Skip to content

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

chore: impl index type allow list rule for MySQL (#10989)

boojack969ce01df4f4
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index 4965f6358c..cbea428eb9 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -197,6 +197,9 @@ const (
// MySQLIndexTotalNumberLimit is an advisor type for MySQL index total number limit.
MySQLIndexTotalNumberLimit Type = "bb.plugin.advisor.mysql.index.total-number-limit"
+ // MySQLIndexTypeAllowList is an advisor type for MySQL index type allowlist.
+ MySQLIndexTypeAllowList Type = "bb.plugin.advisor.mysql.index.type-allow-list"
+
// MySQLCharsetAllowlist is an advisor type for MySQL charset allowlist.
MySQLCharsetAllowlist Type = "bb.plugin.advisor.mysql.charset.allowlist"
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index 173aee3a95..b587fcf507 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -125,6 +125,7 @@ const (
IndexCountExceedsLimit Code = 813
CreateIndexUnconcurrently Code = 814
DuplicateIndexInTable Code = 815
+ IndexTypeNotAllowed Code = 816
// 1001 ~ 1099 charset error code.
DisabledCharset Code = 1001
diff --git a/backend/plugin/advisor/mysql/advisor_index_type_allow_list.go b/backend/plugin/advisor/mysql/advisor_index_type_allow_list.go
new file mode 100644
index 0000000000..28b5d0836a
--- /dev/null
+++ b/backend/plugin/advisor/mysql/advisor_index_type_allow_list.go
@@ -0,0 +1,163 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "slices"
+
+ "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 = (*IndexTypeAllowListAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLIndexTypeAllowList, &IndexTypeAllowListAdvisor{})
+}
+
+// IndexTypeAllowListAdvisor is the advisor checking for index types.
+type IndexTypeAllowListAdvisor struct {
+}
+
+func (*IndexTypeAllowListAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to mysql parser result")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &indexTypeAllowListChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker.allowList = payload.List
+
+ for _, stmt := range stmtList {
+ checker.baseLine = stmt.BaseLine
+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)
+ }
+
+ 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 indexTypeAllowListChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ baseLine int
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ allowList []string
+}
+
+func (checker *indexTypeAllowListChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if ctx.TableName() == nil {
+ return
+ }
+ if ctx.TableElementList() == nil {
+ return
+ }
+
+ for _, tableElement := range ctx.TableElementList().AllTableElement() {
+ if tableElement == nil || tableElement.TableConstraintDef() == nil {
+ continue
+ }
+ checker.handleConstraintDef(tableElement.TableConstraintDef())
+ }
+}
+
+func (checker *indexTypeAllowListChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ if ctx.TableRef() == nil {
+ return
+ }
+ if ctx.AlterTableActions() == nil || ctx.AlterTableActions().AlterCommandList() == nil || ctx.AlterTableActions().AlterCommandList().AlterList() == nil {
+ return
+ }
+
+ for _, alterListItem := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {
+ if alterListItem == nil {
+ continue
+ }
+ if alterListItem.ADD_SYMBOL() != nil && alterListItem.TableConstraintDef() != nil {
+ checker.handleConstraintDef(alterListItem.TableConstraintDef())
+ }
+ }
+}
+
+func (checker *indexTypeAllowListChecker) handleConstraintDef(ctx mysql.ITableConstraintDefContext) {
+ switch ctx.GetType_().GetTokenType() {
+ case mysql.MySQLParserINDEX_SYMBOL, mysql.MySQLParserKEY_SYMBOL, mysql.MySQLParserPRIMARY_SYMBOL, mysql.MySQLParserUNIQUE_SYMBOL, mysql.MySQLParserFULLTEXT_SYMBOL, mysql.MySQLParserSPATIAL_SYMBOL:
+ default:
+ return
+ }
+
+ indexType := "BTREE"
+ if ctx.IndexNameAndType() != nil && ctx.IndexNameAndType().IndexType() != nil {
+ indexType = ctx.IndexNameAndType().IndexType().GetText()
+ } else {
+ if ctx.FULLTEXT_SYMBOL() != nil {
+ indexType = "FULLTEXT"
+ } else if ctx.SPATIAL_SYMBOL() != nil {
+ indexType = "SPATIAL"
+ }
+ }
+ checker.validateIndexType(indexType, ctx.GetStart().GetLine())
+}
+
+func (checker *indexTypeAllowListChecker) EnterCreateIndex(ctx *mysql.CreateIndexContext) {
+ if ctx.CreateIndexTarget() == nil || ctx.CreateIndexTarget().TableRef() == nil || ctx.CreateIndexTarget().KeyListVariants() == nil {
+ return
+ }
+
+ indexType := "BTREE"
+ if ctx.IndexNameAndType() != nil && ctx.IndexNameAndType().IndexType() != nil {
+ indexType = ctx.IndexNameAndType().IndexType().GetText()
+ } else {
+ if ctx.FULLTEXT_SYMBOL() != nil {
+ indexType = "FULLTEXT"
+ } else if ctx.SPATIAL_SYMBOL() != nil {
+ indexType = "SPATIAL"
+ }
+ }
+ checker.validateIndexType(indexType, ctx.GetStart().GetLine())
+}
+
+// validateIndexType checks if the index type is in the allow list.
+func (checker *indexTypeAllowListChecker) validateIndexType(indexType string, line int) {
+ if slices.Contains(checker.allowList, indexType) {
+ return
+ }
+
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.IndexTypeNotAllowed,
+ Title: checker.title,
+ Content: fmt.Sprintf("Index type `%s` is not allowed", indexType),
+ Line: checker.baseLine + line,
+ })
+}
diff --git a/backend/plugin/advisor/mysql/mysql_rules_test.go b/backend/plugin/advisor/mysql/mysql_rules_test.go
index 4e6eb0f961..25d26850d5 100644
--- a/backend/plugin/advisor/mysql/mysql_rules_test.go
+++ b/backend/plugin/advisor/mysql/mysql_rules_test.go
@@ -119,7 +119,10 @@ func TestMySQLRules(t *testing.T) {
advisor.SchemaRuleIndexTypeNoBlob,
// advisor.SchemaRuleIndexTotalNumberLimit enforce the index total number limit.
advisor.SchemaRuleIndexTotalNumberLimit,
+ // advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist enforce the primary key type allowlist.
advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist,
+ // advisor.SchemaRuleIndexTypeAllowList enforce the index type allowlist.
+ advisor.SchemaRuleIndexTypeAllowList,
// System related rules.
// advisor.SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.
diff --git a/backend/plugin/advisor/mysql/test/index_type_allow_list.yaml b/backend/plugin/advisor/mysql/test/index_type_allow_list.yaml
new file mode 100644
index 0000000000..d0bd2f56b0
--- /dev/null
+++ b/backend/plugin/advisor/mysql/test/index_type_allow_list.yaml
@@ -0,0 +1,46 @@
+- statement: |-
+ CREATE TABLE customers (
+ id INT PRIMARY KEY,
+ email VARCHAR(100),
+ INDEX idx_email (email)
+ );
+ want:
+ - status: SUCCESS
+ title: OK
+- statement: |-
+ CREATE TABLE orders (
+ id INT PRIMARY KEY,
+ order_number INT,
+ customer VARCHAR(50)
+ );
+ CREATE INDEX idx_customer ON orders (customer, (order_number * 2));
+ CREATE INDEX idx_customer_duplicate ON orders (customer, (order_number * 2));
+ want:
+ - status: SUCCESS
+ title: OK
+- statement: |-
+ CREATE TABLE locations (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ geom GEOMETRY NOT NULL
+ );
+ CREATE SPATIAL INDEX spatial_index_name ON locations(geom);
+ want:
+ - status: WARN
+ code: 816
+ title: index.type-allow-list
+ content: "Index type `SPATIAL` is not allowed"
+ line: 5
+ details: ""
+- statement: |-
+ CREATE TABLE locations (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ description TEXT NOT NULL
+ );
+ CREATE FULLTEXT INDEX fulltext_index_name ON locations(description);
+ want:
+ - status: WARN
+ code: 816
+ title: index.type-allow-list
+ content: "Index type `FULLTEXT` is not allowed"
+ line: 5
+ details: ""
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 3c92249bad..86fa79e003 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -174,6 +174,8 @@ const (
SchemaRuleIndexPrimaryKeyTypeAllowlist SQLReviewRuleType = "index.primary-key-type-allowlist"
// SchemaRuleCreateIndexConcurrently require creating indexes concurrently.
SchemaRuleCreateIndexConcurrently SQLReviewRuleType = "index.create-concurrently"
+ // SchemaRuleIndexTypeAllowList enforce the index type allowlist.
+ SchemaRuleIndexTypeAllowList SQLReviewRuleType = "index.type-allow-list"
// SchemaRuleCharsetAllowlist enforce the charset allowlist.
SchemaRuleCharsetAllowlist SQLReviewRuleType = "system.charset.allowlist"
@@ -1402,6 +1404,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
if engine == storepb.Engine_POSTGRES {
return PostgreSQLCreateIndexConcurrently, nil
}
+ case SchemaRuleIndexTypeAllowList:
+ if engine == storepb.Engine_MYSQL {
+ return MySQLIndexTypeAllowList, nil
+ }
case SchemaRuleStatementInsertRowLimit:
switch engine {
case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:
diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.go
index d472a1e8a0..63b6a449d2 100644
--- a/backend/plugin/advisor/utils_for_tests.go
+++ b/backend/plugin/advisor/utils_for_tests.go
@@ -459,6 +459,10 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.Eng
payload, err = json.Marshal(StringArrayTypeRulePayload{
List: []string{"serial", "bigserial", "int", "bigint"},
})
+ case SchemaRuleIndexTypeAllowList:
+ payload, err = json.Marshal(StringArrayTypeRulePayload{
+ List: []string{"BTREE", "HASH"},
+ })
case SchemaRuleIdentifierCase:
payload, err = json.Marshal(NamingCaseRulePayload{
Upper: true,