Skip to content

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

feat(sql-review): implement MySQL index key number limit rule (#2481)

rebelice3963108de64e
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 740109e878..cabe359dff 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -130,6 +130,9 @@ const (
// MySQLIndexNoDuplicateColumn is an advisor type for MySQL no duplicate columns in index.
MySQLIndexNoDuplicateColumn Type = "bb.plugin.advisor.mysql.index.no-duplicate-column"
+ // MySQLIndexKeyNumberLimit is an advisor type for MySQL index key number limit.
+ MySQLIndexKeyNumberLimit Type = "bb.plugin.advisor.mysql.index.key-number-limit"
+
// PostgreSQL Advisor.
// PostgreSQLSyntax is an advisor type for PostgreSQL syntax.
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index 612a1815ef..ed0bcd33aa 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -70,7 +70,8 @@ const (
NotCurrentDatabase Code = 702
// 801 miss index error code.
- NotUseIndex Code = 801
+ NotUseIndex Code = 801
+ IndexKeyNumberExceedsLimit Code = 802
// 901 ~ 999 index error code.
DuplicateColumnInIndex Code = 901
diff --git a/plugin/advisor/mysql/advisor_index_key_number_limit.go b/plugin/advisor/mysql/advisor_index_key_number_limit.go
new file mode 100644
index 0000000000..6ecd5e4a81
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_index_key_number_limit.go
@@ -0,0 +1,147 @@
+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 = (*IndexKeyNumberLimitAdvisor)(nil)
+ _ ast.Visitor = (*indexKeyNumberLimitChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLIndexKeyNumberLimit, &IndexKeyNumberLimitAdvisor{})
+ advisor.Register(db.TiDB, 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, 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 := &indexKeyNumberLimitChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ max: payload.Number,
+ }
+
+ 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 indexKeyNumberLimitChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ max 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
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ if checker.max > 0 && indexKeyNumber(constraint) > checker.max {
+ indexList = append(indexList, indexData{
+ table: node.Table.Name.O,
+ index: constraint.Name,
+ line: constraint.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if checker.max > 0 && len(node.IndexPartSpecifications) > checker.max {
+ indexList = append(indexList, indexData{
+ table: node.Table.Name.O,
+ index: node.IndexName,
+ line: checker.line,
+ })
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableAddConstraint {
+ if checker.max > 0 && indexKeyNumber(spec.Constraint) > checker.max {
+ indexList = append(indexList, indexData{
+ table: node.Table.Name.O,
+ index: spec.Constraint.Name,
+ line: checker.line,
+ })
+ }
+ }
+ }
+ }
+
+ for _, index := range indexList {
+ 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,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexKeyNumberLimitChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+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
+ }
+}
diff --git a/plugin/advisor/mysql/advisor_index_key_number_limit_test.go b/plugin/advisor/mysql/advisor_index_key_number_limit_test.go
new file mode 100644
index 0000000000..91fc3210b4
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_index_key_number_limit_test.go
@@ -0,0 +1,89 @@
+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 TestIndexKeyNumberLimit(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: `CREATE TABLE t(a int, b int, primary key (a, b))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(
+ a int,
+ b int,
+ primary key pk (a, b, b, b, b, b, b))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexKeyNumberExceedsLimit,
+ Title: "index.key-number-limit",
+ Content: "The number of index `pk` in table `t` should be not greater than 5",
+ Line: 4,
+ },
+ },
+ },
+ {
+ Statement: `CREATE INDEX idx ON t(a, b, c, d, e, f, g)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexKeyNumberExceedsLimit,
+ Title: "index.key-number-limit",
+ Content: "The number of index `idx` in table `t` should be not greater than 5",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD UNIQUE KEY uk (a, b, c, d, e, f, g)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexKeyNumberExceedsLimit,
+ Title: "index.key-number-limit",
+ Content: "The number of index `uk` in table `t` should be not greater than 5",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD FOREIGN KEY uk (a, b, c, d, e, f, g) REFERENCES t1(a, b, c, d, e, f, g)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexKeyNumberExceedsLimit,
+ Title: "index.key-number-limit",
+ Content: "The number of index `uk` in table `t` should be not greater than 5",
+ Line: 1,
+ },
+ },
+ },
+ }
+
+ payload, err := json.Marshal(advisor.NumberLimitRulePayload{
+ Number: 5,
+ })
+ require.NoError(t, err)
+ advisor.RunSQLReviewRuleTests(t, tests, &IndexKeyNumberLimitAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleIndexKeyNumberLimit,
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: string(payload),
+ }, advisor.MockMySQLDatabase)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index a20123edfc..f65d0fa168 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -93,6 +93,8 @@ const (
// SchemaRuleIndexNoDuplicateColumn require the index no duplicate column.
SchemaRuleIndexNoDuplicateColumn SQLReviewRuleType = "index.no-duplicate-column"
+ // SchemaRuleIndexKeyNumberLimit enforce the index key number limit.
+ SchemaRuleIndexKeyNumberLimit SQLReviewRuleType = "index.key-number-limit"
// TableNameTemplateToken is the token for table name.
TableNameTemplateToken = "{{table}}"
@@ -186,6 +188,10 @@ func (rule *SQLReviewRule) Validate() error {
if _, err := UnmarshalCommentConventionRulePayload(rule.Payload); err != nil {
return err
}
+ case SchemaRuleIndexKeyNumberLimit:
+ if _, err := UnmarshalNumberLimitRulePayload(rule.Payload); err != nil {
+ return err
+ }
}
return nil
}
@@ -207,6 +213,11 @@ type CommentConventionRulePayload struct {
MaxLength int `json:"maxLength"`
}
+// NumberLimitRulePayload is the payload for number limit rule.
+type NumberLimitRulePayload struct {
+ Number int `json:"number"`
+}
+
// UnamrshalNamingRulePayloadAsRegexp will unmarshal payload to NamingRulePayload and compile it as regular expression.
func UnamrshalNamingRulePayloadAsRegexp(payload string) (*regexp.Regexp, int, error) {
var nr NamingRulePayload
@@ -297,6 +308,15 @@ func UnmarshalCommentConventionRulePayload(payload string) (*CommentConventionRu
return &ccr, nil
}
+// UnmarshalNumberLimitRulePayload will unmarshal payload to NumberLimitRulePayload.
+func UnmarshalNumberLimitRulePayload(payload string) (*NumberLimitRulePayload, error) {
+ var nlr NumberLimitRulePayload
+ if err := json.Unmarshal([]byte(payload), &nlr); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal number limit rule payload %q", payload)
+ }
+ return &nlr, nil
+}
+
// SQLReviewCheckContext is the context for SQL review check.
type SQLReviewCheckContext struct {
Charset string
@@ -512,6 +532,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
case db.MySQL, db.TiDB:
return MySQLIndexNoDuplicateColumn, nil
}
+ case SchemaRuleIndexKeyNumberLimit:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return MySQLIndexKeyNumberLimit, nil
+ }
case SchemaRuleStatementNoCreateTableAs:
switch engine {
case db.MySQL, db.TiDB: