Skip to content

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

chore: migrate column_current_time_count_limit (#9266)

zll600b502f87cda84
diff --git a/backend/plugin/advisor/mysqlwip/advisor_column_current_time_count_limit.go b/backend/plugin/advisor/mysqlwip/advisor_column_current_time_count_limit.go
index b5acaa6a77..2a7b4e8e1d 100644
--- a/backend/plugin/advisor/mysqlwip/advisor_column_current_time_count_limit.go
+++ b/backend/plugin/advisor/mysqlwip/advisor_column_current_time_count_limit.go
@@ -5,13 +5,15 @@ package mysqlwip
import (
"fmt"
"sort"
- "strings"
- "github.com/pingcap/tidb/parser/ast"
- "github.com/pingcap/tidb/parser/mysql"
+ "github.com/antlr4-go/antlr/v4"
"github.com/pkg/errors"
+ mysql "github.com/bytebase/mysql-parser"
+
"github.com/bytebase/bytebase/backend/plugin/advisor"
+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
const (
@@ -21,18 +23,22 @@ const (
var (
_ advisor.Advisor = (*ColumnCurrentTimeCountLimitAdvisor)(nil)
- _ ast.Visitor = (*columnCurrentTimeCountLimitChecker)(nil)
)
+func init() {
+ // only for mysqlwip test.
+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, 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, _ string) ([]advisor.Advice, error) {
- stmtList, ok := ctx.AST.([]ast.StmtNode)
+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)
if !ok {
- return nil, errors.Errorf("failed to convert to StmtNode")
+ return nil, errors.Errorf("failed to convert to mysql parse result")
}
level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
@@ -46,73 +52,105 @@ func (*ColumnCurrentTimeCountLimitAdvisor) Check(ctx advisor.Context, _ string)
}
for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
+ checker.baseLine = stmt.BaseLine
+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)
}
return checker.generateAdvice(), nil
}
type columnCurrentTimeCountLimitChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ baseLine int
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) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if ctx.TableElementList() == nil || ctx.TableName() == nil {
+ return
+ }
+
+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
+ for _, tableElement := range ctx.TableElementList().AllTableElement() {
+ if tableElement.ColumnDefinition() == nil || tableElement.ColumnDefinition().FieldDefinition() == nil || tableElement.ColumnDefinition().FieldDefinition().DataType() == nil {
+ continue
+ }
+ _, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())
+ checker.checkTime(tableName, columnName, tableElement.ColumnDefinition().FieldDefinition())
+ }
}
-func (checker *columnCurrentTimeCountLimitChecker) generateAdvice() []advisor.Advice {
- var tableList []tableData
- for _, table := range checker.tableSet {
- tableList = append(tableList, table)
+func (checker *columnCurrentTimeCountLimitChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ if ctx.AlterTableActions() == nil {
+ return
}
- 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 ctx.AlterTableActions().AlterCommandList() == nil {
+ return
+ }
+ if ctx.AlterTableActions().AlterCommandList().AlterList() == nil {
+ return
+ }
+
+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
+ if tableName == "" {
+ return
+ }
+ // alter table add column, change column, modify column.
+ for _, item := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {
+ if item == nil {
+ continue
}
- 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,
- })
+
+ var columnName string
+ switch {
+ // add column
+ case item.ADD_SYMBOL() != nil:
+ switch {
+ case item.Identifier() != nil && item.FieldDefinition() != nil:
+ columnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())
+ checker.checkTime(tableName, columnName, item.FieldDefinition())
+ case item.OPEN_PAR_SYMBOL() != nil && item.TableElementList() != nil:
+ for _, tableElement := range item.TableElementList().AllTableElement() {
+ if tableElement.ColumnDefinition() == nil || tableElement.ColumnDefinition().ColumnName() == nil || tableElement.ColumnDefinition().FieldDefinition() == nil {
+ continue
+ }
+ _, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())
+ checker.checkTime(tableName, columnName, tableElement.ColumnDefinition().FieldDefinition())
+ }
+ }
+ // change column.
+ case item.CHANGE_SYMBOL() != nil && item.ColumnInternalRef() != nil && item.Identifier() != nil && item.FieldDefinition() != nil:
+ if item.FieldDefinition().DataType() == nil {
+ continue
+ }
+ // only focus on new column name.
+ columnName = mysqlparser.NormalizeMySQLIdentifier(item.Identifier())
+ checker.checkTime(tableName, columnName, item.FieldDefinition())
+ // modify column.
+ case item.MODIFY_SYMBOL() != nil && item.ColumnInternalRef() != nil && item.FieldDefinition() != nil:
+ if item.FieldDefinition().DataType() == nil {
+ continue
+ }
+ columnName = mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())
+ checker.checkTime(tableName, columnName, item.FieldDefinition())
+ default:
+ continue
}
}
- 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) {
+func (checker *columnCurrentTimeCountLimitChecker) checkTime(tableName string, _ string, ctx mysql.IFieldDefinitionContext) {
+ if ctx.DataType() == nil {
+ return
+ }
+
+ switch ctx.DataType().GetType_().GetTokenType() {
+ case mysql.MySQLParserDATETIME_SYMBOL, mysql.MySQLParserTIMESTAMP_SYMBOL:
+ if checker.isDefaultCurrentTime(ctx) {
table, exists := checker.tableSet[tableName]
if !exists {
table = tableData{
@@ -120,10 +158,10 @@ func (checker *columnCurrentTimeCountLimitChecker) count(tableName string, colum
}
}
table.defaultCurrentTimeCount++
- table.line = line
+ table.line = checker.baseLine + ctx.GetStart().GetLine()
checker.tableSet[tableName] = table
}
- if isOnUpdateCurrentTime(column) {
+ if checker.isOnUpdateCurrentTime(ctx) {
table, exists := checker.tableSet[tableName]
if !exists {
table = tableData{
@@ -131,71 +169,65 @@ func (checker *columnCurrentTimeCountLimitChecker) count(tableName string, colum
}
}
table.onUpdateCurrentTimeCount++
- table.line = line
+ table.line = checker.baseLine + ctx.GetStart().GetLine()
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())
- }
+func (*columnCurrentTimeCountLimitChecker) isDefaultCurrentTime(ctx mysql.IFieldDefinitionContext) bool {
+ for _, attr := range ctx.AllColumnAttribute() {
+ if attr.GetValue().GetTokenType() == mysql.MySQLParserDEFAULT_SYMBOL && attr.NOW_SYMBOL() != nil {
+ return true
}
}
-
- return in, false
-}
-
-// Leave implements the ast.Visitor interface.
-func (*columnCurrentTimeCountLimitChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
+ return false
}
-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
- }
+func (*columnCurrentTimeCountLimitChecker) isOnUpdateCurrentTime(ctx mysql.IFieldDefinitionContext) bool {
+ for _, attr := range ctx.AllColumnAttribute() {
+ if attr.GetValue().GetTokenType() == mysql.MySQLParserON_SYMBOL && attr.NOW_SYMBOL() != nil {
+ 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
- }
+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,
+ })
}
}
- 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
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
}
- return false
+ return checker.adviceList
}
diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
index 37792bd862..28733bd767 100644
--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go
@@ -92,6 +92,8 @@ func TestMySQLWIPRules(t *testing.T) {
// advisor.SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.
advisor.SchemaRuleSchemaBackwardCompatibility,
+ // advisor.SchemaRuleCurrentTimeColumnCountLimit enforce the current column count limit.
+ advisor.SchemaRuleCurrentTimeColumnCountLimit,
// advisor.SchemaRuleDropEmptyDatabase enforce the MySQL support check if the database is empty before users drop it.
advisor.SchemaRuleDropEmptyDatabase,
diff --git a/backend/plugin/advisor/mysqlwip/test/column_current_time_count_limit.yaml b/backend/plugin/advisor/mysqlwip/test/column_current_time_count_limit.yaml
index f5b200b722..920718777e 100644
--- a/backend/plugin/advisor/mysqlwip/test/column_current_time_count_limit.yaml
+++ b/backend/plugin/advisor/mysqlwip/test/column_current_time_count_limit.yaml
@@ -1,4 +1,4 @@
-- statement: CREATE TABLE t(a timestamp, b timestamp)
+- statement: CREATE TABLE t(a timestamp, b timestamp);
want:
- status: SUCCESS
code: 0
@@ -11,25 +11,25 @@
a timestamp default now(),
b timestamp default current_timestamp(),
c timestamp default localtime
- )
+ );
want:
- status: WARN
code: 418
title: column.current-time-count-limit
content: Table `t` has 3 DEFAULT CURRENT_TIMESTAMP() columns. The count greater than 2.
- line: 6
+ line: 4
details: ""
- statement: |-
CREATE TABLE t(
a timestamp default now() on update localtime,
b timestamp default current_timestamp() on update localtimestamp()
- )
+ );
want:
- status: WARN
code: 419
title: column.current-time-count-limit
content: Table `t` has 2 ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than 1.
- line: 5
+ line: 3
details: ""
- statement: |-
ALTER TABLE tech_book ADD COLUMN a timestamp default now() on update localtime;
@@ -39,5 +39,5 @@
code: 419
title: column.current-time-count-limit
content: Table `tech_book` has 2 ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than 1.
- line: 3
+ line: 2
details: ""
diff --git a/backend/plugin/advisor/mysqlwip/utils.go b/backend/plugin/advisor/mysqlwip/utils.go
index 8a26d3042b..ca0b288638 100644
--- a/backend/plugin/advisor/mysqlwip/utils.go
+++ b/backend/plugin/advisor/mysqlwip/utils.go
@@ -76,3 +76,10 @@ func (t tableColumnTypes) delete(tableName string, columnName string) {
}
delete(t[tableName], columnName)
}
+
+type tableData struct {
+ tableName string
+ defaultCurrentTimeCount int
+ onUpdateCurrentTimeCount int
+ line int
+}
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 5b93c9a356..7144f18746 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -1315,6 +1315,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
}
case SchemaRuleCurrentTimeColumnCountLimit:
switch engine {
+ // only for mysqlwip test.
+ case storepb.Engine_ENGINE_UNSPECIFIED:
+ return MySQLCurrentTimeColumnCountLimit, nil
case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:
return MySQLCurrentTimeColumnCountLimit, nil
}