Skip to content

Commit

Permalink
Fall back to raw SQL for NOT VALID foreign key constraints (#539)
Browse files Browse the repository at this point in the history
Update how `sql2pgroll` handles conversion of `ALTER TABLE ... ADD
CONSTRAINT ... FOREIGN KEY` statements.

Fall back to raw SQL if `NOT VALID` is specified as part of an `ALTER
TABLE ... ADD CONSTRAINT ... FOREIGN KEY` statement because
`OpCreateMultiColumnConstraint` currently always validates foreign key
constraints.
  • Loading branch information
andrew-farries authored Dec 17, 2024
1 parent 3de40ab commit c68ba72
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
4 changes: 4 additions & 0 deletions pkg/sql2pgroll/alter_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ func convertAlterTableAddForeignKeyConstraint(stmt *pgq.AlterTableStmt, constrai
}

func canConvertAlterTableAddForeignKeyConstraint(constraint *pgq.Constraint) bool {
if constraint.SkipValidation {
return false
}

switch constraint.GetFkUpdAction() {
case "r", "c", "n", "d":
// RESTRICT, CASCADE, SET NULL, SET DEFAULT
Expand Down
5 changes: 1 addition & 4 deletions pkg/sql2pgroll/alter_table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,6 @@ func TestConvertAlterTableStatements(t *testing.T) {
sql: "ALTER TABLE foo ADD CONSTRAINT fk_bar_c FOREIGN KEY (a) REFERENCES bar (c);",
expectedOp: expect.AddForeignKeyOp2,
},
{
sql: "ALTER TABLE foo ADD CONSTRAINT fk_bar_c FOREIGN KEY (a) REFERENCES bar (c) NOT VALID;",
expectedOp: expect.AddForeignKeyOp2,
},
{
sql: "ALTER TABLE schema_a.foo ADD CONSTRAINT fk_bar_c FOREIGN KEY (a) REFERENCES schema_a.bar (c);",
expectedOp: expect.AddForeignKeyOp3,
Expand Down Expand Up @@ -184,6 +180,7 @@ func TestUnconvertableAlterTableStatements(t *testing.T) {
"ALTER TABLE foo ADD CONSTRAINT fk_bar_cd FOREIGN KEY (a, b) REFERENCES bar (c, d) ON UPDATE SET NULL;",
"ALTER TABLE foo ADD CONSTRAINT fk_bar_cd FOREIGN KEY (a, b) REFERENCES bar (c, d) ON UPDATE SET DEFAULT;",
"ALTER TABLE foo ADD CONSTRAINT fk_bar_cd FOREIGN KEY (a, b) REFERENCES bar (c, d) MATCH FULL;",
"ALTER TABLE foo ADD CONSTRAINT fk_bar_cd FOREIGN KEY (a, b) REFERENCES bar (c, d) NOT VALID",
// MATCH PARTIAL is not implemented in the actual parser yet
//"ALTER TABLE foo ADD CONSTRAINT fk_bar_cd FOREIGN KEY (a, b) REFERENCES bar (c, d) MATCH PARTIAL;",

Expand Down

0 comments on commit c68ba72

Please sign in to comment.