Skip to content

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

feat(sql-review): implement snowflake sql review rule table should not contain FK (#6605)

h3n4lbaf3f667836f
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index d4c527cfd1..291ac38f92 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -399,6 +399,9 @@ const (
// SnowflakeTableRequirePK is an advisor type for Snowflake table require primary key.
SnowflakeTableRequirePK Type = "bb.plugin.advisor.snowflake.table.require-pk"
+
+ // SnowflakeTableNoFK is an advisor type for Snowflake table disallow foreign key.
+ SnowflakeTableNoFK Type = "bb.plugin.advisor.snowflake.table.no-foreign-key"
)
// Advice is the result of an advisor.
diff --git a/backend/plugin/advisor/generator/snowflake.template b/backend/plugin/advisor/generator/snowflake.template
index 2e11a3eb06..77302ba7b9 100644
--- a/backend/plugin/advisor/generator/snowflake.template
+++ b/backend/plugin/advisor/generator/snowflake.template
@@ -55,13 +55,13 @@ type %CheckerName struct {
// generateAdvice returns the advices generated by the listener, the advices must not be empty.
func (l *%CheckerName) generateAdvice() ([]advisor.Advice, error) {
- if len(l.advice) == 0 {
- advice = append(advice, advisor.Advice{
+ if len(l.adviceList) == 0 {
+ l.adviceList = append(l.adviceList, advisor.Advice{
Status: advisor.Success,
Code: advisor.Ok,
Title: "OK",
Content: "",
})
}
- return advice, nil
+ return l.adviceList, nil
}
diff --git a/backend/plugin/advisor/snowflake/advisor.go b/backend/plugin/advisor/snowflake/advisor.go
new file mode 100644
index 0000000000..ca4bc8c797
--- /dev/null
+++ b/backend/plugin/advisor/snowflake/advisor.go
@@ -0,0 +1,11 @@
+// Package snowflake is the advisor for snowflake database.
+package snowflake
+
+// currentConstraintAction is the action of current constraint.
+type currentConstraintAction int
+
+const (
+ currentConstraintActionNone currentConstraintAction = iota
+ currentConstraintActionAdd
+ currentConstraintActionDrop
+)
diff --git a/backend/plugin/advisor/snowflake/advisor_table_no_foreign_key.go b/backend/plugin/advisor/snowflake/advisor_table_no_foreign_key.go
new file mode 100644
index 0000000000..bf60d0b40f
--- /dev/null
+++ b/backend/plugin/advisor/snowflake/advisor_table_no_foreign_key.go
@@ -0,0 +1,178 @@
+// Package snowflake is the advisor for snowflake database.
+package snowflake
+
+import (
+ "fmt"
+
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/snowsql-parser"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/db"
+)
+
+var (
+ _ advisor.Advisor = (*TableNoForeignKeyAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(db.Snowflake, advisor.SnowflakeTableNoFK, &TableNoForeignKeyAdvisor{})
+}
+
+// TableNoForeignKeyAdvisor is the advisor checking for table disallow foreign key.
+type TableNoForeignKeyAdvisor struct {
+}
+
+// Check checks for table disallow foreign key.
+func (*TableNoForeignKeyAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ tree, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ listener := &tableNoForeignKeyChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ currentConstraintAction: currentConstraintActionNone,
+ currentNormalizedTableName: "",
+ tableForeignKeyTimes: make(map[string]int),
+ tableOriginalName: make(map[string]string),
+ tableLine: make(map[string]int),
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)
+
+ return listener.generateAdvice()
+}
+
+// tableNoForeignKeyChecker is the listener for table disallow foreign key.
+type tableNoForeignKeyChecker struct {
+ *parser.BaseSnowflakeParserListener
+
+ level advisor.Status
+ title string
+
+ adviceList []advisor.Advice
+
+ currentConstraintAction currentConstraintAction
+ // currentNormalizedTableName is the current table name, and it is normalized.
+ // It should be set then entering create_table, alter_table and so on,
+ // and should be reset then exiting them.
+ currentNormalizedTableName string
+
+ // tableForeignKeyTimes is a map of normalized table name to the times of FOREIGN KEY.
+ tableForeignKeyTimes map[string]int
+ // tableOriginalName is a map of normalized table name to original table name.
+ // The key of the tableOriginalName is the superset of the key of the tableHasForeignKey.
+ tableOriginalName map[string]string
+ // tableLine is a map of normalized table name to the line number of the table.
+ // The key of the tableLine is the superset of the key of the tableHasForeignKey.
+ tableLine map[string]int
+}
+
+// generateAdvice returns the advices generated by the listener, the advices must not be empty.
+func (l *tableNoForeignKeyChecker) generateAdvice() ([]advisor.Advice, error) {
+ for tableName, times := range l.tableForeignKeyTimes {
+ if times > 0 {
+ l.adviceList = append(l.adviceList, advisor.Advice{
+ Status: l.level,
+ Code: advisor.TableHasFK,
+ Title: l.title,
+ Content: fmt.Sprintf("FOREIGN KEY is not allowed in the table %s.", l.tableOriginalName[tableName]),
+ Line: l.tableLine[tableName],
+ })
+ }
+ }
+ if len(l.adviceList) == 0 {
+ return []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ }, nil
+ }
+ return l.adviceList, nil
+}
+
+// EnterCreate_table is called when production create_table is entered.
+func (l *tableNoForeignKeyChecker) EnterCreate_table(ctx *parser.Create_tableContext) {
+ originalTableName := ctx.Object_name().GetText()
+ normalizedTableName := normalizeIdentifierName(originalTableName)
+
+ l.tableForeignKeyTimes[normalizedTableName] = 0
+ l.tableOriginalName[normalizedTableName] = originalTableName
+ l.tableLine[normalizedTableName] = ctx.GetStart().GetLine()
+ l.currentNormalizedTableName = normalizedTableName
+ l.currentConstraintAction = currentConstraintActionAdd
+}
+
+// ExitCreate_table is called when production create_table is exited.
+func (l *tableNoForeignKeyChecker) ExitCreate_table(*parser.Create_tableContext) {
+ l.currentNormalizedTableName = ""
+ l.currentConstraintAction = currentConstraintActionNone
+}
+
+// EnterInline_constraint is called when production inline_constraint is entered.
+func (l *tableNoForeignKeyChecker) EnterInline_constraint(ctx *parser.Inline_constraintContext) {
+ if ctx.REFERENCES() == nil || l.currentNormalizedTableName == "" {
+ return
+ }
+ l.tableForeignKeyTimes[l.currentNormalizedTableName]++
+}
+
+// EnterOut_of_line_constraint is called when production out_of_line_constraint is entered.
+func (l *tableNoForeignKeyChecker) EnterOut_of_line_constraint(ctx *parser.Out_of_line_constraintContext) {
+ if ctx.REFERENCES() == nil || l.currentNormalizedTableName == "" || l.currentConstraintAction == currentConstraintActionNone {
+ return
+ }
+ if l.currentConstraintAction == currentConstraintActionAdd {
+ l.tableForeignKeyTimes[l.currentNormalizedTableName]++
+ l.tableLine[l.currentNormalizedTableName] = ctx.GetStart().GetLine()
+ } else if l.currentConstraintAction == currentConstraintActionDrop {
+ if times, ok := l.tableForeignKeyTimes[l.currentNormalizedTableName]; ok && times > 0 {
+ l.tableForeignKeyTimes[l.currentNormalizedTableName]--
+ }
+ }
+}
+
+// EnterConstraint_action is called when production constraint_action is entered.
+func (l *tableNoForeignKeyChecker) EnterConstraint_action(ctx *parser.Constraint_actionContext) {
+ if l.currentNormalizedTableName == "" {
+ return
+ }
+ if ctx.DROP() != nil && ctx.FOREIGN() != nil {
+ if times, ok := l.tableForeignKeyTimes[l.currentNormalizedTableName]; ok && times > 0 {
+ l.tableForeignKeyTimes[l.currentNormalizedTableName]--
+ }
+ return
+ }
+ if ctx.ADD() != nil {
+ l.currentConstraintAction = currentConstraintActionAdd
+ return
+ }
+}
+
+// EnterAlter_table is called when production alter_table is entered.
+func (l *tableNoForeignKeyChecker) EnterAlter_table(ctx *parser.Alter_tableContext) {
+ if ctx.Constraint_action() == nil {
+ return
+ }
+ originalTableName := ctx.Object_name(0).GetText()
+ normalizedTableName := normalizeIdentifierName(originalTableName)
+
+ l.currentNormalizedTableName = normalizedTableName
+ l.tableOriginalName[normalizedTableName] = originalTableName
+}
+
+// ExitAlter_table is called when production alter_table is exited.
+func (l *tableNoForeignKeyChecker) ExitAlter_table(*parser.Alter_tableContext) {
+ l.currentNormalizedTableName = ""
+ l.currentConstraintAction = currentConstraintActionNone
+}
diff --git a/backend/plugin/advisor/snowflake/advisor_table_require_pk.go b/backend/plugin/advisor/snowflake/advisor_table_require_pk.go
index 74bb0e7898..5873cc4390 100644
--- a/backend/plugin/advisor/snowflake/advisor_table_require_pk.go
+++ b/backend/plugin/advisor/snowflake/advisor_table_require_pk.go
@@ -36,9 +36,9 @@ func (*TableRequirePkAdvisor) Check(ctx advisor.Context, statement string) ([]ad
}
listener := &tableRequirePkChecker{
- currentConstraintAction: currentConstraintActionNone,
level: level,
title: string(ctx.Rule.Type),
+ currentConstraintAction: currentConstraintActionNone,
currentNormalizedTableName: "",
tableHasPrimaryKey: make(map[string]bool),
tableOriginalName: make(map[string]string),
@@ -50,15 +50,6 @@ func (*TableRequirePkAdvisor) Check(ctx advisor.Context, statement string) ([]ad
return listener.generateAdvice()
}
-// currentConstraintAction is the action of current constraint.
-type currentConstraintAction int
-
-const (
- currentConstraintActionNone currentConstraintAction = iota
- currentConstraintActionAdd
- currentConstraintActionDrop
-)
-
// tableRequirePkChecker is the listener for table require primary key.
type tableRequirePkChecker struct {
*parser.BaseSnowflakeParserListener
@@ -122,6 +113,16 @@ func (l *tableRequirePkChecker) EnterCreate_table(ctx *parser.Create_tableContex
l.currentConstraintAction = currentConstraintActionAdd
}
+// EnterDrop_table is called when production drop_table is entered.
+func (l *tableRequirePkChecker) EnterDrop_table(ctx *parser.Drop_tableContext) {
+ originalTableName := ctx.Object_name().GetText()
+ normalizedTableName := normalizeIdentifierName(originalTableName)
+
+ delete(l.tableHasPrimaryKey, normalizedTableName)
+ delete(l.tableOriginalName, normalizedTableName)
+ delete(l.tableLine, normalizedTableName)
+}
+
// ExitCreate_table is called when production create_table is exited.
func (l *tableRequirePkChecker) ExitCreate_table(*parser.Create_tableContext) {
l.currentNormalizedTableName = ""
diff --git a/backend/plugin/advisor/snowflake/snowflake_rules_test.go b/backend/plugin/advisor/snowflake/snowflake_rules_test.go
index f1b75c0cd4..3fb8f03be6 100644
--- a/backend/plugin/advisor/snowflake/snowflake_rules_test.go
+++ b/backend/plugin/advisor/snowflake/snowflake_rules_test.go
@@ -12,6 +12,7 @@ func TestSnowflakeRules(t *testing.T) {
snowflakeRules := []advisor.SQLReviewRuleType{
advisor.SchemaRuleTableNaming,
advisor.SchemaRuleTableRequirePK,
+ advisor.SchemaRuleTableNoFK,
}
for _, rule := range snowflakeRules {
diff --git a/backend/plugin/advisor/snowflake/test/table_no_foreign_key.yaml b/backend/plugin/advisor/snowflake/test/table_no_foreign_key.yaml
new file mode 100644
index 0000000000..2fc11c4e7d
--- /dev/null
+++ b/backend/plugin/advisor/snowflake/test/table_no_foreign_key.yaml
@@ -0,0 +1,80 @@
+- statement: |-
+ CREATE TABLE CUSTOMER
+ (
+ ID INT REFERENCES PERSON(ID),
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100)
+ );
+ want:
+ - status: WARN
+ code: 602
+ title: table.no-foreign-key
+ content: FOREIGN KEY is not allowed in the table CUSTOMER.
+ line: 1
+ details: ""
+- statement: |-
+ CREATE TABLE CUSTOMER
+ (
+ ID INT,
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100),
+ (ID) REFERENCES PERSON(ID)
+ );
+ want:
+ - status: WARN
+ code: 602
+ title: table.no-foreign-key
+ content: FOREIGN KEY is not allowed in the table CUSTOMER.
+ line: 6
+ details: ""
+- statement: |-
+ CREATE TABLE CUSTOMER
+ (
+ ID INT,
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100)
+ );
+ ALTER TABLE CUSTOMER ADD (ID) REFERENCES PERSON(ID);
+ want:
+ - status: WARN
+ code: 602
+ title: table.no-foreign-key
+ content: FOREIGN KEY is not allowed in the table CUSTOMER.
+ line: 7
+ details: ""
+- statement: |-
+ CREATE TABLE CUSTOMER
+ (
+ ID INT REFERENCES PERSON(ID),
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100)
+ );
+ ALTER TABLE CUSTOMER DROP FOREIGN KEY (ID);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE CUSTOMER
+ (
+ ID INT,
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100)
+ );
+ CREATE TABLE PERSON
+ (
+ ID INT,
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100)
+ );
+ ALTER TABLE CUSTOMER ADD CONSTRAINT FK_CUSTOMER_PERSON FOREIGN KEY (ID) REFERENCES PERSON(ID);
+ want:
+ - status: WARN
+ code: 602
+ title: table.no-foreign-key
+ content: FOREIGN KEY is not allowed in the table CUSTOMER.
+ line: 13
+ details: ""
diff --git a/backend/plugin/advisor/snowflake/test/table_require_pk.yaml b/backend/plugin/advisor/snowflake/test/table_require_pk.yaml
index 8e105631be..dfca04f6fb 100644
--- a/backend/plugin/advisor/snowflake/test/table_require_pk.yaml
+++ b/backend/plugin/advisor/snowflake/test/table_require_pk.yaml
@@ -71,6 +71,28 @@
content: ""
line: 0
details: ""
+- statement: |-
+ CREATE TABLE CUSTOMER
+ (
+ ID INT,
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100)
+ );
+ ALTER TABLE CUSTOMER ADD CONSTRAINT PK_CUSTOMER PRIMARY KEY (ID);
+ DROP TABLE CUSTOMER;
+ CREATE TABLE CUSTOMER
+ (
+ ID INT,
+ FULL_NAME VARCHAR(10),
+ POSITION VARCHAR(100)
+ );
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table CUSTOMER requires PRIMARY KEY.
+ line: 9
+ details: ""
- statement: |-
CREATE TABLE CUSTOMER
(
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index a4abba9556..bee7f30f4e 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -1009,6 +1009,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
return PostgreSQLTableNoFK, nil
case db.Oracle:
return OracleTableNoFK, nil
+ case db.Snowflake:
+ return SnowflakeTableNoFK, nil
}
case SchemaRuleTableDropNamingConvention:
switch engine {