Skip to content

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

chore(sql-review): delete MySQL column-exists advisor (#2718)

rebelice96f9fe25dd11
diff --git a/plugin/advisor/catalog/walk_through.go b/plugin/advisor/catalog/walk_through.go
index d7df7c59fe..b4fdcd5815 100644
--- a/plugin/advisor/catalog/walk_through.go
+++ b/plugin/advisor/catalog/walk_through.go
@@ -165,6 +165,14 @@ func (d *databaseState) WalkThrough(stmts string) error {
}
for _, node := range nodeList {
+ // validate DML
+ if dml, ok := node.(tidbast.DMLNode); ok {
+ if err := d.validateDML(dml); err != nil {
+ return err
+ }
+ continue
+ }
+ // change state
if err := d.changeState(node); err != nil {
return err
}
@@ -173,6 +181,30 @@ func (d *databaseState) WalkThrough(stmts string) error {
return nil
}
+func (d *databaseState) validateDML(in tidbast.DMLNode) (err *WalkThroughError) {
+ defer func() {
+ if err == nil {
+ return
+ }
+ if err.Line == 0 {
+ err.Line = in.OriginTextPosition()
+ }
+ }()
+ if d.deleted {
+ return &WalkThroughError{
+ Type: ErrorTypeDatabaseIsDeleted,
+ Content: fmt.Sprintf("Database `%s` is deleted", d.name),
+ }
+ }
+
+ switch node := in.(type) {
+ case *tidbast.InsertStmt:
+ return d.checkInsert(node)
+ default:
+ return nil
+ }
+}
+
func (d *databaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError) {
defer func() {
if err == nil {
@@ -212,6 +244,25 @@ func (d *databaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError)
}
}
+func (d *databaseState) checkInsert(node *tidbast.InsertStmt) *WalkThroughError {
+ tableName, ok := getTableSourceName(node.Table)
+ if ok {
+ table, err := d.findTableState(tableName)
+ if err != nil {
+ return err
+ }
+ if table == nil {
+ return nil
+ }
+ for _, col := range node.Columns {
+ if _, exists := table.columnSet[col.Name.O]; !exists {
+ return NewColumnNotExistsError(table.name, col.Name.O)
+ }
+ }
+ }
+ return nil
+}
+
func (d *databaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughError {
for _, tableToTable := range node.TableToTables {
schema, exists := d.schemaSet[""]
@@ -1063,6 +1114,7 @@ func (d *databaseState) parse(stmts string) ([]tidbast.StmtNode, *WalkThroughErr
}
for i, node := range nodeList {
+ node.SetText(nil, strings.TrimSpace(node.Text()))
node.SetOriginTextPosition(sqlList[i].Line)
if n, ok := node.(*tidbast.CreateTableStmt); ok {
if err := parser.SetLineForMySQLCreateTableStmt(n); err != nil {
@@ -1097,3 +1149,15 @@ func getIndexType(option *tidbast.IndexOption) string {
}
return model.IndexTypeBtree.String()
}
+
+func getTableSourceName(table *tidbast.TableRefsClause) (*tidbast.TableName, bool) {
+ source, isTableSource := table.TableRefs.Left.(*tidbast.TableSource)
+ nilRight := table.TableRefs.Right == nil
+ if isTableSource && nilRight {
+ // isTableSource and nilRight mean it's a table.
+ if tableName, ok := source.Source.(*tidbast.TableName); ok {
+ return tableName, true
+ }
+ }
+ return nil, false
+}
diff --git a/plugin/advisor/catalog/walk_through_test.go b/plugin/advisor/catalog/walk_through_test.go
index 5224fa6eb1..ea9dea0a68 100644
--- a/plugin/advisor/catalog/walk_through_test.go
+++ b/plugin/advisor/catalog/walk_through_test.go
@@ -23,6 +23,141 @@ var (
func TestWalkThrough(t *testing.T) {
tests := []testData{
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ INSERT INTO test values (1);
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeTableNotExists,
+ Content: "Table `test` does not exist",
+ Line: 2,
+ },
+ },
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ INSERT INTO t(a, b, c, d) values (1, 2, 3, 4);
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ CREATE INDEX idx_c on t(c);
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t MODIFY COLUMN c int;
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t CHANGE COLUMN c aa int;
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t DROP COLUMN c;
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t RENAME COLUMN c TO cc;
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
+
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t RENAME COLUMN c TO cc;
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
+ {
+ origin: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ },
+ statement: `
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t ALTER COLUMN c DROP DEFAULT;
+ `,
+ err: &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: "Column `c` does not exist in table `t`",
+ Line: 3,
+ },
+ },
{
origin: &Database{
Name: "test",
@@ -834,15 +969,23 @@ func TestWalkThroughForNoCatalog(t *testing.T) {
DROP TABLE t1, t2
`,
want: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ SchemaList: []*Schema{{}},
+ },
+ },
+ {
+ origin: &Database{
Name: "test",
DbType: db.MySQL,
- SchemaList: []*Schema{
- {
- TableList: []*Table{},
- ViewList: []*View{},
- ExtensionList: []*Extension{},
- },
- },
+ },
+ statement: `
+ INSERT INTO test values (1);
+ `,
+ want: &Database{
+ Name: "test",
+ DbType: db.MySQL,
+ SchemaList: []*Schema{{}},
},
},
}
diff --git a/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go b/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go
index ffe34628d8..563461adff 100644
--- a/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go
+++ b/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go
@@ -68,6 +68,12 @@ type columnAutoIncrementMustIntegerChecker struct {
line int
}
+type columnData struct {
+ table string
+ column string
+ line int
+}
+
// Enter implements the ast.Visitor interface.
func (checker *columnAutoIncrementMustIntegerChecker) Enter(in ast.Node) (ast.Node, bool) {
var columnList []columnData
diff --git a/plugin/advisor/mysql/advisor_column_exists.go b/plugin/advisor/mysql/advisor_column_exists.go
deleted file mode 100644
index d798b098ed..0000000000
--- a/plugin/advisor/mysql/advisor_column_exists.go
+++ /dev/null
@@ -1,146 +0,0 @@
-package mysql
-
-// Framework code is generated by the generator.
-
-import (
- "fmt"
-
- "github.com/pingcap/tidb/parser/ast"
-
- "github.com/bytebase/bytebase/plugin/advisor"
- "github.com/bytebase/bytebase/plugin/advisor/catalog"
- "github.com/bytebase/bytebase/plugin/advisor/db"
-)
-
-var (
- _ advisor.Advisor = (*ColumnExistsAdvisor)(nil)
- _ ast.Visitor = (*columnExistsChecker)(nil)
-)
-
-func init() {
- advisor.Register(db.MySQL, advisor.MySQLColumnExists, &ColumnExistsAdvisor{})
- advisor.Register(db.TiDB, advisor.MySQLColumnExists, &ColumnExistsAdvisor{})
-}
-
-// ColumnExistsAdvisor is the advisor checking for column existence.
-type ColumnExistsAdvisor struct {
-}
-
-// Check checks for column existence.
-func (*ColumnExistsAdvisor) 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 := &columnExistsChecker{
- level: level,
- title: string(ctx.Rule.Type),
- catalog: ctx.Catalog,
- }
-
- for _, stmt := range stmtList {
- checker.text = stmt.Text()
- checker.line = stmt.OriginTextPosition()
- (stmt).Accept(checker)
- }
-
- if len(checker.adviceList) == 0 {
- checker.adviceList = append(checker.adviceList, advisor.Advice{
- Status: advisor.Success,
- Code: advisor.Ok,
- Title: "OK",
- Content: "",
- })
- }
- return checker.adviceList, nil
-}
-
-type columnExistsChecker struct {
- adviceList []advisor.Advice
- level advisor.Status
- title string
- text string
- line int
- catalog *catalog.Finder
-}
-
-type columnData struct {
- table string
- column string
- line int
-}
-
-// Enter implements the ast.Visitor interface.
-func (checker *columnExistsChecker) Enter(in ast.Node) (ast.Node, bool) {
- var columnList []columnData
- switch node := in.(type) {
- case *ast.InsertStmt:
- if table, ok := getInsertTableName(node.Table); ok {
- for _, column := range node.Columns {
- columnList = append(columnList, columnData{table: table, column: column.Name.O})
- }
- }
- case *ast.AlterTableStmt:
- table := node.Table.Name.O
- for _, spec := range node.Specs {
- switch spec.Tp {
- case ast.AlterTableAlterColumn:
- columnList = append(columnList, columnData{table: table, column: spec.NewColumns[0].Name.Name.O})
- case ast.AlterTableRenameColumn:
- columnList = append(columnList, columnData{table: table, column: spec.OldColumnName.Name.O})
- case ast.AlterTableChangeColumn, ast.AlterTableDropColumn:
- if !spec.IfExists {
- columnList = append(columnList, columnData{table: table, column: spec.OldColumnName.Name.O})
- }
- case ast.AlterTableModifyColumn:
- if !spec.IfExists {
- columnList = append(columnList, columnData{table: table, column: spec.NewColumns[0].Name.Name.O})
- }
- }
- }
- case *ast.CreateIndexStmt:
- for _, key := range node.IndexPartSpecifications {
- if key.Expr == nil {
- columnList = append(columnList, columnData{table: node.Table.Name.O, column: key.Column.Name.O})
- }
- }
- }
-
- for _, column := range columnList {
- table := checker.catalog.Origin.FindTable(&catalog.TableFind{TableName: column.table})
- if table == nil {
- continue
- }
-
- if !columnExists(table, column.column) {
- checker.adviceList = append(checker.adviceList, advisor.Advice{
- Status: checker.level,
- Code: advisor.ColumnNotExists,
- Title: checker.title,
- Content: fmt.Sprintf("Column `%s`.`%s` not exists, related statement: \"%s\"", column.table, column.column, checker.text),
- Line: checker.line,
- })
- }
- }
-
- return in, false
-}
-
-// Leave implements the ast.Visitor interface.
-func (*columnExistsChecker) Leave(in ast.Node) (ast.Node, bool) {
- return in, true
-}
-
-func columnExists(table *catalog.Table, column string) bool {
- for _, col := range table.ColumnList {
- if col.Name == column {
- return true
- }
- }
- return false
-}
diff --git a/plugin/advisor/mysql/advisor_column_exists_test.go b/plugin/advisor/mysql/advisor_column_exists_test.go
deleted file mode 100644
index 5907abc504..0000000000
--- a/plugin/advisor/mysql/advisor_column_exists_test.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package mysql
-
-// Framework code is generated by the generator.
-
-import (
- "testing"
-
- "github.com/bytebase/bytebase/plugin/advisor"
-)
-
-func TestColumnExists(t *testing.T) {
- tests := []advisor.TestCase{
- {
- Statement: `INSERT INTO t(a, b, c) values(1, 2, 3)`,
- Want: []advisor.Advice{
- {
- Status: advisor.Success,
- Code: advisor.Ok,
- Title: "OK",
- Content: "",
- },
- },
- },
- {
- Statement: `INSERT INTO tech_book(id, name) values(1, "book1")`,
- Want: []advisor.Advice{
- {
- Status: advisor.Success,
- Code: advisor.Ok,
- Title: "OK",
- Content: "",
- },
- },
- },
- {
- Statement: `INSERT INTO tech_book(aa, bb, cc) values(1, 2, 3)`,
- Want: []advisor.Advice{
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`aa` not exists, related statement: \"INSERT INTO tech_book(aa, bb, cc) values(1, 2, 3)\"",
- Line: 1,
- },
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`bb` not exists, related statement: \"INSERT INTO tech_book(aa, bb, cc) values(1, 2, 3)\"",
- Line: 1,
- },
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`cc` not exists, related statement: \"INSERT INTO tech_book(aa, bb, cc) values(1, 2, 3)\"",
- Line: 1,
- },
- },
- },
- {
- Statement: `ALTER TABLE tech_book ALTER COLUMN aa DROP DEFAULT`,
- Want: []advisor.Advice{
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`aa` not exists, related statement: \"ALTER TABLE tech_book ALTER COLUMN aa DROP DEFAULT\"",
- Line: 1,
- },
- },
- },
- {
- Statement: `ALTER TABLE tech_book RENAME COLUMN aa TO bb`,
- Want: []advisor.Advice{
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`aa` not exists, related statement: \"ALTER TABLE tech_book RENAME COLUMN aa TO bb\"",
- Line: 1,
- },
- },
- },
- {
- Statement: `ALTER TABLE tech_book CHANGE COLUMN aa bb int`,
- Want: []advisor.Advice{
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`aa` not exists, related statement: \"ALTER TABLE tech_book CHANGE COLUMN aa bb int\"",
- Line: 1,
- },
- },
- },
- {
- Statement: `ALTER TABLE tech_book DROP COLUMN aa`,
- Want: []advisor.Advice{
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`aa` not exists, related statement: \"ALTER TABLE tech_book DROP COLUMN aa\"",
- Line: 1,
- },
- },
- },
- {
- Statement: `ALTER TABLE tech_book MODIFY COLUMN aa int`,
- Want: []advisor.Advice{
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`aa` not exists, related statement: \"ALTER TABLE tech_book MODIFY COLUMN aa int\"",
- Line: 1,
- },
- },
- },
- {
- Statement: `CREATE INDEX idx_aa on tech_book(aa)`,
- Want: []advisor.Advice{
- {
- Status: advisor.Warn,
- Code: advisor.ColumnNotExists,
- Title: "column.exists",
- Content: "Column `tech_book`.`aa` not exists, related statement: \"CREATE INDEX idx_aa on tech_book(aa)\"",
- Line: 1,
- },
- },
- },
- }
-
- advisor.RunSQLReviewRuleTests(t, tests, &ColumnExistsAdvisor{}, &advisor.SQLReviewRule{
- Type: advisor.SchemaRuleColumnExists,
- Level: advisor.SchemaRuleLevelWarning,
- Payload: "",
- }, advisor.MockMySQLDatabase)
-}
diff --git a/tests/sql_review_test.go b/tests/sql_review_test.go
index 97088895c9..4857b83300 100644
--- a/tests/sql_review_test.go
+++ b/tests/sql_review_test.go
@@ -543,7 +543,24 @@ func TestSQLReviewForMySQL(t *testing.T) {
},
},
{
- statement: "INSERT INTO t_copy SELECT * FROM t",
+ statement: `
+ CREATE TABLE t(
+ id int NOT NULL,
+ creator_id INT NOT NULL,
+ created_ts TIMESTAMP NOT NULL,
+ updater_id INT NOT NULL,
+ updated_ts TIMESTAMP NOT NULL,
+ CONSTRAINT pk_user_id PRIMARY KEY (id)
+ );
+ CREATE TABLE t_copy(
+ id int NOT NULL,
+ creator_id INT NOT NULL,
+ created_ts TIMESTAMP NOT NULL,
+ updater_id INT NOT NULL,
+ updated_ts TIMESTAMP NOT NULL,
+ CONSTRAINT pk_user_id PRIMARY KEY (id)
+ );
+ INSERT INTO t_copy SELECT * FROM t`,
result: []api.TaskCheckResult{
{
Status: api.TaskCheckStatusError,
@@ -562,7 +579,16 @@ func TestSQLReviewForMySQL(t *testing.T) {
},
},
{
- statement: `INSERT INTO t VALUES (1), (2)`,
+ statement: `
+ CREATE TABLE t(
+ id int NOT NULL,
+ creator_id INT NOT NULL,
+ created_ts TIMESTAMP NOT NULL,
+ updater_id INT NOT NULL,
+ updated_ts TIMESTAMP NOT NULL,
+ CONSTRAINT pk_user_id PRIMARY KEY (id)
+ );
+ INSERT INTO t VALUES (1, 1, now(), 1, now())`,
result: []api.TaskCheckResult{
{
Status: api.TaskCheckStatusSuccess,