Skip to content

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

feat(sql-review-rule): require algorithm/lock options for mysql&mariad (#14100)

boojacke525b7e52da4
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index 4c655e71c3..62842a650c 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -60,6 +60,8 @@ const (
StatementDisallowCrossDBQueries Code = 233
StatementDisallowFunctionsAndCalculations Code = 234
StatementNoMaxExecutionTime Code = 235
+ StatementNoAlgorithmOption Code = 236
+ StatementNoLockOption Code = 237
// 301 ~ 399 naming error code
// 301 table naming advisor error code.
@@ -451,6 +453,12 @@ const (
// MySQLStatementMaxExecutionTime is an advisor type for MySQL statement max execution time.
MySQLStatementMaxExecutionTime Type = "bb.plugin.advisor.mysql.statement.max-execution-time"
+ // MySQLStatementRequireAlgorithmOption is an advisor type for MySQL statement require algorithm option for online DDL.
+ MySQLStatementRequireAlgorithmOption Type = "bb.plugin.advisor.mysql.statement.require-algorithm-option"
+
+ // MySQLStatementRequireLockOption is an advisor type for MySQL statement require lock option for online DDL.
+ MySQLStatementRequireLockOption Type = "bb.plugin.advisor.mysql.statement.require-lock-option"
+
// 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_require_algorithm_or_lock_options.go b/backend/plugin/advisor/mysql/advisor_stmt_require_algorithm_or_lock_options.go
new file mode 100644
index 0000000000..458ae89ab5
--- /dev/null
+++ b/backend/plugin/advisor/mysql/advisor_stmt_require_algorithm_or_lock_options.go
@@ -0,0 +1,133 @@
+package mysql
+
+import (
+ "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 = (*RequireAlgorithmOrLockOptionAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementRequireAlgorithmOption, &RequireAlgorithmOrLockOptionAdvisor{})
+ advisor.Register(storepb.Engine_MARIADB, advisor.MySQLStatementRequireAlgorithmOption, &RequireAlgorithmOrLockOptionAdvisor{})
+
+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementRequireLockOption, &RequireAlgorithmOrLockOptionAdvisor{})
+ advisor.Register(storepb.Engine_MARIADB, advisor.MySQLStatementRequireLockOption, &RequireAlgorithmOrLockOptionAdvisor{})
+}
+
+// RequireAlgorithmOrLockOptionAdvisor is the advisor checking for the max execution time.
+type RequireAlgorithmOrLockOptionAdvisor struct {
+}
+
+func (*RequireAlgorithmOrLockOptionAdvisor) 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
+ }
+
+ requiredOption, errorCode := "ALGORITHM", advisor.StatementNoAlgorithmOption
+ if ctx.Rule.Type == string(advisor.SchemaRuleStatementRequireLockOption) {
+ requiredOption, errorCode = "LOCK", advisor.StatementNoLockOption
+ }
+ checker := &RequireAlgorithmOptionChecker{
+ requiredOption: requiredOption,
+ level: level,
+ title: string(ctx.Rule.Type),
+ adviceList: []*storepb.Advice{},
+ errorCode: errorCode,
+ }
+ for _, stmt := range stmtList {
+ checker.baseLine = stmt.BaseLine
+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)
+ }
+ return checker.adviceList, nil
+}
+
+type RequireAlgorithmOptionChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ requiredOption string
+ hasOption bool
+ inAlterTableStatement bool
+
+ errorCode advisor.Code
+ baseLine int
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ text string
+ line int
+}
+
+func (checker *RequireAlgorithmOptionChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ checker.inAlterTableStatement = true
+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)
+ checker.line = ctx.GetStart().GetLine()
+}
+
+func (checker *RequireAlgorithmOptionChecker) ExitAlterTable(*mysql.AlterTableContext) {
+ if !checker.hasOption {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: int32(checker.errorCode),
+ Title: checker.title,
+ Content: "ALTER TABLE statement should include " + checker.requiredOption + " option",
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + checker.line),
+ },
+ })
+ }
+ checker.inAlterTableStatement = false
+ checker.hasOption = false
+}
+
+func (checker *RequireAlgorithmOptionChecker) EnterAlterTableActions(ctx *mysql.AlterTableActionsContext) {
+ if !checker.inAlterTableStatement {
+ return
+ }
+
+ modifierList := []mysql.IAlterCommandsModifierContext{}
+ if ctx.AlterCommandsModifierList() != nil {
+ modifierList = append(modifierList, ctx.AlterCommandsModifierList().AllAlterCommandsModifier()...)
+ }
+ if ctx.AlterCommandList() != nil {
+ if ctx.AlterCommandList().AlterCommandsModifierList() != nil {
+ modifierList = append(modifierList, ctx.AlterCommandList().AlterCommandsModifierList().AllAlterCommandsModifier()...)
+ }
+ if ctx.AlterCommandList().AlterList() != nil {
+ modifierList = append(modifierList, ctx.AlterCommandList().AlterList().AllAlterCommandsModifier()...)
+ }
+ }
+ for _, modifier := range modifierList {
+ if checker.requiredOption == "ALGORITHM" && modifier.AlterAlgorithmOption() != nil {
+ if modifier.AlterAlgorithmOption().Identifier() != nil {
+ algorithmOptionValue := mysqlparser.NormalizeMySQLIdentifier(modifier.AlterAlgorithmOption().Identifier())
+ // Don't need to check the value of the algorithm option right now.
+ if algorithmOptionValue != "" {
+ checker.hasOption = true
+ }
+ }
+ }
+ if checker.requiredOption == "LOCK" && modifier.AlterLockOption() != nil {
+ if modifier.AlterLockOption().Identifier() != nil {
+ lockOptionValue := mysqlparser.NormalizeMySQLIdentifier(modifier.AlterLockOption().Identifier())
+ // Don't need to check the value of the lock option right now.
+ if lockOptionValue != "" {
+ checker.hasOption = true
+ }
+ }
+ }
+ }
+}
diff --git a/backend/plugin/advisor/mysql/mysql_rules_test.go b/backend/plugin/advisor/mysql/mysql_rules_test.go
index caad79b1d0..4ace55f508 100644
--- a/backend/plugin/advisor/mysql/mysql_rules_test.go
+++ b/backend/plugin/advisor/mysql/mysql_rules_test.go
@@ -67,6 +67,10 @@ func TestMySQLRules(t *testing.T) {
advisor.SchemaRuleStatementWhereMaximumLogicalOperatorCount,
// advisor.SchemaRuleStatementMaxExecutionTime enforce the maximum execution time.
advisor.SchemaRuleStatementMaxExecutionTime,
+ // advisor.SchemaRuleStatementRequireAlgorithmOption require the algorithm option in the alter table statement.
+ advisor.SchemaRuleStatementRequireAlgorithmOption,
+ // advisor.SchemaRuleStatementRequireLockOption require the lock option in the alter table statement.
+ advisor.SchemaRuleStatementRequireLockOption,
// 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_require_algorithm_option.yaml b/backend/plugin/advisor/mysql/test/statement_require_algorithm_option.yaml
new file mode 100644
index 0000000000..a084651fff
--- /dev/null
+++ b/backend/plugin/advisor/mysql/test/statement_require_algorithm_option.yaml
@@ -0,0 +1,13 @@
+- statement: |
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN c INT, ALGORITHM=INSTANT, LOCK=NONE;
+- statement: |
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN c INT;
+ want:
+ - status: 2
+ code: 236
+ title: statement.require-algorithm-option
+ content: "ALTER TABLE statement should include ALGORITHM option"
+ startposition:
+ line: 2
diff --git a/backend/plugin/advisor/mysql/test/statement_require_lock_option.yaml b/backend/plugin/advisor/mysql/test/statement_require_lock_option.yaml
new file mode 100644
index 0000000000..14f0389a0c
--- /dev/null
+++ b/backend/plugin/advisor/mysql/test/statement_require_lock_option.yaml
@@ -0,0 +1,24 @@
+- statement: |
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN c INT, ALGORITHM=INSTANT, LOCK=NONE;
+- statement: |
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN c INT;
+ want:
+ - status: 2
+ code: 237
+ title: statement.require-lock-option
+ content: "ALTER TABLE statement should include LOCK option"
+ startposition:
+ line: 2
+- statement: |
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN c INT, LOCK=NONE;
+ ALTER TABLE t ADD COLUMN d INT;
+ want:
+ - status: 2
+ code: 237
+ title: statement.require-lock-option
+ content: "ALTER TABLE statement should include LOCK option"
+ startposition:
+ line: 3
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index f18d6ec757..28a101e1f8 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -133,6 +133,10 @@ const (
SchemaRuleStatementDisallowCrossDBQueries = "statement.disallow-cross-db-queries"
// SchemaRuleStatementMaxExecutionTime enforce the maximum execution time.
SchemaRuleStatementMaxExecutionTime = "statement.max-execution-time"
+ // SchemaRuleStatementRequireAlgorithmOption require set ALGORITHM option in ALTER TABLE statement.
+ SchemaRuleStatementRequireAlgorithmOption = "statement.require-algorithm-option"
+ // SchemaRuleStatementRequireLockOption require set LOCK option in ALTER TABLE statement.
+ SchemaRuleStatementRequireLockOption = "statement.require-lock-option"
// SchemaRuleTableRequirePK require the table to have a primary key.
SchemaRuleTableRequirePK SQLReviewRuleType = "table.require-pk"
// SchemaRuleTableNoFK require the table disallow the foreign key.
@@ -1486,6 +1490,14 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
if engine == storepb.Engine_MYSQL || engine == storepb.Engine_MARIADB {
return MySQLStatementMaxExecutionTime, nil
}
+ case SchemaRuleStatementRequireAlgorithmOption:
+ if engine == storepb.Engine_MYSQL || engine == storepb.Engine_MARIADB {
+ return MySQLStatementRequireAlgorithmOption, nil
+ }
+ case SchemaRuleStatementRequireLockOption:
+ if engine == storepb.Engine_MYSQL || engine == storepb.Engine_MARIADB {
+ return MySQLStatementRequireLockOption, nil
+ }
case SchemaRuleCommentLength:
if engine == storepb.Engine_POSTGRES {
return PostgreSQLCommentConvention, nil
diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.go
index 1b8070d9ea..58250dbf94 100644
--- a/backend/plugin/advisor/utils_for_tests.go
+++ b/backend/plugin/advisor/utils_for_tests.go
@@ -405,6 +405,8 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.Eng
SchemaRuleStatementPriorBackupCheck,
SchemaRuleStatementJoinStrictColumnAttrs,
SchemaRuleStatementMaxExecutionTime,
+ SchemaRuleStatementRequireAlgorithmOption,
+ SchemaRuleStatementRequireLockOption,
SchemaRuleTableDisallowSetCharset,
SchemaRuleStatementDisallowCrossDBQueries,
SchemaRuleIndexNotRedundant:
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 8814961749..b81b61d238 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -3791,4 +3791,4 @@
"setup": {
"self": "Configuración"
}
-}
+}
\ No newline at end of file
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 122e7d3694..35325210ac 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -3791,4 +3791,4 @@
"setup": {
"self": "設定"
}
-}
+}
\ No newline at end of file
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index d68c6fbd9a..cb2752f39a 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -547,6 +547,14 @@
"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"
},
+ "statement-require-algorithm-option": {
+ "title": "Require specifying the ALGORITHM option in ALTER TABLE statements",
+ "description": "Specifying the ALGORITHM option in ALTER TABLE statements ensures more control over how table changes are applied, minimizing potential disruptions by avoiding full table copies or locks. It helps optimize performance and reduce downtime during schema modifications. Suggested error level: Warning."
+ },
+ "statement-require-lock-option": {
+ "title": "Require specifying the LOCK option in ALTER TABLE statements",
+ "description": "The LOCK option in ALTER TABLE statements allows you to control the level of locking during schema changes, helping to prevent unnecessary table locks and ensuring better concurrency. Proper use of this option can significantly reduce the impact of DDL operations on active queries. Suggested error level: Warning."
+ },
"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.json
index 83f7f33901..246e8f9bf7 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -547,6 +547,14 @@
"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"
},
+ "statement-require-algorithm-option": {
+ "title": "Requiere especificar la opción ALGORITMO en las instrucciones ALTER TABLE",
+ "description": "La especificación de la opción ALGORITHM en las instrucciones ALTER TABLE garantiza un mayor control sobre cómo se aplican los cambios en las tablas, lo que minimiza las posibles interrupciones al evitar copias o bloqueos completos de las tablas. Ayuda a optimizar el rendimiento y reducir el tiempo de inactividad durante las modificaciones del esquema. Nivel de error sugerido: Advertencia."
+ },
+ "statement-require-lock-option": {
+ "title": "Requerir especificar la opción LOCK en las instrucciones ALTER TABLE",
+ "description": "La opción LOCK en las instrucciones ALTER TABLE le permite controlar el nivel de bloqueo durante los cambios de esquema, lo que ayuda a evitar bloqueos de tablas innecesarios y garantiza una mejor concurrencia. El uso adecuado de esta opción puede reducir significativamente el impacto de las operaciones DDL en las consultas activas. Nivel de error sugerido: Advertencia."
+ },
"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.json
index fad180d524..d5f5df5162 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -547,6 +547,14 @@
"title": "最大実行時間",
"description": "SQL 文の最大実行時間を設定します。実行時間が制限を超えると、文は終了します。提案エラー レベル: エラー"
},
+ "statement-require-algorithm-option": {
+ "title": "ALTER TABLE文でALGORITHMオプションを指定する必要がある",
+ "description": "ALTER TABLE ステートメントで ALGORITHM オプションを指定すると、テーブルの変更の適用方法をより細かく制御できるようになり、テーブル全体のコピーやロックを回避することで潜在的な中断を最小限に抑えることができます。これにより、パフォーマンスが最適化され、スキーマ変更中のダウンタイムが短縮されます。推奨されるエラー レベル: 警告。"
+ },
+ "statement-require-lock-option": {
+ "title": "ALTER TABLE文でLOCKオプションを指定する必要がある",
+ "description": "ALTER TABLE ステートメントの LOCK オプションを使用すると、スキーマ変更時のロック レベルを制御できるため、不要なテーブル ロックを防止し、同時実行性を向上させることができます。このオプションを適切に使用すると、アクティブなクエリに対する DDL 操作の影響を大幅に軽減できます。推奨されるエラー レベル: 警告。"
+ },
"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.json
index 37eda533b7..085c47677c 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -547,6 +547,14 @@
"title": "最大执行时间",
"description": "设置SQL语句的最大执行时间,如果执行时间超过限制,语句将被终止。建议错误级别:错误"
},
+ "statement-require-algorithm-option": {
+ "title": "需要在 ALTER TABLE 语句中指定 ALGORITHM 选项",
+ "description": "在 ALTER TABLE 语句中指定 ALGORITHM 选项可确保更好地控制表更改的应用方式,通过避免全表复制或锁定来最大限度地减少潜在的中断。它有助于优化性能并减少 ALTER TABLE 操作的停机时间。建议的错误级别:警告。"
+ },
+ "statement-require-lock-option": {
+ "title": "需要在 ALTER TABLE 语句中指定 LOCK 选项",
+ "description": "ALTER TABLE 语句中的 LOCK 选项允许您控制架构更改期间的锁定级别,有助于防止不必要的表锁定并确保更好的并发性。正确使用此选项可以显著减少 ALTER TABLE 操作对活动查询的影响。建议的错误级别:警告。"
+ },
"database-drop-empty-database": {
"title": "禁止删除非空数据库",
"description": "只有当数据库中不包含任何表时才允许被删除,这能最大程度避免误删除的发生。建议错误等级:错误"
@@ -687,4 +695,4 @@
"warning": "警告",
"disabled": "禁用"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 155d42ac6f..e316c8b4c5 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3791,4 +3791,4 @@
"setup": {
"self": "设置"
}
-}
+}
\ No newline at end of file
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index 0618289dae..eb106696d4 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -658,6 +658,18 @@
- type: statement.max-execution-time
category: STATEMENT
engine: MARIADB
+- type: statement.require-algorithm-option
+ category: STATEMENT
+ engine: MYSQL
+- type: statement.require-algorithm-option
+ category: STATEMENT
+ engine: MARIADB
+- type: statement.require-lock-option
+ category: STATEMENT
+ engine: MYSQL
+- type: statement.require-lock-option
+ category: STATEMENT
+ engine: MARIADB
- type: naming.fully-qualified
category: NAMING
engine: POSTGRES
diff --git a/frontend/src/types/sql-review.prod.yaml b/frontend/src/types/sql-review.prod.yaml
index fc4dcf4dd1..784cfd6454 100644
--- a/frontend/src/types/sql-review.prod.yaml
+++ b/frontend/src/types/sql-review.prod.yaml
@@ -527,6 +527,18 @@ ruleList:
- type: statement.max-execution-time
level: ERROR
engine: MARIADB
+ - type: statement.require-algorithm-option
+ level: ERROR
+ engine: MYSQL
+ - type: statement.require-algorithm-option
+ level: ERROR
+ engine: MARIADB
+ - type: statement.require-lock-option
+ level: ERROR
+ engine: MYSQL
+ - type: statement.require-lock-option
+ level: ERROR
+ engine: MARIADB
- type: naming.fully-qualified
level: WARNING
engine: POSTGRES
diff --git a/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue b/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
index f12bb2cdec..52e5bf2f68 100644
--- a/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
+++ b/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
@@ -17,14 +17,13 @@
class="flex flex-col gap-y-2 items-start md:items-center gap-x-2 justify-center md:flex-row"
>
<BBTextField
- class="flex-1 !text-xl md:!text-2xl py-0.5 !pl-0 px-0.5 font-bold truncate sql-review-title"
+ class="flex-1 !text-xl !pl-0 px-0.5 font-bold truncate sql-review-title"
:disabled="!hasPermission"
:required="true"
:focus-on-mount="false"
:ends-on-enter="true"
:bordered="state.editingTitle"
:value="reviewPolicy.name"
- size="large"
@on-focus="state.editingTitle = true"
@end-editing="changeName"
/>