Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: migrate table_no_fk (#9057)
zll6004b47ac2e133e
diff --git a/backend/plugin/advisor/mysqlwip/advisor_table_no_fk.go b/backend/plugin/advisor/mysqlwip/advisor_table_no_fk.goindex d98acd6821..6633b6f715 100644--- a/backend/plugin/advisor/mysqlwip/advisor_table_no_fk.go+++ b/backend/plugin/advisor/mysqlwip/advisor_table_no_fk.go@@ -2,27 +2,36 @@ package mysqlwipimport ("fmt"+ "strings"- "github.com/pingcap/tidb/parser/ast"+ "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 = (*TableNoFKAdvisor)(nil)- _ ast.Visitor = (*tableNoFKChecker)(nil))+func init() {+ // only for mysqlwip test.+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, advisor.MySQLTableNoFK, &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, _ string) ([]advisor.Advice, error) {- root, ok := ctx.AST.([]ast.StmtNode)+ root, ok := ctx.AST.([]*mysqlparser.ParseResult)if !ok {- return nil, errors.Errorf("failed to convert to StmtNode")+ return nil, errors.Errorf("failed to convert to mysql parse result")}level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)if err != nil {@@ -34,7 +43,8 @@ func (*TableNoFKAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice,title: string(ctx.Rule.Type),}for _, stmtNode := range root {- (stmtNode).Accept(checker)+ checker.baseLine = stmtNode.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmtNode.Tree)}if len(checker.adviceList) == 0 {@@ -50,44 +60,56 @@ func (*TableNoFKAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice,}type tableNoFKChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine intadviceList []advisor.Advicelevel advisor.Statustitle 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),- Line: constraint.OriginTextPosition(),- })- }- }- 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),- Line: in.OriginTextPosition(),- })- }+// EnterCreateTable is called when production createTable is entered.+func (checker *tableNoFKChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ if ctx.TableName() == nil || ctx.TableElementList() == nil {+ return+ }++ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())+ for _, tableElement := range ctx.TableElementList().AllTableElement() {+ if tableElement.TableConstraintDef() == nil {+ continue}+ checker.handleTableConstraintDef(tableName, tableElement.TableConstraintDef())}+}++// EnterAlterTable is called when production alterTable is entered.+func (checker *tableNoFKChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())- return in, false+ for _, option := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {+ switch {+ // ADD CONSTRANIT+ case option.ADD_SYMBOL() != nil && option.TableConstraintDef() != nil:+ checker.handleTableConstraintDef(tableName, option.TableConstraintDef())+ default:+ continue+ }+ }}-// Leave implements the ast.Visitor interface.-func (*tableNoFKChecker) Leave(in ast.Node) (ast.Node, bool) {- return in, true+func (checker *tableNoFKChecker) handleTableConstraintDef(tableName string, ctx mysql.ITableConstraintDefContext) {+ if ctx.GetType_() != nil {+ switch strings.ToUpper(ctx.GetType_().GetText()) {+ case "FOREIGN":+ 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`", tableName),+ Line: checker.baseLine + ctx.GetStart().GetLine(),+ })+ default:+ }+ }}diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.goindex 4f10f8e9aa..0f376ad832 100644--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go@@ -46,6 +46,9 @@ func TestMySQLWIPRules(t *testing.T) {// advisor.SchemaRuleStatementInsertDisallowOrderByRand disallow the order by rand in the INSERT statement.advisor.SchemaRuleStatementInsertDisallowOrderByRand,+ // advisor.SchemaRuleTableNoFK require the table disallow the foreign key.+ advisor.SchemaRuleTableNoFK,+// advisor.SchemaRuleDropEmptyDatabase enforce the MySQL support check if the database is empty before users drop it.advisor.SchemaRuleDropEmptyDatabase,}diff --git a/backend/plugin/advisor/mysqlwip/test/table_no_foreign_key.yaml b/backend/plugin/advisor/mysqlwip/test/table_no_foreign_key.yamlindex 2657588ef9..2656854ba7 100644--- a/backend/plugin/advisor/mysqlwip/test/table_no_foreign_key.yaml+++ b/backend/plugin/advisor/mysqlwip/test/table_no_foreign_key.yaml@@ -1,4 +1,6 @@-- 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);+ ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id);want:- status: WARNcode: 602@@ -6,11 +8,13 @@content: Foreign key is not allowed in the table `tech_book`line: 2details: ""-- statement: CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id_author_id (author_id) REFERENCES author (id))+- statement: |-+ CREATE TABLE t1 (id INT);+ CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id_author_id (author_id) REFERENCES author (id));want:- status: WARNcode: 602title: table.no-foreign-keycontent: Foreign key is not allowed in the table `book`- line: 1+ line: 2details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex b1798a48dd..d9741f220a 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1302,6 +1302,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty}case SchemaRuleTableNoFK:switch engine {+ // only for mysqlwip test.+ case storepb.Engine_ENGINE_UNSPECIFIED:+ return MySQLTableNoFK, nilcase storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:return MySQLTableNoFK, nilcase storepb.Engine_POSTGRES: