Skip to content

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

feat(sql-review): implement MySQL column type restriction rule (#2496)

rebelicef61c3e224343
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index b442589ba1..5d0a256089 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -106,6 +106,9 @@ const (
// MySQLAutoIncrementColumnMustInteger is an advisor type for auto-increment column.
MySQLAutoIncrementColumnMustInteger Type = "bb.plugin.advisor.mysql.column.auto-increment-must-integer"
+ // MySQLColumnTypeRestriction is an advisor type for MySQL column type restriction.
+ MySQLColumnTypeRestriction Type = "bb.plugin.advisor.mysql.column.type-restriction"
+
// 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 d3f92c3465..ae711ac6a0 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -54,6 +54,7 @@ const (
NoColumnComment Code = 408
ColumnCommentTooLong Code = 409
AutoIncrementColumnNotInteger Code = 410
+ DisabledColumnType Code = 411
// 501 engine error code.
NotInnoDBEngine Code = 501
diff --git a/plugin/advisor/mysql/advisor_column_type_restriction.go b/plugin/advisor/mysql/advisor_column_type_restriction.go
new file mode 100644
index 0000000000..9957984403
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_column_type_restriction.go
@@ -0,0 +1,145 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnTypeRestrictionAdvisor)(nil)
+ _ ast.Visitor = (*columnTypeRestrictionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLColumnTypeRestriction, &ColumnTypeRestrictionAdvisor{})
+ advisor.Register(db.TiDB, advisor.MySQLColumnTypeRestriction, &ColumnTypeRestrictionAdvisor{})
+}
+
+// ColumnTypeRestrictionAdvisor is the advisor checking for column type restriction.
+type ColumnTypeRestrictionAdvisor struct {
+}
+
+// Check checks for column type restriction.
+func (*ColumnTypeRestrictionAdvisor) 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
+ }
+ paylaod, err := advisor.UnmarshalTypeRestrictionRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnTypeRestrictionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ typeRestriction: make(map[string]bool),
+ }
+ for _, tp := range paylaod.TypeList {
+ checker.typeRestriction[strings.ToUpper(tp)] = true
+ }
+
+ 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 columnTypeRestrictionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ typeRestriction map[string]bool
+}
+
+type columnTypeData struct {
+ table string
+ column string
+ tp string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnTypeRestrictionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var columnList []columnTypeData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ if _, exist := checker.typeRestriction[strings.ToUpper(column.Tp.CompactStr())]; exist {
+ columnList = append(columnList, columnTypeData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ tp: strings.ToUpper(column.Tp.CompactStr()),
+ line: column.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if _, exist := checker.typeRestriction[strings.ToUpper(column.Tp.CompactStr())]; exist {
+ columnList = append(columnList, columnTypeData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ tp: strings.ToUpper(column.Tp.CompactStr()),
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ column := spec.NewColumns[0]
+ if _, exist := checker.typeRestriction[strings.ToUpper(column.Tp.CompactStr())]; exist {
+ columnList = append(columnList, columnTypeData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ tp: strings.ToUpper(column.Tp.CompactStr()),
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.DisabledColumnType,
+ Title: checker.title,
+ Content: fmt.Sprintf("Disallow column type %s but column `%s`.`%s` is", column.tp, column.table, column.column),
+ Line: column.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnTypeRestrictionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/plugin/advisor/mysql/advisor_column_type_restriction_test.go b/plugin/advisor/mysql/advisor_column_type_restriction_test.go
new file mode 100644
index 0000000000..8d3689beb6
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_column_type_restriction_test.go
@@ -0,0 +1,109 @@
+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 TestColumnTypeRestriction(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: `CREATE TABLE t(a int)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(a JSON, b BLOB, c TEXT)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type JSON but column `t`.`a` is",
+ Line: 1,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type BLOB but column `t`.`b` is",
+ Line: 1,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type TEXT but column `t`.`c` is",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t add COLUMN (a JSON, b BLOB, c TEXT)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type JSON but column `t`.`a` is",
+ Line: 1,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type BLOB but column `t`.`b` is",
+ Line: 1,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type TEXT but column `t`.`c` is",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t CHANGE COLUMN c a JSON, MODIFY b BLOB`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type JSON but column `t`.`a` is",
+ Line: 1,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.DisabledColumnType,
+ Title: "column.type-restriction",
+ Content: "Disallow column type BLOB but column `t`.`b` is",
+ Line: 1,
+ },
+ },
+ },
+ }
+
+ payload, err := json.Marshal(advisor.TypeRestrictionRulePayload{
+ TypeList: []string{"JSON", "BLOB", "TEXT"},
+ })
+ require.NoError(t, err)
+ advisor.RunSQLReviewRuleTests(t, tests, &ColumnTypeRestrictionAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleColumnTypeRestriction,
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: string(payload),
+ }, advisor.MockMySQLDatabase)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index cfcd4c09b4..912d4a7671 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -86,6 +86,8 @@ const (
SchemaRuleColumnCommentConvention SQLReviewRuleType = "column.comment"
// SchemaRuleColumnAutoIncrementMustInteger require the auto-increment column to be integer.
SchemaRuleColumnAutoIncrementMustInteger SQLReviewRuleType = "column.auto-increment-must-integer"
+ // SchemaRuleColumnTypeRestriction enforce the column type restriction.
+ SchemaRuleColumnTypeRestriction SQLReviewRuleType = "column.type-restriction"
// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.
SchemaRuleSchemaBackwardCompatibility SQLReviewRuleType = "schema.backward-compatibility"
@@ -194,6 +196,10 @@ func (rule *SQLReviewRule) Validate() error {
if _, err := UnmarshalNumberLimitRulePayload(rule.Payload); err != nil {
return err
}
+ case SchemaRuleColumnTypeRestriction:
+ if _, err := UnmarshalTypeRestrictionRulePayload(rule.Payload); err != nil {
+ return err
+ }
}
return nil
}
@@ -220,6 +226,11 @@ type NumberLimitRulePayload struct {
Number int `json:"number"`
}
+// TypeRestrictionRulePayload is the payload for type restriction rule.
+type TypeRestrictionRulePayload struct {
+ TypeList []string `json:"typeList"`
+}
+
// UnamrshalNamingRulePayloadAsRegexp will unmarshal payload to NamingRulePayload and compile it as regular expression.
func UnamrshalNamingRulePayloadAsRegexp(payload string) (*regexp.Regexp, int, error) {
var nr NamingRulePayload
@@ -319,6 +330,15 @@ func UnmarshalNumberLimitRulePayload(payload string) (*NumberLimitRulePayload, e
return &nlr, nil
}
+// UnmarshalTypeRestrictionRulePayload will unmarshal payload to TypeRestrictionRulePayload.
+func UnmarshalTypeRestrictionRulePayload(payload string) (*TypeRestrictionRulePayload, error) {
+ var trr TypeRestrictionRulePayload
+ if err := json.Unmarshal([]byte(payload), &trr); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal type restriction rule payload %q", payload)
+ }
+ return &trr, nil
+}
+
// SQLReviewCheckContext is the context for SQL review check.
type SQLReviewCheckContext struct {
Charset string
@@ -491,6 +511,16 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
case db.MySQL, db.TiDB:
return MySQLColumnCommentConvention, nil
}
+ case SchemaRuleColumnAutoIncrementMustInteger:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return MySQLAutoIncrementColumnMustInteger, nil
+ }
+ case SchemaRuleColumnTypeRestriction:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return MySQLColumnTypeRestriction, nil
+ }
case SchemaRuleTableRequirePK:
switch engine {
case db.MySQL, db.TiDB: