Skip to content

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

feat(sql-review): implement MySQL max-char-length rule (#2914)

rebelicef8aaf390cc75
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 9a6b8d2a50..e601a72497 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -109,6 +109,9 @@ const (
// MySQLDisallowSetColumnCharset is an advisor type for MySQL disallow set column charset.
MySQLDisallowSetColumnCharset Type = "bb.plugin.advisor.mysql.column.disallow-set-charset"
+ // MySQLColumnMaximumCharacterLength is an advisor type for MySQL maximum character length.
+ MySQLColumnMaximumCharacterLength Type = "bb.plugin.advisor.mysql.column.maximum-character-length"
+
// MySQLNoSelectAll is an advisor type for MySQL no select all.
MySQLNoSelectAll Type = "bb.plugin.advisor.mysql.select.no-select-all"
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index b7e19f899b..5941bee75c 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -60,6 +60,7 @@ const (
ColumnExists Code = 412
DropAllColumns Code = 413
SetColumnCharset Code = 414
+ CharLengthExceedsLimit Code = 415
// 501 engine error code.
NotInnoDBEngine Code = 501
diff --git a/plugin/advisor/mysql/advisor_column_maximum_character_length.go b/plugin/advisor/mysql/advisor_column_maximum_character_length.go
new file mode 100644
index 0000000000..de5746c923
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_column_maximum_character_length.go
@@ -0,0 +1,140 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnMaximumCharacterLengthAdvisor)(nil)
+ _ ast.Visitor = (*columnMaximumCharacterLengthChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})
+ advisor.Register(db.TiDB, advisor.MySQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})
+}
+
+// ColumnMaximumCharacterLengthAdvisor is the advisor checking for max character length.
+type ColumnMaximumCharacterLengthAdvisor struct {
+}
+
+// Check checks for maximum character length.
+func (*ColumnMaximumCharacterLengthAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmtList, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalNumberLimitRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnMaximumCharacterLengthChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ maximum: payload.Number,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnMaximumCharacterLengthChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ maximum int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnMaximumCharacterLengthChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var tableName, columnName string
+ var line int
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ charLength := getCharLength(column)
+ if checker.maximum > 0 && charLength > checker.maximum {
+ tableName = node.Table.Name.O
+ columnName = column.Name.Name.O
+ line = column.OriginTextPosition()
+ break
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ charLength := getCharLength(column)
+ if checker.maximum > 0 && charLength > checker.maximum {
+ tableName = node.Table.Name.O
+ columnName = column.Name.Name.O
+ line = node.OriginTextPosition()
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ charLength := getCharLength(spec.NewColumns[0])
+ if checker.maximum > 0 && charLength > checker.maximum {
+ tableName = node.Table.Name.O
+ columnName = spec.NewColumns[0].Name.Name.O
+ line = node.OriginTextPosition()
+ }
+ }
+ if tableName != "" {
+ break
+ }
+ }
+ }
+
+ if tableName != "" {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.CharLengthExceedsLimit,
+ Title: checker.title,
+ Content: fmt.Sprintf("The length of the CHAR column `%s` is bigger than %d, please use VARCHAR instead", columnName, checker.maximum),
+ Line: line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnMaximumCharacterLengthChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func getCharLength(column *ast.ColumnDef) int {
+ if column.Tp.GetType() == mysql.TypeString {
+ return column.Tp.GetFlen()
+ }
+ return 0
+}
diff --git a/plugin/advisor/mysql/advisor_column_maximum_character_length_test.go b/plugin/advisor/mysql/advisor_column_maximum_character_length_test.go
new file mode 100644
index 0000000000..056d964138
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_column_maximum_character_length_test.go
@@ -0,0 +1,97 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestColumnMaximumCharacterLength(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: `CREATE TABLE t(name char(20));`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(name varchar(225));`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(name char(225));`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.CharLengthExceedsLimit,
+ Title: "column.maximum-character-length",
+ Content: "The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE tech_book ADD COLUMN name_2 char(225)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.CharLengthExceedsLimit,
+ Title: "column.maximum-character-length",
+ Content: "The length of the CHAR column `name_2` is bigger than 20, please use VARCHAR instead",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE tech_book CHANGE COLUMN name name char(225)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.CharLengthExceedsLimit,
+ Title: "column.maximum-character-length",
+ Content: "The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE tech_book MODIFY COLUMN name char(225)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.CharLengthExceedsLimit,
+ Title: "column.maximum-character-length",
+ Content: "The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead",
+ Line: 1,
+ },
+ },
+ },
+ }
+
+ payload, err := json.Marshal(advisor.NumberLimitRulePayload{
+ Number: 20,
+ })
+ require.NoError(t, err)
+ advisor.RunSQLReviewRuleTests(t, tests, &ColumnMaximumCharacterLengthAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleColumnMaximumCharacterLength,
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: string(payload),
+ }, advisor.MockMySQLDatabase)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index aabe451075..9803e0101e 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -93,6 +93,8 @@ const (
SchemaRuleColumnTypeRestriction SQLReviewRuleType = "column.type-restriction"
// SchemaRuleColumnDisallowSetCharset disallow set column charset.
SchemaRuleColumnDisallowSetCharset SQLReviewRuleType = "column.disallow-set-charset"
+ // SchemaRuleColumnMaximumCharacterLength enforce the maximum character length.
+ SchemaRuleColumnMaximumCharacterLength SQLReviewRuleType = "column.maximum-character-length"
// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.
SchemaRuleSchemaBackwardCompatibility SQLReviewRuleType = "schema.backward-compatibility"
@@ -211,7 +213,7 @@ func (rule *SQLReviewRule) Validate() error {
if _, err := UnmarshalCommentConventionRulePayload(rule.Payload); err != nil {
return err
}
- case SchemaRuleIndexKeyNumberLimit, SchemaRuleInsertRowLimit, SchemaRuleIndexTotalNumberLimit:
+ case SchemaRuleIndexKeyNumberLimit, SchemaRuleInsertRowLimit, SchemaRuleIndexTotalNumberLimit, SchemaRuleColumnMaximumCharacterLength:
if _, err := UnmarshalNumberLimitRulePayload(rule.Payload); err != nil {
return err
}
@@ -707,6 +709,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
case db.MySQL, db.TiDB:
return MySQLDisallowSetColumnCharset, nil
}
+ case SchemaRuleColumnMaximumCharacterLength:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return MySQLColumnMaximumCharacterLength, nil
+ }
case SchemaRuleTableRequirePK:
switch engine {
case db.MySQL, db.TiDB: