Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert column DEFAULTs in CREATE TABLE statements #553

Merged
merged 1 commit into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pkg/sql2pgroll/create_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func convertColumnDef(tableName string, col *pgq.ColumnDef) (*migrations.Column,
// Convert column constraints
var notNull, pk, unique bool
var check *migrations.CheckConstraint
var defaultValue *string
for _, c := range col.GetConstraints() {
switch c.GetConstraint().GetContype() {
case pgq.ConstrType_CONSTR_NULL:
Expand All @@ -123,6 +124,12 @@ func convertColumnDef(tableName string, col *pgq.ColumnDef) (*migrations.Column,
if check == nil {
return nil, nil
}
case pgq.ConstrType_CONSTR_DEFAULT:
d, err := pgq.DeparseExpr(c.GetConstraint().GetRawExpr())
if err != nil {
return nil, fmt.Errorf("error deparsing default value: %w", err)
}
defaultValue = &d
case pgq.ConstrType_CONSTR_FOREIGN:
if !canConvertForeignKeyConstraint(c.GetConstraint()) {
return nil, nil
Expand All @@ -136,6 +143,7 @@ func convertColumnDef(tableName string, col *pgq.ColumnDef) (*migrations.Column,
Nullable: !notNull,
Pk: pk,
Check: check,
Default: defaultValue,
Unique: unique,
}, 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 @@ -44,6 +44,10 @@ func TestConvertCreateTableStatements(t *testing.T) {
sql: "CREATE TABLE foo(a int CHECK (a > 0))",
expectedOp: expect.CreateTableOp10,
},
{
sql: "CREATE TABLE foo(a timestamptz DEFAULT now())",
expectedOp: expect.CreateTableOp11,
},
{
sql: "CREATE TABLE foo(a varchar(255))",
expectedOp: expect.CreateTableOp3,
Expand Down
12 changes: 12 additions & 0 deletions pkg/sql2pgroll/expect/create_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,15 @@ var CreateTableOp10 = &migrations.OpCreateTable{
},
},
}

var CreateTableOp11 = &migrations.OpCreateTable{
Name: "foo",
Columns: []migrations.Column{
{
Name: "a",
Type: "timestamptz",
Nullable: true,
Default: ptr("now()"),
},
},
}