Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: migrate index_key_number_limit (#9173)
zll600c92a024edd34
diff --git a/backend/plugin/advisor/mysqlwip/advisor_index_key_number_limit.go b/backend/plugin/advisor/mysqlwip/advisor_index_key_number_limit.goindex 3110305eaa..847624351c 100644--- a/backend/plugin/advisor/mysqlwip/advisor_index_key_number_limit.go+++ b/backend/plugin/advisor/mysqlwip/advisor_index_key_number_limit.go@@ -5,26 +5,34 @@ package mysqlwipimport ("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 = (*IndexKeyNumberLimitAdvisor)(nil)- _ ast.Visitor = (*indexKeyNumberLimitChecker)(nil))+func init() {+ // only for mysqlwip test.+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, advisor.MySQLIndexKeyNumberLimit, &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, _ 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)@@ -42,9 +50,8 @@ func (*IndexKeyNumberLimitAdvisor) Check(ctx advisor.Context, _ string) ([]advis}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 {@@ -59,81 +66,127 @@ func (*IndexKeyNumberLimitAdvisor) Check(ctx advisor.Context, _ string) ([]advis}type indexKeyNumberLimitChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine intadviceList []advisor.Advicelevel advisor.Statustitle string- text string- line intmax int}-type indexData struct {- table string- index string- line int-}--// Enter implements the ast.Visitor interface.-func (checker *indexKeyNumberLimitChecker) Enter(in ast.Node) (ast.Node, bool) {- var indexList []indexData-- appendIndexItem := func(table, index string, line int) {- indexList = append(indexList, indexData{- table: table,- index: index,- line: line,- })+func (checker *indexKeyNumberLimitChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ if ctx.TableName() == nil {+ return+ }+ if ctx.TableElementList() == nil {+ return}- switch node := in.(type) {- case *ast.CreateTableStmt:- for _, constraint := range node.Constraints {- if checker.max > 0 && indexKeyNumber(constraint) > checker.max {- appendIndexItem(node.Table.Name.O, constraint.Name, constraint.OriginTextPosition())- }+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())+ for _, tableElement := range ctx.TableElementList().AllTableElement() {+ if tableElement == nil {+ continue+ }+ if tableElement.TableConstraintDef() == nil {+ continue}- case *ast.CreateIndexStmt:- if checker.max > 0 && len(node.IndexPartSpecifications) > checker.max {- appendIndexItem(node.Table.Name.O, node.IndexName, checker.line)+ checker.handleConstraintDef(tableName, tableElement.TableConstraintDef())+ }+}++func (checker *indexKeyNumberLimitChecker) handleConstraintDef(tableName string, ctx mysql.ITableConstraintDefContext) {+ var columnList []string+ switch ctx.GetType_().GetTokenType() {+ case mysql.MySQLParserINDEX_SYMBOL, mysql.MySQLParserKEY_SYMBOL, mysql.MySQLParserPRIMARY_SYMBOL, mysql.MySQLParserUNIQUE_SYMBOL:+ if ctx.KeyListVariants() == nil {+ return}- case *ast.AlterTableStmt:- for _, spec := range node.Specs {- if spec.Tp == ast.AlterTableAddConstraint {- if checker.max > 0 && indexKeyNumber(spec.Constraint) > checker.max {- appendIndexItem(node.Table.Name.O, spec.Constraint.Name, checker.line)- }- }+ columnList = mysqlparser.NormalizeKeyListVariants(ctx.KeyListVariants())+ case mysql.MySQLParserFOREIGN_SYMBOL:+ if ctx.KeyList() == nil {+ return}+ columnList = mysqlparser.NormalizeKeyList(ctx.KeyList())+ default:+ return+ }++ indexName := ""+ if ctx.IndexName() != nil {+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexName())+ }+ if ctx.IndexNameAndType() != nil && ctx.IndexNameAndType().IndexName() != nil {+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexNameAndType().IndexName())}- for _, index := range indexList {+ if checker.max > 0 && len(columnList) > checker.max {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.index, index.table, checker.max),- Line: index.line,+ Content: fmt.Sprintf("The number of index `%s` in table `%s` should be not greater than %d", indexName, tableName, checker.max),+ Line: checker.baseLine + ctx.GetStart().GetLine(),})}-- return in, false}-// Leave implements the ast.Visitor interface.-func (*indexKeyNumberLimitChecker) Leave(in ast.Node) (ast.Node, bool) {- return in, true+func (checker *indexKeyNumberLimitChecker) 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+ }++ indexName := ""+ if ctx.IndexName() != nil {+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexName())+ }+ if ctx.IndexNameAndType() != nil && ctx.IndexNameAndType().IndexName() != nil {+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexNameAndType().IndexName())+ }++ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.CreateIndexTarget().TableRef())+ columnList := mysqlparser.NormalizeKeyListVariants(ctx.CreateIndexTarget().KeyListVariants())+ if checker.max > 0 && len(columnList) > checker.max {+ 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", indexName, tableName, checker.max),+ Line: checker.baseLine + ctx.GetStart().GetLine(),+ })+ }}-func indexKeyNumber(constraint *ast.Constraint) int {- switch constraint.Tp {- case ast.ConstraintIndex,- ast.ConstraintPrimaryKey,- ast.ConstraintUniq,- ast.ConstraintUniqKey,- ast.ConstraintUniqIndex,- ast.ConstraintForeignKey:- return len(constraint.Keys)- default:- return 0+func (checker *indexKeyNumberLimitChecker) 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+ }}}diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.goindex 443698e812..646980aa49 100644--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go@@ -73,6 +73,8 @@ func TestMySQLWIPRules(t *testing.T) {// advisor.SchemaRuleIndexNoDuplicateColumn require the index no duplicate column.advisor.SchemaRuleIndexNoDuplicateColumn,+ // advisor.SchemaRuleIndexKeyNumberLimit enforce the index key number limit.+ advisor.SchemaRuleIndexKeyNumberLimit,}for _, rule := range mysqlwipRules {diff --git a/backend/plugin/advisor/mysqlwip/test/index_key_number_limit.yaml b/backend/plugin/advisor/mysqlwip/test/index_key_number_limit.yamlindex bab83ee30a..1799a25b4a 100644--- a/backend/plugin/advisor/mysqlwip/test/index_key_number_limit.yaml+++ b/backend/plugin/advisor/mysqlwip/test/index_key_number_limit.yaml@@ -1,4 +1,4 @@-- statement: CREATE TABLE t(a int, b int, primary key (a, b))+- statement: CREATE TABLE t(a int, b int, primary key (a, b));want:- status: SUCCESScode: 0@@ -8,9 +8,12 @@details: ""- statement: |-CREATE TABLE t(- a int,- b int,- primary key pk (a, b, b, b, b, b, b))+ a int,+ b int,+ primary key pk (a, b, b, b, b, b, b),+ unique key uk (a, b, b, b, b, b, b),+ foreign key fk (a, b, b, b, b, b) references t1(a, b, b, b, b, b)+ );want:- status: WARNcode: 802@@ -18,20 +21,45 @@content: The number of index `pk` in table `t` should be not greater than 5line: 4details: ""+ - status: WARN+ code: 802+ title: index.key-number-limit+ content: The number of index `uk` in table `t` should be not greater than 5+ line: 5+ details: ""+ - status: WARN+ code: 802+ title: index.key-number-limit+ content: The number of index `fk` in table `t` should be not greater than 5+ line: 6+ details: ""- statement: |-CREATE TABLE t(a int, b int, c int, d int, e int, f int, g int);- CREATE INDEX idx ON t(a, b, c, d, e, f, g)+ CREATE INDEX idx ON t(a, b, c, d, e, f, g);+ CREATE UNIQUE INDEX uk ON t(a, b, c, d, e, f, g);want:- status: WARNcode: 802title: index.key-number-limitcontent: The number of index `idx` in table `t` should be not greater than 5+ line: 2+ - status: WARN+ code: 802+ title: index.key-number-limit+ content: The number of index `uk` in table `t` should be not greater than 5line: 3details: ""- statement: |-CREATE TABLE t(a int, b int, c int, d int, e int, f int, g int);- ALTER TABLE t ADD UNIQUE KEY uk (a, b, c, d, e, f, g)+ ALTER TABLE t ADD PRIMARY KEY pk (a, b, c, d, e, f, g);+ ALTER TABLE t ADD UNIQUE KEY uk (a, b, c, d, e, f, g);want:+ - status: WARN+ code: 802+ title: index.key-number-limit+ content: The number of index `pk` in table `t` should be not greater than 5+ line: 2+ details: ""- status: WARNcode: 802title: index.key-number-limit@@ -46,5 +74,15 @@code: 802title: index.key-number-limitcontent: The number of index `uk` in table `t` should be not greater than 5- line: 3+ line: 2+ details: ""+- statement: |-+ CREATE TABLE t(a int, b varchar(255));+ CREATE FULLTEXT INDEX idx ON t(b, b, b, b, b, b);+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex f3406e4cba..42e5e536f8 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1399,6 +1399,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty}case SchemaRuleIndexKeyNumberLimit:switch engine {+ // only for mysqlwip test.+ case storepb.Engine_ENGINE_UNSPECIFIED:+ return MySQLIndexKeyNumberLimit, nilcase storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:return MySQLIndexKeyNumberLimit, nilcase storepb.Engine_POSTGRES: