Skip to content

Commit

Permalink
Make down SQL in rename column operations use the new name of the c…
Browse files Browse the repository at this point in the history
…olumn (#354)

Ensure that 'alter column' operations that rename a column and also
specify `down` SQL (such as those that alter some other column attribute
at the time of the rename) must use the new name of the column in the
`down` SQL.

Without this change, the `down` SQL would require the use of the old
column name.

Fixes #350
  • Loading branch information
andrew-farries committed May 16, 2024
1 parent 4c1bc6a commit 4d3faeb
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
2 changes: 1 addition & 1 deletion examples/35_alter_column_multiple.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"constraint": "length(name) > 3"
},
"up": "(SELECT CASE WHEN name IS NULL OR LENGTH(name) <= 3 THEN 'placeholder' ELSE name END)",
"down": "name"
"down": "event_name"
}
}
]
Expand Down
13 changes: 12 additions & 1 deletion pkg/migrations/op_alter_column.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package migrations
import (
"context"
"fmt"
"maps"

"github.com/lib/pq"
"github.com/xataio/pgroll/pkg/db"
Expand Down Expand Up @@ -57,11 +58,21 @@ func (o *OpAlterColumn) Start(ctx context.Context, conn db.DB, stateSchema strin
Name: TemporaryName(o.Column),
})

// If the column has been renamed, temporarily update the column name in
// the internal schema representation to ensure that the variable name in
// the down trigger corresponds to the new name of column.
cols := table.Columns
if o.Name != nil {
cols = maps.Clone(table.Columns)
cols[*o.Name] = cols[o.Column]
delete(cols, o.Column)
}

// Add a trigger to copy values from the new column to the old.
err = createTrigger(ctx, conn, tr, triggerConfig{
Name: TriggerName(o.Table, TemporaryName(o.Column)),
Direction: TriggerDirectionDown,
Columns: table.Columns,
Columns: cols,
SchemaName: s.Name,
TableName: o.Table,
PhysicalColumn: o.Column,
Expand Down
4 changes: 2 additions & 2 deletions pkg/migrations/op_alter_column_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func TestAlterColumnMultipleSubOperations(t *testing.T) {
Table: "events",
Column: "name",
Up: "(SELECT CASE WHEN name IS NULL OR LENGTH(name) <= 3 THEN 'placeholder' ELSE name END)",
Down: "name",
Down: "event_name",
Name: ptr("event_name"),
Type: ptr("text"),
Comment: nullable.NewNullableWithValue("the name of the event"),
Expand Down Expand Up @@ -319,7 +319,7 @@ func TestAlterColumnMultipleSubOperations(t *testing.T) {
Table: "events",
Column: "name",
Up: "name || '-' || random()*999::int",
Down: "name",
Down: "event_name",
Name: ptr("event_name"),
Unique: &migrations.UniqueConstraint{
Name: "events_event_name_unique",
Expand Down

0 comments on commit 4d3faeb

Please sign in to comment.