diff --git a/packages/plugins/collection-manager/src/__tests__/field-options/indexes.test.ts b/packages/plugins/collection-manager/src/__tests__/field-options/indexes.test.ts index 52aa12baf..269de0105 100644 --- a/packages/plugins/collection-manager/src/__tests__/field-options/indexes.test.ts +++ b/packages/plugins/collection-manager/src/__tests__/field-options/indexes.test.ts @@ -51,6 +51,12 @@ describe('field indexes', () => { } }); expect(response3.status).toBe(400); + + const response4 = await agent.resource(tableName).create({ + values: { title: 't1' } + }); + expect(response4.status).toBe(200); + expect(response4.body.data.title).toBe('t1'); }); it('field value cannot be duplicated with unique index', async () => { diff --git a/packages/plugins/collection-manager/src/models/field.ts b/packages/plugins/collection-manager/src/models/field.ts index 38c2333c1..55194ab62 100644 --- a/packages/plugins/collection-manager/src/models/field.ts +++ b/packages/plugins/collection-manager/src/models/field.ts @@ -6,7 +6,9 @@ interface LoadOptions extends Transactionable { skipExist?: boolean; } -interface MigrateOptions extends SyncOptions, Transactionable {} +interface MigrateOptions extends SyncOptions, Transactionable { + isNew?: boolean; +} async function migrate(field: Field, options: MigrateOptions): Promise { const { unique } = field.options; @@ -75,19 +77,22 @@ export class FieldModel extends MagicAttributeModel { return collection.setField(name, options); } - async migrate(options: MigrateOptions = {}) { + async migrate({ isNew, ...options }: MigrateOptions = {}) { const field = await this.load({ transaction: options.transaction, }); if (!field) { return; } - // const migrator = Dialects[field.database.options.dialect] ?? migrate; + try { await migrate(field, options); } catch (error) { // field sync failed, delete from memory - field.remove(); + if (isNew) { + // update field should not remove field from memory + field.remove(); + } throw error; } } diff --git a/packages/plugins/collection-manager/src/server.ts b/packages/plugins/collection-manager/src/server.ts index 4214ed38d..43a427014 100644 --- a/packages/plugins/collection-manager/src/server.ts +++ b/packages/plugins/collection-manager/src/server.ts @@ -65,13 +65,19 @@ export class CollectionManagerPlugin extends Plugin { this.app.db.on('collections.afterCreateWithAssociations', async (model, { context, transaction }) => { if (context) { - await model.migrate({ transaction }); + await model.migrate({ + isNew: true, + transaction + }); } }); this.app.db.on('fields.afterCreate', async (model: FieldModel, { context, transaction }) => { if (context) { - await model.migrate({ transaction }); + await model.migrate({ + isNew: true, + transaction + }); } });