Skip to content

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

feat(sql-review): add PostgreSQL table-no-fk rule (#2226)

rebelicefa1030efaa32
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index 7de6d98afc..bca2c09ff5 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -24,6 +24,7 @@ ruleList:
engineList:
- MYSQL
- TIDB
+ - POSTGRES
componentList: []
- type: table.drop-naming-convention
category: TABLE
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index f74f1d2cd4..d37edf645e 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -141,6 +141,9 @@ const (
// PostgreSQLMigrationCompatibility is an advisor type for PostgreSQL migration compatibility.
PostgreSQLMigrationCompatibility Type = "bb.plugin.advisor.postgresql.migration-compatibility"
+
+ // PostgreSQLTableNoFK is an advisor type for PostgreSQL table disallow foreign key.
+ PostgreSQLTableNoFK Type = "bb.plugin.advisor.postgresql.table.no-foreign-key"
)
// Advice is the result of an advisor.
diff --git a/plugin/advisor/pg/advisor_table_no_fk.go b/plugin/advisor/pg/advisor_table_no_fk.go
new file mode 100644
index 0000000000..558955633e
--- /dev/null
+++ b/plugin/advisor/pg/advisor_table_no_fk.go
@@ -0,0 +1,109 @@
+package pg
+
+import (
+ "fmt"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*TableNoFKAdvisor)(nil)
+ _ ast.Visitor = (*tableNoFKChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLTableNoFK, &TableNoFKAdvisor{})
+}
+
+// TableNoFKAdvisor is the advisor checking table disallow foreign key.
+type TableNoFKAdvisor struct {
+}
+
+// Check checks table disallow foreign key.
+func (*TableNoFKAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmts, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &tableNoFKChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmts {
+ checker.text = stmt.Text()
+ ast.Walk(checker, stmt)
+ }
+
+ 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
+ text string
+}
+
+// Visit implements the ast.Visitor interface.
+func (checker *tableNoFKChecker) Visit(node ast.Node) ast.Visitor {
+ var tableHasFK *ast.TableDef
+ switch n := node.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ for _, column := range n.ColumnList {
+ if containFK(column.ConstraintList) {
+ tableHasFK = n.Name
+ break
+ }
+ }
+ if containFK(n.ConstraintList) {
+ tableHasFK = n.Name
+ }
+ // ADD CONSTRAINT
+ case *ast.AddConstraintStmt:
+ if n.Constraint.Type == ast.ConstraintTypeForeign {
+ tableHasFK = n.Table
+ }
+ }
+
+ if tableHasFK != nil {
+ 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 %q.%q, related statement: \"%s\"",
+ normalizeSchemaName(tableHasFK.Schema),
+ tableHasFK.Name,
+ checker.text,
+ ),
+ })
+ }
+
+ return checker
+}
+
+func containFK(list []*ast.ConstraintDef) bool {
+ for _, cons := range list {
+ if cons.Type == ast.ConstraintTypeForeign {
+ return true
+ }
+ }
+ return false
+}
diff --git a/plugin/advisor/pg/advisor_table_no_fk_test.go b/plugin/advisor/pg/advisor_table_no_fk_test.go
new file mode 100644
index 0000000000..2c5c5aee72
--- /dev/null
+++ b/plugin/advisor/pg/advisor_table_no_fk_test.go
@@ -0,0 +1,40 @@
+package pg
+
+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 \"public\".\"tech_book\", related statement: \"ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id)\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id INT, author_id INT, CONSTRAINT fk_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 \"public\".\"book\", related statement: \"CREATE TABLE book(id INT, author_id INT, CONSTRAINT fk_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id))\"",
+ },
+ },
+ },
+ }
+
+ advisor.RunSQLReviewRuleTests(t, tests, &TableNoFKAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleTableNoFK,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: "",
+ }, advisor.MockPostgreSQLDatabase)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 4102ff2df8..0107ed390f 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -406,6 +406,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
switch engine {
case db.MySQL, db.TiDB:
return MySQLTableNoFK, nil
+ case db.Postgres:
+ return PostgreSQLTableNoFK, nil
}
case SchemaRuleTableDropNamingConvention:
switch engine {
diff --git a/tests/sql_review_test.go b/tests/sql_review_test.go
index bca0e9d32f..726ff68056 100644
--- a/tests/sql_review_test.go
+++ b/tests/sql_review_test.go
@@ -131,6 +131,13 @@ func TestSQLReviewForPostgreSQL(t *testing.T) {
Title: "table.require-pk",
Content: fmt.Sprintf(`Table "public"."userTable" requires PRIMARY KEY, related statement: %q`, statements[1]),
},
+ {
+ Status: api.TaskCheckStatusError,
+ Namespace: api.AdvisorNamespace,
+ Code: advisor.TableHasFK.Int(),
+ Title: "table.no-foreign-key",
+ Content: fmt.Sprintf(`Foreign key is not allowed in the table "public"."userTable", related statement: "%s"`, statements[1]),
+ },
{
Status: api.TaskCheckStatusWarn,
Namespace: api.AdvisorNamespace,