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 table-exists rule (#2443)
rebelicea1440b483e93
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 6ceb3d026f..18ebb1beba 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -103,6 +103,9 @@ const (// MySQLTableDropNamingConvention is an advisor type for MySQL table drop with naming convention.MySQLTableDropNamingConvention Type = "bb.plugin.advisor.mysql.table.drop-naming-convention"+ // MySQLTableExists is an advisor type for MySQL table existence.+ MySQLTableExists Type = "bb.plugin.advisor.mysql.table.exists"+// MySQLDatabaseAllowDropIfEmpty is an advisor type for MySQL only allow drop empty database.MySQLDatabaseAllowDropIfEmpty Type = "bb.plugin.advisor.mysql.database.drop-empty-database"diff --git a/plugin/advisor/catalog/catalog.go b/plugin/advisor/catalog/catalog.goindex e5d8429ee9..d0c2a05b5d 100644--- a/plugin/advisor/catalog/catalog.go+++ b/plugin/advisor/catalog/catalog.go@@ -199,3 +199,24 @@ func (d *Database) FindColumn(find *ColumnFind) *Column {}return nil}++// TableFind is for find table.+type TableFind struct {+ SchemaName string+ TableName string+}++// FindTable finds the table.+func (d *Database) FindTable(find *TableFind) *Table {+ for _, schema := range d.SchemaList {+ if schema.Name != find.SchemaName {+ continue+ }+ for _, table := range schema.TableList {+ if table.Name == find.TableName {+ return table+ }+ }+ }+ return nil+}diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex f372327d06..89da3ee9bc 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -55,6 +55,7 @@ const (TableNoPK Code = 601TableHasFK Code = 602TableDropNamingConventionMismatch Code = 603+ TableNotExists Code = 604// 701 ~ 799 database advisor error code.DatabaseNotEmpty Code = 701diff --git a/plugin/advisor/mysql/advisor_table_exists.go b/plugin/advisor/mysql/advisor_table_exists.gonew file mode 100644index 0000000000..b743eda4f8--- /dev/null+++ b/plugin/advisor/mysql/advisor_table_exists.go@@ -0,0 +1,117 @@+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 = (*TableExistsAdvisor)(nil)+ _ ast.Visitor = (*tableExistsChecker)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLTableExists, &TableExistsAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLTableExists, &TableExistsAdvisor{})+}++// TableExistsAdvisor is the advisor checking for table existence..+type TableExistsAdvisor struct {+}++// Check checks for table existence..+func (*TableExistsAdvisor) 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 := &tableExistsChecker{+ 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 tableExistsChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ line int+ database *catalog.Database+}++// Enter implements the ast.Visitor interface.+func (checker *tableExistsChecker) Enter(in ast.Node) (ast.Node, bool) {+ var tableList []string+ switch 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)+ }+ }+ case *ast.AlterTableStmt:+ tableList = append(tableList, node.Table.Name.O)+ case *ast.CreateTableStmt:+ if node.ReferTable != nil && sameDatabase(node.ReferTable.Schema.O, checker.database.Name) {+ tableList = append(tableList, node.ReferTable.Name.O)+ }+ }++ for _, table := range tableList {+ if checker.database.FindTable(&catalog.TableFind{TableName: table}) == nil {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.TableNotExists,+ Title: checker.title,+ Content: fmt.Sprintf("Table `%s` not exists, related statement: \"%s\"", table, checker.text),+ Line: checker.line,+ })+ }+ }++ return in, false+}++// Leave implements the ast.Visitor interface.+func (*tableExistsChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++func sameDatabase(a string, b string) bool {+ if a == "" || b == "" {+ return true+ }+ return a == b+}diff --git a/plugin/advisor/mysql/advisor_table_exists_test.go b/plugin/advisor/mysql/advisor_table_exists_test.gonew file mode 100644index 0000000000..9a27af07be--- /dev/null+++ b/plugin/advisor/mysql/advisor_table_exists_test.go@@ -0,0 +1,111 @@+package mysql++// Framework code is generated by the generator.++import (+ "testing"++ "github.com/bytebase/bytebase/plugin/advisor"+)++func TestTableExists(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `INSERT INTO tech_book values (1)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `INSERT INTO t values (1)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.TableNotExists,+ Title: "table.exists",+ Content: "Table `t` not exists, related statement: \"INSERT INTO t values (1)\"",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE t ADD COLUMN a int`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.TableNotExists,+ Title: "table.exists",+ Content: "Table `t` not exists, related statement: \"ALTER TABLE t ADD COLUMN a int\"",+ Line: 1,+ },+ },+ },+ {+ Statement: `CREATE TABLE t_copy LIKE t`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.TableNotExists,+ Title: "table.exists",+ Content: "Table `t` not exists, related statement: \"CREATE TABLE t_copy LIKE t\"",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE tech_book RENAME TO tech`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE tech_book_copy LIKE tech_book`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE tech_book_copy AS SELECT * from t`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE tech_book_copy (a int)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ }++ advisor.RunSQLReviewRuleTests(t, tests, &TableExistsAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleTableExists,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: "",+ }, advisor.MockMySQLDatabase)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 8af11fa157..004b687b6a 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -61,6 +61,8 @@ const (SchemaRuleTableNoFK SQLReviewRuleType = "table.no-foreign-key"// SchemaRuleTableDropNamingConvention require only the table following the naming convention can be deleted.SchemaRuleTableDropNamingConvention SQLReviewRuleType = "table.drop-naming-convention"+ // SchemaRuleTableExists require the table existence.+ SchemaRuleTableExists SQLReviewRuleType = "table.exists"// SchemaRuleRequiredColumn enforce the required columns in each table.SchemaRuleRequiredColumn SQLReviewRuleType = "column.required"@@ -432,6 +434,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLTableDropNamingConvention, nil}+ case SchemaRuleTableExists:+ switch engine {+ case db.MySQL, db.TiDB:+ return MySQLTableExists, nil+ }case SchemaRuleMySQLEngine:if engine == db.MySQL {return MySQLUseInnoDB, nil