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 PK/UK/FK CONSTRAINT in CREATE TABLE statement (#1718)
rebelicee0339562cb89
diff --git a/go.mod b/go.modindex 20993c2c8d..4769506382 100644--- a/go.mod+++ b/go.mod@@ -17,6 +17,7 @@ require (github.com/gosimple/slug v1.10.0github.com/jackc/pgtype v1.10.0github.com/jackc/pgx/v4 v4.15.0+ github.com/kr/pretty v0.2.1github.com/labstack/echo-contrib v0.12.0github.com/labstack/echo/v4 v4.7.2github.com/mattn/go-sqlite3 v1.14.7diff --git a/plugin/parser/ast/column_def.go b/plugin/parser/ast/column_def.goindex f4fe7b84dc..9234630e4c 100644--- a/plugin/parser/ast/column_def.go+++ b/plugin/parser/ast/column_def.go@@ -4,5 +4,6 @@ package asttype ColumnDef struct {node- ColumnName string+ ColumnName string+ ConstraintList []*ConstraintDef}diff --git a/plugin/parser/ast/constraint_def.go b/plugin/parser/ast/constraint_def.gonew file mode 100644index 0000000000..56c832b714--- /dev/null+++ b/plugin/parser/ast/constraint_def.go@@ -0,0 +1,41 @@+package ast++// ConstraintType is the type for constraints.+type ConstraintType int++const (+ // ConstraintTypeUndefined is the undefined type.+ ConstraintTypeUndefined ConstraintType = iota+ // ConstraintTypePrimary is the primary key constraint.+ ConstraintTypePrimary+ // ConstraintTypeUnique is the unique constraint.+ ConstraintTypeUnique+ // ConstraintTypeForeign is the foreign key constraint.+ ConstraintTypeForeign+)++// ConstraintDef is struct for constraint definition.+// For PRIMARY:+// Name: It's the PK constraint name.+// KeyList: It's the name list of the columns in PK.+//+// For UNIQUE+// Name: It's the UK constraint name.+// KeyList: It's the name list of the columns in UK.+//+// For Foreign+// Name: It's the FK constraint name.+// KeyList: It's the name list of the columns in FK.+// Foreign: It's the reference content for this FK.+type ConstraintDef struct {+ node++ Type ConstraintType+ Name string+ // KeyList is the list for constraint key.+ // Whether it is a column constraint or a table constraint,+ // there is a corresponding key list.+ KeyList []string+ // Foreign is a FOREIGN type specific field.+ Foreign *ForeignDef+}diff --git a/plugin/parser/ast/create_table_stmt.go b/plugin/parser/ast/create_table_stmt.goindex f191f11b92..4a3fb73f69 100644--- a/plugin/parser/ast/create_table_stmt.go+++ b/plugin/parser/ast/create_table_stmt.go@@ -4,7 +4,8 @@ package asttype CreateTableStmt struct {node- IfNotExists bool- Name *TableDef- ColumnList []*ColumnDef+ IfNotExists bool+ Name *TableDef+ ColumnList []*ColumnDef+ ConstraintList []*ConstraintDef}diff --git a/plugin/parser/ast/foreign_def.go b/plugin/parser/ast/foreign_def.gonew file mode 100644index 0000000000..334f635e1e--- /dev/null+++ b/plugin/parser/ast/foreign_def.go@@ -0,0 +1,9 @@+package ast++// ForeignDef is struct for foreign key reference.+type ForeignDef struct {+ node++ Table *TableDef+ ColumnList []string+}diff --git a/plugin/parser/ast/table_name.go b/plugin/parser/ast/table_def.gosimilarity index 100%rename from plugin/parser/ast/table_name.gorename to plugin/parser/ast/table_def.godiff --git a/plugin/parser/ast/utils.go b/plugin/parser/ast/utils.goindex ef75547588..81c3775a65 100644--- a/plugin/parser/ast/utils.go+++ b/plugin/parser/ast/utils.go@@ -41,6 +41,10 @@ func Walk(v Visitor, node Node) {Walk(v, cmd)}case *ColumnDef:+ case *ConstraintDef:+ if n.Foreign != nil {+ Walk(v, n.Foreign)+ }case *CreateTableStmt:if n.Name != nil {Walk(v, n.Name)@@ -48,6 +52,13 @@ func Walk(v Visitor, node Node) {for _, col := range n.ColumnList {Walk(v, col)}+ for _, cons := range n.ConstraintList {+ Walk(v, cons)+ }+ case *ForeignDef:+ if n.Table != nil {+ Walk(v, n.Table)+ }case *RenameTableStmt:if n.Table != nil {Walk(v, n.Table)diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.goindex dedfe8f5c2..d35e7f2c3e 100644--- a/plugin/parser/engine/pg/convert.go+++ b/plugin/parser/engine/pg/convert.go@@ -44,19 +44,41 @@ func convert(node *pgquery.Node) (ast.Node, error) {}return alterTable, nilcase *pgquery.Node_CreateStmt:- stmt := &ast.CreateTableStmt{+ table := &ast.CreateTableStmt{IfNotExists: in.CreateStmt.IfNotExists,Name: convertRangeVarToTableName(in.CreateStmt.Relation),}for _, elt := range in.CreateStmt.TableElts {- if colDef, ok := elt.Node.(*pgquery.Node_ColumnDef); ok {- stmt.ColumnList = append(stmt.ColumnList, &ast.ColumnDef{- ColumnName: colDef.ColumnDef.Colname,- })+ switch item := elt.Node.(type) {+ case *pgquery.Node_ColumnDef:+ column := &ast.ColumnDef{+ ColumnName: item.ColumnDef.Colname,+ }++ for _, cons := range item.ColumnDef.Constraints {+ constraint, ok := cons.Node.(*pgquery.Node_Constraint)+ if !ok {+ return nil, fmt.Errorf("expected Constraint but found %t", cons.Node)+ }+ columnCons, err := convertConstraint(constraint)+ if err != nil {+ return nil, err+ }+ columnCons.KeyList = append(columnCons.KeyList, item.ColumnDef.Colname)+ column.ConstraintList = append(column.ConstraintList, columnCons)+ }++ table.ColumnList = append(table.ColumnList, column)+ case *pgquery.Node_Constraint:+ cons, err := convertConstraint(item)+ if err != nil {+ return nil, err+ }+ table.ConstraintList = append(table.ConstraintList, cons)}}- return stmt, nil+ return table, nilcase *pgquery.Node_RenameStmt:switch in.RenameStmt.RenameType {case pgquery.ObjectType_OBJECT_COLUMN:@@ -83,3 +105,54 @@ func convertRangeVarToTableName(in *pgquery.RangeVar) *ast.TableDef {Name: in.Relname,}}++func convertConstraint(in *pgquery.Node_Constraint) (*ast.ConstraintDef, error) {+ cons := &ast.ConstraintDef{+ Name: in.Constraint.Conname,+ Type: convertConstraintType(in.Constraint.Contype),+ }++ for _, key := range in.Constraint.Keys {+ name, ok := key.Node.(*pgquery.Node_String_)+ if !ok {+ return nil, fmt.Errorf("expected String but found %t", key.Node)+ }+ cons.KeyList = append(cons.KeyList, name.String_.Str)+ }++ if cons.Type == ast.ConstraintTypeForeign {+ cons.Foreign = &ast.ForeignDef{+ Table: convertRangeVarToTableName(in.Constraint.Pktable),+ }++ for _, item := range in.Constraint.PkAttrs {+ name, ok := item.Node.(*pgquery.Node_String_)+ if !ok {+ return nil, fmt.Errorf("expected String but found %t", item.Node)+ }+ cons.Foreign.ColumnList = append(cons.Foreign.ColumnList, name.String_.Str)+ }++ for _, item := range in.Constraint.FkAttrs {+ name, ok := item.Node.(*pgquery.Node_String_)+ if !ok {+ return nil, fmt.Errorf("expected String but found %t", item.Node)+ }+ cons.KeyList = append(cons.KeyList, name.String_.Str)+ }+ }++ return cons, nil+}++func convertConstraintType(in pgquery.ConstrType) ast.ConstraintType {+ switch in {+ case pgquery.ConstrType_CONSTR_PRIMARY:+ return ast.ConstraintTypePrimary+ case pgquery.ConstrType_CONSTR_UNIQUE:+ return ast.ConstraintTypeUnique+ case pgquery.ConstrType_CONSTR_FOREIGN:+ return ast.ConstraintTypeForeign+ }+ return ast.ConstraintTypeUndefined+}diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.goindex fd9809cbb2..7316273c10 100644--- a/plugin/parser/engine/pg/convert_test.go+++ b/plugin/parser/engine/pg/convert_test.go@@ -5,6 +5,7 @@ import ("github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/ast"+ "github.com/kr/pretty""github.com/stretchr/testify/require")@@ -45,6 +46,97 @@ func TestPGConvertCreateTableStmt(t *testing.T) {},},},+ {+ stmt: "CREATE TABLE tech_book(a INT CONSTRAINT t_pk_a PRIMARY KEY)",+ want: []ast.Node{+ &ast.CreateTableStmt{+ Name: &ast.TableDef{+ Name: "tech_book",+ },+ ColumnList: []*ast.ColumnDef{+ {+ ColumnName: "a",+ ConstraintList: []*ast.ConstraintDef{+ {+ Name: "t_pk_a",+ Type: ast.ConstraintTypePrimary,+ KeyList: []string{"a"},+ },+ },+ },+ },+ },+ },+ },+ {+ stmt: "CREATE TABLE tech_book(a INT, b int CONSTRAINT uk_b UNIQUE, CONSTRAINT t_pk_a PRIMARY KEY(a))",+ want: []ast.Node{+ &ast.CreateTableStmt{+ Name: &ast.TableDef{+ Name: "tech_book",+ },+ ColumnList: []*ast.ColumnDef{+ {+ ColumnName: "a",+ },+ {+ ColumnName: "b",+ ConstraintList: []*ast.ConstraintDef{+ {+ Name: "uk_b",+ Type: ast.ConstraintTypeUnique,+ KeyList: []string{"b"},+ },+ },+ },+ },+ ConstraintList: []*ast.ConstraintDef{+ {+ Name: "t_pk_a",+ Type: ast.ConstraintTypePrimary,+ KeyList: []string{"a"},+ },+ },+ },+ },+ },+ {+ stmt: "CREATE TABLE tech_book(a INT CONSTRAINT fk_a REFERENCES people(id), CONSTRAINT fk_a_people_b FOREIGN KEY (a) REFERENCES people(b))",+ want: []ast.Node{+ &ast.CreateTableStmt{+ Name: &ast.TableDef{+ Name: "tech_book",+ },+ ColumnList: []*ast.ColumnDef{+ {+ ColumnName: "a",+ ConstraintList: []*ast.ConstraintDef{+ {+ Name: "fk_a",+ Type: ast.ConstraintTypeForeign,+ KeyList: []string{"a"},+ Foreign: &ast.ForeignDef{+ Table: &ast.TableDef{Name: "people"},+ ColumnList: []string{"id"},+ },+ },+ },+ },+ },+ ConstraintList: []*ast.ConstraintDef{+ {+ Name: "fk_a_people_b",+ Type: ast.ConstraintTypeForeign,+ KeyList: []string{"a"},+ Foreign: &ast.ForeignDef{+ Table: &ast.TableDef{Name: "people"},+ ColumnList: []string{"b"},+ },+ },+ },+ },+ },+ },}p := &PostgreSQLParser{}@@ -52,7 +144,7 @@ func TestPGConvertCreateTableStmt(t *testing.T) {for _, test := range tests {res, err := p.Parse(parser.Context{}, test.stmt)require.NoError(t, err)- require.True(t, equalCreateTableStmt(test.want, res))+ require.Nilf(t, pretty.Diff(test.want, res), "stmt: %s", test.stmt)}}@@ -85,7 +177,7 @@ func TestPGAddColumnStmt(t *testing.T) {for _, test := range tests {res, err := p.Parse(parser.Context{}, test.stmt)require.NoError(t, err)- require.True(t, equalAlterTableStmt(test.want, res))+ require.Nilf(t, pretty.Diff(test.want, res), "stmt: %s", test.stmt)}}@@ -109,7 +201,7 @@ func TestPGRenameTableStmt(t *testing.T) {for _, test := range tests {res, err := p.Parse(parser.Context{}, test.stmt)require.NoError(t, err)- require.True(t, equalRenameTableStmt(test.want, res))+ require.Nilf(t, pretty.Diff(test.want, res), "stmt: %s", test.stmt)}}@@ -136,159 +228,6 @@ func TestPGRenameColumnStmt(t *testing.T) {for _, test := range tests {res, err := p.Parse(parser.Context{}, test.stmt)require.NoError(t, err)- require.True(t, equalRenameColumnStmt(test.want, res))- }-}--func equalRenameColumnStmt(expected []ast.Node, actual []ast.Node) bool {- if len(expected) != len(actual) {- return false- }-- for i := range expected {- exp, ok := expected[i].(*ast.RenameColumnStmt)- if !ok {- return false- }- act, ok := actual[i].(*ast.RenameColumnStmt)- if !ok {- return false- }-- equalTableDef := equalTableDef(exp.Table, act.Table)- equalColumnDef := equalColumnDef(exp.Column, act.Column)- equalNewName := (exp.NewName == act.NewName)- if !equalTableDef || !equalColumnDef || !equalNewName {- return false- }- }-- return true-}--func equalRenameTableStmt(expected []ast.Node, actual []ast.Node) bool {- if len(expected) != len(actual) {- return false- }-- for i := range expected {- exp, ok := expected[i].(*ast.RenameTableStmt)- if !ok {- return false- }- act, ok := actual[i].(*ast.RenameTableStmt)- if !ok {- return false- }-- equalTableDef := equalTableDef(exp.Table, act.Table)- equalNewName := (exp.NewName == act.NewName)- if !equalTableDef || !equalNewName {- return false- }- }-- return true-}--func equalAlterTableStmt(expected []ast.Node, actual []ast.Node) bool {- if len(expected) != len(actual) {- return false- }-- for i := range expected {- exp, ok := expected[i].(*ast.AlterTableStmt)- if !ok {- return false- }- act, ok := actual[i].(*ast.AlterTableStmt)- if !ok {- return false- }-- equalTableDef := equalTableDef(exp.Table, act.Table)- equalAlterAction := equalAlterAction(exp.AlterItemList, act.AlterItemList)-- if !equalTableDef || !equalAlterAction {- return false- }- }-- return true-}--func equalAlterAction(expected []ast.Node, actual []ast.Node) bool {- if len(expected) != len(actual) {- return false- }-- for i := range expected {- if exp, ok := expected[i].(*ast.AddColumnListStmt); ok {- act, ok := actual[i].(*ast.AddColumnListStmt)- if !ok {- return false- }- if !equalAddColumnStmt(exp, act) {- return false- }- }- }-- return true-}--func equalAddColumnStmt(expected *ast.AddColumnListStmt, actual *ast.AddColumnListStmt) bool {- equalTableDef := equalTableDef(expected.Table, actual.Table)- equalColumnList := equalColumnList(expected.ColumnList, actual.ColumnList)- return equalTableDef && equalColumnList-}--func equalCreateTableStmt(expected []ast.Node, actual []ast.Node) bool {- if len(expected) != len(actual) {- return false- }-- for i := range expected {- exp, ok := expected[i].(*ast.CreateTableStmt)- if !ok {- return false- }- act, ok := actual[i].(*ast.CreateTableStmt)- if !ok {- return false- }-- equalFlag := (exp.IfNotExists == act.IfNotExists)- equalTableDef := equalTableDef(exp.Name, act.Name)- equalColumnList := equalColumnList(exp.ColumnList, act.ColumnList)- if !equalFlag || !equalTableDef || !equalColumnList {- return false- }- }- return true-}--func equalTableDef(expected *ast.TableDef, actual *ast.TableDef) bool {- equalDatabase := (expected.Database == actual.Database)- equalSchema := (expected.Schema == actual.Schema)- equalName := (expected.Name == actual.Name)- return equalDatabase && equalSchema && equalName-}--func equalColumnList(expected []*ast.ColumnDef, actual []*ast.ColumnDef) bool {- if len(expected) != len(actual) {- return false+ require.Nilf(t, pretty.Diff(test.want, res), "stmt: %s", test.stmt)}-- for i := range expected {- if !equalColumnDef(expected[i], actual[i]) {- return false- }- }-- return true-}--func equalColumnDef(expected *ast.ColumnDef, actual *ast.ColumnDef) bool {- return (expected.ColumnName == actual.ColumnName)}