From 34b623f09cea66d3cc22c9a644f2210155e59e3e Mon Sep 17 00:00:00 2001 From: Andrew Farries Date: Thu, 5 Dec 2024 11:16:00 +0000 Subject: [PATCH] Convert `RENAME CONSTRAINT` SQL to `pgroll` operation (#514) Convert SQL statements like: ```sql ALTER TABLE foo RENAME CONSTRAINT bar TO baz ``` to an `OpRenameConstraint` operation: ```json [ { "rename_constraint": { "table": "foo", "from": "bar", "to": "baz" } } ] ``` Part of #504 --- pkg/sql2pgroll/expect/rename_constraint.go | 11 +++++++++++ pkg/sql2pgroll/rename.go | 17 +++++++++++++++++ pkg/sql2pgroll/rename_test.go | 4 ++++ 3 files changed, 32 insertions(+) create mode 100644 pkg/sql2pgroll/expect/rename_constraint.go diff --git a/pkg/sql2pgroll/expect/rename_constraint.go b/pkg/sql2pgroll/expect/rename_constraint.go new file mode 100644 index 00000000..fd511016 --- /dev/null +++ b/pkg/sql2pgroll/expect/rename_constraint.go @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: Apache-2.0 + +package expect + +import "github.com/xataio/pgroll/pkg/migrations" + +var RenameConstraintOp1 = &migrations.OpRenameConstraint{ + Table: "foo", + From: "bar", + To: "baz", +} diff --git a/pkg/sql2pgroll/rename.go b/pkg/sql2pgroll/rename.go index cd78a67f..2b47c792 100644 --- a/pkg/sql2pgroll/rename.go +++ b/pkg/sql2pgroll/rename.go @@ -14,6 +14,8 @@ func convertRenameStmt(stmt *pgq.RenameStmt) (migrations.Operations, error) { return convertRenameTable(stmt) case pgq.ObjectType_OBJECT_COLUMN: return convertRenameColumn(stmt) + case pgq.ObjectType_OBJECT_TABCONSTRAINT: + return convertRenameConstraint(stmt) default: return nil, nil } @@ -48,3 +50,18 @@ func convertRenameTable(stmt *pgq.RenameStmt) (migrations.Operations, error) { }, }, nil } + +// convertRenameConstraint converts SQL statements like: +// +// `ALTER TABLE foo RENAME CONSTRAINT a TO b` +// +// to an OpRenameConstraint operation. +func convertRenameConstraint(stmt *pgq.RenameStmt) (migrations.Operations, error) { + return migrations.Operations{ + &migrations.OpRenameConstraint{ + Table: stmt.GetRelation().GetRelname(), + From: stmt.GetSubname(), + To: stmt.GetNewname(), + }, + }, nil +} diff --git a/pkg/sql2pgroll/rename_test.go b/pkg/sql2pgroll/rename_test.go index b1d67420..e3888922 100644 --- a/pkg/sql2pgroll/rename_test.go +++ b/pkg/sql2pgroll/rename_test.go @@ -31,6 +31,10 @@ func TestConvertRenameStatements(t *testing.T) { sql: "ALTER TABLE foo RENAME TO bar", expectedOp: expect.RenameTableOp1, }, + { + sql: "ALTER TABLE foo RENAME CONSTRAINT bar TO baz", + expectedOp: expect.RenameConstraintOp1, + }, } for _, tc := range tests {