Skip to content

Commit

Permalink
Convert DROP NOT NULL SQL to pgroll operation (#505)
Browse files Browse the repository at this point in the history
Update the `sql2pgroll` package to 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"
    }
  }
]
```
  • Loading branch information
andrew-farries authored Dec 3, 2024
1 parent f85bca4 commit 84661eb
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
9 changes: 5 additions & 4 deletions pkg/sql2pgroll/alter_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,22 @@ func convertAlterTableStmt(stmt *pgq.AlterTableStmt) (migrations.Operations, err
continue
}

//nolint:gocritic
switch alterTableCmd.Subtype {
case pgq.AlterTableType_AT_SetNotNull:
ops = append(ops, convertAlterTableSetNotNull(stmt, alterTableCmd))
ops = append(ops, convertAlterTableSetNotNull(stmt, alterTableCmd, true))
case pgq.AlterTableType_AT_DropNotNull:
ops = append(ops, convertAlterTableSetNotNull(stmt, alterTableCmd, false))
}
}

return ops, nil
}

func convertAlterTableSetNotNull(stmt *pgq.AlterTableStmt, cmd *pgq.AlterTableCmd) migrations.Operation {
func convertAlterTableSetNotNull(stmt *pgq.AlterTableStmt, cmd *pgq.AlterTableCmd, notNull bool) migrations.Operation {
return &migrations.OpAlterColumn{
Table: stmt.GetRelation().GetRelname(),
Column: cmd.GetName(),
Nullable: ptr(false),
Nullable: ptr(!notNull),
Up: PlaceHolderSQL,
Down: PlaceHolderSQL,
}
Expand Down
4 changes: 4 additions & 0 deletions pkg/sql2pgroll/alter_table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ func TestConvertAlterTableStatements(t *testing.T) {
sql: "ALTER TABLE foo ALTER COLUMN a SET NOT NULL",
expectedOp: expect.AlterTableOp1,
},
{
sql: "ALTER TABLE foo ALTER COLUMN a DROP NOT NULL",
expectedOp: expect.AlterTableOp2,
},
}

for _, tc := range tests {
Expand Down
8 changes: 8 additions & 0 deletions pkg/sql2pgroll/expect/alter_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ var AlterTableOp1 = &migrations.OpAlterColumn{
Down: sql2pgroll.PlaceHolderSQL,
}

var AlterTableOp2 = &migrations.OpAlterColumn{
Table: "foo",
Column: "a",
Nullable: ptr(true),
Up: sql2pgroll.PlaceHolderSQL,
Down: sql2pgroll.PlaceHolderSQL,
}

func ptr[T any](v T) *T {
return &v
}

0 comments on commit 84661eb

Please sign in to comment.