Skip to content

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

chore: implement disallow ddl for specific tables rule (#11486)

boojack0127d251d66e
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index 23666737d3..9b052d4c66 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -582,6 +582,9 @@ const (
// MSSQLColumnTypeDisallowList is an advisor type for MSSQL column type disallow list.
MSSQLColumnTypeDisallowList Type = "bb.plugin.advisor.mssql.column.type-disallow-list"
+
+ // MSSQLTableDisallowDDL is an advisor type for MSSQL disallow DDL for specific tables.
+ MSSQLTableDisallowDDL = "bb.plugin.advisor.mssql.table.disallow-ddl"
)
// Advice is the result of an advisor.
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index ed64d154ed..a6aa28705c 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -118,6 +118,7 @@ const (
CreateTableTrigger Code = 610
TotalTextLengthExceedsLimit Code = 611
DisallowSetCharset Code = 612
+ TableDisallowDDL Code = 613
// 701 ~ 799 database advisor error code.
DatabaseNotEmpty Code = 701
diff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yaml
index 853d57c8b6..e785ccc7fa 100644
--- a/backend/plugin/advisor/config/sql-review.prod.yaml
+++ b/backend/plugin/advisor/config/sql-review.prod.yaml
@@ -27,6 +27,8 @@ ruleList:
number: 1000
- type: table.disallow-set-charset
level: WARNING
+ - type: table.disallow-ddl
+ level: WARNING
- type: statement.select.no-select-all
level: ERROR
- type: statement.where.require
diff --git a/backend/plugin/advisor/mssql/advisor_column_type_disallow_list.go b/backend/plugin/advisor/mssql/advisor_column_type_disallow_list.go
index 9db311ea50..d109115839 100644
--- a/backend/plugin/advisor/mssql/advisor_column_type_disallow_list.go
+++ b/backend/plugin/advisor/mssql/advisor_column_type_disallow_list.go
@@ -35,7 +35,7 @@ func (*ColumnTypeDisallowListAdvisor) Check(ctx advisor.Context, _ string) ([]ad
if err != nil {
return nil, err
}
- paylaod, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
if err != nil {
return nil, err
}
@@ -44,7 +44,7 @@ func (*ColumnTypeDisallowListAdvisor) Check(ctx advisor.Context, _ string) ([]ad
title: string(ctx.Rule.Type),
disallowTypes: []string{},
}
- for _, tp := range paylaod.List {
+ for _, tp := range payload.List {
checker.disallowTypes = append(checker.disallowTypes, strings.ToUpper(tp))
}
diff --git a/backend/plugin/advisor/mssql/advisor_table_disallow_ddl.go b/backend/plugin/advisor/mssql/advisor_table_disallow_ddl.go
new file mode 100644
index 0000000000..99fa176202
--- /dev/null
+++ b/backend/plugin/advisor/mssql/advisor_table_disallow_ddl.go
@@ -0,0 +1,121 @@
+// Package mssql is the advisor for MSSQL database.
+package mssql
+
+import (
+ "fmt"
+
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/tsql-parser"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*TableDisallowDDLAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_MSSQL, advisor.MSSQLTableDisallowDDL, &TableDisallowDDLAdvisor{})
+}
+
+// TableDisallowDDLAdvisor is the advisor checking for disallow DDL on specific tables.
+type TableDisallowDDLAdvisor struct {
+}
+
+func (*TableDisallowDDLAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ tree, ok := ctx.AST.(antlr.Tree)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to Tree")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &tableDisallowDDLChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ disallowList: payload.List,
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(checker, 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 tableDisallowDDLChecker struct {
+ *parser.BaseTSqlParserListener
+
+ level advisor.Status
+ title string
+ adviceList []advisor.Advice
+ // disallowList is the list of table names that disallow DDL.
+ disallowList []string
+}
+
+func (checker *tableDisallowDDLChecker) EnterCreate_table(ctx *parser.Create_tableContext) {
+ tableName := ctx.Table_name()
+ if tableName == nil {
+ return
+ }
+ normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
+ checker.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
+}
+
+func (checker *tableDisallowDDLChecker) EnterAlter_table(ctx *parser.Alter_tableContext) {
+ tableName := ctx.Table_name(0)
+ if tableName == nil {
+ return
+ }
+ normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
+ checker.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
+}
+
+func (checker *tableDisallowDDLChecker) EnterDrop_table(ctx *parser.Drop_tableContext) {
+ for _, tableName := range ctx.AllTable_name() {
+ if tableName == nil {
+ return
+ }
+ normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
+ checker.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
+ }
+}
+
+func (checker *tableDisallowDDLChecker) EnterTruncate_table(ctx *parser.Truncate_tableContext) {
+ tableName := ctx.Table_name()
+ if tableName == nil {
+ return
+ }
+ normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
+ checker.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
+}
+
+func (checker *tableDisallowDDLChecker) checkTableName(normalizedTableName string, line int) {
+ for _, disallow := range checker.disallowList {
+ if normalizedTableName == disallow {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.TableDisallowDDL,
+ Title: checker.title,
+ Content: fmt.Sprintf("DDL is disallowed on table %s.", normalizedTableName),
+ Line: line,
+ })
+ return
+ }
+ }
+}
diff --git a/backend/plugin/advisor/mssql/mssql_rules_test.go b/backend/plugin/advisor/mssql/mssql_rules_test.go
index 5683e32bbb..e09549e682 100644
--- a/backend/plugin/advisor/mssql/mssql_rules_test.go
+++ b/backend/plugin/advisor/mssql/mssql_rules_test.go
@@ -20,6 +20,7 @@ func TestMSSQLRules(t *testing.T) {
advisor.SchemaRuleTableRequirePK,
advisor.SchemaRuleColumnNotNull,
advisor.SchemaRuleTableNoFK,
+ advisor.SchemaRuleTableDisallowDDL,
advisor.SchemaRuleSchemaBackwardCompatibility,
advisor.SchemaRuleRequiredColumn,
advisor.SchemaRuleColumnTypeDisallowList,
diff --git a/backend/plugin/advisor/mssql/test/table_disallow_ddl.yaml b/backend/plugin/advisor/mssql/test/table_disallow_ddl.yaml
new file mode 100644
index 0000000000..84522f69cd
--- /dev/null
+++ b/backend/plugin/advisor/mssql/test/table_disallow_ddl.yaml
@@ -0,0 +1,15 @@
+- statement: |-
+ CREATE TABLE MySchema.MyTable (
+ Id INT NOT NULL,
+ Name VARCHAR(50) NOT NULL
+ );
+ CREATE TABLE MySchema.Identifier (
+ Id INT NOT NULL,
+ Name VARCHAR(50) NOT NULL
+ );
+ want:
+ - status: WARN
+ code: 613
+ title: table.disallow-ddl
+ content: DDL is disallowed on table MySchema.Identifier.
+ line: 5
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index aff1109870..432e003f67 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -150,6 +150,8 @@ const (
SchemaRuleTableTextFieldsTotalLength SQLReviewRuleType = "table.text-fields-total-length"
// SchemaRuleTableDisallowSetCharset disallow set table charset.
SchemaRuleTableDisallowSetCharset SQLReviewRuleType = "table.disallow-set-charset"
+ // SchemaRuleTableDisallowDDL disallow the DDL for specific tables.
+ SchemaRuleTableDisallowDDL SQLReviewRuleType = "table.disallow-ddl"
// SchemaRuleRequiredColumn enforce the required columns in each table.
SchemaRuleRequiredColumn SQLReviewRuleType = "column.required"
@@ -1405,6 +1407,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
if engine == storepb.Engine_MYSQL {
return MySQLTableDisallowSetCharset, nil
}
+ case SchemaRuleTableDisallowDDL:
+ if engine == storepb.Engine_MSSQL {
+ return MSSQLTableDisallowDDL, nil
+ }
case SchemaRuleMySQLEngine:
switch engine {
case storepb.Engine_MYSQL, storepb.Engine_MARIADB:
diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.go
index 8557e1bdd8..510042c119 100644
--- a/backend/plugin/advisor/utils_for_tests.go
+++ b/backend/plugin/advisor/utils_for_tests.go
@@ -461,6 +461,16 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.Eng
payload, err = json.Marshal(NumberTypeRulePayload{
Number: 20,
})
+ case SchemaRuleTableDisallowDDL:
+ if dbType == storepb.Engine_MSSQL {
+ payload, err = json.Marshal(StringArrayTypeRulePayload{
+ List: []string{"MySchema.Identifier"},
+ })
+ } else {
+ payload, err = json.Marshal(StringArrayTypeRulePayload{
+ List: []string{"identifier"},
+ })
+ }
case SchemaRuleIndexKeyNumberLimit, SchemaRuleIndexTotalNumberLimit:
payload, err = json.Marshal(NumberTypeRulePayload{
Number: 5,
diff --git a/backend/plugin/parser/tsql/tsql.go b/backend/plugin/parser/tsql/tsql.go
index 91e8392994..9ee71dad0d 100644
--- a/backend/plugin/parser/tsql/tsql.go
+++ b/backend/plugin/parser/tsql/tsql.go
@@ -1,7 +1,6 @@
package tsql
import (
- "fmt"
"strings"
"unicode"
@@ -74,7 +73,17 @@ func NormalizeTSQLTableName(ctx parser.ITable_nameContext, fallbackDatabaseName,
table = id
}
}
- return fmt.Sprintf("%s.%s.%s", database, schema, table)
+ tableNameParts := []string{}
+ if database != "" {
+ tableNameParts = append(tableNameParts, database)
+ }
+ if schema != "" {
+ tableNameParts = append(tableNameParts, schema)
+ }
+ if table != "" {
+ tableNameParts = append(tableNameParts, table)
+ }
+ return strings.Join(tableNameParts, ".")
}
// NormalizeTSQLIdentifier returns the normalized identifier.
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 9be59399e7..7b3641620f 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -90,6 +90,15 @@
}
}
},
+ "table-disallow-ddl": {
+ "title": "Disallow DDL",
+ "description": "Configure which tables are prohibited from executing DDL. Suggestion error level: Warning",
+ "component": {
+ "list": {
+ "title": "Table names"
+ }
+ }
+ },
"naming-table": {
"title": "Enforce table naming format",
"description": "The default format is all lowercase letters, separated by underscores between words, and no more than 63 characters long, such as \"abc\" and \"abc_def\". 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 1dd696afcb..7a318507d8 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -90,6 +90,15 @@
}
}
},
+ "table-disallow-ddl": {
+ "title": "No permitir DDL",
+ "description": "Configure qué tablas tienen prohibido ejecutar DDL. Nivel de error de sugerencia: Advertencia",
+ "component": {
+ "list": {
+ "title": "Nombres de tablas"
+ }
+ }
+ },
"naming-table": {
"title": "Imponer formato de nomenclatura de tabla",
"description": "El formato predeterminado es todo en minúsculas, separado por guiones bajos entre palabras, y no más de 63 caracteres de largo, como \"abc\" y \"abc_def\". Nivel de sugerencia de error: Advertencia",
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 7413deb0a7..3fd0e3f718 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -90,6 +90,15 @@
}
}
},
+ "table-disallow-ddl": {
+ "title": "DDL を禁止する",
+ "description": "DDL の実行を禁止するテーブルを設定します。提案エラー レベル: 警告",
+ "component": {
+ "list": {
+ "title": "テーブル名"
+ }
+ }
+ },
"naming-table": {
"title": "テーブルの命名形式の強制",
"description": "デフォルトの形式はすべて小文字で、単語間にアンダースコアで区切られ、最大63文字までです。例えば「abc」や「abc_def」です。提案エラーレベル:警告",
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index 179ab26488..0099863738 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -90,6 +90,15 @@
}
}
},
+ "table-disallow-ddl": {
+ "title": "Không cho phép DDL",
+ "description": "Định cấu hình bảng nào bị cấm thực thi DDL. Mức độ lỗi đề xuất: Cảnh báo",
+ "component": {
+ "list": {
+ "title": "Tên bảng"
+ }
+ }
+ },
"naming-table": {
"title": "Thực thi định dạng đặt tên bảng",
"description": "Định dạng mặc định là tất cả các chữ cái viết thường, phân tách bằng dấu gạch dưới giữa các từ và không dài quá 63 ký tự, chẳng hạn như \"abc\" và \"abc_def\". 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 8ba6ab86c4..3af9eed640 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -90,6 +90,15 @@
}
}
},
+ "table-disallow-ddl": {
+ "title": "禁止DDL",
+ "description": "配置哪些表禁止执行 DDL。建议错误级别:警告",
+ "component": {
+ "list": {
+ "title": "表名"
+ }
+ }
+ },
"naming-table": {
"title": "强制表命名格式",
"description": "默认格式为全小写字母,单词之间以下划线分割,长度不超过 63 个字符,例如 \"abc\",\"abc_def\"。建议错误等级:警告",
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index 8909305895..d3e894b857 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -88,6 +88,15 @@ ruleList:
category: TABLE
engineList:
- MYSQL
+ - type: table.disallow-ddl
+ category: TABLE
+ engineList:
+ - MSSQL
+ componentList:
+ - key: list
+ payload:
+ type: STRING_ARRAY
+ default: []
- type: statement.select.no-select-all
category: STATEMENT
engineList: