Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: reuse ast (#12299)
Danny Xudf74d8f3288f
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 8d6448c778..6055fe7897 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -1256,7 +1256,7 @@ func (s *SQLService) sqlReviewCheck(ctx context.Context, statement string, changdbMetadata = dbSchema.GetMetadata()}- catalog, err := s.store.NewCatalog(ctx, database.UID, instance.Engine, store.IgnoreDatabaseAndTableCaseSensitive(instance), overrideMetadata)+ catalog, err := catalog.NewCatalog(ctx, s.store, database.UID, instance.Engine, store.IgnoreDatabaseAndTableCaseSensitive(instance), overrideMetadata)if err != nil {return storepb.Advice_ERROR, nil, status.Errorf(codes.Internal, "Failed to create a catalog: %v", err)}@@ -1321,7 +1321,7 @@ func (s *SQLService) sqlCheck(environmentID int,statement string,changeType v1pb.CheckRequest_ChangeType,- catalog catalog.Catalog,+ catalog *catalog.Catalog,driver *sql.DB,currentDatabase string,) (storepb.Advice_Status, []*storepb.Advice, error) {diff --git a/backend/plugin/advisor/catalog/catalog.go b/backend/plugin/advisor/catalog/catalog.goindex 94314bca44..b5bc9716af 100644--- a/backend/plugin/advisor/catalog/catalog.go+++ b/backend/plugin/advisor/catalog/catalog.go@@ -1,7 +1,45 @@// Package catalog provides API definition for catalog service.package catalog-// Catalog is the service for catalog.-type Catalog interface {- GetFinder() *Finder+import (+ "context"++ "github.com/bytebase/bytebase/backend/store"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++// Catalog is the database catalog.+type Catalog struct {+ Finder *Finder+}++// NewCatalog creates a new database catalog.+func NewCatalog(ctx context.Context, s *store.Store, databaseID int, engineType storepb.Engine, ignoreCaseSensitive bool, overrideDatabaseMetadata *storepb.DatabaseSchemaMetadata) (*Catalog, error) {+ c := &Catalog{}++ dbMetadata := overrideDatabaseMetadata+ if dbMetadata == nil {+ databaseMeta, err := s.GetDBSchema(ctx, databaseID)+ if err != nil {+ return nil, err+ }+ if databaseMeta == nil {+ return nil, nil+ }+ dbMetadata = databaseMeta.GetMetadata()+ }+ c.Finder = NewFinder(dbMetadata, &FinderContext{CheckIntegrity: true, EngineType: engineType, IgnoreCaseSensitive: ignoreCaseSensitive})+ return c, nil+}++// GetFinder implements the catalog.Catalog interface.+func (c *Catalog) GetFinder() *Finder {+ return c.Finder+}++// NewEmptyCatalog creates a new empty database catalog.+func NewEmptyCatalog(engineType storepb.Engine) (*Catalog, error) {+ return &Catalog{+ NewEmptyFinder(&FinderContext{CheckIntegrity: false, EngineType: engineType, IgnoreCaseSensitive: false}),+ }, nil}diff --git a/backend/plugin/advisor/catalog/finder.go b/backend/plugin/advisor/catalog/finder.goindex 20377b0eff..23247dd27f 100644--- a/backend/plugin/advisor/catalog/finder.go+++ b/backend/plugin/advisor/catalog/finder.go@@ -58,6 +58,6 @@ func NewEmptyFinder(ctx *FinderContext) *Finder {}// WalkThrough does the walk through.-func (f *Finder) WalkThrough(statements string) error {- return f.Final.WalkThrough(statements)+func (f *Finder) WalkThrough(ast any) error {+ return f.Final.WalkThrough(ast)}diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.goindex 87b1d7dec9..68baec4469 100644--- a/backend/plugin/advisor/catalog/walk_through.go+++ b/backend/plugin/advisor/catalog/walk_through.go@@ -4,15 +4,13 @@ import ("fmt""strings"- tidbparser "github.com/pingcap/tidb/pkg/parser"tidbast "github.com/pingcap/tidb/pkg/parser/ast""github.com/pingcap/tidb/pkg/parser/format""github.com/pingcap/tidb/pkg/parser/model""github.com/pingcap/tidb/pkg/parser/mysql""github.com/pingcap/tidb/pkg/types"+ "github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/plugin/parser/base"- tidbbbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -213,16 +211,16 @@ func (e *WalkThroughError) Error() string {}// WalkThrough will collect the catalog schema in the databaseState as it walks through the stmt.-func (d *DatabaseState) WalkThrough(stmt string) error {+func (d *DatabaseState) WalkThrough(ast any) error {switch d.dbType {case storepb.Engine_TIDB:- err := d.tidbWalkThrough(stmt)+ err := d.tidbWalkThrough(ast)return errcase storepb.Engine_MYSQL, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:- err := d.mysqlWalkThrough(stmt)+ err := d.mysqlWalkThrough(ast)return errcase storepb.Engine_POSTGRES:- if err := d.pgWalkThrough(stmt); err != nil {+ if err := d.pgWalkThrough(ast); err != nil {if d.ctx.CheckIntegrity {return err}@@ -240,7 +238,7 @@ func (d *DatabaseState) WalkThrough(stmt string) error {}}-func (d *DatabaseState) tidbWalkThrough(stmt string) error {+func (d *DatabaseState) tidbWalkThrough(ast any) error {// We define the Catalog as Database -> Schema -> Table. The Schema is only for PostgreSQL.// So we use a Schema whose name is empty for other engines, such as MySQL.// If there is no empty-string-name schema, create it to avoid corner cases.@@ -248,11 +246,10 @@ func (d *DatabaseState) tidbWalkThrough(stmt string) error {d.createSchema("")}- nodeList, err := d.parse(stmt)- if err != nil {- return err+ nodeList, ok := ast.([]tidbast.StmtNode)+ if !ok {+ return errors.Errorf("invalid ast type %T", ast)}-for _, node := range nodeList {// change stateif err := d.changeState(node); err != nil {@@ -1356,42 +1353,6 @@ func (d *DatabaseState) createSchema(name string) *SchemaState {return schema}-func (*DatabaseState) parse(statement string) ([]tidbast.StmtNode, *WalkThroughError) {- p := tidbparser.New()- // To support MySQL8 window function syntax.- // See https://github.com/bytebase/bytebase/issues/175.- p.EnableWindowFunc(true)-- singleSQLs, err := base.SplitMultiSQL(storepb.Engine_TIDB, statement)- if err != nil {- return nil, NewSetLineError(err.Error())- }-- var returnNodes []tidbast.StmtNode- for _, singleSQL := range singleSQLs {- nodes, _, err := p.Parse(singleSQL.Text, "", "")- if err != nil {- return nil, NewSetLineError(err.Error())- }-- if len(nodes) != 1 {- continue- }-- node := nodes[0]- node.SetText(nil, singleSQL.Text)- node.SetOriginTextPosition(singleSQL.LastLine)- if n, ok := node.(*tidbast.CreateTableStmt); ok {- if err := tidbbbparser.SetLineForMySQLCreateTableStmt(n); err != nil {- return nil, NewSetLineError(err.Error())- }- }- returnNodes = append(returnNodes, node)- }-- return returnNodes, nil-}-func restoreNode(node tidbast.Node, flag format.RestoreFlags) (string, *WalkThroughError) {var buffer strings.Builderctx := format.NewRestoreCtx(flag, &buffer)diff --git a/backend/plugin/advisor/catalog/walk_through_for_mysql.go b/backend/plugin/advisor/catalog/walk_through_for_mysql.goindex 7e3f83b273..9d3170c37b 100644--- a/backend/plugin/advisor/catalog/walk_through_for_mysql.go+++ b/backend/plugin/advisor/catalog/walk_through_for_mysql.go@@ -7,12 +7,13 @@ import ("github.com/antlr4-go/antlr/v4"mysql "github.com/bytebase/mysql-parser"tidbast "github.com/pingcap/tidb/pkg/parser/ast"+ "github.com/pkg/errors"mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql""github.com/bytebase/bytebase/backend/plugin/parser/tidb")-func (d *DatabaseState) mysqlWalkThrough(stmt string) error {+func (d *DatabaseState) mysqlWalkThrough(ast any) error {// We define the Catalog as Database -> Schema -> Table. The Schema is only for PostgreSQL.// So we use a Schema whose name is empty for other engines, such as MySQL.// If there is no empty-string-name schema, create it to avoid corner cases.@@ -20,9 +21,9 @@ func (d *DatabaseState) mysqlWalkThrough(stmt string) error {d.createSchema("")}- nodeList, err := mysqlparser.ParseMySQL(stmt + ";")- if err != nil {- return NewParseError(err.Error())+ nodeList, ok := ast.([]*mysqlparser.ParseResult)+ if !ok {+ return errors.Errorf("invalid ast type %T", ast)}for _, node := range nodeList {if err := d.mysqlChangeState(node); err != nil {diff --git a/backend/plugin/advisor/catalog/walk_through_for_pg.go b/backend/plugin/advisor/catalog/walk_through_for_pg.goindex 02d90f5c0d..9e184cc1e4 100644--- a/backend/plugin/advisor/catalog/walk_through_for_pg.go+++ b/backend/plugin/advisor/catalog/walk_through_for_pg.go@@ -15,12 +15,11 @@ const (publicSchemaName = "public")-func (d *DatabaseState) pgWalkThrough(stmt string) error {- nodeList, err := pgParse(stmt)- if err != nil {- return NewParseError(err.Error())+func (d *DatabaseState) pgWalkThrough(pgAst any) error {+ nodeList, ok := pgAst.([]ast.Node)+ if !ok {+ return errors.Errorf("invalid ast type %T", pgAst)}-for _, node := range nodeList {if err := d.pgChangeState(node); err != nil {return err@@ -1064,10 +1063,6 @@ func (t *TableState) getColumn(columnName string) (*ColumnState, *WalkThroughErrreturn column, nil}-func pgParse(stmt string) ([]ast.Node, error) {- return pgrawparser.Parse(pgrawparser.ParseContext{}, stmt)-}-func normalizeCollation(collation *ast.CollationNameDef) string {if collation == nil {return ""diff --git a/backend/plugin/advisor/catalog/walk_through_test.go b/backend/plugin/advisor/catalog/walk_through_test.goindex 705b34d578..5bb9af129f 100644--- a/backend/plugin/advisor/catalog/walk_through_test.go+++ b/backend/plugin/advisor/catalog/walk_through_test.go@@ -17,6 +17,7 @@ import (storepb "github.com/bytebase/bytebase/proto/generated-go/store"// Register postgresql parser driver.+ "github.com/bytebase/bytebase/backend/component/sheet"_ "github.com/bytebase/bytebase/backend/plugin/parser/sql/engine/pg")@@ -139,6 +140,7 @@ func runWalkThroughTest(t *testing.T, file string, engineType storepb.Engine, orrequire.NoError(t, err)err = yaml.Unmarshal(byteValue, &tests)require.NoError(t, err)+ sm := sheet.NewManager(nil)for i, test := range tests {var state *DatabaseState@@ -149,7 +151,8 @@ func runWalkThroughTest(t *testing.T, file string, engineType storepb.Engine, orstate = finder.Origin}- err := state.WalkThrough(test.Statement)+ ast, _ := sm.GetAST(engineType, test.Statement)+ err := state.WalkThrough(ast)if err != nil {if record {walkThroughError, ok := err.(*WalkThroughError)diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex e8ce56db12..d62509902b 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -465,6 +465,11 @@ func UnmarshalNamingCaseRulePayload(payload string) (*NamingCaseRulePayload, errreturn &ncr, nil}+// Catalog is the service for catalog.+type catalogInterface interface {+ GetFinder() *catalog.Finder+}+// SQLReviewCheckContext is the context for SQL review check.type SQLReviewCheckContext struct {Charset string@@ -472,7 +477,7 @@ type SQLReviewCheckContext struct {ChangeType storepb.PlanCheckRunConfig_ChangeDatabaseTypeDBSchema *storepb.DatabaseSchemaMetadataDbType storepb.Engine- Catalog catalog.Catalog+ Catalog catalogInterfaceDriver *sql.DBContext context.ContextPreUpdateBackupDetail *storepb.PlanCheckRunConfig_PreUpdateBackupDetail@@ -491,7 +496,7 @@ func SQLReviewCheck(sm *sheet.Manager, statements string, ruleList []*storepb.SQfinder := checkContext.Catalog.GetFinder()switch checkContext.DbType {case storepb.Engine_TIDB, storepb.Engine_MYSQL, storepb.Engine_MARIADB, storepb.Engine_POSTGRES, storepb.Engine_OCEANBASE:- if err := finder.WalkThrough(statements); err != nil {+ if err := finder.WalkThrough(ast); err != nil {return convertWalkThroughErrorToAdvice(checkContext, err)}}diff --git a/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml b/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yamlindex 27206f2252..5d38ced230 100644--- a/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml+++ b/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml@@ -2,12 +2,14 @@CREATE TABLE t(a int);ALTER TABLE t MODIFY COLUMN a intwant:- - status: 1- code: 0- title: OK- content: ""+ - status: 2+ code: 407+ title: column.disallow-changing-order+ content: '"ALTER TABLE t MODIFY COLUMN a int" changes column order'detail: ""- startposition: null+ startposition:+ line: 2+ column: 0- statement: |-CREATE TABLE t(a int);ALTER TABLE t MODIFY COLUMN a int FIRSTdiff --git a/backend/runner/plancheck/statement_advise_executor.go b/backend/runner/plancheck/statement_advise_executor.goindex 281c089abc..e7482866be 100644--- a/backend/runner/plancheck/statement_advise_executor.go+++ b/backend/runner/plancheck/statement_advise_executor.go@@ -12,6 +12,7 @@ import (enterprise "github.com/bytebase/bytebase/backend/enterprise/api"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"@@ -150,7 +151,7 @@ func (e *StatementAdviseExecutor) runForDatabaseTarget(ctx context.Context, conf}}- catalog, err := e.store.NewCatalog(ctx, database.UID, instance.Engine, store.IgnoreDatabaseAndTableCaseSensitive(instance), nil /* Override Metadata */)+ catalog, err := catalog.NewCatalog(ctx, e.store, database.UID, instance.Engine, store.IgnoreDatabaseAndTableCaseSensitive(instance), nil /* Override Metadata */)if err != nil {return nil, common.Wrapf(err, common.Internal, "failed to create a catalog")}@@ -340,7 +341,7 @@ func (e *StatementAdviseExecutor) runForDatabaseGroupTarget(ctx context.Context,}}- catalog, err := e.store.NewCatalog(ctx, database.UID, instance.Engine, store.IgnoreDatabaseAndTableCaseSensitive(instance), nil /* Override Metadata */)+ catalog, err := catalog.NewCatalog(ctx, e.store, database.UID, instance.Engine, store.IgnoreDatabaseAndTableCaseSensitive(instance), nil /* Override Metadata */)if err != nil {return nil, common.Wrapf(err, common.Internal, "failed to create a catalog")}diff --git a/backend/store/catalog.go b/backend/store/catalog.godeleted file mode 100644index d0911b30b2..0000000000--- a/backend/store/catalog.go+++ /dev/null@@ -1,48 +0,0 @@-package store--import (- "context"-- "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"- storepb "github.com/bytebase/bytebase/proto/generated-go/store"-)--var (- _ catalog.Catalog = (*Catalog)(nil)-)--// Catalog is the database catalog.-type Catalog struct {- Finder *catalog.Finder-}--// NewCatalog creates a new database catalog.-func (s *Store) NewCatalog(ctx context.Context, databaseID int, engineType storepb.Engine, ignoreCaseSensitive bool, overrideDatabaseMetadata *storepb.DatabaseSchemaMetadata) (catalog.Catalog, error) {- c := &Catalog{}-- dbMetadata := overrideDatabaseMetadata- if dbMetadata == nil {- databaseMeta, err := s.GetDBSchema(ctx, databaseID)- if err != nil {- return nil, err- }- if databaseMeta == nil {- return nil, nil- }- dbMetadata = databaseMeta.GetMetadata()- }- c.Finder = catalog.NewFinder(dbMetadata, &catalog.FinderContext{CheckIntegrity: true, EngineType: engineType, IgnoreCaseSensitive: ignoreCaseSensitive})- return c, nil-}--// GetFinder implements the catalog.Catalog interface.-func (c *Catalog) GetFinder() *catalog.Finder {- return c.Finder-}--// NewEmptyCatalog creates a new empty database catalog.-func NewEmptyCatalog(engineType storepb.Engine) (catalog.Catalog, error) {- return &Catalog{- catalog.NewEmptyFinder(&catalog.FinderContext{CheckIntegrity: false, EngineType: engineType, IgnoreCaseSensitive: false}),- }, nil-}