Skip to content

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

chore: implement check query plan level (#11084)

boojack6064db700bfd
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index e52b135c3f..ffb99ca8f4 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -48,6 +48,7 @@ const (
StatementWhereNoEqualNull Code = 221
StatementExceedMaximumLimitValue Code = 222
StatementMaximumJoinTableCount Code = 223
+ StatementUnwantedQueryPlanLevel Code = 224
// 301 ~ 399 naming error code
// 301 table naming advisor error code.
diff --git a/backend/plugin/advisor/config/sql-review.dev.yaml b/backend/plugin/advisor/config/sql-review.dev.yaml
index bb76242d68..853523e125 100644
--- a/backend/plugin/advisor/config/sql-review.dev.yaml
+++ b/backend/plugin/advisor/config/sql-review.dev.yaml
@@ -77,7 +77,7 @@ ruleList:
level: WARNING
- type: statement.where.disallow-using-function
level: WARNING
- - type: statement.where.statement.query.minimum-plan-level
+ - type: statement.query.minimum-plan-level
level: WARNING
payload:
required: true
diff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yaml
index afcf4c82f3..1d4d6a18f8 100644
--- a/backend/plugin/advisor/config/sql-review.prod.yaml
+++ b/backend/plugin/advisor/config/sql-review.prod.yaml
@@ -77,7 +77,7 @@ ruleList:
level: WARNING
- type: statement.where.disallow-using-function
level: WARNING
- - type: statement.where.statement.query.minimum-plan-level
+ - type: statement.query.minimum-plan-level
level: WARNING
payload:
required: true
diff --git a/backend/plugin/advisor/mysql/advisor_statement_query_minumum_plan_level.go b/backend/plugin/advisor/mysql/advisor_statement_query_minumum_plan_level.go
index c48e52143c..29b0a8ecb0 100644
--- a/backend/plugin/advisor/mysql/advisor_statement_query_minumum_plan_level.go
+++ b/backend/plugin/advisor/mysql/advisor_statement_query_minumum_plan_level.go
@@ -1,6 +1,11 @@
package mysql
import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strings"
+
"github.com/antlr4-go/antlr/v4"
"github.com/pkg/errors"
@@ -32,14 +37,24 @@ func (*StatementQueryMinumumPlanLevelAdvisor) Check(ctx advisor.Context, _ strin
if err != nil {
return nil, err
}
+ payload, err := advisor.UnmarshalStringTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+
checker := &statementQueryMinumumPlanLevelChecker{
- level: level,
- title: string(ctx.Rule.Type),
+ level: level,
+ title: string(ctx.Rule.Type),
+ driver: ctx.Driver,
+ ctx: ctx.Context,
+ explainType: convertExplainTypeFromString(strings.ToUpper(payload.String)),
}
- for _, stmt := range stmtList {
- checker.baseLine = stmt.BaseLine
- antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)
+ if checker.driver != nil {
+ for _, stmt := range stmtList {
+ checker.baseLine = stmt.BaseLine
+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)
+ }
}
if len(checker.adviceList) == 0 {
@@ -53,17 +68,169 @@ func (*StatementQueryMinumumPlanLevelAdvisor) Check(ctx advisor.Context, _ strin
return checker.adviceList, nil
}
-// TODO(sql-review): implement me please.
type statementQueryMinumumPlanLevelChecker struct {
*mysql.BaseMySQLParserListener
- baseLine int
- adviceList []advisor.Advice
- level advisor.Status
- title string
- text string
+ baseLine int
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ driver *sql.DB
+ ctx context.Context
+ explainType ExplainType
+}
+
+type ExplainType int
+
+const (
+ ExplainTypeAll ExplainType = iota
+ ExplainTypeIndex
+ ExplainTypeRange
+ ExplainTypeRef
+ ExplainTypeEqRef
+ ExplainTypeConst
+)
+
+func (t ExplainType) String() string {
+ switch t {
+ case ExplainTypeAll:
+ return "ALL"
+ case ExplainTypeIndex:
+ return "INDEX"
+ case ExplainTypeRange:
+ return "RANGE"
+ case ExplainTypeRef:
+ return "REF"
+ case ExplainTypeEqRef:
+ return "EQ_REF"
+ case ExplainTypeConst:
+ return "CONST"
+ default:
+ return "UNKNOWN"
+ }
+}
+
+func convertExplainTypeFromString(explainTypeStr string) ExplainType {
+ switch explainTypeStr {
+ case "ALL":
+ return ExplainTypeAll
+ case "INDEX":
+ return ExplainTypeIndex
+ case "RANGE":
+ return ExplainTypeRange
+ case "REF":
+ return ExplainTypeRef
+ case "EQ_REF":
+ return ExplainTypeEqRef
+ case "CONST":
+ return ExplainTypeConst
+ default:
+ // Default to ALL if we don't recognize the explain type.
+ return ExplainTypeAll
+ }
}
func (checker *statementQueryMinumumPlanLevelChecker) EnterQuery(ctx *mysql.QueryContext) {
checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)
}
+
+func (checker *statementQueryMinumumPlanLevelChecker) EnterSelectStatement(ctx *mysql.SelectStatementContext) {
+ if _, ok := ctx.GetParent().(*mysql.SimpleStatementContext); !ok {
+ return
+ }
+
+ query := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)
+ res, err := advisor.Query(checker.ctx, checker.driver, fmt.Sprintf("EXPLAIN %s", query))
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.StatementExplainQueryFailed,
+ Title: checker.title,
+ Content: fmt.Sprintf("Failed to explain query: %s, with error: %s", query, err),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
+ })
+ } else {
+ explainTypes, err := getQueryExplainTypes(res)
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.Internal,
+ Title: checker.title,
+ Content: fmt.Sprintf("Failed to check explain type column: %s, with error: %s", query, err),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
+ })
+ } else if len(explainTypes) > 0 {
+ overused, overusedType := false, ExplainTypeAll
+ for _, explainType := range explainTypes {
+ if explainType < checker.explainType {
+ overused = true
+ overusedType = explainType
+ break
+ }
+ }
+ if overused {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.StatementUnwantedQueryPlanLevel,
+ Title: checker.title,
+ Content: fmt.Sprintf("Overused query plan level detected %s, minimum plan level: %s", overusedType.String(), checker.explainType.String()),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
+ })
+ }
+ }
+ }
+}
+
+func getQueryExplainTypes(res []any) ([]ExplainType, error) {
+ if len(res) != 3 {
+ return nil, errors.Errorf("expected 3 but got %d", len(res))
+ }
+ rowList, ok := res[2].([]any)
+ if !ok {
+ return nil, errors.Errorf("expected []any but got %t", res[2])
+ }
+ if len(rowList) < 1 {
+ return nil, errors.Errorf("not found any data")
+ }
+
+ // MySQL EXPLAIN statement result has 12 columns.
+ // 1. the column 4 is the data 'type'.
+ // We check all rows of the result to see if any of them has 'ALL' or 'index' in the 'type' column.
+ // 2. the column 11 is the 'Extra' column.
+ // If the 'Extra' column dose not contain
+ //
+ // mysql> explain delete from td;
+ // +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
+ // | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+ // +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
+ // | 1 | DELETE | td | NULL | ALL | NULL | NULL | NULL | NULL | 1 | 100.00 | NULL |
+ // +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
+ //
+ // mysql> explain insert into td select * from td;
+ // +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-----------------+
+ // | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+ // +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-----------------+
+ // | 1 | INSERT | td | NULL | ALL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+ // | 1 | SIMPLE | td | NULL | ALL | NULL | NULL | NULL | NULL | 1 | 100.00 | Using temporary |
+ // +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-----------------+
+
+ explainTypes := []ExplainType{}
+ for _, rowAny := range rowList {
+ row, ok := rowAny.([]any)
+ if !ok {
+ return nil, errors.Errorf("expected []any but got %t", row)
+ }
+ if len(row) != 12 {
+ return nil, errors.Errorf("expected 12 but got %d", len(row))
+ }
+ explainType, ok := row[4].(string)
+ if !ok {
+ // Skip the row if the type column is not a string.
+ continue
+ }
+ explainTypes = append(explainTypes, convertExplainTypeFromString(explainType))
+ }
+
+ return explainTypes, nil
+}
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 849f9fa48a..f9abc70027 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -296,6 +296,11 @@ type NumberTypeRulePayload struct {
Number int `json:"number"`
}
+// StringTypeRulePayload is the string type payload.
+type StringTypeRulePayload struct {
+ String string `json:"string"`
+}
+
// NamingCaseRulePayload is the payload for naming case rule.
type NamingCaseRulePayload struct {
// Upper is true means the case should be upper case, otherwise lower case.
@@ -421,6 +426,15 @@ func UnmarshalNumberTypeRulePayload(payload string) (*NumberTypeRulePayload, err
return &nlr, nil
}
+// UnmarshalStringTypeRulePayload will unmarshal payload to StringTypeRulePayload.
+func UnmarshalStringTypeRulePayload(payload string) (*StringTypeRulePayload, error) {
+ var slr StringTypeRulePayload
+ if err := json.Unmarshal([]byte(payload), &slr); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal string type rule payload %q", payload)
+ }
+ return &slr, nil
+}
+
// UnmarshalStringArrayTypeRulePayload will unmarshal payload to StringArrayTypeRulePayload.
func UnmarshalStringArrayTypeRulePayload(payload string) (*StringArrayTypeRulePayload, error) {
var trr StringArrayTypeRulePayload
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 862d281ca1..c2e2d52a18 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -412,7 +412,7 @@
"title": "Do not apply functions or perform calculations on indexed fields in the WHERE clause",
"description": "If you apply a function or perform a calculation on the indexed field, the database cannot use the index and has to scan the entire table instead."
},
- "statement-where-statement-query-minimum-plan-level": {
+ "statement-query-minimum-plan-level": {
"title": "Restrict the maximum level of query access method",
"description": "SQL performance optimization strives for constant (const) access, aiming for reference (ref) level as a baseline, with acceptable performance at range level.",
"component": {
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 39990da52f..f95aafffe2 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -412,7 +412,7 @@
"title": "No aplique funciones ni realice cálculos en campos indexados en la cláusula WHERE",
"description": "Si aplica una función o realiza un cálculo en el campo indexado, la base de datos no puede usar el índice y tiene que escanear toda la tabla."
},
- "statement-where-statement-query-minimum-plan-level": {
+ "statement-query-minimum-plan-level": {
"title": "Limitar el nivel máximo del método de acceso a la consulta",
"description": "La optimización del rendimiento de SQL busca un acceso constante (const), con el nivel de referencia (ref) como base, y un rendimiento aceptable a nivel de rango.",
"component": {
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 0a44cd4cc3..d3a209eb23 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -412,7 +412,7 @@
"title": "WHERE 句でインデックス付きフィールドに関数や計算を適用しないでください",
"description": "あなたがインデックス付けされたフィールドに関数や計算を適用すると、データベースはインデックスを使用できず、代わりにテーブル全体をスキャンする必要があります。"
},
- "statement-where-statement-query-minimum-plan-level": {
+ "statement-query-minimum-plan-level": {
"title": "クエリ アクセス メソッドの最大レベルを制限する",
"description": "SQL パフォーマンス最適化は、定数時間 (じょうすうじかん) アクセスを目指すもので、基準として参照 (さんしょう) レベルを置き、許容範囲として範囲 (はんい) レベルのパフォーマンスを想定します。",
"component": {
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index a8f7dcfc4d..1d931c55a3 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -412,7 +412,7 @@
"title": "Ch tránh sử dụng các hàm hoặc thực hiện tính toán trên các trường được lập chỉ mục trong mệnh đề WHERE",
"description": "Nếu bạn áp dụng một hàm hoặc thực hiện tính toán trên trường được lập chỉ mục, cơ sở dữ liệu không thể sử dụng chỉ mục và phải quét toàn bộ bảng."
},
- "statement-where-statement-query-minimum-plan-level": {
+ "statement-query-minimum-plan-level": {
"title": "Hạn chế mức truy cập tối đa của phương thức truy vấn",
"description": "Ch tối ưu hóa hiệu suất SQL hướng đến truy cập hằng số (const), đặt mục tiêu mức tham chiếu (ref) làm tiêu chuẩn, với hiệu suất chấp nhận được ở mức phạm vi (range).",
"component": {
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index ab1ceb81c3..7d13a92798 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -412,7 +412,7 @@
"title": "在 WHERE 子句中避免对索引字段应用函数或执行计算",
"description": "如果对索引字段应用函数或执行计算,则数据库无法使用索引,而必须扫描整个表。"
},
- "statement-where-statement-query-minimum-plan-level": {
+ "statement-query-minimum-plan-level": {
"title": "限制查询访问方法的最大级别",
"description": "在 SQL 性能优化中,追求常量访问速度,以引用级别作为基线,区间级别的性能尚可接受。",
"component": {
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index ce5d88efc7..f12cfbf245 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -248,7 +248,7 @@ ruleList:
category: STATEMENT
engineList:
- MYSQL
- - type: statement.where.statement.query.minimum-plan-level
+ - type: statement.query.minimum-plan-level
category: STATEMENT
engineList:
- MYSQL
diff --git a/frontend/src/types/sqlReview.ts b/frontend/src/types/sqlReview.ts
index cce070a39c..38bcdcf3d1 100644
--- a/frontend/src/types/sqlReview.ts
+++ b/frontend/src/types/sqlReview.ts
@@ -110,6 +110,12 @@ interface NumberLimitPayload {
number: number;
}
+// The string rule payload.
+// Used by the backend.
+interface StringPayload {
+ string: string;
+}
+
// The case rule payload.
// Used by the backend.
interface CasePayload {
@@ -385,9 +391,26 @@ export const convertPolicyRuleToRuleTemplate = (
);
switch (ruleTemplate.type) {
+ case "statement.query.minimum-plan-level":
+ if (!stringComponent) {
+ throw new Error(`Invalid rule ${ruleTemplate.type}`);
+ }
+
+ return {
+ ...res,
+ componentList: [
+ {
+ ...stringComponent,
+ payload: {
+ ...stringComponent.payload,
+ value: (payload as StringPayload).string,
+ } as StringPayload,
+ },
+ ],
+ individualConfigList,
+ };
// Following rules require STRING component.
case "table.drop-naming-convention":
- case "statement.where.statement.query.minimum-plan-level":
if (!stringComponent) {
throw new Error(`Invalid rule ${ruleTemplate.type}`);
}
@@ -624,9 +647,19 @@ const mergeIndividualConfigAsRule = (
)?.payload as StringArrayPayload | undefined;
switch (template.type) {
+ case "statement.query.minimum-plan-level":
+ if (!stringPayload) {
+ throw new Error(`Invalid rule ${template.type}`);
+ }
+
+ return {
+ ...base,
+ payload: {
+ string: stringPayload.value ?? stringPayload.default,
+ },
+ };
// Following rules require STRING component.
case "table.drop-naming-convention":
- case "statement.where.statement.query.minimum-plan-level":
if (!stringPayload) {
throw new Error(`Invalid rule ${template.type}`);
}