Skip to content

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

chore: add table no foreign key rule (#1854)

ecmadaob0d18464cabd
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 124c6901e5..85727e5881 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -24,6 +24,10 @@
"title": "Require primary key",
"description": "Require the table to have a primary key."
},
+ "table-no-foreign-key": {
+ "title": "No foreign key",
+ "description": "Disallow the foreign key in the table."
+ },
"naming-table": {
"title": "Table naming check",
"description": "Enforce the table name format and length limit. Default snake_lower_case with 64 characters.",
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index 7af482b932..be2b058ccd 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -24,6 +24,10 @@
"title": "强制主键",
"description": "要求每张表必须有一个主键。"
},
+ "table-no-foreign-key": {
+ "title": "禁止外键",
+ "description": "禁止给表创建外键。"
+ },
"naming-table": {
"title": "表名命名检查",
"description": "限制表名命名风格和长度,默认为小写字母_下划线,且不超过 64 个字符。",
diff --git a/frontend/src/types/schemaSystem.ts b/frontend/src/types/schemaSystem.ts
index de69fb71ec..3cce0c7031 100644
--- a/frontend/src/types/schemaSystem.ts
+++ b/frontend/src/types/schemaSystem.ts
@@ -74,6 +74,7 @@ export interface RuleConfigComponent {
export type RuleType =
| "engine.mysql.use-innodb"
| "table.require-pk"
+ | "table.no-foreign-key"
| "naming.table"
| "naming.column"
| "naming.index.uk"
diff --git a/frontend/src/types/sqlReviewConfig.yaml b/frontend/src/types/sqlReviewConfig.yaml
index 0f3777adb8..8f7ed0a897 100644
--- a/frontend/src/types/sqlReviewConfig.yaml
+++ b/frontend/src/types/sqlReviewConfig.yaml
@@ -19,6 +19,11 @@ templateList:
engine: COMMON
level: ERROR
componentList: []
+ - type: table.no-foreign-key
+ category: TABLE
+ engine: COMMON
+ level: ERROR
+ componentList: []
- type: statement.select.no-select-all
category: STATEMENT
engine: COMMON
@@ -146,6 +151,11 @@ templateList:
engine: COMMON
level: ERROR
componentList: []
+ - type: table.no-foreign-key
+ category: TABLE
+ engine: COMMON
+ level: WARNING
+ componentList: []
- type: naming.table
category: NAMING
engine: COMMON
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index bdfe3252a7..bf38fd56f8 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -87,6 +87,9 @@ const (
// MySQLTableRequirePK is an advisor type for MySQL table require primary key.
MySQLTableRequirePK Type = "bb.plugin.advisor.mysql.table.require-pk"
+ // MySQLTableNoFK is an advisor type for MySQL table disallow foreign key.
+ MySQLTableNoFK Type = "bb.plugin.advisor.mysql.table.no-foreign-key"
+
// PostgreSQL Advisor
// PostgreSQLSyntax is an advisor type for PostgreSQL syntax.
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index 540d2e34ca..79946335ef 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -47,8 +47,9 @@ const (
// 501 engine error code
NotInnoDBEngine Code = 501
- // 601 table rule advisor error code
- TableNoPK Code = 601
+ // 601 ~ 699 table rule advisor error code
+ TableNoPK Code = 601
+ TableHasFK Code = 602
)
// Int returns the int type of code.
diff --git a/plugin/advisor/mysql/advisor_table_no_fk.go b/plugin/advisor/mysql/advisor_table_no_fk.go
new file mode 100644
index 0000000000..cc0ce4e671
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_table_no_fk.go
@@ -0,0 +1,94 @@
+package mysql
+
+import (
+ "fmt"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/pingcap/tidb/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*TableNoFKAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(advisor.MySQL, advisor.MySQLTableNoFK, &TableNoFKAdvisor{})
+ advisor.Register(advisor.TiDB, advisor.MySQLTableNoFK, &TableNoFKAdvisor{})
+}
+
+// TableNoFKAdvisor is the advisor checking table disallow foreign key.
+type TableNoFKAdvisor struct {
+}
+
+// Check checks table disallow foreign key.
+func (adv *TableNoFKAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySchemaReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &tableNoFKChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ 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 tableNoFKChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+}
+
+// Enter implements the ast.Visitor interface
+func (checker *tableNoFKChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ if constraint.Tp == ast.ConstraintForeignKey {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.TableHasFK,
+ Title: checker.title,
+ Content: fmt.Sprintf("Foreign key is not allowed in the table `%s`", node.Table.Name),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableAddConstraint && spec.Constraint.Tp == ast.ConstraintForeignKey {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.TableHasFK,
+ Title: checker.title,
+ Content: fmt.Sprintf("Foreign key is not allowed in the table `%s`", node.Table.Name),
+ })
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface
+func (checker *tableNoFKChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/plugin/advisor/mysql/advisor_table_no_fk_test.go b/plugin/advisor/mysql/advisor_table_no_fk_test.go
new file mode 100644
index 0000000000..8c33498302
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_table_no_fk_test.go
@@ -0,0 +1,40 @@
+package mysql
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestTableNoFK(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.TableHasFK,
+ Title: "table.no-foreign-key",
+ Content: "Foreign key is not allowed in the table `tech_book`",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id_author_id (author_id) REFERENCES author (id))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.TableHasFK,
+ Title: "table.no-foreign-key",
+ Content: "Foreign key is not allowed in the table `book`",
+ },
+ },
+ },
+ }
+
+ advisor.RunSchemaReviewRuleTests(t, tests, &TableNoFKAdvisor{}, &advisor.SchemaReviewRule{
+ Type: advisor.SchemaRuleTableNoFK,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: "",
+ }, &advisor.MockCatalogService{})
+}
diff --git a/plugin/advisor/schema_review.go b/plugin/advisor/schema_review.go
index b83302e0f6..c796f760ec 100644
--- a/plugin/advisor/schema_review.go
+++ b/plugin/advisor/schema_review.go
@@ -53,6 +53,8 @@ const (
// SchemaRuleTableRequirePK require the table to have a primary key.
SchemaRuleTableRequirePK SchemaReviewRuleType = "table.require-pk"
+ // SchemaRuleTableNoFK require the table disallow the foreign key.
+ SchemaRuleTableNoFK SchemaReviewRuleType = "table.no-foreign-key"
// SchemaRuleRequiredColumn enforce the required columns in each table.
SchemaRuleRequiredColumn SchemaReviewRuleType = "column.required"
@@ -360,6 +362,11 @@ func getAdvisorTypeByRule(ruleType SchemaReviewRuleType, engine DBType) (Type, e
case MySQL, TiDB:
return MySQLTableRequirePK, nil
}
+ case SchemaRuleTableNoFK:
+ switch engine {
+ case MySQL, TiDB:
+ return MySQLTableNoFK, nil
+ }
case SchemaRuleMySQLEngine:
if engine == MySQL {
return MySQLUseInnoDB, nil
diff --git a/tests/schema_system_test.go b/tests/schema_system_test.go
index c990727dd6..fee48bd0a4 100644
--- a/tests/schema_system_test.go
+++ b/tests/schema_system_test.go
@@ -39,8 +39,7 @@ func TestSchemaSystem(t *testing.T) {
"updater_id INT NOT NULL," +
"updated_ts TIMESTAMP NOT NULL," +
"INDEX idx_user_name(name)," +
- "UNIQUE KEY uk_user_id_name(id, name)," +
- "FOREIGN KEY fk_user_room_id_room_id(room_id) REFERENCES room(id)" +
+ "UNIQUE KEY uk_user_id_name(id, name)" +
") ENGINE = INNODB",
"CREATE TABLE userTable(" +
"id INT," +
@@ -137,6 +136,13 @@ func TestSchemaSystem(t *testing.T) {
Title: "table.require-pk",
Content: "Table `userTable` requires PRIMARY KEY",
},
+ {
+ Status: api.TaskCheckStatusError,
+ Namespace: api.AdvisorNamespace,
+ Code: advisor.TableHasFK.Int(),
+ Title: "table.no-foreign-key",
+ Content: "Foreign key is not allowed in the table `userTable`",
+ },
{
Status: api.TaskCheckStatusWarn,
Namespace: api.AdvisorNamespace,
diff --git a/tests/tests.go b/tests/tests.go
index d1b9635539..9107e89a04 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -1427,6 +1427,7 @@ func setDefaultSchemaReviewRulePayload(ruleTp advisor.SchemaReviewRuleType) (str
case advisor.SchemaRuleStatementRequireWhere:
case advisor.SchemaRuleStatementNoLeadingWildcardLike:
case advisor.SchemaRuleTableRequirePK:
+ case advisor.SchemaRuleTableNoFK:
case advisor.SchemaRuleColumnNotNull:
case advisor.SchemaRuleSchemaBackwardCompatibility:
case advisor.SchemaRuleTableNaming:
@@ -1512,6 +1513,10 @@ func prodTemplateSchemaReviewPolicy() (string, error) {
Type: advisor.SchemaRuleTableRequirePK,
Level: advisor.SchemaRuleLevelError,
},
+ {
+ Type: advisor.SchemaRuleTableNoFK,
+ Level: advisor.SchemaRuleLevelError,
+ },
{
Type: advisor.SchemaRuleRequiredColumn,
Level: advisor.SchemaRuleLevelWarning,