diff --git a/pkg/sql2pgroll/expect/rename_table.go b/pkg/sql2pgroll/expect/rename_table.go new file mode 100644 index 00000000..3f5060bc --- /dev/null +++ b/pkg/sql2pgroll/expect/rename_table.go @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: Apache-2.0 + +package expect + +import "github.com/xataio/pgroll/pkg/migrations" + +var RenameTableOp1 = &migrations.OpRenameTable{ + From: "foo", + To: "bar", +} diff --git a/pkg/sql2pgroll/rename.go b/pkg/sql2pgroll/rename.go index a9f58340..cd78a67f 100644 --- a/pkg/sql2pgroll/rename.go +++ b/pkg/sql2pgroll/rename.go @@ -7,14 +7,25 @@ import ( "github.com/xataio/pgroll/pkg/migrations" ) +// convertRenameStmt converts RenameStmt nodes to pgroll operations. func convertRenameStmt(stmt *pgq.RenameStmt) (migrations.Operations, error) { - if stmt.GetRelationType() != pgq.ObjectType_OBJECT_TABLE { - return nil, nil - } - if stmt.GetRenameType() != pgq.ObjectType_OBJECT_COLUMN { + switch stmt.GetRenameType() { + case pgq.ObjectType_OBJECT_TABLE: + return convertRenameTable(stmt) + case pgq.ObjectType_OBJECT_COLUMN: + return convertRenameColumn(stmt) + default: return nil, nil } +} +// convertRenameColumn converts SQL statements like: +// +// `ALTER TABLE foo RENAME COLUMN a TO b` +// `ALTER TABLE foo RENAME a TO b` +// +// to an OpAlterColumn operation. +func convertRenameColumn(stmt *pgq.RenameStmt) (migrations.Operations, error) { return migrations.Operations{ &migrations.OpAlterColumn{ Table: stmt.GetRelation().GetRelname(), @@ -23,3 +34,17 @@ func convertRenameStmt(stmt *pgq.RenameStmt) (migrations.Operations, error) { }, }, nil } + +// convertRenameTable converts SQL statements like: +// +// `ALTER TABLE foo RENAME TO bar` +// +// to an OpRenameTable operation. +func convertRenameTable(stmt *pgq.RenameStmt) (migrations.Operations, error) { + return migrations.Operations{ + &migrations.OpRenameTable{ + From: stmt.GetRelation().GetRelname(), + To: stmt.GetNewname(), + }, + }, nil +} diff --git a/pkg/sql2pgroll/rename_test.go b/pkg/sql2pgroll/rename_test.go index 3295fa4a..b1d67420 100644 --- a/pkg/sql2pgroll/rename_test.go +++ b/pkg/sql2pgroll/rename_test.go @@ -12,7 +12,7 @@ import ( "github.com/xataio/pgroll/pkg/sql2pgroll/expect" ) -func TestConvertRenameColumnStatements(t *testing.T) { +func TestConvertRenameStatements(t *testing.T) { t.Parallel() tests := []struct { @@ -27,6 +27,10 @@ func TestConvertRenameColumnStatements(t *testing.T) { sql: "ALTER TABLE foo RENAME a TO b", expectedOp: expect.AlterColumnOp4, }, + { + sql: "ALTER TABLE foo RENAME TO bar", + expectedOp: expect.RenameTableOp1, + }, } for _, tc := range tests {