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 column naming convention (#1234)
rebelicea14513d67107
diff --git a/common/error.go b/common/error.goindex efa1d978b1..85380871c4 100644--- a/common/error.go+++ b/common/error.go@@ -52,7 +52,8 @@ const (StatementNoWhere Code = 10101// 10201 naming advisor error code- TableNamingConventionMismatch Code = 10201+ NamingTableConventionMismatch Code = 10201+ NamingColumnConventionMismatch Code = 10202// 10301 column rule advisor error codeNoRequiredColumn Code = 10301diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 85f2451896..8f484965b0 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -53,14 +53,21 @@ type Type stringconst (// Fake is a fake advisor type for testing.Fake Type = "bb.plugin.advisor.fake"+// MySQLSyntax is an advisor type for MySQL syntax.MySQLSyntax Type = "bb.plugin.advisor.mysql.syntax"+// MySQLMigrationCompatibility is an advisor type for MySQL migration compatibility.MySQLMigrationCompatibility Type = "bb.plugin.advisor.mysql.migration-compatibility"+// MySQLWhereRequirement is an advisor type for MySQL WHERE clause requirement.MySQLWhereRequirement Type = "bb.plugin.advisor.mysql.where.require"+// MySQLNamingTableConvention is an advisor type for MySQL table naming convention.MySQLNamingTableConvention Type = "bb.plugin.advisor.mysql.naming.table"+ // MySQLNamingColumnConvention is an advisor type for MySQL column naming convention.+ MySQLNamingColumnConvention Type = "bb.plugin.advisor.mysql.naming.column"+// MySQLColumnRequirement is an advisor type for MySQL column requirement.MySQLColumnRequirement Type = "bb.plugin.advisor.mysql.column.require")diff --git a/plugin/advisor/mysql/advisor_column_required.go b/plugin/advisor/mysql/advisor_column_required.goindex a0c25e7e8a..082e5c0c64 100644--- a/plugin/advisor/mysql/advisor_column_required.go+++ b/plugin/advisor/mysql/advisor_column_required.go@@ -57,9 +57,6 @@ func (adv *ColumnRequirementAdvisor) Check(ctx advisor.Context, statement stringreturn checker.generateAdvisorList(), nil}-type columnSet map[string]bool-type tableState map[string]columnSet-type columnRequirementChecker struct {adviceList []advisor.Advicelevel advisor.Status@@ -74,8 +71,8 @@ func (v *columnRequirementChecker) Enter(in ast.Node) (ast.Node, bool) {v.createTable(node)// ALTER TABLEcase *ast.AlterTableStmt:+ table := node.Table.Name.Ofor _, spec := range node.Specs {- table := node.Table.Name.Oswitch spec.Tp {// RENAME COLUMNcase ast.AlterTableRenameColumn:@@ -103,11 +100,7 @@ func (v *columnRequirementChecker) Leave(in ast.Node) (ast.Node, bool) {func (v *columnRequirementChecker) generateAdvisorList() []advisor.Advice {// Order it cause the random iteration order in Go, see https://go.dev/blog/maps- var tableList []string- for tableName := range v.tables {- tableList = append(tableList, tableName)- }- sort.Strings(tableList)+ tableList := v.tables.tableList()for _, tableName := range tableList {table := v.tables[tableName]var missingColumns []stringdiff --git a/plugin/advisor/mysql/advisor_naming_column.go b/plugin/advisor/mysql/advisor_naming_column.gonew file mode 100644index 0000000000..c70242b902--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_column.go@@ -0,0 +1,117 @@+package mysql++import (+ "fmt"+ "regexp"++ "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 = (*NamingColumnConventionAdvisor)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLNamingColumnConvention, &NamingColumnConventionAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLNamingColumnConvention, &NamingColumnConventionAdvisor{})+}++// NamingColumnConventionAdvisor is the advisor checking for column naming convention.+type NamingColumnConventionAdvisor struct {+}++// Check checks for column naming convention.+func (adv *NamingColumnConventionAdvisor) 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, err := api.UnmarshalNamingRulePayloadFormat(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &namingColumnConventionChecker{+ level: level,+ format: format,+ tables: make(tableState),+ }++ 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 namingColumnConventionChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ format *regexp.Regexp+ tables tableState+}++func (v *namingColumnConventionChecker) Enter(in ast.Node) (ast.Node, bool) {+ var columnList []string+ var tableName string+ switch node := in.(type) {+ // CREATE TABLE+ case *ast.CreateTableStmt:+ tableName = node.Table.Name.O+ for _, column := range node.Cols {+ columnList = append(columnList, column.Name.Name.O)+ }+ // ALTER TABLE+ case *ast.AlterTableStmt:+ tableName = node.Table.Name.O+ for _, spec := range node.Specs {+ switch spec.Tp {+ // RENAME COLUMN+ case ast.AlterTableRenameColumn:+ columnList = append(columnList, spec.NewColumnName.Name.O)+ // ADD COLUMNS+ case ast.AlterTableAddColumns:+ for _, column := range spec.NewColumns {+ columnList = append(columnList, column.Name.Name.O)+ }+ // CHANGE COLUMN+ case ast.AlterTableChangeColumn:+ columnList = append(columnList, spec.NewColumns[0].Name.Name.O)+ }+ }+ }++ for _, column := range columnList {+ if !v.format.MatchString(column) {+ v.adviceList = append(v.adviceList, advisor.Advice{+ Status: v.level,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: fmt.Sprintf("`%s`.`%s` mismatches column naming convention", tableName, column),+ })+ }+ }++ return in, false+}++func (v *namingColumnConventionChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}diff --git a/plugin/advisor/mysql/advisor_naming_column_test.go b/plugin/advisor/mysql/advisor_naming_column_test.gonew file mode 100644index 0000000000..8ec8b44755--- /dev/null+++ b/plugin/advisor/mysql/advisor_naming_column_test.go@@ -0,0 +1,163 @@+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 TestNamingColumnConvention(t *testing.T) {+ tests := []test{+ {+ statement: "CREATE TABLE book(id int, creatorId int)",+ want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`book`.`creatorId` mismatches column naming convention",+ },+ },+ },+ {+ statement: "CREATE TABLE book(id int, creator_id int)",+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: `CREATE TABLE book(id int, creator_id int);+ ALTER TABLE book RENAME COLUMN creator_id TO creatorId`,+ want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`book`.`creatorId` mismatches column naming convention",+ },+ },+ },+ {+ statement: `ALTER TABLE book RENAME COLUMN creatorId TO creator_id;`,+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: `CREATE TABLE book(+ id int,+ creator_id int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp);+ ALTER TABLE book CHANGE COLUMN creator_id creatorId int;`,+ want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`book`.`creatorId` mismatches column naming convention",+ },+ },+ },+ {+ statement: `ALTER TABLE book CHANGE COLUMN creatorId creator_id int;`,+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: `ALTER TABLE book DROP COLUMN contentString;`,+ want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ statement: `CREATE TABLE book(+ id int,+ creator_id int,+ created_ts timestamp,+ updated_ts timestamp);+ ALTER TABLE book ADD COLUMN contentString varchar(255);`,+ want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`book`.`contentString` mismatches column naming convention",+ },+ },+ },+ {+ statement: `CREATE TABLE book(+ id int,+ createdTs timestamp,+ updaterId int,+ updated_ts timestamp);+ CREATE TABLE student(+ id int,+ createdTs timestamp,+ updatedTs timestamp);`,+ want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`book`.`createdTs` mismatches column naming convention",+ },+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`book`.`updaterId` mismatches column naming convention",+ },+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`student`.`createdTs` mismatches column naming convention",+ },+ {+ Status: advisor.Warn,+ Code: common.NamingColumnConventionMismatch,+ Title: "Mismatch column naming convention",+ Content: "`student`.`updatedTs` mismatches column naming convention",+ },+ },+ },+ }++ payload, err := json.Marshal(api.NamingRulePayload{+ Format: "^[a-z]+(_[a-z]+)?$",+ })+ require.NoError(t, err)+ runSchemaReviewRuleTests(t, tests, &NamingColumnConventionAdvisor{}, &api.SchemaReviewRule{+ Type: api.SchemaRuleColumnNaming,+ Level: api.SchemaRuleLevelWarning,+ Payload: string(payload),+ })+}diff --git a/plugin/advisor/mysql/advisor_naming_table.go b/plugin/advisor/mysql/advisor_naming_table.goindex 61578498d6..7533dbc18b 100644--- a/plugin/advisor/mysql/advisor_naming_table.go+++ b/plugin/advisor/mysql/advisor_naming_table.go@@ -90,7 +90,7 @@ func (v *namingTableConventionChecker) Enter(in ast.Node) (ast.Node, bool) {for _, tableName := range tableNames {if !v.format.MatchString(tableName) {- code = common.TableNamingConventionMismatch+ code = common.NamingTableConventionMismatchbreak}}diff --git a/plugin/advisor/mysql/advisor_naming_table_test.go b/plugin/advisor/mysql/advisor_naming_table_test.goindex 45dc61a07b..b40cd2fe14 100644--- a/plugin/advisor/mysql/advisor_naming_table_test.go+++ b/plugin/advisor/mysql/advisor_naming_table_test.go@@ -10,14 +10,14 @@ import ("github.com/stretchr/testify/require")-func TestTableNamingRequirement(t *testing.T) {+func TestNamingTableConvention(t *testing.T) {tests := []test{{statement: "CREATE TABLE techBook(id int, name varchar(255))",want: []advisor.Advice{{Status: advisor.Error,- Code: common.TableNamingConventionMismatch,+ Code: common.NamingTableConventionMismatch,Title: "Mismatch table naming convention",Content: "\"CREATE TABLE techBook(id int, name varchar(255))\" mismatches table naming convention",},@@ -39,7 +39,7 @@ func TestTableNamingRequirement(t *testing.T) {want: []advisor.Advice{{Status: advisor.Error,- Code: common.TableNamingConventionMismatch,+ Code: common.NamingTableConventionMismatch,Title: "Mismatch table naming convention",Content: "\"ALTER TABLE techBook RENAME TO TechBook\" mismatches table naming convention",},@@ -61,7 +61,7 @@ func TestTableNamingRequirement(t *testing.T) {want: []advisor.Advice{{Status: advisor.Error,- Code: common.TableNamingConventionMismatch,+ Code: common.NamingTableConventionMismatch,Title: "Mismatch table naming convention",Content: "\"RENAME TABLE techBook TO tech_book, literaryBook TO LiteraryBook\" mismatches table naming convention",},diff --git a/plugin/advisor/mysql/utils.go b/plugin/advisor/mysql/utils.gonew file mode 100644index 0000000000..4d0d9c7e00--- /dev/null+++ b/plugin/advisor/mysql/utils.go@@ -0,0 +1,16 @@+package mysql++import "sort"++type columnSet map[string]bool+type tableState map[string]columnSet++// tableList returns table list in lexicographical order.+func (t tableState) tableList() []string {+ var tableList []string+ for tableName := range t {+ tableList = append(tableList, tableName)+ }+ sort.Strings(tableList)+ return tableList+}diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.goindex 64737715ab..ec18fa750a 100644--- a/server/task_check_executor_statement_advisor_composite.go+++ b/server/task_check_executor_statement_advisor_composite.go@@ -128,6 +128,11 @@ func getAdvisorTypeByRule(ruleType api.SchemaReviewRuleType, engine db.Type) (adcase db.MySQL, db.TiDB:return advisor.MySQLNamingTableConvention, nil}+ case api.SchemaRuleColumnNaming:+ switch engine {+ case db.MySQL, db.TiDB:+ return advisor.MySQLNamingColumnConvention, nil+ }case api.SchemaRuleRequiredColumn:switch engine {case db.MySQL, db.TiDB: