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(catalog): walk-through func supports MySQL DROP TABLE statements (#2601)
rebelicee78658eef935
diff --git a/plugin/advisor/catalog/catalog.go b/plugin/advisor/catalog/catalog.goindex e1cbd04f49..9eda71087d 100644--- a/plugin/advisor/catalog/catalog.go+++ b/plugin/advisor/catalog/catalog.go@@ -8,6 +8,7 @@ import (// Catalog is the service for catalog.type Catalog interface {GetDatabase() *Database+ GetFinder() *Finder}// Database is the database.diff --git a/plugin/advisor/catalog/finder.go b/plugin/advisor/catalog/finder.goindex 57baa56a57..a985ac0f95 100644--- a/plugin/advisor/catalog/finder.go+++ b/plugin/advisor/catalog/finder.go@@ -2,14 +2,44 @@ package catalogimport "github.com/bytebase/bytebase/plugin/advisor/db"+// FinderContext is the context for finder.+type FinderContext struct {+ // CheckIntegrity defines the policy for integrity checking.+ // There are two cases that will cause database to have an empty catalog:+ // 1. we can not fetch the catalog, such as GitHub App/Actions.+ // 2. the databse is indeed empty.+ // We need different logic to deal with these two cases separately.+ // If DROP TABLE t and t not exists:+ // 1. For case one, just ignore this statement.+ // 2. For case two, return the error that table t not exists.+ // In addition, We need fine-grained CheckIntegrity.+ // Consider the case one, and then create a table t by CREATE TABLE statement.+ // After this, drop column a in table t, but column a not exists.+ // In this case, we need return the error that column a does not exist in table t,+ // instead of ignoring this drop-column statement.+ CheckIntegrity bool+}++// Copy returns the deep copy.+func (ctx *FinderContext) Copy() *FinderContext {+ return &FinderContext{+ CheckIntegrity: ctx.CheckIntegrity,+ }+}+// Finder is the service for finding schema information in database.type Finder struct {database *databaseState}// NewFinder creates a new finder.-func NewFinder(database *Database) *Finder {- return &Finder{database: newDatabaseState(database)}+func NewFinder(database *Database, context *FinderContext) *Finder {+ return &Finder{database: newDatabaseState(database, context)}+}++// NewEmptyFinder creates a finder with empty databse.+func NewEmptyFinder(ctx *FinderContext) *Finder {+ return &Finder{database: newDatabaseState(&Database{}, ctx)}}// HasNoTable returns true if the current database has no table.diff --git a/plugin/advisor/catalog/state.go b/plugin/advisor/catalog/state.goindex 3de123a37e..07d173654c 100644--- a/plugin/advisor/catalog/state.go+++ b/plugin/advisor/catalog/state.go@@ -8,32 +8,34 @@ import ("github.com/bytebase/bytebase/plugin/advisor/db")-func newDatabaseState(d *Database) *databaseState {+func newDatabaseState(d *Database, context *FinderContext) *databaseState {database := &databaseState{name: d.Name,characterSet: d.CharacterSet,collation: d.Collation,dbType: d.DbType,schemaSet: make(schemaStateMap),+ context: context.Copy(),}for _, schema := range d.SchemaList {- database.schemaSet[schema.Name] = newSchemaState(schema)+ database.schemaSet[schema.Name] = newSchemaState(schema, context)}return database}-func newSchemaState(s *Schema) *schemaState {+func newSchemaState(s *Schema, context *FinderContext) *schemaState {schema := &schemaState{name: s.Name,tableSet: make(tableStateMap),viewSet: make(viewStateMap),extensionSet: make(extensionStateMap),+ context: context.Copy(),}for _, table := range s.TableList {- schema.tableSet[table.Name] = newTableState(table)+ schema.tableSet[table.Name] = newTableState(table, context)}for _, view := range s.ViewList {@@ -63,7 +65,7 @@ func newExtensionState(e *Extension) *extensionState {}}-func newTableState(t *Table) *tableState {+func newTableState(t *Table, context *FinderContext) *tableState {table := &tableState{name: t.Name,tableType: t.Type,@@ -77,6 +79,7 @@ func newTableState(t *Table) *tableState {comment: t.Comment,columnSet: make(columnStateMap),indexSet: make(indexStateMap),+ context: context.Copy(),}for _, column := range t.ColumnList {@@ -122,12 +125,16 @@ type databaseState struct {collation stringdbType db.TypeschemaSet schemaStateMap++ context *FinderContext}type schemaState struct {name stringtableSet tableStateMapviewSet viewStateMapextensionSet extensionStateMap++ context *FinderContext}type schemaStateMap map[string]*schemaState@@ -152,6 +159,8 @@ type tableState struct {columnSet columnStateMap// indexSet isn't supported for ClickHouse, Snowflake.indexSet indexStateMap++ context *FinderContext}type tableStateMap map[string]*tableStatediff --git a/plugin/advisor/catalog/walk_through.go b/plugin/advisor/catalog/walk_through.goindex 59ca1ead41..e33b3bcd63 100644--- a/plugin/advisor/catalog/walk_through.go+++ b/plugin/advisor/catalog/walk_through.go@@ -41,6 +41,8 @@ const (// ErrorTypeTableExists is the error that table exists.ErrorTypeTableExists = 301+ // ErrorTypeTableNotExists is the error that table not exists.+ ErrorTypeTableNotExists = 302// 401 ~ 499 column error type.@@ -112,11 +114,45 @@ func (d *databaseState) changeState(in tidbast.StmtNode) error {switch node := in.(type) {case *tidbast.CreateTableStmt:return d.createTable(node)+ case *tidbast.DropTableStmt:+ return d.dropTable(node)default:return nil}}+func (d *databaseState) dropTable(node *tidbast.DropTableStmt) error {+ // TODO(rebelice): deal with DROP VIEW statement.+ if !node.IsView {+ for _, name := range node.Tables {+ if name.Schema.O != "" && d.name != name.Schema.O {+ return &WalkThroughError{+ Type: ErrorTypeAccessOtherDatabase,+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", name.Schema.O, d.name),+ }+ }++ schema, exists := d.schemaSet[""]+ if !exists {+ schema = d.createSchema("")+ }++ if _, exists = schema.tableSet[name.Name.O]; !exists {+ if node.IfExists || !schema.context.CheckIntegrity {+ return nil+ }+ return &WalkThroughError{+ Type: ErrorTypeTableNotExists,+ Content: fmt.Sprintf("Table `%s` does not exist", name.Name.O),+ }+ }++ delete(schema.tableSet, name.Name.O)+ }+ }+ return nil+}+func (d *databaseState) createTable(node *tidbast.CreateTableStmt) error {if node.Table.Schema.O != "" && d.name != node.Table.Schema.O {return &WalkThroughError{@@ -144,6 +180,7 @@ func (d *databaseState) createTable(node *tidbast.CreateTableStmt) error {name: node.Table.Name.O,columnSet: make(columnStateMap),indexSet: make(indexStateMap),+ context: &FinderContext{CheckIntegrity: true},}schema.tableSet[table.name] = table@@ -366,6 +403,7 @@ func (d *databaseState) createSchema(name string) *schemaState {tableSet: make(tableStateMap),viewSet: make(viewStateMap),extensionSet: make(extensionStateMap),+ context: d.context.Copy(),}d.schemaSet[name] = schemadiff --git a/plugin/advisor/catalog/walk_through_test.go b/plugin/advisor/catalog/walk_through_test.goindex 4b02895e74..215e562612 100644--- a/plugin/advisor/catalog/walk_through_test.go+++ b/plugin/advisor/catalog/walk_through_test.go@@ -14,6 +14,7 @@ type testData struct {origin *Databasestatement stringwant *Database+ err error}var (@@ -181,13 +182,89 @@ func TestWalkThrough(t *testing.T) {},},},+ {+ origin: &Database{+ Name: "test",+ DbType: db.MySQL,+ },+ statement: `+ CREATE TABLE t1(a int, b int, c int);+ CREATE TABLE t2(a int);+ DROP TABLE t1, t2+ `,+ want: &Database{+ Name: "test",+ DbType: db.MySQL,+ SchemaList: []*Schema{+ {+ TableList: []*Table{},+ ViewList: []*View{},+ ExtensionList: []*Extension{},+ },+ },+ },+ },+ {+ origin: &Database{+ Name: "test",+ DbType: db.MySQL,+ },+ statement: `+ DROP TABLE t1, t2+ `,+ err: &WalkThroughError{+ Type: ErrorTypeTableNotExists,+ Content: "Table `t1` does not exist",+ },+ },+ }++ for _, test := range tests {+ state := newDatabaseState(test.origin, &FinderContext{CheckIntegrity: true})+ err := state.WalkThrough(test.statement)+ if test.err != nil {+ require.Equal(t, err, test.err)+ continue+ }+ require.NoError(t, err)+ want := newDatabaseState(test.want, &FinderContext{CheckIntegrity: true})+ require.Equal(t, want, state, test.statement)+ }+}++func TestWalkThroughForNoCatalog(t *testing.T) {+ tests := []testData{+ {+ origin: &Database{+ Name: "test",+ DbType: db.MySQL,+ },+ statement: `+ DROP TABLE t1, t2+ `,+ want: &Database{+ Name: "test",+ DbType: db.MySQL,+ SchemaList: []*Schema{+ {+ TableList: []*Table{},+ ViewList: []*View{},+ ExtensionList: []*Extension{},+ },+ },+ },+ },}for _, test := range tests {- state := newDatabaseState(test.origin)+ state := newDatabaseState(test.origin, &FinderContext{CheckIntegrity: false})err := state.WalkThrough(test.statement)+ if test.err != nil {+ require.Equal(t, err, test.err)+ continue+ }require.NoError(t, err)- want := newDatabaseState(test.want)+ want := newDatabaseState(test.want, &FinderContext{CheckIntegrity: false})require.Equal(t, want, state, test.statement)}}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex b0be38d8ce..e16b09b2d8 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -374,7 +374,6 @@ type SQLReviewCheckContext struct {// SQLReviewCheck checks the statements with sql review rules.func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext SQLReviewCheckContext) ([]Advice, error) {var result []Advice- database := checkContext.Catalog.GetDatabase()for _, rule := range ruleList {if rule.Level == SchemaRuleLevelDisabled {@@ -394,7 +393,7 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext SCharset: checkContext.Charset,Collation: checkContext.Collation,Rule: rule,- Catalog: catalog.NewFinder(database),+ Catalog: checkContext.Catalog.GetFinder(),},statements,)diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.goindex 7341879dd7..3929a5ca65 100644--- a/plugin/advisor/utils_for_tests.go+++ b/plugin/advisor/utils_for_tests.go@@ -125,7 +125,7 @@ func RunSQLReviewRuleTests(Charset: "",Collation: "",Rule: rule,- Catalog: catalog.NewFinder(database),+ Catalog: catalog.NewFinder(database, &catalog.FinderContext{CheckIntegrity: true}),}for _, tc := range tests {adviceList, err := adv.Check(ctx, tc.Statement)diff --git a/server/openapi.go b/server/openapi.goindex 664cf8b8c6..4cd56d4d44 100644--- a/server/openapi.go+++ b/server/openapi.go@@ -29,6 +29,12 @@ func (*catalogService) GetDatabase() *catalog.Database {return &catalog.Database{}}+// GetFinder is the API message in catalog.+// We will not connect to the user's database in the early version of sql check api.+func (*catalogService) GetFinder() *catalog.Finder {+ return catalog.NewEmptyFinder(&catalog.FinderContext{CheckIntegrity: false})+}+type sqlCheckRequestBody struct {Statement string `json:"statement"`DatabaseType string `json:"databaseType"`diff --git a/sql-server/advise.go b/sql-server/advise.goindex 27743a7a16..4db9eb2234 100644--- a/sql-server/advise.go+++ b/sql-server/advise.go@@ -30,6 +30,12 @@ func (*catalogService) GetDatabase() *catalog.Database {return &catalog.Database{}}+// GetDatabase is the API message in catalog.+// We will not connect to the user's database in the early version of sql check api.+func (*catalogService) GetFinder() *catalog.Finder {+ return catalog.NewEmptyFinder(&catalog.FinderContext{CheckIntegrity: false})+}+type sqlCheckRequestBody struct {Statement string `json:"statement"`DatabaseType string `json:"databaseType"`diff --git a/store/catalog.go b/store/catalog.goindex 57c73ba7fa..ff5a16ef0b 100644--- a/store/catalog.go+++ b/store/catalog.go@@ -20,6 +20,7 @@ var (// Catalog is the database catalog.type Catalog struct {Database *catalog.Database+ Finder *catalog.Finder}// NewCatalog creates a new database catalog.@@ -49,8 +50,9 @@ func (s *Store) NewCatalog(ctx context.Context, databaseID int, engineType db.Tyif databaseData.SchemaList, err = s.getSchemaList(ctx, databaseID, engineType); err != nil {return nil, err}-- return &Catalog{Database: databaseData}, nil+ c := &Catalog{Database: databaseData}+ c.Finder = catalog.NewFinder(c.Database, &catalog.FinderContext{CheckIntegrity: true})+ return c, nil}// GetDatabase implements the catalog.Catalog interface.@@ -58,6 +60,11 @@ func (c *Catalog) GetDatabase() *catalog.Database {return c.Database}+// GetFinder implements the catalog.Catalog interface.+func (c *Catalog) GetFinder() *catalog.Finder {+ return c.Finder+}+type schemaMap map[string]*catalog.Schemafunc (m schemaMap) getOrCreateSchema(name string) *catalog.Schema {