From 007d69942d24eeea9edd4665f812d07ed11b3b97 Mon Sep 17 00:00:00 2001 From: CaIon Date: Sat, 12 Sep 2026 18:43:18 +0800 Subject: [PATCH] fix(model): migrate renamed prefill group unique indexes Identify legacy global uniqueness by definition instead of object name. Replace colliding target names inside the locked transaction, preserving unrelated indexes and rolling back failed migrations. Verified fresh schemas, repeated migration, rollback, and upgrades from v1.0.0-rc.37 on SQLite 3.50.4, MySQL 5.7.44/8.0.46, and PostgreSQL 9.6.24/16.15. --- model/prefill_group_migration.go | 65 ++---- model/prefill_group_migration_test.go | 291 +++++++++++++++----------- 2 files changed, 187 insertions(+), 169 deletions(-) diff --git a/model/prefill_group_migration.go b/model/prefill_group_migration.go index 72cdc03fcb..3a0ad2ac6c 100644 --- a/model/prefill_group_migration.go +++ b/model/prefill_group_migration.go @@ -8,7 +8,6 @@ import ( ) const prefillGroupNameIndex = "uk_prefill_name" -const legacyPrefillGroupNameUnique = "idx_prefill_groups_name" type conflictingPrefillGroupUniqueness struct { constraints []string @@ -24,30 +23,6 @@ func (conflicts conflictingPrefillGroupUniqueness) empty() bool { return len(conflicts.constraints) == 0 && len(conflicts.indexes) == 0 } -func (conflicts conflictingPrefillGroupUniqueness) validateAutomaticMigrationScope() error { - unexpectedConstraints := make([]string, 0) - for _, name := range conflicts.constraints { - if name != legacyPrefillGroupNameUnique { - unexpectedConstraints = append(unexpectedConstraints, name) - } - } - unexpectedIndexes := make([]string, 0) - for _, name := range conflicts.indexes { - if name != legacyPrefillGroupNameUnique { - unexpectedIndexes = append(unexpectedIndexes, name) - } - } - if len(unexpectedConstraints) == 0 && len(unexpectedIndexes) == 0 { - return nil - } - return fmt.Errorf( - "prefill_groups.name has unsupported global unique constraints %q and indexes %q; only legacy object %q can be migrated automatically to partial uniqueness", - unexpectedConstraints, - unexpectedIndexes, - legacyPrefillGroupNameUnique, - ) -} - func inspectConflictingPrefillGroupUniqueness(db *gorm.DB, tableName string) (conflictingPrefillGroupUniqueness, error) { var conflicts conflictingPrefillGroupUniqueness if err := db.Raw(` @@ -124,9 +99,10 @@ WHERE index_meta.indrelid = to_regclass(?) return prefillGroupNameIndexState{exists: state.Exists, valid: state.Valid}, nil } -// migratePrefillGroupUniqueness replaces the known global PostgreSQL unique -// object left by older GORM versions before AutoMigrate inspects the column. -// Unknown conflicting objects are reported without being modified. +// migratePrefillGroupUniqueness replaces global PostgreSQL uniqueness on name +// before AutoMigrate inspects the column. Match the definition rather than the +// object name, which can change across older schemas and database imports. +// Composite, expression and partial indexes retain their separate semantics. func migratePrefillGroupUniqueness(db *gorm.DB) error { if db == nil { return fmt.Errorf("migrate prefill group uniqueness: database is nil") @@ -147,10 +123,6 @@ func migratePrefillGroupUniqueness(db *gorm.DB) error { if conflicts.empty() { return nil } - if err := conflicts.validateAutomaticMigrationScope(); err != nil { - return err - } - return db.Transaction(func(tx *gorm.DB) error { migrator := tx.Migrator() if !migrator.HasTable(&PrefillGroup{}) { @@ -171,16 +143,26 @@ func migratePrefillGroupUniqueness(db *gorm.DB) error { if conflicts.empty() { return nil } - if err := conflicts.validateAutomaticMigrationScope(); err != nil { - return err - } - if !migrator.HasColumn(&PrefillGroup{}, "DeletedAt") { if err := migrator.AddColumn(&PrefillGroup{}, "DeletedAt"); err != nil { return fmt.Errorf("add prefill groups deleted_at column: %w", err) } } + // A global index or constraint may already use the target index name. + // Drop it before creating the replacement under the exclusive table lock; + // the transaction restores all old objects if any migration step fails. + for _, constraintName := range conflicts.constraints { + if err := migrator.DropConstraint(&PrefillGroup{}, constraintName); err != nil { + return fmt.Errorf("drop conflicting prefill group constraint %q: %w", constraintName, err) + } + } + for _, indexName := range conflicts.indexes { + if err := migrator.DropIndex(&PrefillGroup{}, indexName); err != nil { + return fmt.Errorf("drop conflicting prefill group index %q: %w", indexName, err) + } + } + targetIndex, err := inspectPrefillGroupNameIndex(tx, tableName) if err != nil { return err @@ -198,17 +180,6 @@ func migratePrefillGroupUniqueness(db *gorm.DB) error { return fmt.Errorf("prefill group index %q has an unexpected definition", prefillGroupNameIndex) } - for _, constraintName := range conflicts.constraints { - if err := migrator.DropConstraint(&PrefillGroup{}, constraintName); err != nil { - return fmt.Errorf("drop conflicting prefill group constraint %q: %w", constraintName, err) - } - } - for _, indexName := range conflicts.indexes { - if err := migrator.DropIndex(&PrefillGroup{}, indexName); err != nil { - return fmt.Errorf("drop conflicting prefill group index %q: %w", indexName, err) - } - } - return nil }) } diff --git a/model/prefill_group_migration_test.go b/model/prefill_group_migration_test.go index 38ef90282f..18ffe4e4ab 100644 --- a/model/prefill_group_migration_test.go +++ b/model/prefill_group_migration_test.go @@ -3,6 +3,7 @@ package model import ( "fmt" "os" + "slices" "strings" "testing" "time" @@ -18,6 +19,13 @@ import ( func testPrefillGroupMigrationNonPostgreSQL(t *testing.T, db *gorm.DB) { t.Helper() + var version string + versionQuery := "SELECT version()" + if db.Dialector.Name() == "sqlite" { + versionQuery = "SELECT sqlite_version()" + } + require.NoError(t, db.Raw(versionQuery).Scan(&version).Error) + t.Logf("%s version: %s", db.Dialector.Name(), version) tableName := fmt.Sprintf("prefill_group_migration_%d", time.Now().UnixNano()) t.Cleanup(func() { _ = db.Migrator().DropTable(tableName) }) @@ -30,15 +38,22 @@ func testPrefillGroupMigrationNonPostgreSQL(t *testing.T, db *gorm.DB) { Description: "preserve me", }).Error) - for range 2 { - require.NoError(t, migratePrefillGroupUniqueness(db)) - require.NoError(t, tableDB.AutoMigrate(&PrefillGroup{})) + recorder := &migrationSQLRecorder{} + for pass := range 2 { + recorder.reset() + require.NoError(t, migratePrefillGroupUniqueness(db.Session(&gorm.Session{Logger: recorder}))) + require.NoError(t, tableDB.Session(&gorm.Session{Logger: recorder}).AutoMigrate(&PrefillGroup{})) + if pass == 1 { + assert.Empty(t, recorder.schemaMutations(), "repeated startup must not change the schema") + } } var preserved PrefillGroup require.NoError(t, tableDB.Where("name = ?", "preserved-name").First(&preserved).Error) assert.Equal(t, "preserve me", preserved.Description) + assert.JSONEq(t, `["gpt-test"]`, string(preserved.Items)) assert.True(t, tableDB.Migrator().HasIndex(&PrefillGroup{}, prefillGroupNameIndex)) + require.Error(t, tableDB.Create(&PrefillGroup{Name: preserved.Name, Type: "model"}).Error) } func TestMigratePrefillGroupUniquenessSQLite(t *testing.T) { @@ -76,83 +91,64 @@ func TestMigratePrefillGroupUniquenessPostgreSQL(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { require.NoError(t, sqlDB.Close()) }) + var version string + require.NoError(t, db.Raw("SELECT version()").Scan(&version).Error) + t.Log(version) + + type indexDefinition struct { + Name string `gorm:"column:indexname"` + Definition string `gorm:"column:indexdef"` + } + tests := []struct { - name string - prepareOld func(*testing.T, *gorm.DB) - blockedConstraints []string - blockedIndexes []string - preservedIndexes []string + name string + constraints []string + indexes []string + replacePartialIndex bool + withoutDeletedAt bool + prepareOld func(*testing.T, *gorm.DB) + wantError string }{ {name: "fresh"}, { - name: "legacy_constraint", + name: "legacy_constraint", + constraints: []string{"idx_prefill_groups_name"}, + }, + { + name: "legacy_standalone_index", + indexes: []string{"idx_prefill_groups_name"}, + replacePartialIndex: true, + }, + { + name: "renamed_constraints_and_indexes", + constraints: []string{"idx_prefill_groups_name", "prefill_groups_name_key"}, + indexes: []string{"idx_37606_uk_prefill_name", `custom "name" index`}, + }, + { + name: "imported_index_without_soft_delete_column", + indexes: []string{"idx_37606_uk_prefill_name"}, + replacePartialIndex: true, + withoutDeletedAt: true, + }, + { + name: "global_index_uses_target_name", + indexes: []string{prefillGroupNameIndex}, + replacePartialIndex: true, + }, + { + name: "global_constraint_uses_target_name", + constraints: []string{prefillGroupNameIndex}, + replacePartialIndex: true, + }, + { + name: "non_conflicting_indexes_are_preserved", + constraints: []string{"prefill_groups_name_key"}, prepareOld: func(t *testing.T, tx *gorm.DB) { t.Helper() require.NoError(t, tx.Exec( - "ALTER TABLE ? ADD CONSTRAINT ? UNIQUE (?)", + "CREATE INDEX ? ON ? (?)", + clause.Column{Name: "keep_prefill_name"}, clause.Table{Name: "prefill_groups"}, - clause.Column{Name: legacyPrefillGroupNameUnique}, - clause.Column{Name: "name"}, - ).Error) - }, - }, - { - name: "legacy_standalone_index", - prepareOld: func(t *testing.T, tx *gorm.DB) { - t.Helper() - require.NoError(t, tx.Migrator().DropIndex(&PrefillGroup{}, prefillGroupNameIndex)) - require.NoError(t, tx.Exec( - "CREATE UNIQUE INDEX ? ON ? (?)", - clause.Column{Name: legacyPrefillGroupNameUnique}, - clause.Table{Name: "prefill_groups"}, - clause.Column{Name: "name"}, - ).Error) - }, - }, - { - name: "arbitrary_constraint_name", - prepareOld: func(t *testing.T, tx *gorm.DB) { - t.Helper() - for _, constraintName := range []string{ - legacyPrefillGroupNameUnique, - "prefill_groups_name_key", - } { - require.NoError(t, tx.Exec( - "ALTER TABLE ? ADD CONSTRAINT ? UNIQUE (?)", - clause.Table{Name: "prefill_groups"}, - clause.Column{Name: constraintName}, - clause.Column{Name: "name"}, - ).Error) - } - }, - blockedConstraints: []string{legacyPrefillGroupNameUnique, "prefill_groups_name_key"}, - }, - { - name: "arbitrary_index_name", - prepareOld: func(t *testing.T, tx *gorm.DB) { - t.Helper() - for _, indexName := range []string{ - legacyPrefillGroupNameUnique, - "prefill_groups_name_key", - } { - require.NoError(t, tx.Exec( - "CREATE UNIQUE INDEX ? ON ? (?)", - clause.Column{Name: indexName}, - clause.Table{Name: "prefill_groups"}, - clause.Column{Name: "name"}, - ).Error) - } - }, - blockedIndexes: []string{legacyPrefillGroupNameUnique, "prefill_groups_name_key"}, - }, - { - name: "non_conflicting_indexes_are_preserved", - prepareOld: func(t *testing.T, tx *gorm.DB) { - t.Helper() - require.NoError(t, tx.Exec( - "ALTER TABLE ? ADD CONSTRAINT ? UNIQUE (?)", - clause.Table{Name: "prefill_groups"}, - clause.Column{Name: legacyPrefillGroupNameUnique}, clause.Column{Name: "name"}, ).Error) require.NoError(t, tx.Exec( @@ -175,11 +171,49 @@ func TestMigratePrefillGroupUniquenessPostgreSQL(t *testing.T) { clause.Column{Name: "name"}, ).Error) }, - preservedIndexes: []string{ - "keep_prefill_name_deleted_at", - "keep_prefill_lower_name", - "keep_prefill_deleted_name", + }, + { + name: "unexpected_target_definition_rolls_back", + constraints: []string{"prefill_groups_name_key"}, + indexes: []string{"idx_37606_uk_prefill_name"}, + replacePartialIndex: true, + prepareOld: func(t *testing.T, tx *gorm.DB) { + t.Helper() + require.NoError(t, tx.Exec( + "CREATE INDEX ? ON ? (?)", + clause.Column{Name: prefillGroupNameIndex}, + clause.Table{Name: "prefill_groups"}, + clause.Column{Name: "type"}, + ).Error) }, + wantError: "unexpected definition", + }, + { + name: "target_name_on_other_table_rolls_back", + indexes: []string{"idx_37606_uk_prefill_name"}, + replacePartialIndex: true, + withoutDeletedAt: true, + prepareOld: func(t *testing.T, tx *gorm.DB) { + t.Helper() + require.NoError(t, tx.Exec("CREATE TABLE other_groups (name varchar(64))").Error) + require.NoError(t, tx.Exec( + "CREATE INDEX ? ON other_groups (name)", + clause.Column{Name: prefillGroupNameIndex}, + ).Error) + }, + wantError: "unexpected definition", + }, + { + name: "foreign_key_dependency_rolls_back", + constraints: []string{"prefill_groups_name_key"}, + replacePartialIndex: true, + withoutDeletedAt: true, + prepareOld: func(t *testing.T, tx *gorm.DB) { + t.Helper() + require.NoError(t, tx.Exec("CREATE TABLE referenced_groups (name varchar(64) REFERENCES prefill_groups(name))").Error) + require.NoError(t, tx.Exec("INSERT INTO referenced_groups (name) VALUES (?)", "shared-name").Error) + }, + wantError: "drop conflicting prefill group constraint", }, } @@ -208,66 +242,79 @@ func TestMigratePrefillGroupUniquenessPostgreSQL(t *testing.T) { Description: "preserve me", } require.NoError(t, tx.Create(&original).Error) + if test.replacePartialIndex { + require.NoError(t, tx.Migrator().DropIndex(&PrefillGroup{}, prefillGroupNameIndex)) + } + if test.withoutDeletedAt { + require.NoError(t, tx.Migrator().DropColumn(&PrefillGroup{}, "DeletedAt")) + } + for _, constraintName := range test.constraints { + require.NoError(t, tx.Exec( + "ALTER TABLE ? ADD CONSTRAINT ? UNIQUE (?)", + clause.Table{Name: "prefill_groups"}, + clause.Column{Name: constraintName}, + clause.Column{Name: "name"}, + ).Error) + } + for _, indexName := range test.indexes { + require.NoError(t, tx.Exec( + "CREATE UNIQUE INDEX ? ON ? (?)", + clause.Column{Name: indexName}, + clause.Table{Name: "prefill_groups"}, + clause.Column{Name: "name"}, + ).Error) + } if test.prepareOld != nil { test.prepareOld(t, tx) } - if len(test.blockedConstraints) > 0 || len(test.blockedIndexes) > 0 { + var oldIndexes []indexDefinition + require.NoError(t, tx.Raw(` +SELECT indexname, indexdef FROM pg_catalog.pg_indexes +WHERE schemaname = current_schema() AND tablename = 'prefill_groups' +ORDER BY indexname`).Scan(&oldIndexes).Error) + if test.wantError != "" { err := migratePrefillGroupUniqueness(tx) - require.Error(t, err) - assert.Contains(t, err.Error(), "prefill_groups_name_key") - for _, constraintName := range test.blockedConstraints { + require.ErrorContains(t, err, test.wantError) + for _, constraintName := range test.constraints { assert.True(t, tx.Migrator().HasConstraint(&PrefillGroup{}, constraintName)) } - for _, indexName := range test.blockedIndexes { - assert.True(t, tx.Migrator().HasIndex(&PrefillGroup{}, indexName)) - } + var restoredIndexes []indexDefinition + require.NoError(t, tx.Raw(` +SELECT indexname, indexdef FROM pg_catalog.pg_indexes +WHERE schemaname = current_schema() AND tablename = 'prefill_groups' +ORDER BY indexname`).Scan(&restoredIndexes).Error) + assert.Equal(t, oldIndexes, restoredIndexes) + assert.Equal(t, !test.withoutDeletedAt, tx.Migrator().HasColumn(&PrefillGroup{}, "DeletedAt")) + var preserved PrefillGroup + require.NoError(t, tx.Unscoped().First(&preserved, original.Id).Error) + assert.Equal(t, original, preserved) return } - for range 2 { - require.NoError(t, migratePrefillGroupUniqueness(tx)) - require.NoError(t, tx.AutoMigrate(&PrefillGroup{})) + recorder := &migrationSQLRecorder{} + migrationDB := tx.Session(&gorm.Session{Logger: recorder}) + for pass := range 2 { + recorder.reset() + require.NoError(t, migratePrefillGroupUniqueness(migrationDB)) + require.NoError(t, migrationDB.AutoMigrate(&PrefillGroup{})) + if pass == 1 { + assert.Empty(t, recorder.schemaMutations(), "repeated startup must not change the schema") + } } - for _, indexName := range test.preservedIndexes { - assert.True(t, tx.Migrator().HasIndex(&PrefillGroup{}, indexName)) + for _, oldIndex := range oldIndexes { + if oldIndex.Name == prefillGroupNameIndex || slices.Contains(test.constraints, oldIndex.Name) || slices.Contains(test.indexes, oldIndex.Name) { + continue + } + var definition string + require.NoError(t, tx.Raw(` +SELECT indexdef FROM pg_catalog.pg_indexes +WHERE schemaname = current_schema() AND indexname = ?`, oldIndex.Name).Scan(&definition).Error) + assert.Equal(t, oldIndex.Definition, definition) } var preserved PrefillGroup require.NoError(t, tx.First(&preserved, original.Id).Error) - assert.Equal(t, original.Name, preserved.Name) - assert.Equal(t, original.Description, preserved.Description) - - var globalConstraintCount int64 - require.NoError(t, tx.Raw(` -SELECT count(*) -FROM pg_catalog.pg_constraint AS constraint_meta -WHERE constraint_meta.conrelid = to_regclass('prefill_groups') - AND constraint_meta.contype = 'u' - AND cardinality(constraint_meta.conkey) = 1 - AND EXISTS ( - SELECT 1 - FROM pg_catalog.pg_attribute AS attribute_meta - WHERE attribute_meta.attrelid = constraint_meta.conrelid - AND attribute_meta.attnum = constraint_meta.conkey[1] - AND attribute_meta.attname = 'name' - )`).Scan(&globalConstraintCount).Error) - assert.Zero(t, globalConstraintCount) - - var globalIndexCount int64 - require.NoError(t, tx.Raw(` -SELECT count(*) -FROM pg_catalog.pg_index AS index_meta -JOIN pg_catalog.pg_attribute AS attribute_meta - ON attribute_meta.attrelid = index_meta.indrelid - AND attribute_meta.attnum = index_meta.indkey[0] -WHERE index_meta.indrelid = to_regclass('prefill_groups') - AND index_meta.indisunique - AND NOT index_meta.indisprimary - AND index_meta.indpred IS NULL - AND index_meta.indexprs IS NULL - AND index_meta.indnatts = 1 - AND attribute_meta.attname = 'name'`).Scan(&globalIndexCount).Error) - assert.Zero(t, globalIndexCount) + assert.Equal(t, original, preserved) var targetIndexDefinition string require.NoError(t, tx.Raw(`