Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support table and column rename operations preceding create_constraint operations #674

Merged
merged 6 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions pkg/migrations/op_create_constraint.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,42 +22,50 @@ func (o *OpCreateConstraint) Start(ctx context.Context, conn db.DB, latestSchema
columns[i] = table.GetColumn(colName)
}

// Duplicate each column using its final name after migration completion
d := NewColumnDuplicator(conn, table, columns...)
for _, colName := range o.Columns {
d = d.WithName(table.GetColumn(colName).Name, TemporaryName(colName))
}
if err := d.Duplicate(ctx); err != nil {
return nil, fmt.Errorf("failed to duplicate columns for new constraint: %w", err)
}

// Setup triggers
for _, colName := range o.Columns {
upSQL := o.Up[colName]
physicalColumnName := TemporaryName(colName)
err := createTrigger(ctx, conn, tr, triggerConfig{
Name: TriggerName(o.Table, colName),
Direction: TriggerDirectionUp,
Columns: table.Columns,
SchemaName: s.Name,
LatestSchema: latestSchema,
TableName: o.Table,
PhysicalColumn: physicalColumnName,
TableName: table.Name,
PhysicalColumn: TemporaryName(colName),
SQL: upSQL,
})
if err != nil {
return nil, fmt.Errorf("failed to create up trigger: %w", err)
}

// Add the new column to the internal schema representation. This is done
// here, before creation of the down trigger, so that the trigger can declare
// a variable for the new column. Save the old column name for use as the
// physical column name in the down trigger first.
oldPhysicalColumn := table.GetColumn(colName).Name
table.AddColumn(colName, &schema.Column{
Name: physicalColumnName,
Name: TemporaryName(colName),
})

downSQL := o.Down[colName]
err = createTrigger(ctx, conn, tr, triggerConfig{
Name: TriggerName(o.Table, physicalColumnName),
Name: TriggerName(o.Table, TemporaryName(colName)),
Direction: TriggerDirectionDown,
Columns: table.Columns,
LatestSchema: latestSchema,
SchemaName: s.Name,
TableName: o.Table,
PhysicalColumn: colName,
TableName: table.Name,
PhysicalColumn: oldPhysicalColumn,
SQL: downSQL,
})
if err != nil {
Expand All @@ -69,7 +77,7 @@ func (o *OpCreateConstraint) Start(ctx context.Context, conn db.DB, latestSchema
case OpCreateConstraintTypeUnique:
return table, createUniqueIndexConcurrently(ctx, conn, s.Name, o.Name, o.Table, temporaryNames(o.Columns))
case OpCreateConstraintTypeCheck:
return table, o.addCheckConstraint(ctx, conn)
return table, o.addCheckConstraint(ctx, conn, table.Name)
case OpCreateConstraintTypeForeignKey:
return table, o.addForeignKeyConstraint(ctx, conn)
}
Expand Down Expand Up @@ -134,8 +142,10 @@ func (o *OpCreateConstraint) Complete(ctx context.Context, conn db.DB, tr SQLTra
}

func (o *OpCreateConstraint) Rollback(ctx context.Context, conn db.DB, tr SQLTransformer, s *schema.Schema) error {
table := s.GetTable(o.Table)

_, err := conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s %s",
pq.QuoteIdentifier(o.Table),
pq.QuoteIdentifier(table.Name),
dropMultipleColumns(quotedTemporaryNames(o.Columns)),
))
if err != nil {
Expand Down Expand Up @@ -232,9 +242,9 @@ func (o *OpCreateConstraint) Validate(ctx context.Context, s *schema.Schema) err
return nil
}

func (o *OpCreateConstraint) addCheckConstraint(ctx context.Context, conn db.DB) error {
func (o *OpCreateConstraint) addCheckConstraint(ctx context.Context, conn db.DB, tableName string) error {
_, err := conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s ADD CONSTRAINT %s CHECK (%s) NOT VALID",
pq.QuoteIdentifier(o.Table),
pq.QuoteIdentifier(tableName),
pq.QuoteIdentifier(o.Name),
rewriteCheckExpression(*o.Check, o.Columns...),
))
Expand Down
228 changes: 228 additions & 0 deletions pkg/migrations/op_create_constraint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,234 @@ func TestCreateConstraint(t *testing.T) {
})
}

func TestCreateConstraintInMultiOperationMigrations(t *testing.T) {
t.Parallel()

ExecuteTests(t, TestCases{
{
name: "rename table, create constraint",
migrations: []migrations.Migration{
{
Name: "01_create_table",
Operations: migrations.Operations{
&migrations.OpCreateTable{
Name: "items",
Columns: []migrations.Column{
{
Name: "id",
Type: "int",
Pk: true,
},
{
Name: "name",
Type: "varchar(255)",
Nullable: true,
},
},
},
},
},
{
Name: "02_multi_operation",
Operations: migrations.Operations{
&migrations.OpRenameTable{
From: "items",
To: "products",
},
&migrations.OpCreateConstraint{
Table: "products",
Type: migrations.OpCreateConstraintTypeCheck,
Name: "check_name",
Check: ptr("length(name) > 3"),
Columns: []string{"name"},
Up: map[string]string{
"name": "CASE WHEN length(name) <= 3 THEN name || '-xxx' ELSE name END",
},
Down: map[string]string{
"name": "name",
},
},
},
},
},
afterStart: func(t *testing.T, db *sql.DB, schema string) {
// Can insert a row into the new schema that meets the constraint
MustInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "1",
"name": "apple",
})

// Can't insert a row into the new schema that violates the constraint
MustNotInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "2",
"name": "abc",
}, testutils.CheckViolationErrorCode)

// Can insert a row into the old schema that violates the constraint
MustInsert(t, db, schema, "01_create_table", "items", map[string]string{
"id": "2",
"name": "abc",
})

// The new view has the expected rows
rows := MustSelect(t, db, schema, "02_multi_operation", "products")
assert.Equal(t, []map[string]any{
{"id": 1, "name": "apple"},
{"id": 2, "name": "abc-xxx"},
}, rows)

// The old view has the expected rows
rows = MustSelect(t, db, schema, "01_create_table", "items")
assert.Equal(t, []map[string]any{
{"id": 1, "name": "apple"},
{"id": 2, "name": "abc"},
}, rows)
},
afterRollback: func(t *testing.T, db *sql.DB, schema string) {
// The table has been cleaned up
TableMustBeCleanedUp(t, db, schema, "items", "name")
},
afterComplete: func(t *testing.T, db *sql.DB, schema string) {
// Can insert a row into the new schema that meets the constraint
MustInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "3",
"name": "banana",
})

// Can't insert a row into the new schema that violates the constraint
MustNotInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "3",
"name": "abc",
}, testutils.CheckViolationErrorCode)

// The new view has the expected rows
rows := MustSelect(t, db, schema, "02_multi_operation", "products")
assert.Equal(t, []map[string]any{
{"id": 1, "name": "apple"},
{"id": 2, "name": "abc-xxx"},
{"id": 3, "name": "banana"},
}, rows)

// The table has been cleaned up
TableMustBeCleanedUp(t, db, schema, "products", "name")
},
},
{
name: "rename table, rename column, create constraint",
migrations: []migrations.Migration{
{
Name: "01_create_table",
Operations: migrations.Operations{
&migrations.OpCreateTable{
Name: "items",
Columns: []migrations.Column{
{
Name: "id",
Type: "int",
Pk: true,
},
{
Name: "name",
Type: "varchar(255)",
Nullable: true,
},
},
},
},
},
{
Name: "02_multi_operation",
Operations: migrations.Operations{
&migrations.OpRenameTable{
From: "items",
To: "products",
},
&migrations.OpRenameColumn{
Table: "products",
From: "name",
To: "item_name",
},
&migrations.OpCreateConstraint{
Table: "products",
Type: migrations.OpCreateConstraintTypeCheck,
Name: "check_item_name",
Check: ptr("length(item_name) > 3"),
Columns: []string{"item_name"},
Up: map[string]string{
"item_name": "CASE WHEN length(item_name) <= 3 THEN item_name || '-xxx' ELSE item_name END",
},
Down: map[string]string{
"item_name": "item_name",
},
},
},
},
},
afterStart: func(t *testing.T, db *sql.DB, schema string) {
// Can insert a row into the new schema that meets the constraint
MustInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "1",
"item_name": "apple",
})

// Can't insert a row into the new schema that violates the constraint
MustNotInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "2",
"item_name": "abc",
}, testutils.CheckViolationErrorCode)

// Can insert a row into the old schema that violates the constraint
MustInsert(t, db, schema, "01_create_table", "items", map[string]string{
"id": "2",
"name": "abc",
})

// The new view has the expected rows
rows := MustSelect(t, db, schema, "02_multi_operation", "products")
assert.Equal(t, []map[string]any{
{"id": 1, "item_name": "apple"},
{"id": 2, "item_name": "abc-xxx"},
}, rows)

// The old view has the expected rows
rows = MustSelect(t, db, schema, "01_create_table", "items")
assert.Equal(t, []map[string]any{
{"id": 1, "name": "apple"},
{"id": 2, "name": "abc"},
}, rows)
},
afterRollback: func(t *testing.T, db *sql.DB, schema string) {
// The table has been cleaned up
TableMustBeCleanedUp(t, db, schema, "items", "name")
},
afterComplete: func(t *testing.T, db *sql.DB, schema string) {
// Can insert a row into the new schema that meets the constraint
MustInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "3",
"item_name": "banana",
})

// Can't insert a row into the new schema that violates the constraint
MustNotInsert(t, db, schema, "02_multi_operation", "products", map[string]string{
"id": "3",
"item_name": "abc",
}, testutils.CheckViolationErrorCode)

// The new view has the expected rows
rows := MustSelect(t, db, schema, "02_multi_operation", "products")
assert.Equal(t, []map[string]any{
{"id": 1, "item_name": "apple"},
{"id": 2, "item_name": "abc-xxx"},
{"id": 3, "item_name": "banana"},
}, rows)

// The table has been cleaned up
TableMustBeCleanedUp(t, db, schema, "products", "name")
},
},
})
}

func TestCreateConstraintValidation(t *testing.T) {
t.Parallel()

Expand Down