Skip to content

Commit

Permalink
Convert inline CHECK constraints
Browse files Browse the repository at this point in the history
Convert SQL `CREATE TABLE` statements with inline `CHECK` constraints
like this:

```
CREATE TABLE foo(a int CHECK (a > 0))
```

to `OpCreateTable` operations.
  • Loading branch information
andrew-farries committed Dec 19, 2024
1 parent 3d0b93f commit 58cd329
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
23 changes: 22 additions & 1 deletion pkg/sql2pgroll/create_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func convertColumnDef(col *pgq.ColumnDef) (*migrations.Column, error) {

// Convert column constraints
var notNull, pk, unique bool
var check *migrations.CheckConstraint
for _, c := range col.GetConstraints() {
switch c.GetConstraint().GetContype() {
case pgq.ConstrType_CONSTR_NULL:
Expand All @@ -115,7 +116,11 @@ func convertColumnDef(col *pgq.ColumnDef) (*migrations.Column, error) {
pk = true
notNull = true
case pgq.ConstrType_CONSTR_CHECK:
if !canConvertCheckConstraint(c.GetConstraint()) {
check, err = convertInlineCheckConstraint(c.GetConstraint())
if err != nil {
return nil, fmt.Errorf("error converting inline check constraint: %w", err)
}
if check == nil {
return nil, nil
}
case pgq.ConstrType_CONSTR_FOREIGN:
Expand All @@ -130,6 +135,7 @@ func convertColumnDef(col *pgq.ColumnDef) (*migrations.Column, error) {
Type: typeString,
Nullable: !notNull,
Pk: pk,
Check: check,
Unique: unique,
}, nil
}
Expand Down Expand Up @@ -164,3 +170,18 @@ func canConvertPrimaryKeyConstraint(constraint *pgq.Constraint) bool {
return true
}
}

func convertInlineCheckConstraint(constraint *pgq.Constraint) (*migrations.CheckConstraint, error) {
if !canConvertCheckConstraint(constraint) {
return nil, nil
}

expr, err := pgq.DeparseExpr(constraint.GetRawExpr())
if err != nil {
return nil, fmt.Errorf("failed to deparse CHECK expression: %w", err)
}

return &migrations.CheckConstraint{
Constraint: expr,
}, nil
}
4 changes: 4 additions & 0 deletions pkg/sql2pgroll/create_table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ func TestConvertCreateTableStatements(t *testing.T) {
sql: "CREATE TABLE foo(a text[5][3])",
expectedOp: expect.CreateTableOp9,
},
{
sql: "CREATE TABLE foo(a int CHECK (a > 0))",
expectedOp: expect.CreateTableOp10,
},
}

for _, tc := range tests {
Expand Down
14 changes: 14 additions & 0 deletions pkg/sql2pgroll/expect/create_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,17 @@ var CreateTableOp9 = &migrations.OpCreateTable{
},
},
}

var CreateTableOp10 = &migrations.OpCreateTable{
Name: "foo",
Columns: []migrations.Column{
{
Name: "a",
Type: "int",
Nullable: true,
Check: &migrations.CheckConstraint{
Constraint: "a > 0",
},
},
},
}

0 comments on commit 58cd329

Please sign in to comment.