Skip to content

Commit

Permalink
Make ALTER TABLE foo ALTER COLUMN a SET DATA TYPE text options unre…
Browse files Browse the repository at this point in the history
…presentable (#508)

Ensure that SQL statements of the form:

```sql
ALTER TABLE foo ALTER COLUMN a SET DATA TYPE text COLLATE "en_US"
ALTER TABLE foo ALTER COLUMN a SET DATA TYPE text USING 'foo'
```

are converted to raw SQL operations instead of an `OpAlterColumn`
operation. The change of collation is not currently representable by an
`OpAlterColumn` operation and neither is the `USING` clause.

Part of #504
  • Loading branch information
andrew-farries authored Dec 4, 2024
1 parent 06bfebd commit 5b7980d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkg/sql2pgroll/alter_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ func convertAlterTableAlterColumnType(stmt *pgq.AlterTableStmt, cmd *pgq.AlterTa
return nil, fmt.Errorf("expected column definition, got %T", cmd.GetDef().Node)
}

if !canConvertColumnForSetDataType(node.ColumnDef) {
return nil, nil
}

return &migrations.OpAlterColumn{
Table: stmt.GetRelation().GetRelname(),
Column: cmd.GetName(),
Expand Down Expand Up @@ -170,6 +174,19 @@ func canConvertUniqueConstraint(constraint *pgq.Constraint) bool {
return true
}

// canConvertColumnForSetDataType checks if `column` can be faithfully
// converted as part of an OpAlterColumn operation to set a new type for the
// column.
func canConvertColumnForSetDataType(column *pgq.ColumnDef) bool {
if column.GetCollClause() != nil {
return false
}
if column.GetRawDefault() != nil {
return false
}
return true
}

func ptr[T any](x T) *T {
return &x
}
5 changes: 5 additions & 0 deletions pkg/sql2pgroll/alter_table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ func TestUnconvertableAlterTableAddConstraintStatements(t *testing.T) {
"ALTER TABLE foo ADD CONSTRAINT bar UNIQUE (a) INCLUDE (b)",
"ALTER TABLE foo ADD CONSTRAINT bar UNIQUE (a) WITH (fillfactor=70)",
"ALTER TABLE foo ADD CONSTRAINT bar UNIQUE (a) USING INDEX TABLESPACE baz",

// COLLATE and USING clauses are not representable by `OpAlterColumn`
// operations when changing data type.
`ALTER TABLE foo ALTER COLUMN a SET DATA TYPE text COLLATE "en_US"`,
"ALTER TABLE foo ALTER COLUMN a SET DATA TYPE text USING 'foo'",
}

for _, sql := range tests {
Expand Down

0 comments on commit 5b7980d

Please sign in to comment.