Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: add accessor methods to catalog package state (#18096)
Danny Xu3544aff1e7b7
diff --git a/backend/plugin/advisor/catalog/state.go b/backend/plugin/advisor/catalog/state.goindex 10e7948f49..a2f8d8e459 100644--- a/backend/plugin/advisor/catalog/state.go+++ b/backend/plugin/advisor/catalog/state.go@@ -575,27 +575,27 @@ type ViewState struct {type viewStateMap map[string]*ViewStatefunc copyStringPointer(p *string) *string {- if p != nil {- v := *p- return &v+ if p == nil {+ return nil}- return nil+ v := *p+ return &v}func copyBoolPointer(p *bool) *bool {- if p != nil {- v := *p- return &v+ if p == nil {+ return nil}- return nil+ v := *p+ return &v}func copyIntPointer(p *int) *int {- if p != nil {- v := *p- return &v+ if p == nil {+ return nil}- return nil+ v := *p+ return &v}func copyStringSlice(in []string) []string {@@ -630,3 +630,598 @@ func newFalsePointer() *bool {func newBoolPointer(v bool) *bool {return &v}++// Schema-level operations.++// createSchemaState creates a new schema state with the given name.+func (d *DatabaseState) createSchemaState(schemaName string) *SchemaState {+ schema := &SchemaState{+ ctx: d.ctx.Copy(),+ name: schemaName,+ tableSet: make(tableStateMap),+ viewSet: make(viewStateMap),+ identifierMap: make(identifierMap),+ }+ d.schemaSet[schemaName] = schema+ return schema+}++// GetOrCreateSchema gets an existing schema or creates a new one if it doesn't exist.+func (d *DatabaseState) GetOrCreateSchema(schemaName string) *SchemaState {+ if schema, exists := d.schemaSet[schemaName]; exists {+ return schema+ }+ return d.createSchemaState(schemaName)+}++// GetSchema gets an existing schema.+//+//nolint:revive+func (d *DatabaseState) GetSchema(schemaName string) (*SchemaState, *WalkThroughError) {+ if schemaName == "" {+ schemaName = publicSchemaName+ }+ if schema, exists := d.schemaSet[schemaName]; exists {+ return schema, nil+ }+ if schemaName != publicSchemaName {+ return nil, &WalkThroughError{+ Type: ErrorTypeSchemaNotExists,+ Content: fmt.Sprintf("The schema %q doesn't exist", schemaName),+ }+ }+ return d.createSchemaState(publicSchemaName), nil+}++// DropSchema drops a schema.+func (d *DatabaseState) DropSchema(schemaName string) *WalkThroughError {+ schema, exists := d.schemaSet[schemaName]+ if !exists {+ return &WalkThroughError{+ Type: ErrorTypeSchemaNotExists,+ Content: fmt.Sprintf("Schema %q does not exist", schemaName),+ }+ }++ // Delete all identifiers in this schema+ for tableName := range schema.tableSet {+ delete(schema.identifierMap, tableName)+ }+ for viewName := range schema.viewSet {+ delete(schema.identifierMap, viewName)+ }++ // Delete the schema+ delete(d.schemaSet, schemaName)+ return nil+}++// Table-level operations.++// CreateTable creates a new table in the schema.+func (s *SchemaState) CreateTable(tableName string) (*TableState, *WalkThroughError) {+ if _, exists := s.getTable(tableName); exists {+ return nil, NewTableExistsError(tableName)+ }++ table := &TableState{+ name: tableName,+ engine: newEmptyStringPointer(),+ collation: newEmptyStringPointer(),+ comment: newEmptyStringPointer(),+ columnSet: make(columnStateMap),+ indexSet: make(IndexStateMap),+ dependencyView: make(map[string]bool),+ }+ s.tableSet[tableName] = table++ // For PostgreSQL, track in identifier map+ if s.identifierMap != nil {+ s.identifierMap[tableName] = true+ }++ return table, nil+}++// GetTable gets a table from the schema.+//+//nolint:revive+func (s *SchemaState) GetTable(tableName string) (*TableState, *WalkThroughError) {+ table, exists := s.tableSet[tableName]+ if !exists {+ return nil, &WalkThroughError{+ Type: ErrorTypeTableNotExists,+ Content: fmt.Sprintf("The table %q does not exist in schema %q", tableName, s.name),+ }+ }+ return table, nil+}++// DropTable drops a table from the schema.+func (s *SchemaState) DropTable(tableName string, checkViewDependency func(*TableState) ([]string, *WalkThroughError)) *WalkThroughError {+ table, err := s.GetTable(tableName)+ if err != nil {+ return err+ }++ // Check for view dependencies if checker is provided+ if checkViewDependency != nil {+ viewList, err := checkViewDependency(table)+ if err != nil {+ return err+ }+ if len(viewList) > 0 {+ return &WalkThroughError{+ Type: ErrorTypeTableIsReferencedByView,+ Content: fmt.Sprintf("Cannot drop table %q.%q, it's referenced by view: %s", s.name, table.name, strings.Join(viewList, ", ")),+ Payload: viewList,+ }+ }+ }++ // Delete all indexes associated with the table (for PostgreSQL identifier map)+ if s.identifierMap != nil {+ for indexName := range table.indexSet {+ delete(s.identifierMap, indexName)+ }+ delete(s.identifierMap, table.name)+ }++ delete(s.tableSet, tableName)+ return nil+}++// RenameTable renames a table in the schema.+//+//nolint:revive+func (s *SchemaState) RenameTable(oldName string, newName string) *WalkThroughError {+ if oldName == newName {+ return nil+ }++ table, exists := s.getTable(oldName)+ if !exists {+ if s.ctx.CheckIntegrity {+ return NewTableNotExistsError(oldName)+ }+ table = s.createIncompleteTable(oldName)+ }++ if _, exists := s.getTable(newName); exists {+ return NewTableExistsError(newName)+ }++ // For PostgreSQL, update identifier map+ if s.identifierMap != nil {+ if _, exists := s.identifierMap[newName]; exists {+ return NewRelationExistsError(newName, s.name)+ }+ delete(s.identifierMap, table.name)+ s.identifierMap[newName] = true+ }++ table.name = newName+ delete(s.tableSet, oldName)+ s.tableSet[newName] = table+ return nil+}++// Column-level operations.++// CreateColumn creates a new column in the table.+//+//nolint:revive+func (t *TableState) CreateColumn(columnName string, columnType *string, nullable *bool, defaultValue *string, position *int, characterSet *string, collation *string, comment *string) *WalkThroughError {+ if _, exists := t.columnSet[strings.ToLower(columnName)]; exists {+ return &WalkThroughError{+ Type: ErrorTypeColumnExists,+ Content: fmt.Sprintf("Column `%s` already exists in table `%s`", columnName, t.name),+ }+ }++ pos := len(t.columnSet) + 1+ if position != nil {+ pos = *position+ }++ col := &ColumnState{+ name: columnName,+ position: &pos,+ defaultValue: defaultValue,+ nullable: nullable,+ columnType: columnType,+ characterSet: characterSet,+ collation: collation,+ comment: comment,+ dependencyView: make(map[string]bool),+ }+ t.columnSet[strings.ToLower(columnName)] = col+ return nil+}++// GetColumn gets a column from the table.+//+//nolint:revive+func (t *TableState) GetColumn(columnName string) (*ColumnState, *WalkThroughError) {+ column, exists := t.columnSet[strings.ToLower(columnName)]+ if !exists {+ return nil, NewColumnNotExistsError(t.name, columnName)+ }+ return column, nil+}++// DropColumn drops a column from the table.+//+//nolint:revive+func (t *TableState) DropColumn(columnName string, checkIntegrity bool, checkViewDependency func(*ColumnState) ([]string, *WalkThroughError)) *WalkThroughError {+ column, exists := t.columnSet[strings.ToLower(columnName)]+ if !exists {+ if checkIntegrity {+ return NewColumnNotExistsError(t.name, columnName)+ }+ return nil+ }++ // Check integrity mode requirements+ if checkIntegrity {+ // Cannot drop all columns in a table using ALTER TABLE DROP COLUMN.+ if len(t.columnSet) == 1 {+ return &WalkThroughError{+ Type: ErrorTypeDropAllColumns,+ Content: fmt.Sprintf("Can't delete all columns with ALTER TABLE; use DROP TABLE %s instead", t.name),+ }+ }++ // Check for view dependencies if checker is provided+ if checkViewDependency != nil {+ viewList, err := checkViewDependency(column)+ if err != nil {+ return err+ }+ if len(viewList) > 0 {+ return &WalkThroughError{+ Type: ErrorTypeColumnIsReferencedByView,+ Content: fmt.Sprintf("Cannot drop column %q in table %q, it's referenced by view: %s", column.name, t.name, strings.Join(viewList, ", ")),+ Payload: viewList,+ }+ }+ }++ // Modify the column position+ for _, col := range t.columnSet {+ if *col.position > *column.position {+ *col.position--+ }+ }+ }++ // Remove column from indexes, and drop indexes that become empty+ for _, index := range t.indexSet {+ // Remove the column from the index key list+ var newKeyList []string+ for _, key := range index.expressionList {+ if !strings.EqualFold(key, columnName) {+ newKeyList = append(newKeyList, key)+ }+ }+ index.expressionList = newKeyList++ // If all columns that make up an index are dropped, the index is dropped as well+ if len(index.expressionList) == 0 {+ delete(t.indexSet, strings.ToLower(index.name))+ }+ }++ delete(t.columnSet, strings.ToLower(columnName))+ return nil+}++// RenameColumn renames a column in the table.+//+//nolint:revive+func (t *TableState) RenameColumn(oldName string, newName string, checkIntegrity bool) *WalkThroughError {+ if strings.EqualFold(oldName, newName) {+ return nil+ }++ column, exists := t.columnSet[strings.ToLower(oldName)]+ if !exists {+ if checkIntegrity {+ return NewColumnNotExistsError(t.name, oldName)+ }+ column = t.createIncompleteColumn(oldName)+ }++ if _, exists := t.columnSet[strings.ToLower(newName)]; exists {+ return &WalkThroughError{+ Type: ErrorTypeColumnExists,+ Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newName, t.name),+ }+ }++ // Rename column in all indexes that reference it+ for _, index := range t.indexSet {+ for i, key := range index.expressionList {+ if strings.EqualFold(key, oldName) {+ index.expressionList[i] = newName+ }+ }+ }++ column.name = newName+ delete(t.columnSet, strings.ToLower(oldName))+ t.columnSet[strings.ToLower(newName)] = column+ return nil+}++// Index-level operations.++// CreateIndex creates a new index in the table.+//+//nolint:revive+func (t *TableState) CreateIndex(indexName string, expressionList []string, unique bool, indexType string, primary bool, visible *bool, comment *string, isConstraint bool, identifierMap identifierMap) *WalkThroughError {+ if len(expressionList) == 0 {+ return &WalkThroughError{+ Type: ErrorTypeIndexEmptyKeys,+ Content: fmt.Sprintf("Index `%s` in table `%s` has empty key", indexName, t.name),+ }+ }++ // Auto-generate name if empty+ if indexName == "" {+ suffix := 1+ baseName := expressionList[0]+ for {+ indexName = baseName+ if suffix > 1 {+ indexName = fmt.Sprintf("%s_%d", baseName, suffix)+ }+ if _, exists := t.indexSet[strings.ToLower(indexName)]; !exists {+ break+ }+ suffix+++ }+ } else {+ // Check if index already exists+ if _, exists := t.indexSet[strings.ToLower(indexName)]; exists {+ return NewIndexExistsError(t.name, indexName)+ }+ }++ // For PostgreSQL, check identifier map+ if identifierMap != nil {+ if _, exists := identifierMap[indexName]; exists {+ return NewRelationExistsError(indexName, "")+ }+ }++ if visible == nil {+ visible = newTruePointer()+ }+ if comment == nil {+ comment = newEmptyStringPointer()+ }++ index := &IndexState{+ name: indexName,+ expressionList: expressionList,+ indexType: &indexType,+ unique: &unique,+ primary: &primary,+ visible: visible,+ comment: comment,+ isConstraint: isConstraint,+ }+ t.indexSet[strings.ToLower(indexName)] = index++ // For PostgreSQL, track in identifier map+ if identifierMap != nil {+ identifierMap[indexName] = true+ }++ return nil+}++// CreatePrimaryKey creates a primary key index in the table.+//+//nolint:revive+func (t *TableState) CreatePrimaryKey(keyList []string, indexType string, identifierMap identifierMap) *WalkThroughError {+ pkName := PrimaryKeyName++ if _, exists := t.indexSet[strings.ToLower(pkName)]; exists {+ return &WalkThroughError{+ Type: ErrorTypePrimaryKeyExists,+ Content: fmt.Sprintf("Primary key exists in table `%s`", t.name),+ }+ }++ // For PostgreSQL, check identifier map+ if identifierMap != nil {+ if _, exists := identifierMap[pkName]; exists {+ return NewRelationExistsError(pkName, "")+ }+ }++ pk := &IndexState{+ name: pkName,+ expressionList: keyList,+ indexType: &indexType,+ unique: newTruePointer(),+ primary: newTruePointer(),+ visible: newTruePointer(),+ comment: newEmptyStringPointer(),+ isConstraint: true,+ }+ t.indexSet[strings.ToLower(pkName)] = pk++ // For PostgreSQL, track in identifier map+ if identifierMap != nil {+ identifierMap[pkName] = true+ }++ return nil+}++// GetIndex gets an index from the table.+func (t *TableState) GetIndex(indexName string) (*IndexState, *WalkThroughError) {+ index, exists := t.indexSet[strings.ToLower(indexName)]+ if !exists {+ return nil, NewIndexNotExistsError(t.name, indexName)+ }+ return index, nil+}++// DropIndex drops an index from the table.+//+//nolint:revive+func (t *TableState) DropIndex(indexName string, checkIntegrity bool, identifierMap identifierMap) *WalkThroughError {+ if checkIntegrity {+ if _, exists := t.indexSet[strings.ToLower(indexName)]; !exists {+ if strings.EqualFold(indexName, PrimaryKeyName) {+ return &WalkThroughError{+ Type: ErrorTypePrimaryKeyNotExists,+ Content: fmt.Sprintf("Primary key does not exist in table `%s`", t.name),+ }+ }+ return NewIndexNotExistsError(t.name, indexName)+ }+ }++ // For PostgreSQL, remove from identifier map+ if identifierMap != nil {+ delete(identifierMap, indexName)+ }++ delete(t.indexSet, strings.ToLower(indexName))+ return nil+}++// RenameIndex renames an index in the table.+//+//nolint:revive+func (t *TableState) RenameIndex(oldName string, newName string, checkIntegrity bool, identifierMap identifierMap) *WalkThroughError {+ // For MySQL, the primary key has a special name 'PRIMARY'.+ if strings.ToUpper(oldName) == PrimaryKeyName || strings.ToUpper(newName) == PrimaryKeyName {+ incorrectName := oldName+ if strings.ToUpper(oldName) != PrimaryKeyName {+ incorrectName = newName+ }+ return &WalkThroughError{+ Type: ErrorTypeIncorrectIndexName,+ Content: fmt.Sprintf("Incorrect index name `%s`", incorrectName),+ }+ }++ index, exists := t.indexSet[strings.ToLower(oldName)]+ if !exists {+ if checkIntegrity {+ return NewIndexNotExistsError(t.name, oldName)+ }+ index = t.createIncompleteIndex(oldName)+ }++ if _, exists := t.indexSet[strings.ToLower(newName)]; exists {+ return NewIndexExistsError(t.name, newName)+ }++ // For PostgreSQL, update identifier map+ if identifierMap != nil {+ if _, exists := identifierMap[newName]; exists {+ return NewRelationExistsError(newName, "")+ }+ delete(identifierMap, oldName)+ identifierMap[newName] = true+ }++ index.name = newName+ delete(t.indexSet, strings.ToLower(oldName))+ t.indexSet[strings.ToLower(newName)] = index+ return nil+}++// View-level operations.++// CreateView creates a new view in the schema.+func (s *SchemaState) CreateView(viewName string, definition *string, comment *string) (*ViewState, *WalkThroughError) {+ view := &ViewState{+ name: viewName,+ definition: definition,+ comment: comment,+ }+ s.viewSet[viewName] = view++ // For PostgreSQL, track in identifier map+ if s.identifierMap != nil {+ s.identifierMap[viewName] = true+ }++ return view, nil+}++// DropView drops a view from the schema.+func (s *SchemaState) DropView(viewName string, identifierMap identifierMap) *WalkThroughError {+ // For PostgreSQL, remove from identifier map+ if identifierMap != nil {+ delete(identifierMap, viewName)+ }++ delete(s.viewSet, viewName)+ return nil+}++// Database-level operations.++// MarkDeleted marks the database as deleted.+func (d *DatabaseState) MarkDeleted() {+ d.deleted = true+}++// IsDeleted returns true if the database is marked as deleted.+func (d *DatabaseState) IsDeleted() bool {+ return d.deleted+}++// SetCharacterSet sets the character set of the database.+func (d *DatabaseState) SetCharacterSet(characterSet string) {+ d.characterSet = characterSet+}++// SetCollation sets the collation of the database.+func (d *DatabaseState) SetCollation(collation string) {+ d.collation = collation+}++// SetTableEngine sets the engine of the table.+func (t *TableState) SetEngine(engine string) {+ t.engine = newStringPointer(engine)+}++// SetTableCollation sets the collation of the table.+func (t *TableState) SetCollation(collation string) {+ t.collation = newStringPointer(collation)+}++// SetTableComment sets the comment of the table.+func (t *TableState) SetComment(comment string) {+ t.comment = newStringPointer(comment)+}++// SetColumnNullable sets the nullable property of the column.+func (col *ColumnState) SetNullable(nullable bool) {+ col.nullable = newBoolPointer(nullable)+}++// SetColumnDefault sets the default value of the column.+func (col *ColumnState) SetDefault(defaultValue *string) {+ col.defaultValue = defaultValue+}++// SetColumnType sets the type of the column.+func (col *ColumnState) SetType(columnType string) {+ col.columnType = newStringPointer(columnType)+}++// SetIndexVisibility sets the visibility of the index.+func (idx *IndexState) SetVisibility(visible bool) {+ idx.visible = newBoolPointer(visible)+}diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.goindex fd19fb7bb1..c51dabe3db 100644--- a/backend/plugin/advisor/catalog/walk_through.go+++ b/backend/plugin/advisor/catalog/walk_through.go@@ -216,6 +216,8 @@ func (d *DatabaseState) isCurrentDatabase(database string) bool {// getTable returns the table with the given name if it exists in the schema.// TODO(zp): It's used for MySQL, we should refactor the package to make it more clear.+//+//nolint:revivefunc (s *SchemaState) getTable(table string) (*TableState, bool) {for k, v := range s.tableSet {if compareIdentifier(k, table, s.ctx.IgnoreCaseSensitive) {@@ -234,6 +236,7 @@ func (t *TableState) createIncompleteIndex(name string) *IndexState {return index}+//nolint:revivefunc (s *SchemaState) renameTable(ctx *FinderContext, oldName string, newName string) *WalkThroughError {if oldName == newName {return nil@@ -346,6 +349,7 @@ func (s *SchemaState) pgGeneratePrimaryKeyName(tableName string) string {}}+//nolint:revivefunc (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThroughError) {if schemaName == "" {schemaName = publicSchemaName@@ -370,6 +374,7 @@ func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThroughreturn schema, nil}+//nolint:revivefunc (t *TableState) getColumn(columnName string) (*ColumnState, *WalkThroughError) {column, exists := t.columnSet[columnName]if !exists {diff --git a/backend/plugin/advisor/catalog/walk_through_for_mysql.go b/backend/plugin/advisor/catalog/walk_through_for_mysql.goindex 11b9b6447f..a28e656bad 100644--- a/backend/plugin/advisor/catalog/walk_through_for_mysql.go+++ b/backend/plugin/advisor/catalog/walk_through_for_mysql.go@@ -17,9 +17,7 @@ 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.- if _, exists := d.schemaSet[""]; !exists {- d.createSchema()- }+ d.GetOrCreateSchema("")nodeList, ok := ast.([]*mysqlparser.ParseResult)if !ok {@@ -97,11 +95,8 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {return}- schema, exists := l.databaseState.schemaSet[""]- if !exists {- schema = l.databaseState.createSchema()- }- if _, exists = schema.getTable(tableName); exists {+ schema := l.databaseState.GetOrCreateSchema("")+ if _, exists := schema.getTable(tableName); exists {if ctx.IfNotExists() != nil {return}@@ -126,15 +121,11 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {return}- table := &TableState{- name: tableName,- engine: newEmptyStringPointer(),- collation: newEmptyStringPointer(),- comment: newEmptyStringPointer(),- columnSet: make(columnStateMap),- indexSet: make(IndexStateMap),+ table, err := schema.CreateTable(tableName)+ if err != nil {+ l.err = err+ return}- schema.tableSet[table.name] = tableif ctx.TableElementList() == nil {return@@ -194,10 +185,7 @@ func (l *mysqlListener) EnterDropTable(ctx *mysql.DropTableContext) {}}- schema, exists := l.databaseState.schemaSet[""]- if !exists {- schema = l.databaseState.createSchema()- }+ schema := l.databaseState.GetOrCreateSchema("")table, exists := schema.getTable(tableName)if !exists {@@ -211,7 +199,11 @@ func (l *mysqlListener) EnterDropTable(ctx *mysql.DropTableContext) {return}- delete(schema.tableSet, table.name)+ // MySQL doesn't check view dependencies for DROP TABLE, so pass nil+ if err := schema.DropTable(table.name, nil); err != nil {+ l.err = err+ return+ }}}@@ -251,15 +243,15 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {continue}engine := op.EngineRef().GetText()- table.engine = newStringPointer(engine)+ table.SetEngine(engine)// table comment.case op.COMMENT_SYMBOL() != nil && op.TextStringLiteral() != nil:comment := mysqlparser.NormalizeMySQLTextStringLiteral(op.TextStringLiteral())- table.comment = newStringPointer(comment)+ table.SetComment(comment)// table collation.case op.DefaultCollation() != nil && op.DefaultCollation().CollationName() != nil:collation := mysqlparser.NormalizeMySQLCollationName(op.DefaultCollation().CollationName())- table.collation = newStringPointer(collation)+ table.SetCollation(collation)default:}}@@ -311,20 +303,20 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {// drop column.case item.ColumnInternalRef() != nil:columnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())- if err := table.dropColumn(l.databaseState.ctx, columnName); err != nil {+ if err := table.DropColumn(columnName, l.databaseState.ctx.CheckIntegrity, nil); err != nil {l.err = errreturn}// drop primary key.case item.PRIMARY_SYMBOL() != nil && item.KEY_SYMBOL() != nil:- if err := table.dropIndex(l.databaseState.ctx, PrimaryKeyName); err != nil {+ if err := table.DropIndex(PrimaryKeyName, l.databaseState.ctx.CheckIntegrity, nil); err != nil {l.err = errreturn}// drop key/index.case item.KeyOrIndex() != nil && item.IndexRef() != nil:_, _, indexName := mysqlparser.NormalizeIndexRef(item.IndexRef())- if err := table.dropIndex(l.databaseState.ctx, indexName); err != nil {+ if err := table.DropIndex(indexName, l.databaseState.ctx.CheckIntegrity, nil); err != nil {l.err = errreturn}@@ -350,7 +342,7 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {case item.RENAME_SYMBOL() != nil && item.COLUMN_SYMBOL() != nil:oldColumnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())newColumnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())- if err := table.renameColumn(l.databaseState.ctx, oldColumnName, newColumnName); err != nil {+ if err := table.RenameColumn(oldColumnName, newColumnName, l.databaseState.ctx.CheckIntegrity); err != nil {l.err = errreturn}@@ -374,8 +366,8 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {// rename table.case item.RENAME_SYMBOL() != nil && item.TableName() != nil:_, newTableName := mysqlparser.NormalizeMySQLTableName(item.TableName())- schema := l.databaseState.schemaSet[""]- if err := schema.renameTable(l.databaseState.ctx, table.name, newTableName); err != nil {+ schema := l.databaseState.GetOrCreateSchema("")+ if err := schema.RenameTable(table.name, newTableName); err != nil {l.err = errreturn}@@ -383,7 +375,7 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {case item.RENAME_SYMBOL() != nil && item.KeyOrIndex() != nil && item.IndexRef() != nil && item.IndexName() != nil:_, _, oldIndexName := mysqlparser.NormalizeIndexRef(item.IndexRef())newIndexName := mysqlparser.NormalizeIndexName(item.IndexName())- if err := table.renameIndex(l.databaseState.ctx, oldIndexName, newIndexName); err != nil {+ if err := table.RenameIndex(oldIndexName, newIndexName, l.databaseState.ctx.CheckIntegrity, nil); err != nil {l.err = errreturn}@@ -413,7 +405,7 @@ func (l *mysqlListener) EnterDropIndex(ctx *mysql.DropIndexContext) {}_, _, indexName := mysqlparser.NormalizeIndexRef(ctx.IndexRef())- if err := table.dropIndex(l.databaseState.ctx, indexName); err != nil {+ if err := table.DropIndex(indexName, l.databaseState.ctx.CheckIntegrity, nil); err != nil {l.err = err}}@@ -497,10 +489,10 @@ func (l *mysqlListener) EnterAlterDatabase(ctx *mysql.AlterDatabaseContext) {switch {case option.CreateDatabaseOption().DefaultCharset() != nil && option.CreateDatabaseOption().DefaultCharset().CharsetName() != nil:charset := mysqlparser.NormalizeMySQLCharsetName(option.CreateDatabaseOption().DefaultCharset().CharsetName())- l.databaseState.characterSet = charset+ l.databaseState.SetCharacterSet(charset)case option.CreateDatabaseOption().DefaultCollation() != nil && option.CreateDatabaseOption().DefaultCollation().CollationName() != nil:collation := mysqlparser.NormalizeMySQLCollationName(option.CreateDatabaseOption().DefaultCollation().CollationName())- l.databaseState.collation = collation+ l.databaseState.SetCollation(collation)default:// Other options}@@ -522,7 +514,7 @@ func (l *mysqlListener) EnterDropDatabase(ctx *mysql.DropDatabaseContext) {return}- l.databaseState.deleted = true+ l.databaseState.MarkDeleted()}// EnterCreateDatabase is called when production createDatabase is entered.@@ -543,10 +535,7 @@ func (l *mysqlListener) EnterRenameTableStatement(ctx *mysql.RenameTableStatemenreturn}for _, pair := range ctx.AllRenamePair() {- schema, exists := l.databaseState.schemaSet[""]- if !exists {- schema = l.databaseState.createSchema()- }+ schema := l.databaseState.GetOrCreateSchema("")_, oldTableName := mysqlparser.NormalizeMySQLTableRef(pair.TableRef())_, newTableName := mysqlparser.NormalizeMySQLTableName(pair.TableName())@@ -849,7 +838,7 @@ func (d *DatabaseState) mysqlCopyTable(databaseName, tableName, referTable strinreturn err}- schema := d.schemaSet[""]+ schema := d.GetOrCreateSchema("")table := targetTable.copy()table.name = tableNameschema.tableSet[table.name] = table@@ -861,10 +850,7 @@ func (d *DatabaseState) mysqlFindTableState(databaseName, tableName string) (*Tareturn nil, NewAccessOtherDatabaseError(d.name, databaseName)}- schema, exists := d.schemaSet[""]- if !exists {- schema = d.createSchema()- }+ schema := d.GetOrCreateSchema("")table, exists := schema.getTable(tableName)if !exists {diff --git a/backend/plugin/advisor/catalog/walk_through_for_pg.go b/backend/plugin/advisor/catalog/walk_through_for_pg.goindex 4b81c485e4..b91ca418dc 100644--- a/backend/plugin/advisor/catalog/walk_through_for_pg.go+++ b/backend/plugin/advisor/catalog/walk_through_for_pg.go@@ -67,7 +67,7 @@ func (l *pgCatalogListener) setError(err *WalkThroughError) {// Helper method to check if database is deletedfunc (l *pgCatalogListener) checkDatabaseNotDeleted() bool {- if l.databaseState.deleted {+ if l.databaseState.IsDeleted() {l.setError(&WalkThroughError{Type: ErrorTypeDatabaseIsDeleted,Content: fmt.Sprintf(`Database %q is deleted`, l.databaseState.name),diff --git a/backend/plugin/advisor/catalog/walk_through_for_tidb.go b/backend/plugin/advisor/catalog/walk_through_for_tidb.goindex 29da7d52bd..b87012e6ae 100644--- a/backend/plugin/advisor/catalog/walk_through_for_tidb.go+++ b/backend/plugin/advisor/catalog/walk_through_for_tidb.go@@ -15,9 +15,7 @@ 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.- if _, exists := d.schemaSet[""]; !exists {- d.createSchema()- }+ d.GetOrCreateSchema("")nodeList, ok := ast.([]tidbast.StmtNode)if !ok {@@ -188,7 +186,7 @@ func (d *DatabaseState) dropIndex(node *tidbast.DropIndexStmt) *WalkThroughErrorreturn err}- return table.dropIndex(d.ctx, node.IndexName)+ return table.DropIndex(node.IndexName, d.ctx.CheckIntegrity, nil)}func (d *DatabaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughError {@@ -264,15 +262,15 @@ func (d *DatabaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughErrreturn err}case tidbast.AlterTableDropColumn:- if err := table.dropColumn(d.ctx, spec.OldColumnName.Name.O); err != nil {+ if err := table.DropColumn(spec.OldColumnName.Name.O, d.ctx.CheckIntegrity, nil); err != nil {return err}case tidbast.AlterTableDropPrimaryKey:- if err := table.dropIndex(d.ctx, PrimaryKeyName); err != nil {+ if err := table.DropIndex(PrimaryKeyName, d.ctx.CheckIntegrity, nil); err != nil {return err}case tidbast.AlterTableDropIndex:- if err := table.dropIndex(d.ctx, spec.Name); err != nil {+ if err := table.DropIndex(spec.Name, d.ctx.CheckIntegrity, nil); err != nil {return err}case tidbast.AlterTableDropForeignKey:@@ -286,7 +284,7 @@ func (d *DatabaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughErrreturn err}case tidbast.AlterTableRenameColumn:- if err := table.renameColumn(d.ctx, spec.OldColumnName.Name.O, spec.NewColumnName.Name.O); err != nil {+ if err := table.RenameColumn(spec.OldColumnName.Name.O, spec.NewColumnName.Name.O, d.ctx.CheckIntegrity); err != nil {return err}case tidbast.AlterTableRenameTable:@@ -299,7 +297,7 @@ func (d *DatabaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughErrreturn err}case tidbast.AlterTableRenameIndex:- if err := table.renameIndex(d.ctx, spec.FromKey.O, spec.ToKey.O); err != nil {+ if err := table.RenameIndex(spec.FromKey.O, spec.ToKey.O, d.ctx.CheckIntegrity, nil); err != nil {return err}case tidbast.AlterTableIndexInvisible:@@ -333,38 +331,6 @@ func (t *TableState) changeIndexVisibility(ctx *FinderContext, indexName string,return nil}-func (t *TableState) renameIndex(ctx *FinderContext, oldName string, newName string) *WalkThroughError {- // For MySQL, the primary key has a special name 'PRIMARY'.- // And the other indexes cannot use the name which case-insensitive equals 'PRIMARY'.- if strings.ToUpper(oldName) == PrimaryKeyName || strings.ToUpper(newName) == PrimaryKeyName {- incorrectName := oldName- if strings.ToUpper(oldName) != PrimaryKeyName {- incorrectName = newName- }- return &WalkThroughError{- Type: ErrorTypeIncorrectIndexName,- Content: fmt.Sprintf("Incorrect index name `%s`", incorrectName),- }- }-- index, exists := t.indexSet[strings.ToLower(oldName)]- if !exists {- if ctx.CheckIntegrity {- return NewIndexNotExistsError(t.name, oldName)- }- index = t.createIncompleteIndex(oldName)- }-- if _, exists := t.indexSet[strings.ToLower(newName)]; exists {- return NewIndexExistsError(t.name, newName)- }-- index.name = newName- delete(t.indexSet, strings.ToLower(oldName))- t.indexSet[strings.ToLower(newName)] = index- return nil-}-func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.ColumnDef) *WalkThroughError {columnName := column.Name.Name.LcolState, exists := t.columnSet[columnName]@@ -416,34 +382,6 @@ func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.Colreturn nil}-func (t *TableState) renameColumn(ctx *FinderContext, oldName string, newName string) *WalkThroughError {- if strings.EqualFold(oldName, newName) {- return nil- }-- column, exists := t.columnSet[strings.ToLower(oldName)]- if !exists {- if ctx.CheckIntegrity {- return NewColumnNotExistsError(t.name, oldName)- }- column = t.createIncompleteColumn(oldName)- }-- if _, exists := t.columnSet[strings.ToLower(newName)]; exists {- return &WalkThroughError{- Type: ErrorTypeColumnExists,- Content: fmt.Sprintf("Column `%s` already exists in table `%s", newName, t.name),- }- }-- column.name = newName- delete(t.columnSet, strings.ToLower(oldName))- t.columnSet[strings.ToLower(newName)] = column-- t.renameColumnInIndexKey(oldName, newName)- return nil-}-func (t *TableState) renameColumnInIndexKey(oldName string, newName string) {if strings.EqualFold(oldName, newName) {return@@ -532,96 +470,6 @@ func (t *TableState) changeColumn(ctx *FinderContext, oldName string, newColumnreturn t.incompleteTableChangeColumn(ctx, oldName, newColumn, position)}-func (t *TableState) dropIndex(ctx *FinderContext, indexName string) *WalkThroughError {- if ctx.CheckIntegrity {- if _, exists := t.indexSet[strings.ToLower(indexName)]; !exists {- if strings.EqualFold(indexName, PrimaryKeyName) {- return &WalkThroughError{- Type: ErrorTypePrimaryKeyNotExists,- Content: fmt.Sprintf("Primary key does not exist in table `%s`", t.name),- }- }- return NewIndexNotExistsError(t.name, indexName)- }- }-- delete(t.indexSet, strings.ToLower(indexName))- return nil-}--func (t *TableState) completeTableDropColumn(columnName string) *WalkThroughError {- column, exists := t.columnSet[strings.ToLower(columnName)]- if !exists {- return NewColumnNotExistsError(t.name, columnName)- }-- // Cannot drop all columns in a table using ALTER TABLE DROP COLUMN.- if len(t.columnSet) == 1 {- return &WalkThroughError{- Type: ErrorTypeDropAllColumns,- // Error content comes from MySQL error content.- Content: fmt.Sprintf("Can't delete all columns with ALTER TABLE; use DROP TABLE %s instead", t.name),- }- }-- // If columns are dropped from a table, the columns are also removed from any index of which they are a part.- for _, index := range t.indexSet {- index.dropColumn(columnName)- // If all columns that make up an index are dropped, the index is dropped as well.- if len(index.expressionList) == 0 {- delete(t.indexSet, strings.ToLower(index.name))- }- }-- // modify the column position- for _, col := range t.columnSet {- if *col.position > *column.position {- *col.position--- }- }-- delete(t.columnSet, strings.ToLower(columnName))- return nil-}--func (t *TableState) incompleteTableDropColumn(columnName string) *WalkThroughError {- // If columns are dropped from a table, the columns are also removed from any index of which they are a part.- for _, index := range t.indexSet {- if len(index.expressionList) == 0 {- continue- }- index.dropColumn(columnName)- // If all columns that make up an index are dropped, the index is dropped as well.- if len(index.expressionList) == 0 {- delete(t.indexSet, strings.ToLower(index.name))- }- }-- delete(t.columnSet, strings.ToLower(columnName))- return nil-}--func (t *TableState) dropColumn(ctx *FinderContext, columnName string) *WalkThroughError {- if ctx.CheckIntegrity {- return t.completeTableDropColumn(columnName)- }- return t.incompleteTableDropColumn(columnName)-}--func (idx *IndexState) dropColumn(columnName string) {- if len(idx.expressionList) == 0 {- return- }- var newKeyList []string- for _, key := range idx.expressionList {- if !strings.EqualFold(key, columnName) {- newKeyList = append(newKeyList, key)- }- }-- idx.expressionList = newKeyList-}-// reorderColumn reorders the columns for new column and returns the new column position.func (t *TableState) reorderColumn(position *tidbast.ColumnPosition) (int, *WalkThroughError) {switch position.Tp {@@ -890,6 +738,7 @@ func checkDefault(columnName string, columnType *types.FieldType, value tidbast.return nil}+//nolint:revivefunc (t *TableState) createColumn(ctx *FinderContext, column *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {if _, exists := t.columnSet[column.Name.Name.L]; exists {return &WalkThroughError{@@ -996,6 +845,7 @@ func (t *TableState) createColumn(ctx *FinderContext, column *tidbast.ColumnDef,return nil}+//nolint:revivefunc (t *TableState) createIndex(name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) *WalkThroughError {if len(keyList) == 0 {return &WalkThroughError{@@ -1039,6 +889,7 @@ func (t *TableState) createIndex(name string, keyList []string, unique bool, tpreturn nil}+//nolint:revivefunc (t *TableState) createPrimaryKey(keys []string, tp string) *WalkThroughError {if _, exists := t.indexSet[strings.ToLower(PrimaryKeyName)]; exists {return &WalkThroughError{