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): introduce catalog walk-through (#2698)
rebelicebd29b2b0d956
diff --git a/plugin/advisor/catalog/finder.go b/plugin/advisor/catalog/finder.goindex a985ac0f95..71ad25a505 100644--- a/plugin/advisor/catalog/finder.go+++ b/plugin/advisor/catalog/finder.go@@ -1,7 +1,5 @@package catalog-import "github.com/bytebase/bytebase/plugin/advisor/db"-// FinderContext is the context for finder.type FinderContext struct {// CheckIntegrity defines the policy for integrity checking.@@ -29,142 +27,22 @@ func (ctx *FinderContext) Copy() *FinderContext {// Finder is the service for finding schema information in database.type Finder struct {- database *databaseState+ Origin *databaseState+ Final *databaseState}// NewFinder creates a new finder.func NewFinder(database *Database, context *FinderContext) *Finder {- return &Finder{database: newDatabaseState(database, context)}+ return &Finder{Origin: 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.-func (f *Finder) HasNoTable() bool {- for _, schema := range f.database.schemaSet {- if len(schema.tableSet) != 0 {- return false- }- }-- return true-}--// DatabaseName returns the database name.-func (f *Finder) DatabaseName() string {- return f.database.name-}--// IndexFind is for find index.-type IndexFind struct {- SchemaName string- TableName string- IndexName string-}--// FindIndex finds the index.-func (f *Finder) FindIndex(find *IndexFind) (string, *Index) {- // needMatchTable is used for PostgreSQL. In PostgreSQL, the index name is unique in a schema, not a table.- needMatchTable := (f.database.dbType != db.Postgres || find.SchemaName == "" || find.TableName != "")- if needMatchTable {- schema, exists := f.database.schemaSet[find.SchemaName]- if !exists {- return "", nil- }- table, exists := schema.tableSet[find.TableName]- if !exists {- return "", nil- }- index, exists := table.indexSet[find.IndexName]- if !exists {- return "", nil- }- return table.name, index.convertToCatalog()- }- for _, schema := range f.database.schemaSet {- if schema.name != find.SchemaName {- continue- }- for _, table := range schema.tableSet {- // no need to match table name.- index, exists := table.indexSet[find.IndexName]- if !exists {- return "", nil- }- return table.name, index.convertToCatalog()- }- }- return "", nil-}--// PrimaryKeyFind is for find primary key.-type PrimaryKeyFind struct {- SchemaName string- TableName string+ return &Finder{Origin: newDatabaseState(&Database{}, ctx)}}-// FindPrimaryKey finds the primary key.-func (f *Finder) FindPrimaryKey(find *PrimaryKeyFind) *Index {- for _, schema := range f.database.schemaSet {- if schema.name != find.SchemaName {- continue- }- for _, table := range schema.tableSet {- if table.name != find.TableName {- continue- }- for _, index := range table.indexSet {- if index.primary {- return index.convertToCatalog()- }- }- }- }- return nil-}--// ColumnFind is for find column.-type ColumnFind struct {- SchemaName string- TableName string- ColumnName string-}--// FindColumn finds the column.-func (f *Finder) FindColumn(find *ColumnFind) *Column {- schema, exists := f.database.schemaSet[find.SchemaName]- if !exists {- return nil- }- table, exists := schema.tableSet[find.TableName]- if !exists {- return nil- }- column, exists := table.columnSet[find.ColumnName]- if !exists {- return nil- }- return column.convertToCatalog()-}--// TableFind is for find table.-type TableFind struct {- SchemaName string- TableName string-}--// FindTable finds the table.-func (f *Finder) FindTable(find *TableFind) *Table {- schema, exists := f.database.schemaSet[find.SchemaName]- if !exists {- return nil- }- table, exists := schema.tableSet[find.TableName]- if !exists {- return nil- }- return table.convertToCatalog()+// WalkThrough does the walk through.+func (f *Finder) WalkThrough(statements string) error {+ f.Final = f.Origin.copy()+ return f.Final.WalkThrough(statements)}diff --git a/plugin/advisor/catalog/state.go b/plugin/advisor/catalog/state.goindex 6897bd84d3..9083232327 100644--- a/plugin/advisor/catalog/state.go+++ b/plugin/advisor/catalog/state.go@@ -128,6 +128,154 @@ type databaseState struct {context *FinderContext}++// HasNoTable returns true if the current database has no table.+func (d *databaseState) HasNoTable() bool {+ for _, schema := range d.schemaSet {+ if len(schema.tableSet) != 0 {+ return false+ }+ }++ return true+}++// DatabaseName returns the database name.+func (d *databaseState) DatabaseName() string {+ return d.name+}++// IndexFind is for find index.+type IndexFind struct {+ SchemaName string+ TableName string+ IndexName string+}++func (d *databaseState) FindIndex(find *IndexFind) (string, *Index) {+ // There are two cases to find a index:+ // 1. find an index in specific table. e.g. MySQL and TiDB.+ // 2. find an index in the schema. e.g. PostgreSQL.+ // In PostgreSQL, the index name is unique in a schema, not a table.+ // In MySQL and TiDB, the index name is unique in a table.+ // So for case one, we need match table name, but for case two, we don't need.+ needMatchTable := (d.dbType != db.Postgres || find.SchemaName == "" || find.TableName != "")+ if needMatchTable {+ schema, exists := d.schemaSet[find.SchemaName]+ if !exists {+ return "", nil+ }+ table, exists := schema.tableSet[find.TableName]+ if !exists {+ return "", nil+ }+ index, exists := table.indexSet[find.IndexName]+ if !exists {+ return "", nil+ }+ return table.name, index.convertToCatalog()+ }+ for _, schema := range d.schemaSet {+ if schema.name != find.SchemaName {+ continue+ }+ for _, table := range schema.tableSet {+ // no need to further match table name because index is already unique in the schema+ index, exists := table.indexSet[find.IndexName]+ if !exists {+ return "", nil+ }+ return table.name, index.convertToCatalog()+ }+ }+ return "", nil+}++// PrimaryKeyFind is for finding primary key.+type PrimaryKeyFind struct {+ SchemaName string+ TableName string+}++// FindPrimaryKey finds the primary key.+func (d *databaseState) FindPrimaryKey(find *PrimaryKeyFind) *Index {+ for _, schema := range d.schemaSet {+ if schema.name != find.SchemaName {+ continue+ }+ for _, table := range schema.tableSet {+ if table.name != find.TableName {+ continue+ }+ for _, index := range table.indexSet {+ if index.primary {+ return index.convertToCatalog()+ }+ }+ }+ }+ return nil+}++// ColumnFind is for finding column.+type ColumnFind struct {+ SchemaName string+ TableName string+ ColumnName string+}++// FindColumn finds the column.+func (d *databaseState) FindColumn(find *ColumnFind) *Column {+ schema, exists := d.schemaSet[find.SchemaName]+ if !exists {+ return nil+ }+ table, exists := schema.tableSet[find.TableName]+ if !exists {+ return nil+ }+ column, exists := table.columnSet[find.ColumnName]+ if !exists {+ return nil+ }+ return column.convertToCatalog()+}++// TableFind is for find table.+type TableFind struct {+ SchemaName string+ TableName string+}++// FindTable finds the table.+func (d *databaseState) FindTable(find *TableFind) *Table {+ schema, exists := d.schemaSet[find.SchemaName]+ if !exists {+ return nil+ }+ table, exists := schema.tableSet[find.TableName]+ if !exists {+ return nil+ }+ return table.convertToCatalog()+}++func (d *databaseState) copy() *databaseState {+ newDb := newDatabaseState(d.convertToCatalog(), &FinderContext{CheckIntegrity: d.context.CheckIntegrity})+ newDb.deleted = d.deleted+ return newDb+}++func (d *databaseState) convertToCatalog() *Database {+ return &Database{+ Name: d.name,+ CharacterSet: d.characterSet,+ Collation: d.collation,+ DbType: d.dbType,+ SchemaList: d.schemaSet.convertToCatalog(),+ }+}+type schemaState struct {name stringtableSet tableStateMap@@ -138,6 +286,23 @@ type schemaState struct {}type schemaStateMap map[string]*schemaState+func (m schemaStateMap) convertToCatalog() []*Schema {+ var res []*Schema+ for _, schema := range m {+ res = append(res, schema.convertToCatalog())+ }+ return res+}++func (schema *schemaState) convertToCatalog() *Schema {+ return &Schema{+ Name: schema.name,+ TableList: schema.tableSet.convertToCatalog(),+ ViewList: schema.viewSet.convertToCatalog(),+ ExtensionList: schema.extensionSet.convertToCatalog(),+ }+}+type tableState struct {name stringtableType string@@ -162,6 +327,14 @@ type tableState struct {}type tableStateMap map[string]*tableState+func (m tableStateMap) convertToCatalog() []*Table {+ var res []*Table+ for _, table := range m {+ res = append(res, table.convertToCatalog())+ }+ return res+}+func (table *tableState) convertToCatalog() *Table {return &Table{Name: table.name,@@ -262,9 +435,41 @@ type viewState struct {}type viewStateMap map[string]*viewState+func (m viewStateMap) convertToCatalog() []*View {+ var res []*View+ for _, view := range m {+ res = append(res, view.convertToCatalog())+ }+ return res+}++func (view *viewState) convertToCatalog() *View {+ return &View{+ Name: view.name,+ Definition: view.definition,+ Comment: view.comment,+ }+}+type extensionState struct {name stringversion stringdescription string}type extensionStateMap map[string]*extensionState++func (m extensionStateMap) convertToCatalog() []*Extension {+ var res []*Extension+ for _, extension := range m {+ res = append(res, extension.convertToCatalog())+ }+ return res+}++func (extension *extensionState) convertToCatalog() *Extension {+ return &Extension{+ Name: extension.name,+ Version: extension.version,+ Description: extension.description,+ }+}diff --git a/plugin/advisor/catalog/walk_through.go b/plugin/advisor/catalog/walk_through.goindex b2f8124bc5..d7df7c59fe 100644--- a/plugin/advisor/catalog/walk_through.go+++ b/plugin/advisor/catalog/walk_through.go@@ -79,6 +79,7 @@ const (type WalkThroughError struct {Type WalkThroughErrorTypeContent string+ Line int}// NewParseError returns a new ErrorTypeParseError.@@ -144,10 +145,10 @@ func (e *WalkThroughError) Error() string {// WalkThrough will collect the catalog schema in the databaseState as it walks through the stmts.func (d *databaseState) WalkThrough(stmts string) error {- if d.dbType != db.MySQL {+ if d.dbType != db.MySQL && d.dbType != db.TiDB {return &WalkThroughError{Type: ErrorTypeUnsupported,- Content: fmt.Sprintf("Engine type %s is not supported", d.dbType),+ Content: fmt.Sprintf("Walk-through doesn't support engine type: %s", d.dbType),}}@@ -172,7 +173,15 @@ func (d *databaseState) WalkThrough(stmts string) error {return nil}-func (d *databaseState) changeState(in tidbast.StmtNode) error {+func (d *databaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError) {+ defer func() {+ if err == nil {+ return+ }+ if err.Line == 0 {+ err.Line = in.OriginTextPosition()+ }+ }()if d.deleted {return &WalkThroughError{Type: ErrorTypeDatabaseIsDeleted,@@ -203,7 +212,7 @@ func (d *databaseState) changeState(in tidbast.StmtNode) error {}}-func (d *databaseState) renameTable(node *tidbast.RenameTableStmt) error {+func (d *databaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughError {for _, tableToTable := range node.TableToTables {schema, exists := d.schemaSet[""]if !exists {@@ -257,7 +266,7 @@ func (d *databaseState) theCurrentDatabase(node *tidbast.TableToTable) bool {return true}-func (d *databaseState) dropDatabase(node *tidbast.DropDatabaseStmt) error {+func (d *databaseState) dropDatabase(node *tidbast.DropDatabaseStmt) *WalkThroughError {if node.Name != d.name {return NewAccessOtherDatabaseError(d.name, node.Name)}@@ -266,7 +275,7 @@ func (d *databaseState) dropDatabase(node *tidbast.DropDatabaseStmt) error {return nil}-func (d *databaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) error {+func (d *databaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) *WalkThroughError {if !node.AlterDefaultDatabase && node.Name != d.name {return NewAccessOtherDatabaseError(d.name, node.Name)}@@ -282,7 +291,7 @@ func (d *databaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) error {return nil}-func (d *databaseState) findTable(tableName *tidbast.TableName) (*tableState, error) {+func (d *databaseState) findTableState(tableName *tidbast.TableName) (*tableState, *WalkThroughError) {if tableName.Schema.O != "" && tableName.Schema.O != d.name {return nil, NewAccessOtherDatabaseError(d.name, tableName.Schema.O)}@@ -304,8 +313,8 @@ func (d *databaseState) findTable(tableName *tidbast.TableName) (*tableState, erreturn table, nil}-func (d *databaseState) dropIndex(node *tidbast.DropIndexStmt) error {- table, err := d.findTable(node.Table)+func (d *databaseState) dropIndex(node *tidbast.DropIndexStmt) *WalkThroughError {+ table, err := d.findTableState(node.Table)if err != nil {return err}@@ -316,8 +325,8 @@ func (d *databaseState) dropIndex(node *tidbast.DropIndexStmt) error {return table.dropIndex(node.IndexName)}-func (d *databaseState) createIndex(node *tidbast.CreateIndexStmt) error {- table, err := d.findTable(node.Table)+func (d *databaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughError {+ table, err := d.findTableState(node.Table)if err != nil {return err}@@ -348,8 +357,8 @@ func (d *databaseState) createIndex(node *tidbast.CreateIndexStmt) error {return table.createIndex(node.IndexName, keyList, unique, tp, node.IndexOption)}-func (d *databaseState) alterTable(node *tidbast.AlterTableStmt) error {- table, err := d.findTable(node.Table)+func (d *databaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughError {+ table, err := d.findTableState(node.Table)if err != nil {return err}@@ -439,7 +448,7 @@ func (d *databaseState) alterTable(node *tidbast.AlterTableStmt) error {return nil}-func (t *tableState) changeIndexVisibility(indexName string, visibility tidbast.IndexVisibility) error {+func (t *tableState) changeIndexVisibility(indexName string, visibility tidbast.IndexVisibility) *WalkThroughError {index, exists := t.indexSet[indexName]if !exists {return NewIndexNotExistsError(t.name, indexName)@@ -453,7 +462,7 @@ func (t *tableState) changeIndexVisibility(indexName string, visibility tidbast.return nil}-func (t *tableState) renameIndex(oldName string, newName string) error {+func (t *tableState) renameIndex(oldName string, newName string) *WalkThroughError {// For MySQL, the primary key has a special name 'PRIMARY'.// And the other indexes can not use the name which case-insensitive equals 'PRIMARY'.if strings.ToUpper(oldName) == PrimaryKeyName || strings.ToUpper(newName) == PrimaryKeyName {@@ -482,7 +491,7 @@ func (t *tableState) renameIndex(oldName string, newName string) error {return nil}-func (t *tableState) changeColumnDefault(column *tidbast.ColumnDef) error {+func (t *tableState) changeColumnDefault(column *tidbast.ColumnDef) *WalkThroughError {columnName := column.Name.Name.OcolState, exists := t.columnSet[columnName]if !exists {@@ -503,7 +512,7 @@ func (t *tableState) changeColumnDefault(column *tidbast.ColumnDef) error {return nil}-func (s *schemaState) renameTable(oldName string, newName string) error {+func (s *schemaState) renameTable(oldName string, newName string) *WalkThroughError {if oldName == newName {return nil}@@ -529,7 +538,7 @@ func (s *schemaState) renameTable(oldName string, newName string) error {return nil}-func (t *tableState) renameColumn(oldName string, newName string) error {+func (t *tableState) renameColumn(oldName string, newName string) *WalkThroughError {if oldName == newName {return nil}@@ -576,7 +585,7 @@ func (t *tableState) renameColumnInIndexKey(oldName string, newName string) {// 1. drop column from tableState.columnSet, but do not drop column from indexSet.// 2. rename column from indexSet.// 3. create a new column in columnSet.-func (t *tableState) changeColumn(oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) error {+func (t *tableState) changeColumn(oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {column, exists := t.columnSet[oldName]if !exists {return NewColumnNotExistsError(t.name, oldName)@@ -617,7 +626,7 @@ func (t *tableState) changeColumn(oldName string, newColumn *tidbast.ColumnDef,return t.createColumn(newColumn, position)}-func (t *tableState) dropIndex(indexName string) error {+func (t *tableState) dropIndex(indexName string) *WalkThroughError {if _, exists := t.indexSet[indexName]; !exists {if indexName == PrimaryKeyName {return &WalkThroughError{@@ -632,7 +641,7 @@ func (t *tableState) dropIndex(indexName string) error {return nil}-func (t *tableState) dropColumn(columnName string) error {+func (t *tableState) dropColumn(columnName string) *WalkThroughError {column, exists := t.columnSet[columnName]if !exists {return NewColumnNotExistsError(t.name, columnName)@@ -679,7 +688,7 @@ func (idx *indexState) dropColumn(columnName string) {}// reorderColumn reorders the columns for new column and returns the new column position.-func (t *tableState) reorderColumn(position *tidbast.ColumnPosition) (int, error) {+func (t *tableState) reorderColumn(position *tidbast.ColumnPosition) (int, *WalkThroughError) {switch position.Tp {case tidbast.ColumnPositionNone:return len(t.columnSet) + 1, nil@@ -707,7 +716,7 @@ func (t *tableState) reorderColumn(position *tidbast.ColumnPosition) (int, error}}-func (d *databaseState) dropTable(node *tidbast.DropTableStmt) error {+func (d *databaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError {// TODO(rebelice): deal with DROP VIEW statement.if !node.IsView {for _, name := range node.Tables {@@ -739,8 +748,8 @@ func (d *databaseState) dropTable(node *tidbast.DropTableStmt) error {return nil}-func (d *databaseState) copyTable(node *tidbast.CreateTableStmt) error {- targetTable, err := d.findTable(node.ReferTable)+func (d *databaseState) copyTable(node *tidbast.CreateTableStmt) *WalkThroughError {+ targetTable, err := d.findTableState(node.ReferTable)if err != nil {return err}@@ -756,7 +765,7 @@ func (d *databaseState) copyTable(node *tidbast.CreateTableStmt) error {return nil}-func (d *databaseState) createTable(node *tidbast.CreateTableStmt) error {+func (d *databaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughError {if node.Table.Schema.O != "" && d.name != node.Table.Schema.O {return &WalkThroughError{Type: ErrorTypeAccessOtherDatabase,@@ -792,12 +801,14 @@ func (d *databaseState) createTable(node *tidbast.CreateTableStmt) error {for _, column := range node.Cols {if err := table.createColumn(column, nil); err != nil {+ err.Line = column.OriginTextPosition()return err}}for _, constraint := range node.Constraints {if err := table.createConstraint(constraint); err != nil {+ err.Line = constraint.OriginTextPosition()return err}}@@ -805,7 +816,7 @@ func (d *databaseState) createTable(node *tidbast.CreateTableStmt) error {return nil}-func (t *tableState) createConstraint(constraint *tidbast.Constraint) error {+func (t *tableState) createConstraint(constraint *tidbast.Constraint) *WalkThroughError {switch constraint.Tp {case tidbast.ConstraintPrimaryKey:keyList, err := t.validateAndGetKeyStringList(constraint.Keys, true /* primary */, false /* isSpatial */)@@ -848,7 +859,7 @@ func (t *tableState) createConstraint(constraint *tidbast.Constraint) error {return nil}-func (t *tableState) validateAndGetKeyStringList(keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, error) {+func (t *tableState) validateAndGetKeyStringList(keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, *WalkThroughError) {var res []stringfor _, key := range keyList {if key.Expr != nil {@@ -879,7 +890,7 @@ func (t *tableState) validateAndGetKeyStringList(keyList []*tidbast.IndexPartSpereturn res, nil}-func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.ColumnPosition) error {+func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {if _, exists := t.columnSet[column.Name.Name.O]; exists {return &WalkThroughError{Type: ErrorTypeColumnExists,@@ -889,7 +900,7 @@ func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.Cpos := len(t.columnSet) + 1if position != nil {- var err error+ var err *WalkThroughErrorpos, err = t.reorderColumn(position)if err != nil {return err@@ -958,7 +969,7 @@ func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.Creturn nil}-func (t *tableState) createIndex(name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) error {+func (t *tableState) createIndex(name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) *WalkThroughError {if len(keyList) == 0 {return &WalkThroughError{Type: ErrorTypeIndexEmptyKeys,@@ -1000,7 +1011,7 @@ func (t *tableState) createIndex(name string, keyList []string, unique bool, tpreturn nil}-func (t *tableState) createPrimaryKey(keys []string, tp string) error {+func (t *tableState) createPrimaryKey(keys []string, tp string) *WalkThroughError {if _, exists := t.indexSet[PrimaryKeyName]; exists {return &WalkThroughError{Type: ErrorTypePrimaryKeyExists,@@ -1033,7 +1044,7 @@ func (d *databaseState) createSchema(name string) *schemaState {return schema}-func (d *databaseState) parse(stmts string) ([]tidbast.StmtNode, error) {+func (d *databaseState) parse(stmts string) ([]tidbast.StmtNode, *WalkThroughError) {p := tidbparser.New()// To support MySQL8 window function syntax.// See https://github.com/bytebase/bytebase/issues/175.@@ -1063,7 +1074,7 @@ func (d *databaseState) parse(stmts string) ([]tidbast.StmtNode, error) {return nodeList, nil}-func restoreNode(node tidbast.Node, flag format.RestoreFlags) (string, error) {+func restoreNode(node tidbast.Node, flag format.RestoreFlags) (string, *WalkThroughError) {var buffer strings.Builderctx := format.NewRestoreCtx(flag, &buffer)if err := node.Restore(ctx); err != nil {diff --git a/plugin/advisor/catalog/walk_through_test.go b/plugin/advisor/catalog/walk_through_test.goindex 3bca51d320..5224fa6eb1 100644--- a/plugin/advisor/catalog/walk_through_test.go+++ b/plugin/advisor/catalog/walk_through_test.go@@ -441,6 +441,7 @@ func TestWalkThrough(t *testing.T) {err: &WalkThroughError{Type: ErrorTypeTableNotExists,Content: "Table `t1` does not exist",+ Line: 2,},},{@@ -498,13 +499,14 @@ func TestWalkThrough(t *testing.T) {Name: "test",DbType: db.MySQL,},- statement: `+ statement: `-- this is commentDROP DATABASE test;CREATE TABLE t(a int);`,err: &WalkThroughError{Type: ErrorTypeDatabaseIsDeleted,Content: "Database `test` is deleted",+ Line: 3,},},{diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex 49c5c1027a..cc09c13048 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -5,9 +5,10 @@ type Code int// Application error codes.const (- Ok Code = 0- Internal Code = 1- NotFound Code = 2+ Ok Code = 0+ Internal Code = 1+ NotFound Code = 2+ Unsupported Code = 3// 101 ~ 199 compatibility error code.CompatibilityDropDatabase Code = 101@@ -55,6 +56,8 @@ const (ColumnCommentTooLong Code = 409AutoIncrementColumnNotInteger Code = 410DisabledColumnType Code = 411+ ColumnExists Code = 412+ DropAllColumns Code = 413// 501 engine error code.NotInnoDBEngine Code = 501@@ -71,6 +74,7 @@ const (// 701 ~ 799 database advisor error code.DatabaseNotEmpty Code = 701NotCurrentDatabase Code = 702+ DatabaseIsDeleted Code = 703// 801 miss index error code.NotUseIndex Code = 801@@ -78,6 +82,12 @@ const (IndexPKType Code = 803IndexTypeNoBlob Code = 804IndexExists Code = 805+ PrimaryKeyExists Code = 806+ IndexEmptyKeys Code = 807+ PrimaryKeyNotExists Code = 808+ IndexNotExists Code = 809+ IncorrectIndexName Code = 810+ SpatialIndexKeyNullable Code = 811// 901 ~ 999 index error code.DuplicateColumnInIndex Code = 901diff --git a/plugin/advisor/mysql/advisor_column_disallow_changing_type.go b/plugin/advisor/mysql/advisor_column_disallow_changing_type.goindex 996a3f130a..2a84f8e3f3 100644--- a/plugin/advisor/mysql/advisor_column_disallow_changing_type.go+++ b/plugin/advisor/mysql/advisor_column_disallow_changing_type.go@@ -123,7 +123,7 @@ func getTypeString(tp *types.FieldType) string {}func (checker *columnDisallowChangingTypeChecker) changeColumnType(tableName string, columName string, newType string) bool {- column := checker.catalog.FindColumn(&catalog.ColumnFind{+ column := checker.catalog.Origin.FindColumn(&catalog.ColumnFind{TableName: tableName,ColumnName: columName,})diff --git a/plugin/advisor/mysql/advisor_column_exists.go b/plugin/advisor/mysql/advisor_column_exists.goindex 3926a06208..d798b098ed 100644--- a/plugin/advisor/mysql/advisor_column_exists.go+++ b/plugin/advisor/mysql/advisor_column_exists.go@@ -112,7 +112,7 @@ func (checker *columnExistsChecker) Enter(in ast.Node) (ast.Node, bool) {}for _, column := range columnList {- table := checker.catalog.FindTable(&catalog.TableFind{TableName: column.table})+ table := checker.catalog.Origin.FindTable(&catalog.TableFind{TableName: column.table})if table == nil {continue}diff --git a/plugin/advisor/mysql/advisor_database_drop_empty_db.go b/plugin/advisor/mysql/advisor_database_drop_empty_db.goindex 4f0bdf532b..4967ea9126 100644--- a/plugin/advisor/mysql/advisor_database_drop_empty_db.go+++ b/plugin/advisor/mysql/advisor_database_drop_empty_db.go@@ -66,15 +66,15 @@ type allowDropEmptyDBChecker struct {// Enter implements the ast.Visitor interface.func (v *allowDropEmptyDBChecker) Enter(in ast.Node) (ast.Node, bool) {if node, ok := in.(*ast.DropDatabaseStmt); ok {- if v.catalog.DatabaseName() != node.Name {+ if v.catalog.Origin.DatabaseName() != node.Name {v.adviceList = append(v.adviceList, advisor.Advice{Status: v.level,Code: advisor.NotCurrentDatabase,Title: v.title,- Content: fmt.Sprintf("Database `%s` that is trying to be deleted is not the current database `%s`", node.Name, v.catalog.DatabaseName()),+ Content: fmt.Sprintf("Database `%s` that is trying to be deleted is not the current database `%s`", node.Name, v.catalog.Origin.DatabaseName()),Line: node.OriginTextPosition(),})- } else if !v.catalog.HasNoTable() {+ } else if !v.catalog.Origin.HasNoTable() {v.adviceList = append(v.adviceList, advisor.Advice{Status: v.level,Code: advisor.DatabaseNotEmpty,diff --git a/plugin/advisor/mysql/advisor_index_not_exists.go b/plugin/advisor/mysql/advisor_index_not_exists.goindex 78a4355af3..f2fc69373e 100644--- a/plugin/advisor/mysql/advisor_index_not_exists.go+++ b/plugin/advisor/mysql/advisor_index_not_exists.go@@ -124,6 +124,6 @@ func (*indexNotExistsChecker) Leave(in ast.Node) (ast.Node, bool) {}func (checker *indexNotExistsChecker) indexExists(table string, index string) bool {- _, idx := checker.catalog.FindIndex(&catalog.IndexFind{TableName: table, IndexName: index})+ _, idx := checker.catalog.Origin.FindIndex(&catalog.IndexFind{TableName: table, IndexName: index})return idx != nil}diff --git a/plugin/advisor/mysql/advisor_index_pk_type.go b/plugin/advisor/mysql/advisor_index_pk_type.goindex 6cbb675850..142131d556 100644--- a/plugin/advisor/mysql/advisor_index_pk_type.go+++ b/plugin/advisor/mysql/advisor_index_pk_type.go@@ -224,7 +224,7 @@ func (v *indexPkTypeChecker) getPKColumnType(tableName string, columnName stringif colDef, ok := v.tablesNewColumns.get(tableName, columnName); ok {return v.getIntOrBigIntStr(colDef.Tp), nil}- column := v.catalog.FindColumn(&catalog.ColumnFind{+ column := v.catalog.Origin.FindColumn(&catalog.ColumnFind{TableName: tableName,ColumnName: columnName,})diff --git a/plugin/advisor/mysql/advisor_index_type_no_blob.go b/plugin/advisor/mysql/advisor_index_type_no_blob.goindex 68a9f2b9cf..b44ef6cba9 100644--- a/plugin/advisor/mysql/advisor_index_type_no_blob.go+++ b/plugin/advisor/mysql/advisor_index_type_no_blob.go@@ -220,7 +220,7 @@ func (v *indexTypeNoBlobChecker) getColumnType(tableName string, columnName striif colDef, ok := v.tablesNewColumns.get(tableName, columnName); ok {return v.getBlobStr(colDef.Tp), nil}- column := v.catalog.FindColumn(&catalog.ColumnFind{+ column := v.catalog.Origin.FindColumn(&catalog.ColumnFind{TableName: tableName,ColumnName: columnName,})diff --git a/plugin/advisor/mysql/advisor_naming_index_convention.go b/plugin/advisor/mysql/advisor_naming_index_convention.goindex 83a25ab80b..473a2186b4 100644--- a/plugin/advisor/mysql/advisor_naming_index_convention.go+++ b/plugin/advisor/mysql/advisor_naming_index_convention.go@@ -154,7 +154,7 @@ func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*indfor _, spec := range node.Specs {switch spec.Tp {case ast.AlterTableRenameIndex:- _, index := checker.catalog.FindIndex(&catalog.IndexFind{+ _, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{TableName: node.Table.Name.String(),IndexName: spec.FromKey.String(),})diff --git a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go b/plugin/advisor/mysql/advisor_naming_unique_key_convention.goindex 3d9fed3896..0fbffbd1bb 100644--- a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go+++ b/plugin/advisor/mysql/advisor_naming_unique_key_convention.go@@ -146,7 +146,7 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexMfor _, spec := range node.Specs {switch spec.Tp {case ast.AlterTableRenameIndex:- _, index := checker.catalog.FindIndex(&catalog.IndexFind{+ _, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{TableName: node.Table.Name.String(),IndexName: spec.FromKey.String(),})diff --git a/plugin/advisor/mysql/advisor_table_exists.go b/plugin/advisor/mysql/advisor_table_exists.goindex d6d12f827c..55e42a4e31 100644--- a/plugin/advisor/mysql/advisor_table_exists.go+++ b/plugin/advisor/mysql/advisor_table_exists.go@@ -80,13 +80,13 @@ func (checker *tableExistsChecker) Enter(in ast.Node) (ast.Node, bool) {case *ast.AlterTableStmt:tableList = append(tableList, node.Table.Name.O)case *ast.CreateTableStmt:- if node.ReferTable != nil && sameDatabase(node.ReferTable.Schema.O, checker.catalog.DatabaseName()) {+ if node.ReferTable != nil && sameDatabase(node.ReferTable.Schema.O, checker.catalog.Origin.DatabaseName()) {tableList = append(tableList, node.ReferTable.Name.O)}}for _, table := range tableList {- if checker.catalog.FindTable(&catalog.TableFind{TableName: table}) == nil {+ if checker.catalog.Origin.FindTable(&catalog.TableFind{TableName: table}) == nil {checker.adviceList = append(checker.adviceList, advisor.Advice{Status: checker.level,Code: advisor.TableNotExists,diff --git a/plugin/advisor/mysql/advisor_table_not_exists.go b/plugin/advisor/mysql/advisor_table_not_exists.goindex 0b007d9443..bd8f3ab83c 100644--- a/plugin/advisor/mysql/advisor_table_not_exists.go+++ b/plugin/advisor/mysql/advisor_table_not_exists.go@@ -92,5 +92,5 @@ func (*tableNotExistsChecker) Leave(in ast.Node) (ast.Node, bool) {}func (checker *tableNotExistsChecker) tableExists(table string) bool {- return checker.catalog.FindTable(&catalog.TableFind{TableName: table}) != nil+ return checker.catalog.Origin.FindTable(&catalog.TableFind{TableName: table}) != nil}diff --git a/plugin/advisor/mysql/advisor_table_require_pk.go b/plugin/advisor/mysql/advisor_table_require_pk.goindex dd790dd915..5f3d0035ed 100644--- a/plugin/advisor/mysql/advisor_table_require_pk.go+++ b/plugin/advisor/mysql/advisor_table_require_pk.go@@ -169,7 +169,7 @@ func (v *tableRequirePKChecker) createTable(node *ast.CreateTableStmt) {func (v *tableRequirePKChecker) dropColumn(table string, column string) bool {if _, ok := v.tables[table]; !ok {- _, pk := v.catalog.FindIndex(&catalog.IndexFind{+ _, pk := v.catalog.Origin.FindIndex(&catalog.IndexFind{TableName: table,IndexName: primaryKeyName,})diff --git a/plugin/advisor/mysql/parser.go b/plugin/advisor/mysql/parser.goindex 6998b300d3..7e3ea718b8 100644--- a/plugin/advisor/mysql/parser.go+++ b/plugin/advisor/mysql/parser.go@@ -2,6 +2,7 @@ package mysqlimport ("fmt"+ "strings"tidbparser "github.com/pingcap/tidb/parser""github.com/pingcap/tidb/parser/ast"@@ -65,6 +66,7 @@ func parseStatement(statement string, charset string, collation string) ([]ast.S}for i, node := range root {+ node.SetText(nil, strings.TrimSpace(node.Text()))node.SetOriginTextPosition(sqlList[i].Line)if n, ok := node.(*ast.CreateTableStmt); ok {if err := parser.SetLineForMySQLCreateTableStmt(n); err != nil {diff --git a/plugin/advisor/pg/advisor_column_no_null.go b/plugin/advisor/pg/advisor_column_no_null.goindex 6df9c4c82c..81f0e57295 100644--- a/plugin/advisor/pg/advisor_column_no_null.go+++ b/plugin/advisor/pg/advisor_column_no_null.go@@ -147,7 +147,7 @@ func (checker *columnNoNullChecker) removeColumnByConstraintList(table *ast.Tablchecker.removeColumn(table, column)}case ast.ConstraintTypePrimaryUsingIndex:- _, index := checker.catalog.FindIndex(&catalog.IndexFind{+ _, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{SchemaName: normalizeSchemaName(table.Schema),TableName: table.Name,IndexName: constraint.IndexName,diff --git a/plugin/advisor/pg/advisor_naming_index_convention.go b/plugin/advisor/pg/advisor_naming_index_convention.goindex 980739b3ab..7fd90559a7 100644--- a/plugin/advisor/pg/advisor_naming_index_convention.go+++ b/plugin/advisor/pg/advisor_naming_index_convention.go@@ -132,7 +132,7 @@ func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*ind})}case *ast.RenameIndexStmt:- tableName, index := checker.catalog.FindIndex(&catalog.IndexFind{+ tableName, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{SchemaName: normalizeSchemaName(node.Table.Schema),TableName: "",IndexName: node.IndexName,diff --git a/plugin/advisor/pg/advisor_naming_primary_key_convention.go b/plugin/advisor/pg/advisor_naming_primary_key_convention.goindex 7ddd1741c3..bffd6a6da3 100644--- a/plugin/advisor/pg/advisor_naming_primary_key_convention.go+++ b/plugin/advisor/pg/advisor_naming_primary_key_convention.go@@ -210,7 +210,7 @@ func (checker *namingPKConventionChecker) getPrimaryKeyMetadata(schemaName strin// findIndex returns index found in catalogs, nil if not found.func (checker *namingPKConventionChecker) findIndex(schemaName string, tableName string, indexName string) (string, *catalog.Index) {- return checker.catalog.FindIndex(&catalog.IndexFind{+ return checker.catalog.Origin.FindIndex(&catalog.IndexFind{SchemaName: normalizeSchemaName(schemaName),TableName: tableName,IndexName: indexName,diff --git a/plugin/advisor/pg/advisor_naming_unique_key_convention.go b/plugin/advisor/pg/advisor_naming_unique_key_convention.goindex 79b2e01892..724057808b 100644--- a/plugin/advisor/pg/advisor_naming_unique_key_convention.go+++ b/plugin/advisor/pg/advisor_naming_unique_key_convention.go@@ -227,7 +227,7 @@ func (checker *namingUKConventionChecker) getUniqueKeyMetadata(schemaName string// findIndex returns index found in catalogs, nil if not found.func (checker *namingUKConventionChecker) findIndex(schemaName string, tableName string, indexName string) (string, *catalog.Index) {- return checker.catalog.FindIndex(&catalog.IndexFind{+ return checker.catalog.Origin.FindIndex(&catalog.IndexFind{SchemaName: normalizeSchemaName(schemaName),TableName: tableName,IndexName: indexName,diff --git a/plugin/advisor/pg/advisor_table_require_pk.go b/plugin/advisor/pg/advisor_table_require_pk.goindex 16b1c24ae8..212dc6987e 100644--- a/plugin/advisor/pg/advisor_table_require_pk.go+++ b/plugin/advisor/pg/advisor_table_require_pk.go@@ -84,7 +84,7 @@ func (checker *tableRequirePKChecker) Visit(node ast.Node) ast.Visitor {}// DROP CONSTRAINTcase *ast.DropConstraintStmt:- _, index := checker.catalog.FindIndex(&catalog.IndexFind{+ _, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{SchemaName: normalizeSchemaName(n.Table.Schema),TableName: n.Table.Name,IndexName: n.ConstraintName,@@ -94,7 +94,7 @@ func (checker *tableRequirePKChecker) Visit(node ast.Node) ast.Visitor {}// DROP COLUMNcase *ast.DropColumnStmt:- pk := checker.catalog.FindPrimaryKey(&catalog.PrimaryKeyFind{+ pk := checker.catalog.Origin.FindPrimaryKey(&catalog.PrimaryKeyFind{SchemaName: normalizeSchemaName(n.Table.Schema),TableName: n.Table.Name,})diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex e16b09b2d8..fa78f83207 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -375,6 +375,14 @@ type SQLReviewCheckContext struct {func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext SQLReviewCheckContext) ([]Advice, error) {var result []Advice+ finder := checkContext.Catalog.GetFinder()+ switch checkContext.DbType {+ case db.TiDB, db.MySQL:+ if err := finder.WalkThrough(statements); err != nil {+ return convertWalkThroughErrorToAdvice(err)+ }+ }+for _, rule := range ruleList {if rule.Level == SchemaRuleLevelDisabled {continue@@ -393,7 +401,7 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext SCharset: checkContext.Charset,Collation: checkContext.Collation,Rule: rule,- Catalog: checkContext.Catalog.GetFinder(),+ Catalog: finder,},statements,)@@ -419,6 +427,154 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext Sreturn result, nil}+func convertWalkThroughErrorToAdvice(err error) ([]Advice, error) {+ walkThroughError, ok := err.(*catalog.WalkThroughError)+ if !ok {+ return nil, err+ }++ var res []Advice+ switch walkThroughError.Type {+ case catalog.ErrorTypeUnsupported:+ res = append(res, Advice{+ Status: Error,+ Code: Unsupported,+ Title: walkThroughError.Content,+ Content: "",+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeParseError:+ res = append(res, Advice{+ Status: Error,+ Code: StatementSyntaxError,+ Title: SyntaxErrorTitle,+ Content: walkThroughError.Content,+ })+ case catalog.ErrorTypeRestoreError:+ res = append(res, Advice{+ Status: Error,+ Code: Internal,+ Title: "Internal error for walk-through",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeAccessOtherDatabase:+ res = append(res, Advice{+ Status: Error,+ Code: NotCurrentDatabase,+ Title: "Access other database",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeDatabaseIsDeleted:+ res = append(res, Advice{+ Status: Error,+ Code: DatabaseIsDeleted,+ Title: "Access deleted database",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeTableExists:+ res = append(res, Advice{+ Status: Error,+ Code: TableExists,+ Title: "Table already exists",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeTableNotExists:+ res = append(res, Advice{+ Status: Error,+ Code: TableNotExists,+ Title: "Table does not exist",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeColumnExists:+ res = append(res, Advice{+ Status: Error,+ Code: ColumnExists,+ Title: "Column already exists",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeColumnNotExists:+ res = append(res, Advice{+ Status: Error,+ Code: ColumnNotExists,+ Title: "Column does not exist",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeDropAllColumns:+ res = append(res, Advice{+ Status: Error,+ Code: DropAllColumns,+ Title: "Drop all columns",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypePrimaryKeyExists:+ res = append(res, Advice{+ Status: Error,+ Code: PrimaryKeyExists,+ Title: "Primary key exists",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeIndexExists:+ res = append(res, Advice{+ Status: Error,+ Code: IndexExists,+ Title: "Index exists",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeIndexEmptyKeys:+ res = append(res, Advice{+ Status: Error,+ Code: IndexEmptyKeys,+ Title: "Index empty keys",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypePrimaryKeyNotExists:+ res = append(res, Advice{+ Status: Error,+ Code: PrimaryKeyNotExists,+ Title: "Primary key does not exist",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeIndexNotExists:+ res = append(res, Advice{+ Status: Error,+ Code: IndexNotExists,+ Title: "Index does not exist",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeIncorrectIndexName:+ res = append(res, Advice{+ Status: Error,+ Code: IncorrectIndexName,+ Title: "Incorrect index name",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ case catalog.ErrorTypeSpatialIndexKeyNullable:+ res = append(res, Advice{+ Status: Error,+ Code: SpatialIndexKeyNullable,+ Title: "Spatial index key must be NOT NULL",+ Content: walkThroughError.Content,+ Line: walkThroughError.Line,+ })+ }++ return res, nil+}+func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, error) {switch ruleType {case SchemaRuleStatementRequireWhere:diff --git a/tests/sql_review_test.go b/tests/sql_review_test.goindex b4dddf96a9..97088895c9 100644--- a/tests/sql_review_test.go+++ b/tests/sql_review_test.go@@ -586,7 +586,17 @@ func TestSQLReviewForMySQL(t *testing.T) {},},{- statement: "DROP TABLE user",+ statement: `+ CREATE TABLE user(+ 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)+ );+ DROP TABLE user;+ `,result: []api.TaskCheckResult{{Status: api.TaskCheckStatusError,@@ -600,7 +610,7 @@ func TestSQLReviewForMySQL(t *testing.T) {Namespace: api.AdvisorNamespace,Code: advisor.CompatibilityDropTable.Int(),Title: "schema.backward-compatibility",- Content: "\"DROP TABLE user\" may cause incompatibility with the existing data and code",+ Content: "\"DROP TABLE user;\" may cause incompatibility with the existing data and code",},},},