Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(schema system): support MySQL index/pk/uk/fk naming convention rule (#1230)
ecmadaoc79aeba8b11d
diff --git a/api/schema_system.go b/api/schema_system.goindex 004f28feb7..e63b93baf0 100644--- a/api/schema_system.go+++ b/api/schema_system.go@@ -53,6 +53,43 @@ const (// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.SchemaRuleSchemaBackwardCompatibility SchemaReviewRuleType = "schema.backward-compatibility"++ // TableNameTemplateToken is the token for table name+ TableNameTemplateToken = "{{table}}"+ // ColumnListTemplateToken is the token for column name list+ ColumnListTemplateToken = "{{column_list}}"+ // ReferencingTableNameTemplateToken is the token for referencing table name+ ReferencingTableNameTemplateToken = "{{referencing_table}}"+ // ReferencingColumnNameTemplateToken is the token for referencing column name+ ReferencingColumnNameTemplateToken = "{{referencing_column}}"+ // ReferencedTableNameTemplateToken is the token for referenced table name+ ReferencedTableNameTemplateToken = "{{referenced_table}}"+ // ReferencedColumnNameTemplateToken is the token for referenced column name+ ReferencedColumnNameTemplateToken = "{{referenced_column}}"+)++var (+ // TemplateNamingTokens is the mapping for rule type to template token+ TemplateNamingTokens = map[SchemaReviewRuleType]map[string]bool{+ SchemaRulePKNaming: {+ TableNameTemplateToken: true,+ ColumnListTemplateToken: true,+ },+ SchemaRuleIDXNaming: {+ TableNameTemplateToken: true,+ ColumnListTemplateToken: true,+ },+ SchemaRuleUKNaming: {+ TableNameTemplateToken: true,+ ColumnListTemplateToken: true,+ },+ SchemaRuleFKNaming: {+ ReferencingTableNameTemplateToken: true,+ ReferencingColumnNameTemplateToken: true,+ ReferencedTableNameTemplateToken: true,+ ReferencedColumnNameTemplateToken: true,+ },+ })// SchemaReviewPolicy is the policy configuration for schema review.@@ -88,7 +125,11 @@ func (rule *SchemaReviewRule) Validate() error {// TODO(rebelice): add other schema review rule validation.switch rule.Type {case SchemaRuleTableNaming, SchemaRuleColumnNaming:- if _, err := UnmarshalNamingRulePayloadFormat(rule.Payload); err != nil {+ if _, err := UnamrshalNamingRulePayloadAsRegexp(rule.Payload); err != nil {+ return err+ }+ case SchemaRulePKNaming, SchemaRuleFKNaming, SchemaRuleIDXNaming, SchemaRuleUKNaming:+ if _, _, err := UnmarshalNamingRulePayloadAsTemplate(rule.Type, rule.Payload); err != nil {return err}case SchemaRuleRequiredColumn:@@ -109,8 +150,8 @@ type RequiredColumnRulePayload struct {ColumnList []string `json:"columnList"`}-// UnmarshalNamingRulePayloadFormat will unmarshal payload to NamingRulePayload and compile it as regular expression.-func UnmarshalNamingRulePayloadFormat(payload string) (*regexp.Regexp, error) {+// UnamrshalNamingRulePayloadAsRegexp will unmarshal payload to NamingRulePayload and compile it as regular expression.+func UnamrshalNamingRulePayloadAsRegexp(payload string) (*regexp.Regexp, error) {var nr NamingRulePayloadif err := json.Unmarshal([]byte(payload), &nr); err != nil {return nil, fmt.Errorf("failed to unmarshal naming rule payload %q: %q", payload, err)@@ -122,6 +163,27 @@ func UnmarshalNamingRulePayloadFormat(payload string) (*regexp.Regexp, error) {return format, nil}+// UnmarshalNamingRulePayloadAsTemplate will unmarshal payload to NamingRulePayload and extract all the template keys.+// For example, "hard_code_{{table}}_{{column}}_end" will return+// "hard_code_{{table}}_{{column}}_end", ["{{table}}", "{{column}}"]+func UnmarshalNamingRulePayloadAsTemplate(ruleType SchemaReviewRuleType, payload string) (string, []string, error) {+ var nr NamingRulePayload+ if err := json.Unmarshal([]byte(payload), &nr); err != nil {+ return "", nil, fmt.Errorf("failed to unmarshal naming rule payload %q: %q", payload, err)+ }++ template := nr.Format+ keys := getTemplateTokens(template)++ for _, key := range keys {+ if _, ok := TemplateNamingTokens[ruleType][key]; !ok {+ return "", nil, fmt.Errorf("invalid template %s for rule %s", key, ruleType)+ }+ }++ return template, keys, nil+}+// UnmarshalRequiredColumnRulePayload will unmarshal payload to RequiredColumnRulePayload.func UnmarshalRequiredColumnRulePayload(payload string) (*RequiredColumnRulePayload, error) {var rcr RequiredColumnRulePayloaddiff --git a/common/error.go b/common/error.goindex 85380871c4..11405b897d 100644--- a/common/error.go+++ b/common/error.go@@ -51,9 +51,18 @@ const (StatementNoWhere Code = 10101- // 10201 naming advisor error code- NamingTableConventionMismatch Code = 10201+ // 10201 table naming advisor error code+ NamingTableConventionMismatch Code = 10201+ // 10202 column naming advisor error codeNamingColumnConventionMismatch Code = 10202+ // 10203 index naming advisor error code+ NamingIndexConventionMismatch Code = 10203+ // 10203 unique key naming advisor error code+ NamingUKConventionMismatch Code = 10204+ // 10203 primary key naming advisor error code+ NamingPKConventionMismatch Code = 10205+ // 10203 foreign key naming advisor error code+ NamingFKConventionMismatch Code = 10206// 10301 column rule advisor error codeNoRequiredColumn Code = 10301diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 8f484965b0..a737635a49 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -8,6 +8,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/catalog""github.com/bytebase/bytebase/plugin/db""go.uber.org/zap")@@ -65,6 +66,19 @@ const (// MySQLNamingTableConvention is an advisor type for MySQL table naming convention.MySQLNamingTableConvention Type = "bb.plugin.advisor.mysql.naming.table"++ // MySQLNamingIndexConvention is an advisor type for MySQL index key naming convention.+ MySQLNamingIndexConvention Type = "bb.plugin.advisor.mysql.naming.index"++ // MySQLNamingUKConvention is an advisor type for MySQL unique key naming convention.+ MySQLNamingUKConvention Type = "bb.plugin.advisor.mysql.naming.uk"++ // MySQLNamingPKConvention is an advisor type for MySQL primary key naming convention.+ MySQLNamingPKConvention Type = "bb.plugin.advisor.mysql.naming.pk"++ // MySQLNamingFKConvention is an advisor type for MySQL foreign key naming convention.+ MySQLNamingFKConvention Type = "bb.plugin.advisor.mysql.naming.fk"+// MySQLNamingColumnConvention is an advisor type for MySQL column naming convention.MySQLNamingColumnConvention Type = "bb.plugin.advisor.mysql.naming.column"@@ -87,7 +101,8 @@ type Context struct {Collation string// Schema review rule special fields.- Rule *api.SchemaReviewRule+ Rule *api.SchemaReviewRule+ Catalog catalog.Service}// Advisor is the interface for advisor.diff --git a/plugin/advisor/mysql/advisor_column_required_test.go b/plugin/advisor/mysql/advisor_column_required_test.goindex 8f67006a08..78a8280fc4 100644--- a/plugin/advisor/mysql/advisor_column_required_test.go+++ b/plugin/advisor/mysql/advisor_column_required_test.go@@ -215,5 +215,5 @@ func TestColumnRequirement(t *testing.T) {Type: api.SchemaRuleRequiredColumn,Level: api.SchemaRuleLevelWarning,Payload: string(payload),- })+ }, &MockCatalogService{})}diff --git a/plugin/advisor/mysql/advisor_naming_column.go b/plugin/advisor/mysql/advisor_naming_column.goindex 09075711bd..927a373791 100644--- a/plugin/advisor/mysql/advisor_naming_column.go+++ b/plugin/advisor/mysql/advisor_naming_column.go@@ -35,7 +35,7 @@ func (adv *NamingColumnConventionAdvisor) Check(ctx advisor.Context, statement sif err != nil {return nil, err}- format, err := api.UnmarshalNamingRulePayloadFormat(ctx.Rule.Payload)+ format, err := api.UnamrshalNamingRulePayloadAsRegexp(ctx.Rule.Payload)if err != nil {return nil, err}diff --git a/plugin/advisor/mysql/advisor_naming_column_test.go b/plugin/advisor/mysql/advisor_naming_column_test.goindex 1302c1d6f5..f4b1173175 100644--- a/plugin/advisor/mysql/advisor_naming_column_test.go+++ b/plugin/advisor/mysql/advisor_naming_column_test.go@@ -159,5 +159,5 @@ func TestNamingColumnConvention(t *testing.T) {Type: api.SchemaRuleColumnNaming,Level: api.SchemaRuleLevelWarning,Payload: string(payload),- })+ }, &MockCatalogService{})}diff --git a/plugin/advisor/mysql/advisor_naming_foreign_key_convention.go b/plugin/advisor/mysql/advisor_naming_foreign_key_convention.gonew file mode 100644index 0000000000..8b6ad41b3a--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_foreign_key_convention.go@@ -0,0 +1,163 @@+package mysql++import (+ "fmt"+ "strings"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/pingcap/tidb/parser/ast"+)++var (+ _ advisor.Advisor = (*NamingFKConventionAdvisor)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})+}++// NamingFKConventionAdvisor is the advisor checking for foreign key naming convention.+type NamingFKConventionAdvisor struct {+}++// Check checks for foreign key naming convention.+func (check *NamingFKConventionAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySchemaReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ format, templateList, err := api.UnmarshalNamingRulePayloadAsTemplate(ctx.Rule.Type, ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &namingFKConventionChecker{+ level: level,+ format: format,+ templateList: templateList,+ }+ for _, stmtNode := range root {+ (stmtNode).Accept(checker)+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ })+ }++ return checker.adviceList, nil+}++type namingFKConventionChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ format string+ templateList []string+}++// Enter implements the ast.Visitor interface+func (checker *namingFKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {+ indexDataList := checker.getMetaDataList(in)++ for _, indexData := range indexDataList {+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)+ if err != nil {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.Internal,+ Title: "Internal error for foreign key naming convention rule",+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),+ })+ continue+ }+ if !regex.MatchString(indexData.indexName) {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.NamingFKConventionMismatch,+ Title: "Mismatch foreign key naming convention",+ Content: fmt.Sprintf("Foreign key in table `%s` mismatches the naming convention, expect %q but found `%s`", indexData.tableName, regex, indexData.indexName),+ })+ }+ }++ return in, false+}++// Leave implements the ast.Visitor interface+func (checker *namingFKConventionChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++// getMetaDataList returns the list of foreign key with meta data.+func (checker *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{+ api.ReferencingTableNameTemplateToken: node.Table.Name.String(),+ api.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),+ api.ReferencedTableNameTemplateToken: constraint.Refer.Table.Name.String(),+ api.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),+ }++ res = append(res, &indexMetaData{+ indexName: constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ 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{+ api.ReferencingTableNameTemplateToken: node.Table.Name.String(),+ api.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),+ api.ReferencedTableNameTemplateToken: spec.Constraint.Refer.Table.Name.String(),+ api.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),+ }+ res = append(res, &indexMetaData{+ indexName: spec.Constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ }++ return res+}diff --git a/plugin/advisor/mysql/advisor_naming_foreign_key_convention_test.go b/plugin/advisor/mysql/advisor_naming_foreign_key_convention_test.gonew file mode 100644index 0000000000..e778762386--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_foreign_key_convention_test.go@@ -0,0 +1,70 @@+package mysql++import (+ "encoding/json"+ "testing"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/stretchr/testify/require"+)++func TestNamingFKConvention(t *testing.T) {+ tests := []test{+ {+ 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.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "ALTER TABLE tech_book ADD CONSTRAINT fk_author_id FOREIGN KEY (author_id) REFERENCES author (id)",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingFKConventionMismatch,+ Title: "Mismatch foreign key naming convention",+ Content: "Foreign key in table `tech_book` mismatches the naming convention, expect \"^fk_tech_book_author_id_author_id$\" but found `fk_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: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id (author_id) REFERENCES author (id))",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingFKConventionMismatch,+ Title: "Mismatch foreign key naming convention",+ Content: "Foreign key in table `book` mismatches the naming convention, expect \"^fk_book_author_id_author_id$\" but found `fk_book_author_id`",+ },+ },+ },+ }++ payload, err := json.Marshal(api.NamingRulePayload{+ Format: "^fk_{{referencing_table}}_{{referencing_column}}_{{referenced_table}}_{{referenced_column}}$",+ })+ require.NoError(t, err)+ runSchemaReviewRuleTests(t, tests, &NamingFKConventionAdvisor{}, &api.SchemaReviewRule{+ Type: api.SchemaRuleFKNaming,+ Level: api.SchemaRuleLevelError,+ Payload: string(payload),+ }, &MockCatalogService{})+}diff --git a/plugin/advisor/mysql/advisor_naming_index_convention.go b/plugin/advisor/mysql/advisor_naming_index_convention.gonew file mode 100644index 0000000000..ce1471f459--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_index_convention.go@@ -0,0 +1,221 @@+package mysql++import (+ "context"+ "fmt"+ "regexp"+ "strings"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/catalog"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/pingcap/tidb/parser/ast"+ "go.uber.org/zap"+)++var (+ _ advisor.Advisor = (*NamingIndexConventionAdvisor)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLNamingIndexConvention, &NamingIndexConventionAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLNamingIndexConvention, &NamingIndexConventionAdvisor{})+}++// NamingIndexConventionAdvisor is the advisor checking for index naming convention.+type NamingIndexConventionAdvisor struct {+}++// Check checks for index naming convention.+func (check *NamingIndexConventionAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySchemaReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ format, templateList, err := api.UnmarshalNamingRulePayloadAsTemplate(ctx.Rule.Type, ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &namingIndexConventionChecker{+ level: level,+ format: format,+ templateList: templateList,+ catalog: ctx.Catalog,+ logger: ctx.Logger,+ }+ for _, stmtNode := range root {+ (stmtNode).Accept(checker)+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ })+ }++ return checker.adviceList, nil+}++type namingIndexConventionChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ format string+ templateList []string+ catalog catalog.Service+ logger *zap.Logger+}++// Enter implements the ast.Visitor interface+func (checker *namingIndexConventionChecker) Enter(in ast.Node) (ast.Node, bool) {+ indexDataList := checker.getMetaDataList(in)++ for _, indexData := range indexDataList {+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)+ if err != nil {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.Internal,+ Title: "Internal error for index naming convention rule",+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),+ })+ continue+ }+ if !regex.MatchString(indexData.indexName) {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.NamingIndexConventionMismatch,+ Title: "Mismatch index naming convention",+ Content: fmt.Sprintf("Index in table `%s` mismatches the naming convention, expect %q but found `%s`", indexData.tableName, regex, indexData.indexName),+ })+ }+ }++ return in, false+}++// Leave implements the ast.Visitor interface+func (checker *namingIndexConventionChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++type indexMetaData struct {+ indexName string+ tableName string+ metaData map[string]string+}++// getMetaDataList returns the list of index with meta data.+func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {+ var res []*indexMetaData++ switch node := in.(type) {+ case *ast.CreateTableStmt:+ for _, constraint := range node.Constraints {+ if constraint.Tp == ast.ConstraintIndex {+ var columnList []string+ for _, key := range constraint.Keys {+ columnList = append(columnList, key.Column.Name.String())+ }+ metaData := map[string]string{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ case *ast.AlterTableStmt:+ for _, spec := range node.Specs {+ switch spec.Tp {+ case ast.AlterTableRenameIndex:+ ctx := context.Background()+ index, err := checker.catalog.FindIndex(ctx, &catalog.IndexFind{+ TableName: node.Table.Name.String(),+ IndexName: spec.FromKey.String(),+ })+ if err != nil {+ checker.logger.Error(+ "Cannot find index in table",+ zap.String("table_name", node.Table.Name.String()),+ zap.String("index_name", spec.FromKey.String()),+ zap.Error(err),+ )+ continue+ }+ if index.Unique {+ // Unique index naming convention should in advisor_naming_unique_key_convention.go+ continue+ }+ metaData := map[string]string{+ api.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: spec.ToKey.String(),+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ case ast.AlterTableAddConstraint:+ if spec.Constraint.Tp == ast.ConstraintIndex {+ var columnList []string+ for _, key := range spec.Constraint.Keys {+ columnList = append(columnList, key.Column.Name.String())+ }++ metaData := map[string]string{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: spec.Constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ }+ 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{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: node.IndexName,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }++ return 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/plugin/advisor/mysql/advisor_naming_index_convention_test.go b/plugin/advisor/mysql/advisor_naming_index_convention_test.gonew file mode 100644index 0000000000..c51478670c--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_index_convention_test.go@@ -0,0 +1,123 @@+package mysql++import (+ "encoding/json"+ "fmt"+ "strings"+ "testing"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/stretchr/testify/require"+)++func TestNamingIndexConvention(t *testing.T) {+ tests := []test{+ {+ statement: "CREATE INDEX idx_tech_book_id_name ON tech_book(id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "CREATE INDEX tech_book_id_name ON tech_book(id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingIndexConventionMismatch,+ Title: "Mismatch index naming convention",+ Content: "Index in table `tech_book` mismatches the naming convention, expect \"^idx_tech_book_id_name$\" but found `tech_book_id_name`",+ },+ },+ },+ {+ statement: fmt.Sprintf(+ "ALTER TABLE tech_book RENAME INDEX %s TO idx_tech_book_%s",+ MockOldIndexName,+ strings.Join(MockIndexColumnList, "_"),+ ),+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: fmt.Sprintf(+ "ALTER TABLE tech_book RENAME INDEX %s TO idx_tech_book",+ MockOldIndexName,+ ),+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingIndexConventionMismatch,+ Title: "Mismatch index naming convention",+ Content: "Index in table `tech_book` mismatches the naming convention, expect \"^idx_tech_book_id_name$\" but found `idx_tech_book`",+ },+ },+ },+ {+ statement: "ALTER TABLE tech_book ADD INDEX idx_tech_book_id_name (id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "ALTER TABLE tech_book ADD INDEX tech_book_id_name (id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingIndexConventionMismatch,+ Title: "Mismatch index naming convention",+ Content: "Index in table `tech_book` mismatches the naming convention, expect \"^idx_tech_book_id_name$\" but found `tech_book_id_name`",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), INDEX idx_tech_book_name (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), INDEX (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingIndexConventionMismatch,+ Title: "Mismatch index naming convention",+ Content: "Index in table `tech_book` mismatches the naming convention, expect \"^idx_tech_book_name$\" but found ``",+ },+ },+ },+ }++ payload, err := json.Marshal(api.NamingRulePayload{+ Format: "^idx_{{table}}_{{column_list}}$",+ })+ require.NoError(t, err)+ runSchemaReviewRuleTests(t, tests, &NamingIndexConventionAdvisor{}, &api.SchemaReviewRule{+ Type: api.SchemaRuleIDXNaming,+ Level: api.SchemaRuleLevelError,+ Payload: string(payload),+ }, &MockCatalogService{})+}diff --git a/plugin/advisor/mysql/advisor_naming_primary_key_convention.go b/plugin/advisor/mysql/advisor_naming_primary_key_convention.gonew file mode 100644index 0000000000..43840d17d6--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_primary_key_convention.go@@ -0,0 +1,148 @@+package mysql++import (+ "fmt"+ "strings"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/pingcap/tidb/parser/ast"+)++var (+ _ advisor.Advisor = (*NamingPKConventionAdvisor)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLNamingPKConvention, &NamingPKConventionAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLNamingPKConvention, &NamingPKConventionAdvisor{})+}++// NamingPKConventionAdvisor is the advisor checking for primary key naming convention.+type NamingPKConventionAdvisor struct {+}++// Check checks for primary key naming convention.+func (check *NamingPKConventionAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySchemaReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ format, templateList, err := api.UnmarshalNamingRulePayloadAsTemplate(ctx.Rule.Type, ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &namingPKConventionChecker{+ level: level,+ format: format,+ templateList: templateList,+ }+ for _, stmtNode := range root {+ (stmtNode).Accept(checker)+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return checker.adviceList, nil+}++type namingPKConventionChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ format string+ templateList []string+}++// Enter implements the ast.Visitor interface+func (checker *namingPKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {+ indexDataList := checker.getMetaDataList(in)++ for _, indexData := range indexDataList {+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)+ if err != nil {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.Internal,+ Title: "Internal error for primary key naming convention rule",+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),+ })+ continue+ }+ if !regex.MatchString(indexData.indexName) {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.NamingPKConventionMismatch,+ Title: "Mismatch primary key naming convention",+ Content: fmt.Sprintf("Primary key in table `%s` mismatches the naming convention, expect %q but found `%s`", indexData.tableName, regex, indexData.indexName),+ })+ }+ }++ return in, false+}++// Leave implements the ast.Visitor interface+func (checker *namingPKConventionChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++// getMetaDataList returns the list of primary key with meta data.+func (checker *namingPKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {+ var res []*indexMetaData++ switch node := in.(type) {+ case *ast.CreateTableStmt:+ for _, constraint := range node.Constraints {+ if constraint.Tp == ast.ConstraintPrimaryKey {+ var columnList []string+ for _, key := range constraint.Keys {+ columnList = append(columnList, key.Column.Name.String())+ }+ metaData := map[string]string{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ case *ast.AlterTableStmt:+ for _, spec := range node.Specs {+ if spec.Tp == ast.AlterTableAddConstraint && spec.Constraint.Tp == ast.ConstraintPrimaryKey {+ var columnList []string+ for _, key := range spec.Constraint.Keys {+ columnList = append(columnList, key.Column.Name.String())+ }++ metaData := map[string]string{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: spec.Constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ }++ return res+}diff --git a/plugin/advisor/mysql/advisor_naming_primary_key_convention_test.go b/plugin/advisor/mysql/advisor_naming_primary_key_convention_test.gonew file mode 100644index 0000000000..b5ca0f6fdf--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_primary_key_convention_test.go@@ -0,0 +1,70 @@+package mysql++import (+ "encoding/json"+ "testing"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/stretchr/testify/require"+)++func TestNamingPKConvention(t *testing.T) {+ tests := []test{+ {+ statement: "ALTER TABLE tech_book ADD PRIMARY KEY pk_tech_book_id (id)",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "ALTER TABLE tech_book ADD PRIMARY KEY tech_book_id (id)",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingPKConventionMismatch,+ Title: "Mismatch primary key naming convention",+ Content: "Primary key in table `tech_book` mismatches the naming convention, expect \"^pk_tech_book_id$\" but found `tech_book_id`",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT, name VARCHAR(20), PRIMARY KEY pk_tech_book_name (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT, name VARCHAR(20), PRIMARY KEY (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingPKConventionMismatch,+ Title: "Mismatch primary key naming convention",+ Content: "Primary key in table `tech_book` mismatches the naming convention, expect \"^pk_tech_book_name$\" but found ``",+ },+ },+ },+ }++ payload, err := json.Marshal(api.NamingRulePayload{+ Format: "^pk_{{table}}_{{column_list}}$",+ })+ require.NoError(t, err)+ runSchemaReviewRuleTests(t, tests, &NamingPKConventionAdvisor{}, &api.SchemaReviewRule{+ Type: api.SchemaRulePKNaming,+ Level: api.SchemaRuleLevelError,+ Payload: string(payload),+ }, &MockCatalogService{})+}diff --git a/plugin/advisor/mysql/advisor_naming_table.go b/plugin/advisor/mysql/advisor_naming_table.goindex d0f441a5df..a5818b942d 100644--- a/plugin/advisor/mysql/advisor_naming_table.go+++ b/plugin/advisor/mysql/advisor_naming_table.go@@ -35,7 +35,7 @@ func (adv *NamingTableConventionAdvisor) Check(ctx advisor.Context, statement stif err != nil {return nil, err}- format, err := api.UnmarshalNamingRulePayloadFormat(ctx.Rule.Payload)+ format, err := api.UnamrshalNamingRulePayloadAsRegexp(ctx.Rule.Payload)if err != nil {return nil, err}diff --git a/plugin/advisor/mysql/advisor_naming_table_test.go b/plugin/advisor/mysql/advisor_naming_table_test.goindex ee7027adbe..0db27350fd 100644--- a/plugin/advisor/mysql/advisor_naming_table_test.go+++ b/plugin/advisor/mysql/advisor_naming_table_test.go@@ -104,5 +104,5 @@ func TestNamingTableConvention(t *testing.T) {Type: api.SchemaRuleTableNaming,Level: api.SchemaRuleLevelError,Payload: string(payload),- })+ }, &MockCatalogService{})}diff --git a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go b/plugin/advisor/mysql/advisor_naming_unique_key_convention.gonew file mode 100644index 0000000000..c18a887b87--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_unique_key_convention.go@@ -0,0 +1,204 @@+package mysql++import (+ "context"+ "fmt"+ "strings"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/catalog"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/pingcap/tidb/parser/ast"+ "go.uber.org/zap"+)++var (+ _ advisor.Advisor = (*NamingUKConventionAdvisor)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})+}++// NamingUKConventionAdvisor is the advisor checking for unique key naming convention.+type NamingUKConventionAdvisor struct {+}++// Check checks for index naming convention.+func (check *NamingUKConventionAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySchemaReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ format, templateList, err := api.UnmarshalNamingRulePayloadAsTemplate(ctx.Rule.Type, ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &namingUKConventionChecker{+ level: level,+ format: format,+ templateList: templateList,+ catalog: ctx.Catalog,+ logger: ctx.Logger,+ }+ for _, stmtNode := range root {+ (stmtNode).Accept(checker)+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return checker.adviceList, nil+}++type namingUKConventionChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ format string+ templateList []string+ catalog catalog.Service+ logger *zap.Logger+}++// Enter implements the ast.Visitor interface+func (checker *namingUKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {+ indexDataList := checker.getMetaDataList(in)++ for _, indexData := range indexDataList {+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)+ if err != nil {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.Internal,+ Title: "Internal error for unique key naming convention rule",+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),+ })+ continue+ }+ if !regex.MatchString(indexData.indexName) {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: common.NamingUKConventionMismatch,+ Title: "Mismatch unique key naming convention",+ Content: fmt.Sprintf("Unique key in table `%s` mismatches the naming convention, expect %q but found `%s`", indexData.tableName, regex, indexData.indexName),+ })+ }+ }++ return in, false+}++// Leave implements the ast.Visitor interface+func (checker *namingUKConventionChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++// 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{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ case *ast.AlterTableStmt:+ for _, spec := range node.Specs {+ switch spec.Tp {+ case ast.AlterTableRenameIndex:+ ctx := context.Background()+ index, err := checker.catalog.FindIndex(ctx, &catalog.IndexFind{+ TableName: node.Table.Name.String(),+ IndexName: spec.FromKey.String(),+ })+ if err != nil {+ checker.logger.Error(+ "Cannot find index in table",+ zap.String("table_name", node.Table.Name.String()),+ zap.String("index_name", spec.FromKey.String()),+ zap.Error(err),+ )+ continue+ }+ if !index.Unique {+ // Index naming convention should in advisor_naming_index_convention.go+ continue+ }+ metaData := map[string]string{+ api.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: spec.ToKey.String(),+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ 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{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: spec.Constraint.Name,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }+ }+ 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{+ api.ColumnListTemplateToken: strings.Join(columnList, "_"),+ api.TableNameTemplateToken: node.Table.Name.String(),+ }+ res = append(res, &indexMetaData{+ indexName: node.IndexName,+ tableName: node.Table.Name.String(),+ metaData: metaData,+ })+ }+ }++ return res+}diff --git a/plugin/advisor/mysql/advisor_naming_unique_key_convention_test.go b/plugin/advisor/mysql/advisor_naming_unique_key_convention_test.gonew file mode 100644index 0000000000..057eeafe34--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_unique_key_convention_test.go@@ -0,0 +1,145 @@+package mysql++import (+ "encoding/json"+ "fmt"+ "strings"+ "testing"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/stretchr/testify/require"+)++func TestNamingUKConvention(t *testing.T) {+ tests := []test{+ {+ statement: "CREATE UNIQUE INDEX uk_tech_book_id_name ON tech_book(id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "CREATE UNIQUE INDEX tech_book_id_name ON tech_book(id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingUKConventionMismatch,+ Title: "Mismatch unique key naming convention",+ Content: "Unique key in table `tech_book` mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found `tech_book_id_name`",+ },+ },+ },+ {+ statement: "ALTER TABLE tech_book ADD UNIQUE uk_tech_book_id_name (id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "ALTER TABLE tech_book ADD UNIQUE tech_book_id_name (id, name)",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingUKConventionMismatch,+ Title: "Mismatch unique key naming convention",+ Content: "Unique key in table `tech_book` mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found `tech_book_id_name`",+ },+ },+ },+ {+ statement: fmt.Sprintf(+ "ALTER TABLE tech_book RENAME INDEX %s TO uk_tech_book_%s",+ MockOldUKName,+ strings.Join(MockIndexColumnList, "_"),+ ),+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: fmt.Sprintf(+ "ALTER TABLE tech_book RENAME INDEX %s TO uk_tech_book",+ MockOldUKName,+ ),+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingUKConventionMismatch,+ Title: "Mismatch unique key naming convention",+ Content: "Unique key in table `tech_book` mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found `uk_tech_book`",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE INDEX uk_tech_book_name (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE KEY (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingUKConventionMismatch,+ Title: "Mismatch unique key naming convention",+ Content: "Unique key in table `tech_book` mismatches the naming convention, expect \"^uk_tech_book_name$\" but found ``",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE INDEX (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingUKConventionMismatch,+ Title: "Mismatch unique key naming convention",+ Content: "Unique key in table `tech_book` mismatches the naming convention, expect \"^uk_tech_book_name$\" but found ``",+ },+ },+ },+ {+ statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE KEY (name))",+ want: []advisor.Advice{+ {+ Status: advisor.Error,+ Code: common.NamingUKConventionMismatch,+ Title: "Mismatch unique key naming convention",+ Content: "Unique key in table `tech_book` mismatches the naming convention, expect \"^uk_tech_book_name$\" but found ``",+ },+ },+ },+ }++ payload, err := json.Marshal(api.NamingRulePayload{+ Format: "^uk_{{table}}_{{column_list}}$",+ })+ require.NoError(t, err)+ runSchemaReviewRuleTests(t, tests, &NamingUKConventionAdvisor{}, &api.SchemaReviewRule{+ Type: api.SchemaRuleUKNaming,+ Level: api.SchemaRuleLevelError,+ Payload: string(payload),+ }, &MockCatalogService{})+}diff --git a/plugin/advisor/mysql/advisor_stmt_where_required_test.go b/plugin/advisor/mysql/advisor_stmt_where_required_test.goindex 4b77fe192d..ae816b2680 100644--- a/plugin/advisor/mysql/advisor_stmt_where_required_test.go+++ b/plugin/advisor/mysql/advisor_stmt_where_required_test.go@@ -6,26 +6,8 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/advisor"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"- "go.uber.org/zap")-func runSchemaReviewRuleTests(t *testing.T, tests []test, adv advisor.Advisor, rule *api.SchemaReviewRule) {- logger, _ := zap.NewDevelopmentConfig().Build()- ctx := advisor.Context{- Logger: logger,- Charset: "",- Collation: "",- Rule: rule,- }- for _, tc := range tests {- adviceList, err := adv.Check(ctx, tc.statement)- require.NoError(t, err)- assert.Equal(t, tc.want, adviceList)- }-}-func TestWhereRequirement(t *testing.T) {tests := []test{{@@ -78,5 +60,5 @@ func TestWhereRequirement(t *testing.T) {Type: api.SchemaRuleStatementRequireWhere,Level: api.SchemaRuleLevelWarning,Payload: "",- })+ }, &MockCatalogService{})}diff --git a/plugin/advisor/mysql/utils.go b/plugin/advisor/mysql/utils.goindex 4d0d9c7e00..c7a75b92cf 100644--- a/plugin/advisor/mysql/utils.go+++ b/plugin/advisor/mysql/utils.go@@ -1,6 +1,8 @@package mysql-import "sort"+import (+ "sort"+)type columnSet map[string]booltype tableState map[string]columnSetdiff --git a/plugin/advisor/mysql/utils_for_test.go b/plugin/advisor/mysql/utils_for_test.gonew file mode 100644index 0000000000..e62b722e23--- /dev/null+++ b/plugin/advisor/mysql/utils_for_test.go@@ -0,0 +1,64 @@+package mysql++import (+ "context"+ "fmt"+ "testing"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/catalog"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.uber.org/zap"+)++type MockCatalogService struct{}++const (+ MockOldIndexName = "old_index"+ MockOldUKName = "old_uk"+)++var (+ MockIndexColumnList = []string{"id", "name"}+)++func (c *MockCatalogService) FindIndex(ctx context.Context, find *catalog.IndexFind) (*catalog.Index, error) {+ switch find.IndexName {+ case MockOldIndexName:+ return &catalog.Index{+ Name: MockOldIndexName,+ ColumnExpressions: MockIndexColumnList,+ }, nil+ case MockOldUKName:+ return &catalog.Index{+ Unique: true,+ Name: MockOldIndexName,+ ColumnExpressions: MockIndexColumnList,+ }, nil+ }+ return nil, fmt.Errorf("cannot find index for %v", find)+}++func runSchemaReviewRuleTests(+ t *testing.T,+ tests []test,+ adv advisor.Advisor,+ rule *api.SchemaReviewRule,+ catalog catalog.Service,+) {+ logger, _ := zap.NewDevelopmentConfig().Build()+ ctx := advisor.Context{+ Logger: logger,+ Charset: "",+ Collation: "",+ Rule: rule,+ Catalog: catalog,+ }+ for _, tc := range tests {+ adviceList, err := adv.Check(ctx, tc.statement)+ require.NoError(t, err)+ assert.Equal(t, tc.want, adviceList)+ }+}diff --git a/plugin/catalog/catalog.go b/plugin/catalog/catalog.gonew file mode 100644index 0000000000..a2e8b69acd--- /dev/null+++ b/plugin/catalog/catalog.go@@ -0,0 +1,88 @@+package catalog++import (+ "context"+ "sort"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/store"+ "go.uber.org/zap"+)++// Catalog is the database catalog.+type Catalog struct {+ logger *zap.Logger++ // catalog special fields.+ databaseID *int+ store *store.Store+}++// Service is the service for catalog.+type Service interface {+ FindIndex(ctx context.Context, find *IndexFind) (*Index, error)+}++// Index is the API message for an index.+type Index struct {+ Name string+ TableName string+ Type string+ Unique bool+ ColumnExpressions []string+}++// IndexFind is the API message for find index+type IndexFind struct {+ TableName string+ IndexName string+}++// NewService creates a new instance of Catalog+func NewService(logger *zap.Logger, databaseID *int, store *store.Store) *Catalog {+ return &Catalog{+ logger: logger,+ databaseID: databaseID,+ store: store,+ }+}++// FindIndex finds the index by IndexFind+func (c *Catalog) FindIndex(ctx context.Context, find *IndexFind) (*Index, error) {+ table, err := c.store.GetTable(ctx, &api.TableFind{+ DatabaseID: c.databaseID,+ Name: &find.TableName,+ })+ if err != nil {+ return nil, err+ }++ indexList, err := c.store.FindIndex(ctx, &api.IndexFind{+ DatabaseID: c.databaseID,+ TableID: &table.ID,+ Name: &find.IndexName,+ })+ if err != nil {+ return nil, err+ }+ if len(indexList) == 0 {+ return nil, nil+ }++ sort.Slice(indexList, func(i, j int) bool {+ return indexList[i].Position < indexList[j].Position+ })++ var columnExpressions []string+ for _, index := range indexList {+ columnExpressions = append(columnExpressions, index.Expression)+ }++ return &Index{+ Name: indexList[0].Name,+ TableName: table.Name,+ Type: indexList[0].Type,+ Unique: indexList[0].Unique,+ ColumnExpressions: columnExpressions,+ }, nil+}diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.goindex ec18fa750a..de5d34b5ee 100644--- a/server/task_check_executor_statement_advisor_composite.go+++ b/server/task_check_executor_statement_advisor_composite.go@@ -8,6 +8,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/catalog""github.com/bytebase/bytebase/plugin/db""go.uber.org/zap")@@ -54,6 +55,11 @@ func (exec *TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context,return nil, common.Errorf(common.Internal, fmt.Errorf("failed to get schema review policy: %w", err))}+ task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)+ if err != nil {+ return nil, common.Errorf(common.Internal, fmt.Errorf("failed to get task by id: %w", err))+ }+result = []api.TaskCheckResult{}for _, rule := range policy.RuleList {if rule.Level == api.SchemaRuleLevelDisabled {@@ -72,6 +78,7 @@ func (exec *TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context,Charset: payload.Charset,Collation: payload.Collation,Rule: rule,+ Catalog: catalog.NewService(exec.l, task.DatabaseID, server.store),},payload.Statement,)@@ -128,6 +135,26 @@ func getAdvisorTypeByRule(ruleType api.SchemaReviewRuleType, engine db.Type) (adcase db.MySQL, db.TiDB:return advisor.MySQLNamingTableConvention, nil}+ case api.SchemaRuleIDXNaming:+ switch engine {+ case db.MySQL, db.TiDB:+ return advisor.MySQLNamingIndexConvention, nil+ }+ case api.SchemaRuleUKNaming:+ switch engine {+ case db.MySQL, db.TiDB:+ return advisor.MySQLNamingUKConvention, nil+ }+ case api.SchemaRulePKNaming:+ switch engine {+ case db.MySQL, db.TiDB:+ return advisor.MySQLNamingPKConvention, nil+ }+ case api.SchemaRuleFKNaming:+ switch engine {+ case db.MySQL, db.TiDB:+ return advisor.MySQLNamingFKConvention, nil+ }case api.SchemaRuleColumnNaming:switch engine {case db.MySQL, db.TiDB: