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 PG pk required rule (#2026)
rebelice8d648ec49092
diff --git a/plugin/advisor/catalog/catalog.go b/plugin/advisor/catalog/catalog.goindex 3361d3430c..ee0ecd2c1e 100644--- a/plugin/advisor/catalog/catalog.go+++ b/plugin/advisor/catalog/catalog.go@@ -143,3 +143,29 @@ func (d *Database) FindIndex(find *IndexFind) (string, *Index) {}return "", nil}++// PrimaryKeyFind is for find primary key.+type PrimaryKeyFind struct {+ SchemaName string+ TableName string+}++// FindPrimaryKey finds the primary key.+func (d *Database) FindPrimaryKey(find *PrimaryKeyFind) *Index {+ for _, schema := range d.SchemaList {+ if schema.Name != find.SchemaName {+ continue+ }+ for _, table := range schema.TableList {+ if table.Name != find.TableName {+ continue+ }+ for _, index := range table.IndexList {+ if index.Primary {+ return index+ }+ }+ }+ }+ return nil+}diff --git a/plugin/advisor/pg/advisor_table_require_pk.go b/plugin/advisor/pg/advisor_table_require_pk.goindex e250f96034..5310ef8d0a 100644--- a/plugin/advisor/pg/advisor_table_require_pk.go+++ b/plugin/advisor/pg/advisor_table_require_pk.go@@ -1,7 +1,10 @@package pgimport (+ "fmt"+"github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/catalog""github.com/bytebase/bytebase/plugin/parser/ast")@@ -25,30 +28,105 @@ func (*TableRequirePKAdvisor) Check(ctx advisor.Context, statement string) ([]adreturn errAdvice, nil}- _, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)if err != nil {return nil, err}- checker := &tableRequirePKChecker{}+ checker := &tableRequirePKChecker{+ level: level,+ title: string(ctx.Rule.Type),+ database: ctx.Database,+ }for _, stmt := range stmts {+ checker.text = stmt.Text()ast.Walk(checker, stmt)}- return []advisor.Advice{}, nil+ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return checker.adviceList, nil}-// TODO(rebelice): fill the implementation to check table PK.type tableRequirePKChecker struct {- // adviceList []advisor.Advice- // level advisor.Status- // title string- // tables: make(tablePK),- // catalog catalog.Catalog+ adviceList []advisor.Advice+ level advisor.Status+ title string+ database *catalog.Database+ text string}// Visit implements the ast.Visitor interface.-func (checker *tableRequirePKChecker) Visit(ast.Node) ast.Visitor {+func (checker *tableRequirePKChecker) Visit(node ast.Node) ast.Visitor {+ var missingPK *ast.TableDef+ switch n := node.(type) {+ // CREATE TABLE+ case *ast.CreateTableStmt:+ hasPK := false+ for _, column := range n.ColumnList {+ if containPK(column.ConstraintList) {+ hasPK = true+ }+ }+ if containPK(n.ConstraintList) {+ hasPK = true+ }+ if !hasPK {+ missingPK = n.Name+ }+ // DROP CONSTRAINT+ case *ast.DropConstraintStmt:+ _, index := checker.database.FindIndex(&catalog.IndexFind{+ SchemaName: normalizeSchemaName(n.Table.Schema),+ TableName: n.Table.Name,+ IndexName: n.ConstraintName,+ })+ if index != nil && index.Primary {+ missingPK = n.Table+ }+ // DROP COLUMN+ case *ast.DropColumnStmt:+ pk := checker.database.FindPrimaryKey(&catalog.PrimaryKeyFind{+ SchemaName: normalizeSchemaName(n.Table.Schema),+ TableName: n.Table.Name,+ })+ if pk != nil {+ for _, column := range pk.ExpressionList {+ if column == n.ColumnName {+ missingPK = n.Table+ }+ }+ }+ }++ if missingPK != nil {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.TableNoPK,+ Title: checker.title,+ Content: fmt.Sprintf("Table %q.%q requires PRIMARY KEY, related statement: %q",+ normalizeSchemaName(missingPK.Schema),+ missingPK.Name,+ checker.text,+ ),+ })+ }+return checker}++func containPK(list []*ast.ConstraintDef) bool {+ for _, cons := range list {+ if cons.Type == ast.ConstraintTypePrimary || cons.Type == ast.ConstraintTypePrimaryUsingIndex {+ return true+ }+ }+ return false+}diff --git a/plugin/advisor/pg/advisor_table_require_pk_test.go b/plugin/advisor/pg/advisor_table_require_pk_test.goindex cd9408fa38..454c465140 100644--- a/plugin/advisor/pg/advisor_table_require_pk_test.go+++ b/plugin/advisor/pg/advisor_table_require_pk_test.go@@ -1,6 +1,7 @@package pgimport (+ "fmt""testing""github.com/bytebase/bytebase/plugin/advisor"@@ -10,7 +11,91 @@ func TestRequirePK(t *testing.T) {tests := []advisor.TestCase{{Statement: "CREATE TABLE t(id INT PRIMARY KEY)",- Want: []advisor.Advice{},+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: "CREATE TABLE t(id INT, PRIMARY KEY (id))",+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: "CREATE TABLE t(id INT)",+ Want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: advisor.TableNoPK,+ Title: "table.require-pk",+ Content: "Table \"public\".\"t\" requires PRIMARY KEY, related statement: \"CREATE TABLE t(id INT)\"",+ },+ },+ },+ {+ Statement: fmt.Sprintf("ALTER TABLE %q DROP CONSTRAINT %q", advisor.MockTableName, advisor.MockOldPostgreSQLPKName),+ Want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: advisor.TableNoPK,+ Title: "table.require-pk",+ Content: "Table \"public\".\"tech_book\" requires PRIMARY KEY, related statement: \"ALTER TABLE \\\"tech_book\\\" DROP CONSTRAINT \\\"old_pk\\\"\"",+ },+ },+ },+ {+ Statement: fmt.Sprintf("ALTER TABLE %q DROP CONSTRAINT %q", advisor.MockTableName, advisor.MockOldIndexName),+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: fmt.Sprintf("ALTER TABLE %q DROP CONSTRAINT constraint_not_in_catalog", advisor.MockTableName),+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: fmt.Sprintf("ALTER TABLE %q DROP COLUMN id", advisor.MockTableName),+ Want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: advisor.TableNoPK,+ Title: "table.require-pk",+ Content: "Table \"public\".\"tech_book\" requires PRIMARY KEY, related statement: \"ALTER TABLE \\\"tech_book\\\" DROP COLUMN id\"",+ },+ },+ },+ {+ Statement: fmt.Sprintf("ALTER TABLE %q DROP COLUMN column_not_in_pk", advisor.MockTableName),+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },},}