Skip to content

Commit 1038bc2

Browse files
Change CREATE TABLE DEFAULT constraint handling (#561)
Change how `CREATE TABLE` statements like: ```sql CREATE TABLE foo(a int DEFAULT NULL) ``` are converted to `OpCreateTable` operations. 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.
1 parent 9fedb2c commit 1038bc2

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

pkg/sql2pgroll/create_table.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,14 @@ func convertColumnDef(tableName string, col *pgq.ColumnDef) (*migrations.Column,
137137
if isConstraintNamed(c.GetConstraint()) {
138138
return nil, nil
139139
}
140-
d, err := pgq.DeparseExpr(c.GetConstraint().GetRawExpr())
140+
d, err := extractDefault(c.GetConstraint().GetRawExpr())
141141
if err != nil {
142142
return nil, fmt.Errorf("error deparsing default value: %w", err)
143143
}
144-
defaultValue = &d
144+
if !d.IsNull() {
145+
v := d.MustGet()
146+
defaultValue = &v
147+
}
145148
case pgq.ConstrType_CONSTR_FOREIGN:
146149
foreignKey, err = convertInlineForeignKeyConstraint(tableName, col.GetColname(), c.GetConstraint())
147150
if err != nil {

pkg/sql2pgroll/create_table_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ func TestConvertCreateTableStatements(t *testing.T) {
7272
sql: "CREATE TABLE foo(a timestamptz DEFAULT now())",
7373
expectedOp: expect.CreateTableOp11,
7474
},
75+
{
76+
sql: "CREATE TABLE foo(a int DEFAULT NULL)",
77+
expectedOp: expect.CreateTableOp20,
78+
},
7579
{
7680
sql: "CREATE TABLE foo(a int CONSTRAINT my_fk REFERENCES bar(b))",
7781
expectedOp: expect.CreateTableOp19,

pkg/sql2pgroll/expect/create_table.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,3 +257,14 @@ var CreateTableOp19 = &migrations.OpCreateTable{
257257
},
258258
},
259259
}
260+
261+
var CreateTableOp20 = &migrations.OpCreateTable{
262+
Name: "foo",
263+
Columns: []migrations.Column{
264+
{
265+
Name: "a",
266+
Type: "int",
267+
Nullable: true,
268+
},
269+
},
270+
}

0 commit comments

Comments
 (0)