|
| 1 | +package model |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "gorm.io/gorm" |
| 7 | + "gorm.io/gorm/clause" |
| 8 | +) |
| 9 | + |
| 10 | +const prefillGroupNameIndex = "uk_prefill_name" |
| 11 | + |
| 12 | +type conflictingPrefillGroupUniqueness struct { |
| 13 | + constraints []string |
| 14 | + indexes []string |
| 15 | +} |
| 16 | + |
| 17 | +type prefillGroupNameIndexState struct { |
| 18 | + exists bool |
| 19 | + valid bool |
| 20 | +} |
| 21 | + |
| 22 | +func (conflicts conflictingPrefillGroupUniqueness) empty() bool { |
| 23 | + return len(conflicts.constraints) == 0 && len(conflicts.indexes) == 0 |
| 24 | +} |
| 25 | + |
| 26 | +func inspectConflictingPrefillGroupUniqueness(db *gorm.DB, tableName string) (conflictingPrefillGroupUniqueness, error) { |
| 27 | + var conflicts conflictingPrefillGroupUniqueness |
| 28 | + if err := db.Raw(` |
| 29 | +SELECT constraint_meta.conname |
| 30 | +FROM pg_catalog.pg_constraint AS constraint_meta |
| 31 | +WHERE constraint_meta.conrelid = to_regclass(?) |
| 32 | + AND constraint_meta.contype = 'u' |
| 33 | + AND cardinality(constraint_meta.conkey) = 1 |
| 34 | + AND EXISTS ( |
| 35 | + SELECT 1 |
| 36 | + FROM pg_catalog.pg_attribute AS attribute_meta |
| 37 | + WHERE attribute_meta.attrelid = constraint_meta.conrelid |
| 38 | + AND attribute_meta.attnum = constraint_meta.conkey[1] |
| 39 | + AND attribute_meta.attname = ? |
| 40 | + ) |
| 41 | +ORDER BY constraint_meta.conname`, tableName, "name").Scan(&conflicts.constraints).Error; err != nil { |
| 42 | + return conflicts, fmt.Errorf("inspect conflicting prefill group unique constraints: %w", err) |
| 43 | + } |
| 44 | + |
| 45 | + if err := db.Raw(` |
| 46 | +SELECT index_class.relname |
| 47 | +FROM pg_catalog.pg_index AS index_meta |
| 48 | +JOIN pg_catalog.pg_class AS index_class |
| 49 | + ON index_class.oid = index_meta.indexrelid |
| 50 | +JOIN pg_catalog.pg_attribute AS attribute_meta |
| 51 | + ON attribute_meta.attrelid = index_meta.indrelid |
| 52 | + AND attribute_meta.attnum = index_meta.indkey[0] |
| 53 | +WHERE index_meta.indrelid = to_regclass(?) |
| 54 | + AND index_meta.indisunique |
| 55 | + AND NOT index_meta.indisprimary |
| 56 | + AND index_meta.indpred IS NULL |
| 57 | + AND index_meta.indexprs IS NULL |
| 58 | + AND index_meta.indnatts = 1 |
| 59 | + AND attribute_meta.attname = ? |
| 60 | + AND NOT EXISTS ( |
| 61 | + SELECT 1 |
| 62 | + FROM pg_catalog.pg_constraint AS constraint_meta |
| 63 | + WHERE constraint_meta.conindid = index_meta.indexrelid |
| 64 | + ) |
| 65 | +ORDER BY index_class.relname`, tableName, "name").Scan(&conflicts.indexes).Error; err != nil { |
| 66 | + return conflicts, fmt.Errorf("inspect conflicting prefill group unique indexes: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + return conflicts, nil |
| 70 | +} |
| 71 | + |
| 72 | +func inspectPrefillGroupNameIndex(db *gorm.DB, tableName string) (prefillGroupNameIndexState, error) { |
| 73 | + var state struct { |
| 74 | + Exists bool `gorm:"column:index_exists"` |
| 75 | + Valid bool `gorm:"column:index_valid"` |
| 76 | + } |
| 77 | + if err := db.Raw(` |
| 78 | +SELECT count(*) > 0 AS index_exists, |
| 79 | + COALESCE(bool_or( |
| 80 | + index_meta.indisunique |
| 81 | + AND index_meta.indisvalid |
| 82 | + AND index_meta.indisready |
| 83 | + AND NOT index_meta.indisprimary |
| 84 | + AND index_meta.indexprs IS NULL |
| 85 | + AND index_meta.indnatts = 1 |
| 86 | + AND attribute_meta.attname = ? |
| 87 | + AND pg_get_expr(index_meta.indpred, index_meta.indrelid) = '(deleted_at IS NULL)' |
| 88 | + ), false) AS index_valid |
| 89 | +FROM pg_catalog.pg_index AS index_meta |
| 90 | +JOIN pg_catalog.pg_class AS index_class |
| 91 | + ON index_class.oid = index_meta.indexrelid |
| 92 | +LEFT JOIN pg_catalog.pg_attribute AS attribute_meta |
| 93 | + ON attribute_meta.attrelid = index_meta.indrelid |
| 94 | + AND attribute_meta.attnum = index_meta.indkey[0] |
| 95 | +WHERE index_meta.indrelid = to_regclass(?) |
| 96 | + AND index_class.relname = ?`, "name", tableName, prefillGroupNameIndex).Scan(&state).Error; err != nil { |
| 97 | + return prefillGroupNameIndexState{}, fmt.Errorf("inspect prefill group partial unique index: %w", err) |
| 98 | + } |
| 99 | + return prefillGroupNameIndexState{exists: state.Exists, valid: state.Valid}, nil |
| 100 | +} |
| 101 | + |
| 102 | +// migratePrefillGroupUniqueness removes global PostgreSQL uniqueness left by |
| 103 | +// older GORM versions before AutoMigrate reconciles the current partial index. |
| 104 | +func migratePrefillGroupUniqueness(db *gorm.DB) error { |
| 105 | + if db == nil { |
| 106 | + return fmt.Errorf("migrate prefill group uniqueness: database is nil") |
| 107 | + } |
| 108 | + if db.Dialector.Name() != "postgres" { |
| 109 | + return nil |
| 110 | + } |
| 111 | + |
| 112 | + statement := &gorm.Statement{DB: db} |
| 113 | + if err := statement.Parse(&PrefillGroup{}); err != nil { |
| 114 | + return fmt.Errorf("parse prefill group schema: %w", err) |
| 115 | + } |
| 116 | + tableName := statement.Schema.Table |
| 117 | + conflicts, err := inspectConflictingPrefillGroupUniqueness(db, tableName) |
| 118 | + if err != nil { |
| 119 | + return err |
| 120 | + } |
| 121 | + if conflicts.empty() { |
| 122 | + return nil |
| 123 | + } |
| 124 | + |
| 125 | + return db.Transaction(func(tx *gorm.DB) error { |
| 126 | + migrator := tx.Migrator() |
| 127 | + if !migrator.HasTable(&PrefillGroup{}) { |
| 128 | + return nil |
| 129 | + } |
| 130 | + |
| 131 | + if err := tx.Exec( |
| 132 | + "LOCK TABLE ? IN ACCESS EXCLUSIVE MODE", |
| 133 | + clause.Table{Name: tableName}, |
| 134 | + ).Error; err != nil { |
| 135 | + return fmt.Errorf("lock prefill groups for uniqueness migration: %w", err) |
| 136 | + } |
| 137 | + |
| 138 | + conflicts, err := inspectConflictingPrefillGroupUniqueness(tx, tableName) |
| 139 | + if err != nil { |
| 140 | + return err |
| 141 | + } |
| 142 | + if conflicts.empty() { |
| 143 | + return nil |
| 144 | + } |
| 145 | + |
| 146 | + if !migrator.HasColumn(&PrefillGroup{}, "DeletedAt") { |
| 147 | + if err := migrator.AddColumn(&PrefillGroup{}, "DeletedAt"); err != nil { |
| 148 | + return fmt.Errorf("add prefill groups deleted_at column: %w", err) |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + for _, constraintName := range conflicts.constraints { |
| 153 | + if err := migrator.DropConstraint(&PrefillGroup{}, constraintName); err != nil { |
| 154 | + return fmt.Errorf("drop conflicting prefill group constraint %q: %w", constraintName, err) |
| 155 | + } |
| 156 | + } |
| 157 | + for _, indexName := range conflicts.indexes { |
| 158 | + if err := migrator.DropIndex(&PrefillGroup{}, indexName); err != nil { |
| 159 | + return fmt.Errorf("drop conflicting prefill group index %q: %w", indexName, err) |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + targetIndex, err := inspectPrefillGroupNameIndex(tx, tableName) |
| 164 | + if err != nil { |
| 165 | + return err |
| 166 | + } |
| 167 | + if !targetIndex.exists { |
| 168 | + if err := migrator.CreateIndex(&PrefillGroup{}, prefillGroupNameIndex); err != nil { |
| 169 | + return fmt.Errorf("create prefill group partial unique index: %w", err) |
| 170 | + } |
| 171 | + targetIndex, err = inspectPrefillGroupNameIndex(tx, tableName) |
| 172 | + if err != nil { |
| 173 | + return err |
| 174 | + } |
| 175 | + } |
| 176 | + if !targetIndex.valid { |
| 177 | + return fmt.Errorf("prefill group index %q has an unexpected definition", prefillGroupNameIndex) |
| 178 | + } |
| 179 | + |
| 180 | + return nil |
| 181 | + }) |
| 182 | +} |
0 commit comments