Skip to content

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

refactor(advisor/tidb): migrate column_disallow_changing trio to omni AST (Phase 1.5 §1.5.3 batch 11) (#20302)

Vincent Huang0071d6062f9c
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_changing.go b/backend/plugin/advisor/tidb/advisor_column_disallow_changing.go
index e78d88602b..72d45a5a15 100644
--- a/backend/plugin/advisor/tidb/advisor_column_disallow_changing.go
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_changing.go
@@ -1,23 +1,19 @@
package tidb
-// Framework code is generated by the generator.
-
import (
"context"
"fmt"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/pingcap/tidb/pkg/parser/ast"
+ "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"
)
var (
_ advisor.Advisor = (*ColumnDisallowChangingAdvisor)(nil)
- _ ast.Visitor = (*columnDisallowChangingChecker)(nil)
)
func init() {
@@ -30,8 +26,7 @@ type ColumnDisallowChangingAdvisor struct {
// Check checks for disallow CHANGE COLUMN statement.
func (*ColumnDisallowChangingAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
- stmtList, err := getTiDBNodes(checkCtx)
-
+ stmts, err := getTiDBOmniNodes(checkCtx)
if err != nil {
return nil, err
}
@@ -40,49 +35,30 @@ func (*ColumnDisallowChangingAdvisor) Check(_ context.Context, checkCtx advisor.
if err != nil {
return nil, err
}
- checker := &columnDisallowChangingChecker{
- level: level,
- title: checkCtx.Rule.Type.String(),
- }
-
- for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
- }
-
- return checker.adviceList, nil
-}
-
-type columnDisallowChangingChecker struct {
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- text string
- line int
-}
-
-// Enter implements the ast.Visitor interface.
-func (checker *columnDisallowChangingChecker) Enter(in ast.Node) (ast.Node, bool) {
- if node, ok := in.(*ast.AlterTableStmt); ok {
- for _, spec := range node.Specs {
- if spec.Tp == ast.AlterTableChangeColumn {
- checker.adviceList = append(checker.adviceList, &storepb.Advice{
- Status: checker.level,
- Code: code.UseChangeColumnStatement.Int32(),
- Title: checker.title,
- Content: fmt.Sprintf("\"%s\" contains CHANGE COLUMN statement", checker.text),
- StartPosition: common.ConvertANTLRLineToPosition(checker.line),
- })
- break
- }
+ title := checkCtx.Rule.Type.String()
+ var adviceList []*storepb.Advice
+ for _, ostmt := range stmts {
+ alter, ok := ostmt.Node.(*ast.AlterTableStmt)
+ if !ok {
+ continue
+ }
+ // Single-advice-per-statement contract: pingcap-tidb's Visitor
+ // broke after the first match; preserve via firstAlterCommandMatching
+ // (the helper returns the first index satisfying the matcher).
+ // Mysql analog emits per-cmd without breaking — cardinality
+ // divergence preserved on the tidb side per invariant #7.
+ if firstAlterCommandMatching(alter, func(cmd *ast.AlterTableCmd) bool {
+ return cmd.Type == ast.ATChangeColumn
+ }) >= 0 {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
+ Code: code.UseChangeColumnStatement.Int32(),
+ Title: title,
+ Content: fmt.Sprintf("\"%s\" contains CHANGE COLUMN statement", ostmt.TrimmedText()),
+ StartPosition: common.ConvertANTLRLineToPosition(ostmt.AbsoluteLine(alter.Loc.Start)),
+ })
}
}
- return in, false
-}
-
-// Leave implements the ast.Visitor interface.
-func (*columnDisallowChangingChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
+ return adviceList, nil
}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_changing_order.go b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_order.go
index 4a647ee7b4..9c6ebe27ac 100644
--- a/backend/plugin/advisor/tidb/advisor_column_disallow_changing_order.go
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_order.go
@@ -1,23 +1,19 @@
package tidb
-// Framework code is generated by the generator.
-
import (
"context"
"fmt"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/pingcap/tidb/pkg/parser/ast"
+ "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"
)
var (
_ advisor.Advisor = (*ColumnDisallowChangingOrderAdvisor)(nil)
- _ ast.Visitor = (*columnDisallowChangingOrderChecker)(nil)
)
func init() {
@@ -30,8 +26,7 @@ type ColumnDisallowChangingOrderAdvisor struct {
// Check checks for disallow changing column order.
func (*ColumnDisallowChangingOrderAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
- stmtList, err := getTiDBNodes(checkCtx)
-
+ stmts, err := getTiDBOmniNodes(checkCtx)
if err != nil {
return nil, err
}
@@ -40,50 +35,28 @@ func (*ColumnDisallowChangingOrderAdvisor) Check(_ context.Context, checkCtx adv
if err != nil {
return nil, err
}
- checker := &columnDisallowChangingOrderChecker{
- level: level,
- title: checkCtx.Rule.Type.String(),
- }
-
- for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
- }
-
- return checker.adviceList, nil
-}
-
-type columnDisallowChangingOrderChecker struct {
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- text string
- line int
-}
-
-// Enter implements the ast.Visitor interface.
-func (checker *columnDisallowChangingOrderChecker) Enter(in ast.Node) (ast.Node, bool) {
- if node, ok := in.(*ast.AlterTableStmt); ok {
- for _, spec := range node.Specs {
- if (spec.Tp == ast.AlterTableChangeColumn || spec.Tp == ast.AlterTableModifyColumn) &&
- spec.Position.Tp != ast.ColumnPositionNone {
- checker.adviceList = append(checker.adviceList, &storepb.Advice{
- Status: checker.level,
- Code: code.ChangeColumnOrder.Int32(),
- Title: checker.title,
- Content: fmt.Sprintf("\"%s\" changes column order", checker.text),
- StartPosition: common.ConvertANTLRLineToPosition(checker.line),
- })
- break
- }
+ title := checkCtx.Rule.Type.String()
+ var adviceList []*storepb.Advice
+ for _, ostmt := range stmts {
+ alter, ok := ostmt.Node.(*ast.AlterTableStmt)
+ if !ok {
+ continue
+ }
+ // Single-advice-per-statement contract (mirrors pingcap-tidb).
+ // Mysql analog emits per-cmd; preserve pingcap behavior.
+ if firstAlterCommandMatching(alter, func(cmd *ast.AlterTableCmd) bool {
+ return (cmd.Type == ast.ATChangeColumn || cmd.Type == ast.ATModifyColumn) &&
+ (cmd.First || cmd.After != "")
+ }) >= 0 {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
+ Code: code.ChangeColumnOrder.Int32(),
+ Title: title,
+ Content: fmt.Sprintf("\"%s\" changes column order", ostmt.TrimmedText()),
+ StartPosition: common.ConvertANTLRLineToPosition(ostmt.AbsoluteLine(alter.Loc.Start)),
+ })
}
}
- return in, false
-}
-
-// Leave implements the ast.Visitor interface.
-func (*columnDisallowChangingOrderChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
+ return adviceList, nil
}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type.go b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type.go
index 067d656f5c..5d239a6960 100644
--- a/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type.go
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type.go
@@ -1,39 +1,34 @@
package tidb
-// Framework code is generated by the generator.
-
import (
"context"
"fmt"
"strings"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/pingcap/tidb/pkg/parser/ast"
+ "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"
"github.com/bytebase/bytebase/backend/store/model"
)
var (
_ advisor.Advisor = (*ColumnDisallowChangingTypeAdvisor)(nil)
- _ ast.Visitor = (*columnDisallowChangingTypeChecker)(nil)
)
func init() {
advisor.Register(storepb.Engine_TIDB, storepb.SQLReviewRule_COLUMN_DISALLOW_CHANGE_TYPE, &ColumnDisallowChangingTypeAdvisor{})
}
-// ColumnDisallowChangingTypeAdvisor is the advisor checking for disallow changing column type..
+// ColumnDisallowChangingTypeAdvisor is the advisor checking for disallow changing column type.
type ColumnDisallowChangingTypeAdvisor struct {
}
-// Check checks for disallow changing column type..
+// Check checks for disallow changing column type.
func (*ColumnDisallowChangingTypeAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
- stmtList, err := getTiDBNodes(checkCtx)
-
+ stmts, err := getTiDBOmniNodes(checkCtx)
if err != nil {
return nil, err
}
@@ -42,69 +37,331 @@ func (*ColumnDisallowChangingTypeAdvisor) Check(_ context.Context, checkCtx advi
if err != nil {
return nil, err
}
- checker := &columnDisallowChangingTypeChecker{
- level: level,
- title: checkCtx.Rule.Type.String(),
- originalMetadata: checkCtx.OriginalMetadata,
+ title := checkCtx.Rule.Type.String()
+ originalMetadata := checkCtx.OriginalMetadata
+
+ var adviceList []*storepb.Advice
+ for _, ostmt := range stmts {
+ alter, ok := ostmt.Node.(*ast.AlterTableStmt)
+ if !ok || alter.Table == nil {
+ continue
+ }
+ tableName := alter.Table.Name
+ changed := false
+ for _, cmd := range alter.Commands {
+ if cmd == nil {
+ continue
+ }
+ var oldColumnName string
+ switch cmd.Type {
+ case ast.ATChangeColumn:
+ // CHANGE COLUMN: cmd.Name is the OLD column name.
+ oldColumnName = cmd.Name
+ case ast.ATModifyColumn:
+ // MODIFY COLUMN: column name comes from the column def.
+ if cmd.Column != nil {
+ oldColumnName = cmd.Column.Name
+ }
+ default:
+ continue
+ }
+ if cmd.Column == nil || cmd.Column.TypeName == nil || oldColumnName == "" {
+ continue
+ }
+ if columnTypeChanged(originalMetadata, tableName, oldColumnName, cmd.Column.TypeName) {
+ changed = true
+ break
+ }
+ }
+ if changed {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
+ Code: code.ChangeColumnType.Int32(),
+ Title: title,
+ Content: fmt.Sprintf("\"%s\" changes column type", ostmt.TrimmedText()),
+ StartPosition: common.ConvertANTLRLineToPosition(ostmt.AbsoluteLine(alter.Loc.Start)),
+ })
+ }
}
- for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
+ return adviceList, nil
+}
+
+// columnTypeChanged compares the new type (rendered from the omni
+// DataType) against the catalog-stored type for the given column. Both
+// sides are routed through normalizeColumnType to canonicalize the
+// integer default-length forms (`int` ↔ `int(11)` etc.). Returns false
+// if the column is not in the catalog (treated as "no change to detect").
+//
+// Note: pingcap-typed predecessor used `Tp.String()` which appended a
+// ` BINARY` charset annotation on BLOB/TINYBLOB/VARBINARY etc., causing
+// false-positive flags on no-op type changes (catalog stores the type
+// without the charset suffix; pingcap rendered it with). Omni's
+// DataType.Name is the bare type name with no charset suffix, so the
+// omni port correctly compares "blob" against catalog "blob" — fixes
+// the latent false-positive. See cumulative #21.
+func columnTypeChanged(metadata *model.DatabaseMetadata, tableName, columnName string, dt *ast.DataType) bool {
+ column := metadata.GetSchemaMetadata("").GetTable(tableName).GetColumn(columnName)
+ if column == nil {
+ return false
}
+ return normalizeColumnType(column.GetProto().Type) != normalizeColumnType(omniBuildColumnTypeString(dt))
+}
+
+// omniBuildColumnTypeString renders an omni DataType into the lowercase
+// "name[(...)] [unsigned] [zerofill]" form that the normalizeColumnType
+// helper + catalog comparison expects.
+//
+// Rendering rules per type family (each verified empirically against
+// pingcap's Tp.String() during pre-batch protocol; cumulative #21):
+//
+// - **ENUM / SET:** render the literal value list as
+// `enum('v1','v2',…)` / `set('v1','v2',…)`, single quotes inside
+// values doubled per SQL convention. Pingcap preserved the literals
+// in `Tp.String()`; catalog stores them via MySQL's COLUMN_TYPE.
+// A naive builder that dropped EnumValues would false-positive on
+// no-op `MODIFY status ENUM('a','b')` (Codex round-4 catch).
+//
+// - **DECIMAL / NUMERIC / FIXED (exact-precision):** always (M,D)
+// when Length > 0; Scale defaults to 0. Pingcap and MySQL
+// info_schema both canonicalize `DECIMAL(10)` → `decimal(10,0)`.
+//
+// - **FLOAT / DOUBLE / REAL (approximate):** (M,D) ONLY when Scale
+// was explicitly given (Scale > 0); otherwise render bare type
+// name. MySQL drops the precision hint for `FLOAT(10)` —
+// pingcap's `Tp.String()` returns `"float"` for `FLOAT(10)` and
+// `"float"` for `FLOAT(10,0)`. Treating these like DECIMAL caused
+// false-positives on no-op `MODIFY x FLOAT(10)` (Codex round-3
+// catch).
+//
+// - **All other types** (VARCHAR / CHAR / BINARY / VARBINARY /
+// integer family / etc.): (Length) when Length > 0; no scale.
+//
+// Additional attributes:
+//
+// - **ZEROFILL**: pingcap appended `" ZEROFILL"` (and implied
+// UNSIGNED) for zerofill columns. Render `" zerofill"` when
+// `Zerofill` is set; treat Zerofill as implying Unsigned in the
+// output. Caveat: MySQL canonicalizes ZEROFILL display widths to
+// maximums (e.g. `int(11)` → `int(10)`); the normalizeColumnType
+// map doesn't cover zerofill cases, so display-width-
+// canonicalization differences may still surface as false-
+// positives on rare ZEROFILL no-op modifies. Out of scope
+// (ZEROFILL is deprecated in MySQL 8.0.17+).
+//
+// - **Charset / collation:** pingcap appended a `" BINARY"` charset
+// annotation on BLOB/TINYBLOB/VARBINARY; omni's DataType has no
+// charset suffix. Latent pingcap false-positive — silently fixed
+// by the migration (cumulative #21).
+func omniBuildColumnTypeString(dt *ast.DataType) string {
+ if dt == nil {
+ return ""
+ }
+ lower := strings.ToLower(dt.Name)
+
+ // Build the base form (without UNSIGNED/ZEROFILL modifiers).
+ // Modifier handling is centralized below so canonical-bare-form
+ // types (DECIMAL → decimal(10,0), INT → int(11), etc.) compose
+ // correctly with UNSIGNED/ZEROFILL — this avoids the
+ // bare-form × modifier Cartesian product false-positive class
+ // (Codex round-8 catch on PR #20302; otherwise
+ // `MODIFY x DECIMAL UNSIGNED` against `decimal(10,0) unsigned`
+ // catalog would false-positive because my builder previously
+ // emitted "decimal unsigned" and normalizeColumnType had no
+ // "decimal unsigned" entry).
+ base := buildBaseTypeForm(dt, lower)
+
+ // ZEROFILL implies UNSIGNED in MySQL storage; pingcap's Tp.String()
+ // rendered both. Match that convention.
+ if dt.Unsigned || dt.Zerofill {
+ base += " unsigned"
+ }
+ if dt.Zerofill {
+ base += " zerofill"
+ }
+ return base
+}
- return checker.adviceList, nil
+// buildBaseTypeForm renders the type body (without UNSIGNED/ZEROFILL
+// suffixes), applying MySQL canonical default precisions where the
+// type family carries them. ENUM/SET use their value list as the body.
+func buildBaseTypeForm(dt *ast.DataType, lower string) string {
+ switch {
+ case isEnumOrSetTypeName(lower):
+ return fmt.Sprintf("%s(%s)", lower, formatEnumValueList(dt.EnumValues))
+ case dt.Length > 0 && isExactDecimalTypeName(lower):
+ // DECIMAL / NUMERIC / FIXED with explicit length: always (M,D),
+ // defaulting Scale=0. Canonicalize the type name to "decimal"
+ // — pingcap's Tp.String() and MySQL info_schema both render
+ // `NUMERIC(8,2)` and `FIXED(8,2)` as `decimal(8,2)`. Empirical:
+ // omni pre-normalizes FIXED/DEC/INTEGER but does NOT
+ // pre-normalize NUMERIC (Name stays "NUMERIC"); render
+ // "decimal(...)" regardless to match catalog (Codex round-9).
+ return fmt.Sprintf("decimal(%d,%d)", dt.Length, dt.Scale)
+ case dt.Length > 0 && dt.Scale > 0:
+ // Any other type with explicit (M,D) — render both.
+ return fmt.Sprintf("%s(%d,%d)", lower, dt.Length, dt.Scale)
+ case dt.Length > 0 && !isApproximateFloatTypeName(lower):
+ // VARCHAR / CHAR / integer-with-display-width / etc.: (Length).
+ // FLOAT(N) / DOUBLE(N) / REAL(N) fall through to default below →
+ // bare name, matching pingcap's precision-hint drop.
+ return fmt.Sprintf("%s(%d)", lower, dt.Length)
+ }
+ // No length, OR float-family without explicit scale.
+ // Apply MySQL canonical default precision for type families whose
+ // catalog/info_schema rendering carries the default.
+ if canonical, ok := canonicalBareTypeForm(lower); ok {
+ return canonical
+ }
+ return lower
}
-type columnDisallowChangingTypeChecker struct {
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- text string
- line int
- originalMetadata *model.DatabaseMetadata
+// canonicalBareTypeForm returns the MySQL canonical default rendering
+// for type families whose info_schema / pingcap Tp.String() always
+// includes an explicit length/precision even when the user wrote the
+// bare form. Returns "", false for type families that store/render
+// bare (FLOAT, DOUBLE, JSON, DATE, …).
+//
+// This centralizes the "what does MySQL canonicalize?" knowledge in
+// one place. Adding a new family is a single switch entry rather
+// than: one normalize entry per type-modifier combination.
+func canonicalBareTypeForm(lower string) (string, bool) {
+ switch lower {
+ case "decimal", "numeric", "fixed":
+ return "decimal(10,0)", true
+ case "tinyint":
+ return "tinyint(4)", true
+ case "smallint":
+ return "smallint(6)", true
+ case "mediumint":
+ return "mediumint(9)", true
+ case "int", "integer":
+ return "int(11)", true
+ case "bigint":
+ return "bigint(20)", true
+ case "bit":
+ return "bit(1)", true
+ case "binary":
+ return "binary(1)", true
+ case "year":
+ return "year(4)", true
+ case "boolean", "bool":
+ // BOOLEAN is a TINYINT(1) alias; UNSIGNED/ZEROFILL append
+ // to "tinyint(1)" if syntactically present (e.g. malformed
+ // SQL like `BOOLEAN UNSIGNED`) — matches pingcap rendering.
+ return "tinyint(1)", true
+ default:
+ return "", false
+ }
}
-// Enter implements the ast.Visitor interface.
-func (checker *columnDisallowChangingTypeChecker) Enter(in ast.Node) (ast.Node, bool) {
- changeType := false
- if node, ok := in.(*ast.AlterTableStmt); ok {
- for _, spec := range node.Specs {
- switch spec.Tp {
- case ast.AlterTableChangeColumn:
- changeType = checker.changeColumnType(node.Table.Name.O, spec.OldColumnName.Name.O, spec.NewColumns[0].Tp.String())
- case ast.AlterTableModifyColumn:
- changeType = checker.changeColumnType(node.Table.Name.O, spec.NewColumns[0].Name.Name.O, spec.NewColumns[0].Tp.String())
- default:
- // Skip other alter table specification types
- }
- if changeType {
- break
- }
- }
+// isExactDecimalTypeName returns true for column types whose canonical
+// MySQL rendering always carries an explicit scale, even when zero.
+// Pingcap's `Tp.String()` canonicalizes `DECIMAL(M)` → `decimal(M,0)`;
+// MySQL info_schema does the same.
+func isExactDecimalTypeName(lower string) bool {
+ switch lower {
+ case "decimal", "numeric", "fixed":
+ return true
+ default:
+ return false
}
+}
- if changeType {
- checker.adviceList = append(checker.adviceList, &storepb.Advice{
- Status: checker.level,
- Code: code.ChangeColumnType.Int32(),
- Title: checker.title,
- Content: fmt.Sprintf("\"%s\" changes column type", checker.text),
- StartPosition: common.ConvertANTLRLineToPosition(checker.line),
- })
+// isApproximateFloatTypeName returns true for column types whose
+// canonical MySQL rendering drops the precision hint when scale is
+// not explicitly given. Pingcap's `Tp.String()` returns `"float"` for
+// `FLOAT(10)` and `"float"` for `FLOAT(10,0)` — only `FLOAT(M,D)`
+// with D > 0 renders as `float(M,D)`. Same applies to DOUBLE and
+// REAL (REAL is an alias for DOUBLE in pingcap + MySQL).
+func isApproximateFloatTypeName(lower string) bool {
+ switch lower {
+ case "float", "double", "real":
+ return true
+ default:
+ return false
}
+}
- return in, false
+// isEnumOrSetTypeName returns true for the ENUM and SET pseudo-types
+// whose canonical rendering carries a value list rather than a length
+// or scale.
+func isEnumOrSetTypeName(lower string) bool {
+ return lower == "enum" || lower == "set"
}
-// Leave implements the ast.Visitor interface.
-func (*columnDisallowChangingTypeChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
+// formatEnumValueList renders an ENUM / SET value list in pingcap's
+// `'v1','v2',…` canonical form: each value SQL-escaped (single quotes
+// doubled) and wrapped in single quotes, comma-separated with no
+// spaces. Matches pingcap's `Tp.String()` output for ENUM/SET as well
+// as MySQL info_schema's COLUMN_TYPE rendering.
+func formatEnumValueList(values []string) string {
+ if len(values) == 0 {
+ return ""
+ }
+ parts := make([]string, len(values))
+ for i, v := range values {
+ parts[i] = "'" + strings.ReplaceAll(v, "'", "''") + "'"
+ }
+ return strings.Join(parts, ",")
}
+// normalizeColumnType canonicalizes type-name forms so that
+// equivalent renderings on either side of the comparison
+// (omni-built new type vs catalog-stored existing type) match.
+// Two classes of normalization:
+//
+// - **Integer default-length**: bare `int` ↔ `int(11)`, `tinyint`
+// ↔ `tinyint(4)`, etc. Pingcap's `Tp.String()` always rendered
+// the default display width; catalog stores it too. The omni
+// port may emit either form depending on whether the user
+// specified a length.
+//
+// - **Alias normalization**: `boolean` ↔ `tinyint(1)`. Omni
+// preserves `DataType.Name = "BOOLEAN"` from the user's
+// literal source; pingcap and MySQL info_schema both
+// canonicalize boolean columns to `tinyint(1)` (verified via
+// `backend/plugin/schema/{tidb,mysql}/get_database_metadata.go`
+// and pingcap's Tp.String() for BOOLEAN columns). Without
+// this entry, no-op `MODIFY x BOOLEAN` on a tinyint(1)
+// column would false-positive (Codex round-5 catch).
+//
+// Kept structurally aligned with the mysql analog + pingcap-typed
+// predecessor for fixture parity.
func normalizeColumnType(tp string) string {
switch strings.ToLower(tp) {
+ case "boolean", "bool":
+ // MySQL canonicalizes BOOL/BOOLEAN to tinyint(1). Both
+ // pingcap rendering and INFORMATION_SCHEMA agree.
+ return "tinyint(1)"
+ case "decimal", "numeric", "fixed":
+ // MySQL applies default precision (10) and scale (0) when
+ // user writes bare DECIMAL (or its NUMERIC / FIXED aliases).
+ // Pingcap's Tp.String() and INFORMATION_SCHEMA both
+ // canonicalize the bare form to decimal(10,0). The
+ // omniBuildColumnTypeString builder renders the bare form
+ // when Length=0 because there's no length to render;
+ // catch the canonicalization here.
+ return "decimal(10,0)"
+ case "bit":
+ // Pre-merge round-7 risk check surfaced this: MySQL's
+ // default BIT precision is 1, pingcap renders `BIT` as
+ // `bit(1)`, INFORMATION_SCHEMA stores `bit(1)`.
+ return "bit(1)"
+ case "binary":
+ // Pre-merge round-7 risk check surfaced this: MySQL's
+ // default BINARY length is 1, pingcap renders bare BINARY
+ // as `binary(1)`, INFORMATION_SCHEMA stores `binary(1)`.
+ return "binary(1)"
+ case "year":
+ // Pre-merge round-7 risk check surfaced this: MySQL's
+ // default YEAR display width is 4 (legacy; YEAR(2) was
+ // deprecated then removed). Pingcap renders bare YEAR as
+ // `year(-1)` (an internal sentinel for "no width specified"
+ // — a pingcap-side artifact); INFORMATION_SCHEMA stores
+ // `year(4)`. Canonicalize bare year to year(4) to match the
+ // catalog form.
+ return "year(4)"
case "tinyint":
return "tinyint(4)"
case "tinyint unsigned":
@@ -129,12 +386,3 @@ func normalizeColumnType(tp string) string {
return strings.ToLower(tp)
}
}
-
-func (checker *columnDisallowChangingTypeChecker) changeColumnType(tableName string, columName string, newType string) bool {
- column := checker.originalMetadata.GetSchemaMetadata("").GetTable(tableName).GetColumn(columName)
- if column == nil {
- return false
- }
-
- return normalizeColumnType(column.GetProto().Type) != normalizeColumnType(newType)
-}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type_test.go b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type_test.go
new file mode 100644
index 0000000000..342cbb9a97
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type_test.go
@@ -0,0 +1,240 @@
+package tidb
+
+// Pure-function unit tests for omniBuildColumnTypeString +
+// normalizeColumnType. Each case locks one of the empirical
+// receipts from a Codex review round on PR #20302 so future
+// changes to the type-string rendering path have a CI guard
+// against re-introducing the same class of bug.
+//
+// These tests bypass the advisor / catalog framework entirely —
+// they exercise the pure (DataType, alias) → string transforms
+// directly. No shared-mock-catalog cross-engine impact concern.
+
+import (
+ "testing"
+
+ "github.com/bytebase/omni/tidb/ast"
+)
+
+func TestOmniBuildColumnTypeString(t *testing.T) {
+ cases := []struct {
+ name string
+ dt *ast.DataType
+ want string
+ }{
+ // Round 1 / cumulative #21: BLOB-family renders without
+ // pingcap's accidental " BINARY" charset suffix.
+ {"BLOB", &ast.DataType{Name: "BLOB"}, "blob"},
+ {"TINYBLOB", &ast.DataType{Name: "TINYBLOB"}, "tinyblob"},
+ {"MEDIUMBLOB", &ast.DataType{Name: "MEDIUMBLOB"}, "mediumblob"},
+ {"LONGBLOB", &ast.DataType{Name: "LONGBLOB"}, "longblob"},
+ {"TEXT", &ast.DataType{Name: "TEXT"}, "text"},
+ // Round 2: exact-decimal types always render (M,D), Scale=0
+ // when not explicitly given.
+ {"DECIMAL(10)", &ast.DataType{Name: "DECIMAL", Length: 10}, "decimal(10,0)"},
+ {"DECIMAL(10,0)", &ast.DataType{Name: "DECIMAL", Length: 10, Scale: 0}, "decimal(10,0)"},
+ {"DECIMAL(10,2)", &ast.DataType{Name: "DECIMAL", Length: 10, Scale: 2}, "decimal(10,2)"},
+ // Round 9: NUMERIC/FIXED aliases canonicalize to "decimal" in
+ // the rendered form. Omni pre-normalizes FIXED→DECIMAL but NOT
+ // NUMERIC→DECIMAL, so the builder canonicalizes for both.
+ {"NUMERIC(8)", &ast.DataType{Name: "NUMERIC", Length: 8}, "decimal(8,0)"},
+ {"NUMERIC(8,2)", &ast.DataType{Name: "NUMERIC", Length: 8, Scale: 2}, "decimal(8,2)"},
+ {"FIXED(8,2)-defensive", &ast.DataType{Name: "FIXED", Length: 8, Scale: 2}, "decimal(8,2)"},
+ {"NUMERIC(10,2)-UNSIGNED", &ast.DataType{Name: "NUMERIC", Length: 10, Scale: 2, Unsigned: true}, "decimal(10,2) unsigned"},
+ // Round 2: ZEROFILL implies UNSIGNED + appends zerofill.
+ // Note: round-8 fix updated bare INT ZEROFILL from "int unsigned zerofill"
+ // (the original round-2 output, which mismatched catalog) to the
+ // canonical "int(11) unsigned zerofill" form that catalog stores.
+ {"INT(11)-ZEROFILL", &ast.DataType{Name: "INT", Length: 11, Zerofill: true}, "int(11) unsigned zerofill"},
+ // Round 3: FLOAT/DOUBLE/REAL drop precision hint when no
+ // explicit scale; render (M,D) only when Scale > 0.
+ {"FLOAT", &ast.DataType{Name: "FLOAT"}, "float"},
+ {"FLOAT(10)", &ast.DataType{Name: "FLOAT", Length: 10}, "float"},
+ {"FLOAT(10,0)", &ast.DataType{Name: "FLOAT", Length: 10, Scale: 0}, "float"},
+ {"FLOAT(10,2)", &ast.DataType{Name: "FLOAT", Length: 10, Scale: 2}, "float(10,2)"},
+ {"DOUBLE(10,4)", &ast.DataType{Name: "DOUBLE", Length: 10, Scale: 4}, "double(10,4)"},
+ {"REAL", &ast.DataType{Name: "REAL"}, "real"},
+ // Round 4: ENUM/SET render their value list with SQL
+ // single-quote escaping; length/scale/unsigned attributes
+ // don't apply.
+ {"ENUM-2", &ast.DataType{Name: "ENUM", EnumValues: []string{"a", "b"}}, "enum('a','b')"},
+ {"ENUM-3", &ast.DataType{Name: "ENUM", EnumValues: []string{"x", "y", "z"}}, "enum('x','y','z')"},
+ {"SET-3", &ast.DataType{Name: "SET", EnumValues: []string{"a", "b", "c"}}, "set('a','b','c')"},
+ {"ENUM-escape", &ast.DataType{Name: "ENUM", EnumValues: []string{"with'quote"}}, "enum('with''quote')"},
+ // Rounds 5, 6, 7, 8 — the builder now applies MySQL canonical
+ // default forms for type families whose info_schema rendering
+ // carries explicit length/precision. Previously these were
+ // emitted bare and relied on normalizeColumnType; now the
+ // builder produces the canonical form directly so that the
+ // bare-form × modifier (UNSIGNED/ZEROFILL) Cartesian product
+ // composes without combinatorial normalize-map entries.
+ {"BOOLEAN", &ast.DataType{Name: "BOOLEAN"}, "tinyint(1)"},
+ {"DECIMAL-bare", &ast.DataType{Name: "DECIMAL"}, "decimal(10,0)"},
+ {"NUMERIC-bare", &ast.DataType{Name: "NUMERIC"}, "decimal(10,0)"},
+ {"BIT-bare", &ast.DataType{Name: "BIT"}, "bit(1)"},
+ {"BINARY-bare", &ast.DataType{Name: "BINARY"}, "binary(1)"},
+ {"YEAR-bare", &ast.DataType{Name: "YEAR"}, "year(4)"},
+ {"INT-bare", &ast.DataType{Name: "INT"}, "int(11)"},
+ {"TINYINT-bare", &ast.DataType{Name: "TINYINT"}, "tinyint(4)"},
+ {"BIGINT-bare", &ast.DataType{Name: "BIGINT"}, "bigint(20)"},
+ // Round 8 / peer-review-prompted: bare-form × modifier
+ // combinations. Pre-fix these emitted "decimal unsigned" /
+ // "int unsigned zerofill" (bare base + suffix); now emit
+ // the canonical-base + suffix forms that match what pingcap
+ // Tp.String() and info_schema render.
+ {"DECIMAL-bare-UNSIGNED", &ast.DataType{Name: "DECIMAL", Unsigned: true}, "decimal(10,0) unsigned"},
+ {"DECIMAL-bare-ZEROFILL", &ast.DataType{Name: "DECIMAL", Zerofill: true}, "decimal(10,0) unsigned zerofill"},
+ {"DECIMAL-bare-UNSIGNED-ZEROFILL", &ast.DataType{Name: "DECIMAL", Unsigned: true, Zerofill: true}, "decimal(10,0) unsigned zerofill"},
+ {"NUMERIC-bare-UNSIGNED", &ast.DataType{Name: "NUMERIC", Unsigned: true}, "decimal(10,0) unsigned"},
+ {"INT-bare-ZEROFILL", &ast.DataType{Name: "INT", Zerofill: true}, "int(11) unsigned zerofill"},
+ {"INT-bare-UNSIGNED-ZEROFILL", &ast.DataType{Name: "INT", Unsigned: true, Zerofill: true}, "int(11) unsigned zerofill"},
+ {"TINYINT-bare-ZEROFILL", &ast.DataType{Name: "TINYINT", Zerofill: true}, "tinyint(4) unsigned zerofill"},
+ {"SMALLINT-bare-ZEROFILL", &ast.DataType{Name: "SMALLINT", Zerofill: true}, "smallint(6) unsigned zerofill"},
+ {"MEDIUMINT-bare-ZEROFILL", &ast.DataType{Name: "MEDIUMINT", Zerofill: true}, "mediumint(9) unsigned zerofill"},
+ {"BIGINT-bare-ZEROFILL", &ast.DataType{Name: "BIGINT", Zerofill: true}, "bigint(20) unsigned zerofill"},
+ {"INT-bare-UNSIGNED", &ast.DataType{Name: "INT", Unsigned: true}, "int(11) unsigned"},
+ {"BIGINT-bare-UNSIGNED", &ast.DataType{Name: "BIGINT", Unsigned: true}, "bigint(20) unsigned"},
+ // FLOAT/DOUBLE/REAL with bare-form + modifier: float-family
+ // does NOT apply default precision, so bare → "float unsigned"
+ // (matches pingcap's precision-hint-drop behavior even with
+ // modifiers).
+ {"FLOAT-bare-UNSIGNED", &ast.DataType{Name: "FLOAT", Unsigned: true}, "float unsigned"},
+ {"DOUBLE-bare-UNSIGNED", &ast.DataType{Name: "DOUBLE", Unsigned: true}, "double unsigned"},
+ // Regular cases that should "just work".
+ {"VARCHAR(255)", &ast.DataType{Name: "VARCHAR", Length: 255}, "varchar(255)"},
+ {"CHAR(10)", &ast.DataType{Name: "CHAR", Length: 10}, "char(10)"},
+ {"TIMESTAMP(3)", &ast.DataType{Name: "TIMESTAMP", Length: 3}, "timestamp(3)"},
+ {"DATETIME", &ast.DataType{Name: "DATETIME"}, "datetime"},
+ {"JSON", &ast.DataType{Name: "JSON"}, "json"},
+ {"INT(11)-UNSIGNED", &ast.DataType{Name: "INT", Length: 11, Unsigned: true}, "int(11) unsigned"},
+ {"nil", nil, ""},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := omniBuildColumnTypeString(tc.dt)
+ if got != tc.want {
+ t.Errorf("omniBuildColumnTypeString = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestNormalizeColumnType(t *testing.T) {
+ cases := []struct {
+ name string
+ in string
+ want string
+ }{
+ // Round 5: BOOLEAN ↔ tinyint(1) canonicalization (MySQL
+ // stores boolean columns as tinyint(1)).
+ {"BOOLEAN", "boolean", "tinyint(1)"},
+ {"BOOL", "bool", "tinyint(1)"},
+ {"tinyint(1) identity", "tinyint(1)", "tinyint(1)"},
+ // Round 6: bare DECIMAL/NUMERIC/FIXED → decimal(10,0)
+ // canonicalization (MySQL default precision/scale).
+ {"bare decimal", "decimal", "decimal(10,0)"},
+ {"bare numeric", "numeric", "decimal(10,0)"},
+ {"bare fixed", "fixed", "decimal(10,0)"},
+ // Round 7: bare BIT/BINARY/YEAR → default-form
+ // canonicalization (MySQL defaults match info_schema).
+ {"bare bit", "bit", "bit(1)"},
+ {"bare binary", "binary", "binary(1)"},
+ {"bare year", "year", "year(4)"},
+ // Pre-existing: integer default display widths.
+ {"bare tinyint", "tinyint", "tinyint(4)"},
+ {"bare smallint", "smallint", "smallint(6)"},
+ {"bare mediumint", "mediumint", "mediumint(9)"},
+ {"bare int", "int", "int(11)"},
+ {"bare bigint", "bigint", "bigint(20)"},
+ {"int unsigned", "int unsigned", "int(11) unsigned"},
+ {"bigint unsigned", "bigint unsigned", "bigint(20) unsigned"},
+ // Default branch: identity-lowercase.
+ {"varchar(255) identity", "varchar(255)", "varchar(255)"},
+ {"already-canonical decimal", "decimal(10,2)", "decimal(10,2)"},
+ {"empty string", "", ""},
+ {"uppercase input", "VARCHAR(255)", "varchar(255)"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := normalizeColumnType(tc.in)
+ if got != tc.want {
+ t.Errorf("normalizeColumnType(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestTypeStringRoundTripAgainstNormalize asserts that for the
+// no-op type-change scenarios across all six Codex rounds + the
+// round-7 risk check, normalizeColumnType applied to (a) the
+// catalog-side rendering and (b) the omni-built rendering produces
+// matching strings. This is the load-bearing invariant for the
+// columnTypeChanged comparison — if the two normalize calls ever
+// produce different strings for the same logical column type, the
+// rule will false-positive.
+func TestTypeStringRoundTripAgainstNormalize(t *testing.T) {
+ cases := []struct {
+ name string
+ omniDT *ast.DataType
+ catalogStored string // what MySQL info_schema returns
+ shouldNoChange bool // true when this is a no-op-modify scenario
+ }{
+ // All six Codex rounds + round-7 fixes — the load-bearing
+ // invariant: normalize(omni-built) == normalize(catalog).
+ {"BLOB", &ast.DataType{Name: "BLOB"}, "blob", true},
+ {"TINYBLOB", &ast.DataType{Name: "TINYBLOB"}, "tinyblob", true},
+ {"VARBINARY(100)", &ast.DataType{Name: "VARBINARY", Length: 100}, "varbinary(100)", true},
+ {"DECIMAL(10)", &ast.DataType{Name: "DECIMAL", Length: 10}, "decimal(10,0)", true},
+ {"DECIMAL(10,0)", &ast.DataType{Name: "DECIMAL", Length: 10, Scale: 0}, "decimal(10,0)", true},
+ {"FLOAT", &ast.DataType{Name: "FLOAT"}, "float", true},
+ {"FLOAT(10)", &ast.DataType{Name: "FLOAT", Length: 10}, "float", true},
+ {"FLOAT(10,2)", &ast.DataType{Name: "FLOAT", Length: 10, Scale: 2}, "float(10,2)", true},
+ {"DOUBLE(10,4)", &ast.DataType{Name: "DOUBLE", Length: 10, Scale: 4}, "double(10,4)", true},
+ {"ENUM-2", &ast.DataType{Name: "ENUM", EnumValues: []string{"a", "b"}}, "enum('a','b')", true},
+ {"SET-3", &ast.DataType{Name: "SET", EnumValues: []string{"x", "y", "z"}}, "set('x','y','z')", true},
+ {"BOOLEAN", &ast.DataType{Name: "BOOLEAN"}, "tinyint(1)", true},
+ {"BOOL", &ast.DataType{Name: "BOOLEAN"}, "tinyint(1)", true},
+ {"bare DECIMAL", &ast.DataType{Name: "DECIMAL"}, "decimal(10,0)", true},
+ {"bare NUMERIC", &ast.DataType{Name: "NUMERIC"}, "decimal(10,0)", true},
+ {"bare BIT", &ast.DataType{Name: "BIT"}, "bit(1)", true},
+ {"bare BINARY", &ast.DataType{Name: "BINARY"}, "binary(1)", true},
+ {"bare YEAR", &ast.DataType{Name: "YEAR"}, "year(4)", true},
+ // Regular pass-through cases.
+ {"bare INT", &ast.DataType{Name: "INT"}, "int(11)", true},
+ {"INT(11)", &ast.DataType{Name: "INT", Length: 11}, "int(11)", true},
+ {"bare TINYINT", &ast.DataType{Name: "TINYINT"}, "tinyint(4)", true},
+ {"VARCHAR(255)", &ast.DataType{Name: "VARCHAR", Length: 255}, "varchar(255)", true},
+ // Round 8: bare-form × modifier no-op-modify scenarios.
+ // Catalog stores the canonical form (default precision +
+ // UNSIGNED [+ ZEROFILL]); builder now produces matching form.
+ {"DECIMAL UNSIGNED no-op", &ast.DataType{Name: "DECIMAL", Unsigned: true}, "decimal(10,0) unsigned", true},
+ // Round 9: NUMERIC alias no-op against catalog stored as decimal.
+ {"NUMERIC(8,2) no-op (catalog decimal)", &ast.DataType{Name: "NUMERIC", Length: 8, Scale: 2}, "decimal(8,2)", true},
+ {"NUMERIC bare no-op (catalog decimal)", &ast.DataType{Name: "NUMERIC"}, "decimal(10,0)", true},
+ {"DECIMAL ZEROFILL no-op", &ast.DataType{Name: "DECIMAL", Zerofill: true}, "decimal(10,0) unsigned zerofill", true},
+ {"INT ZEROFILL no-op", &ast.DataType{Name: "INT", Zerofill: true}, "int(11) unsigned zerofill", true},
+ {"TINYINT ZEROFILL no-op", &ast.DataType{Name: "TINYINT", Zerofill: true}, "tinyint(4) unsigned zerofill", true},
+ {"INT UNSIGNED no-op", &ast.DataType{Name: "INT", Unsigned: true}, "int(11) unsigned", true},
+ {"BIGINT UNSIGNED no-op", &ast.DataType{Name: "BIGINT", Unsigned: true}, "bigint(20) unsigned", true},
+ // Negative case: actual type change. Normalize should NOT
+ // produce matching strings.
+ {"INT → BIGINT", &ast.DataType{Name: "BIGINT"}, "int(11)", false},
+ {"VARCHAR(50) → VARCHAR(255)", &ast.DataType{Name: "VARCHAR", Length: 255}, "varchar(50)", false},
+ {"DECIMAL(10,2) → DECIMAL(10,4)", &ast.DataType{Name: "DECIMAL", Length: 10, Scale: 4}, "decimal(10,2)", false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ omniBuilt := omniBuildColumnTypeString(tc.omniDT)
+ omniNorm := normalizeColumnType(omniBuilt)
+ catalogNorm := normalizeColumnType(tc.catalogStored)
+ matched := omniNorm == catalogNorm
+ if matched != tc.shouldNoChange {
+ t.Errorf("normalize match = %v, want %v (omni-built=%q normalized=%q vs catalog=%q normalized=%q)",
+ matched, tc.shouldNoChange, omniBuilt, omniNorm, tc.catalogStored, catalogNorm)
+ }
+ })
+ }
+}
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_change.yaml b/backend/plugin/advisor/tidb/test/column_disallow_change.yaml
index d2826aeb62..a08210991b 100644
--- a/backend/plugin/advisor/tidb/test/column_disallow_change.yaml
+++ b/backend/plugin/advisor/tidb/test/column_disallow_change.yaml
@@ -15,3 +15,21 @@
line: 2
column: 0
endposition: null
+# Single-advice-per-statement cardinality pin (batch 11): pingcap-tidb's
+# Visitor broke after the first CHANGE COLUMN match. Multiple CHANGE
+# COLUMN specs in one ALTER TABLE produce ONE advice, not N. (Mysql
+# analog emits per-cmd — cardinality divergence preserved on the tidb
+# side per invariant #7's "preserve pingcap behavior" rule.)
+- statement: |-
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t CHANGE COLUMN a c int, CHANGE COLUMN b d int;
+ changeType: 1
+ want:
+ - status: 2
+ code: 406
+ title: COLUMN_DISALLOW_CHANGE
+ content: '"ALTER TABLE t CHANGE COLUMN a c int, CHANGE COLUMN b d int;" contains CHANGE COLUMN statement'
+ startposition:
+ line: 2
+ column: 0
+ endposition: null
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_change_type.yaml b/backend/plugin/advisor/tidb/test/column_disallow_change_type.yaml
index 45b87eacc6..827b0914b6 100644
--- a/backend/plugin/advisor/tidb/test/column_disallow_change_type.yaml
+++ b/backend/plugin/advisor/tidb/test/column_disallow_change_type.yaml
@@ -33,3 +33,28 @@
line: 1
column: 0
endposition: null
+# Single-advice-per-statement cardinality pin (batch 11): multiple
+# type-changing specs in one ALTER TABLE produce ONE advice (pingcap-tidb
+# broke after first match). Mysql analog emits per-cmd — cardinality
+# divergence preserved on the tidb side per invariant #7.
+- statement: ALTER TABLE tech_book MODIFY id bigint, MODIFY name varchar(20)
+ changeType: 1
+ want:
+ - status: 2
+ code: 403
+ title: COLUMN_DISALLOW_CHANGE_TYPE
+ content: '"ALTER TABLE tech_book MODIFY id bigint, MODIFY name varchar(20)" changes column type'
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+# No-op type-change baseline pin (batch 11 / cumulative #21 conceptual):
+# `MODIFY id int` on an `int` column is a no-op — no advice. Catalog
+# stores type as the bare canonical form ("int"); omni renders the new
+# type the same way; normalizeColumnType canonicalizes both to "int(11)";
+# strings match → no flag. This test was passing pre-migration too
+# (already in fixture above); included here adjacent to the cumulative
+# #21 comment for context. The BLOB/TINYBLOB/VARBINARY "BINARY"-suffix
+# false-positive fix is documented conceptually in plan-doc cumulative
+# #21 — not pinned via fixture because tech_book's mock catalog doesn't
+# carry BLOB columns and adding one would have cross-engine impact.
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml b/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml
index 711cd57bae..f65deda21a 100644
--- a/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml
+++ b/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml
@@ -54,3 +54,20 @@
line: 2
column: 0
endposition: null
+# Single-advice-per-statement cardinality pin (batch 11): multiple
+# position-changing specs in one ALTER TABLE produce ONE advice
+# (pingcap-tidb broke after first match). Mysql analog emits per-cmd —
+# cardinality divergence preserved on the tidb side per invariant #7.
+- statement: |-
+ CREATE TABLE t(a int, b int, c int);
+ ALTER TABLE t MODIFY COLUMN a int FIRST, MODIFY COLUMN b int AFTER c;
+ changeType: 1
+ want:
+ - status: 2
+ code: 407
+ title: COLUMN_DISALLOW_CHANGING_ORDER
+ content: '"ALTER TABLE t MODIFY COLUMN a int FIRST, MODIFY COLUMN b int AFTER c;" changes column order'
+ startposition:
+ line: 2
+ column: 0
+ endposition: null
diff --git a/backend/plugin/advisor/tidb/utils.go b/backend/plugin/advisor/tidb/utils.go
index 3fb8737b82..28aceb8109 100644
--- a/backend/plugin/advisor/tidb/utils.go
+++ b/backend/plugin/advisor/tidb/utils.go
@@ -325,6 +325,29 @@ func collectColumnViolations(ostmt OmniStmt, isViolation func(*omniast.ColumnDef
return cols
}
+// firstAlterCommandMatching returns the index of the first AlterTableCmd
+// in n.Commands satisfying matcher, or -1 if none match. Used by ALTER-
+// TABLE-only advisors that emit a single advice per statement
+// (cardinality-1) on the first triggering command — `disallow_changing`
+// and `disallow_changing_order` share this exact shape.
+//
+// Returns -1 when n is nil, n.Commands is empty, or matcher returns
+// false for every non-nil command.
+func firstAlterCommandMatching(n *omniast.AlterTableStmt, matcher func(*omniast.AlterTableCmd) bool) int {
+ if n == nil || matcher == nil {
+ return -1
+ }
+ for i, cmd := range n.Commands {
+ if cmd == nil {
+ continue
+ }
+ if matcher(cmd) {
+ return i
+ }
+ }
+ return -1
+}
+
// 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`