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 current-time-count-limit rule (#3079)
rebeliceeb1753504ebe
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex cdc4a684e3..568ed643be 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -121,8 +121,8 @@ 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"+ // MySQLCurrentTimeColumnCountLimit is an advisor type for MySQL current time column count limit.+ MySQLCurrentTimeColumnCountLimit Type = "bb.plugin.advisor.mysql.column.current-time-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/code.go b/plugin/advisor/code.goindex 15dd68a53c..a4a11531c8 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -49,24 +49,25 @@ const (NamingAutoIncrementColumnConventionMismatch Code = 307// 401 ~ 499 column error code.- NoRequiredColumn Code = 401- ColumnCannotNull Code = 402- ChangeColumnType Code = 403- NotNullColumnWithNullDefault Code = 404- ColumnNotExists Code = 405- UseChangeColumnStatement Code = 406- ChangeColumnOrder Code = 407- NoColumnComment Code = 408- ColumnCommentTooLong Code = 409- AutoIncrementColumnNotInteger Code = 410- DisabledColumnType Code = 411- ColumnExists Code = 412- DropAllColumns Code = 413- SetColumnCharset Code = 414- CharLengthExceedsLimit Code = 415- AutoIncrementColumnInitialValueNotMatch Code = 416- AutoIncrementColumnSigned Code = 417- DatetimeCountExceedsLimit Code = 418+ NoRequiredColumn Code = 401+ ColumnCannotNull Code = 402+ ChangeColumnType Code = 403+ NotNullColumnWithNullDefault Code = 404+ ColumnNotExists Code = 405+ UseChangeColumnStatement Code = 406+ ChangeColumnOrder Code = 407+ NoColumnComment Code = 408+ ColumnCommentTooLong Code = 409+ AutoIncrementColumnNotInteger Code = 410+ DisabledColumnType Code = 411+ ColumnExists Code = 412+ DropAllColumns Code = 413+ SetColumnCharset Code = 414+ CharLengthExceedsLimit Code = 415+ AutoIncrementColumnInitialValueNotMatch Code = 416+ AutoIncrementColumnSigned Code = 417+ DefaultCurrentTimeColumnCountExceedsLimit Code = 418+ OnUpdateCurrentTimeColumnCountExceedsLimit Code = 419// 501 engine error code.NotInnoDBEngine Code = 501diff --git a/plugin/advisor/mysql/advisor_column_current_time_count_limit.go b/plugin/advisor/mysql/advisor_column_current_time_count_limit.gonew file mode 100644index 0000000000..3fe0dae35d--- /dev/null+++ b/plugin/advisor/mysql/advisor_column_current_time_count_limit.go@@ -0,0 +1,206 @@+package mysql++// Framework code is generated by the generator.++import (+ "fmt"+ "sort"+ "strings"++ "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"+)++const (+ maxDefaultCurrentTimeColumCount = 2+ maxOnUpdateCurrentTimeColumnCount = 1+)++var (+ _ advisor.Advisor = (*ColumnCurrentTimeCountLimitAdvisor)(nil)+ _ ast.Visitor = (*columnCurrentTimeCountLimitChecker)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLCurrentTimeColumnCountLimit, &ColumnCurrentTimeCountLimitAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLCurrentTimeColumnCountLimit, &ColumnCurrentTimeCountLimitAdvisor{})+}++// ColumnCurrentTimeCountLimitAdvisor is the advisor checking for current time column count limit.+type ColumnCurrentTimeCountLimitAdvisor struct {+}++// Check checks for current time column count limit.+func (*ColumnCurrentTimeCountLimitAdvisor) 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+ }+ checker := &columnCurrentTimeCountLimitChecker{+ level: level,+ title: string(ctx.Rule.Type),+ tableSet: make(map[string]tableData),+ }++ for _, stmt := range stmtList {+ checker.text = stmt.Text()+ checker.line = stmt.OriginTextPosition()+ (stmt).Accept(checker)+ }++ return checker.generateAdvice(), nil+}++type columnCurrentTimeCountLimitChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ line int+ tableSet map[string]tableData+}++type tableData struct {+ tableName string+ defaultCurrentTimeCount int+ onUpdateCurrentTimeCount int+ line int+}++func (checker *columnCurrentTimeCountLimitChecker) 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 {+ if table.defaultCurrentTimeCount > maxDefaultCurrentTimeColumCount {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.DefaultCurrentTimeColumnCountExceedsLimit,+ Title: checker.title,+ Content: fmt.Sprintf("Table `%s` has %d DEFAULT CURRENT_TIMESTAMP() columns. The count greater than %d.", table.tableName, table.defaultCurrentTimeCount, maxDefaultCurrentTimeColumCount),+ Line: table.line,+ })+ }+ if table.onUpdateCurrentTimeCount > maxOnUpdateCurrentTimeColumnCount {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.OnUpdateCurrentTimeColumnCountExceedsLimit,+ Title: checker.title,+ Content: fmt.Sprintf("Table `%s` has %d ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than %d.", table.tableName, table.onUpdateCurrentTimeCount, maxOnUpdateCurrentTimeColumnCount),+ 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+}++func (checker *columnCurrentTimeCountLimitChecker) count(tableName string, column *ast.ColumnDef, line int) {+ switch column.Tp.GetType() {+ case mysql.TypeDatetime, mysql.TypeTimestamp:+ if isDefaultCurrentTime(column) {+ table, exists := checker.tableSet[tableName]+ if !exists {+ table = tableData{+ tableName: tableName,+ }+ }+ table.defaultCurrentTimeCount+++ table.line = line+ checker.tableSet[tableName] = table+ }+ if isOnUpdateCurrentTime(column) {+ table, exists := checker.tableSet[tableName]+ if !exists {+ table = tableData{+ tableName: tableName,+ }+ }+ table.onUpdateCurrentTimeCount+++ table.line = line+ checker.tableSet[tableName] = table+ }+ }+}++// Enter implements the ast.Visitor interface.+func (checker *columnCurrentTimeCountLimitChecker) Enter(in ast.Node) (ast.Node, bool) {+ switch node := in.(type) {+ case *ast.CreateTableStmt:+ tableName := node.Table.Name.O+ for _, column := range node.Cols {+ checker.count(tableName, column, node.OriginTextPosition())+ }+ case *ast.AlterTableStmt:+ tableName := node.Table.Name.O+ for _, spec := range node.Specs {+ switch spec.Tp {+ case ast.AlterTableAddColumns:+ for _, column := range spec.NewColumns {+ checker.count(tableName, column, node.OriginTextPosition())+ }+ case ast.AlterTableModifyColumn, ast.AlterTableChangeColumn:+ checker.count(tableName, spec.NewColumns[0], node.OriginTextPosition())+ }+ }+ }++ return in, false+}++// Leave implements the ast.Visitor interface.+func (*columnCurrentTimeCountLimitChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++func isOnUpdateCurrentTime(column *ast.ColumnDef) bool {+ for _, option := range column.Options {+ if option.Tp == ast.ColumnOptionOnUpdate {+ if function, ok := option.Expr.(*ast.FuncCallExpr); ok && isCurrentTime(function.FnName.L) {+ return true+ }+ }+ }+ return false+}++func isDefaultCurrentTime(column *ast.ColumnDef) bool {+ for _, option := range column.Options {+ if option.Tp == ast.ColumnOptionDefaultValue {+ if function, ok := option.Expr.(*ast.FuncCallExpr); ok && isCurrentTime(function.FnName.L) {+ return true+ }+ }+ }+ return false+}++func isCurrentTime(name string) bool {+ switch strings.ToLower(name) {+ // Any of the synonyms for CURRENT_TIMESTAMP have the same meaning as CURRENT_TIMESTAMP.+ // These are CURRENT_TIMESTAMP(), NOW(), LOCALTIME, LOCALTIME(), LOCALTIMESTAMP, and LOCALTIMESTAMP().+ // See https://dev.mysql.com/doc/refman/8.0/en/timestamp-initialization.html.+ case "current_timestamp", "now", "localtime", "localtimestamp":+ return true+ }+ return false+}diff --git a/plugin/advisor/mysql/advisor_column_current_time_count_limit_test.go b/plugin/advisor/mysql/advisor_column_current_time_count_limit_test.gonew file mode 100644index 0000000000..19fd0710c1--- /dev/null+++ b/plugin/advisor/mysql/advisor_column_current_time_count_limit_test.go@@ -0,0 +1,79 @@+package mysql++// Framework code is generated by the generator.++import (+ "testing"++ "github.com/bytebase/bytebase/plugin/advisor"+)++func TestColumnCurrentTimeCountLimit(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `CREATE TABLE t(a timestamp, b timestamp)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(+ a timestamp default now(),+ b timestamp default current_timestamp(),+ c timestamp default localtime+ )`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DefaultCurrentTimeColumnCountExceedsLimit,+ Title: "column.current-time-count-limit",+ Content: "Table `t` has 3 DEFAULT CURRENT_TIMESTAMP() columns. The count greater than 2.",+ Line: 6,+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(+ a timestamp default now() on update localtime,+ b timestamp default current_timestamp() on update localtimestamp()+ )`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.OnUpdateCurrentTimeColumnCountExceedsLimit,+ Title: "column.current-time-count-limit",+ Content: "Table `t` has 2 ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than 1.",+ Line: 5,+ },+ },+ },+ {+ Statement: `+ ALTER TABLE tech_book ADD COLUMN a timestamp default now() on update localtime;+ ALTER TABLE tech_book ADD COLUMN b timestamp default current_timestamp() on update localtimestamp();+ `,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.OnUpdateCurrentTimeColumnCountExceedsLimit,+ Title: "column.current-time-count-limit",+ Content: "Table `tech_book` has 2 ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than 1.",+ Line: 3,+ },+ },+ },+ }++ advisor.RunSQLReviewRuleTests(t, tests, &ColumnCurrentTimeCountLimitAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleCurrentTimeColumnCountLimit,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: "",+ }, advisor.MockMySQLDatabase)+}diff --git a/plugin/advisor/mysql/advisor_column_datetime_count_limit.go b/plugin/advisor/mysql/advisor_column_datetime_count_limit.godeleted file mode 100644index bc0be48d40..0000000000--- a/plugin/advisor/mysql/advisor_column_datetime_count_limit.go+++ /dev/null@@ -1,159 +0,0 @@-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.godeleted file mode 100644index 5a95c3fd8a..0000000000--- a/plugin/advisor/mysql/advisor_column_datetime_count_limit_test.go+++ /dev/null@@ -1,80 +0,0 @@-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 4620bf67e9..6719a6f0e2 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -111,8 +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"+ // SchemaRuleCurrentTimeColumnCountLimit enforce the current column count limit.+ SchemaRuleCurrentTimeColumnCountLimit SQLReviewRuleType = "column.current-time-count-limit"// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.SchemaRuleSchemaBackwardCompatibility SQLReviewRuleType = "schema.backward-compatibility"@@ -233,7 +233,7 @@ func (rule *SQLReviewRule) Validate() error {return err}case SchemaRuleIndexKeyNumberLimit, SchemaRuleStatementInsertRowLimit, SchemaRuleIndexTotalNumberLimit,- SchemaRuleColumnMaximumCharacterLength, SchemaRuleColumnAutoIncrementInitialValue, SchemaRuleDatetimeColumnCountLimit:+ SchemaRuleColumnMaximumCharacterLength, SchemaRuleColumnAutoIncrementInitialValue:if _, err := UnmarshalNumberTypeRulePayload(rule.Payload); err != nil {return err}@@ -755,10 +755,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLAutoIncrementColumnMustUnsigned, nil}- case SchemaRuleDatetimeColumnCountLimit:+ case SchemaRuleCurrentTimeColumnCountLimit:switch engine {case db.MySQL, db.TiDB:- return MySQLDatetimeColumnCountLimit, nil+ return MySQLCurrentTimeColumnCountLimit, nil}case SchemaRuleTableRequirePK:switch engine {