Skip to content

Commit

Permalink
Change CREATE TABLE default constraint handling
Browse files Browse the repository at this point in the history
When a column has a default value of `NULL`, the `default` field in the
resulting `Column` object should be omitted, rather than set to
`"NULL"`.

This makes conversion of `CREATE TABLE` statements consistent with
conversion of `ALTER TABLE ADD COLUMN` statements.
  • Loading branch information
andrew-farries committed Dec 20, 2024
1 parent 5b04017 commit bd13dde
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
7 changes: 5 additions & 2 deletions pkg/sql2pgroll/create_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,14 @@ func convertColumnDef(tableName string, col *pgq.ColumnDef) (*migrations.Column,
if isConstraintNamed(c.GetConstraint()) {
return nil, nil
}
d, err := pgq.DeparseExpr(c.GetConstraint().GetRawExpr())
d, err := extractDefault(c.GetConstraint().GetRawExpr())
if err != nil {
return nil, fmt.Errorf("error deparsing default value: %w", err)
}
defaultValue = &d
if !d.IsNull() {
v := d.MustGet()
defaultValue = &v
}
case pgq.ConstrType_CONSTR_FOREIGN:
foreignKey, err = convertInlineForeignKeyConstraint(tableName, col.GetColname(), c.GetConstraint())
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions pkg/sql2pgroll/create_table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ func TestConvertCreateTableStatements(t *testing.T) {
sql: "CREATE TABLE foo(a timestamptz DEFAULT now())",
expectedOp: expect.CreateTableOp11,
},
{
sql: "CREATE TABLE foo(a int DEFAULT NULL)",
expectedOp: expect.CreateTableOp20,
},
{
sql: "CREATE TABLE foo(a int CONSTRAINT my_fk REFERENCES bar(b))",
expectedOp: expect.CreateTableOp19,
Expand Down
11 changes: 11 additions & 0 deletions pkg/sql2pgroll/expect/create_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,14 @@ var CreateTableOp19 = &migrations.OpCreateTable{
},
},
}

var CreateTableOp20 = &migrations.OpCreateTable{
Name: "foo",
Columns: []migrations.Column{
{
Name: "a",
Type: "timestamptz",
Nullable: true,
},
},
}

0 comments on commit bd13dde

Please sign in to comment.