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-not-exists rule (#2521)
rebelicea48595604c83
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 8f60db4161..fa33a5a9c0 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -145,6 +145,9 @@ const (// MySQLIndexKeyNumberLimit is an advisor type for MySQL index key number limit.MySQLIndexKeyNumberLimit Type = "bb.plugin.advisor.mysql.index.key-number-limit"+ // MySQLIndexNotExists is an advisor type for MySQL index name conflict check.+ MySQLIndexNotExists Type = "bb.plugin.advisor.mysql.index.not-exists"+// MySQLCharsetAllowlist is an advisor type for MySQL charset allowlist.MySQLCharsetAllowlist Type = "bb.plugin.advisor.mysql.charset.allowlist"diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex 084a5af0d5..49c5c1027a 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -77,6 +77,7 @@ const (IndexKeyNumberExceedsLimit Code = 802IndexPKType Code = 803IndexTypeNoBlob Code = 804+ IndexExists Code = 805// 901 ~ 999 index error code.DuplicateColumnInIndex Code = 901diff --git a/plugin/advisor/mysql/advisor_index_not_exists.go b/plugin/advisor/mysql/advisor_index_not_exists.gonew file mode 100644index 0000000000..0b6bdd16e5--- /dev/null+++ b/plugin/advisor/mysql/advisor_index_not_exists.go@@ -0,0 +1,129 @@+package mysql++// Framework code is generated by the generator.++import (+ "fmt"++ "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 = (*IndexNotExistsAdvisor)(nil)+ _ ast.Visitor = (*indexNotExistsChecker)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLIndexNotExists, &IndexNotExistsAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLIndexNotExists, &IndexNotExistsAdvisor{})+}++// IndexNotExistsAdvisor is the advisor checking for index name conflict check.+type IndexNotExistsAdvisor struct {+}++// Check checks for index name conflict check.+func (*IndexNotExistsAdvisor) 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+ }+ checker := &indexNotExistsChecker{+ level: level,+ title: string(ctx.Rule.Type),+ database: ctx.Database,+ }++ for _, stmt := range stmtList {+ checker.text = stmt.Text()+ checker.line = stmt.OriginTextPosition()+ (stmt).Accept(checker)+ }++ 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 indexNotExistsChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ line int+ database *catalog.Database+}++// Enter implements the ast.Visitor interface.+func (checker *indexNotExistsChecker) Enter(in ast.Node) (ast.Node, bool) {+ type indexData struct {+ table string+ index string+ }+ var indexList []indexData+ switch node := in.(type) {+ case *ast.AlterTableStmt:+ for _, spec := range node.Specs {+ if spec.Tp == ast.AlterTableAddConstraint {+ switch spec.Constraint.Tp {+ case ast.ConstraintUniq,+ ast.ConstraintUniqIndex,+ ast.ConstraintUniqKey,+ ast.ConstraintIndex,+ ast.ConstraintKey:+ if spec.Constraint.Name != "" &&+ !spec.Constraint.IfNotExists &&+ checker.indexExists(node.Table.Name.O, spec.Constraint.Name) {+ indexList = append(indexList, indexData{+ table: node.Table.Name.O,+ index: spec.Constraint.Name,+ })+ }+ }+ }+ }+ case *ast.CreateIndexStmt:+ if node.IndexName != "" && !node.IfNotExists && checker.indexExists(node.Table.Name.O, node.IndexName) {+ indexList = append(indexList, indexData{+ table: node.Table.Name.O,+ index: node.IndexName,+ })+ }+ }++ for _, index := range indexList {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.IndexExists,+ Title: checker.title,+ Content: fmt.Sprintf("Index `%s` in table `%s` exists", index.index, index.table),+ Line: checker.line,+ })+ }+ return in, false+}++// Leave implements the ast.Visitor interface.+func (*indexNotExistsChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++func (checker *indexNotExistsChecker) indexExists(table string, index string) bool {+ _, idx := checker.database.FindIndex(&catalog.IndexFind{TableName: table, IndexName: index})+ return idx != nil+}diff --git a/plugin/advisor/mysql/advisor_index_not_exists_test.go b/plugin/advisor/mysql/advisor_index_not_exists_test.gonew file mode 100644index 0000000000..1ee131ce1c--- /dev/null+++ b/plugin/advisor/mysql/advisor_index_not_exists_test.go@@ -0,0 +1,79 @@+package mysql++// Framework code is generated by the generator.++import (+ "testing"++ "github.com/bytebase/bytebase/plugin/advisor"+)++func TestIndexNotExists(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `CREATE INDEX idx on t(a)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE INDEX old_index on tech_book(a)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexExists,+ Title: "index.not-exists",+ Content: "Index `old_index` in table `tech_book` exists",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE tech_book ADD CONSTRAINT old_uk UNIQUE KEY (a)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexExists,+ Title: "index.not-exists",+ Content: "Index `old_uk` in table `tech_book` exists",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE tech_book ADD UNIQUE KEY old_uk (a)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexExists,+ Title: "index.not-exists",+ Content: "Index `old_uk` in table `tech_book` exists",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE tech_book ADD KEY old_index (a)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.IndexExists,+ Title: "index.not-exists",+ Content: "Index `old_index` in table `tech_book` exists",+ Line: 1,+ },+ },+ },+ }++ advisor.RunSQLReviewRuleTests(t, tests, &IndexNotExistsAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleIndexNotExists,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: "",+ }, advisor.MockMySQLDatabase)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 50b524d761..ff20be1b46 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -105,6 +105,8 @@ const (SchemaRuleIndexPKType SQLReviewRuleType = "index.pk-type"// SchemaRuleIndexTypeNoBlob enforce the type restriction of columns in index.SchemaRuleIndexTypeNoBlob SQLReviewRuleType = "index.type-no-blob"+ // SchemaRuleIndexNotExists check the index name conflict.+ SchemaRuleIndexNotExists SQLReviewRuleType = "index.not-exists"// SchemaRuleCharsetAllowlist enforce the charset allowlist.SchemaRuleCharsetAllowlist SQLReviewRuleType = "charset.allowlist"@@ -612,6 +614,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLIndexTypeNoBlob, nil}+ case SchemaRuleIndexNotExists:+ switch engine {+ case db.MySQL, db.TiDB:+ return MySQLIndexNotExists, nil+ }}return Fake, errors.Errorf("unknown SQL review rule type %v for %v", ruleType, engine)}