From 6dd898a98f28d716b06668a4446cb61873432d08 Mon Sep 17 00:00:00 2001 From: Andrew Farries Date: Thu, 19 Dec 2024 13:19:48 +0000 Subject: [PATCH] Convert column `DEFAULT`s in `CREATE TABLE` statements (#553) Convert inline `DEFAULT` values in `CREATE TABLE` statements like this: ```sql CREATE TABLE foo(a text DEFAULT 'foo') ``` into `OpCreateTable` operations like this: ```json [ { "create_table": { "columns": [ { "default": "'foo'", "name": "a", "nullable": true, "type": "text" } ], "name": "foo" } } ] ``` --- pkg/sql2pgroll/create_table.go | 8 ++++++++ pkg/sql2pgroll/create_table_test.go | 4 ++++ pkg/sql2pgroll/expect/create_table.go | 12 ++++++++++++ 3 files changed, 24 insertions(+) diff --git a/pkg/sql2pgroll/create_table.go b/pkg/sql2pgroll/create_table.go index 76f20c9a..8daf6d25 100644 --- a/pkg/sql2pgroll/create_table.go +++ b/pkg/sql2pgroll/create_table.go @@ -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: @@ -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 @@ -136,6 +143,7 @@ func convertColumnDef(tableName string, col *pgq.ColumnDef) (*migrations.Column, Nullable: !notNull, Pk: pk, Check: check, + Default: defaultValue, Unique: unique, }, nil } diff --git a/pkg/sql2pgroll/create_table_test.go b/pkg/sql2pgroll/create_table_test.go index c7fea50b..e5c9ef9f 100644 --- a/pkg/sql2pgroll/create_table_test.go +++ b/pkg/sql2pgroll/create_table_test.go @@ -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, diff --git a/pkg/sql2pgroll/expect/create_table.go b/pkg/sql2pgroll/expect/create_table.go index a578642b..a7e72fe1 100644 --- a/pkg/sql2pgroll/expect/create_table.go +++ b/pkg/sql2pgroll/expect/create_table.go @@ -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()"), + }, + }, +}