Skip to content

The open alternative to Salesforce, designed for AI.

Delete indexes on deleted fields and clean up field-less index metadata (#26714)

Félix Malfaitb50155173fe7
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
index 464e1efb491..d3fe3a20bd8 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
@@ -1,8 +1,9 @@
import { Module } from '@nestjs/common';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
-import { VerifyCommonRecordSharingCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790590808102-verify-common-record-sharing.command';
import { RenameCallRecordingTabsToTranscriptCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790583246061-rename-call-recording-tabs-to-transcript.command';
+import { VerifyCommonRecordSharingCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790590808102-verify-common-record-sharing.command';
+import { DeleteFieldLessIndexMetadataCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595494562-delete-field-less-index-metadata.command';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@@ -15,6 +16,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
providers: [
RenameCallRecordingTabsToTranscriptCommand,
VerifyCommonRecordSharingCommand,
+ DeleteFieldLessIndexMetadataCommand,
],
})
export class V2_44_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595494562-delete-field-less-index-metadata.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595494562-delete-field-less-index-metadata.command.ts
new file mode 100644
index 00000000000..c889c34c4eb
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595494562-delete-field-less-index-metadata.command.ts
@@ -0,0 +1,85 @@
+import { Command } from 'nest-commander';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { findFieldLessFlatIndexes } from 'src/database/commands/upgrade-version-command/2-44/utils/find-field-less-flat-indexes.util';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+@RegisteredWorkspaceCommand('2.44.0', 1790595494562)
+@Command({
+ name: 'upgrade:2-44:delete-field-less-index-metadata',
+ description:
+ 'Delete indexMetadata rows left without any index field after their fields were deleted, so their name no longer blocks recreating the index',
+})
+export class DeleteFieldLessIndexMetadataCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace({
+ workspaceId,
+ options,
+ dataSource,
+ }: RunOnWorkspaceArgs): Promise<void> {
+ if (!isDefined(dataSource)) {
+ return;
+ }
+
+ const { flatIndexMaps } = await this.workspaceCacheService.getOrRecompute(
+ workspaceId,
+ ['flatIndexMaps'],
+ );
+
+ const fieldLessFlatIndexes = findFieldLessFlatIndexes({
+ flatIndexes: Object.values(flatIndexMaps.byUniversalIdentifier).filter(
+ isDefined,
+ ),
+ });
+
+ if (fieldLessFlatIndexes.length === 0) {
+ return;
+ }
+
+ const fieldLessIndexNames = fieldLessFlatIndexes
+ .map(({ name }) => name)
+ .join(', ');
+
+ if (options.dryRun) {
+ this.logger.log(
+ `[DRY RUN] Would delete ${fieldLessFlatIndexes.length} field-less index metadata row(s) (${fieldLessIndexNames}) for workspace ${workspaceId}`,
+ );
+
+ return;
+ }
+
+ // Metadata rows only: a workspace migration would also DROP INDEX by name,
+ // and a physical index can outlive its field rows when a field was
+ // re-created on a kept column. Leaving it in place is harmless; index
+ // creation reuses it through IF NOT EXISTS.
+ const [, deletedCount] = await dataSource.query<[unknown[], number]>(
+ `DELETE FROM core."indexMetadata" i
+ WHERE i."workspaceId" = $1
+ AND i.id = ANY($2::uuid[])
+ AND NOT EXISTS (
+ SELECT 1 FROM core."indexFieldMetadata" f
+ WHERE f."indexMetadataId" = i.id
+ )`,
+ [workspaceId, fieldLessFlatIndexes.map(({ id }) => id)],
+ );
+
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ 'flatIndexMaps',
+ 'flatObjectMetadataMaps',
+ ]);
+
+ this.logger.log(
+ `Deleted ${deletedCount} field-less index metadata row(s) (${fieldLessIndexNames}) for workspace ${workspaceId}`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/find-field-less-flat-indexes.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/find-field-less-flat-indexes.util.spec.ts
new file mode 100644
index 00000000000..fddb6e4d1fa
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/find-field-less-flat-indexes.util.spec.ts
@@ -0,0 +1,43 @@
+import { findFieldLessFlatIndexes } from 'src/database/commands/upgrade-version-command/2-44/utils/find-field-less-flat-indexes.util';
+
+const buildFlatIndex = ({
+ name,
+ fieldCount,
+}: {
+ name: string;
+ fieldCount: number;
+}) => ({
+ name,
+ flatIndexFieldMetadatas: Array.from({ length: fieldCount }, (_, order) => ({
+ fieldMetadataId: `${name}-field-${order}`,
+ order,
+ })),
+});
+
+describe('findFieldLessFlatIndexes', () => {
+ it('should return indexes that have no index field left', () => {
+ const orphan = buildFlatIndex({ name: 'IDX_orphan', fieldCount: 0 });
+ const live = buildFlatIndex({ name: 'IDX_live', fieldCount: 1 });
+
+ expect(findFieldLessFlatIndexes({ flatIndexes: [orphan, live] })).toEqual([
+ orphan,
+ ]);
+ });
+
+ it('should return the field-less index even when a live index shares its name', () => {
+ const orphan = buildFlatIndex({ name: 'IDX_shared', fieldCount: 0 });
+ const live = buildFlatIndex({ name: 'IDX_shared', fieldCount: 1 });
+
+ expect(findFieldLessFlatIndexes({ flatIndexes: [orphan, live] })).toEqual([
+ orphan,
+ ]);
+ });
+
+ it('should return nothing when every index has fields', () => {
+ expect(
+ findFieldLessFlatIndexes({
+ flatIndexes: [buildFlatIndex({ name: 'IDX_live', fieldCount: 2 })],
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/find-field-less-flat-indexes.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/find-field-less-flat-indexes.util.ts
new file mode 100644
index 00000000000..cc3958c3bdb
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/find-field-less-flat-indexes.util.ts
@@ -0,0 +1,14 @@
+type FieldLessIndexCandidate = {
+ flatIndexFieldMetadatas: unknown[];
+};
+
+export const findFieldLessFlatIndexes = <
+ TFlatIndex extends FieldLessIndexCandidate,
+>({
+ flatIndexes,
+}: {
+ flatIndexes: TFlatIndex[];
+}): TFlatIndex[] =>
+ flatIndexes.filter(
+ (flatIndex) => flatIndex.flatIndexFieldMetadatas.length === 0,
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
index e2f2772bcde..01d0c627fd2 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
@@ -13,7 +13,6 @@ import { toApplicationCapabilities } from 'src/engine/core-modules/application/u
import { ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';
import { ApplicationUninstallService } from 'src/engine/core-modules/application/application-manifest/services/application-uninstall.service';
import { enrichApplicationManifestSyncError } from 'src/engine/core-modules/application/application-manifest/utils/enrich-application-manifest-sync-error.util';
-import { buildFromToAllUniversalFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/build-from-to-all-universal-flat-entity-maps.util';
import { ApplicationTranslationSyncService } from 'src/engine/core-modules/application/application-translation/application-translation-sync.service';
import { getApplicationSubAllFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/get-application-sub-all-flat-entity-maps.util';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
@@ -27,7 +26,7 @@ import { type FlatApplication } from 'src/engine/core-modules/application/types/
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
import { LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN } from 'src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-driver-factory.token';
import { type LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
-import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';
+import { type AllFlatEntityOperationRecordByMetadataName } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-operation-record-by-metadata-name.type';
import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
import { FrontComponentEntity } from 'src/engine/metadata-modules/front-component/entities/front-component.entity';
import { WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';
@@ -404,12 +403,11 @@ export class ApplicationSyncService {
getMetadataFlatEntityMapsKey,
);
- const cacheResult = await this.workspaceCacheService.getOrRecompute(
- workspaceId,
- [...flatEntityMapsCacheKeys, 'featureFlagsMap'],
- );
-
- const { featureFlagsMap, ...fromAllFlatEntityMaps } = cacheResult;
+ const fromAllFlatEntityMaps =
+ await this.workspaceCacheService.getOrRecompute(
+ workspaceId,
+ flatEntityMapsCacheKeys,
+ );
const applicationFromAllFlatEntityMaps = getApplicationSubAllFlatEntityMaps(
{
@@ -418,22 +416,31 @@ export class ApplicationSyncService {
},
);
- const fromToAllFlatEntityMaps = buildFromToAllUniversalFlatEntityMaps({
- fromAllFlatEntityMaps: applicationFromAllFlatEntityMaps,
- toAllUniversalFlatEntityMaps: createEmptyAllFlatEntityMaps(),
- });
+ // Uninstall also removes engine-owned and workspace-local metadata that
+ // manifest omission intentionally preserves. Expand these explicit deletions
+ // so dependents owned by other applications are cleaned up too.
+ const allFlatEntityOperationRecordByMetadataName: AllFlatEntityOperationRecordByMetadataName =
+ Object.fromEntries(
+ Object.values(ALL_METADATA_NAME).map((metadataName) => [
+ metadataName,
+ {
+ flatEntityToCreate: {},
+ flatEntityToUpdate: {},
+ flatEntityToDelete:
+ applicationFromAllFlatEntityMaps[
+ getMetadataFlatEntityMapsKey(metadataName)
+ ].byUniversalIdentifier,
+ },
+ ]),
+ );
const validateAndBuildResult =
- await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigrationFromTo(
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigrationFromRecord(
{
- buildOptions: {
- isSystemBuild: true,
- inferDeletionFromMissingEntities: true,
- applicationUniversalIdentifier,
- },
- fromToAllFlatEntityMaps,
+ isSystemBuild: true,
+ applicationUniversalIdentifier,
+ allFlatEntityOperationRecordByMetadataName,
workspaceId,
- additionalCacheDataMaps: { featureFlagsMap },
},
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-system-side-effects-on-delete-side-effect-handler.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-system-side-effects-on-delete-side-effect-handler.service.spec.ts
index 316c3a0f074..2120b144786 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-system-side-effects-on-delete-side-effect-handler.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-system-side-effects-on-delete-side-effect-handler.service.spec.ts
@@ -244,6 +244,91 @@ describe('ObjectSystemSideEffectsOnDeleteSideEffectHandlerService', () => {
).toEqual([REVERSE_INDEX_UNIVERSAL_IDENTIFIER]);
});
+ it.each([false, true])(
+ 'should delete a legacy reverse-field index, including the whole multi-column index (multiple fields: %s)',
+ (hasMultipleFields) => {
+ const result = handler.buildSideEffects(
+ buildArgs({
+ fieldUniversalIdentifiers: [FORWARD_FIELD_UNIVERSAL_IDENTIFIER],
+ relatedFlatEntityMaps: {
+ flatObjectMetadataMaps: {
+ byUniversalIdentifier: {
+ [OTHER_OBJECT_UNIVERSAL_IDENTIFIER]: {
+ universalIdentifier: OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
+ indexMetadataUniversalIdentifiers: [
+ REVERSE_INDEX_UNIVERSAL_IDENTIFIER,
+ GIN_INDEX_UNIVERSAL_IDENTIFIER,
+ ],
+ },
+ },
+ },
+ flatFieldMetadataMaps: buildFieldMetadataMaps([
+ {
+ universalIdentifier: FORWARD_FIELD_UNIVERSAL_IDENTIFIER,
+ isSystemSideEffect: true,
+ relationTargetFieldMetadataUniversalIdentifier:
+ REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
+ },
+ {
+ universalIdentifier: REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
+ isSystemSideEffect: true,
+ objectMetadataUniversalIdentifier:
+ OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
+ },
+ ]),
+ flatIndexMaps: {
+ byUniversalIdentifier: {
+ [REVERSE_INDEX_UNIVERSAL_IDENTIFIER]: {
+ universalIdentifier: REVERSE_INDEX_UNIVERSAL_IDENTIFIER,
+ isSystemSideEffect: false,
+ applicationUniversalIdentifier: 'another-application',
+ objectMetadataUniversalIdentifier:
+ OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
+ universalFlatIndexFieldMetadatas: [
+ {
+ fieldMetadataUniversalIdentifier:
+ REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
+ },
+ ...(hasMultipleFields
+ ? [
+ {
+ fieldMetadataUniversalIdentifier:
+ AUTHOR_FIELD_UNIVERSAL_IDENTIFIER,
+ },
+ ]
+ : []),
+ ],
+ },
+ [GIN_INDEX_UNIVERSAL_IDENTIFIER]: {
+ universalIdentifier: GIN_INDEX_UNIVERSAL_IDENTIFIER,
+ isSystemSideEffect: false,
+ objectMetadataUniversalIdentifier:
+ OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
+ universalFlatIndexFieldMetadatas: [
+ {
+ fieldMetadataUniversalIdentifier:
+ AUTHOR_FIELD_UNIVERSAL_IDENTIFIER,
+ },
+ ],
+ },
+ },
+ },
+ },
+ }),
+ );
+
+ expect(result.status).toBe('success');
+
+ if (result.status !== 'success') {
+ throw new Error('expected success');
+ }
+
+ expect(
+ Object.keys(result.operations.index?.flatEntityToDelete ?? {}),
+ ).toEqual([REVERSE_INDEX_UNIVERSAL_IDENTIFIER]);
+ },
+ );
+
it('should not delete entities the object aggregators do not reference', () => {
const result = handler.buildSideEffects(
buildArgs({
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts
index 9381953aaea..7563c583d72 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts
@@ -210,10 +210,7 @@ export class ObjectSystemSideEffectsOnDeleteSideEffectHandlerService extends Met
indexUniversalIdentifier
];
- if (
- !isDefined(flatIndexMetadata) ||
- flatIndexMetadata.isSystemSideEffect !== true
- ) {
+ if (!isDefined(flatIndexMetadata)) {
continue;
}
@@ -228,7 +225,15 @@ export class ObjectSystemSideEffectsOnDeleteSideEffectHandlerService extends Met
),
);
- if (!belongsToObject && !referencesDeletedField) {
+ // Dropping a column drops every physical index on it, so an index on a
+ // deleted field must go whatever its flags or owner. Join-column indexes
+ // backfilled before isSystemSideEffect existed are still flagged false,
+ // and skipping them left field-less indexMetadata rows whose name then
+ // collided when the field was recreated.
+ const isEngineOwnedIndexOfObject =
+ belongsToObject && flatIndexMetadata.isSystemSideEffect;
+
+ if (!referencesDeletedField && !isEngineOwnedIndexOfObject) {
continue;
}
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/system-relation-index-deletion.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/system-relation-index-deletion.integration-spec.ts
new file mode 100644
index 00000000000..6e0bf1e5afd
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/system-relation-index-deletion.integration-spec.ts
@@ -0,0 +1,216 @@
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { buildDefaultObjectManifest } from 'test/integration/metadata/suites/application/utils/build-default-object-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { uninstallApplication } from 'test/integration/metadata/suites/application/utils/uninstall-application.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { v4 as uuidv4 } from 'uuid';
+
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const APPLICATION_UNIVERSAL_IDENTIFIER = uuidv4();
+const ROLE_UNIVERSAL_IDENTIFIER = uuidv4();
+const TEST_OBJECT = buildDefaultObjectManifest({
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ nameSingular: 'indexLifecycleTicket',
+ namePlural: 'indexLifecycleTickets',
+ labelSingular: 'Index Lifecycle Ticket',
+ labelPlural: 'Index Lifecycle Tickets',
+});
+
+const buildManifest = (includeObject: boolean) =>
+ buildBaseManifest({
+ appId: APPLICATION_UNIVERSAL_IDENTIFIER,
+ roleId: ROLE_UNIVERSAL_IDENTIFIER,
+ overrides: { objects: includeObject ? [TEST_OBJECT] : [] },
+ });
+
+const setupApplication = () =>
+ setupApplicationForSync({
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ name: 'Index Lifecycle Application',
+ description: 'Tests deletion of legacy system relation indexes',
+ sourcePath: 'test-index-lifecycle',
+ });
+
+type RelationIndex = {
+ id: string;
+ name: string;
+ universalIdentifier: string;
+ fieldMetadataId: string;
+ objectMetadataId: string;
+};
+
+const findRelationIndexes = (): Promise<RelationIndex[]> =>
+ globalThis.testDataSource.query(
+ `SELECT i.id, i.name, i."universalIdentifier", i."objectMetadataId",
+ f.id AS "fieldMetadataId"
+ FROM core."indexMetadata" i
+ JOIN core."indexFieldMetadata" indexed ON indexed."indexMetadataId" = i.id
+ JOIN core."fieldMetadata" f ON f.id = indexed."fieldMetadataId"
+ JOIN core."objectMetadata" target ON target.id = f."relationTargetObjectMetadataId"
+ WHERE target."universalIdentifier" = $1 AND i."workspaceId" = $2
+ AND f."isSystemSideEffect" = true`,
+ [TEST_OBJECT.universalIdentifier, SEED_APPLE_WORKSPACE_ID],
+ );
+
+const findPhysicalIndexes = (
+ names: string[],
+): Promise<{ indexname: string }[]> =>
+ globalThis.testDataSource.query(
+ `SELECT indexname FROM pg_indexes
+ WHERE schemaname = $1 AND indexname = ANY($2::text[])`,
+ [getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID), names],
+ );
+
+describe.each(['sync', 'uninstall'] as const)(
+ 'System relation index deletion through %s',
+ (deletionMethod) => {
+ beforeEach(setupApplication, 60000);
+
+ afterEach(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ });
+ });
+
+ it.each([
+ ['another application', TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER],
+ ['the same application', APPLICATION_UNIVERSAL_IDENTIFIER],
+ ])(
+ 'deletes legacy indexes owned by %s and allows recreation',
+ async (_, indexOwnerUniversalIdentifier) => {
+ await syncApplication({
+ manifest: buildManifest(true),
+ expectToFail: false,
+ });
+
+ const indexes = await findRelationIndexes();
+
+ expect(indexes.length).toBeGreaterThan(0);
+
+ const indexIds = indexes.map(({ id }) => id);
+ const indexNames = indexes.map(({ name }) => name);
+ const fieldIds = indexes.map(({ fieldMetadataId }) => fieldMetadataId);
+ const unrelatedIndexes = await globalThis.testDataSource.query<
+ { id: string }[]
+ >(
+ `SELECT id FROM core."indexMetadata"
+ WHERE "workspaceId" = $1 AND "objectMetadataId" = ANY($2::uuid[])
+ AND NOT (id = ANY($3::uuid[]))`,
+ [
+ SEED_APPLE_WORKSPACE_ID,
+ indexes.map(({ objectMetadataId }) => objectMetadataId),
+ indexIds,
+ ],
+ );
+
+ expect(unrelatedIndexes.length).toBeGreaterThan(0);
+ expect(await findPhysicalIndexes(indexNames)).toHaveLength(
+ indexes.length,
+ );
+
+ // Older backfills left these generated indexes unflagged and sometimes
+ // owned by Twenty Standard rather than the application owning the field.
+ await globalThis.testDataSource.query(
+ `UPDATE core."indexMetadata" SET "isSystemSideEffect" = false,
+ "applicationId" = (
+ SELECT id FROM core."application"
+ WHERE "universalIdentifier" = $1 AND "workspaceId" = $2
+ )
+ WHERE id = ANY($3::uuid[]) AND "workspaceId" = $2`,
+ [indexOwnerUniversalIdentifier, SEED_APPLE_WORKSPACE_ID, indexIds],
+ );
+
+ await getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, [
+ 'flatIndexMaps',
+ 'flatObjectMetadataMaps',
+ ]);
+
+ if (deletionMethod === 'sync') {
+ const { data } = await syncApplication({
+ manifest: buildManifest(false),
+ expectToFail: false,
+ });
+
+ for (const index of indexes) {
+ expect(
+ data.syncApplication.actions.filter(
+ (action) =>
+ action.type === 'delete' &&
+ action.metadataName === 'index' &&
+ action.universalIdentifier === index.universalIdentifier,
+ ),
+ ).toHaveLength(1);
+ }
+ } else {
+ const { data } = await uninstallApplication({
+ universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ expectToFail: false,
+ });
+
+ expect(data.uninstallApplication).toBe(true);
+ }
+
+ expect(
+ await globalThis.testDataSource.query(
+ 'SELECT id FROM core."indexMetadata" WHERE id = ANY($1::uuid[])',
+ [indexIds],
+ ),
+ ).toEqual([]);
+ expect(
+ await globalThis.testDataSource.query(
+ 'SELECT id FROM core."indexFieldMetadata" WHERE "indexMetadataId" = ANY($1::uuid[])',
+ [indexIds],
+ ),
+ ).toEqual([]);
+ expect(
+ await globalThis.testDataSource.query(
+ 'SELECT id FROM core."fieldMetadata" WHERE id = ANY($1::uuid[])',
+ [fieldIds],
+ ),
+ ).toEqual([]);
+ expect(await findPhysicalIndexes(indexNames)).toEqual([]);
+ expect(
+ await globalThis.testDataSource.query(
+ 'SELECT id FROM core."indexMetadata" WHERE id = ANY($1::uuid[])',
+ [unrelatedIndexes.map(({ id }) => id)],
+ ),
+ ).toHaveLength(unrelatedIndexes.length);
+
+ if (deletionMethod === 'uninstall') {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ });
+ await setupApplication();
+ }
+
+ await syncApplication({
+ manifest: buildManifest(true),
+ expectToFail: false,
+ });
+
+ expect(
+ (await findRelationIndexes()).map(({ name }) => name).sort(),
+ ).toEqual(indexNames.sort());
+ expect(await findPhysicalIndexes(indexNames)).toHaveLength(
+ indexes.length,
+ );
+
+ const { data: resyncData } = await syncApplication({
+ manifest: buildManifest(true),
+ expectToFail: false,
+ });
+
+ expect(resyncData.syncApplication.actions).toEqual([]);
+ },
+ 60000,
+ );
+ },
+);