|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +package migrations |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/lib/pq" |
| 11 | + |
| 12 | + "github.com/xataio/pgroll/pkg/db" |
| 13 | + "github.com/xataio/pgroll/pkg/schema" |
| 14 | +) |
| 15 | + |
| 16 | +var _ Operation = (*OpCreateConstraint)(nil) |
| 17 | + |
| 18 | +func (o *OpCreateConstraint) Start(ctx context.Context, conn db.DB, latestSchema string, tr SQLTransformer, s *schema.Schema, cbs ...CallbackFn) (*schema.Table, error) { |
| 19 | + var err error |
| 20 | + var table *schema.Table |
| 21 | + for _, col := range o.Columns { |
| 22 | + if table, err = o.duplicateColumnBeforeStart(ctx, conn, latestSchema, tr, col, s); err != nil { |
| 23 | + return nil, err |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + switch o.Type { //nolint:gocritic // more cases will be added |
| 28 | + case OpCreateConstraintTypeUnique: |
| 29 | + return table, o.addUniqueIndex(ctx, conn) |
| 30 | + } |
| 31 | + |
| 32 | + return table, nil |
| 33 | +} |
| 34 | + |
| 35 | +func (o *OpCreateConstraint) duplicateColumnBeforeStart(ctx context.Context, conn db.DB, latestSchema string, tr SQLTransformer, colName string, s *schema.Schema) (*schema.Table, error) { |
| 36 | + table := s.GetTable(o.Table) |
| 37 | + column := table.GetColumn(colName) |
| 38 | + |
| 39 | + d := NewColumnDuplicator(conn, table, column) |
| 40 | + if err := d.Duplicate(ctx); err != nil { |
| 41 | + return nil, fmt.Errorf("failed to duplicate column for new constraint: %w", err) |
| 42 | + } |
| 43 | + |
| 44 | + upSQL, ok := o.Up[colName] |
| 45 | + if !ok { |
| 46 | + return nil, fmt.Errorf("up migration is missing for column %s", colName) |
| 47 | + } |
| 48 | + physicalColumnName := TemporaryName(colName) |
| 49 | + err := createTrigger(ctx, conn, tr, triggerConfig{ |
| 50 | + Name: TriggerName(o.Table, colName), |
| 51 | + Direction: TriggerDirectionUp, |
| 52 | + Columns: table.Columns, |
| 53 | + SchemaName: s.Name, |
| 54 | + LatestSchema: latestSchema, |
| 55 | + TableName: o.Table, |
| 56 | + PhysicalColumn: physicalColumnName, |
| 57 | + SQL: upSQL, |
| 58 | + }) |
| 59 | + if err != nil { |
| 60 | + return nil, fmt.Errorf("failed to create up trigger: %w", err) |
| 61 | + } |
| 62 | + |
| 63 | + table.AddColumn(colName, schema.Column{ |
| 64 | + Name: physicalColumnName, |
| 65 | + }) |
| 66 | + |
| 67 | + downSQL, ok := o.Down[colName] |
| 68 | + if !ok { |
| 69 | + return nil, fmt.Errorf("down migration is missing for column %s", colName) |
| 70 | + } |
| 71 | + err = createTrigger(ctx, conn, tr, triggerConfig{ |
| 72 | + Name: TriggerName(o.Table, physicalColumnName), |
| 73 | + Direction: TriggerDirectionDown, |
| 74 | + Columns: table.Columns, |
| 75 | + LatestSchema: latestSchema, |
| 76 | + SchemaName: s.Name, |
| 77 | + TableName: o.Table, |
| 78 | + PhysicalColumn: colName, |
| 79 | + SQL: downSQL, |
| 80 | + }) |
| 81 | + if err != nil { |
| 82 | + return nil, fmt.Errorf("failed to create down trigger: %w", err) |
| 83 | + } |
| 84 | + return table, nil |
| 85 | +} |
| 86 | + |
| 87 | +func (o *OpCreateConstraint) Complete(ctx context.Context, conn db.DB, tr SQLTransformer, s *schema.Schema) error { |
| 88 | + switch o.Type { //nolint:gocritic // more cases will be added |
| 89 | + case OpCreateConstraintTypeUnique: |
| 90 | + uniqueOp := &OpSetUnique{ |
| 91 | + Table: o.Table, |
| 92 | + Name: o.Name, |
| 93 | + } |
| 94 | + err := uniqueOp.Complete(ctx, conn, tr, s) |
| 95 | + if err != nil { |
| 96 | + return err |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + // remove old columns |
| 101 | + _, err := conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s %s", |
| 102 | + pq.QuoteIdentifier(o.Table), |
| 103 | + dropMultipleColumns(quoteColumnNames(o.Columns)), |
| 104 | + )) |
| 105 | + if err != nil { |
| 106 | + return err |
| 107 | + } |
| 108 | + |
| 109 | + // rename new columns to old name |
| 110 | + table := s.GetTable(o.Table) |
| 111 | + for _, col := range o.Columns { |
| 112 | + column := table.GetColumn(col) |
| 113 | + if err := RenameDuplicatedColumn(ctx, conn, table, column); err != nil { |
| 114 | + return err |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + return o.removeTriggers(ctx, conn) |
| 119 | +} |
| 120 | + |
| 121 | +func (o *OpCreateConstraint) Rollback(ctx context.Context, conn db.DB, tr SQLTransformer, s *schema.Schema) error { |
| 122 | + _, err := conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s %s", |
| 123 | + pq.QuoteIdentifier(o.Table), |
| 124 | + dropMultipleColumns(quotedTemporaryNames(o.Columns)), |
| 125 | + )) |
| 126 | + if err != nil { |
| 127 | + return err |
| 128 | + } |
| 129 | + |
| 130 | + return o.removeTriggers(ctx, conn) |
| 131 | +} |
| 132 | + |
| 133 | +func (o *OpCreateConstraint) removeTriggers(ctx context.Context, conn db.DB) error { |
| 134 | + dropFuncs := make([]string, len(o.Columns)*2) |
| 135 | + for i, j := 0, 0; i < len(o.Columns); i, j = i+1, j+2 { |
| 136 | + dropFuncs[j] = pq.QuoteIdentifier(TriggerFunctionName(o.Table, o.Columns[i])) |
| 137 | + dropFuncs[j+1] = pq.QuoteIdentifier(TriggerFunctionName(o.Table, TemporaryName(o.Columns[i]))) |
| 138 | + } |
| 139 | + _, err := conn.ExecContext(ctx, fmt.Sprintf("DROP FUNCTION IF EXISTS %s CASCADE", |
| 140 | + strings.Join(dropFuncs, ", "), |
| 141 | + )) |
| 142 | + return err |
| 143 | +} |
| 144 | + |
| 145 | +func dropMultipleColumns(columns []string) string { |
| 146 | + for i, col := range columns { |
| 147 | + columns[i] = "DROP COLUMN IF EXISTS " + col |
| 148 | + } |
| 149 | + return strings.Join(columns, ", ") |
| 150 | +} |
| 151 | + |
| 152 | +func (o *OpCreateConstraint) Validate(ctx context.Context, s *schema.Schema) error { |
| 153 | + table := s.GetTable(o.Table) |
| 154 | + if table == nil { |
| 155 | + return TableDoesNotExistError{Name: o.Table} |
| 156 | + } |
| 157 | + |
| 158 | + if err := ValidateIdentifierLength(o.Name); err != nil { |
| 159 | + return err |
| 160 | + } |
| 161 | + |
| 162 | + if table.ConstraintExists(o.Name) { |
| 163 | + return ConstraintAlreadyExistsError{ |
| 164 | + Table: o.Table, |
| 165 | + Constraint: o.Name, |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + for _, col := range o.Columns { |
| 170 | + if table.GetColumn(col) == nil { |
| 171 | + return ColumnDoesNotExistError{ |
| 172 | + Table: o.Table, |
| 173 | + Name: col, |
| 174 | + } |
| 175 | + } |
| 176 | + if _, ok := o.Up[col]; !ok { |
| 177 | + return ColumnMigrationMissingError{ |
| 178 | + Table: o.Table, |
| 179 | + Name: col, |
| 180 | + } |
| 181 | + } |
| 182 | + if _, ok := o.Down[col]; !ok { |
| 183 | + return ColumnMigrationMissingError{ |
| 184 | + Table: o.Table, |
| 185 | + Name: col, |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + switch o.Type { //nolint:gocritic // more cases will be added |
| 191 | + case OpCreateConstraintTypeUnique: |
| 192 | + if len(o.Columns) == 0 { |
| 193 | + return FieldRequiredError{Name: "columns"} |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + return nil |
| 198 | +} |
| 199 | + |
| 200 | +func (o *OpCreateConstraint) addUniqueIndex(ctx context.Context, conn db.DB) error { |
| 201 | + _, err := conn.ExecContext(ctx, fmt.Sprintf("CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS %s ON %s (%s)", |
| 202 | + pq.QuoteIdentifier(o.Name), |
| 203 | + pq.QuoteIdentifier(o.Table), |
| 204 | + strings.Join(quotedTemporaryNames(o.Columns), ", "), |
| 205 | + )) |
| 206 | + |
| 207 | + return err |
| 208 | +} |
| 209 | + |
| 210 | +func quotedTemporaryNames(columns []string) []string { |
| 211 | + names := make([]string, len(columns)) |
| 212 | + for i, col := range columns { |
| 213 | + names[i] = pq.QuoteIdentifier(TemporaryName(col)) |
| 214 | + } |
| 215 | + return names |
| 216 | +} |
0 commit comments