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: add max execution time rule for mysql&mariadb (#14015)
boojack6b8ad4a8b0a6
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex a2dae9e7ea..4c655e71c3 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -59,6 +59,7 @@ const (StatementOfflineDDL Code = 232StatementDisallowCrossDBQueries Code = 233StatementDisallowFunctionsAndCalculations Code = 234+ StatementNoMaxExecutionTime Code = 235// 301 ~ 399 naming error code// 301 table naming advisor error code.@@ -447,6 +448,9 @@ const (// MySQLStatementAddColumnWithoutPosition is an advisor type for MySQL checking no position in ADD COLUMN clause.MySQLStatementAddColumnWithoutPosition Type = "bb.plugin.advisor.mysql.statement.add-column-without-position"+ // MySQLStatementMaxExecutionTime is an advisor type for MySQL statement max execution time.+ MySQLStatementMaxExecutionTime Type = "bb.plugin.advisor.mysql.statement.max-execution-time"+// MySQLProcedureDisallowCreate is an advisor type for MySQL disallow create procedure.MySQLProcedureDisallowCreate Type = "bb.plugin.advisor.mysql.procedure.disallow-create"diff --git a/backend/plugin/advisor/mysql/advisor_stmt_max_execution_time.go b/backend/plugin/advisor/mysql/advisor_stmt_max_execution_time.gonew file mode 100644index 0000000000..44c8c290be--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_stmt_max_execution_time.go@@ -0,0 +1,126 @@+package mysql++import (+ "fmt"+ "strconv"+ "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 = (*MaxExecutionTimeAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementMaxExecutionTime, &MaxExecutionTimeAdvisor{})+ advisor.Register(storepb.Engine_MARIADB, advisor.MySQLStatementMaxExecutionTime, &MaxExecutionTimeAdvisor{})+}++// MaxExecutionTimeAdvisor is the advisor checking for the max execution time.+type MaxExecutionTimeAdvisor struct {+}++func (*MaxExecutionTimeAdvisor) Check(ctx advisor.Context, _ string) ([]*storepb.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to stmt list")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ systemVariable := "max_execution_time"+ // For MariaDB, the system variable is `max_statement_time`.+ if ctx.Rule.Engine == storepb.Engine_MARIADB {+ systemVariable = "max_statement_time"+ }+ checker := &maxExecutionTimeChecker{+ level: level,+ title: string(ctx.Rule.Type),+ systemVariable: systemVariable,+ adviceList: []*storepb.Advice{},+ }+ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }+ // If no system variable is set, we should set the advice.+ if !checker.hasSet {+ checker.setAdvice()+ }+ return checker.adviceList, nil+}++type maxExecutionTimeChecker struct {+ *mysql.BaseMySQLParserListener++ // The system variable name for max execution time.+ // For MySQL, it is `max_execution_time`.+ // For MariaDB, it is `max_statement_time`.+ systemVariable string+ hasSet bool++ baseLine int+ adviceList []*storepb.Advice+ level storepb.Advice_Status+ title string+}++func (checker *maxExecutionTimeChecker) EnterSimpleStatement(ctx *mysql.SimpleStatementContext) {+ // Skip if we have already found the system variable is set or the statement is a SET statement.+ if checker.hasSet || ctx.SetStatement() != nil {+ return+ }++ // The set max execution time statement should be the first statement in the SQL.+ // Otherwise, we will always set the advice.+ checker.setAdvice()+}++func (checker *maxExecutionTimeChecker) EnterSetStatement(ctx *mysql.SetStatementContext) {+ startOptionValueList := ctx.StartOptionValueList()+ if ctx.StartOptionValueList() == nil {+ return+ }++ variable, value := "", ""+ optionValueList := startOptionValueList.StartOptionValueListFollowingOptionType()+ if optionValueList != nil {+ tmp := optionValueList.OptionValueFollowingOptionType()+ if tmp != nil {+ if tmp.InternalVariableName() != nil && tmp.SetExprOrDefault() != nil {+ variable, value = tmp.InternalVariableName().GetText(), tmp.SetExprOrDefault().GetText()+ }+ }+ }+ optionValueNoOptionType := startOptionValueList.OptionValueNoOptionType()+ if optionValueNoOptionType != nil {+ if optionValueNoOptionType.InternalVariableName() != nil && optionValueNoOptionType.SetExprOrDefault() != nil {+ variable, value = optionValueNoOptionType.InternalVariableName().GetText(), optionValueNoOptionType.SetExprOrDefault().GetText()+ }+ }+ _, err := strconv.Atoi(value)+ if strings.ToLower(variable) == checker.systemVariable && err == nil {+ checker.hasSet = true+ }+}++func (checker *maxExecutionTimeChecker) setAdvice() {+ checker.adviceList = []*storepb.Advice{+ {+ Status: checker.level,+ Code: advisor.StatementNoMaxExecutionTime.Int32(),+ Title: checker.title,+ Content: fmt.Sprintf("The %s is not set", checker.systemVariable),+ },+ }+}diff --git a/backend/plugin/advisor/mysql/mysql_rules_test.go b/backend/plugin/advisor/mysql/mysql_rules_test.goindex dfb7c74fe1..caad79b1d0 100644--- a/backend/plugin/advisor/mysql/mysql_rules_test.go+++ b/backend/plugin/advisor/mysql/mysql_rules_test.go@@ -65,6 +65,8 @@ func TestMySQLRules(t *testing.T) {advisor.SchemaRuleStatementWhereDisallowFunctionsAndCaculations,// advisor.SchemaRuleStatementWhereMaximumLogicalOperatorCount enforces maximum number of logical operators in the where clause.advisor.SchemaRuleStatementWhereMaximumLogicalOperatorCount,+ // advisor.SchemaRuleStatementMaxExecutionTime enforce the maximum execution time.+ advisor.SchemaRuleStatementMaxExecutionTime,// Database related rules.// advisor.SchemaRuleDropEmptyDatabase enforce the MySQL support check if the database is empty before users drop it.diff --git a/backend/plugin/advisor/mysql/test/statement_max_execution_time.yaml b/backend/plugin/advisor/mysql/test/statement_max_execution_time.yamlnew file mode 100644index 0000000000..733c5ad18f--- /dev/null+++ b/backend/plugin/advisor/mysql/test/statement_max_execution_time.yaml@@ -0,0 +1,14 @@+- statement: SET MAX_EXECUTION_TIME = 1000; SELECT * FROM employee;+- statement: SET GLOBAL max_execution_time = 10; SELECT * FROM employee;+- statement: SELECT * FROM employee; SET max_execution_time = 1000;+ want:+ - status: 2+ code: 235+ title: statement.max-execution-time+ content: "The max_execution_time is not set"+- statement: SELECT * FROM t;+ want:+ - status: 2+ code: 235+ title: statement.max-execution-time+ content: "The max_execution_time is not set"diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 63de4e24bb..f18d6ec757 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -131,6 +131,8 @@ const (SchemaRuleStatementDisallowOfflineDDL = "statement.disallow-offline-ddl"// SchemaRuleStatementDisallowCrossDBQueries disallow cross database queries.SchemaRuleStatementDisallowCrossDBQueries = "statement.disallow-cross-db-queries"+ // SchemaRuleStatementMaxExecutionTime enforce the maximum execution time.+ SchemaRuleStatementMaxExecutionTime = "statement.max-execution-time"// SchemaRuleTableRequirePK require the table to have a primary key.SchemaRuleTableRequirePK SQLReviewRuleType = "table.require-pk"// SchemaRuleTableNoFK require the table disallow the foreign key.@@ -1480,6 +1482,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MSSQL {return MSSQLStatementDisallowCrossDBQueries, nil}+ case SchemaRuleStatementMaxExecutionTime:+ if engine == storepb.Engine_MYSQL || engine == storepb.Engine_MARIADB {+ return MySQLStatementMaxExecutionTime, nil+ }case SchemaRuleCommentLength:if engine == storepb.Engine_POSTGRES {return PostgreSQLCommentConvention, nildiff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 85bc547e80..1b8070d9ea 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -244,6 +244,9 @@ func RunSQLReviewRuleTest(t *testing.T, rule SQLReviewRuleType, dbType storepb.EadviceList, err := SQLReviewCheck(sm, tc.Statement, ruleList, ctx)// Sort adviceList by (line, content)sort.Slice(adviceList, func(i, j int) bool {+ if adviceList[i].GetStartPosition() == nil || adviceList[j].GetStartPosition() == nil {+ return adviceList[i].GetStartPosition() == nil+ }if adviceList[i].GetStartPosition().Line != adviceList[j].GetStartPosition().Line {return adviceList[i].GetStartPosition().Line < adviceList[j].GetStartPosition().Line}@@ -401,6 +404,7 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.EngSchemaRuleStatementDisallowMixDDLDML,SchemaRuleStatementPriorBackupCheck,SchemaRuleStatementJoinStrictColumnAttrs,+ SchemaRuleStatementMaxExecutionTime,SchemaRuleTableDisallowSetCharset,SchemaRuleStatementDisallowCrossDBQueries,SchemaRuleIndexNotRedundant:diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex b986f81f9f..d68c6fbd9a 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -543,6 +543,10 @@"title": "Check application backward compatibility","description": "Some changes may affect running applications, such as modifying the name of database object, adding new constraints, etc. This rule can avoid careless changes that lead to the failure of existing application. Suggestion error level: Warning"},+ "statement-max-execution-time": {+ "title": "Max execution time",+ "description": "Set the maximum execution time for SQL statements. If the execution time exceeds the limit, the statement will be terminated. Suggestion error level: Error"+ },"database-drop-empty-database": {"title": "Prohibit deleting non-empty database","description": "Deletion is only allowed when there are no tables in the database, which can greatly avoid accidental deletion. Suggested error level: Error"diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.jsonindex 7c9bc4c5cc..83f7f33901 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -543,6 +543,10 @@"title": "Comprobación de la compatibilidad con versiones anteriores de la aplicación","description": "Algunos cambios pueden afectar las aplicaciones en ejecución, como modificar el nombre del objeto de la base de datos, agregar nuevas restricciones, etc. Esta regla puede evitar cambios descuidados que lleven al fallo de la aplicación existente. Nivel de error sugerido: Advertencia"},+ "statement-max-execution-time": {+ "title": "Tiempo máximo de ejecución",+ "description": "Establezca el tiempo máximo de ejecución de las sentencias SQL. Si el tiempo de ejecución supera el límite, la sentencia finalizará. Nivel de error sugerido: Error"+ },"database-drop-empty-database": {"title": "Prohibir eliminar base de datos no vacía","description": "Solo se permite la eliminación cuando no hay tablas en la base de datos, lo que puede evitar la eliminación accidental. Nivel de error sugerido: Error"diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.jsonindex c29d73c713..fad180d524 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -543,6 +543,10 @@"title": "アプリケーションの後方互換性を確認する","description": "一部の変更は実行中のアプリケーションに影響を与える可能性があります。データベースオブジェクトの名前の変更や新しい制約の追加などが該当します。このルールにより、既存のアプリケーションの障害を防ぐことができます。提案されるエラーレベル:警告"},+ "statement-max-execution-time": {+ "title": "最大実行時間",+ "description": "SQL 文の最大実行時間を設定します。実行時間が制限を超えると、文は終了します。提案エラー レベル: エラー"+ },"database-drop-empty-database": {"title": "空でないデータベースの削除を禁止する","description": "データベース内にテーブルが存在しない場合のみ削除が許可されます。これにより、誤って削除することを大幅に防ぐことができます。提案されるエラーレベル:エラー"diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.jsonindex c87fca9406..37eda533b7 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -543,6 +543,10 @@"title": "检查应用向后兼容性","description": "某些变更可能影响现有应用功能,例如修改数据库对象名,增加新的约束等,此规范可避免不谨慎变更导致现有应用运行失败。建议错误等级:警告"},+ "statement-max-execution-time": {+ "title": "最大执行时间",+ "description": "设置SQL语句的最大执行时间,如果执行时间超过限制,语句将被终止。建议错误级别:错误"+ },"database-drop-empty-database": {"title": "禁止删除非空数据库","description": "只有当数据库中不包含任何表时才允许被删除,这能最大程度避免误删除的发生。建议错误等级:错误"diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex e599f37a1b..0618289dae 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -652,6 +652,12 @@- type: statement.disallow-cross-db-queriescategory: STATEMENTengine: MSSQL+- type: statement.max-execution-time+ category: STATEMENT+ engine: MYSQL+- type: statement.max-execution-time+ category: STATEMENT+ engine: MARIADB- type: naming.fully-qualifiedcategory: NAMINGengine: POSTGRESdiff --git a/frontend/src/types/sql-review.prod.yaml b/frontend/src/types/sql-review.prod.yamlindex 80d6127bf4..fc4dcf4dd1 100644--- a/frontend/src/types/sql-review.prod.yaml+++ b/frontend/src/types/sql-review.prod.yaml@@ -521,6 +521,12 @@ ruleList:- type: statement.disallow-cross-db-querieslevel: WARNINGengine: MSSQL+ - type: statement.max-execution-time+ level: ERROR+ engine: MYSQL+ - type: statement.max-execution-time+ level: ERROR+ engine: MARIADB- type: naming.fully-qualifiedlevel: WARNINGengine: POSTGRES