Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(sql-review): implement MySQL index no duplicate column rule (#2469)

rebelicea12c1dcde670
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 6118aa6731..700fec9fa6 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -124,6 +124,9 @@ const (
// MySQLDatabaseAllowDropIfEmpty is an advisor type for MySQL only allow drop empty database.
MySQLDatabaseAllowDropIfEmpty Type = "bb.plugin.advisor.mysql.database.drop-empty-database"
+ // MySQLIndexNoDuplicateColumn is an advisor type for MySQL no duplicate columns in index.
+ MySQLIndexNoDuplicateColumn Type = "bb.plugin.advisor.mysql.index.no-duplicate-column"
+
// PostgreSQL Advisor.
// PostgreSQLSyntax is an advisor type for PostgreSQL syntax.
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index 7bec97752f..33d73ac9ee 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -68,6 +68,9 @@ const (
// 801 miss index error code.
NotUseIndex Code = 801
+
+ // 901 ~ 999 index error code.
+ DuplicateColumnInIndex Code = 901
)
// Int returns the int type of code.
diff --git a/plugin/advisor/mysql/advisor_index_no_duplicate_column.go b/plugin/advisor/mysql/advisor_index_no_duplicate_column.go
new file mode 100644
index 0000000000..2671756f3a
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_index_no_duplicate_column.go
@@ -0,0 +1,176 @@
+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/db"
+)
+
+var (
+ _ advisor.Advisor = (*IndexNoDuplicateColumnAdvisor)(nil)
+ _ ast.Visitor = (*indexNoDuplicateColumnChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
+ advisor.Register(db.TiDB, advisor.MySQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
+}
+
+// IndexNoDuplicateColumnAdvisor is the advisor checking for no duplicate columns in index.
+type IndexNoDuplicateColumnAdvisor struct {
+}
+
+// Check checks for no duplicate columns in index.
+func (*IndexNoDuplicateColumnAdvisor) 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 := &indexNoDuplicateColumnChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ 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 indexNoDuplicateColumnChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *indexNoDuplicateColumnChecker) Enter(in ast.Node) (ast.Node, bool) {
+ type duplicateColumn struct {
+ table string
+ index string
+ column string
+ line int
+ tp string
+ }
+ var columnList []duplicateColumn
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ switch constraint.Tp {
+ case ast.ConstraintPrimaryKey,
+ ast.ConstraintUniq,
+ ast.ConstraintUniqIndex,
+ ast.ConstraintIndex,
+ ast.ConstraintForeignKey:
+ if column, duplicate := hasDuplicateColumn(constraint.Keys); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ tp: indexTypeString(constraint.Tp),
+ table: node.Table.Name.O,
+ index: constraint.Name,
+ column: column,
+ line: constraint.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if column, duplicate := hasDuplicateColumn(node.IndexPartSpecifications); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ tp: "INDEX",
+ table: node.Table.Name.O,
+ index: node.IndexName,
+ column: column,
+ line: checker.line,
+ })
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableAddConstraint {
+ switch spec.Constraint.Tp {
+ case ast.ConstraintPrimaryKey,
+ ast.ConstraintUniq,
+ ast.ConstraintUniqIndex,
+ ast.ConstraintIndex,
+ ast.ConstraintForeignKey:
+ if column, duplicate := hasDuplicateColumn(spec.Constraint.Keys); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ tp: indexTypeString(spec.Constraint.Tp),
+ table: node.Table.Name.O,
+ index: spec.Constraint.Name,
+ column: column,
+ line: checker.line,
+ })
+ }
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: checker.title,
+ Content: fmt.Sprintf("%s `%s` has duplicate column `%s`.`%s`", column.tp, column.index, column.table, column.column),
+ Line: column.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexNoDuplicateColumnChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func hasDuplicateColumn(keyList []*ast.IndexPartSpecification) (string, bool) {
+ checker := make(map[string]bool)
+ for _, key := range keyList {
+ if key.Expr == nil {
+ if _, exists := checker[key.Column.Name.O]; exists {
+ return key.Column.Name.O, true
+ }
+ checker[key.Column.Name.O] = true
+ }
+ }
+
+ return "", false
+}
+
+func indexTypeString(tp ast.ConstraintType) string {
+ switch tp {
+ case ast.ConstraintPrimaryKey:
+ return "PRIMARY KEY"
+ case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:
+ return "UNIQUE KEY"
+ case ast.ConstraintForeignKey:
+ return "FOREIGN KEY"
+ case ast.ConstraintIndex:
+ return "INDEX"
+ }
+ return "INDEX"
+}
diff --git a/plugin/advisor/mysql/advisor_index_no_duplicate_column_test.go b/plugin/advisor/mysql/advisor_index_no_duplicate_column_test.go
new file mode 100644
index 0000000000..a133b853c6
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_index_no_duplicate_column_test.go
@@ -0,0 +1,105 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestIndexNoDuplicateColumn(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: `CREATE TABLE t (a int, PRIMARY KEY (a))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t (
+ a int,
+ INDEX idx_a (a, a))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "INDEX `idx_a` has duplicate column `t`.`a`",
+ Line: 3,
+ },
+ },
+ },
+ {
+ Statement: `CREATE INDEX idx_a on t(a, a)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "INDEX `idx_a` has duplicate column `t`.`a`",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD INDEX idx_a (a, a)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "INDEX `idx_a` has duplicate column `t`.`a`",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD PRIMARY KEY pk_a (a, a)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "PRIMARY KEY `pk_a` has duplicate column `t`.`a`",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD UNIQUE KEY uk_a (a, a)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "UNIQUE KEY `uk_a` has duplicate column `t`.`a`",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD FOREIGN KEY fk_a (a, a) REFERENCES t1(a, b)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "FOREIGN KEY `fk_a` has duplicate column `t`.`a`",
+ Line: 1,
+ },
+ },
+ },
+ }
+
+ advisor.RunSQLReviewRuleTests(t, tests, &IndexNoDuplicateColumnAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleIndexNoDuplicateColumn,
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: "",
+ }, advisor.MockMySQLDatabase)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index c584de1631..c3eb2ffd56 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -89,6 +89,9 @@ const (
// SchemaRuleDropEmptyDatabase enforce the MySQL and TiDB support check if the database is empty before users drop it.
SchemaRuleDropEmptyDatabase SQLReviewRuleType = "database.drop-empty-database"
+ // SchemaRuleIndexNoDuplicateColumn require the index no duplicate column.
+ SchemaRuleIndexNoDuplicateColumn SQLReviewRuleType = "index.no-duplicate-column"
+
// TableNameTemplateToken is the token for table name.
TableNameTemplateToken = "{{table}}"
// ColumnListTemplateToken is the token for column name list.
@@ -483,6 +486,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
case db.MySQL, db.TiDB:
return MySQLDatabaseAllowDropIfEmpty, nil
}
+ case SchemaRuleIndexNoDuplicateColumn:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return MySQLIndexNoDuplicateColumn, nil
+ }
}
return Fake, errors.Errorf("unknown SQL review rule type %v for %v", ruleType, engine)
}