Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-review): implement MySQL column-exists rule (#2451)
rebelice080a40cb9a58
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 18ebb1beba..b273338ce0 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -91,6 +91,9 @@ const (// MySQLColumnSetDefaultForNotNull is an advisor type for MySQL set default value for not null column.MySQLColumnSetDefaultForNotNull Type = "bb.plugin.advisor.mysql.column.set-default-for-not-null"+ // MySQLColumnExists is an advisor type for MySQL column existence.+ MySQLColumnExists Type = "bb.plugin.advisor.mysql.column.exists"+// MySQLNoSelectAll is an advisor type for MySQL no select all.MySQLNoSelectAll Type = "bb.plugin.advisor.mysql.select.no-select-all"diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex 89da3ee9bc..44306ffd52 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -47,6 +47,7 @@ const (ColumnCanNotNull Code = 402ChangeColumnType Code = 403NotNullColumnWithNullDefault Code = 404+ ColumnNotExists Code = 405// 501 engine error code.NotInnoDBEngine Code = 501diff --git a/plugin/advisor/mysql/advisor_column_exists.go b/plugin/advisor/mysql/advisor_column_exists.gonew file mode 100644index 0000000000..c0ac865fcd--- /dev/null+++ b/plugin/advisor/mysql/advisor_column_exists.go@@ -0,0 +1,145 @@+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),+ database: ctx.Database,+ }++ 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+ database *catalog.Database+}++type columnData struct {+ table string+ column string+}++// 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.database.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.gonew file mode 100644index 0000000000..5907abc504--- /dev/null+++ b/plugin/advisor/mysql/advisor_column_exists_test.go@@ -0,0 +1,140 @@+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/plugin/advisor/mysql/advisor_table_exists.go b/plugin/advisor/mysql/advisor_table_exists.goindex b743eda4f8..6318c3b324 100644--- a/plugin/advisor/mysql/advisor_table_exists.go+++ b/plugin/advisor/mysql/advisor_table_exists.go@@ -74,12 +74,8 @@ func (checker *tableExistsChecker) Enter(in ast.Node) (ast.Node, bool) {var tableList []stringswitch node := in.(type) {case *ast.InsertStmt:- source, isTableSource := node.Table.TableRefs.Left.(*ast.TableSource)- nilRight := node.Table.TableRefs.Right == nil- if isTableSource && nilRight {- if tableName, ok := source.Source.(*ast.TableName); ok {- tableList = append(tableList, tableName.Name.O)- }+ if name, ok := getInsertTableName(node.Table); ok {+ tableList = append(tableList, name)}case *ast.AlterTableStmt:tableList = append(tableList, node.Table.Name.O)@@ -115,3 +111,14 @@ func sameDatabase(a string, b string) bool {}return a == b}++func getInsertTableName(table *ast.TableRefsClause) (string, bool) {+ source, isTableSource := table.TableRefs.Left.(*ast.TableSource)+ nilRight := table.TableRefs.Right == nil+ if isTableSource && nilRight {+ if tableName, ok := source.Source.(*ast.TableName); ok {+ return tableName.Name.O, true+ }+ }+ return "", false+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 004b687b6a..bfbc5f30f2 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -72,6 +72,8 @@ const (SchemaRuleColumnDisallowChangeType SQLReviewRuleType = "column.disallow-change-type"// SchemaRuleColumnSetDefaultForNotNull require the not null column to set default value.SchemaRuleColumnSetDefaultForNotNull SQLReviewRuleType = "column.set-default-for-not-null"+ // SchemaRuleColumnExists require the column existence.+ SchemaRuleColumnExists SQLReviewRuleType = "column.exists"// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.SchemaRuleSchemaBackwardCompatibility SQLReviewRuleType = "schema.backward-compatibility"@@ -415,6 +417,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLColumnSetDefaultForNotNull, nil}+ case SchemaRuleColumnExists:+ switch engine {+ case db.MySQL, db.TiDB:+ return MySQLColumnExists, nil+ }case SchemaRuleTableRequirePK:switch engine {case db.MySQL, db.TiDB: