Skip to content

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

refactor(advisor/tidb): migrate type-byte pair to omni AST + add cumulative #22 (Phase 1.5 §1.5.3 batch 13) (#20312)

Vincent Huang4c77abd1c0a1
diff --git a/backend/plugin/advisor/tidb/advisor_column_current_time_count_limit.go b/backend/plugin/advisor/tidb/advisor_column_current_time_count_limit.go
index 3883a04c15..cf6a342240 100644
--- a/backend/plugin/advisor/tidb/advisor_column_current_time_count_limit.go
+++ b/backend/plugin/advisor/tidb/advisor_column_current_time_count_limit.go
@@ -1,21 +1,16 @@
package tidb
-// Framework code is generated by the generator.
-
import (
"context"
"fmt"
"slices"
- "strings"
-
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/pingcap/tidb/pkg/parser/ast"
- "github.com/pingcap/tidb/pkg/parser/mysql"
+ "github.com/bytebase/omni/tidb/ast"
"github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
const (
@@ -25,7 +20,6 @@ const (
var (
_ advisor.Advisor = (*ColumnCurrentTimeCountLimitAdvisor)(nil)
- _ ast.Visitor = (*columnCurrentTimeCountLimitChecker)(nil)
)
func init() {
@@ -38,8 +32,7 @@ type ColumnCurrentTimeCountLimitAdvisor struct {
// Check checks for current time column count limit.
func (*ColumnCurrentTimeCountLimitAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
- stmtList, err := getTiDBNodes(checkCtx)
-
+ stmts, err := getTiDBOmniNodes(checkCtx)
if err != nil {
return nil, err
}
@@ -48,167 +41,130 @@ func (*ColumnCurrentTimeCountLimitAdvisor) Check(_ context.Context, checkCtx adv
if err != nil {
return nil, err
}
- checker := &columnCurrentTimeCountLimitChecker{
- level: level,
- title: checkCtx.Rule.Type.String(),
- tableSet: make(map[string]tableData),
- }
-
- for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
+ title := checkCtx.Rule.Type.String()
+
+ // Cross-statement accumulator: tracks per-table counts of
+ // DEFAULT-CURRENT_TIMESTAMP and ON-UPDATE-CURRENT_TIMESTAMP
+ // columns across all statements in the review. Pingcap-typed
+ // predecessor used the same single-pass accumulation pattern.
+ tableSet := make(map[string]currentTimeTableData)
+
+ for _, ostmt := range stmts {
+ switch n := ostmt.Node.(type) {
+ case *ast.CreateTableStmt:
+ if n.Table == nil {
+ continue
+ }
+ tableName := n.Table.Name
+ line := ostmt.AbsoluteLine(n.Loc.Start)
+ for _, column := range n.Columns {
+ countCurrentTimeColumn(tableSet, tableName, column, line)
+ }
+ case *ast.AlterTableStmt:
+ if n.Table == nil {
+ continue
+ }
+ tableName := n.Table.Name
+ line := ostmt.AbsoluteLine(n.Loc.Start)
+ for _, cmd := range n.Commands {
+ if cmd == nil {
+ continue
+ }
+ switch cmd.Type {
+ case ast.ATAddColumn:
+ for _, column := range addColumnTargets(cmd) {
+ countCurrentTimeColumn(tableSet, tableName, column, line)
+ }
+ case ast.ATChangeColumn, ast.ATModifyColumn:
+ if cmd.Column != nil {
+ countCurrentTimeColumn(tableSet, tableName, cmd.Column, line)
+ }
+ default:
+ }
+ }
+ default:
+ }
}
- return checker.generateAdvice(), nil
+ return generateCurrentTimeAdvice(tableSet, level, title), nil
}
-type columnCurrentTimeCountLimitChecker struct {
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- text string
- line int
- tableSet map[string]tableData
-}
-
-type tableData struct {
+// currentTimeTableData accumulates per-table counts of columns
+// declaring DEFAULT CURRENT_TIMESTAMP and/or ON UPDATE CURRENT_TIMESTAMP
+// (or their synonyms NOW/LOCALTIME/LOCALTIMESTAMP).
+type currentTimeTableData struct {
tableName string
defaultCurrentTimeCount int
onUpdateCurrentTimeCount int
line int
}
-func (checker *columnCurrentTimeCountLimitChecker) generateAdvice() []*storepb.Advice {
- var tableList []tableData
- for _, table := range checker.tableSet {
+// countCurrentTimeColumn increments the per-table counts for a single
+// column. Only DATETIME/TIMESTAMP columns are counted; the omniIsTimeType
+// gate matches pingcap-typed predecessor's TypeDatetime/TypeTimestamp
+// switch.
+func countCurrentTimeColumn(tableSet map[string]currentTimeTableData, tableName string, column *ast.ColumnDef, line int) {
+ if column == nil || !omniIsTimeType(column.TypeName) {
+ return
+ }
+ if omniIsDefaultCurrentTime(column) {
+ table, exists := tableSet[tableName]
+ if !exists {
+ table = currentTimeTableData{tableName: tableName}
+ }
+ table.defaultCurrentTimeCount++
+ table.line = line
+ tableSet[tableName] = table
+ }
+ if omniIsOnUpdateCurrentTime(column) {
+ table, exists := tableSet[tableName]
+ if !exists {
+ table = currentTimeTableData{tableName: tableName}
+ }
+ table.onUpdateCurrentTimeCount++
+ table.line = line
+ tableSet[tableName] = table
+ }
+}
+
+// generateCurrentTimeAdvice emits one advice per (table, category)
+// where the count exceeds the limit, sorted by line for deterministic
+// output. Mirrors pingcap-typed predecessor's generateAdvice exactly.
+func generateCurrentTimeAdvice(tableSet map[string]currentTimeTableData, level storepb.Advice_Status, title string) []*storepb.Advice {
+ var tableList []currentTimeTableData
+ for _, table := range tableSet {
tableList = append(tableList, table)
}
- slices.SortFunc(tableList, func(i, j tableData) int {
- if i.line < j.line {
+ slices.SortFunc(tableList, func(a, b currentTimeTableData) int {
+ if a.line < b.line {
return -1
}
- if i.line > j.line {
+ if a.line > b.line {
return 1
}
return 0
})
+
+ var adviceList []*storepb.Advice
for _, table := range tableList {
if table.defaultCurrentTimeCount > maxDefaultCurrentTimeColumCount {
- checker.adviceList = append(checker.adviceList, &storepb.Advice{
- Status: checker.level,
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
Code: code.DefaultCurrentTimeColumnCountExceedsLimit.Int32(),
- Title: checker.title,
+ Title: title,
Content: fmt.Sprintf("Table `%s` has %d DEFAULT CURRENT_TIMESTAMP() columns. The count greater than %d.", table.tableName, table.defaultCurrentTimeCount, maxDefaultCurrentTimeColumCount),
StartPosition: common.ConvertANTLRLineToPosition(table.line),
})
}
if table.onUpdateCurrentTimeCount > maxOnUpdateCurrentTimeColumnCount {
- checker.adviceList = append(checker.adviceList, &storepb.Advice{
- Status: checker.level,
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
Code: code.OnUpdateCurrentTimeColumnCountExceedsLimit.Int32(),
- Title: checker.title,
+ Title: title,
Content: fmt.Sprintf("Table `%s` has %d ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than %d.", table.tableName, table.onUpdateCurrentTimeCount, maxOnUpdateCurrentTimeColumnCount),
StartPosition: common.ConvertANTLRLineToPosition(table.line),
})
}
}
-
- 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
- }
- default:
- // Other column types
- }
-}
-
-// 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())
- default:
- }
- }
- default:
- }
-
- 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
- default:
- }
- return false
+ return adviceList
}
diff --git a/backend/plugin/advisor/tidb/advisor_column_maximum_character_length.go b/backend/plugin/advisor/tidb/advisor_column_maximum_character_length.go
index c8c64f1818..788eccd19a 100644
--- a/backend/plugin/advisor/tidb/advisor_column_maximum_character_length.go
+++ b/backend/plugin/advisor/tidb/advisor_column_maximum_character_length.go
@@ -1,26 +1,20 @@
package tidb
-// Framework code is generated by the generator.
-
import (
"context"
"fmt"
+ "github.com/bytebase/omni/tidb/ast"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/pingcap/tidb/pkg/parser/ast"
- "github.com/pingcap/tidb/pkg/parser/mysql"
-
"github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
var (
_ advisor.Advisor = (*ColumnMaximumCharacterLengthAdvisor)(nil)
- _ ast.Visitor = (*columnMaximumCharacterLengthChecker)(nil)
)
func init() {
@@ -33,8 +27,7 @@ type ColumnMaximumCharacterLengthAdvisor struct {
// Check checks for maximum character length.
func (*ColumnMaximumCharacterLengthAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
- stmtList, err := getTiDBNodes(checkCtx)
-
+ stmts, err := getTiDBOmniNodes(checkCtx)
if err != nil {
return nil, err
}
@@ -47,94 +40,91 @@ func (*ColumnMaximumCharacterLengthAdvisor) Check(_ context.Context, checkCtx ad
if numberPayload == nil {
return nil, errors.New("number_payload is required for column maximum character length rule")
}
- checker := &columnMaximumCharacterLengthChecker{
- level: level,
- title: checkCtx.Rule.Type.String(),
- maximum: int(numberPayload.Number),
- }
-
- for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
+ maximum := int(numberPayload.Number)
+ title := checkCtx.Rule.Type.String()
+
+ var adviceList []*storepb.Advice
+ for _, ostmt := range stmts {
+ advice := checkStmtForCharLength(ostmt, maximum, level, title)
+ if advice != nil {
+ adviceList = append(adviceList, advice)
+ }
}
- return checker.adviceList, nil
+ return adviceList, nil
}
-type columnMaximumCharacterLengthChecker struct {
- adviceList []*storepb.Advice
- level storepb.Advice_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) {
+// checkStmtForCharLength returns at most ONE advice per top-level
+// statement, mirroring pingcap-typed predecessor's `break`-after-first-
+// match cardinality contract. Mysql analog emits per-column (no break)
+// — cardinality divergence preserved on the tidb side per invariant #7.
+//
+// Rule fires on CHAR or BINARY columns whose length exceeds the
+// configured maximum. Cumulative #22 territory: pingcap's
+// `mysql.TypeString` covered BOTH CHAR and BINARY (charset-pair
+// unification); my omni port matches both via omniIsCharOrBinaryType.
+// MySQL's "max character length" rule conceptually applies to CHAR;
+// extending to BINARY preserves the pingcap behavior even though it's
+// semantically odd (BINARY length is bytes, not characters).
+func checkStmtForCharLength(ostmt OmniStmt, maximum int, level storepb.Advice_Status, title string) *storepb.Advice {
+ if maximum <= 0 {
+ return nil
+ }
+ switch n := ostmt.Node.(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
+ if n.Table == nil {
+ return nil
+ }
+ tableName := n.Table.Name
+ for _, column := range n.Columns {
+ if column == nil {
+ continue
+ }
+ if charLength := omniCharLength(column.TypeName); charLength > maximum {
+ return buildCharLengthAdvice(level, title, tableName, column.Name, charLength, maximum, ostmt.AbsoluteLine(column.Loc.Start))
}
}
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()
+ if n.Table == nil {
+ return nil
+ }
+ tableName := n.Table.Name
+ stmtLine := ostmt.AbsoluteLine(n.Loc.Start)
+ for _, cmd := range n.Commands {
+ if cmd == nil {
+ continue
+ }
+ switch cmd.Type {
+ case ast.ATAddColumn:
+ for _, column := range addColumnTargets(cmd) {
+ if column == nil {
+ continue
+ }
+ if charLength := omniCharLength(column.TypeName); charLength > maximum {
+ return buildCharLengthAdvice(level, title, tableName, column.Name, charLength, maximum, stmtLine)
}
}
- 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()
+ case ast.ATChangeColumn, ast.ATModifyColumn:
+ if cmd.Column == nil {
+ continue
+ }
+ if charLength := omniCharLength(cmd.Column.TypeName); charLength > maximum {
+ return buildCharLengthAdvice(level, title, tableName, cmd.Column.Name, charLength, maximum, stmtLine)
}
default:
}
- if tableName != "" {
- break
- }
}
default:
}
-
- if tableName != "" {
- checker.adviceList = append(checker.adviceList, &storepb.Advice{
- Status: checker.level,
- Code: code.CharLengthExceedsLimit.Int32(),
- Title: checker.title,
- Content: fmt.Sprintf("The length of the CHAR column `%s` is bigger than %d, please use VARCHAR instead", columnName, checker.maximum),
- StartPosition: common.ConvertANTLRLineToPosition(line),
- })
- }
-
- return in, false
-}
-
-// Leave implements the ast.Visitor interface.
-func (*columnMaximumCharacterLengthChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
+ return nil
}
-func getCharLength(column *ast.ColumnDef) int {
- if column.Tp.GetType() == mysql.TypeString {
- return column.Tp.GetFlen()
+func buildCharLengthAdvice(level storepb.Advice_Status, title, _, columnName string, charLength, maximum, line int) *storepb.Advice {
+ return &storepb.Advice{
+ Status: level,
+ Code: code.CharLengthExceedsLimit.Int32(),
+ Title: title,
+ Content: fmt.Sprintf("The length of the CHAR column `%s` is %d, bigger than %d, please use VARCHAR instead", columnName, charLength, maximum),
+ StartPosition: common.ConvertANTLRLineToPosition(line),
}
- return 0
}
diff --git a/backend/plugin/advisor/tidb/test/column_maximum_character_length.yaml b/backend/plugin/advisor/tidb/test/column_maximum_character_length.yaml
index 253d9ee34a..d10a0562d5 100644
--- a/backend/plugin/advisor/tidb/test/column_maximum_character_length.yaml
+++ b/backend/plugin/advisor/tidb/test/column_maximum_character_length.yaml
@@ -8,7 +8,7 @@
- status: 2
code: 415
title: COLUMN_MAXIMUM_CHARACTER_LENGTH
- content: The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead
+ content: The length of the CHAR column `name` is 225, bigger than 20, please use VARCHAR instead
startposition:
line: 1
column: 0
@@ -19,7 +19,7 @@
- status: 2
code: 415
title: COLUMN_MAXIMUM_CHARACTER_LENGTH
- content: The length of the CHAR column `name_2` is bigger than 20, please use VARCHAR instead
+ content: The length of the CHAR column `name_2` is 225, bigger than 20, please use VARCHAR instead
startposition:
line: 1
column: 0
@@ -30,7 +30,7 @@
- status: 2
code: 415
title: COLUMN_MAXIMUM_CHARACTER_LENGTH
- content: The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead
+ content: The length of the CHAR column `name` is 225, bigger than 20, please use VARCHAR instead
startposition:
line: 1
column: 0
@@ -41,7 +41,42 @@
- status: 2
code: 415
title: COLUMN_MAXIMUM_CHARACTER_LENGTH
- content: The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead
+ content: The length of the CHAR column `name` is 225, bigger than 20, please use VARCHAR instead
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+# Cumulative #22 pin (batch 13): pingcap's mysql.TypeString covered
+# BOTH CHAR and BINARY (charset-pair unification, same shape as #18
+# BLOB/TEXT). The pingcap-tidb rule fired on BINARY(N>maximum) too;
+# a mechanical port matching only "CHAR" would drop BINARY coverage
+# (mysql analog had this latent gap — pre-omni mysql also missed it
+# via ANTLR token symbols; long-standing mysql gap, not regression
+# per invariant #10). This fixture locks the BINARY-coverage contract
+# on tidb.
+- statement: CREATE TABLE t(blob_col binary(225))
+ changeType: 1
+ want:
+ - status: 2
+ code: 415
+ title: COLUMN_MAXIMUM_CHARACTER_LENGTH
+ content: The length of the CHAR column `blob_col` is 225, bigger than 20, please use VARCHAR instead
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+# Single-advice-per-statement cardinality pin (batch 13): pingcap-tidb's
+# Visitor broke after the first CHAR/BINARY column exceeding the limit
+# — ONE advice per top-level statement. Mysql analog emits per-column.
+# Tidb preserves pingcap behavior. Multi-column fixture verifies exactly
+# 1 advice for a statement with TWO violating columns.
+- statement: CREATE TABLE t(a char(225), b binary(225))
+ changeType: 1
+ want:
+ - status: 2
+ code: 415
+ title: COLUMN_MAXIMUM_CHARACTER_LENGTH
+ content: The length of the CHAR column `a` is 225, bigger than 20, please use VARCHAR instead
startposition:
line: 1
column: 0
diff --git a/backend/plugin/advisor/tidb/utils.go b/backend/plugin/advisor/tidb/utils.go
index 28aceb8109..98fdb0966c 100644
--- a/backend/plugin/advisor/tidb/utils.go
+++ b/backend/plugin/advisor/tidb/utils.go
@@ -348,6 +348,110 @@ func firstAlterCommandMatching(n *omniast.AlterTableStmt, matcher func(*omniast.
return -1
}
+// omniIsTimeType reports whether the column type is DATETIME or
+// TIMESTAMP. Pingcap dispatched on `mysql.TypeDatetime` /
+// `mysql.TypeTimestamp` — distinct type bytes, no unification.
+// omni surfaces both as their own DataType.Name with no aliasing.
+func omniIsTimeType(dt *omniast.DataType) bool {
+ if dt == nil {
+ return false
+ }
+ switch strings.ToUpper(dt.Name) {
+ case "DATETIME", "TIMESTAMP":
+ return true
+ default:
+ return false
+ }
+}
+
+// omniIsDefaultCurrentTime reports whether a column has
+// `DEFAULT CURRENT_TIMESTAMP` (or one of its synonyms: NOW(),
+// LOCALTIME, LOCALTIMESTAMP). The omni AST puts the default
+// expression on `col.DefaultValue` (as an ExprNode); a function-call
+// default surfaces as `*omniast.FuncCallExpr` with `Name` carrying
+// the function token.
+func omniIsDefaultCurrentTime(col *omniast.ColumnDef) bool {
+ if col == nil {
+ return false
+ }
+ return omniIsCurrentTimeFuncCall(col.DefaultValue)
+}
+
+// omniIsOnUpdateCurrentTime reports whether a column has
+// `ON UPDATE CURRENT_TIMESTAMP` (or its synonyms). Omni surfaces
+// the on-update expression on `col.OnUpdate` — a separate top-level
+// field on ColumnDef (NOT inside Constraints[]).
+func omniIsOnUpdateCurrentTime(col *omniast.ColumnDef) bool {
+ if col == nil {
+ return false
+ }
+ return omniIsCurrentTimeFuncCall(col.OnUpdate)
+}
+
+// omniIsCurrentTimeFuncCall checks whether the given expression is a
+// function call to one of the CURRENT_TIMESTAMP synonyms:
+// CURRENT_TIMESTAMP, NOW, LOCALTIME, LOCALTIMESTAMP. Pingcap
+// canonicalized these to lowercase via `FnName.L`; omni keeps the
+// user's original case in `FuncCallExpr.Name`, so we compare
+// case-insensitively.
+func omniIsCurrentTimeFuncCall(expr omniast.ExprNode) bool {
+ if expr == nil {
+ return false
+ }
+ fc, ok := expr.(*omniast.FuncCallExpr)
+ if !ok {
+ return false
+ }
+ switch strings.ToUpper(fc.Name) {
+ case "NOW", "CURRENT_TIMESTAMP", "LOCALTIME", "LOCALTIMESTAMP":
+ return true
+ default:
+ return false
+ }
+}
+
+// omniIsCharOrBinaryType reports whether the column type is a
+// fixed-length character/binary type (CHAR or BINARY). Pingcap-tidb
+// dispatched on `mysql.TypeString` which covered BOTH `CHAR` and
+// `BINARY` via charset distinction (charset-pair unification, same
+// shape as cumulative #18 BLOB/TEXT and #20 TINYINT/BOOLEAN). Omni
+// splits to distinct `DataType.Name = "CHAR"` and `"BINARY"`.
+// Cumulative #22 — both must be matched to preserve pingcap behavior.
+// Mysql analog only matches CHAR (long-standing mysql gap; pre-omni
+// mysql used ANTLR token symbols and never matched BINARY either —
+// NOT a regression).
+func omniIsCharOrBinaryType(dt *omniast.DataType) bool {
+ if dt == nil {
+ return false
+ }
+ switch strings.ToUpper(dt.Name) {
+ case "CHAR", "BINARY":
+ return true
+ default:
+ return false
+ }
+}
+
+// omniCharLength returns the declared length of a CHAR/BINARY column,
+// applying the MySQL default of 1 when no explicit length is given.
+// Pingcap's `column.Tp.GetFlen()` returned the canonical default
+// width for bare CHAR / BARE BINARY; omni keeps Length=0 in that
+// case. Matches both omni-builder behavior and INFORMATION_SCHEMA
+// rendering.
+//
+// Returns 0 for non-CHAR/BINARY types — callers gate on
+// omniIsCharOrBinaryType first.
+func omniCharLength(dt *omniast.DataType) int {
+ if dt == nil || !omniIsCharOrBinaryType(dt) {
+ return 0
+ }
+ if dt.Length == 0 {
+ // MySQL default: bare CHAR → CHAR(1); bare BINARY → BINARY(1).
+ return 1
+ }
+ return dt.Length
+}
+
// omniIsIntegerType reports whether the column type is an integer type
// from the perspective of pingcap-tidb's `isInteger` helper. Pingcap
// dispatched on `mysql.TypeTiny`/`TypeShort`/`TypeInt24`/`TypeLong`/`TypeLonglong`
diff --git a/backend/plugin/advisor/tidb/utils_test.go b/backend/plugin/advisor/tidb/utils_test.go
index d667b3e365..91d00f47e6 100644
--- a/backend/plugin/advisor/tidb/utils_test.go
+++ b/backend/plugin/advisor/tidb/utils_test.go
@@ -291,3 +291,114 @@ func TestOmniColumnHasComment_PresentAbsentDistinction(t *testing.T) {
require.True(t, omniColumnHasComment(regularCommentCol),
"explicit COMMENT with value: omniColumnHasComment must return true")
}
+
+// TestOmniIsTimeType pins the DATETIME/TIMESTAMP detection for
+// column_current_time_count_limit (batch 13). Pingcap dispatched
+// on mysql.TypeDatetime/TypeTimestamp — distinct type bytes,
+// no unification concern.
+func TestOmniIsTimeType(t *testing.T) {
+ cases := []struct {
+ name string
+ dt *omniast.DataType
+ want bool
+ }{
+ {"DATETIME", &omniast.DataType{Name: "DATETIME"}, true},
+ {"TIMESTAMP", &omniast.DataType{Name: "TIMESTAMP"}, true},
+ {"lowercase datetime", &omniast.DataType{Name: "datetime"}, true},
+ {"DATE", &omniast.DataType{Name: "DATE"}, false},
+ {"TIME", &omniast.DataType{Name: "TIME"}, false},
+ {"YEAR", &omniast.DataType{Name: "YEAR"}, false},
+ {"VARCHAR", &omniast.DataType{Name: "VARCHAR"}, false},
+ {"nil", nil, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, omniIsTimeType(tc.dt))
+ })
+ }
+}
+
+// TestOmniIsCurrentTimeFuncCall covers the CURRENT_TIMESTAMP synonym
+// detection used by column_current_time_count_limit. Pingcap used
+// FnName.L (lowercased); omni keeps user case in FuncCallExpr.Name,
+// so we compare case-insensitively.
+func TestOmniIsCurrentTimeFuncCall(t *testing.T) {
+ cases := []struct {
+ name string
+ expr omniast.ExprNode
+ want bool
+ }{
+ {"CURRENT_TIMESTAMP uppercase", &omniast.FuncCallExpr{Name: "CURRENT_TIMESTAMP"}, true},
+ {"current_timestamp lowercase", &omniast.FuncCallExpr{Name: "current_timestamp"}, true},
+ {"NOW", &omniast.FuncCallExpr{Name: "NOW"}, true},
+ {"LOCALTIME", &omniast.FuncCallExpr{Name: "LOCALTIME"}, true},
+ {"LOCALTIMESTAMP", &omniast.FuncCallExpr{Name: "LOCALTIMESTAMP"}, true},
+ {"UTC_TIMESTAMP (not synonym)", &omniast.FuncCallExpr{Name: "UTC_TIMESTAMP"}, false},
+ {"unknown function", &omniast.FuncCallExpr{Name: "FOO"}, false},
+ {"nil expr", nil, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, omniIsCurrentTimeFuncCall(tc.expr))
+ })
+ }
+}
+
+// TestOmniIsCharOrBinaryType pins cumulative #22 — pingcap's
+// `mysql.TypeString` covered BOTH CHAR and BINARY via charset
+// distinction. The omni port must match both names; a mechanical
+// port matching only "CHAR" (like the mysql analog does) silently
+// drops BINARY coverage. Same shape as cumulative #18 (BLOB/TEXT
+// under TypeBlob) and #20 (TINYINT/BOOLEAN under TypeTiny).
+//
+// VARCHAR/VARBINARY are TypeVarString in pingcap, NOT TypeString —
+// pingcap rule did NOT fire on those. Pin the negative case too.
+func TestOmniIsCharOrBinaryType(t *testing.T) {
+ cases := []struct {
+ name string
+ dt *omniast.DataType
+ want bool
+ }{
+ {"CHAR", &omniast.DataType{Name: "CHAR"}, true},
+ {"BINARY", &omniast.DataType{Name: "BINARY"}, true},
+ {"lowercase char", &omniast.DataType{Name: "char"}, true},
+ {"lowercase binary", &omniast.DataType{Name: "binary"}, true},
+ {"VARCHAR (negative)", &omniast.DataType{Name: "VARCHAR"}, false},
+ {"VARBINARY (negative)", &omniast.DataType{Name: "VARBINARY"}, false},
+ {"TEXT", &omniast.DataType{Name: "TEXT"}, false},
+ {"BLOB", &omniast.DataType{Name: "BLOB"}, false},
+ {"nil", nil, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, omniIsCharOrBinaryType(tc.dt))
+ })
+ }
+}
+
+// TestOmniCharLength pins the MySQL default-1 application for bare
+// CHAR / BINARY columns. Pingcap's column.Tp.GetFlen() returned the
+// canonical default (1) for bare CHAR; omni leaves Length=0, so the
+// helper must apply the default explicitly to preserve pingcap
+// behavior on column_maximum_character_length.
+func TestOmniCharLength(t *testing.T) {
+ cases := []struct {
+ name string
+ dt *omniast.DataType
+ want int
+ }{
+ {"bare CHAR → 1", &omniast.DataType{Name: "CHAR"}, 1},
+ {"bare BINARY → 1", &omniast.DataType{Name: "BINARY"}, 1},
+ {"CHAR(10)", &omniast.DataType{Name: "CHAR", Length: 10}, 10},
+ {"BINARY(16)", &omniast.DataType{Name: "BINARY", Length: 16}, 16},
+ {"CHAR(255)", &omniast.DataType{Name: "CHAR", Length: 255}, 255},
+ {"VARCHAR(255) → 0", &omniast.DataType{Name: "VARCHAR", Length: 255}, 0},
+ {"INT → 0", &omniast.DataType{Name: "INT"}, 0},
+ {"nil → 0", nil, 0},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, omniCharLength(tc.dt))
+ })
+ }
+}