Skip to content

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

chore: migrate index_no_duplicate_column (#9171)

zll6002f9f29af7a43
diff --git a/backend/plugin/advisor/mysqlwip/advisor_index_no_duplicate_column.go b/backend/plugin/advisor/mysqlwip/advisor_index_no_duplicate_column.go
index 3a761b9339..5ebc16fa20 100644
--- a/backend/plugin/advisor/mysqlwip/advisor_index_no_duplicate_column.go
+++ b/backend/plugin/advisor/mysqlwip/advisor_index_no_duplicate_column.go
@@ -5,26 +5,34 @@ package mysqlwip
import (
"fmt"
- "github.com/pingcap/tidb/parser/ast"
+ "github.com/antlr4-go/antlr/v4"
"github.com/pkg/errors"
+ mysql "github.com/bytebase/mysql-parser"
+
"github.com/bytebase/bytebase/backend/plugin/advisor"
+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
var (
_ advisor.Advisor = (*IndexNoDuplicateColumnAdvisor)(nil)
- _ ast.Visitor = (*indexNoDuplicateColumnChecker)(nil)
)
+func init() {
+ // only for mysqlwip test.
+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, 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, _ string) ([]advisor.Advice, error) {
- stmtList, ok := ctx.AST.([]ast.StmtNode)
+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)
if !ok {
- return nil, errors.Errorf("failed to convert to StmtNode")
+ return nil, errors.Errorf("failed to convert to mysql parser result")
}
level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
@@ -37,9 +45,8 @@ func (*IndexNoDuplicateColumnAdvisor) Check(ctx advisor.Context, _ string) ([]ad
}
for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
+ checker.baseLine = stmt.BaseLine
+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)
}
if len(checker.adviceList) == 0 {
@@ -54,118 +61,166 @@ func (*IndexNoDuplicateColumnAdvisor) Check(ctx advisor.Context, _ string) ([]ad
}
type indexNoDuplicateColumnChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ baseLine int
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(),
- })
- }
- }
+func (checker *indexNoDuplicateColumnChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if ctx.TableName() == nil {
+ return
+ }
+ if ctx.TableElementList() == nil {
+ return
+ }
+
+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
+ for _, tableElement := range ctx.TableElementList().AllTableElement() {
+ if tableElement == nil {
+ continue
}
- 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,
- })
+ if tableElement.TableConstraintDef() == nil {
+ continue
}
- 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,
- })
- }
- }
- }
+ checker.handleConstraintDef(tableName, tableElement.TableConstraintDef())
+ }
+}
+
+func (checker *indexNoDuplicateColumnChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ if ctx.AlterTableActions() == nil {
+ return
+ }
+ if ctx.AlterTableActions().AlterCommandList() == nil {
+ return
+ }
+ if ctx.AlterTableActions().AlterCommandList().AlterList() == nil {
+ return
+ }
+ if ctx.TableRef() == nil {
+ return
+ }
+
+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
+ for _, alterListItem := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {
+ if alterListItem == nil {
+ continue
}
+
+ switch {
+ // add index.
+ case alterListItem.ADD_SYMBOL() != nil && alterListItem.TableConstraintDef() != nil:
+ checker.handleConstraintDef(tableName, alterListItem.TableConstraintDef())
+ default:
+ continue
+ }
+ }
+}
+
+func (checker *indexNoDuplicateColumnChecker) EnterCreateIndex(ctx *mysql.CreateIndexContext) {
+ switch ctx.GetType_().GetTokenType() {
+ case mysql.MySQLParserFULLTEXT_SYMBOL, mysql.MySQLParserSPATIAL_SYMBOL:
+ return
+ }
+ if ctx.CreateIndexTarget() == nil || ctx.CreateIndexTarget().TableRef() == nil || ctx.CreateIndexTarget().KeyListVariants() == nil {
+ return
+ }
+ indexType := ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.CreateIndexTarget().KeyListVariants().GetStart().GetTokenIndex()-1,
+ ))
+
+ indexName := ""
+ if ctx.IndexName() != nil {
+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexName())
+ indexType = ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.IndexName().GetStart().GetTokenIndex()-1,
+ ))
+ }
+ if ctx.IndexNameAndType() != nil && ctx.IndexNameAndType().IndexName() != nil {
+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexNameAndType().IndexName())
+ indexType = ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.IndexNameAndType().GetStart().GetTokenIndex()-1,
+ ))
}
- for _, column := range columnList {
+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.CreateIndexTarget().TableRef())
+ columnList := mysqlparser.NormalizeKeyListVariants(ctx.CreateIndexTarget().KeyListVariants())
+ if column, duplicate := checker.hasDuplicateColumn(columnList); duplicate {
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,
+ Content: fmt.Sprintf("%s`%s` has duplicate column `%s`.`%s`", indexType, indexName, tableName, column),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
})
}
-
- return in, false
}
-// Leave implements the ast.Visitor interface.
-func (*indexNoDuplicateColumnChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
+func (checker *indexNoDuplicateColumnChecker) handleConstraintDef(tableName string, ctx mysql.ITableConstraintDefContext) {
+ var columnList []string
+ indexType := ""
+ switch ctx.GetType_().GetTokenType() {
+ case mysql.MySQLParserINDEX_SYMBOL, mysql.MySQLParserKEY_SYMBOL, mysql.MySQLParserPRIMARY_SYMBOL, mysql.MySQLParserUNIQUE_SYMBOL:
+ if ctx.KeyListVariants() == nil {
+ return
+ }
+ columnList = mysqlparser.NormalizeKeyListVariants(ctx.KeyListVariants())
+ indexType = ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.KeyListVariants().GetStart().GetTokenIndex()-1,
+ ))
+ case mysql.MySQLParserFOREIGN_SYMBOL:
+ if ctx.KeyList() == nil {
+ return
+ }
+ columnList = mysqlparser.NormalizeKeyList(ctx.KeyList())
+ indexType = ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.KeyList().GetStart().GetTokenIndex()-1,
+ ))
+ default:
+ return
+ }
+
+ indexName := ""
+ if ctx.IndexName() != nil {
+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexName())
+ indexType = ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.IndexName().GetStart().GetTokenIndex()-1,
+ ))
+ }
+ if ctx.IndexNameAndType() != nil && ctx.IndexNameAndType().IndexName() != nil {
+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexNameAndType().IndexName())
+ indexType = ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.IndexNameAndType().GetStart().GetTokenIndex()-1,
+ ))
+ }
+ if column, duplicate := checker.hasDuplicateColumn(columnList); duplicate {
+ 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`", indexType, indexName, tableName, column),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
+ })
+ }
}
-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
+func (*indexNoDuplicateColumnChecker) hasDuplicateColumn(keyList []string) (string, bool) {
+ listMap := make(map[string]struct{})
+ for _, keyName := range keyList {
+ if _, exists := listMap[keyName]; exists {
+ return keyName, true
}
+ listMap[keyName] = struct{}{}
}
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/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
index 26c49fcaab..443698e812 100644
--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
@@ -70,6 +70,9 @@ func TestMySQLWIPRules(t *testing.T) {
// advisor.SchemaRuleDropEmptyDatabase enforce the MySQL support check if the database is empty before users drop it.
advisor.SchemaRuleDropEmptyDatabase,
+
+ // advisor.SchemaRuleIndexNoDuplicateColumn require the index no duplicate column.
+ advisor.SchemaRuleIndexNoDuplicateColumn,
}
for _, rule := range mysqlwipRules {
diff --git a/backend/plugin/advisor/mysqlwip/test/index_no_duplicate_column.yaml b/backend/plugin/advisor/mysqlwip/test/index_no_duplicate_column.yaml
index c16e93b8f3..0c5f76d55e 100644
--- a/backend/plugin/advisor/mysqlwip/test/index_no_duplicate_column.yaml
+++ b/backend/plugin/advisor/mysqlwip/test/index_no_duplicate_column.yaml
@@ -1,4 +1,4 @@
-- statement: CREATE TABLE t (a int, PRIMARY KEY (a))
+- statement: CREATE TABLE t (a int, PRIMARY KEY (a));
want:
- status: SUCCESS
code: 0
@@ -8,8 +8,41 @@
details: ""
- statement: |-
CREATE TABLE t (
- a int,
- INDEX idx_a (a, a))
+ a int,
+ PRIMARY KEY (a, a)
+ );
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: PRIMARY KEY `` has duplicate column `t`.`a`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t1 (
+ a int,
+ PRIMARY KEY (a)
+ );
+ CREATE TABLE t2 (
+ a int,
+ FOREIGN KEY fk1 (a) REFERENCES t1(a)
+ );
+ CREATE TABLE t3 (
+ a int,
+ FOREIGN KEY fk1 (a, a) REFERENCES t1(a, a)
+ );
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: FOREIGN KEY `fk1` has duplicate column `t3`.`a`
+ line: 11
+ details: ""
+- statement: |-
+ CREATE TABLE t (
+ a int,
+ INDEX idx_a (a, a)
+ );
want:
- status: WARN
code: 812
@@ -19,7 +52,8 @@
details: ""
- statement: |-
CREATE TABLE t(a int);
- CREATE INDEX idx_a on t(a, a)
+ CREATE INDEX idx ON t(a);
+ CREATE INDEX idx_a ON t(a, a);
want:
- status: WARN
code: 812
@@ -29,7 +63,19 @@
details: ""
- statement: |-
CREATE TABLE t(a int);
- ALTER TABLE t ADD INDEX idx_a (a, a)
+ CREATE UNIQUE INDEX idx ON t(a);
+ CREATE UNIQUE INDEX idx_a ON t(a, a);
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: UNIQUE INDEX `idx_a` has duplicate column `t`.`a`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD INDEX idx (a);
+ ALTER TABLE t ADD INDEX idx_a (a, a);
want:
- status: WARN
code: 812
@@ -39,17 +85,28 @@
details: ""
- statement: |-
CREATE TABLE t(a int);
- ALTER TABLE t ADD PRIMARY KEY pk_a (a, a)
+ ALTER TABLE t ADD PRIMARY KEY pk_a (a, a);
want:
- status: WARN
code: 812
title: index.no-duplicate-column
content: PRIMARY KEY `pk_a` has duplicate column `t`.`a`
- line: 3
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD PRIMARY KEY pk_a (a);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
details: ""
- statement: |-
CREATE TABLE t(a int);
- ALTER TABLE t ADD UNIQUE KEY uk_a (a, a)
+ ALTER TABLE t ADD UNIQUE KEY uk (a);
+ ALTER TABLE t ADD UNIQUE KEY uk_a (a, a);
want:
- status: WARN
code: 812
@@ -59,7 +116,8 @@
details: ""
- statement: |-
CREATE TABLE t(a int);
- ALTER TABLE t ADD FOREIGN KEY fk_a (a, a) REFERENCES t1(a, b)
+ ALTER TABLE t ADD FOREIGN KEY fk (a) REFERENCES t1(a);
+ ALTER TABLE t ADD FOREIGN KEY fk_a (a, a) REFERENCES t1(a, b);
want:
- status: WARN
code: 812
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index d710ef00b6..f3406e4cba 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -1389,6 +1389,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
}
case SchemaRuleIndexNoDuplicateColumn:
switch engine {
+ // only for mysqlwip test.
+ case storepb.Engine_ENGINE_UNSPECIFIED:
+ return MySQLIndexNoDuplicateColumn, nil
case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:
return MySQLIndexNoDuplicateColumn, nil
case storepb.Engine_POSTGRES: