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 MySQL index total number limit (#2852)
rebeliced373838240a7
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex e9588324c6..2b138f5dbc 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -142,6 +142,9 @@ const (// MySQLIndexKeyNumberLimit is an advisor type for MySQL index key number limit.MySQLIndexKeyNumberLimit Type = "bb.plugin.advisor.mysql.index.key-number-limit"+ // MySQLIndexTotalNumberLimit is an advisor type for MySQL index total number limit.+ MySQLIndexTotalNumberLimit Type = "bb.plugin.advisor.mysql.index.total-number-limit"+// MySQLCharsetAllowlist is an advisor type for MySQL charset allowlist.MySQLCharsetAllowlist Type = "bb.plugin.advisor.mysql.charset.allowlist"diff --git a/plugin/advisor/catalog/state.go b/plugin/advisor/catalog/state.goindex 86d2f8cc79..a95c1b85ed 100644--- a/plugin/advisor/catalog/state.go+++ b/plugin/advisor/catalog/state.go@@ -281,6 +281,11 @@ type TableState struct {indexSet indexStateMap}+// CountIndex return the index total number.+func (table *TableState) CountIndex() int {+ return len(table.indexSet)+}+func (table *TableState) copy() *TableState {return &TableState{name: table.name,diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex e4cdfa8d1a..1e7baa9113 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -79,7 +79,7 @@ const (NotCurrentDatabase Code = 702DatabaseIsDeleted Code = 703- // 801 miss index error code.+ // 801 ~ 899 index error code.NotUseIndex Code = 801IndexKeyNumberExceedsLimit Code = 802IndexPKType Code = 803@@ -91,9 +91,8 @@ const (IndexNotExists Code = 809IncorrectIndexName Code = 810SpatialIndexKeyNullable Code = 811-- // 901 ~ 999 index error code.- DuplicateColumnInIndex Code = 901+ DuplicateColumnInIndex Code = 812+ IndexCountExceedsLimit Code = 813// 1001 ~ 1099 charset error code.DisabledCharset Code = 1001diff --git a/plugin/advisor/mysql/advisor_index_total_number_limit.go b/plugin/advisor/mysql/advisor_index_total_number_limit.gonew file mode 100644index 0000000000..137a3bda76--- /dev/null+++ b/plugin/advisor/mysql/advisor_index_total_number_limit.go@@ -0,0 +1,173 @@+package mysql++// Framework code is generated by the generator.++import (+ "fmt"+ "sort"++ "github.com/pingcap/tidb/parser/ast"++ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/catalog"+ "github.com/bytebase/bytebase/plugin/advisor/db"+)++var (+ _ advisor.Advisor = (*IndexTotalNumberLimitAdvisor)(nil)+ _ ast.Visitor = (*indexTotalNumberLimitChecker)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})+}++// IndexTotalNumberLimitAdvisor is the advisor checking for index total number limit.+type IndexTotalNumberLimitAdvisor struct {+}++// Check checks for index total number limit.+func (*IndexTotalNumberLimitAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ stmtList, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)+ 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 := &indexTotalNumberLimitChecker{+ level: level,+ title: string(ctx.Rule.Type),+ max: payload.Number,+ lineForTable: make(map[string]int),+ catalog: ctx.Catalog,+ }++ for _, stmt := range stmtList {+ checker.text = stmt.Text()+ checker.line = stmt.OriginTextPosition()+ (stmt).Accept(checker)+ }++ return checker.generateAdvice(), nil+}++type indexTotalNumberLimitChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ line int+ max int+ lineForTable map[string]int+ catalog *catalog.Finder+}++func (checker *indexTotalNumberLimitChecker) generateAdvice() []advisor.Advice {+ type tableName struct {+ name string+ line int+ }+ var tableList []tableName++ for k, v := range checker.lineForTable {+ tableList = append(tableList, tableName{+ name: k,+ line: v,+ })+ }+ sort.Slice(tableList, func(i, j int) bool {+ return tableList[i].line < tableList[j].line+ })++ for _, table := range tableList {+ tableInfo := checker.catalog.Final.FindTable(&catalog.TableFind{TableName: table.name})+ if tableInfo != nil && tableInfo.CountIndex() > checker.max {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.IndexCountExceedsLimit,+ Title: checker.title,+ Content: fmt.Sprintf("The count of index in table `%s` should be no more than %d, but found %d", table.name, checker.max, tableInfo.CountIndex()),+ Line: table.line,+ })+ }+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return checker.adviceList+}++// Enter implements the ast.Visitor interface.+func (checker *indexTotalNumberLimitChecker) Enter(in ast.Node) (ast.Node, bool) {+ switch node := in.(type) {+ case *ast.CreateTableStmt:+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()+ case *ast.AlterTableStmt:+ for _, spec := range node.Specs {+ switch spec.Tp {+ case ast.AlterTableAddColumns:+ for _, column := range spec.NewColumns {+ if createIndex(column) {+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()+ break+ }+ }+ case ast.AlterTableAddConstraint:+ if createIndex(spec.Constraint) {+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()+ }+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:+ if createIndex(spec.NewColumns[0]) {+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()+ }+ }+ }+ case *ast.CreateIndexStmt:+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()+ }++ return in, false+}++// Leave implements the ast.Visitor interface.+func (*indexTotalNumberLimitChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++func createIndex(in ast.Node) bool {+ switch node := in.(type) {+ case *ast.ColumnDef:+ for _, option := range node.Options {+ switch option.Tp {+ case ast.ColumnOptionPrimaryKey, ast.ColumnOptionUniqKey:+ return true+ }+ }+ case *ast.Constraint:+ switch node.Tp {+ case ast.ConstraintPrimaryKey,+ ast.ConstraintUniq,+ ast.ConstraintUniqKey,+ ast.ConstraintUniqIndex,+ ast.ConstraintKey,+ ast.ConstraintIndex,+ ast.ConstraintFulltext:+ return true+ }+ }+ return false+}diff --git a/plugin/advisor/mysql/advisor_index_total_number_limit_test.go b/plugin/advisor/mysql/advisor_index_total_number_limit_test.gonew file mode 100644index 0000000000..8abfa890f2--- /dev/null+++ b/plugin/advisor/mysql/advisor_index_total_number_limit_test.go@@ -0,0 +1,109 @@+package mysql++// Framework code is generated by the generator.++import (+ "encoding/json"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/plugin/advisor"+)++func TestIndexTotalNumberLimit(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `CREATE TABLE t(a int, b int, c int, unique key(a, b, c))`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE INDEX idx_id_name on tech_book(id, name)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ // tech_book had 3 indexes originally.+ Statement: `+ CREATE INDEX idx_id_name_1 on tech_book(id, name);+ CREATE INDEX idx_id_name_2 on tech_book(id, name);+ CREATE INDEX idx_id_name_3 on tech_book(id, name);+ CREATE INDEX idx_id_name_4 on tech_book(id, name);+ CREATE INDEX idx_id_name_5 on tech_book(id, name);+ `,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexCountExceedsLimit,+ Title: "index.total-number-limit",+ Content: "The count of index in table `tech_book` should be no more than 5, but found 8",+ Line: 6,+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(a int PRIMARY KEY, b int, c int);+ CREATE INDEX idx_a_b_1 on t(a, b);+ CREATE INDEX idx_a_b_2 on t(a, b);+ CREATE INDEX idx_a_b_3 on t(a, b);+ CREATE INDEX idx_a_b_4 on t(a, b);+ CREATE INDEX idx_a_b_5 on t(a, b);+ `,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexCountExceedsLimit,+ Title: "index.total-number-limit",+ Content: "The count of index in table `t` should be no more than 5, but found 6",+ Line: 7,+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(+ a int PRIMARY KEY,+ b int,+ c int,+ INDEX idx_a_b_1 (a, b),+ INDEX idx_a_b_2 (a, b),+ INDEX idx_a_b_3 (a, b),+ INDEX idx_a_b_4 (a, b),+ INDEX idx_a_b_5 (a, b));+ `,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexCountExceedsLimit,+ Title: "index.total-number-limit",+ Content: "The count of index in table `t` should be no more than 5, but found 6",+ Line: 10,+ },+ },+ },+ }++ payload, err := json.Marshal(advisor.NumberLimitRulePayload{+ Number: 5,+ })+ require.NoError(t, err)+ advisor.RunSQLReviewRuleTests(t, tests, &IndexTotalNumberLimitAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleIndexTotalNumberLimit,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: string(payload),+ }, advisor.MockMySQLDatabase)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 283a984b4b..153b1a57ae 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -106,6 +106,8 @@ const (SchemaRuleIndexPKType SQLReviewRuleType = "index.pk-type"// SchemaRuleIndexTypeNoBlob enforce the type restriction of columns in index.SchemaRuleIndexTypeNoBlob SQLReviewRuleType = "index.type-no-blob"+ // SchemaRuleIndexTotalNumberLimit enforce the index total number limit.+ SchemaRuleIndexTotalNumberLimit SQLReviewRuleType = "index.total-number-limit"// SchemaRuleCharsetAllowlist enforce the charset allowlist.SchemaRuleCharsetAllowlist SQLReviewRuleType = "charset.allowlist"@@ -209,7 +211,7 @@ func (rule *SQLReviewRule) Validate() error {if _, err := UnmarshalCommentConventionRulePayload(rule.Payload); err != nil {return err}- case SchemaRuleIndexKeyNumberLimit, SchemaRuleInsertRowLimit:+ case SchemaRuleIndexKeyNumberLimit, SchemaRuleInsertRowLimit, SchemaRuleIndexTotalNumberLimit:if _, err := UnmarshalNumberLimitRulePayload(rule.Payload); err != nil {return err}@@ -753,6 +755,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLIndexKeyNumberLimit, nil}+ case SchemaRuleIndexTotalNumberLimit:+ switch engine {+ case db.MySQL, db.TiDB:+ return MySQLIndexTotalNumberLimit, nil+ }case SchemaRuleStatementNoCreateTableAs:switch engine {case db.MySQL, db.TiDB: