Skip to content

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

chore: implement disallow using temporary rule for MySQL (#11000)

boojacke5bac9cc0221
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index 54d3b92652..0b0a2f56b6 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -218,6 +218,9 @@ const (
// MySQLStatementDisallowUsingFilesort is an advisor type for MySQL disallow using filesort in execution plan.
MySQLStatementDisallowUsingFilesort Type = "bb.plugin.advisor.mysql.statement.disallow-using-filesort"
+ // MySQLStatementDisallowUsingTemporary is an advisor type for MySQL disallow using temporary in execution plan.
+ MySQLStatementDisallowUsingTemporary Type = "bb.plugin.advisor.mysql.statement.disallow-using-temporary"
+
// MySQLInsertRowLimit is an advisor type for MySQL to limit INSERT rows.
MySQLInsertRowLimit Type = "bb.plugin.advisor.mysql.insert.row-limit"
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index e51cd773b0..896b818aa3 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -44,6 +44,7 @@ const (
StatementCheckSetRoleVariable Code = 217
StatementExplainQueryFailed Code = 218
StatementHasUsingFilesort Code = 219
+ StatementHasUsingTemporary Code = 220
// 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 8d3e41b5aa..2e3037be1b 100644
--- a/backend/plugin/advisor/config/sql-review.dev.yaml
+++ b/backend/plugin/advisor/config/sql-review.dev.yaml
@@ -65,6 +65,8 @@ ruleList:
level: WARNING
- type: statement.disallow-using-filesort
level: WARNING
+ - type: statement.disallow-using-temporary
+ level: WARNING
- type: naming.table
level: WARNING
payload:
diff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yaml
index 63c37258f2..2214470506 100644
--- a/backend/plugin/advisor/config/sql-review.prod.yaml
+++ b/backend/plugin/advisor/config/sql-review.prod.yaml
@@ -65,6 +65,8 @@ ruleList:
level: WARNING
- type: statement.disallow-using-filesort
level: WARNING
+ - type: statement.disallow-using-temporary
+ level: WARNING
- type: naming.table
level: WARNING
payload:
diff --git a/backend/plugin/advisor/mysql/advisor_statement_disallow_using_filesort.go b/backend/plugin/advisor/mysql/advisor_statement_disallow_using_filesort.go
index e1552a9577..04f0a8ba8b 100644
--- a/backend/plugin/advisor/mysql/advisor_statement_disallow_using_filesort.go
+++ b/backend/plugin/advisor/mysql/advisor_statement_disallow_using_filesort.go
@@ -90,13 +90,13 @@ func (checker *disallowUsingFilesortChecker) EnterSelectStatement(ctx *mysql.Sel
Line: checker.baseLine + ctx.GetStart().GetLine(),
})
} else {
- hasUsingFilesort, tables, err := hasUsingFilesortExtraColumn(res)
+ hasUsingFilesort, tables, err := hasUsingFilesortInExtraColumn(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 using filesort: %s, with error: %s", query, err),
+ Content: fmt.Sprintf("Failed to check extra column: %s, with error: %s", query, err),
Line: checker.baseLine + ctx.GetStart().GetLine(),
})
} else if hasUsingFilesort {
@@ -111,7 +111,7 @@ func (checker *disallowUsingFilesortChecker) EnterSelectStatement(ctx *mysql.Sel
}
}
-func hasUsingFilesortExtraColumn(res []any) (bool, string, error) {
+func hasUsingFilesortInExtraColumn(res []any) (bool, string, error) {
if len(res) != 3 {
return false, "", errors.Errorf("expected 3 but got %d", len(res))
}
diff --git a/backend/plugin/advisor/mysql/advisor_statement_disallow_using_temporary.go b/backend/plugin/advisor/mysql/advisor_statement_disallow_using_temporary.go
new file mode 100644
index 0000000000..ace31b3f05
--- /dev/null
+++ b/backend/plugin/advisor/mysql/advisor_statement_disallow_using_temporary.go
@@ -0,0 +1,166 @@
+package mysql
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strings"
+
+ "github.com/antlr4-go/antlr/v4"
+ mysql "github.com/bytebase/mysql-parser"
+ "github.com/pkg/errors"
+
+ "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 = (*StatementDisallowUsingTemporaryAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementDisallowUsingTemporary, &StatementDisallowUsingTemporaryAdvisor{})
+}
+
+// StatementDisallowUsingTemporaryAdvisor is the advisor checking for using temporary.
+type StatementDisallowUsingTemporaryAdvisor struct {
+}
+
+func (*StatementDisallowUsingTemporaryAdvisor) 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 ParseResult")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &disallowUsingTemporaryChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ driver: ctx.Driver,
+ ctx: ctx.Context,
+ }
+
+ if checker.driver != nil {
+ 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 disallowUsingTemporaryChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ baseLine int
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ driver *sql.DB
+ ctx context.Context
+}
+
+func (checker *disallowUsingTemporaryChecker) 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 {
+ hasUsingTemporary, tables, err := hasUsingTemporaryInExtraColumn(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 extra column: %s, with error: %s", query, err),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
+ })
+ } else if hasUsingTemporary {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.StatementHasUsingTemporary,
+ Title: checker.title,
+ Content: fmt.Sprintf("Using temporary detected on table(s): %s", tables),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
+ })
+ }
+ }
+}
+
+func hasUsingTemporaryInExtraColumn(res []any) (bool, string, error) {
+ if len(res) != 3 {
+ return false, "", errors.Errorf("expected 3 but got %d", len(res))
+ }
+ rowList, ok := res[2].([]any)
+ if !ok {
+ return false, "", errors.Errorf("expected []any but got %t", res[2])
+ }
+ if len(rowList) < 1 {
+ return false, "", 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 |
+ // +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-----------------+
+
+ var tables []string
+ for _, rowAny := range rowList {
+ row, ok := rowAny.([]any)
+ if !ok {
+ return false, "", errors.Errorf("expected []any but got %t", row)
+ }
+ if len(row) != 12 {
+ return false, "", errors.Errorf("expected 12 but got %d", len(row))
+ }
+ if row[11] == "Using temporary" {
+ tables = append(tables, row[2].(string))
+ }
+ }
+
+ if len(tables) == 0 {
+ return false, "", nil
+ }
+
+ return true, strings.Join(tables, ", "), nil
+}
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 62d206997b..4caf66a852 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -103,6 +103,8 @@ const (
SchemaRuleStatementCheckSetRoleVariable = "statement.check-set-role-variable"
// SchemaRuleStatementDisallowUsingFilesort disallow using filesort in execution plan.
SchemaRuleStatementDisallowUsingFilesort = "statement.disallow-using-filesort"
+ // SchemaRuleStatementDisallowUsingTemporary disallow using temporary in execution plan.
+ SchemaRuleStatementDisallowUsingTemporary = "statement.disallow-using-temporary"
// SchemaRuleTableRequirePK require the table to have a primary key.
SchemaRuleTableRequirePK SQLReviewRuleType = "table.require-pk"
@@ -1375,6 +1377,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
if engine == storepb.Engine_MYSQL {
return MySQLStatementDisallowUsingFilesort, nil
}
+ case SchemaRuleStatementDisallowUsingTemporary:
+ if engine == storepb.Engine_MYSQL {
+ return MySQLStatementDisallowUsingTemporary, nil
+ }
case SchemaRuleCharsetAllowlist:
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 4aed14b6a7..6d9a8b91ae 100644
--- a/backend/plugin/advisor/utils_for_tests.go
+++ b/backend/plugin/advisor/utils_for_tests.go
@@ -328,6 +328,7 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.Eng
SchemaRuleStatementInsertDisallowOrderByRand,
SchemaRuleStatementDMLDryRun,
SchemaRuleStatementDisallowUsingFilesort,
+ SchemaRuleStatementDisallowUsingTemporary,
SchemaRuleTableRequirePK,
SchemaRuleTableNoFK,
SchemaRuleTableDisallowPartition,