Skip to content

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

feat(schema system): support MySQL table naming convention rule (#1208)

rebelice07441b6a2088
diff --git a/api/policy.go b/api/policy.go
index 22f6321192..94cbfc0d11 100644
--- a/api/policy.go
+++ b/api/policy.go
@@ -196,8 +196,8 @@ func ValidatePolicy(pType PolicyType, payload string) error {
if err != nil {
return err
}
- if sr.Name == "" || len(sr.RuleList) == 0 {
- return fmt.Errorf("invalid payload for schema review policy, name or rule list cannot be empty")
+ if err := sr.Validate(); err != nil {
+ return fmt.Errorf("invalid schema review policy: %w", err)
}
}
return nil
diff --git a/api/schema_system.go b/api/schema_system.go
index 2c73a6d5dc..62f3458b88 100644
--- a/api/schema_system.go
+++ b/api/schema_system.go
@@ -1,5 +1,11 @@
package api
+import (
+ "encoding/json"
+ "fmt"
+ "regexp"
+)
+
// SchemaReviewRuleLevel is the error level for schema review rule.
type SchemaReviewRuleLevel string
@@ -52,6 +58,19 @@ type SchemaReviewPolicy struct {
RuleList []*SchemaReviewRule `json:"ruleList"`
}
+// Validate validates the SchemaReviewPolicy. It also validates the each review rule.
+func (policy *SchemaReviewPolicy) Validate() error {
+ if policy.Name == "" || len(policy.RuleList) == 0 {
+ return fmt.Errorf("invalid payload, name or rule list cannot be empty")
+ }
+ for _, rule := range policy.RuleList {
+ if err := rule.Validate(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
// SchemaReviewRule is the rule for schema review policy.
type SchemaReviewRule struct {
Type SchemaReviewRuleType `json:"type"`
@@ -61,6 +80,18 @@ type SchemaReviewRule struct {
Payload string `json:"payload"`
}
+// Validate validates the schema review rule.
+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 {
+ return err
+ }
+ }
+ return nil
+}
+
// NamingRulePayload is the payload for naming rule.
type NamingRulePayload struct {
Format string `json:"format"`
@@ -70,3 +101,16 @@ type NamingRulePayload struct {
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) {
+ 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)
+ }
+ format, err := regexp.Compile(nr.Format)
+ if err != nil {
+ return nil, fmt.Errorf("failed to compile regular expression: %v, err: %v", nr.Format, err)
+ }
+ return format, nil
+}
diff --git a/common/error.go b/common/error.go
index 005f1df974..73fe95a98b 100644
--- a/common/error.go
+++ b/common/error.go
@@ -50,6 +50,9 @@ const (
CompatibilityAlterColumn Code = 10011
StatementNoWhere Code = 10101
+
+ // 10201 naming advisor error code
+ TableNamingConventionMismatch Code = 10201
)
// Error represents an application-specific error. Application errors can be
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index d25ec99f1a..73eac3c9eb 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -59,6 +59,8 @@ const (
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"
+ // MySQLTableNamingConvention is an advisor type for MySQL table naming convention.
+ MySQLTableNamingConvention Type = "bb.plugin.advisor.mysql.naming.table"
)
// Advice is the result of an advisor.
diff --git a/plugin/advisor/mysql/mysql_migration_compatibility_advisor.go b/plugin/advisor/mysql/mysql_migration_compatibility_advisor.go
index 2d45b132ee..bba8bdd241 100644
--- a/plugin/advisor/mysql/mysql_migration_compatibility_advisor.go
+++ b/plugin/advisor/mysql/mysql_migration_compatibility_advisor.go
@@ -25,17 +25,9 @@ type CompatibilityAdvisor struct {
// Check checks schema backward compatibility.
func (adv *CompatibilityAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
- p := newParser()
-
- root, _, err := p.Parse(statement, ctx.Charset, ctx.Collation)
- if err != nil {
- return []advisor.Advice{
- {
- Status: advisor.Error,
- Title: "Syntax error",
- Content: err.Error(),
- },
- }, nil
+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
}
c := &compatibilityChecker{}
diff --git a/plugin/advisor/mysql/mysql_parser.go b/plugin/advisor/mysql/mysql_parser.go
index c1d3e2bbb4..101eac22ac 100644
--- a/plugin/advisor/mysql/mysql_parser.go
+++ b/plugin/advisor/mysql/mysql_parser.go
@@ -1,6 +1,10 @@
package mysql
-import "github.com/pingcap/tidb/parser"
+import (
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/pingcap/tidb/parser"
+ "github.com/pingcap/tidb/parser/ast"
+)
// Wrapper for parser.New().
func newParser() *parser.Parser {
@@ -12,3 +16,19 @@ func newParser() *parser.Parser {
return p
}
+
+func parseStatement(statement string, charset string, collation string) ([]ast.StmtNode, []advisor.Advice) {
+ p := newParser()
+
+ root, _, err := p.Parse(statement, charset, collation)
+ if err != nil {
+ return nil, []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Title: "Syntax error",
+ Content: err.Error(),
+ },
+ }
+ }
+ return root, nil
+}
diff --git a/plugin/advisor/mysql/mysql_table_naming_convention.go b/plugin/advisor/mysql/mysql_table_naming_convention.go
new file mode 100644
index 0000000000..c5a97e25be
--- /dev/null
+++ b/plugin/advisor/mysql/mysql_table_naming_convention.go
@@ -0,0 +1,111 @@
+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 = (*TableNamingConventionAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLTableNamingConvention, &TableNamingConventionAdvisor{})
+ advisor.Register(db.TiDB, advisor.MySQLTableNamingConvention, &TableNamingConventionAdvisor{})
+}
+
+// TableNamingConventionAdvisor is the advisor checking for table naming convention.
+type TableNamingConventionAdvisor struct {
+}
+
+// Check checks for table naming convention.
+func (adv *TableNamingConventionAdvisor) 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 := &tableNamingConventionChecker{
+ level: level,
+ format: format,
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.advisorList) == 0 {
+ checker.advisorList = append(checker.advisorList, advisor.Advice{
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.advisorList, nil
+}
+
+type tableNamingConventionChecker struct {
+ advisorList []advisor.Advice
+ level advisor.Status
+ format *regexp.Regexp
+}
+
+func (v *tableNamingConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ tableNames := make([]string, 0)
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ // Original string
+ tableNames = append(tableNames, node.Table.Name.O)
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ // RENAME TABLE
+ if spec.Tp == ast.AlterTableRenameTable {
+ tableNames = append(tableNames, spec.NewTable.Name.O)
+ }
+ }
+ // RENAME TABLE
+ case *ast.RenameTableStmt:
+ for _, table2Table := range node.TableToTables {
+ tableNames = append(tableNames, table2Table.NewTable.Name.O)
+ }
+ }
+
+ code := common.Ok
+
+ for _, tableName := range tableNames {
+ if !v.format.MatchString(tableName) {
+ code = common.TableNamingConventionMismatch
+ break
+ }
+ }
+
+ if code != common.Ok {
+ v.advisorList = append(v.advisorList, advisor.Advice{
+ Status: v.level,
+ Code: code,
+ Title: "Mismatch table naming convention",
+ Content: fmt.Sprintf("%q mismatches table naming convention", in.Text()),
+ })
+ }
+ return in, false
+}
+
+func (v *tableNamingConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/plugin/advisor/mysql/mysql_table_naming_convention_test.go b/plugin/advisor/mysql/mysql_table_naming_convention_test.go
new file mode 100644
index 0000000000..80b0afc5be
--- /dev/null
+++ b/plugin/advisor/mysql/mysql_table_naming_convention_test.go
@@ -0,0 +1,91 @@
+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 TestTableNamingRequirement(t *testing.T) {
+ tests := []test{
+ {
+ statement: "CREATE TABLE techBook(id int, name varchar(255))",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNamingConventionMismatch,
+ Title: "Mismatch table naming convention",
+ Content: "\"CREATE TABLE techBook(id int, name varchar(255))\" mismatches table naming convention",
+ },
+ },
+ },
+ {
+ statement: "CREATE TABLE tech_book(id int, name varchar(255))",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: "ALTER TABLE techBook RENAME TO TechBook",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNamingConventionMismatch,
+ Title: "Mismatch table naming convention",
+ Content: "\"ALTER TABLE techBook RENAME TO TechBook\" mismatches table naming convention",
+ },
+ },
+ },
+ {
+ statement: "ALTER TABLE techBook RENAME TO tech_book",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: "RENAME TABLE techBook TO tech_book, literaryBook TO LiteraryBook",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNamingConventionMismatch,
+ Title: "Mismatch table naming convention",
+ Content: "\"RENAME TABLE techBook TO tech_book, literaryBook TO LiteraryBook\" mismatches table naming convention",
+ },
+ },
+ },
+ {
+ statement: "RENAME TABLE techBook TO tech_book, literaryBook TO literary_book",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ }
+ payload, err := json.Marshal(api.NamingRulePayload{
+ Format: "^[a-z]+(_[a-z]+)?$",
+ })
+ require.NoError(t, err)
+ runSchemaReviewRuleTests(t, tests, &TableNamingConventionAdvisor{}, &api.SchemaReviewRule{
+ Type: api.SchemaRuleTableNaming,
+ Level: api.SchemaRuleLevelError,
+ Payload: string(payload),
+ })
+}
diff --git a/plugin/advisor/mysql/mysql_where_requirement_advisor.go b/plugin/advisor/mysql/mysql_where_requirement_advisor.go
index 7490201bb1..7521af1caa 100644
--- a/plugin/advisor/mysql/mysql_where_requirement_advisor.go
+++ b/plugin/advisor/mysql/mysql_where_requirement_advisor.go
@@ -25,18 +25,11 @@ type WhereRequirementAdvisor struct {
// Check checks for the WHERE clause requirement for UPDATE/DELETE.
func (adv *WhereRequirementAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
- p := newParser()
-
- root, _, err := p.Parse(statement, ctx.Charset, ctx.Collation)
- if err != nil {
- return []advisor.Advice{
- {
- Status: advisor.Error,
- Title: "Syntax error",
- Content: err.Error(),
- },
- }, nil
+ 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 []advisor.Advice{}, err
diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.go
index f9a10ff6b4..65c02673a3 100644
--- a/server/task_check_executor_statement_advisor_composite.go
+++ b/server/task_check_executor_statement_advisor_composite.go
@@ -118,7 +118,11 @@ func getAdvisorTypeByRule(ruleType api.SchemaReviewRuleType, engine db.Type) (ad
case db.MySQL, db.TiDB:
return advisor.MySQLWhereRequirement, nil
}
- return advisor.Fake, fmt.Errorf("unknown schema review rule type %v for %v", ruleType, engine)
+ case api.SchemaRuleTableNaming:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return advisor.MySQLTableNamingConvention, nil
+ }
}
return advisor.Fake, fmt.Errorf("unknown schema review rule type %v for %v", ruleType, engine)
}