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: naming unique key (#8957)
zll600353065ebbe0c
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex ad4d2b992b..36ab2c5fda 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -57,6 +57,8 @@ const (NameIsKeywordIdentifier Code = 308// 309 naming case mismatch advisor error code.NamingCaseMismatch Code = 309+ // 310 unique key name is empty advisor error code.+ NamingUKNameEmpty Code = 310// 401 ~ 499 column error code.NoRequiredColumn Code = 401diff --git a/backend/plugin/advisor/mysqlwip/advisor_naming_index_convention.go b/backend/plugin/advisor/mysqlwip/advisor_naming_index_convention.goindex fcde3c960c..8e8be80429 100644--- a/backend/plugin/advisor/mysqlwip/advisor_naming_index_convention.go+++ b/backend/plugin/advisor/mysqlwip/advisor_naming_index_convention.go@@ -2,7 +2,6 @@ package mysqlwipimport ("fmt"- "regexp""strings""github.com/pingcap/tidb/parser/ast"@@ -211,14 +210,3 @@ func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*indreturn res}--// getTemplateRegexp formats the template as regex.-func getTemplateRegexp(template string, templateList []string, tokens map[string]string) (*regexp.Regexp, error) {- for _, key := range templateList {- if token, ok := tokens[key]; ok {- template = strings.ReplaceAll(template, key, token)- }- }-- return regexp.Compile(template)-}diff --git a/backend/plugin/advisor/mysqlwip/advisor_naming_unique_key_convention.go b/backend/plugin/advisor/mysqlwip/advisor_naming_unique_key_convention.goindex 933261ff09..2643c094ed 100644--- a/backend/plugin/advisor/mysqlwip/advisor_naming_unique_key_convention.go+++ b/backend/plugin/advisor/mysqlwip/advisor_naming_unique_key_convention.go@@ -4,27 +4,35 @@ 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""github.com/bytebase/bytebase/backend/plugin/advisor/catalog"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")var (_ advisor.Advisor = (*NamingUKConventionAdvisor)(nil)- _ ast.Visitor = (*namingUKConventionChecker)(nil))+func init() {+ // only for mysqlwip test.+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})+}+// NamingUKConventionAdvisor is the advisor checking for unique key naming convention.type NamingUKConventionAdvisor struct {}// Check checks for index naming convention.func (*NamingUKConventionAdvisor) 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)@@ -45,7 +53,8 @@ func (*NamingUKConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisocatalog: ctx.Catalog,}for _, stmtNode := range root {- (stmtNode).Accept(checker)+ checker.baseLine = stmtNode.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmtNode.Tree)}if len(checker.adviceList) == 0 {@@ -60,6 +69,10 @@ func (*NamingUKConventionAdvisor) Check(ctx advisor.Context, _ string) ([]adviso}type namingUKConventionChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ text stringadviceList []advisor.Advicelevel advisor.Statustitle string@@ -69,18 +82,148 @@ type namingUKConventionChecker struct {catalog *catalog.Finder}-// Enter implements the ast.Visitor interface.-func (checker *namingUKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {- indexDataList := checker.getMetaDataList(in)+func (checker *namingUKConventionChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}++func (checker *namingUKConventionChecker) 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 *namingUKConventionChecker) 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+ }++ switch {+ // add index.+ case alterListItem.ADD_SYMBOL() != nil && alterListItem.TableConstraintDef() != nil:+ if metaData := checker.handleConstraintDef(tableName, alterListItem.TableConstraintDef()); metaData != nil {+ indexDataList = append(indexDataList, metaData)+ }+ // rename index.+ case alterListItem.RENAME_SYMBOL() != nil && alterListItem.KeyOrIndex() != nil && alterListItem.IndexRef() != nil && alterListItem.IndexName() != nil:+ _, _, oldIndexName := mysqlparser.NormalizeIndexRef(alterListItem.IndexRef())+ newIndexName := mysqlparser.NormalizeIndexName(alterListItem.IndexName())+ indexStateMap := checker.catalog.Origin.Index(&catalog.TableIndexFind{+ SchemaName: "",+ TableName: tableName,+ })+ if indexStateMap == nil {+ continue+ }+ indexState, ok := (*indexStateMap)[oldIndexName]+ if !ok {+ continue+ }+ if !indexState.Unique() {+ continue+ }+ columnList := indexState.ExpressionList()+ metaData := map[string]string{+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),+ advisor.TableNameTemplateToken: tableName,+ }+ indexData := &indexMetaData{+ indexName: newIndexName,+ tableName: tableName,+ metaData: metaData,+ line: checker.baseLine + ctx.GetStart().GetLine(),+ }+ indexDataList = append(indexDataList, indexData)+ }+ }+ checker.handleIndexList(indexDataList)+}++func (checker *namingUKConventionChecker) EnterCreateIndex(ctx *mysql.CreateIndexContext) {+ // only focus on unique index.+ if ctx.UNIQUE_SYMBOL() == nil {+ return+ }+ if ctx.IndexName() == nil || ctx.CreateIndexTarget() == nil || ctx.CreateIndexTarget().TableRef() == nil {+ return+ }++ indexName := mysqlparser.NormalizeIndexName(ctx.IndexName())+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.CreateIndexTarget().TableRef())++ if ctx.CreateIndexTarget().KeyListVariants() == nil {+ return+ }+ columnList := mysqlparser.NormalizeKeyListVariants(ctx.CreateIndexTarget().KeyListVariants())+ metaData := map[string]string{+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),+ advisor.TableNameTemplateToken: tableName,+ }+ indexDataList := []*indexMetaData{+ {+ indexName: indexName,+ tableName: tableName,+ metaData: metaData,+ line: checker.baseLine + ctx.GetStart().GetLine(),+ },+ }+ checker.handleIndexList(indexDataList)+}++func (checker *namingUKConventionChecker) handleIndexList(indexDataList []*indexMetaData) {for _, indexData := range indexDataList {+ // if indexName is not set explicitly. we throw an error.+ if indexData.indexName == "" {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Title: checker.title,+ Code: advisor.NamingUKNameEmpty,+ Content: fmt.Sprintf("Unique key in table `%s` should be set a name explicitly", indexData.tableName),+ Line: indexData.line,+ })+ continue+ }regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)if err != nil {checker.adviceList = append(checker.adviceList, advisor.Advice{Status: checker.level,Code: advisor.Internal,Title: "Internal error for unique 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}@@ -103,104 +246,28 @@ func (checker *namingUKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {})}}-- return in, false}-// Leave implements the ast.Visitor interface.-func (*namingUKConventionChecker) Leave(in ast.Node) (ast.Node, bool) {- return in, true-}+func (checker *namingUKConventionChecker) handleConstraintDef(tableName string, ctx mysql.ITableConstraintDefContext) *indexMetaData {+ // focus on unique index.+ if ctx.UNIQUE_SYMBOL() == nil || ctx.KeyListVariants() == nil {+ return nil+ }-// getMetaDataList returns the list of unique key with meta data.-func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {- var res []*indexMetaData-- switch node := in.(type) {- case *ast.CreateTableStmt:- for _, constraint := range node.Constraints {- switch constraint.Tp {- case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:- var columnList []string- for _, key := range constraint.Keys {- columnList = append(columnList, key.Column.Name.String())- }- metaData := map[string]string{- advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),- advisor.TableNameTemplateToken: node.Table.Name.String(),- }- 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 {- switch spec.Tp {- case ast.AlterTableRenameIndex:- _, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{- TableName: node.Table.Name.String(),- IndexName: spec.FromKey.String(),- })- if index == nil {- continue- }- if !index.Unique() {- // Index naming convention should in advisor_naming_index_convention.go- continue- }- metaData := map[string]string{- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),- advisor.TableNameTemplateToken: node.Table.Name.String(),- }- res = append(res, &indexMetaData{- indexName: spec.ToKey.String(),- tableName: node.Table.Name.String(),- metaData: metaData,- line: in.OriginTextPosition(),- })- case ast.AlterTableAddConstraint:- switch spec.Constraint.Tp {- case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:- var columnList []string- for _, key := range spec.Constraint.Keys {- columnList = append(columnList, key.Column.Name.String())- }-- metaData := map[string]string{- advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),- advisor.TableNameTemplateToken: node.Table.Name.String(),- }- res = append(res, &indexMetaData{- indexName: spec.Constraint.Name,- tableName: node.Table.Name.String(),- metaData: metaData,- line: in.OriginTextPosition(),- })- }- }- }- case *ast.CreateIndexStmt:- if node.KeyType == ast.IndexKeyTypeUnique {- var columnList []string- for _, spec := range node.IndexPartSpecifications {- columnList = append(columnList, spec.Column.Name.String())- }- metaData := map[string]string{- advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),- advisor.TableNameTemplateToken: node.Table.Name.String(),- }- res = append(res, &indexMetaData{- indexName: node.IndexName,- tableName: node.Table.Name.String(),- metaData: metaData,- line: in.OriginTextPosition(),- })- }+ indexName := ""+ if ctx.IndexNameAndType() != nil && ctx.IndexNameAndType().IndexName() != nil {+ indexName = mysqlparser.NormalizeIndexName(ctx.IndexNameAndType().IndexName())}- return res+ columnList := mysqlparser.NormalizeKeyListVariants(ctx.KeyListVariants())+ metaData := map[string]string{+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),+ advisor.TableNameTemplateToken: tableName,+ }+ return &indexMetaData{+ indexName: indexName,+ tableName: tableName,+ metaData: metaData,+ line: checker.baseLine + ctx.GetStart().GetLine(),+ }}diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.goindex 728d63d461..a439c13e1f 100644--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go@@ -14,9 +14,10 @@ func TestMySQLWIPRules(t *testing.T) {// advisor.SchemaRuleTableNaming enforce the table name format.advisor.SchemaRuleTableNaming,-// advisor.SchemaRuleColumnNaming enforce the column name format.advisor.SchemaRuleColumnNaming,+ // advisor.SchemaRuleUKNaming enforce the unique key name format.+ advisor.SchemaRuleUKNaming,// advisor.SchemaRuleStatementNoSelectAll disallow 'SELECT *'.advisor.SchemaRuleStatementNoSelectAll,diff --git a/backend/plugin/advisor/mysqlwip/test/naming_index_uk.yaml b/backend/plugin/advisor/mysqlwip/test/naming_index_uk.yamlindex abe7b98e56..8260b074bd 100644--- a/backend/plugin/advisor/mysqlwip/test/naming_index_uk.yaml+++ b/backend/plugin/advisor/mysqlwip/test/naming_index_uk.yaml@@ -1,4 +1,4 @@-- statement: CREATE UNIQUE INDEX uk_tech_book_id_name ON tech_book(id, name)+- statement: CREATE UNIQUE INDEX uk_tech_book_id_name ON tech_book(id, name);want:- status: SUCCESScode: 0@@ -6,7 +6,9 @@content: ""line: 0details: ""-- statement: CREATE UNIQUE INDEX tech_book_id_name ON tech_book(id, name)+- statement: |+ CREATE UNIQUE INDEX uk_tech_book_id_name ON tech_book(id, name);+ CREATE UNIQUE INDEX tech_book_id_name ON tech_book(id, name);want:- status: WARNcode: 304@@ -14,7 +16,9 @@content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `tech_book_id_name`line: 2details: ""-- statement: CREATE UNIQUE INDEX qtzmquwvlnttctfluoouxelxeliltcfzzstrtyocogwwyiyrflmrkbhbfasynlacy ON tech_book(id, name)+- statement: |+ CREATE UNIQUE INDEX uk_tech_book_id_name ON tech_book(id, name);+ CREATE UNIQUE INDEX qtzmquwvlnttctfluoouxelxeliltcfzzstrtyocogwwyiyrflmrkbhbfasynlacy ON tech_book(id, name)want:- status: WARNcode: 304@@ -28,7 +32,7 @@content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `qtzmquwvlnttctfluoouxelxeliltcfzzstrtyocogwwyiyrflmrkbhbfasynlacy`line: 2details: ""-- statement: ALTER TABLE tech_book ADD UNIQUE uk_tech_book_id_name (id, name)+- statement: ALTER TABLE tech_book ADD UNIQUE uk_tech_book_id_name (id, name);want:- status: SUCCESScode: 0@@ -36,7 +40,9 @@content: ""line: 0details: ""-- statement: ALTER TABLE tech_book ADD UNIQUE tech_book_id_name (id, name)+- statement: |+ CREATE TABLE t1(a INT);+ ALTER TABLE tech_book ADD UNIQUE tech_book_id_name (id, name);want:- status: WARNcode: 304@@ -44,7 +50,7 @@content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `tech_book_id_name`line: 2details: ""-- statement: ALTER TABLE tech_book RENAME INDEX old_uk TO uk_tech_book_id_name+- statement: ALTER TABLE tech_book RENAME INDEX old_uk TO uk_tech_book_id_name;want:- status: SUCCESScode: 0@@ -52,7 +58,9 @@content: ""line: 0details: ""-- statement: ALTER TABLE tech_book RENAME INDEX old_uk TO uk_tech_book+- statement: |+ CREATE TABLE t1(a INT);+ ALTER TABLE tech_book RENAME INDEX old_uk TO uk_tech_book;want:- status: WARNcode: 304@@ -60,7 +68,7 @@content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `uk_tech_book`line: 2details: ""-- statement: CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE INDEX uk_book_name (name))+- statement: CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE INDEX uk_book_name (name));want:- status: SUCCESScode: 0@@ -68,19 +76,29 @@content: ""line: 0details: ""-- statement: CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE KEY (name))+- statement: |+ CREATE TABLE book(+ id INT PRIMARY KEY,+ name VARCHAR(20),+ UNIQUE KEY (name)+ );want:- - status: SUCCESS- code: 0- title: OK- content: ""- line: 0+ - status: WARN+ code: 310+ title: naming.index.uk+ content: "Unique key in table `book` should be set a name explicitly"+ line: 4details: ""-- statement: CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE INDEX (name))+- statement: |+ CREATE TABLE book(+ id INT PRIMARY KEY,+ name VARCHAR(20),+ UNIQUE INDEX (name)+ );want:- - status: SUCCESS- code: 0- title: OK- content: ""- line: 0+ - status: WARN+ code: 310+ title: naming.index.uk+ content: "Unique key in table `book` should be set a name explicitly"+ line: 4details: ""diff --git a/backend/plugin/advisor/mysqlwip/utils.go b/backend/plugin/advisor/mysqlwip/utils.goindex 1ada57191a..128b886af1 100644--- a/backend/plugin/advisor/mysqlwip/utils.go+++ b/backend/plugin/advisor/mysqlwip/utils.go@@ -2,6 +2,7 @@package mysqlwipimport (+ "regexp""sort""strings"@@ -51,3 +52,14 @@ func restoreNode(node ast.Node, flag format.RestoreFlags) (string, error) {}return buffer.String(), nil}++// getTemplateRegexp formats the template as regex.+func getTemplateRegexp(template string, templateList []string, tokens map[string]string) (*regexp.Regexp, error) {+ for _, key := range templateList {+ if token, ok := tokens[key]; ok {+ template = strings.ReplaceAll(template, key, token)+ }+ }++ return regexp.Compile(template)+}diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex ed4e0364fb..14dd1e8ffc 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1094,6 +1094,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty}case SchemaRuleUKNaming:switch engine {+ // only for mysqlwip test.+ case storepb.Engine_ENGINE_UNSPECIFIED:+ return MySQLNamingUKConvention, nilcase storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:return MySQLNamingUKConvention, nilcase storepb.Engine_POSTGRES:diff --git a/backend/plugin/parser/mysql/normalize.go b/backend/plugin/parser/mysql/normalize.goindex 8fb05577dd..0441713a0b 100644--- a/backend/plugin/parser/mysql/normalize.go+++ b/backend/plugin/parser/mysql/normalize.go@@ -155,3 +155,55 @@ func NormalizeMySQLSchemaRef(ctx parser.ISchemaRefContext) string {}return ""}++// NormalizeMySQLKeyListVariants normalize the given keyListVariants.+func NormalizeKeyListVariants(ctx parser.IKeyListVariantsContext) []string {+ if ctx.KeyList() != nil {+ return NormalizeKeyList(ctx.KeyList())+ }+ if ctx.KeyListWithExpression() != nil {+ return NormalizeKeyListWithExpression(ctx.KeyListWithExpression())+ }+ return nil+}++// NormalizeMySQLKeyList normalize the given keyList.+func NormalizeKeyList(ctx parser.IKeyListContext) []string {+ var result []string+ for _, key := range ctx.AllKeyPart() {+ keyText := NormalizeMySQLIdentifier(key.Identifier())+ result = append(result, keyText)+ }+ return result+}++// NormalizeMySQLKeyListWithExpression normalize the given keyListWithExpression.+func NormalizeKeyListWithExpression(ctx parser.IKeyListWithExpressionContext) []string {+ var result []string+ for _, key := range ctx.AllKeyPartOrExpression() {+ if key.KeyPart() != nil {+ keyText := NormalizeMySQLIdentifier(key.KeyPart().Identifier())+ result = append(result, keyText)+ } else if key.ExprWithParentheses() != nil {+ keyText := key.GetParser().GetTokenStream().GetTextFromRuleContext(key.ExprWithParentheses())+ result = append(result, keyText)+ }+ }+ return result+}++// NormalizeMySQLIndexName normalize the given IndexName.+func NormalizeIndexName(ctx parser.IIndexNameContext) string {+ if ctx.Identifier() != nil {+ return NormalizeMySQLIdentifier(ctx.Identifier())+ }+ return ""+}++// NormalizeMySQLIndexName normalize the given IndeRef.+func NormalizeIndexRef(ctx parser.IIndexRefContext) (string, string, string) {+ if ctx.FieldIdentifier() != nil {+ return NormalizeMySQLFieldIdentifier(ctx.FieldIdentifier())+ }+ return "", "", ""+}