Make down SQL in rename column operations use the new name of the column (#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
This commit is contained in:
Andrew Farries 2024-05-16 11:57:53 +01:00 committed by GitHub
parent 4c1bc6a03f
commit 4d3faebffd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 15 additions and 4 deletions

View File

@ -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"
}
}
]

View File

@ -5,6 +5,7 @@ package migrations
import (
"context"
"fmt"
"maps"
"github.com/lib/pq"
"github.com/xataio/pgroll/pkg/db"
@ -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,

View File

@ -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"),
@ -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",