Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle migration of Email to Emails fields #6885

Merged
merged 14 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,11 @@ xLink
id
createdAt
city
email
emails
{
primaryEmail
additionalEmails
}
jobTitle
name
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ describe('mapObjectMetadataToGraphQLQuery', () => {
firstName
lastName
}
email
emails
{
primaryEmail
additionalEmails
}
phone
createdAt
avatarUrl
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { DataSeedDemoWorkspaceModule } from 'src/database/commands/data-seed-dem
import { DataSeedWorkspaceCommand } from 'src/database/commands/data-seed-dev-workspace.command';
import { ConfirmationQuestion } from 'src/database/commands/questions/confirmation.question';
import { UpgradeTo0_24CommandModule } from 'src/database/commands/upgrade-version/0-24/0-24-upgrade-version.module';
import { UpgradeTo0_25CommandModule } from 'src/database/commands/upgrade-version/0-25/0-25-upgrade-version.module';
import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { BillingSubscription } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
Expand Down Expand Up @@ -46,6 +47,7 @@ import { WorkspaceSyncMetadataModule } from 'src/engine/workspace-manager/worksp
DataSeedDemoWorkspaceModule,
WorkspaceMetadataVersionModule,
UpgradeTo0_24CommandModule,
ijreilly marked this conversation as resolved.
Show resolved Hide resolved
UpgradeTo0_25CommandModule,
],
providers: [
DataSeedWorkspaceCommand,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,305 @@
import { InjectRepository } from '@nestjs/typeorm';

import chalk from 'chalk';
import { Command, Option } from 'nest-commander';
import { QueryRunner, Repository } from 'typeorm';

import { ActiveWorkspacesCommandRunner } from 'src/database/commands/active-workspaces.command';
import { TypeORMService } from 'src/database/typeorm/typeorm.service';
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
import { DataSourceEntity } from 'src/engine/metadata-modules/data-source/data-source.entity';
import { DataSourceService } from 'src/engine/metadata-modules/data-source/data-source.service';
import { CreateFieldInput } from 'src/engine/metadata-modules/field-metadata/dtos/create-field.input';
import {
FieldMetadataEntity,
FieldMetadataType,
} from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
import { FieldMetadataService } from 'src/engine/metadata-modules/field-metadata/field-metadata.service';
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
import { TwentyORMGlobalManager } from 'src/engine/twenty-orm/twenty-orm-global.manager';
import { computeTableName } from 'src/engine/utils/compute-table-name.util';
import { ViewService } from 'src/modules/view/services/view.service';
import { ViewFieldWorkspaceEntity } from 'src/modules/view/standard-objects/view-field.workspace-entity';

interface MigrateEmailFieldsToEmailsCommandOptions {
ijreilly marked this conversation as resolved.
Show resolved Hide resolved
workspaceId?: string;
}

@Command({
name: 'upgrade-0.25:migrate-email-fields-to-emails',
description: 'Migrating fields of deprecated type EMAIL to type EMAILS',
})
export class MigrateEmailFieldsToEmailsCommand extends ActiveWorkspacesCommandRunner {
constructor(
@InjectRepository(Workspace, 'core')
protected readonly workspaceRepository: Repository<Workspace>,
@InjectRepository(FieldMetadataEntity, 'metadata')
private readonly fieldMetadataRepository: Repository<FieldMetadataEntity>,
@InjectRepository(ObjectMetadataEntity, 'metadata')
private readonly objectMetadataRepository: Repository<ObjectMetadataEntity>,
private readonly fieldMetadataService: FieldMetadataService,
private readonly twentyORMGlobalManager: TwentyORMGlobalManager,
private readonly typeORMService: TypeORMService,
private readonly dataSourceService: DataSourceService,
private readonly viewService: ViewService,
) {
super(workspaceRepository);
}

@Option({
ijreilly marked this conversation as resolved.
Show resolved Hide resolved
flags: '-w, --workspace-id [workspace_id]',
description:
'workspace id. Command runs on all active workspaces if not provided',
required: false,
})
async executeActiveWorkspacesCommand(
_passedParam: string[],
options: MigrateEmailFieldsToEmailsCommandOptions,
workspaceIds: string[],
): Promise<void> {
this.logger.log(
'Running command to migrate email type fields to emails type',
);
const _workspaceIds = options.workspaceId
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't want to care about the options if it's workspaceIds that you need, that's the goal of ActiveWorkspacesCommandRunner which extracts it for you so you only need to use workspaceIds from the method above

? [options.workspaceId]
: workspaceIds;

for (const workspaceId of _workspaceIds) {
ijreilly marked this conversation as resolved.
Show resolved Hide resolved
this.logger.log(`Running command for workspace ${workspaceId}`);
try {
const dataSourceMetadata =
await this.dataSourceService.getLastDataSourceMetadataFromWorkspaceId(
workspaceId,
);

if (!dataSourceMetadata) {
throw new Error(
`Could not find dataSourceMetadata for workspace ${workspaceId}`,
);
}

const workspaceDataSource =
await this.typeORMService.connectToDataSource(dataSourceMetadata);

if (!workspaceDataSource) {
throw new Error(
`Could not connect to dataSource for workspace ${workspaceId}`,
);
}

const fieldsWithEmailType = await this.fieldMetadataRepository.find({
where: {
workspaceId,
type: FieldMetadataType.EMAIL,
},
ijreilly marked this conversation as resolved.
Show resolved Hide resolved
});

for (const fieldWithEmailType of fieldsWithEmailType) {
const objectMetadata = await this.objectMetadataRepository.findOne({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I feel like this whole block could be optimised (in terms of queries to the DB) but since it's a command we can keep it like this I guess 🤔

where: { id: fieldWithEmailType.objectMetadataId },
});

if (!objectMetadata) {
throw new Error(
`Could not find objectMetadata for field ${fieldWithEmailType.name}`,
);
}

this.logger.log(
`Attempting to migrate field ${fieldWithEmailType.name} on ${objectMetadata.nameSingular}.`,
);
const workspaceQueryRunner = workspaceDataSource.createQueryRunner();

await workspaceQueryRunner.connect();

const fieldName = fieldWithEmailType.name;
const { id: _id, ...fieldWithEmailTypeWithoutId } =
fieldWithEmailType;

const emailDefaultValue = fieldWithEmailTypeWithoutId.defaultValue;

const defaultValueForEmailsField = {
primaryEmail: emailDefaultValue,
additionalEmails: null,
};

try {
const tmpNewEmailsField = await this.fieldMetadataService.createOne(
{
...fieldWithEmailTypeWithoutId,
type: FieldMetadataType.EMAILS,
defaultValue: defaultValueForEmailsField,
name: `${fieldName}Tmp`,
} satisfies CreateFieldInput,
);

const tableName = computeTableName(
objectMetadata.nameSingular,
objectMetadata.isCustom,
);

// Migrate data from email to emails.primaryEmail
await this.migrateDataWithinTable({
sourceColumnName: `${fieldWithEmailType.name}`,
targetColumnName: `${tmpNewEmailsField.name}PrimaryEmail`,
tableName,
workspaceQueryRunner,
dataSourceMetadata,
});

// Duplicate email field's views behaviour for new emails field
await this.viewService.removeFieldFromViews({
workspaceId: workspaceId,
fieldId: tmpNewEmailsField.id,
});

const viewFieldRepository =
await this.twentyORMGlobalManager.getRepositoryForWorkspace<ViewFieldWorkspaceEntity>(
workspaceId,
'viewField',
);
const viewFieldsWithDeprecatedField =
await viewFieldRepository.find({
where: {
fieldMetadataId: fieldWithEmailType.id,
isVisible: true,
},
});

await this.viewService.addFieldToViews({
workspaceId: workspaceId,
fieldId: tmpNewEmailsField.id,
viewsIds: viewFieldsWithDeprecatedField
.filter((viewField) => viewField.viewId !== null)
.map((viewField) => viewField.viewId as string),
positions: viewFieldsWithDeprecatedField.reduce(
(acc, viewField) => {
if (!viewField.viewId) {
return acc;
}
acc[viewField.viewId] = viewField.position;

return acc;
},
[],
),
});

// Delete email field
await this.fieldMetadataService.deleteOneField(
{ id: fieldWithEmailType.id },
workspaceId,
);

// Rename temporary emails field
await this.fieldMetadataService.updateOne(tmpNewEmailsField.id, {
id: tmpNewEmailsField.id,
workspaceId: tmpNewEmailsField.workspaceId,
name: `${fieldName}`,
isCustom: false,
});

this.logger.log(
`Migration of ${fieldWithEmailType.name} on ${objectMetadata.nameSingular} done!`,
);
} catch (error) {
this.logger.log(
`Failed to migrate field ${fieldWithEmailType.name} on ${objectMetadata.nameSingular}, rolling back.`,
);

// Re-create initial field if it was deleted
const initialField =
await this.fieldMetadataService.findOneWithinWorkspace(
workspaceId,
{
where: {
name: `${fieldWithEmailType.name}`,
objectMetadataId: fieldWithEmailType.objectMetadataId,
},
},
);

const tmpNewEmailsField =
await this.fieldMetadataService.findOneWithinWorkspace(
workspaceId,
{
where: {
name: `${fieldWithEmailType.name}Tmp`,
objectMetadataId: fieldWithEmailType.objectMetadataId,
},
},
);

if (!initialField) {
this.logger.log(
`Re-creating initial Email field ${fieldWithEmailType.name} but of type emails`, // Cannot create email fields anymore
);
const restoredField = await this.fieldMetadataService.createOne({
...fieldWithEmailType,
defaultValue: defaultValueForEmailsField,
type: FieldMetadataType.EMAILS,
});
const tableName = computeTableName(
objectMetadata.nameSingular,
objectMetadata.isCustom,
);

if (tmpNewEmailsField) {
this.logger.log(
`Restoring data in field ${fieldWithEmailType.name}`,
);
await this.migrateDataWithinTable({
sourceColumnName: `${tmpNewEmailsField.name}PrimaryEmail`,
targetColumnName: `${restoredField.name}PrimaryEmail`,
tableName,
workspaceQueryRunner,
dataSourceMetadata,
});
} else {
this.logger.log(
`Failed to restore data in link field ${fieldWithEmailType.name}`,
);
}
}

if (tmpNewEmailsField) {
await this.fieldMetadataService.deleteOneField(
{ id: tmpNewEmailsField.id },
workspaceId,
);
}
} finally {
await workspaceQueryRunner.release();
}
}
} catch (error) {
this.logger.log(
chalk.red(
`Running command on workspace ${workspaceId} failed with error: ${error}`,
),
);
continue;
}

this.logger.log(chalk.green(`Command completed!`));
}
}

private async migrateDataWithinTable({
sourceColumnName,
targetColumnName,
tableName,
workspaceQueryRunner,
dataSourceMetadata,
}: {
sourceColumnName: string;
targetColumnName: string;
tableName: string;
workspaceQueryRunner: QueryRunner;
dataSourceMetadata: DataSourceEntity;
}) {
await workspaceQueryRunner.query(
`UPDATE "${dataSourceMetadata.schema}"."${tableName}" SET "${targetColumnName}" = "${sourceColumnName}"`,
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Command, CommandRunner, Option } from 'nest-commander';

import { MigrateEmailFieldsToEmailsCommand } from 'src/database/commands/upgrade-version/0-25/0-25-migrate-email-fields-to-emails.command';
import { SyncWorkspaceMetadataCommand } from 'src/engine/workspace-manager/workspace-sync-metadata/commands/sync-workspace-metadata.command';

interface UpdateTo0_25CommandOptions {
workspaceId?: string;
}

@Command({
name: 'upgrade-0.25',
description: 'Upgrade to 0.25',
})
export class UpgradeTo0_25Command extends CommandRunner {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Could extend ActiveWorkspacesCommandRunner as well :)

constructor(
private readonly syncWorkspaceMetadataCommand: SyncWorkspaceMetadataCommand,
private readonly migrateEmailFieldsToEmails: MigrateEmailFieldsToEmailsCommand,
) {
super();
}

@Option({
flags: '-w, --workspace-id [workspace_id]',
description:
'workspace id. Command runs on all active workspaces if not provided',
required: false,
})
parseWorkspaceId(value: string): string {
return value;
}

async run(
passedParam: string[],
options: UpdateTo0_25CommandOptions,
): Promise<void> {
await this.migrateEmailFieldsToEmails.run(passedParam, options);
await this.syncWorkspaceMetadataCommand.run(passedParam, {
...options,
force: true,
});
}
}
Loading
Loading