Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-review): check redundant indexes fo MSSQL (#12159)
Azusain50c917f879a6
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 4db14e2cb9..48a0149a05 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -621,6 +621,8 @@ const (// MSSQLStatementWhereDisallowFunctionsAndCalculations prohibit using functions or performing calculation in the where clause.MSSQLStatementWhereDisallowFunctionsAndCalculations Type = "bb.plugin.advisor.mssql.statement.disallow-functions-and-calculations"++ MSSQLIndexNotRedundant Type = "bb.plugin.advisor.mssql.index.not-redundant")// Advice is the result of an advisor.diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex 0fc5216232..3eb9d19b46 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -152,6 +152,7 @@ const (CreateIndexUnconcurrently Code = 814DuplicateIndexInTable Code = 815IndexTypeNotAllowed Code = 816+ RedundantIndex Code = 817// 1001 ~ 1099 charset error code.DisabledCharset Code = 1001diff --git a/backend/plugin/advisor/config/sql-review.dev.yaml b/backend/plugin/advisor/config/sql-review.dev.yamlindex 3b5d43af84..d70f96511b 100644--- a/backend/plugin/advisor/config/sql-review.dev.yaml+++ b/backend/plugin/advisor/config/sql-review.dev.yaml@@ -254,6 +254,8 @@ ruleList:list:- BTREE- HASH+ - type: index.not-redundant+ level: WARNING- type: system.charset.allowlistlevel: WARNINGpayload:diff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yamlindex 3e2c423f3b..c0069df6ea 100644--- a/backend/plugin/advisor/config/sql-review.prod.yaml+++ b/backend/plugin/advisor/config/sql-review.prod.yaml@@ -268,6 +268,8 @@ ruleList:list:- BTREE- HASH+ - type: index.not-redundant+ level: WARNING- type: system.charset.allowlistlevel: ERRORpayload:diff --git a/backend/plugin/advisor/mssql/advisor_index_not_redundant.go b/backend/plugin/advisor/mssql/advisor_index_not_redundant.gonew file mode 100644index 0000000000..583af47e15--- /dev/null+++ b/backend/plugin/advisor/mssql/advisor_index_not_redundant.go@@ -0,0 +1,153 @@+package mssql++import (+ "fmt"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/tsql-parser"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/advisor"++ "github.com/bytebase/bytebase/proto/generated-go/store"+)++func init() {+ advisor.Register(store.Engine_MSSQL, advisor.MSSQLIndexNotRedundant, IndexNotRedundantAdvisor{})+}++var dftMSSQLSchemaName = "dbo"++// We consider all the indexes are based on B-Tree. Only in this situation ordered column list makes sense.+// TODO(zp): However, some of the indexes in MSSQL are not implemented with B-Tree:+// ref: https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-indexes-transact-sql?view=sql-server-ver16/.++type IndexNotRedundantAdvisor struct{}++type IndexNotRedundantChecker struct {+ *parser.BaseTSqlParserListener+ level advisor.Status+ title string+ curDB string+ indexMap *IndexMap+ adviceList []advisor.Advice+}++// TODO(zp): we currently don't have runtime checks for indexes created in the statements.+func (IndexNotRedundantAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ tree, ok := ctx.AST.(antlr.Tree)+ if !ok {+ return nil, errors.Errorf("failed to convert to AST tree")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ checker := &IndexNotRedundantChecker{+ level: level,+ title: ctx.Rule.Type,+ curDB: ctx.CurrentDatabase,+ indexMap: getIndexMapFromMetadata(ctx.DBSchema),+ }++ antlr.ParseTreeWalkerDefault.Walk(checker, 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+}++func (checker *IndexNotRedundantChecker) EnterCreate_index(ctx *parser.Create_indexContext) {+ idxSchemaName := dftMSSQLSchemaName+ idxTblName := ""++ // Get full table name.+ if fullTblName := ctx.Table_name(); fullTblName != nil {+ // TODO(zp): we only check indexes in the current database due to the lack of necessary metadata.+ // Case sensitive!+ if database := fullTblName.GetDatabase(); database != nil && database.GetText() != checker.curDB {+ return+ }+ if schema := fullTblName.GetSchema(); schema != nil {+ idxSchemaName = schema.GetText()+ }+ idxTblName = fullTblName.GetTable().GetText()+ }++ // Get index name from statement.+ statIdxName := ctx.AllId_()[0].GetText()++ // Get ordered index list from metadata.+ findIdxKey := FindIndexesKey{+ schemaName: idxSchemaName,+ tblName: idxTblName,+ }+ metaIdxList, ok := (*checker.indexMap)[findIdxKey]+ if !ok {+ return+ }++ // Get ordered column list from statement.+ statIdxColList := ctx.Column_name_list_with_order()+ if metaIdxName := containRedundantPrefix(metaIdxList, &statIdxColList); metaIdxName != "" {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Title: checker.title,+ Line: ctx.GetStart().GetLine(),+ Code: advisor.RedundantIndex,+ Content: fmt.Sprintf("Redundant indexes with the same prefix ('%s' and '%s') in '%s.%s' is not allowed",+ metaIdxName, statIdxName, findIdxKey.schemaName, findIdxKey.tblName),+ })+ }+}++type FindIndexesKey struct {+ schemaName string+ tblName string+}++// The value in the map represents the column list of a certain index.+type IndexMap = map[FindIndexesKey][]*store.IndexMetadata++// Return the name of the index if redundant prefixes are found.+func containRedundantPrefix(metaIdxList []*store.IndexMetadata, statColumnList *parser.IColumn_name_list_with_orderContext) string {+ for _, metaIndex := range metaIdxList {+ if statColumnList != nil && len((*statColumnList).AllId_()) != 0 && len(metaIdxList) != 0 {+ if metaIndex.Expressions[0] == (*statColumnList).AllId_()[0].GetText() {+ return metaIndex.Name+ }+ }+ }+ return ""+}++func getIndexMapFromMetadata(dbMetadata *store.DatabaseSchemaMetadata) *IndexMap {+ indexMap := IndexMap{}+ if dbMetadata == nil {+ return &indexMap+ }+ for _, schema := range dbMetadata.Schemas {+ if schema.Name == "" {+ continue+ }+ for _, tbl := range schema.Tables {+ if tbl.Name == "" {+ continue+ }+ indexMap[FindIndexesKey{+ schemaName: schema.Name,+ tblName: tbl.Name,+ }] = tbl.Indexes+ }+ }+ return &indexMap+}diff --git a/backend/plugin/advisor/mssql/mssql_rules_test.go b/backend/plugin/advisor/mssql/mssql_rules_test.goindex c7ae90f23a..86a5a779bb 100644--- a/backend/plugin/advisor/mssql/mssql_rules_test.go+++ b/backend/plugin/advisor/mssql/mssql_rules_test.go@@ -28,7 +28,8 @@ func TestMSSQLRules(t *testing.T) {advisor.SchemaRuleFunctionDisallowCreate,advisor.SchemaRuleProcedureDisallowCreate,advisor.SchemaRuleStatementDisallowCrossDBQueries,- advisor.SchemaRuleStatementWhereDisallowFunctionsAndCalculations,+ advisor.SchemaRuleStatementWhereDisallowFunctionsAndCaculations,+ advisor.SchemaRuleIndexNotRedundant,}for _, rule := range mssqlRules {@@ -41,4 +42,5 @@ func TestMSSQLRules(t *testing.T) {var advisorNeedMockData = map[advisor.SQLReviewRuleType]bool{advisor.SchemaRuleStatementDisallowCrossDBQueries: true,advisor.SchemaRuleSchemaBackwardCompatibility: true,+ advisor.SchemaRuleIndexNotRedundant: true,}diff --git a/backend/plugin/advisor/mssql/test/index_not_redundant.yaml b/backend/plugin/advisor/mssql/test/index_not_redundant.yamlnew file mode 100644index 0000000000..9982557230--- /dev/null+++ b/backend/plugin/advisor/mssql/test/index_not_redundant.yaml@@ -0,0 +1,14 @@+- statement: |-+ CREATE INDEX test_index ON dbo.pokes (c1, c2);+ want:+ - status: WARN+ title: index.not-redundant+ content: "Redundant indexes with the same prefix ('idx_0' and 'test_index') in 'dbo.pokes' is not allowed"+ code: 817+ line: 1+- statement: |-+ CREATE INDEX test_index ON dbo.pokes (c100, c200);+ want:+ - status: SUCCESS+ title: OK+ content: ""diff --git a/backend/plugin/advisor/mysql/mysql_rules_test.go b/backend/plugin/advisor/mysql/mysql_rules_test.goindex 6301d328b3..296c769865 100644--- a/backend/plugin/advisor/mysql/mysql_rules_test.go+++ b/backend/plugin/advisor/mysql/mysql_rules_test.go@@ -60,7 +60,7 @@ func TestMySQLRules(t *testing.T) {// advisor.SchemaRuleStatementMaximumJoinTableCount enforces maximum of tables in the joins.advisor.SchemaRuleStatementMaximumJoinTableCount,// advisor.SchemaRuleStatementWhereDisallowUsingFunction disallow using function in where clause.- advisor.SchemaRuleStatementWhereDisallowFunctionsAndCalculations,+ advisor.SchemaRuleStatementWhereDisallowFunctionsAndCaculations,// advisor.SchemaRuleStatementWhereMaximumLogicalOperatorCount enforces maximum number of logical operators in the where clause.advisor.SchemaRuleStatementWhereMaximumLogicalOperatorCount,diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 7ec129359d..9b4fd450f7 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -114,8 +114,8 @@ const (SchemaRuleStatementDisallowUsingTemporary = "statement.disallow-using-temporary"// SchemaRuleStatementWhereNoEqualNull check the WHERE clause no equal null.SchemaRuleStatementWhereNoEqualNull = "statement.where.no-equal-null"- // SchemaRuleStatementWhereDisallowFunctionsAndCalculations disallow using function in WHERE clause.- SchemaRuleStatementWhereDisallowFunctionsAndCalculations = "statement.where.disallow-functions-and-calculations"+ // SchemaRuleStatementWhereDisallowFunctionsAndCaculations disallow using function in WHERE clause.+ SchemaRuleStatementWhereDisallowFunctionsAndCaculations = "statement.where.disallow-functions-and-calculations"// SchemaRuleStatementQueryMinumumPlanLevel enforce the minimum plan level.SchemaRuleStatementQueryMinumumPlanLevel = "statement.query.minimum-plan-level"// SchemaRuleStatementWhereMaximumLogicalOperatorCount enforce the maximum logical operator count in WHERE clause.@@ -225,6 +225,8 @@ const (SchemaRuleCreateIndexConcurrently SQLReviewRuleType = "index.create-concurrently"// SchemaRuleIndexTypeAllowList enforce the index type allowlist.SchemaRuleIndexTypeAllowList SQLReviewRuleType = "index.type-allow-list"+ // SchemaRuleIndexNotRedundant prohibits createing redundant indices.+ SchemaRuleIndexNotRedundant SQLReviewRuleType = "index.not-redundant"// SchemaRuleCharsetAllowlist enforce the charset allowlist.SchemaRuleCharsetAllowlist SQLReviewRuleType = "system.charset.allowlist"@@ -1470,6 +1472,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tycase storepb.Engine_POSTGRES:return PostgreSQLIndexTotalNumberLimit, nil}+ case SchemaRuleIndexNotRedundant:+ if engine == storepb.Engine_MSSQL {+ return MSSQLIndexNotRedundant, nil+ }case SchemaRuleStatementDisallowRemoveTblCascade:if engine == storepb.Engine_POSTGRES {return PostgreSQLStatementDisallowRemoveTblCascade, nil@@ -1637,13 +1643,16 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLStatementWhereNoEqualNull, nil}- case SchemaRuleStatementWhereDisallowFunctionsAndCalculations:+ case SchemaRuleStatementWhereDisallowFunctionsAndCaculations:if engine == storepb.Engine_MYSQL {return MySQLStatementWhereDisallowUsingFunction, nil}if engine == storepb.Engine_MSSQL {return MSSQLStatementWhereDisallowFunctionsAndCalculations, nil}+ if engine == storepb.Engine_MSSQL {+ return MSSQLStatementWhereDisallowFunctionsAndCalculations, nil+ }case SchemaRuleStatementQueryMinumumPlanLevel:if engine == storepb.Engine_MYSQL {return MySQLStatementQueryMinumumPlanLevel, nildiff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 61b0dbba01..5550392b79 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -124,7 +124,19 @@ var ({Name: "dbo",Tables: []*storepb.TableMetadata{- {Name: "pokes"},+ {+ Name: "pokes",+ Indexes: []*storepb.IndexMetadata{+ {+ Name: "idx_0",+ Expressions: []string{"c1", "c2", "c3"},+ },+ {+ Name: "idx_1",+ Expressions: []string{"c10", "c20"},+ },+ },+ },{Name: "pokes2"},{Name: "pokes3"},},@@ -392,12 +404,13 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.EngSchemaRuleFunctionDisallowCreate,SchemaRuleStatementCreateSpecifySchema,SchemaRuleStatementCheckSetRoleVariable,- SchemaRuleStatementWhereDisallowFunctionsAndCalculations,+ SchemaRuleStatementWhereDisallowFunctionsAndCaculations,SchemaRuleStatementDisallowMixDDLDML,SchemaRuleStatementPriorBackupCheck,SchemaRuleStatementJoinStrictColumnAttrs,SchemaRuleTableDisallowSetCharset,- SchemaRuleStatementDisallowCrossDBQueries:+ SchemaRuleStatementDisallowCrossDBQueries,+ SchemaRuleIndexNotRedundant:case SchemaRuleTableDropNamingConvention:payload, err = json.Marshal(NamingRulePayload{Format: "_delete$",diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex 3f3ad3dcca..bbfa660760 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -580,6 +580,10 @@}}},+ "index-not-redundant": {+ "title": "Disallow redundant indexes",+ "description": "Redundant index may result in performance loss and occupy additional space. For example, the index on columns (c1, c2) will be treated as redundant indexes if there is already a index on column (c1). Suggestion error level: Warning"+ },"system-charset-allowlist": {"title": "Allowable list of Charset","description": "The character set determines which characters can be stored in the table. Using the wrong character set may result in certain characters in the application being unable to be stored and displayed correctly, such as CJK and Emoji. Suggested error level: Error",diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.jsonindex c5e927adcc..6e18c00fa6 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -580,6 +580,10 @@}}},+ "index-not-redundant": {+ "title": "Prohibir índices redundantes",+ "description": "El índice redundante puede resultar en pérdida de rendimiento y ocupar espacio adicional. Por ejemplo, el índice en las columnas (c1, c2) se tratará como índices redundantes si ya hay un índice en la columna (c1). Nivel de error sugerido: Advertencia"+ },"system-charset-allowlist": {"title": "Lista permitida de juegos de caracteres","description": "El juego de caracteres determina qué caracteres se pueden almacenar en la tabla. El uso de un juego de caracteres incorrecto puede hacer que ciertos caracteres de la aplicación no se puedan almacenar ni mostrar correctamente, como los caracteres CJK y Emoji. Nivel de error sugerido: Error",@@ -656,4 +660,4 @@"warning": "Advertencia","disabled": "Deshabilitado"}-}\ No newline at end of file+}diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.jsonindex 4dc65ff1c3..4e0c9a0611 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -580,6 +580,10 @@}}},+ "index-not-redundant": {+ "title": "冗長なインデックスを禁止する",+ "description": "冗長なインデックスはパフォーマンスの損失と追加のスペースの占有を引き起こす可能性があります。例えば、列(c1)にすでにインデックスが存在する場合、列(c1、c2)上のインデックスは冗長なインデックスとして扱われます。提案されるエラーレベル:警告"+ },"system-charset-allowlist": {"title": "許可される文字セットのリスト","description": "文字セットは、テーブルに格納できる文字を決定します。間違った文字セットを使用すると、アプリケーションの一部の文字が正しく格納および表示されない場合があります。CJKや絵文字などが該当します。提案エラーレベル:エラー",@@ -656,4 +660,4 @@"warning": "警告","disabled": "無効化"}-}\ No newline at end of file+}diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.jsonindex 92f9bb1f7b..3e934d61ca 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -580,6 +580,10 @@}}},+ "index-not-redundant": {+ "title": "禁止冗余索引",+ "description": "冗余索引可能会导致性能损失并占用额外空间。例如,如果列(c1)上已经有一个索引,那么在列(c1,c2)上的索引将被视为冗余索引。建议的错误级别:警告"+ },"system-charset-allowlist": {"title": "允许使用的字符集(Charset)列表","description": "字符集决定了表中可以存储哪些字符,使用错误的字符集可能导致应用中的某些字符无法正确存储与显示,例如中文与 Emoji 表情。建议错误等级:错误",@@ -656,4 +660,4 @@"warning": "警告","disabled": "禁用"}-}\ No newline at end of file+}diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex b2fdcd1a78..ff7aedbd86 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -818,6 +818,10 @@ ruleList:payload:type: STRING_ARRAYdefault: []+ - type: index.not-redundant+ category: INDEX+ engineList:+ - MSSQL- type: system.charset.allowlistcategory: SYSTEMengineList: