Skip to content

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

feat(sql-review): new rule for checking no position in add column clause (#11953)

He Wange197b56d9e81
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index 405da24023..6d90a0ab85 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -284,6 +284,9 @@ const (
// MySQLStatementPriorBackupCheck is an advisor type for MySQL prior backup check.
MySQLStatementPriorBackupCheck Type = "bb.plugin.advisor.mysql.statement.prior-backup-check"
+ // 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"
+
// 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/code.go b/backend/plugin/advisor/code.go
index 7e8762cc84..896ab1abb2 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -55,6 +55,7 @@ const (
StatementPriorBackupCheck Code = 228
StatementAddFKWithValidation Code = 229
StatementNonTransactional Code = 230
+ StatementAddColumnWithPosition Code = 231
// 301 ~ 399 naming error code
// 301 table naming advisor error code.
diff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yaml
index 14de3bb8a4..66bc6b02d5 100644
--- a/backend/plugin/advisor/config/sql-review.prod.yaml
+++ b/backend/plugin/advisor/config/sql-review.prod.yaml
@@ -114,6 +114,8 @@ ruleList:
level: WARNING
- type: statement.prior-backup-check
level: ERROR
+ - type: statement.add-column-without-position
+ level: WARNING
- type: naming.fully-qualified
level: WARNING
- type: naming.table
diff --git a/backend/plugin/advisor/mysql/advisor_statement_add_column_without_position.go b/backend/plugin/advisor/mysql/advisor_statement_add_column_without_position.go
new file mode 100644
index 0000000000..cf9e5eba1f
--- /dev/null
+++ b/backend/plugin/advisor/mysql/advisor_statement_add_column_without_position.go
@@ -0,0 +1,148 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/antlr4-go/antlr/v4"
+ "github.com/pkg/errors"
+
+ mysql "github.com/bytebase/mysql-parser"
+
+ "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 = (*StatementAddColumnWithoutPositionAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLStatementAddColumnWithoutPosition, &StatementAddColumnWithoutPositionAdvisor{})
+}
+
+// StatementAddColumnWithoutPositionAdvisor is the advisor checking for checking no position in ADD COLUMN clause.
+type StatementAddColumnWithoutPositionAdvisor struct {
+}
+
+// Check checks for checking no position in ADD COLUMN clause.
+func (*StatementAddColumnWithoutPositionAdvisor) 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 parser result")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &statementAddColumnWithoutPositionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ 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 statementAddColumnWithoutPositionChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ baseLine int
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+}
+
+func (checker *statementAddColumnWithoutPositionChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ if !mysqlparser.IsTopMySQLRule(&ctx.BaseParserRuleContext) {
+ return
+ }
+ if ctx.AlterTableActions() == nil {
+ return
+ }
+ if ctx.AlterTableActions().AlterCommandList() == nil {
+ return
+ }
+ if ctx.AlterTableActions().AlterCommandList().AlterList() == nil {
+ return
+ }
+ if ctx.TableRef() == nil {
+ return
+ }
+
+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
+ if tableName == "" {
+ return
+ }
+
+ for _, item := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {
+ if item == nil || item.ADD_SYMBOL() == nil {
+ continue
+ }
+
+ var position string
+
+ switch {
+ case item.Identifier() != nil && item.FieldDefinition() != nil:
+ position = getPosition(item.Place())
+ case item.OPEN_PAR_SYMBOL() != nil && item.TableElementList() != nil:
+ for _, tableElement := range item.TableElementList().AllTableElement() {
+ if tableElement.ColumnDefinition() == nil {
+ continue
+ }
+ if tableElement.ColumnDefinition().FieldDefinition() == nil {
+ continue
+ }
+
+ position = getPosition(item.Place())
+ if len(position) != 0 {
+ break
+ }
+ }
+ }
+
+ if len(position) != 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.StatementAddColumnWithPosition,
+ Title: checker.title,
+ Content: fmt.Sprintf("add column with position \"%s\"", position),
+ Line: checker.baseLine + ctx.GetStart().GetLine(),
+ })
+ }
+ }
+}
+
+func getPosition(ctx mysql.IPlaceContext) string {
+ if ctx == nil {
+ return ""
+ }
+ place, ok := ctx.(*mysql.PlaceContext)
+ if !ok || place == nil {
+ return ""
+ }
+
+ switch {
+ case place.FIRST_SYMBOL() != nil:
+ return "FIRST"
+ case place.AFTER_SYMBOL() != nil:
+ return "AFTER"
+ default:
+ return ""
+ }
+}
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index db31dff4da..d49b34da8e 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -135,6 +135,8 @@ const (
SchemaRuleStatementPriorBackupCheck = "statement.prior-backup-check"
// SchemaRuleStatementNonTransactional checks for non-transactional statements.
SchemaRuleStatementNonTransactional = "statement.non-transactional"
+ // SchemaRuleStatementAddColumnWithoutPosition check no position in ADD COLUMN clause.
+ SchemaRuleStatementAddColumnWithoutPosition = "statement.add-column-without-position"
// SchemaRuleTableRequirePK require the table to have a primary key.
SchemaRuleTableRequirePK SQLReviewRuleType = "table.require-pk"
@@ -1497,6 +1499,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
case storepb.Engine_POSTGRES:
return PostgreSQLStatementPriorBackupCheck, nil
}
+ case SchemaRuleStatementAddColumnWithoutPosition:
+ if engine == storepb.Engine_OCEANBASE {
+ return MySQLStatementAddColumnWithoutPosition, nil
+ }
case SchemaRuleCharsetAllowlist:
switch engine {
case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 698fbbf8ab..aca103566d 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -504,6 +504,10 @@
"title": "Check for prior backup before data change",
"description": "This rule will check if a backup can be created before the data change. For more details, contains the backup target database exists and disallow the DDL statement."
},
+ "statement-add-column-without-position": {
+ "title": "Check no position in ADD COLUMN clause",
+ "description": "In some cases, using FIRST/AFTER to add columns will cause data reorganization (rewriting all data). Suggested error level: Warning"
+ },
"schema-backward-compatibility": {
"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"
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 92d4bc0266..b7eb604e08 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -504,6 +504,10 @@
"title": "Verificar la existencia de una copia de seguridad previa antes de cambiar los datos",
"description": "Esta regla verificará si se puede crear una copia de seguridad antes del cambio de datos. Para más detalles, contiene la existencia de la base de datos objetivo de la copia de seguridad y no permite la sentencia DDL."
},
+ "statement-add-column-without-position": {
+ "title": "Prohibir añadir columnas en una posición especificada",
+ "description": "En algunos casos, usar FIRST/AFTER para añadir columnas en una posición especificada puede causar una reorganización de los datos (reescribiendo los datos originales). Nivel de recomendación: advertencia."
+ },
"schema-backward-compatibility": {
"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"
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index a71f3f3648..1b3000bb33 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -504,6 +504,10 @@
"title": "データ変更前のバックアップの確認",
"description": "このルールは、データ変更前にバックアップが作成できるかどうかを確認します。詳細については、バックアップ対象のデータベースが存在し、DDLステートメントを許可しないことを含みます。"
},
+ "statement-add-column-without-position": {
+ "title": "指定位置への列の追加を禁止",
+ "description": "場合によっては、FIRST/AFTER を使用して指定位置に列を追加すると、データの再編成(元のデータを再び書き直す)が発生する可能性があります。推奨エラーレベル:警告。"
+ },
"schema-backward-compatibility": {
"title": "アプリケーションの後方互換性を確認する",
"description": "一部の変更は実行中のアプリケーションに影響を与える可能性があります。データベースオブジェクトの名前の変更や新しい制約の追加などが該当します。このルールにより、既存のアプリケーションの障害を防ぐことができます。提案されるエラーレベル:警告"
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index 5c906dfbdb..ab568c22be 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -504,6 +504,10 @@
"title": "Kiểm tra sao lưu trước khi thay đổi dữ liệu",
"description": "Quy tắc này sẽ kiểm tra xem có thể tạo sao lưu trước khi thay đổi dữ liệu hay không. Để biết thêm chi tiết, hãy kiểm tra xem cơ sở dữ liệu mục tiêu sao lưu có tồn tại và không cho phép câu lệnh DDL."
},
+ "statement-add-column-without-position": {
+ "title": "Cấm thêm cột vào vị trí được chỉ định",
+ "description": "Trong một số trường hợp, việc sử dụng FIRST/AFTER để thêm cột vào vị trí được chỉ định có thể gây ra việc sắp xếp lại dữ liệu (viết lại dữ liệu gốc). Mức độ khuyến cáo: cảnh báo."
+ },
"schema-backward-compatibility": {
"title": "Kiểm tra khả năng tương thích ngược của ứng dụng",
"description": "Một số thay đổi có thể ảnh hưởng đến các ứng dụng đang chạy, chẳng hạn như sửa đổi tên đối tượng cơ sở dữ liệu, thêm các ràng buộc mới, v.v. Quy tắc này có thể tránh những thay đổi bất cẩn dẫn đến lỗi ứng dụng hiện có. Mức độ lỗi đề xuất: Cảnh báo"
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index e56a0b0441..c70d8c6325 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -504,6 +504,10 @@
"title": "检查能否预前备份数据",
"description": "此规则将检查是否可以在数据更改前创建备份。该规则要求备份目标数据库存在且不存在DDL语句。"
},
+ "statement-add-column-without-position": {
+ "title": "禁止在指定位置加列",
+ "description": "某些情况下,使用 FIRST/AFTER 在指定位置加列将引起数据重整(把原来的数据重写一遍)。建议错误级别:警告"
+ },
"schema-backward-compatibility": {
"title": "检查应用向后兼容性",
"description": "某些变更可能影响现有应用功能,例如修改数据库对象名,增加新的约束等,此规范可避免不谨慎变更导致现有应用运行失败。建议错误等级:警告"
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index cc8eac67a7..d853cb65b5 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -344,6 +344,10 @@ ruleList:
- MYSQL
- POSTGRES
- TIDB
+ - type: statement.add-column-without-position
+ category: STATEMENT
+ engineList:
+ - OCEANBASE
- type: naming.fully-qualified
category: NAMING
engineList: