Skip to content

Commit 4b37c76

Browse files
Convert DROP NOT NULL SQL to pgroll operation
Convert SQL like: ```sql ALTER TABLE foo ALTER COLUMN a DROP NOT NULL ``` to the equivalent `pgroll` operation: ```json [ { "alter_column": { "column": "a", "down": "TODO: Implement SQL data migration", "nullable": true, "table": "foo", "up": "TODO: Implement SQL data migration" } } ] ```
1 parent 1f6f49b commit 4b37c76

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

pkg/sql2pgroll/alter_table.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,22 @@ func convertAlterTableStmt(stmt *pgq.AlterTableStmt) (migrations.Operations, err
2222
continue
2323
}
2424

25-
//nolint:gocritic
2625
switch alterTableCmd.Subtype {
2726
case pgq.AlterTableType_AT_SetNotNull:
28-
ops = append(ops, convertAlterTableSetNotNull(stmt, alterTableCmd))
27+
ops = append(ops, convertAlterTableSetNotNull(stmt, alterTableCmd, true))
28+
case pgq.AlterTableType_AT_DropNotNull:
29+
ops = append(ops, convertAlterTableSetNotNull(stmt, alterTableCmd, false))
2930
}
3031
}
3132

3233
return ops, nil
3334
}
3435

35-
func convertAlterTableSetNotNull(stmt *pgq.AlterTableStmt, cmd *pgq.AlterTableCmd) migrations.Operation {
36+
func convertAlterTableSetNotNull(stmt *pgq.AlterTableStmt, cmd *pgq.AlterTableCmd, notNull bool) migrations.Operation {
3637
return &migrations.OpAlterColumn{
3738
Table: stmt.GetRelation().GetRelname(),
3839
Column: cmd.GetName(),
39-
Nullable: ptr(false),
40+
Nullable: ptr(!notNull),
4041
Up: PlaceHolderSQL,
4142
Down: PlaceHolderSQL,
4243
}

pkg/sql2pgroll/alter_table_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ func TestConvertAlterTableStatements(t *testing.T) {
2323
sql: "ALTER TABLE foo ALTER COLUMN a SET NOT NULL",
2424
expectedOp: expect.AlterTableOp1,
2525
},
26+
{
27+
sql: "ALTER TABLE foo ALTER COLUMN a DROP NOT NULL",
28+
expectedOp: expect.AlterTableOp2,
29+
},
2630
}
2731

2832
for _, tc := range tests {

pkg/sql2pgroll/expect/alter_table.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ var AlterTableOp1 = &migrations.OpAlterColumn{
1515
Down: sql2pgroll.PlaceHolderSQL,
1616
}
1717

18+
var AlterTableOp2 = &migrations.OpAlterColumn{
19+
Table: "foo",
20+
Column: "a",
21+
Nullable: ptr(true),
22+
Up: sql2pgroll.PlaceHolderSQL,
23+
Down: sql2pgroll.PlaceHolderSQL,
24+
}
25+
1826
func ptr[T any](v T) *T {
1927
return &v
2028
}

0 commit comments

Comments
 (0)