Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support sync unique constraint (#3341)
h3n4la0ed11a5841b
diff --git a/plugin/parser/ast/drop_constraint_stmt.go b/plugin/parser/ast/drop_constraint_stmt.goindex 19a9520c1e..9f798ba27d 100644--- a/plugin/parser/ast/drop_constraint_stmt.go+++ b/plugin/parser/ast/drop_constraint_stmt.go@@ -6,4 +6,5 @@ type DropConstraintStmt struct {Table *TableDefConstraintName string+ IfExists bool}diff --git a/plugin/parser/differ/pg/differ.go b/plugin/parser/differ/pg/differ.goindex 8376afea35..e7fc4d8905 100644--- a/plugin/parser/differ/pg/differ.go+++ b/plugin/parser/differ/pg/differ.go@@ -32,22 +32,25 @@ type diffNode struct {dropNodeList []ast.Node}+type constraintMap map[string]*constraintInfotype tableMap map[string]*tableInfotype schemaMap map[string]*schemaInfotype schemaInfo struct {- id int- existsInNew bool- createSchema *ast.CreateSchemaStmt- tableMap tableMap+ id int+ existsInNew bool+ createSchema *ast.CreateSchemaStmt+ tableMap tableMap+ constraintMap constraintMap}func newSchemaInfo(id int, createSchema *ast.CreateSchemaStmt) *schemaInfo {return &schemaInfo{- id: id,- existsInNew: false,- createSchema: createSchema,- tableMap: make(tableMap),+ id: id,+ existsInNew: false,+ createSchema: createSchema,+ tableMap: make(tableMap),+ constraintMap: make(constraintMap),}}@@ -65,6 +68,20 @@ func newTableInfo(id int, createTable *ast.CreateTableStmt) *tableInfo {}}+type constraintInfo struct {+ id int+ existsInNew bool+ addConstraint *ast.AddConstraintStmt+}++func newConstraintInfo(id int, addConstraint *ast.AddConstraintStmt) *constraintInfo {+ return &constraintInfo{+ id: id,+ existsInNew: false,+ addConstraint: addConstraint,+ }+}+func (m schemaMap) addTable(id int, table *ast.CreateTableStmt) error {schema, exists := m[table.Name.Schema]if !exists {@@ -82,6 +99,32 @@ func (m schemaMap) getTable(schemaName string, tableName string) *tableInfo {return schema.tableMap[tableName]}+func (m schemaMap) addConstraint(id int, addConstraint *ast.AddConstraintStmt) error {+ schema, exists := m[addConstraint.Table.Schema]+ if !exists {+ return errors.Errorf("failed to add constraint: schema %s not found", addConstraint.Table.Schema)+ }+ if _, exists = schema.tableMap[addConstraint.Table.Name]; !exists {+ if !exists {+ return errors.Errorf("failed to add constraint: table %s not found", addConstraint.Table.Name)+ }+ }+ constraintName := addConstraint.Constraint.Name+ if constraintName == "" {+ return errors.Errorf("failed to add constraint: constraint name is empty")+ }+ schema.constraintMap[constraintName] = newConstraintInfo(id, addConstraint)+ return nil+}++func (m schemaMap) getConstraint(schemaName string, constraintName string) *constraintInfo {+ schema, exists := m[schemaName]+ if !exists {+ return nil+ }+ return schema.constraintMap[constraintName]+}+// SchemaDiff computes the schema differences between old and new schema.func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {oldNodes, err := parser.Parse(parser.Postgres, parser.ParseContext{}, oldStmt)@@ -103,6 +146,22 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {if err := oldSchemaMap.addTable(i, stmt); err != nil {return "", err}+ case *ast.AlterTableStmt:+ for _, alterItem := range stmt.AlterItemList {+ switch item := alterItem.(type) {+ case *ast.AddConstraintStmt:+ switch item.Constraint.Type {+ case ast.ConstraintTypeUnique:+ if err := oldSchemaMap.addConstraint(i, item); err != nil {+ return "", err+ }+ default:+ return "", errors.Errorf("unsupported constraint type %d", item.Constraint.Type)+ }+ default:+ return "", errors.Errorf("unsupported alter table item type %T", item)+ }+ }}}@@ -128,6 +187,46 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {continue}schema.existsInNew = true+ case *ast.AlterTableStmt:+ alterTableStmt := &ast.AlterTableStmt{+ Table: stmt.Table,+ }+ for _, alterItem := range stmt.AlterItemList {+ switch item := alterItem.(type) {+ case *ast.AddConstraintStmt:+ switch item.Constraint.Type {+ case ast.ConstraintTypeUnique:+ oldConstraint := oldSchemaMap.getConstraint(item.Table.Schema, item.Constraint.Name)+ if oldConstraint == nil {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, item)+ continue+ }++ oldConstraint.existsInNew = true+ if oldConstraint.addConstraint.Table.Name != item.Table.Name {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropConstraintStmt{+ Table: alterTableStmt.Table,+ IfExists: true,+ })+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.AddConstraintStmt{+ Table: alterTableStmt.Table,+ Constraint: item.Constraint,+ })+ continue+ }+ if err := diff.modifyConstraint(alterTableStmt, oldConstraint.addConstraint.Constraint, item.Constraint); err != nil {+ return "", err+ }+ default:+ return "", errors.Errorf("unsupported constraint type %d", item.Constraint.Type)+ }+ default:+ return "", errors.Errorf("unsupported alter table item type %T", item)+ }+ }+ if len(alterTableStmt.AlterItemList) > 0 {+ diff.modifyTableList = append(diff.modifyTableList, alterTableStmt)+ }default:return "", errors.Errorf("unsupported statement %+v", stmt)}@@ -142,15 +241,22 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {}func (diff *diffNode) dropObject(oldSchemaMap schemaMap) error {- // Drop the renaming old schema.+ // Drop the remaining old schema.if dropSchemaStmt := dropSchema(oldSchemaMap); dropSchemaStmt != nil {diff.dropNodeList = append(diff.dropNodeList, dropSchemaStmt)}- // Drop the renaming old table.+ // Drop the remaining old table.if dropTableStmt := dropTable(oldSchemaMap); dropTableStmt != nil {diff.dropNodeList = append(diff.dropNodeList, dropTableStmt)}++ // Drop the remaining old constraints.+ dropConstraintStms := dropConstraint(oldSchemaMap)+ for _, dropConstraintStmt := range dropConstraintStms {+ diff.dropNodeList = append(diff.dropNodeList, dropConstraintStmt)+ }+return nil}@@ -257,6 +363,28 @@ func (*diffNode) modifyConstraint(alterTableStmt *ast.AlterTableStmt, oldConstra})return nil}+ case ast.ConstraintTypeUnique:+ // TODO(zp): To make the logic simple now, we just restore the statement, and drop and create the new one if+ // there is any difference.+ oldAlterTableAddConstraint, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, oldConstraint)+ if err != nil {+ return errors.Wrapf(err, "failed to deparse old alter table constraintDef: %v", oldConstraint)+ }+ newAlterTableAddConstraint, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, newConstraint)+ if err != nil {+ return errors.Wrapf(err, "failed to deparse new alter table constraintDef: %v", newConstraint)+ }+ if oldAlterTableAddConstraint != newAlterTableAddConstraint {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropConstraintStmt{+ Table: alterTableStmt.Table,+ ConstraintName: constraintName,+ IfExists: true,+ })+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.AddConstraintStmt{+ Table: alterTableStmt.Table,+ Constraint: newConstraint,+ })+ }default:return errors.Errorf("Unsupported table constraint type: %d for modifyConstraint", newConstraint.Type)}@@ -389,6 +517,39 @@ func (diff *diffNode) deparse() (string, error) {return buf.String(), nil}+func dropConstraint(m schemaMap) []*ast.AlterTableStmt {+ var dropConstraintList []*ast.AlterTableStmt+ for schemaName, schemaInfo := range m {+ constraintMap := make(map[string][]*constraintInfo)+ for _, constraintInfo := range schemaInfo.constraintMap {+ if !constraintInfo.existsInNew {+ constraintMap[constraintInfo.addConstraint.Table.Name] = append(constraintMap[constraintInfo.addConstraint.Table.Name], constraintInfo)+ }+ }+ for tableName, constraintList := range constraintMap {+ sort.Slice(constraintList, func(i, j int) bool {+ return constraintList[i].id < constraintList[j].id+ })+ var alterItemList []ast.Node+ for _, constraintInfo := range constraintList {+ alterItemList = append(alterItemList, &ast.DropConstraintStmt{+ Table: &ast.TableDef{Schema: schemaName, Name: tableName},+ ConstraintName: constraintInfo.addConstraint.Constraint.Name,+ IfExists: true,+ })+ }+ dropConstraintList = append(dropConstraintList, &ast.AlterTableStmt{+ Table: &ast.TableDef{+ Schema: schemaName,+ Name: tableName,+ },+ AlterItemList: alterItemList,+ })+ }+ }+ return dropConstraintList+}+func dropTable(m schemaMap) *ast.DropTableStmt {var tableList []*tableInfofor _, schema := range m {diff --git a/plugin/parser/differ/pg/differ_test.go b/plugin/parser/differ/pg/differ_test.goindex 9a701ff54a..8f8569da3f 100644--- a/plugin/parser/differ/pg/differ_test.go+++ b/plugin/parser/differ/pg/differ_test.go@@ -56,8 +56,10 @@ func runDifferTest(t *testing.T, file string, record bool) {func TestComputeDiff(t *testing.T) {testFileList := []string{"test_differ_data.yaml",- // Schema+ // // Schema"test_differ_schema.yaml",+ // Constraint+ "test_differ_constraint.yaml",}for _, test := range testFileList {runDifferTest(t, test, false /* record */)diff --git a/plugin/parser/differ/pg/test-data/test_differ_constraint.yaml b/plugin/parser/differ/pg/test-data/test_differ_constraint.yamlnew file mode 100644index 0000000000..ae1e05640e--- /dev/null+++ b/plugin/parser/differ/pg/test-data/test_differ_constraint.yaml@@ -0,0 +1,48 @@+- oldSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ newSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (order_id);+ diff: |+ ALTER TABLE "public"."order_details"+ ADD CONSTRAINT "order_details_un_order_id" UNIQUE ("order_id");+- oldSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (order_id);+ newSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ diff: |+ ALTER TABLE "public"."order_details"+ DROP CONSTRAINT IF EXISTS "order_details_un_order_id";+- oldSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (id, order_id);+ newSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (order_id);+ diff: |+ ALTER TABLE "public"."order_details"+ DROP CONSTRAINT IF EXISTS "order_details_un_order_id",+ ADD CONSTRAINT "order_details_un_order_id" UNIQUE ("order_id");+- oldSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (order_id);+ newSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (id, order_id);+ diff: |+ ALTER TABLE "public"."order_details"+ DROP CONSTRAINT IF EXISTS "order_details_un_order_id",+ ADD CONSTRAINT "order_details_un_order_id" UNIQUE ("id", "order_id");+- oldSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT, email_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (id, order_id, email_id);+ newSchema: |+ CREATE TABLE public.order_details(id INT, order_id INT);+ ALTER TABLE public.order_details ADD CONSTRAINT order_details_un_order_id UNIQUE (id, order_id);+ diff: |+ ALTER TABLE "public"."order_details"+ DROP COLUMN "email_id";+ ALTER TABLE "public"."order_details"+ DROP CONSTRAINT IF EXISTS "order_details_un_order_id",+ ADD CONSTRAINT "order_details_un_order_id" UNIQUE ("id", "order_id");diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.goindex 0cf1f9b0a7..a6b390c705 100644--- a/plugin/parser/engine/pg/convert.go+++ b/plugin/parser/engine/pg/convert.go@@ -82,6 +82,7 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, errdropConstraint := &ast.DropConstraintStmt{Table: alterTable.Table,ConstraintName: alterCmd.Name,+ IfExists: alterCmd.MissingOk,}alterTable.AlterItemList = append(alterTable.AlterItemList, dropConstraint)diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.goindex c3cf5d356a..5380c4b5a6 100644--- a/plugin/parser/engine/pg/convert_test.go+++ b/plugin/parser/engine/pg/convert_test.go@@ -885,6 +885,7 @@ func TestPGDropConstraintStmt(t *testing.T) {Name: "tech_book",},ConstraintName: "uk_tech_a",+ IfExists: false,},},},@@ -896,6 +897,33 @@ func TestPGDropConstraintStmt(t *testing.T) {},},},+ {+ stmt: "ALTER TABLE tech_book DROP CONSTRAINT IF EXISTS uk_tech_a",+ want: []ast.Node{+ &ast.AlterTableStmt{+ Table: &ast.TableDef{+ Type: ast.TableTypeBaseTable,+ Name: "tech_book",+ },+ AlterItemList: []ast.Node{+ &ast.DropConstraintStmt{+ Table: &ast.TableDef{+ Type: ast.TableTypeBaseTable,+ Name: "tech_book",+ },+ ConstraintName: "uk_tech_a",+ IfExists: true,+ },+ },+ },+ },+ statementList: []parser.SingleSQL{+ {+ Text: "ALTER TABLE tech_book DROP CONSTRAINT IF EXISTS uk_tech_a",+ LastLine: 1,+ },+ },+ },}runTests(t, tests)diff --git a/plugin/parser/engine/pg/deparse.go b/plugin/parser/engine/pg/deparse.goindex 0c89a7ce78..22e44ac661 100644--- a/plugin/parser/engine/pg/deparse.go+++ b/plugin/parser/engine/pg/deparse.go@@ -44,6 +44,8 @@ func deparse(context parser.DeparseContext, in ast.Node, buf *strings.Builder) ereturn err}return buf.WriteByte(';')+ case *ast.ConstraintDef:+ return deparseConstraintDef(context, node, buf)case *ast.CreateIndexStmt:if err := deparseCreateIndex(context, node, buf); err != nil {return err@@ -320,20 +322,24 @@ func deparseAddConstraint(context parser.DeparseContext, in *ast.AddConstraintStreturn err}}- switch in.Constraint.Type {+ return deparseConstraintDef(context, in.Constraint, buf)+}++func deparseConstraintDef(_ parser.DeparseContext, in *ast.ConstraintDef, buf *strings.Builder) error {+ switch in.Type {case ast.ConstraintTypeUniqueUsingIndex:if _, err := buf.WriteString("UNIQUE USING INDEX "); err != nil {return err}- if err := writeSurrounding(buf, in.Constraint.IndexName, `"`); err != nil {+ if err := writeSurrounding(buf, in.IndexName, `"`); err != nil {return err}- if in.Constraint.Initdeferred {+ if in.Initdeferred {if _, err := buf.WriteString(" INITIALLY DEFERRED"); err != nil {return err}- } else if in.Constraint.Deferrable {+ } else if in.Deferrable {if _, err := buf.WriteString(" DEFERRABLE"); err != nil {return err}@@ -342,7 +348,7 @@ func deparseAddConstraint(context parser.DeparseContext, in *ast.AddConstraintStif _, err := buf.WriteString("UNIQUE ("); err != nil {return err}- for idx, col := range in.Constraint.KeyList {+ for idx, col := range in.KeyList {if idx >= 1 {if _, err := buf.WriteString(", "); err != nil {return err@@ -352,11 +358,11 @@ func deparseAddConstraint(context parser.DeparseContext, in *ast.AddConstraintStreturn err}}- if len(in.Constraint.Including) > 0 {+ if len(in.Including) > 0 {if _, err := buf.WriteString(") INCLUDE ("); err != nil {return err}- for idx, col := range in.Constraint.Including {+ for idx, col := range in.Including {if idx >= 1 {if _, err := buf.WriteString(", "); err != nil {return err@@ -370,11 +376,11 @@ func deparseAddConstraint(context parser.DeparseContext, in *ast.AddConstraintStif _, err := buf.WriteString(")"); err != nil {return err}- if in.Constraint.IndexTableSpace != "" {+ if in.IndexTableSpace != "" {if _, err := buf.WriteString(" USING INDEX TABLESPACE "); err != nil {return err}- if err := writeSurrounding(buf, in.Constraint.IndexTableSpace, `"`); err != nil {+ if err := writeSurrounding(buf, in.IndexTableSpace, `"`); err != nil {return err}}@@ -382,7 +388,7 @@ func deparseAddConstraint(context parser.DeparseContext, in *ast.AddConstraintStif _, err := buf.WriteString("CHECK ("); err != nil {return err}- if _, err := buf.WriteString(in.Constraint.Expression.Text()); err != nil {+ if _, err := buf.WriteString(in.Expression.Text()); err != nil {return err}if _, err := buf.WriteString(")"); err != nil {@@ -399,6 +405,11 @@ func deparseDropConstraint(context parser.DeparseContext, in *ast.DropConstraintif _, err := buf.WriteString("DROP CONSTRAINT "); err != nil {return err}+ if in.IfExists {+ if _, err := buf.WriteString("IF EXISTS "); err != nil {+ return err+ }+ }return writeSurrounding(buf, in.ConstraintName, `"`)}diff --git a/plugin/parser/engine/pg/test-data/test_alter_table_data.yaml b/plugin/parser/engine/pg/test-data/test_alter_table_data.yamlindex 73f28e5911..9dc471a135 100644--- a/plugin/parser/engine/pg/test-data/test_alter_table_data.yaml+++ b/plugin/parser/engine/pg/test-data/test_alter_table_data.yaml@@ -54,6 +54,12 @@want: |-ALTER TABLE "t"DROP CONSTRAINT "unique_tbl_email_key";+- stmt: |-+ alter table t+ drop constraint if exists unique_tbl_email_key;+ want: |-+ ALTER TABLE "t"+ DROP CONSTRAINT IF EXISTS "unique_tbl_email_key";- stmt: |-alter table tadd constraint email_unique_key unique(email);