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(sql-review): implement postgresql check the number of index columns (#2965)
wangxiaolei8075d0d6c8aa
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 996fec87aa..0faf6ec9b5 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -221,6 +221,9 @@ const (// PostgreSQLInsertRowLimit is an advisor type for PostgreSQL to limit INSERT rows.PostgreSQLInsertRowLimit Type = "bb.plugin.advisor.postgresql.insert.row-limit"++ // PostgreSQLIndexKeyNumberLimit is an advisor type for postgresql index key number limit.+ PostgreSQLIndexKeyNumberLimit Type = "bb.plugin.advisor.postgresql.index.key-number-limit")// Advice is the result of an advisor.diff --git a/plugin/advisor/pg/advisor_index_key_number_limit.go b/plugin/advisor/pg/advisor_index_key_number_limit.gonew file mode 100644index 0000000000..5a65467bf0--- /dev/null+++ b/plugin/advisor/pg/advisor_index_key_number_limit.go@@ -0,0 +1,127 @@+package pg++import (+ "fmt"++ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/db"+ "github.com/bytebase/bytebase/plugin/parser/ast"+)++var (+ _ advisor.Advisor = (*IndexKeyNumberLimitAdvisor)(nil)+ _ ast.Visitor = (*indexKeyNumberLimitChecker)(nil)+)++func init() {+ advisor.Register(db.Postgres, advisor.PostgreSQLIndexKeyNumberLimit, &IndexKeyNumberLimitAdvisor{})+}++// IndexKeyNumberLimitAdvisor is the advisor checking for index key number limit.+type IndexKeyNumberLimitAdvisor struct {+}++// Check checks for index key number limit.+func (*IndexKeyNumberLimitAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ stmts, errAdvice := parseStatement(statement)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ payload, err := advisor.UnmarshalNumberLimitRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &indexKeyNumberLimitChecker{+ level: level,+ title: string(ctx.Rule.Type),+ max: payload.Number,+ }++ for _, stmt := range stmts {+ ast.Walk(checker, stmt)+ }++ 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+}++type indexKeyNumberLimitChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ max int+}++func (checker *indexKeyNumberLimitChecker) getMetaDataList(in ast.Node) []*indexMetaData {+ var res []*indexMetaData++ switch node := in.(type) {+ case *ast.CreateIndexStmt:+ if checker.max > 0 && len(node.Index.KeyList) > checker.max {+ res = append(res, &indexMetaData{+ indexName: node.Index.Name,+ tableName: node.Index.Table.Name,+ line: node.LastLine(),+ })+ }+ case *ast.CreateTableStmt:+ for _, constraint := range node.ConstraintList {+ if checker.max > 0 && indexKeyNumber(constraint) > checker.max {+ res = append(res, &indexMetaData{+ indexName: constraint.Name,+ tableName: node.Name.Name,+ line: constraint.LastLine(),+ })+ }+ }+ case *ast.AddConstraintStmt:+ if checker.max > 0 && indexKeyNumber(node.Constraint) > checker.max {+ res = append(res, &indexMetaData{+ indexName: node.Constraint.Name,+ tableName: node.Table.Name,+ line: node.LastLine(),+ })+ }+ }++ return res+}++func (checker *indexKeyNumberLimitChecker) Visit(node ast.Node) ast.Visitor {+ indexDataList := checker.getMetaDataList(node)++ for _, index := range indexDataList {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.IndexKeyNumberExceedsLimit,+ Title: checker.title,+ Content: fmt.Sprintf("The number of index `%s` in table `%s` should be not greater than %d", index.indexName, index.tableName, checker.max),+ Line: index.line,+ })+ }+ return checker+}++func indexKeyNumber(constraint *ast.ConstraintDef) int {+ switch constraint.Type {+ case ast.ConstraintTypePrimary,+ ast.ConstraintTypeUnique,+ ast.ConstraintTypeForeign:+ return len(constraint.KeyList)+ default:+ return 0+ }+}diff --git a/plugin/advisor/pg/advisor_index_key_number_limit_test.go b/plugin/advisor/pg/advisor_index_key_number_limit_test.gonew file mode 100644index 0000000000..f625a0d2c3--- /dev/null+++ b/plugin/advisor/pg/advisor_index_key_number_limit_test.go@@ -0,0 +1,118 @@+package pg++import (+ "encoding/json"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/plugin/advisor"+)++func TestIndexKeyNumberLimitAdvisor(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `CREATE TABLE t(name char(20));`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE t(name varchar(225));`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE t(name char(225), PRIMARY KEY (name));`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE t(id int, name char(225), CONSTRAINT t_id_name PRIMARY KEY (id, name));`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexKeyNumberExceedsLimit,+ Title: "index.key-number-limit",+ Content: "The number of index `t_id_name` in table `t` should be not greater than 1",+ Line: 1,+ },+ },+ },+ {+ Statement: `CREATE TABLE t(id int, name char(225), CONSTRAINT t_id_name UNIQUE (id, name));`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexKeyNumberExceedsLimit,+ Title: "index.key-number-limit",+ Content: "The number of index `t_id_name` in table `t` should be not greater than 1",+ Line: 1,+ },+ },+ },+ {+ Statement: `CREATE INDEX idx_address_phone ON address(id, phone);`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexKeyNumberExceedsLimit,+ Title: "index.key-number-limit",+ Content: "The number of index `idx_address_phone` in table `address` should be not greater than 1",+ Line: 1,+ },+ },+ },+ {+ Statement: `CREATE UNIQUE INDEX idx_address_phone ON address(id, phone);`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexKeyNumberExceedsLimit,+ Title: "index.key-number-limit",+ Content: "The number of index `idx_address_phone` in table `address` should be not greater than 1",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE t ADD CONSTRAINT t_id_name UNIQUE (id, name);`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexKeyNumberExceedsLimit,+ Title: "index.key-number-limit",+ Content: "The number of index `t_id_name` in table `t` should be not greater than 1",+ Line: 1,+ },+ },+ },+ }++ payload, err := json.Marshal(advisor.NumberLimitRulePayload{+ Number: 1,+ })+ require.NoError(t, err)+ advisor.RunSQLReviewRuleTests(t, tests, &IndexKeyNumberLimitAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleIndexKeyNumberLimit,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: string(payload),+ }, advisor.MockPostgreSQLDatabase)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 0cc4fb7bd0..a6624edc8d 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -764,7 +764,7 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err}case SchemaRuleIndexKeyNumberLimit:switch engine {- case db.MySQL, db.TiDB:+ case db.MySQL, db.TiDB, db.Postgres:return MySQLIndexKeyNumberLimit, nil}case SchemaRuleIndexTotalNumberLimit: