Skip to content

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

chore: migrate naming_fk rule (#8973)

zll600366c926f82ef
diff --git a/backend/plugin/advisor/mysqlwip/advisor_naming_foreign_key_convention.go b/backend/plugin/advisor/mysqlwip/advisor_naming_foreign_key_convention.go
index 238f3fa7a2..9eb4a780e0 100644
--- a/backend/plugin/advisor/mysqlwip/advisor_naming_foreign_key_convention.go
+++ b/backend/plugin/advisor/mysqlwip/advisor_naming_foreign_key_convention.go
@@ -4,26 +4,33 @@ import (
"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 = (*NamingFKConventionAdvisor)(nil)
- _ ast.Visitor = (*namingFKConventionChecker)(nil)
)
+func init() {
+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})
+}
+
// NamingFKConventionAdvisor is the advisor checking for foreign key naming convention.
type NamingFKConventionAdvisor struct {
}
// Check checks for foreign key naming convention.
func (*NamingFKConventionAdvisor) 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)
@@ -43,7 +50,8 @@ func (*NamingFKConventionAdvisor) Check(ctx advisor.Context, _ string) ([]adviso
templateList: templateList,
}
for _, stmtNode := range root {
- (stmtNode).Accept(checker)
+ checker.baseLine = stmtNode.BaseLine
+ antlr.ParseTreeWalkerDefault.Walk(checker, stmtNode.Tree)
}
if len(checker.adviceList) == 0 {
@@ -59,6 +67,10 @@ func (*NamingFKConventionAdvisor) Check(ctx advisor.Context, _ string) ([]adviso
}
type namingFKConventionChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ baseLine int
+ text string
adviceList []advisor.Advice
level advisor.Status
title string
@@ -67,10 +79,67 @@ type namingFKConventionChecker struct {
templateList []string
}
-// Enter implements the ast.Visitor interface.
-func (checker *namingFKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
- indexDataList := checker.getMetaDataList(in)
+func (checker *namingFKConventionChecker) EnterQuery(ctx *mysql.QueryContext) {
+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)
+}
+
+func (checker *namingFKConventionChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if ctx.TableName() == nil {
+ return
+ }
+ if ctx.TableElementList() == nil {
+ return
+ }
+
+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
+
+ var indexDataList []*indexMetaData
+ for _, tableElement := range ctx.TableElementList().AllTableElement() {
+ if tableElement == nil {
+ continue
+ }
+ if tableElement.TableConstraintDef() == nil {
+ continue
+ }
+ if metaData := checker.handleConstraintDef(tableName, tableElement.TableConstraintDef()); metaData != nil {
+ indexDataList = append(indexDataList, metaData)
+ }
+ }
+ checker.handleIndexList(indexDataList)
+}
+
+func (checker *namingFKConventionChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ if ctx.AlterTableActions() == nil {
+ return
+ }
+ if ctx.AlterTableActions().AlterCommandList() == nil {
+ return
+ }
+ if ctx.AlterTableActions().AlterCommandList().AlterList() == nil {
+ return
+ }
+ if ctx.TableRef() == nil {
+ return
+ }
+
+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
+ var indexDataList []*indexMetaData
+ for _, alterListItem := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {
+ if alterListItem == nil {
+ continue
+ }
+ // add constriant.
+ if alterListItem.ADD_SYMBOL() != nil && alterListItem.TableConstraintDef() != nil {
+ if metaData := checker.handleConstraintDef(tableName, alterListItem.TableConstraintDef()); metaData != nil {
+ indexDataList = append(indexDataList, metaData)
+ }
+ }
+ }
+ checker.handleIndexList(indexDataList)
+}
+
+func (checker *namingFKConventionChecker) handleIndexList(indexDataList []*indexMetaData) {
for _, indexData := range indexDataList {
regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)
if err != nil {
@@ -78,7 +147,7 @@ func (checker *namingFKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
Status: checker.level,
Code: advisor.Internal,
Title: "Internal error for foreign key naming convention rule",
- Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),
+ Content: fmt.Sprintf("%q meet internal error %q", checker.text, err.Error()),
})
continue
}
@@ -101,74 +170,45 @@ func (checker *namingFKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
})
}
}
-
- return in, false
}
-// Leave implements the ast.Visitor interface.
-func (*namingFKConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
+func (checker *namingFKConventionChecker) handleConstraintDef(tableName string, ctx mysql.ITableConstraintDefContext) *indexMetaData {
+ // focus on foreign index.
+ if ctx.FOREIGN_SYMBOL() == nil || ctx.KEY_SYMBOL() == nil || ctx.KeyList() == nil || ctx.References() == nil {
+ return nil
+ }
+
+ indexName := ""
+ // for mysql, foreign key use constraint name as unique identifier.
+ if ctx.ConstraintName() != nil {
+ indexName = mysqlparser.NormalizeConstraintName(ctx.ConstraintName())
+ }
+
+ referencingColumnList := mysqlparser.NormalizeKeyList(ctx.KeyList())
+ referencedTable, referencedColumnList := checker.handleReferences(ctx.References())
+ metaData := map[string]string{
+ advisor.ReferencingTableNameTemplateToken: tableName,
+ advisor.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),
+ advisor.ReferencedTableNameTemplateToken: referencedTable,
+ advisor.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),
+ }
+ return &indexMetaData{
+ indexName: indexName,
+ tableName: tableName,
+ metaData: metaData,
+ line: checker.baseLine + ctx.GetStart().GetLine(),
+ }
}
-// getMetaDataList returns the list of foreign key with meta data.
-func (*namingFKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
- var res []*indexMetaData
-
- switch node := in.(type) {
- case *ast.CreateTableStmt:
- for _, constraint := range node.Constraints {
- if constraint.Tp == ast.ConstraintForeignKey {
- var referencingColumnList []string
- for _, key := range constraint.Keys {
- referencingColumnList = append(referencingColumnList, key.Column.Name.String())
- }
- var referencedColumnList []string
- for _, spec := range constraint.Refer.IndexPartSpecifications {
- referencedColumnList = append(referencedColumnList, spec.Column.Name.String())
- }
-
- metaData := map[string]string{
- advisor.ReferencingTableNameTemplateToken: node.Table.Name.String(),
- advisor.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),
- advisor.ReferencedTableNameTemplateToken: constraint.Refer.Table.Name.String(),
- advisor.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),
- }
-
- res = append(res, &indexMetaData{
- indexName: constraint.Name,
- tableName: node.Table.Name.String(),
- metaData: metaData,
- line: constraint.OriginTextPosition(),
- })
- }
- }
- case *ast.AlterTableStmt:
- for _, spec := range node.Specs {
- if spec.Tp == ast.AlterTableAddConstraint && spec.Constraint.Tp == ast.ConstraintForeignKey {
- var referencingColumnList []string
- for _, key := range spec.Constraint.Keys {
- referencingColumnList = append(referencingColumnList, key.Column.Name.String())
- }
- var referencedColumnList []string
- for _, spec := range spec.Constraint.Refer.IndexPartSpecifications {
- referencedColumnList = append(referencedColumnList, spec.Column.Name.String())
- }
-
- metaData := map[string]string{
- advisor.ReferencingTableNameTemplateToken: node.Table.Name.String(),
- advisor.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),
- advisor.ReferencedTableNameTemplateToken: spec.Constraint.Refer.Table.Name.String(),
- advisor.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),
- }
- res = append(res, &indexMetaData{
- indexName: spec.Constraint.Name,
- tableName: node.Table.Name.String(),
- metaData: metaData,
- line: in.OriginTextPosition(),
- })
- }
- }
+func (*namingFKConventionChecker) handleReferences(ctx mysql.IReferencesContext) (string, []string) {
+ tableName := ""
+ if ctx.TableRef() != nil {
+ _, tableName = mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
}
- return res
+ var columns []string
+ if ctx.IdentifierListWithParentheses() != nil {
+ columns = mysqlparser.NormalizeIdentifierListWithParentheses(ctx.IdentifierListWithParentheses())
+ }
+ return tableName, columns
}
diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
index a439c13e1f..f0224d3ed5 100644
--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
@@ -18,6 +18,8 @@ func TestMySQLWIPRules(t *testing.T) {
advisor.SchemaRuleColumnNaming,
// advisor.SchemaRuleUKNaming enforce the unique key name format.
advisor.SchemaRuleUKNaming,
+ // advisor.SchemaRuleFKNaming enforce the foreign key name format.
+ advisor.SchemaRuleFKNaming,
// advisor.SchemaRuleStatementNoSelectAll disallow 'SELECT *'.
advisor.SchemaRuleStatementNoSelectAll,
diff --git a/backend/plugin/advisor/mysqlwip/test/naming_index_fk.yaml b/backend/plugin/advisor/mysqlwip/test/naming_index_fk.yaml
index 149bba0c69..8e897bc7ba 100644
--- a/backend/plugin/advisor/mysqlwip/test/naming_index_fk.yaml
+++ b/backend/plugin/advisor/mysqlwip/test/naming_index_fk.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 tech_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: SUCCESS
code: 0
@@ -6,7 +8,9 @@
content: ""
line: 0
details: ""
-- statement: ALTER TABLE tech_book ADD CONSTRAINT fk_author_id FOREIGN KEY (author_id) REFERENCES author (id)
+- statement: |
+ CREATE TABLE tech_book(id INT);
+ ALTER TABLE tech_book ADD CONSTRAINT fk_author_id FOREIGN KEY (author_id) REFERENCES author (id);
want:
- status: WARN
code: 305
@@ -14,21 +18,26 @@
content: Foreign key in table `tech_book` mismatches the naming convention, expect "^$|^fk_tech_book_author_id_author_id$" but found `fk_author_id`
line: 2
details: ""
-- statement: ALTER TABLE tech_book ADD CONSTRAINT rvemempmcmmhutaskvcidmwaldtfjdgmcpkhmibtadfydtkexpuzczrrneucthfwk FOREIGN KEY (author_id) REFERENCES author (id)
+- statement: ALTER TABLE tech_book ADD CONSTRAINT rvemempmcmmhutaskvcidmwaldtfjdgmcpkhmibtadfydtkexpuzczrrneucthfwk FOREIGN KEY (author_id) REFERENCES author (id);
want:
- status: WARN
code: 305
title: naming.index.fk
content: Foreign key `rvemempmcmmhutaskvcidmwaldtfjdgmcpkhmibtadfydtkexpuzczrrneucthfwk` in table `tech_book` mismatches the naming convention, its length should be within 64 characters
- line: 2
+ line: 1
details: ""
- status: WARN
code: 305
title: naming.index.fk
content: Foreign key in table `tech_book` mismatches the naming convention, expect "^$|^fk_tech_book_author_id_author_id$" but found `rvemempmcmmhutaskvcidmwaldtfjdgmcpkhmibtadfydtkexpuzczrrneucthfwk`
- line: 2
+ line: 1
details: ""
-- 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 book(
+ id INT,
+ author_id INT,
+ FOREIGN KEY fk_book_author_id_author_id (author_id) REFERENCES author (id)
+ );
want:
- status: SUCCESS
code: 0
@@ -36,7 +45,12 @@
content: ""
line: 0
details: ""
-- statement: CREATE TABLE book(id INT, author_id INT, FOREIGN KEY (author_id) REFERENCES author (id))
+- statement: |
+ CREATE TABLE book(
+ id INT,
+ author_id INT,
+ FOREIGN KEY (author_id) REFERENCES author (id)
+ );
want:
- status: SUCCESS
code: 0
@@ -44,11 +58,16 @@
content: ""
line: 0
details: ""
-- statement: CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id (author_id) REFERENCES author (id))
+- statement: |
+ CREATE TABLE book(
+ id INT,
+ author_id INT,
+ FOREIGN KEY fk_book_author_id (author_id) REFERENCES author (id)
+ );
want:
- - status: WARN
- code: 305
- title: naming.index.fk
- content: Foreign key in table `book` mismatches the naming convention, expect "^$|^fk_book_author_id_author_id$" but found `fk_book_author_id`
- line: 1
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
details: ""
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 14dd1e8ffc..9a081c3e32 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -1104,6 +1104,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
}
case SchemaRuleFKNaming:
switch engine {
+ // only for mysqlwip test.
+ case storepb.Engine_ENGINE_UNSPECIFIED:
+ return MySQLNamingFKConvention, nil
case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:
return MySQLNamingFKConvention, nil
case storepb.Engine_POSTGRES:
diff --git a/backend/plugin/parser/mysql/normalize.go b/backend/plugin/parser/mysql/normalize.go
index 0441713a0b..6956cabd6e 100644
--- a/backend/plugin/parser/mysql/normalize.go
+++ b/backend/plugin/parser/mysql/normalize.go
@@ -207,3 +207,19 @@ func NormalizeIndexRef(ctx parser.IIndexRefContext) (string, string, string) {
}
return "", "", ""
}
+
+// NormalizeMySQLIdentifierListWithParentheses normalize the given IdentififerListWithparentheses.
+func NormalizeIdentifierListWithParentheses(ctx parser.IIdentifierListWithParenthesesContext) []string {
+ if ctx.IdentifierList() != nil {
+ return NormalizeMySQLIdentifierList(ctx.IdentifierList())
+ }
+ return nil
+}
+
+// NormalizeMySQLConstraintName normalize the given IConstraintName.
+func NormalizeConstraintName(ctx parser.IConstraintNameContext) string {
+ if ctx.Identifier() != nil {
+ return NormalizeMySQLIdentifier(ctx.Identifier())
+ }
+ return ""
+}