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(sql-reivew): implement MySQL datetime-column-count-limit rule (#3073)
rebelice831db3552a4e
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 36bed5d599..cdc4a684e3 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -121,6 +121,9 @@ const (// MySQLAutoIncrementColumnMustUnsigned is an advisor type for MySQL unsigned auto-increment column.MySQLAutoIncrementColumnMustUnsigned Type = "bb.plugin.advisor.mysql.column.auto-increment-must-unsigned"+ // MySQLDatetimeColumnCountLimit is an advisor type for MySQL datetime column count limit.+ MySQLDatetimeColumnCountLimit Type = "bb.plugin.advisor.mysql.column.datetime-count-limit"+// 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/catalog/state.go b/plugin/advisor/catalog/state.goindex a95c1b85ed..669df42493 100644--- a/plugin/advisor/catalog/state.go+++ b/plugin/advisor/catalog/state.go@@ -5,6 +5,8 @@ package catalog// 2. the underlying implementation of Finderimport (+ "strings"+"github.com/bytebase/bytebase/plugin/advisor/db")@@ -213,6 +215,32 @@ func (d *DatabaseState) FindPrimaryKey(find *PrimaryKeyFind) *IndexState {return nil}+// ColumnCount is for counting columns.+type ColumnCount struct {+ SchemaName string+ TableName string+ ColumnType string+}++// CountColumn counts columns.+func (d *DatabaseState) CountColumn(count *ColumnCount) int {+ schema, exists := d.schemaSet[count.SchemaName]+ if !exists {+ return 0+ }+ table, exists := schema.tableSet[count.TableName]+ if !exists {+ return 0+ }+ res := 0+ for _, column := range table.columnSet {+ if column.columnType != nil && strings.EqualFold(*column.columnType, count.ColumnType) {+ res+++ }+ }+ return res+}+// ColumnFind is for finding column.type ColumnFind struct {SchemaName stringdiff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex fd0f9347cb..15dd68a53c 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -66,6 +66,7 @@ const (CharLengthExceedsLimit Code = 415AutoIncrementColumnInitialValueNotMatch Code = 416AutoIncrementColumnSigned Code = 417+ DatetimeCountExceedsLimit Code = 418// 501 engine error code.NotInnoDBEngine Code = 501diff --git a/plugin/advisor/mysql/advisor_column_datetime_count_limit.go b/plugin/advisor/mysql/advisor_column_datetime_count_limit.gonew file mode 100644index 0000000000..bc0be48d40--- /dev/null+++ b/plugin/advisor/mysql/advisor_column_datetime_count_limit.go@@ -0,0 +1,159 @@+package mysql++// Framework code is generated by the generator.++import (+ "fmt"+ "sort"++ "github.com/pingcap/tidb/parser/ast"+ "github.com/pingcap/tidb/parser/mysql"++ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/catalog"+ "github.com/bytebase/bytebase/plugin/advisor/db"+)++var (+ _ advisor.Advisor = (*ColumnDatetimeCountLimitAdvisor)(nil)+ _ ast.Visitor = (*columnDatetimeCountLimitChecker)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLDatetimeColumnCountLimit, &ColumnDatetimeCountLimitAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLDatetimeColumnCountLimit, &ColumnDatetimeCountLimitAdvisor{})+}++// ColumnDatetimeCountLimitAdvisor is the advisor checking for datetime column count limit.+type ColumnDatetimeCountLimitAdvisor struct {+}++// Check checks for datetime column count limit.+func (*ColumnDatetimeCountLimitAdvisor) 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.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &columnDatetimeCountLimitChecker{+ level: level,+ title: string(ctx.Rule.Type),+ tableSet: make(map[string]tableData),+ maximum: payload.Number,+ catalog: ctx.Catalog,+ }++ for _, stmt := range stmtList {+ checker.text = stmt.Text()+ checker.line = stmt.OriginTextPosition()+ (stmt).Accept(checker)+ }++ return checker.generateAdvice(), nil+}++type columnDatetimeCountLimitChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ line int+ tableSet map[string]tableData+ catalog *catalog.Finder+ maximum int+}++type tableData struct {+ tableName string+ line int+}++func (checker *columnDatetimeCountLimitChecker) generateAdvice() []advisor.Advice {+ var tableList []tableData+ for _, table := range checker.tableSet {+ tableList = append(tableList, table)+ }+ sort.Slice(tableList, func(i, j int) bool {+ return tableList[i].line < tableList[j].line+ })++ for _, table := range tableList {+ count := checker.catalog.Final.CountColumn(&catalog.ColumnCount{+ TableName: table.tableName,+ ColumnType: "datetime",+ })+ if count > checker.maximum {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.DatetimeCountExceedsLimit,+ Title: checker.title,+ Content: fmt.Sprintf("Table `%s` has %d datetime columns. The count greater than %d.", table.tableName, count, checker.maximum),+ Line: table.line,+ })+ }+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return checker.adviceList+}++// Enter implements the ast.Visitor interface.+func (checker *columnDatetimeCountLimitChecker) Enter(in ast.Node) (ast.Node, bool) {+ switch node := in.(type) {+ case *ast.CreateTableStmt:+ for _, column := range node.Cols {+ if column.Tp.GetType() == mysql.TypeDatetime {+ tableName := node.Table.Name.O+ checker.tableSet[tableName] = tableData{+ tableName: tableName,+ line: node.OriginTextPosition(),+ }+ break+ }+ }+ case *ast.AlterTableStmt:+ tableName := node.Table.Name.O+ for _, spec := range node.Specs {+ switch spec.Tp {+ case ast.AlterTableAddColumns:+ for _, column := range spec.NewColumns {+ if column.Tp.GetType() == mysql.TypeDatetime {+ checker.tableSet[tableName] = tableData{+ tableName: tableName,+ line: node.OriginTextPosition(),+ }+ }+ }+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:+ if spec.NewColumns[0].Tp.GetType() == mysql.TypeDatetime {+ checker.tableSet[tableName] = tableData{+ tableName: tableName,+ line: node.OriginTextPosition(),+ }+ }+ }+ }+ }++ return in, false+}++// Leave implements the ast.Visitor interface.+func (*columnDatetimeCountLimitChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}diff --git a/plugin/advisor/mysql/advisor_column_datetime_count_limit_test.go b/plugin/advisor/mysql/advisor_column_datetime_count_limit_test.gonew file mode 100644index 0000000000..5a95c3fd8a--- /dev/null+++ b/plugin/advisor/mysql/advisor_column_datetime_count_limit_test.go@@ -0,0 +1,80 @@+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 TestColumnDatetimeCountLimit(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `CREATE TABLE t(a datetime)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE t(a datetime, b datetime)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DatetimeCountExceedsLimit,+ Title: "column.datetime-count-limit",+ Content: "Table `t` has 2 datetime columns. The count greater than 1.",+ Line: 1,+ },+ },+ },+ {+ Statement: `+ ALTER TABLE tech_book ADD COLUMN a datetime;+ ALTER TABLE tech_book ADD COLUMN b datetime;+ `,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DatetimeCountExceedsLimit,+ Title: "column.datetime-count-limit",+ Content: "Table `tech_book` has 2 datetime columns. The count greater than 1.",+ Line: 3,+ },+ },+ },+ {+ Statement: `+ ALTER TABLE tech_book MODIFY COLUMN id datetime;+ ALTER TABLE tech_book MODIFY COLUMN name datetime;+ `,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DatetimeCountExceedsLimit,+ Title: "column.datetime-count-limit",+ Content: "Table `tech_book` has 2 datetime columns. The count greater than 1.",+ Line: 3,+ },+ },+ },+ }++ payload, err := json.Marshal(advisor.NumberTypeRulePayload{+ Number: 1,+ })+ require.NoError(t, err)+ advisor.RunSQLReviewRuleTests(t, tests, &ColumnDatetimeCountLimitAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleDatetimeColumnCountLimit,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: string(payload),+ }, advisor.MockMySQLDatabase)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex d7ec917ab0..4620bf67e9 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -111,6 +111,8 @@ const (SchemaRuleColumnAutoIncrementInitialValue SQLReviewRuleType = "column.auto-increment-initial-value"// SchemaRuleColumnAutoIncrementMustUnsigned enforce the auto-increment column to be unsigned.SchemaRuleColumnAutoIncrementMustUnsigned SQLReviewRuleType = "column.auto-increment-must-unsigned"+ // SchemaRuleDatetimeColumnCountLimit enforce the datetime column count limit.+ SchemaRuleDatetimeColumnCountLimit SQLReviewRuleType = "column.datetime-count-limit"// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.SchemaRuleSchemaBackwardCompatibility SQLReviewRuleType = "schema.backward-compatibility"@@ -230,7 +232,8 @@ func (rule *SQLReviewRule) Validate() error {if _, err := UnmarshalCommentConventionRulePayload(rule.Payload); err != nil {return err}- case SchemaRuleIndexKeyNumberLimit, SchemaRuleStatementInsertRowLimit, SchemaRuleIndexTotalNumberLimit, SchemaRuleColumnMaximumCharacterLength, SchemaRuleColumnAutoIncrementInitialValue:+ case SchemaRuleIndexKeyNumberLimit, SchemaRuleStatementInsertRowLimit, SchemaRuleIndexTotalNumberLimit,+ SchemaRuleColumnMaximumCharacterLength, SchemaRuleColumnAutoIncrementInitialValue, SchemaRuleDatetimeColumnCountLimit:if _, err := UnmarshalNumberTypeRulePayload(rule.Payload); err != nil {return err}@@ -752,6 +755,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLAutoIncrementColumnMustUnsigned, nil}+ case SchemaRuleDatetimeColumnCountLimit:+ switch engine {+ case db.MySQL, db.TiDB:+ return MySQLDatetimeColumnCountLimit, nil+ }case SchemaRuleTableRequirePK:switch engine {case db.MySQL, db.TiDB: