Skip to content

Commit

Permalink
Convert column DEFAULTs in CREATE TABLE statements (#553)
Browse files Browse the repository at this point in the history
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"
    }
  }
]
```
  • Loading branch information
andrew-farries authored Dec 19, 2024
1 parent 5450d7a commit 6dd898a
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
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()"),
},
},
}

0 comments on commit 6dd898a

Please sign in to comment.