Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(parser): support to deparse table foreign constraints (#3382)

rebeliceb24eab1dd030
diff --git a/plugin/parser/ast/foreign_def.go b/plugin/parser/ast/foreign_def.go
index 334f635e1e..39d40e7033 100644
--- a/plugin/parser/ast/foreign_def.go
+++ b/plugin/parser/ast/foreign_def.go
@@ -1,9 +1,24 @@
package ast
+// ForeignMatchType is the match type for referencing columns and referenced columns.
+type ForeignMatchType int
+
+const (
+ // ForeignMatchTypeSimple is the match type which allows any of the foreign key columns to be null.
+ ForeignMatchTypeSimple ForeignMatchType = iota
+ // ForeignMatchTypeFull is the match type which doesn't allow one column of a multi-column foreign key to be null unless all foreign key columns are null.
+ ForeignMatchTypeFull
+ // ForeignMatchTypePartial is not yet implemented.
+ ForeignMatchTypePartial
+)
+
// ForeignDef is struct for foreign key reference.
type ForeignDef struct {
node
Table *TableDef
ColumnList []string
+ MatchType ForeignMatchType
+ OnDelete *ReferentialActionDef
+ OnUpdate *ReferentialActionDef
}
diff --git a/plugin/parser/ast/referential_action_def.go b/plugin/parser/ast/referential_action_def.go
new file mode 100644
index 0000000000..e3b8afe0cc
--- /dev/null
+++ b/plugin/parser/ast/referential_action_def.go
@@ -0,0 +1,33 @@
+package ast
+
+// ReferentialActionType is the type for referential action.
+type ReferentialActionType int
+
+const (
+ // ReferentialActionTypeNoAction is the referential action type which will produce an error indicating that the deletion or update would create a foreign key constraint violation.
+ // If the constraint is deferred, this error will be produced at constraint check time if there still exist any referencing rows. This is the default action.
+ ReferentialActionTypeNoAction ReferentialActionType = iota
+ // ReferentialActionTypeRestrict is the referential action type which will produce an error indicating that the deletion or update would create a foreign key constraint violation.
+ // This is the same as NO ACTION except that the check is not deferrable.
+ ReferentialActionTypeRestrict
+ // ReferentialActionTypeCascade is the referential action type which will delete any rows referencing the deleted row, or update the values of the referencing column(s) to the new values of the referenced columns, respectively.
+ ReferentialActionTypeCascade
+ // ReferentialActionTypeSetNull is the referential action type which will set all of the referencing columns, or a specified subset of the referencing columns(pg 15), to null. A subset of columns can only be specified for ON DELETE actions.
+ ReferentialActionTypeSetNull
+ // ReferentialActionTypeSetDefault is the referential action type which will set all of the referencing columns, or a specified subset of the referencing columns(pg 15), to their default values.
+ // A subset of columns can only be specified for ON DELETE actions.
+ // There must be a row in the referenced table matching the default values, if they are not null, or the operation will fail.
+ ReferentialActionTypeSetDefault
+)
+
+// ReferentialActionDef is the struct for referential actions.
+// See https://www.postgresql.org/docs/current/sql-createtable.html for more details.
+//
+// In the PostgreSQL 15, users can specify the subset of the referencing columns to set null or default.
+// This parser only support PostgreSQL 13 currently. But we also define the ReferentialAction as a struct instead of an int.
+// It's for supporting PostgreSQL 15 in the future.
+type ReferentialActionDef struct {
+ node
+
+ Type ReferentialActionType
+}
diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.go
index b94eef3418..411dc186a8 100644
--- a/plugin/parser/engine/pg/convert.go
+++ b/plugin/parser/engine/pg/convert.go
@@ -922,6 +922,17 @@ func convertConstraint(in *pgquery.Node_Constraint) (*ast.ConstraintDef, error)
Table: convertRangeVarToTableName(in.Constraint.Pktable, ast.TableTypeBaseTable),
}
+ var err error
+ if cons.Foreign.MatchType, err = convertForeignMatchType(in.Constraint.FkMatchtype); err != nil {
+ return nil, err
+ }
+ if cons.Foreign.OnUpdate, err = convertReferentialAction(in.Constraint.FkUpdAction); err != nil {
+ return nil, err
+ }
+ if cons.Foreign.OnDelete, err = convertReferentialAction(in.Constraint.FkDelAction); err != nil {
+ return nil, err
+ }
+
for _, item := range in.Constraint.PkAttrs {
name, ok := item.Node.(*pgquery.Node_String_)
if !ok {
@@ -955,6 +966,36 @@ func convertConstraint(in *pgquery.Node_Constraint) (*ast.ConstraintDef, error)
return cons, nil
}
+func convertForeignMatchType(tp string) (ast.ForeignMatchType, error) {
+ switch tp {
+ case "s":
+ return ast.ForeignMatchTypeSimple, nil
+ case "f":
+ return ast.ForeignMatchTypeFull, nil
+ case "p":
+ return ast.ForeignMatchTypePartial, nil
+ default:
+ return ast.ForeignMatchTypeSimple, parser.NewConvertErrorf("unsupported foreign match type: %s", tp)
+ }
+}
+
+func convertReferentialAction(action string) (*ast.ReferentialActionDef, error) {
+ switch action {
+ case "a":
+ return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction}, nil
+ case "r":
+ return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeRestrict}, nil
+ case "c":
+ return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeCascade}, nil
+ case "n":
+ return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetNull}, nil
+ case "d":
+ return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetDefault}, nil
+ default:
+ return nil, parser.NewConvertErrorf("unsupported referential action: %s", action)
+ }
+}
+
func convertConstraintType(in pgquery.ConstrType, usingIndex bool) ast.ConstraintType {
switch in {
case pgquery.ConstrType_CONSTR_PRIMARY:
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index c83d40ded7..033fe214d8 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -441,6 +441,9 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
Name: "people",
},
ColumnList: []string{"id"},
+ MatchType: ast.ForeignMatchTypeSimple,
+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
},
},
},
@@ -457,6 +460,9 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
Name: "people",
},
ColumnList: []string{"b"},
+ MatchType: ast.ForeignMatchTypeSimple,
+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
},
},
},
@@ -982,6 +988,126 @@ func expressionWithText(expression ast.ExpressionNode, text string) ast.Expressi
func TestPGAddConstraintStmt(t *testing.T) {
tests := []testData{
+ {
+ stmt: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION",
+ want: []ast.Node{
+ &ast.AlterTableStmt{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "tech_book",
+ },
+ AlterItemList: []ast.Node{
+ &ast.AddConstraintStmt{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "tech_book",
+ },
+ Constraint: &ast.ConstraintDef{
+ Type: ast.ConstraintTypeForeign,
+ Name: "fk_tech_book_id",
+ KeyList: []string{"id"},
+ Foreign: &ast.ForeignDef{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "people",
+ },
+ ColumnList: []string{"id"},
+ MatchType: ast.ForeignMatchTypeSimple,
+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
+ },
+ },
+ },
+ },
+ },
+ },
+ statementList: []parser.SingleSQL{
+ {
+ Text: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION",
+ LastLine: 1,
+ },
+ },
+ },
+ {
+ stmt: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH FULL ON UPDATE CASCADE ON DELETE SET DEFAULT",
+ want: []ast.Node{
+ &ast.AlterTableStmt{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "tech_book",
+ },
+ AlterItemList: []ast.Node{
+ &ast.AddConstraintStmt{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "tech_book",
+ },
+ Constraint: &ast.ConstraintDef{
+ Type: ast.ConstraintTypeForeign,
+ Name: "fk_tech_book_id",
+ KeyList: []string{"id"},
+ Foreign: &ast.ForeignDef{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "people",
+ },
+ ColumnList: []string{"id"},
+ MatchType: ast.ForeignMatchTypeFull,
+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeCascade},
+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetDefault},
+ },
+ },
+ },
+ },
+ },
+ },
+ statementList: []parser.SingleSQL{
+ {
+ Text: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH FULL ON UPDATE CASCADE ON DELETE SET DEFAULT",
+ LastLine: 1,
+ },
+ },
+ },
+ {
+ stmt: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE SET NULL",
+ want: []ast.Node{
+ &ast.AlterTableStmt{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "tech_book",
+ },
+ AlterItemList: []ast.Node{
+ &ast.AddConstraintStmt{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "tech_book",
+ },
+ Constraint: &ast.ConstraintDef{
+ Type: ast.ConstraintTypeForeign,
+ Name: "fk_tech_book_id",
+ KeyList: []string{"id"},
+ Foreign: &ast.ForeignDef{
+ Table: &ast.TableDef{
+ Type: ast.TableTypeBaseTable,
+ Name: "people",
+ },
+ ColumnList: []string{"id"},
+ MatchType: ast.ForeignMatchTypeSimple,
+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeRestrict},
+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetNull},
+ },
+ },
+ },
+ },
+ },
+ },
+ statementList: []parser.SingleSQL{
+ {
+ Text: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE SET NULL",
+ LastLine: 1,
+ },
+ },
+ },
{
stmt: "ALTER TABLE tech_book ADD CONSTRAINT check_a_bigger_than_b CHECK (a > b) NOT VALID",
want: []ast.Node{
@@ -1131,6 +1257,9 @@ func TestPGAddConstraintStmt(t *testing.T) {
Name: "people",
},
ColumnList: []string{"id"},
+ MatchType: ast.ForeignMatchTypeSimple,
+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
},
},
},
diff --git a/plugin/parser/engine/pg/deparse.go b/plugin/parser/engine/pg/deparse.go
index afb9c3d97a..a663f8a73b 100644
--- a/plugin/parser/engine/pg/deparse.go
+++ b/plugin/parser/engine/pg/deparse.go
@@ -456,6 +456,105 @@ func deparseConstraintDef(_ parser.DeparseContext, in *ast.ConstraintDef, buf *s
if _, err := buf.WriteString(")"); err != nil {
return err
}
+ case ast.ConstraintTypeForeign:
+ if _, err := buf.WriteString("FOREIGN KEY ("); err != nil {
+ return err
+ }
+ for i, column := range in.KeyList {
+ if i != 0 {
+ if _, err := buf.WriteString(", "); err != nil {
+ return err
+ }
+ }
+ if err := writeSurrounding(buf, column, `"`); err != nil {
+ return err
+ }
+ }
+ if _, err := buf.WriteString(") REFERENCES "); err != nil {
+ return err
+ }
+ if err := deparseTableDef(parser.DeparseContext{}, in.Foreign.Table, buf); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(" ("); err != nil {
+ return err
+ }
+ for i, column := range in.Foreign.ColumnList {
+ if i != 0 {
+ if _, err := buf.WriteString(", "); err != nil {
+ return err
+ }
+ }
+ if err := writeSurrounding(buf, column, `"`); err != nil {
+ return err
+ }
+ }
+ if _, err := buf.WriteString(")"); err != nil {
+ return err
+ }
+
+ if err := deparseForeignMatchType(parser.DeparseContext{}, in.Foreign.MatchType, buf); err != nil {
+ return err
+ }
+
+ if err := deparseReferentialAction(parser.DeparseContext{}, "ON DELETE", in.Foreign.OnDelete, buf); err != nil {
+ return err
+ }
+
+ if err := deparseReferentialAction(parser.DeparseContext{}, "ON UPDATE", in.Foreign.OnUpdate, buf); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func deparseReferentialAction(_ parser.DeparseContext, prefix string, in *ast.ReferentialActionDef, buf *strings.Builder) error {
+ if in.Type == ast.ReferentialActionTypeNoAction {
+ // It's default value, no need to print.
+ return nil
+ }
+ if err := buf.WriteByte(' '); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(prefix); err != nil {
+ return err
+ }
+ if err := buf.WriteByte(' '); err != nil {
+ return err
+ }
+ switch in.Type {
+ case ast.ReferentialActionTypeRestrict:
+ if _, err := buf.WriteString("RESTRICT"); err != nil {
+ return err
+ }
+ case ast.ReferentialActionTypeCascade:
+ if _, err := buf.WriteString("CASCADE"); err != nil {
+ return err
+ }
+ case ast.ReferentialActionTypeSetNull:
+ if _, err := buf.WriteString("SET NULL"); err != nil {
+ return err
+ }
+ case ast.ReferentialActionTypeSetDefault:
+ if _, err := buf.WriteString("SET DEFAULT"); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func deparseForeignMatchType(_ parser.DeparseContext, in ast.ForeignMatchType, buf *strings.Builder) error {
+ switch in {
+ case ast.ForeignMatchTypeSimple:
+ // It's default value, no need to print.
+ case ast.ForeignMatchTypeFull:
+ if _, err := buf.WriteString(" MATCH FULL"); err != nil {
+ return err
+ }
+ case ast.ForeignMatchTypePartial:
+ if _, err := buf.WriteString(" MATCH PARTIAL"); err != nil {
+ return err
+ }
}
return nil
}
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.yaml
index 243573c59b..fee8d20d5e 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
@@ -84,6 +84,22 @@
want: |-
ALTER TABLE "t"
ADD CONSTRAINT "check_a" CHECK ((a + b) > c);
+- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c)
+ want: |-
+ ALTER TABLE "t"
+ ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c");
+- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c) match simple on delete no action on update no action
+ want: |-
+ ALTER TABLE "t"
+ ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c");
+- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c) match full on delete set null on update restrict
+ want: |-
+ ALTER TABLE "t"
+ ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c") MATCH FULL ON DELETE SET NULL ON UPDATE RESTRICT;
+- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c) match full on delete set default on update cascade
+ want: |-
+ ALTER TABLE "t"
+ ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c") MATCH FULL ON DELETE SET DEFAULT ON UPDATE CASCADE;
- stmt: |-
alter table t
add constraint email_pkey primary key(email, id);