Skip to content

Commit

Permalink
Preserve column properties on add CHECK constraint operation (#236)
Browse files Browse the repository at this point in the history
Preserve properties of columns when duplicating them for backfilling to
add a`CHECK` constraint. Currently, the column properties that are
preserved are:

* `DEFAULT`s
* foreign key constraints

but this list will grow as more work is done on #227.
  • Loading branch information
andrew-farries committed Jan 16, 2024
1 parent dde27eb commit ddb91d1
Show file tree
Hide file tree
Showing 2 changed files with 265 additions and 117 deletions.
11 changes: 5 additions & 6 deletions pkg/migrations/op_set_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ func (o *OpSetCheckConstraint) Start(ctx context.Context, conn *sql.DB, stateSch
column := table.GetColumn(o.Column)

// Create a copy of the column on the underlying table.
if err := duplicateColumn(ctx, conn, table, *column); err != nil {
d := NewColumnDuplicator(conn, table, column)
if err := d.Duplicate(ctx); err != nil {
return fmt.Errorf("failed to duplicate column: %w", err)
}

Expand Down Expand Up @@ -112,11 +113,9 @@ func (o *OpSetCheckConstraint) Complete(ctx context.Context, conn *sql.DB, s *sc
}

// Rename the new column to the old column name
_, err = conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE IF EXISTS %s RENAME COLUMN %s TO %s",
pq.QuoteIdentifier(o.Table),
pq.QuoteIdentifier(TemporaryName(o.Column)),
pq.QuoteIdentifier(o.Column)))
if err != nil {
table := s.GetTable(o.Table)
column := table.GetColumn(o.Column)
if err := RenameDuplicatedColumn(ctx, conn, table, column); err != nil {
return err
}

Expand Down

0 comments on commit ddb91d1

Please sign in to comment.