Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(catalog): refactor walk through to support incomplete state (#2766)

rebelicef03cf2840ad2
diff --git a/plugin/advisor/catalog/finder.go b/plugin/advisor/catalog/finder.go
index b4374c44c6..cdc8522393 100644
--- a/plugin/advisor/catalog/finder.go
+++ b/plugin/advisor/catalog/finder.go
@@ -29,22 +29,21 @@ func (ctx *FinderContext) Copy() *FinderContext {
// Finder is the service for finding schema information in database.
type Finder struct {
- Origin *databaseState
- Final *databaseState
+ Origin *DatabaseState
+ Final *DatabaseState
}
// NewFinder creates a new finder.
-func NewFinder(database *Database, context *FinderContext) *Finder {
- return &Finder{Origin: newDatabaseState(database, context)}
+func NewFinder(database *Database, ctx *FinderContext) *Finder {
+ return &Finder{Origin: newDatabaseState(database, ctx), Final: newDatabaseState(database, ctx)}
}
// NewEmptyFinder creates a finder with empty databse.
func NewEmptyFinder(ctx *FinderContext, dbType db.Type) *Finder {
- return &Finder{Origin: newDatabaseState(&Database{DbType: dbType}, ctx)}
+ return &Finder{Origin: newDatabaseState(&Database{DbType: dbType}, ctx), Final: newDatabaseState(&Database{DbType: dbType}, ctx)}
}
// 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.go
index 9083232327..86d2f8cc79 100644
--- a/plugin/advisor/catalog/state.go
+++ b/plugin/advisor/catalog/state.go
@@ -8,30 +8,30 @@ import (
"github.com/bytebase/bytebase/plugin/advisor/db"
)
-func newDatabaseState(d *Database, context *FinderContext) *databaseState {
- database := &databaseState{
+func newDatabaseState(d *Database, context *FinderContext) *DatabaseState {
+ database := &DatabaseState{
+ ctx: context.Copy(),
name: d.Name,
characterSet: d.CharacterSet,
collation: d.Collation,
dbType: d.DbType,
schemaSet: make(schemaStateMap),
- context: context.Copy(),
}
for _, schema := range d.SchemaList {
- database.schemaSet[schema.Name] = newSchemaState(schema, context)
+ database.schemaSet[schema.Name] = newSchemaState(schema, database.ctx)
}
return database
}
-func newSchemaState(s *Schema, context *FinderContext) *schemaState {
- schema := &schemaState{
+func newSchemaState(s *Schema, context *FinderContext) *SchemaState {
+ schema := &SchemaState{
+ ctx: context.Copy(),
name: s.Name,
tableSet: make(tableStateMap),
viewSet: make(viewStateMap),
extensionSet: make(extensionStateMap),
- context: context.Copy(),
}
for _, table := range s.TableList {
@@ -49,36 +49,31 @@ func newSchemaState(s *Schema, context *FinderContext) *schemaState {
return schema
}
-func newViewState(v *View) *viewState {
- return &viewState{
+func newViewState(v *View) *ViewState {
+ return &ViewState{
name: v.Name,
- definition: v.Definition,
- comment: v.Comment,
+ definition: newStringPointer(v.Definition),
+ comment: newStringPointer(v.Comment),
}
}
-func newExtensionState(e *Extension) *extensionState {
- return &extensionState{
+func newExtensionState(e *Extension) *ExtensionState {
+ return &ExtensionState{
name: e.Name,
- version: e.Version,
- description: e.Description,
+ version: newStringPointer(e.Version),
+ description: newStringPointer(e.Description),
}
}
-func newTableState(t *Table) *tableState {
- table := &tableState{
- name: t.Name,
- tableType: t.Type,
- engine: t.Engine,
- collation: t.Collation,
- rowCount: t.RowCount,
- dataSize: t.DataSize,
- indexSize: t.IndexSize,
- dataFree: t.DataFree,
- createOptions: t.CreateOptions,
- comment: t.Comment,
- columnSet: make(columnStateMap),
- indexSet: make(indexStateMap),
+func newTableState(t *Table) *TableState {
+ table := &TableState{
+ name: t.Name,
+ tableType: newStringPointer(t.Type),
+ engine: newStringPointer(t.Engine),
+ collation: newStringPointer(t.Collation),
+ comment: newStringPointer(t.Comment),
+ columnSet: make(columnStateMap),
+ indexSet: make(indexStateMap),
}
for _, column := range t.ColumnList {
@@ -92,45 +87,45 @@ func newTableState(t *Table) *tableState {
return table
}
-func newColumnState(c *Column) *columnState {
- return &columnState{
+func newColumnState(c *Column) *ColumnState {
+ return &ColumnState{
name: c.Name,
- position: c.Position,
- defaultValue: c.Default,
- nullable: c.Nullable,
- columnType: c.Type,
- characterSet: c.CharacterSet,
- collation: c.Collation,
- comment: c.Comment,
- }
-}
-
-func newIndexState(i *Index) *indexState {
- index := &indexState{
- name: i.Name,
- indextype: i.Type,
- unique: i.Unique,
- primary: i.Primary,
- visible: i.Visible,
- comment: i.Comment,
- }
- index.expressionList = append(index.expressionList, i.ExpressionList...)
+ position: newIntPointer(c.Position),
+ defaultValue: copyStringPointer(c.Default),
+ nullable: newBoolPointer(c.Nullable),
+ columnType: newStringPointer(c.Type),
+ characterSet: newStringPointer(c.CharacterSet),
+ collation: newStringPointer(c.Collation),
+ comment: newStringPointer(c.Comment),
+ }
+}
+
+func newIndexState(i *Index) *IndexState {
+ index := &IndexState{
+ name: i.Name,
+ indextype: newStringPointer(i.Type),
+ unique: newBoolPointer(i.Unique),
+ primary: newBoolPointer(i.Primary),
+ visible: newBoolPointer(i.Visible),
+ comment: newStringPointer(i.Comment),
+ expressionList: copyStringSlice(i.ExpressionList),
+ }
return index
}
-type databaseState struct {
+// DatabaseState is the state for walk-through.
+type DatabaseState struct {
+ ctx *FinderContext
name string
characterSet string
collation string
dbType db.Type
schemaSet schemaStateMap
deleted bool
-
- context *FinderContext
}
// HasNoTable returns true if the current database has no table.
-func (d *databaseState) HasNoTable() bool {
+func (d *DatabaseState) HasNoTable() bool {
for _, schema := range d.schemaSet {
if len(schema.tableSet) != 0 {
return false
@@ -141,7 +136,7 @@ func (d *databaseState) HasNoTable() bool {
}
// DatabaseName returns the database name.
-func (d *databaseState) DatabaseName() string {
+func (d *DatabaseState) DatabaseName() string {
return d.name
}
@@ -152,7 +147,8 @@ type IndexFind struct {
IndexName string
}
-func (d *databaseState) FindIndex(find *IndexFind) (string, *Index) {
+// FindIndex finds the index.
+func (d *DatabaseState) FindIndex(find *IndexFind) (string, *IndexState) {
// 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.
@@ -173,7 +169,7 @@ func (d *databaseState) FindIndex(find *IndexFind) (string, *Index) {
if !exists {
return "", nil
}
- return table.name, index.convertToCatalog()
+ return table.name, index
}
for _, schema := range d.schemaSet {
if schema.name != find.SchemaName {
@@ -185,7 +181,7 @@ func (d *databaseState) FindIndex(find *IndexFind) (string, *Index) {
if !exists {
return "", nil
}
- return table.name, index.convertToCatalog()
+ return table.name, index
}
}
return "", nil
@@ -198,7 +194,7 @@ type PrimaryKeyFind struct {
}
// FindPrimaryKey finds the primary key.
-func (d *databaseState) FindPrimaryKey(find *PrimaryKeyFind) *Index {
+func (d *DatabaseState) FindPrimaryKey(find *PrimaryKeyFind) *IndexState {
for _, schema := range d.schemaSet {
if schema.name != find.SchemaName {
continue
@@ -208,8 +204,8 @@ func (d *databaseState) FindPrimaryKey(find *PrimaryKeyFind) *Index {
continue
}
for _, index := range table.indexSet {
- if index.primary {
- return index.convertToCatalog()
+ if index.primary != nil && *index.primary {
+ return index
}
}
}
@@ -225,7 +221,7 @@ type ColumnFind struct {
}
// FindColumn finds the column.
-func (d *databaseState) FindColumn(find *ColumnFind) *Column {
+func (d *DatabaseState) FindColumn(find *ColumnFind) *ColumnState {
schema, exists := d.schemaSet[find.SchemaName]
if !exists {
return nil
@@ -238,7 +234,7 @@ func (d *databaseState) FindColumn(find *ColumnFind) *Column {
if !exists {
return nil
}
- return column.convertToCatalog()
+ return column
}
// TableFind is for find table.
@@ -248,7 +244,7 @@ type TableFind struct {
}
// FindTable finds the table.
-func (d *databaseState) FindTable(find *TableFind) *Table {
+func (d *DatabaseState) FindTable(find *TableFind) *TableState {
schema, exists := d.schemaSet[find.SchemaName]
if !exists {
return nil
@@ -257,219 +253,227 @@ func (d *databaseState) FindTable(find *TableFind) *Table {
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(),
- }
+ return table
}
-type schemaState struct {
+// SchemaState is the state for walk-through.
+type SchemaState struct {
+ ctx *FinderContext
name string
tableSet tableStateMap
viewSet viewStateMap
extensionSet extensionStateMap
-
- context *FinderContext
-}
-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 schemaStateMap map[string]*SchemaState
-type tableState struct {
+// TableState is the state for walk-through.
+type TableState struct {
name string
- tableType string
+ tableType *string
// engine isn't supported for Postgres, Snowflake, SQLite.
- engine string
+ engine *string
// collation isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
- collation string
- rowCount int64
- // dataSize isn't supported for SQLite.
- dataSize int64
- // indexSize isn't supported for ClickHouse, Snowflake, SQLite.
- indexSize int64
- // dataFree isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
- dataFree int64
- // createOptions isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
- createOptions string
+ collation *string
// comment isn't supported for SQLite.
- comment string
+ comment *string
columnSet columnStateMap
// indexSet isn't supported for ClickHouse, Snowflake.
indexSet indexStateMap
}
-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,
- Type: table.tableType,
- Engine: table.engine,
- Collation: table.collation,
- RowCount: table.rowCount,
- DataSize: table.dataSize,
- IndexSize: table.indexSize,
- DataFree: table.dataFree,
- CreateOptions: table.createOptions,
- Comment: table.comment,
- ColumnList: table.columnSet.convertToCatalog(),
- IndexList: table.indexSet.convertToCatalog(),
+func (table *TableState) copy() *TableState {
+ return &TableState{
+ name: table.name,
+ tableType: copyStringPointer(table.tableType),
+ engine: copyStringPointer(table.engine),
+ collation: copyStringPointer(table.collation),
+ comment: copyStringPointer(table.comment),
+ columnSet: table.columnSet.copy(),
+ indexSet: table.indexSet.copy(),
}
}
-func (table *tableState) copy() *tableState {
- return newTableState(table.convertToCatalog())
-}
+type tableStateMap map[string]*TableState
-type indexState struct {
+// IndexState is the state for walk-through.
+type IndexState struct {
name string
// This could refer to a column or an expression.
expressionList []string
// Type isn't supported for SQLite.
- indextype string
- unique bool
- primary bool
+ indextype *string
+ unique *bool
+ primary *bool
// Visible isn't supported for Postgres, SQLite.
- visible bool
+ visible *bool
// Comment isn't supported for SQLite.
- comment string
+ comment *string
}
-type indexStateMap map[string]*indexState
-func (m indexStateMap) convertToCatalog() []*Index {
- var res []*Index
- for _, index := range m {
- res = append(res, index.convertToCatalog())
+func (idx *IndexState) copy() *IndexState {
+ return &IndexState{
+ name: idx.name,
+ expressionList: copyStringSlice(idx.expressionList),
+ indextype: copyStringPointer(idx.indextype),
+ unique: copyBoolPointer(idx.unique),
+ primary: copyBoolPointer(idx.primary),
+ visible: copyBoolPointer(idx.visible),
+ comment: copyStringPointer(idx.comment),
}
- return res
}
-func (index *indexState) convertToCatalog() *Index {
- return &Index{
- Name: index.name,
- ExpressionList: index.expressionList,
- Type: index.indextype,
- Unique: index.unique,
- Primary: index.primary,
- Visible: index.visible,
- Comment: index.comment,
+// Unique returns the unique for the index.
+func (idx *IndexState) Unique() bool {
+ if idx.unique != nil {
+ return *idx.unique
+ }
+ return false
+}
+
+// Primary returns the priamry for the index.
+func (idx *IndexState) Primary() bool {
+ if idx.primary != nil {
+ return *idx.primary
+ }
+ return false
+}
+
+// ExpressionList returns the expression list for the index.
+func (idx *IndexState) ExpressionList() []string {
+ return idx.expressionList
+}
+
+type indexStateMap map[string]*IndexState
+
+func (m indexStateMap) copy() indexStateMap {
+ res := make(indexStateMap)
+ for k, v := range m {
+ res[k] = v.copy()
}
+ return res
}
-type columnState struct {
+// ColumnState is the state for walk-through.
+type ColumnState struct {
name string
- position int
+ position *int
defaultValue *string
// nullable isn't supported for ClickHouse.
- nullable bool
- columnType string
+ nullable *bool
+ columnType *string
// characterSet isn't supported for Postgres, ClickHouse, SQLite.
- characterSet string
+ characterSet *string
// collation isn't supported for ClickHouse, SQLite.
- collation string
+ collation *string
// comment isn't supported for SQLite.
- comment string
+ comment *string
}
-type columnStateMap map[string]*columnState
-func (m columnStateMap) convertToCatalog() []*Column {
- var res []*Column
- for _, column := range m {
- res = append(res, column.convertToCatalog())
+func (col *ColumnState) copy() *ColumnState {
+ return &ColumnState{
+ name: col.name,
+ position: copyIntPointer(col.position),
+ defaultValue: copyStringPointer(col.defaultValue),
+ nullable: copyBoolPointer(col.nullable),
+ columnType: copyStringPointer(col.columnType),
+ characterSet: copyStringPointer(col.characterSet),
+ collation: copyStringPointer(col.collation),
+ comment: copyStringPointer(col.comment),
}
- return res
}
-func (column *columnState) convertToCatalog() *Column {
- return &Column{
- Name: column.name,
- Position: column.position,
- Default: column.defaultValue,
- Nullable: column.nullable,
- Type: column.columnType,
- CharacterSet: column.characterSet,
- Collation: column.collation,
- Comment: column.comment,
- }
+// Nullable returns nullable for the column.
+func (col *ColumnState) Nullable() bool {
+ return col.nullable != nil && *col.nullable
}
-type viewState struct {
- name string
- definition string
- comment string
+// Type returns type for the column.
+func (col *ColumnState) Type() string {
+ if col.columnType != nil {
+ return *col.columnType
+ }
+ return ""
}
-type viewStateMap map[string]*viewState
-func (m viewStateMap) convertToCatalog() []*View {
- var res []*View
- for _, view := range m {
- res = append(res, view.convertToCatalog())
+type columnStateMap map[string]*ColumnState
+
+func (m columnStateMap) copy() columnStateMap {
+ res := make(columnStateMap)
+ for k, v := range m {
+ res[k] = v.copy()
}
return res
}
-func (view *viewState) convertToCatalog() *View {
- return &View{
- Name: view.name,
- Definition: view.definition,
- Comment: view.comment,
- }
+// ViewState is the state for walk-through.
+type ViewState struct {
+ name string
+ definition *string
+ comment *string
}
+type viewStateMap map[string]*ViewState
-type extensionState struct {
+// ExtensionState is the state for walk-through.
+type ExtensionState struct {
name string
- version string
- description string
+ version *string
+ description *string
}
-type extensionStateMap map[string]*extensionState
+type extensionStateMap map[string]*ExtensionState
-func (m extensionStateMap) convertToCatalog() []*Extension {
- var res []*Extension
- for _, extension := range m {
- res = append(res, extension.convertToCatalog())
+func copyStringPointer(p *string) *string {
+ if p != nil {
+ v := *p
+ return &v
}
- return res
+ return nil
+}
+
+func copyBoolPointer(p *bool) *bool {
+ if p != nil {
+ v := *p
+ return &v
+ }
+ return nil
}
-func (extension *extensionState) convertToCatalog() *Extension {
- return &Extension{
- Name: extension.name,
- Version: extension.version,
- Description: extension.description,
+func copyIntPointer(p *int) *int {
+ if p != nil {
+ v := *p
+ return &v
}
+ return nil
+}
+
+func copyStringSlice(in []string) []string {
+ var res []string
+ res = append(res, in...)
+ return res
+}
+
+func newEmptyStringPointer() *string {
+ res := ""
+ return &res
+}
+
+func newStringPointer(v string) *string {
+ return &v
+}
+
+func newIntPointer(v int) *int {
+ return &v
+}
+
+func newTruePointer() *bool {
+ v := true
+ return &v
+}
+
+func newFalsePointer() *bool {
+ v := false
+ return &v
+}
+
+func newBoolPointer(v bool) *bool {
+ return &v
}
diff --git a/plugin/advisor/catalog/walk_through.go b/plugin/advisor/catalog/walk_through.go
index 873339fa4c..03bd187821 100644
--- a/plugin/advisor/catalog/walk_through.go
+++ b/plugin/advisor/catalog/walk_through.go
@@ -144,7 +144,7 @@ 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 {
+func (d *DatabaseState) WalkThrough(stmts string) error {
if d.dbType != db.MySQL && d.dbType != db.TiDB {
return &WalkThroughError{
Type: ErrorTypeUnsupported,
@@ -181,7 +181,7 @@ func (d *databaseState) WalkThrough(stmts string) error {
return nil
}
-func (d *databaseState) validateDML(in tidbast.DMLNode) (err *WalkThroughError) {
+func (d *DatabaseState) validateDML(in tidbast.DMLNode) (err *WalkThroughError) {
defer func() {
if err == nil {
return
@@ -205,7 +205,7 @@ func (d *databaseState) validateDML(in tidbast.DMLNode) (err *WalkThroughError)
}
}
-func (d *databaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError) {
+func (d *DatabaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError) {
defer func() {
if err == nil {
return
@@ -244,10 +244,10 @@ func (d *databaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError)
}
}
-func (d *databaseState) checkInsert(node *tidbast.InsertStmt) *WalkThroughError {
+func (d *DatabaseState) checkInsert(node *tidbast.InsertStmt) *WalkThroughError {
tableName, ok := getTableSourceName(node.Table)
if ok {
- table, err := d.findTableState(tableName)
+ table, err := d.findTableState(tableName, false /* createIncompleteTable */)
if err != nil {
return err
}
@@ -263,26 +263,34 @@ func (d *databaseState) checkInsert(node *tidbast.InsertStmt) *WalkThroughError
return nil
}
-func (d *databaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughError {
+func (d *DatabaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughError {
for _, tableToTable := range node.TableToTables {
schema, exists := d.schemaSet[""]
if !exists {
schema = d.createSchema("")
}
+ oldTableName := tableToTable.OldTable.Name.O
+ newTableName := tableToTable.NewTable.Name.O
if d.theCurrentDatabase(tableToTable) {
- table, exists := schema.tableSet[tableToTable.OldTable.Name.O]
+ if oldTableName == newTableName {
+ return nil
+ }
+ table, exists := schema.tableSet[oldTableName]
if !exists {
- return NewTableNotExistsError(tableToTable.OldTable.Name.O)
+ if schema.ctx.CheckIntegrity {
+ return NewTableNotExistsError(oldTableName)
+ }
+ table = schema.createIncompleteTable(oldTableName)
}
- if _, exists := schema.tableSet[tableToTable.NewTable.Name.O]; exists {
- return NewTableExistsError(tableToTable.NewTable.Name.O)
+ if _, exists := schema.tableSet[newTableName]; exists {
+ return NewTableExistsError(newTableName)
}
delete(schema.tableSet, table.name)
- table.name = tableToTable.NewTable.Name.O
+ table.name = newTableName
schema.tableSet[table.name] = table
} else if d.moveToOtherDatabase(tableToTable) {
_, exists := schema.tableSet[tableToTable.OldTable.Name.O]
- if !exists {
+ if !exists && schema.ctx.CheckIntegrity {
return NewTableNotExistsError(tableToTable.OldTable.Name.O)
}
delete(schema.tableSet, tableToTable.OldTable.Name.O)
@@ -293,21 +301,21 @@ func (d *databaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughE
return nil
}
-func (d *databaseState) targetDatabase(node *tidbast.TableToTable) string {
+func (d *DatabaseState) targetDatabase(node *tidbast.TableToTable) string {
if node.OldTable.Schema.O != "" && node.OldTable.Schema.O != d.name {
return node.OldTable.Schema.O
}
return node.NewTable.Schema.O
}
-func (d *databaseState) moveToOtherDatabase(node *tidbast.TableToTable) bool {
+func (d *DatabaseState) moveToOtherDatabase(node *tidbast.TableToTable) bool {
if node.OldTable.Schema.O != "" && node.OldTable.Schema.O != d.name {
return false
}
return node.OldTable.Schema.O != node.NewTable.Schema.O
}
-func (d *databaseState) theCurrentDatabase(node *tidbast.TableToTable) bool {
+func (d *DatabaseState) theCurrentDatabase(node *tidbast.TableToTable) bool {
if node.NewTable.Schema.O != "" && node.NewTable.Schema.O != d.name {
return false
}
@@ -317,7 +325,7 @@ func (d *databaseState) theCurrentDatabase(node *tidbast.TableToTable) bool {
return true
}
-func (d *databaseState) dropDatabase(node *tidbast.DropDatabaseStmt) *WalkThroughError {
+func (d *DatabaseState) dropDatabase(node *tidbast.DropDatabaseStmt) *WalkThroughError {
if node.Name != d.name {
return NewAccessOtherDatabaseError(d.name, node.Name)
}
@@ -326,7 +334,7 @@ func (d *databaseState) dropDatabase(node *tidbast.DropDatabaseStmt) *WalkThroug
return nil
}
-func (d *databaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) *WalkThroughError {
+func (d *DatabaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) *WalkThroughError {
if !node.AlterDefaultDatabase && node.Name != d.name {
return NewAccessOtherDatabaseError(d.name, node.Name)
}
@@ -342,7 +350,7 @@ func (d *databaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) *WalkThro
return nil
}
-func (d *databaseState) findTableState(tableName *tidbast.TableName) (*tableState, *WalkThroughError) {
+func (d *DatabaseState) findTableState(tableName *tidbast.TableName, createIncompleteTable bool) (*TableState, *WalkThroughError) {
if tableName.Schema.O != "" && tableName.Schema.O != d.name {
return nil, NewAccessOtherDatabaseError(d.name, tableName.Schema.O)
}
@@ -354,36 +362,33 @@ func (d *databaseState) findTableState(tableName *tidbast.TableName) (*tableStat
table, exists := schema.tableSet[tableName.Name.O]
if !exists {
- if !schema.context.CheckIntegrity {
+ if schema.ctx.CheckIntegrity {
+ return nil, NewTableNotExistsError(tableName.Name.O)
+ }
+ if createIncompleteTable {
+ table = schema.createIncompleteTable(tableName.Name.O)
+ } else {
return nil, nil
}
-
- return nil, NewTableNotExistsError(tableName.Name.O)
}
return table, nil
}
-func (d *databaseState) dropIndex(node *tidbast.DropIndexStmt) *WalkThroughError {
- table, err := d.findTableState(node.Table)
+func (d *DatabaseState) dropIndex(node *tidbast.DropIndexStmt) *WalkThroughError {
+ table, err := d.findTableState(node.Table, true /* createIncompleteTable */)
if err != nil {
return err
}
- if table == nil {
- return nil
- }
- return table.dropIndex(node.IndexName)
+ return table.dropIndex(d.ctx, node.IndexName)
}
-func (d *databaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughError {
- table, err := d.findTableState(node.Table)
+func (d *DatabaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughError {
+ table, err := d.findTableState(node.Table, true /* createIncompleteTable */)
if err != nil {
return err
}
- if table == nil {
- return nil
- }
unique := false
tp := model.IndexTypeBtree.String()
@@ -400,7 +405,7 @@ func (d *databaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughE
tp = SpatialName
}
- keyList, err := table.validateAndGetKeyStringList(node.IndexPartSpecifications, false /* primary */, isSpatial)
+ keyList, err := table.validateAndGetKeyStringList(d.ctx, node.IndexPartSpecifications, false /* primary */, isSpatial)
if err != nil {
return err
}
@@ -408,14 +413,11 @@ func (d *databaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughE
return table.createIndex(node.IndexName, keyList, unique, tp, node.IndexOption)
}
-func (d *databaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughError {
- table, err := d.findTableState(node.Table)
+func (d *DatabaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughError {
+ table, err := d.findTableState(node.Table, true /* createIncompleteTable */)
if err != nil {
return err
}
- if table == nil {
- return nil
- }
for _, spec := range node.Specs {
switch spec.Tp {
@@ -423,11 +425,11 @@ func (d *databaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughErr
for _, option := range spec.Options {
switch option.Tp {
case tidbast.TableOptionCollate:
- table.collation = option.StrValue
+ table.collation = newStringPointer(option.StrValue)
case tidbast.TableOptionComment:
- table.comment = option.StrValue
+ table.comment = newStringPointer(option.StrValue)
case tidbast.TableOptionEngine:
- table.engine = option.StrValue
+ table.engine = newStringPointer(option.StrValue)
}
}
case tidbast.AlterTableAddColumns:
@@ -436,61 +438,61 @@ func (d *databaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughErr
if len(spec.NewColumns) == 1 {
pos = spec.Position
}
- if err := table.createColumn(column, pos); err != nil {
+ if err := table.createColumn(d.ctx, column, pos); err != nil {
return err
}
}
// MySQL can add table constraints in ALTER TABLE ADD COLUMN statements.
for _, constraint := range spec.NewConstraints {
- if err := table.createConstraint(constraint); err != nil {
+ if err := table.createConstraint(d.ctx, constraint); err != nil {
return err
}
}
case tidbast.AlterTableAddConstraint:
- if err := table.createConstraint(spec.Constraint); err != nil {
+ if err := table.createConstraint(d.ctx, spec.Constraint); err != nil {
return err
}
case tidbast.AlterTableDropColumn:
- if err := table.dropColumn(spec.OldColumnName.Name.O); err != nil {
+ if err := table.dropColumn(d.ctx, spec.OldColumnName.Name.O); err != nil {
return err
}
case tidbast.AlterTableDropPrimaryKey:
- if err := table.dropIndex(PrimaryKeyName); err != nil {
+ if err := table.dropIndex(d.ctx, PrimaryKeyName); err != nil {
return err
}
case tidbast.AlterTableDropIndex:
- if err := table.dropIndex(spec.Name); err != nil {
+ if err := table.dropIndex(d.ctx, spec.Name); err != nil {
return err
}
case tidbast.AlterTableDropForeignKey:
// we do not deal with DROP FOREIGN KEY statements.
case tidbast.AlterTableModifyColumn:
- if err := table.changeColumn(spec.NewColumns[0].Name.Name.O, spec.NewColumns[0], spec.Position); err != nil {
+ if err := table.changeColumn(d.ctx, spec.NewColumns[0].Name.Name.O, spec.NewColumns[0], spec.Position); err != nil {
return err
}
case tidbast.AlterTableChangeColumn:
- if err := table.changeColumn(spec.OldColumnName.Name.O, spec.NewColumns[0], spec.Position); err != nil {
+ if err := table.changeColumn(d.ctx, spec.OldColumnName.Name.O, spec.NewColumns[0], spec.Position); err != nil {
return err
}
case tidbast.AlterTableRenameColumn:
- if err := table.renameColumn(spec.OldColumnName.Name.O, spec.NewColumnName.Name.O); err != nil {
+ if err := table.renameColumn(d.ctx, spec.OldColumnName.Name.O, spec.NewColumnName.Name.O); err != nil {
return err
}
case tidbast.AlterTableRenameTable:
schema := d.schemaSet[""]
- if err := schema.renameTable(table.name, spec.NewTable.Name.O); err != nil {
+ if err := schema.renameTable(d.ctx, table.name, spec.NewTable.Name.O); err != nil {
return err
}
case tidbast.AlterTableAlterColumn:
- if err := table.changeColumnDefault(spec.NewColumns[0]); err != nil {
+ if err := table.changeColumnDefault(d.ctx, spec.NewColumns[0]); err != nil {
return err
}
case tidbast.AlterTableRenameIndex:
- if err := table.renameIndex(spec.FromKey.O, spec.ToKey.O); err != nil {
+ if err := table.renameIndex(d.ctx, spec.FromKey.O, spec.ToKey.O); err != nil {
return err
}
case tidbast.AlterTableIndexInvisible:
- if err := table.changeIndexVisibility(spec.IndexName.O, spec.Visibility); err != nil {
+ if err := table.changeIndexVisibility(d.ctx, spec.IndexName.O, spec.Visibility); err != nil {
return err
}
}
@@ -499,21 +501,24 @@ func (d *databaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughErr
return nil
}
-func (t *tableState) changeIndexVisibility(indexName string, visibility tidbast.IndexVisibility) *WalkThroughError {
+func (t *TableState) changeIndexVisibility(ctx *FinderContext, indexName string, visibility tidbast.IndexVisibility) *WalkThroughError {
index, exists := t.indexSet[indexName]
if !exists {
- return NewIndexNotExistsError(t.name, indexName)
+ if ctx.CheckIntegrity {
+ return NewIndexNotExistsError(t.name, indexName)
+ }
+ index = t.createIncompleteIndex(indexName)
}
switch visibility {
case tidbast.IndexVisibilityVisible:
- index.visible = true
+ index.visible = newTruePointer()
case tidbast.IndexVisibilityInvisible:
- index.visible = false
+ index.visible = newFalsePointer()
}
return nil
}
-func (t *tableState) renameIndex(oldName string, newName string) *WalkThroughError {
+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 can not use the name which case-insensitive equals 'PRIMARY'.
if strings.ToUpper(oldName) == PrimaryKeyName || strings.ToUpper(newName) == PrimaryKeyName {
@@ -529,7 +534,10 @@ func (t *tableState) renameIndex(oldName string, newName string) *WalkThroughErr
index, exists := t.indexSet[oldName]
if !exists {
- return NewIndexNotExistsError(t.name, oldName)
+ if ctx.CheckIntegrity {
+ return NewIndexNotExistsError(t.name, oldName)
+ }
+ index = t.createIncompleteIndex(oldName)
}
if _, exists := t.indexSet[newName]; exists {
@@ -542,11 +550,22 @@ func (t *tableState) renameIndex(oldName string, newName string) *WalkThroughErr
return nil
}
-func (t *tableState) changeColumnDefault(column *tidbast.ColumnDef) *WalkThroughError {
+func (t *TableState) createIncompleteIndex(name string) *IndexState {
+ index := &IndexState{
+ name: name,
+ }
+ t.indexSet[name] = index
+ return index
+}
+
+func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.ColumnDef) *WalkThroughError {
columnName := column.Name.Name.O
colState, exists := t.columnSet[columnName]
if !exists {
- return NewColumnNotExistsError(t.name, columnName)
+ if ctx.CheckIntegrity {
+ return NewColumnNotExistsError(t.name, columnName)
+ }
+ colState = t.createIncompleteColumn(columnName)
}
if len(column.Options) == 1 {
@@ -563,17 +582,20 @@ func (t *tableState) changeColumnDefault(column *tidbast.ColumnDef) *WalkThrough
return nil
}
-func (s *schemaState) renameTable(oldName string, newName string) *WalkThroughError {
+func (s *SchemaState) renameTable(ctx *FinderContext, oldName string, newName string) *WalkThroughError {
if oldName == newName {
return nil
}
table, exists := s.tableSet[oldName]
if !exists {
- return &WalkThroughError{
- Type: ErrorTypeTableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", oldName),
+ if ctx.CheckIntegrity {
+ return &WalkThroughError{
+ Type: ErrorTypeTableNotExists,
+ Content: fmt.Sprintf("Table `%s` does not exist", oldName),
+ }
}
+ table = s.createIncompleteTable(oldName)
}
if _, exists := s.tableSet[newName]; exists {
@@ -589,17 +611,30 @@ func (s *schemaState) renameTable(oldName string, newName string) *WalkThroughEr
return nil
}
-func (t *tableState) renameColumn(oldName string, newName string) *WalkThroughError {
+func (s *SchemaState) createIncompleteTable(name string) *TableState {
+ table := &TableState{
+ name: name,
+ columnSet: make(columnStateMap),
+ indexSet: make(indexStateMap),
+ }
+ s.tableSet[name] = table
+ return table
+}
+
+func (t *TableState) renameColumn(ctx *FinderContext, oldName string, newName string) *WalkThroughError {
if oldName == newName {
return nil
}
column, exists := t.columnSet[oldName]
if !exists {
- return &WalkThroughError{
- Type: ErrorTypeColumnNotExists,
- Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldName, t.name),
+ if ctx.CheckIntegrity {
+ return &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldName, t.name),
+ }
}
+ column = t.createIncompleteColumn(oldName)
}
if _, exists := t.columnSet[newName]; exists {
@@ -614,11 +649,18 @@ func (t *tableState) renameColumn(oldName string, newName string) *WalkThroughEr
t.columnSet[newName] = column
t.renameColumnInIndexKey(oldName, newName)
-
return nil
}
-func (t *tableState) renameColumnInIndexKey(oldName string, newName string) {
+func (t *TableState) createIncompleteColumn(name string) *ColumnState {
+ column := &ColumnState{
+ name: name,
+ }
+ t.columnSet[name] = column
+ return column
+}
+
+func (t *TableState) renameColumnInIndexKey(oldName string, newName string) {
if oldName == newName {
return
}
@@ -631,18 +673,18 @@ func (t *tableState) renameColumnInIndexKey(oldName string, newName string) {
}
}
-// changeColumn changes column definition.
+// completeTableChangeColumn changes column definition.
// It works as:
// 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) *WalkThroughError {
+func (t *TableState) completeTableChangeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
column, exists := t.columnSet[oldName]
if !exists {
return NewColumnNotExistsError(t.name, oldName)
}
- pos := column.position
+ pos := *column.position
// generate Position struct for creating new column
if position == nil {
@@ -653,7 +695,7 @@ func (t *tableState) changeColumn(oldName string, newColumn *tidbast.ColumnDef,
position.Tp = tidbast.ColumnPositionFirst
} else {
for _, col := range t.columnSet {
- if col.position == pos-1 {
+ if *col.position == pos-1 {
position.Tp = tidbast.ColumnPositionAfter
position.RelativeColumn = &tidbast.ColumnName{Name: model.NewCIStr(col.name)}
break
@@ -664,8 +706,8 @@ func (t *tableState) changeColumn(oldName string, newColumn *tidbast.ColumnDef,
// drop column from columnSet
for _, col := range t.columnSet {
- if col.position > pos {
- col.position--
+ if *col.position > pos {
+ *col.position--
}
}
delete(t.columnSet, column.name)
@@ -674,25 +716,46 @@ func (t *tableState) changeColumn(oldName string, newColumn *tidbast.ColumnDef,
t.renameColumnInIndexKey(oldName, newColumn.Name.Name.O)
// create a new column in columnSet
- return t.createColumn(newColumn, position)
+ return t.createColumn(ctx, newColumn, position)
}
-func (t *tableState) dropIndex(indexName string) *WalkThroughError {
- if _, exists := t.indexSet[indexName]; !exists {
- if indexName == PrimaryKeyName {
- return &WalkThroughError{
- Type: ErrorTypePrimaryKeyNotExists,
- Content: fmt.Sprintf("Primary key does not exist in table `%s`", t.name),
+// incompleteTableChangeColumn changes column definition.
+// It does not maintain the position of the column.
+func (t *TableState) incompleteTableChangeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
+ delete(t.columnSet, oldName)
+
+ // rename column from indexSet
+ t.renameColumnInIndexKey(oldName, newColumn.Name.Name.O)
+
+ // create a new column in columnSet
+ return t.createColumn(ctx, newColumn, position)
+}
+
+func (t *TableState) changeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
+ if ctx.CheckIntegrity {
+ return t.completeTableChangeColumn(ctx, oldName, newColumn, position)
+ }
+ return t.incompleteTableChangeColumn(ctx, oldName, newColumn, position)
+}
+
+func (t *TableState) dropIndex(ctx *FinderContext, indexName string) *WalkThroughError {
+ if ctx.CheckIntegrity {
+ if _, exists := t.indexSet[indexName]; !exists {
+ if indexName == PrimaryKeyName {
+ return &WalkThroughError{
+ Type: ErrorTypePrimaryKeyNotExists,
+ Content: fmt.Sprintf("Primary key does not exist in table `%s`", t.name),
+ }
}
+ return NewIndexNotExistsError(t.name, indexName)
}
- return NewIndexNotExistsError(t.name, indexName)
}
delete(t.indexSet, indexName)
return nil
}
-func (t *tableState) dropColumn(columnName string) *WalkThroughError {
+func (t *TableState) completeTableDropColumn(columnName string) *WalkThroughError {
column, exists := t.columnSet[columnName]
if !exists {
return NewColumnNotExistsError(t.name, columnName)
@@ -718,8 +781,25 @@ func (t *tableState) dropColumn(columnName string) *WalkThroughError {
// modify the column position
for _, col := range t.columnSet {
- if col.position > column.position {
- col.position--
+ if *col.position > *column.position {
+ *col.position--
+ }
+ }
+
+ delete(t.columnSet, 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, index.name)
}
}
@@ -727,7 +807,17 @@ func (t *tableState) dropColumn(columnName string) *WalkThroughError {
return nil
}
-func (idx *indexState) dropColumn(columnName string) {
+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 key != columnName {
@@ -739,13 +829,13 @@ 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, *WalkThroughError) {
+func (t *TableState) reorderColumn(position *tidbast.ColumnPosition) (int, *WalkThroughError) {
switch position.Tp {
case tidbast.ColumnPositionNone:
return len(t.columnSet) + 1, nil
case tidbast.ColumnPositionFirst:
for _, column := range t.columnSet {
- column.position++
+ *column.position++
}
return 1, nil
case tidbast.ColumnPositionAfter:
@@ -755,11 +845,11 @@ func (t *tableState) reorderColumn(position *tidbast.ColumnPosition) (int, *Walk
return 0, NewColumnNotExistsError(t.name, columnName)
}
for _, col := range t.columnSet {
- if col.position > column.position {
- col.position++
+ if *col.position > *column.position {
+ *col.position++
}
}
- return column.position + 1, nil
+ return *column.position + 1, nil
}
return 0, &WalkThroughError{
Type: ErrorTypeUnsupported,
@@ -767,7 +857,7 @@ func (t *tableState) reorderColumn(position *tidbast.ColumnPosition) (int, *Walk
}
}
-func (d *databaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError {
+func (d *DatabaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError {
// TODO(rebelice): deal with DROP VIEW statement.
if !node.IsView {
for _, name := range node.Tables {
@@ -784,7 +874,7 @@ func (d *databaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError
}
if _, exists = schema.tableSet[name.Name.O]; !exists {
- if node.IfExists || !schema.context.CheckIntegrity {
+ if node.IfExists || !d.ctx.CheckIntegrity {
return nil
}
return &WalkThroughError{
@@ -799,15 +889,11 @@ func (d *databaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError
return nil
}
-func (d *databaseState) copyTable(node *tidbast.CreateTableStmt) *WalkThroughError {
- targetTable, err := d.findTableState(node.ReferTable)
+func (d *DatabaseState) copyTable(node *tidbast.CreateTableStmt) *WalkThroughError {
+ targetTable, err := d.findTableState(node.ReferTable, true /* createIncompleteTable */)
if err != nil {
return err
}
- if targetTable == nil {
- // For CREATE TABLE ... LIKE ... statements, we can not walk-through if target table dese not exist in catalog.
- return NewTableNotExistsError(node.ReferTable.Name.O)
- }
schema := d.schemaSet[""]
table := targetTable.copy()
@@ -816,7 +902,7 @@ func (d *databaseState) copyTable(node *tidbast.CreateTableStmt) *WalkThroughErr
return nil
}
-func (d *databaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughError {
+func (d *DatabaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughError {
if node.Table.Schema.O != "" && d.name != node.Table.Schema.O {
return &WalkThroughError{
Type: ErrorTypeAccessOtherDatabase,
@@ -843,22 +929,26 @@ func (d *databaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughE
return d.copyTable(node)
}
- table := &tableState{
+ table := &TableState{
name: node.Table.Name.O,
+ tableType: newEmptyStringPointer(),
+ engine: newEmptyStringPointer(),
+ collation: newEmptyStringPointer(),
+ comment: newEmptyStringPointer(),
columnSet: make(columnStateMap),
indexSet: make(indexStateMap),
}
schema.tableSet[table.name] = table
for _, column := range node.Cols {
- if err := table.createColumn(column, nil); err != nil {
+ if err := table.createColumn(d.ctx, column, nil /* position */); err != nil {
err.Line = column.OriginTextPosition()
return err
}
}
for _, constraint := range node.Constraints {
- if err := table.createConstraint(constraint); err != nil {
+ if err := table.createConstraint(d.ctx, constraint); err != nil {
err.Line = constraint.OriginTextPosition()
return err
}
@@ -867,10 +957,10 @@ func (d *databaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughE
return nil
}
-func (t *tableState) createConstraint(constraint *tidbast.Constraint) *WalkThroughError {
+func (t *TableState) createConstraint(ctx *FinderContext, constraint *tidbast.Constraint) *WalkThroughError {
switch constraint.Tp {
case tidbast.ConstraintPrimaryKey:
- keyList, err := t.validateAndGetKeyStringList(constraint.Keys, true /* primary */, false /* isSpatial */)
+ keyList, err := t.validateAndGetKeyStringList(ctx, constraint.Keys, true /* primary */, false /* isSpatial */)
if err != nil {
return err
}
@@ -878,7 +968,7 @@ func (t *tableState) createConstraint(constraint *tidbast.Constraint) *WalkThrou
return err
}
case tidbast.ConstraintKey, tidbast.ConstraintIndex:
- keyList, err := t.validateAndGetKeyStringList(constraint.Keys, false /* primary */, false /* isSpatial */)
+ keyList, err := t.validateAndGetKeyStringList(ctx, constraint.Keys, false /* primary */, false /* isSpatial */)
if err != nil {
return err
}
@@ -886,7 +976,7 @@ func (t *tableState) createConstraint(constraint *tidbast.Constraint) *WalkThrou
return err
}
case tidbast.ConstraintUniq, tidbast.ConstraintUniqKey, tidbast.ConstraintUniqIndex:
- keyList, err := t.validateAndGetKeyStringList(constraint.Keys, false /* primary */, false /* isSpatial */)
+ keyList, err := t.validateAndGetKeyStringList(ctx, constraint.Keys, false /* primary */, false /* isSpatial */)
if err != nil {
return err
}
@@ -896,7 +986,7 @@ func (t *tableState) createConstraint(constraint *tidbast.Constraint) *WalkThrou
case tidbast.ConstraintForeignKey:
// we do not deal with FOREIGN KEY constraints
case tidbast.ConstraintFulltext:
- keyList, err := t.validateAndGetKeyStringList(constraint.Keys, false /* primary */, false /* isSpatial */)
+ keyList, err := t.validateAndGetKeyStringList(ctx, constraint.Keys, false /* primary */, false /* isSpatial */)
if err != nil {
return err
}
@@ -910,7 +1000,7 @@ func (t *tableState) createConstraint(constraint *tidbast.Constraint) *WalkThrou
return nil
}
-func (t *tableState) validateAndGetKeyStringList(keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, *WalkThroughError) {
+func (t *TableState) validateAndGetKeyStringList(ctx *FinderContext, keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, *WalkThroughError) {
var res []string
for _, key := range keyList {
if key.Expr != nil {
@@ -923,25 +1013,29 @@ func (t *tableState) validateAndGetKeyStringList(keyList []*tidbast.IndexPartSpe
columnName := key.Column.Name.O
column, exists := t.columnSet[columnName]
if !exists {
- return nil, NewColumnNotExistsError(t.name, columnName)
- }
- if primary {
- column.nullable = false
- }
- if isSpatial && column.nullable {
- return nil, &WalkThroughError{
- Type: ErrorTypeSpatialIndexKeyNullable,
- // The error content comes from MySQL.
- Content: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name),
+ if ctx.CheckIntegrity {
+ return nil, NewColumnNotExistsError(t.name, columnName)
+ }
+ } else {
+ if primary {
+ column.nullable = newFalsePointer()
+ }
+ if isSpatial && column.nullable != nil && *column.nullable {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeSpatialIndexKeyNullable,
+ // The error content comes from MySQL.
+ Content: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name),
+ }
}
}
+
res = append(res, columnName)
}
}
return res, nil
}
-func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
+func (t *TableState) createColumn(ctx *FinderContext, column *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
if _, exists := t.columnSet[column.Name.Name.O]; exists {
return &WalkThroughError{
Type: ErrorTypeColumnExists,
@@ -950,7 +1044,7 @@ func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.C
}
pos := len(t.columnSet) + 1
- if position != nil {
+ if position != nil && ctx.CheckIntegrity {
var err *WalkThroughError
pos, err = t.reorderColumn(position)
if err != nil {
@@ -958,24 +1052,27 @@ func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.C
}
}
- col := &columnState{
+ vTrue := true
+ col := &ColumnState{
name: column.Name.Name.O,
- position: pos,
- columnType: column.Tp.CompactStr(),
- characterSet: column.Tp.GetCharset(),
- collation: column.Tp.GetCollate(),
- nullable: true,
+ position: &pos,
+ defaultValue: nil,
+ nullable: &vTrue,
+ columnType: newStringPointer(column.Tp.CompactStr()),
+ characterSet: newStringPointer(column.Tp.GetCharset()),
+ collation: newStringPointer(column.Tp.GetCollate()),
+ comment: newEmptyStringPointer(),
}
for _, option := range column.Options {
switch option.Tp {
case tidbast.ColumnOptionPrimaryKey:
- col.nullable = false
+ col.nullable = newFalsePointer()
if err := t.createPrimaryKey([]string{col.name}, model.IndexTypeBtree.String()); err != nil {
return err
}
case tidbast.ColumnOptionNotNull:
- col.nullable = false
+ col.nullable = newFalsePointer()
case tidbast.ColumnOptionAutoIncrement:
// we do not deal with AUTO-INCREMENT
case tidbast.ColumnOptionDefaultValue:
@@ -989,7 +1086,7 @@ func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.C
return err
}
case tidbast.ColumnOptionNull:
- col.nullable = true
+ col.nullable = newTruePointer()
case tidbast.ColumnOptionOnUpdate:
// we do not deal with ON UPDATE
case tidbast.ColumnOptionComment:
@@ -997,14 +1094,14 @@ func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.C
if err != nil {
return err
}
- col.comment = comment
+ col.comment = &comment
case tidbast.ColumnOptionGenerated:
// we do not deal with GENERATED ALWAYS AS
case tidbast.ColumnOptionReference:
// MySQL will ignore the inline REFERENCE
// https://dev.mysql.com/doc/refman/8.0/en/create-table.html
case tidbast.ColumnOptionCollate:
- col.collation = option.StrValue
+ col.collation = newStringPointer(option.StrValue)
case tidbast.ColumnOptionCheck:
// we do not deal with CHECK constraint
case tidbast.ColumnOptionColumnFormat:
@@ -1020,7 +1117,7 @@ func (t *tableState) createColumn(column *tidbast.ColumnDef, position *tidbast.C
return nil
}
-func (t *tableState) createIndex(name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) *WalkThroughError {
+func (t *TableState) createIndex(name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) *WalkThroughError {
if len(keyList) == 0 {
return &WalkThroughError{
Type: ErrorTypeIndexEmptyKeys,
@@ -1045,24 +1142,25 @@ func (t *tableState) createIndex(name string, keyList []string, unique bool, tp
}
}
- index := &indexState{
+ index := &IndexState{
name: name,
expressionList: keyList,
- unique: unique,
- primary: false,
- indextype: tp,
- visible: true,
+ indextype: &tp,
+ unique: &unique,
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
}
if option != nil && option.Visibility == tidbast.IndexVisibilityInvisible {
- index.visible = false
+ index.visible = newFalsePointer()
}
t.indexSet[name] = index
return nil
}
-func (t *tableState) createPrimaryKey(keys []string, tp string) *WalkThroughError {
+func (t *TableState) createPrimaryKey(keys []string, tp string) *WalkThroughError {
if _, exists := t.indexSet[PrimaryKeyName]; exists {
return &WalkThroughError{
Type: ErrorTypePrimaryKeyExists,
@@ -1070,32 +1168,33 @@ func (t *tableState) createPrimaryKey(keys []string, tp string) *WalkThroughErro
}
}
- pk := &indexState{
+ pk := &IndexState{
name: PrimaryKeyName,
expressionList: keys,
- unique: true,
- primary: true,
- indextype: tp,
- visible: true,
+ indextype: &tp,
+ unique: newTruePointer(),
+ primary: newTruePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
}
t.indexSet[pk.name] = pk
return nil
}
-func (d *databaseState) createSchema(name string) *schemaState {
- schema := &schemaState{
+func (d *DatabaseState) createSchema(name string) *SchemaState {
+ schema := &SchemaState{
+ ctx: d.ctx.Copy(),
name: name,
tableSet: make(tableStateMap),
viewSet: make(viewStateMap),
extensionSet: make(extensionStateMap),
- context: d.context.Copy(),
}
d.schemaSet[name] = schema
return schema
}
-func (d *databaseState) parse(stmts string) ([]tidbast.StmtNode, *WalkThroughError) {
+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.
diff --git a/plugin/advisor/catalog/walk_through_test.go b/plugin/advisor/catalog/walk_through_test.go
index ea9dea0a68..1131c9005f 100644
--- a/plugin/advisor/catalog/walk_through_test.go
+++ b/plugin/advisor/catalog/walk_through_test.go
@@ -958,47 +958,389 @@ func TestWalkThrough(t *testing.T) {
}
}
-func TestWalkThroughForNoCatalog(t *testing.T) {
- tests := []testData{
+type testDataForIncomplete struct {
+ statement string
+ want *DatabaseState
+ err error
+}
+
+func TestWalkThroughForIncompleteOriginalCatalog(t *testing.T) {
+ tests := []testDataForIncomplete{
{
- origin: &Database{
- Name: "test",
- DbType: db.MySQL,
+ statement: `CREATE INDEX idx_a on t(a)`,
+ want: &DatabaseState{
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ characterSet: "",
+ collation: "",
+ dbType: db.MySQL,
+ schemaSet: schemaStateMap{
+ "": {
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ tableSet: tableStateMap{
+ "t": {
+ name: "t",
+ tableType: nil,
+ engine: nil,
+ collation: nil,
+ comment: nil,
+ columnSet: columnStateMap{},
+ indexSet: indexStateMap{
+ "idx_a": {
+ name: "idx_a",
+ expressionList: []string{"a"},
+ indextype: newStringPointer("BTREE"),
+ unique: newFalsePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ },
+ },
+ },
+ viewSet: viewStateMap{},
+ extensionSet: extensionStateMap{},
+ },
+ },
+ },
+ },
+ {
+ statement: `ALTER TABLE t RENAME COLUMN a TO a_copy`,
+ want: &DatabaseState{
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ characterSet: *newEmptyStringPointer(),
+ collation: *newEmptyStringPointer(),
+ dbType: db.MySQL,
+ schemaSet: schemaStateMap{
+ "": {
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ tableSet: tableStateMap{
+ "t": {
+ name: "t",
+ tableType: nil,
+ engine: nil,
+ collation: nil,
+ comment: nil,
+ columnSet: columnStateMap{
+ "a_copy": {
+ name: "a_copy",
+ },
+ },
+ indexSet: indexStateMap{},
+ },
+ },
+ viewSet: viewStateMap{},
+ extensionSet: extensionStateMap{},
+ },
+ },
},
+ },
+ {
+ statement: `ALTER TABLE t RENAME TO t1`,
+ want: &DatabaseState{
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ characterSet: "",
+ collation: "",
+ dbType: db.MySQL,
+ schemaSet: schemaStateMap{
+ "": {
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ tableSet: tableStateMap{
+ "t1": {
+ name: "t1",
+ tableType: nil,
+ engine: nil,
+ collation: nil,
+ comment: nil,
+ columnSet: columnStateMap{},
+ indexSet: indexStateMap{},
+ },
+ },
+ viewSet: viewStateMap{},
+ extensionSet: extensionStateMap{},
+ },
+ },
+ },
+ },
+ {
statement: `
- DROP TABLE t1, t2
+ ALTER TABLE t ADD PRIMARY KEY (a);
+ ALTER TABLE t ADD UNIQUE (b);
+ CREATE INDEX idx_a on t(a);
+ CREATE INDEX b_2 on t(b, a);
+ CREATE UNIQUE INDEX b_3 on t(b, c, d);
+ CREATE FULLTEXT INDEX b_4 on t(b, d) WITH PARSER ngram INVISIBLE;
`,
- want: &Database{
- Name: "test",
- DbType: db.MySQL,
- SchemaList: []*Schema{{}},
+ want: &DatabaseState{
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ characterSet: "",
+ collation: "",
+ dbType: db.MySQL,
+ schemaSet: schemaStateMap{
+ "": {
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ tableSet: tableStateMap{
+ "t": {
+ name: "t",
+ tableType: nil,
+ engine: nil,
+ collation: nil,
+ comment: nil,
+ columnSet: columnStateMap{},
+ indexSet: indexStateMap{
+ "PRIMARY": {
+ name: "PRIMARY",
+ expressionList: []string{"a"},
+ indextype: newStringPointer("BTREE"),
+ unique: newTruePointer(),
+ primary: newTruePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b": {
+ name: "b",
+ expressionList: []string{"b"},
+ indextype: newStringPointer("BTREE"),
+ unique: newTruePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "idx_a": {
+ name: "idx_a",
+ expressionList: []string{"a"},
+ indextype: newStringPointer("BTREE"),
+ unique: newFalsePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b_2": {
+ name: "b_2",
+ expressionList: []string{"b", "a"},
+ indextype: newStringPointer("BTREE"),
+ unique: newFalsePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b_3": {
+ name: "b_3",
+ expressionList: []string{"b", "c", "d"},
+ indextype: newStringPointer("BTREE"),
+ unique: newTruePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b_4": {
+ name: "b_4",
+ expressionList: []string{"b", "d"},
+ indextype: newStringPointer("FULLTEXT"),
+ unique: newFalsePointer(),
+ primary: newFalsePointer(),
+ visible: newFalsePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ },
+ },
+ },
+ viewSet: viewStateMap{},
+ extensionSet: extensionStateMap{},
+ },
+ },
},
},
{
- origin: &Database{
- Name: "test",
- DbType: db.MySQL,
- },
statement: `
- INSERT INTO test values (1);
+ CREATE TABLE t(
+ a int PRIMARY KEY DEFAULT 1,
+ b varchar(200) CHARACTER SET utf8mb4 NOT NULL UNIQUE,
+ c int auto_increment NULL COMMENT 'This is a comment',
+ d varchar(10) COLLATE utf8mb4_polish_ci,
+ KEY idx_a (a),
+ INDEX (b, a),
+ UNIQUE (b, c, d),
+ FULLTEXT (b, d) WITH PARSER ngram INVISIBLE
+ )
`,
- want: &Database{
- Name: "test",
- DbType: db.MySQL,
- SchemaList: []*Schema{{}},
+ want: &DatabaseState{
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ characterSet: "",
+ collation: "",
+ dbType: db.MySQL,
+ schemaSet: schemaStateMap{
+ "": {
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ tableSet: tableStateMap{
+ "t": {
+ name: "t",
+ tableType: newEmptyStringPointer(),
+ engine: newEmptyStringPointer(),
+ collation: newEmptyStringPointer(),
+ comment: newEmptyStringPointer(),
+ columnSet: columnStateMap{
+ "a": {
+ name: "a",
+ position: newIntPointer(1),
+ defaultValue: &one,
+ nullable: newFalsePointer(),
+ columnType: newStringPointer("int(11)"),
+ characterSet: newEmptyStringPointer(),
+ collation: newEmptyStringPointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b": {
+ name: "b",
+ position: newIntPointer(2),
+ defaultValue: nil,
+ nullable: newFalsePointer(),
+ columnType: newStringPointer("varchar(200)"),
+ characterSet: newStringPointer("utf8mb4"),
+ collation: newEmptyStringPointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "c": {
+ name: "c",
+ position: newIntPointer(3),
+ defaultValue: nil,
+ nullable: newTruePointer(),
+ columnType: newStringPointer("int(11)"),
+ characterSet: newEmptyStringPointer(),
+ collation: newEmptyStringPointer(),
+ comment: newStringPointer("This is a comment"),
+ },
+ "d": {
+ name: "d",
+ position: newIntPointer(4),
+ defaultValue: nil,
+ nullable: newTruePointer(),
+ columnType: newStringPointer("varchar(10)"),
+ characterSet: newEmptyStringPointer(),
+ collation: newStringPointer("utf8mb4_polish_ci"),
+ comment: newEmptyStringPointer(),
+ },
+ },
+ indexSet: indexStateMap{
+ "PRIMARY": {
+ name: "PRIMARY",
+ expressionList: []string{"a"},
+ indextype: newStringPointer("BTREE"),
+ unique: newTruePointer(),
+ primary: newTruePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b": {
+ name: "b",
+ expressionList: []string{"b"},
+ indextype: newStringPointer("BTREE"),
+ unique: newTruePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "idx_a": {
+ name: "idx_a",
+ expressionList: []string{"a"},
+ indextype: newStringPointer("BTREE"),
+ unique: newFalsePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b_2": {
+ name: "b_2",
+ expressionList: []string{"b", "a"},
+ indextype: newStringPointer("BTREE"),
+ unique: newFalsePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b_3": {
+ name: "b_3",
+ expressionList: []string{"b", "c", "d"},
+ indextype: newStringPointer("BTREE"),
+ unique: newTruePointer(),
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ "b_4": {
+ name: "b_4",
+ expressionList: []string{"b", "d"},
+ indextype: newStringPointer("FULLTEXT"),
+ unique: newFalsePointer(),
+ primary: newFalsePointer(),
+ visible: newFalsePointer(),
+ comment: newEmptyStringPointer(),
+ },
+ },
+ },
+ },
+ viewSet: viewStateMap{},
+ extensionSet: extensionStateMap{},
+ },
+ },
+ },
+ },
+ {
+ statement: `DROP TABLE t1, t2`,
+ want: &DatabaseState{
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ characterSet: "",
+ collation: "",
+ dbType: db.MySQL,
+ schemaSet: schemaStateMap{
+ "": {
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ tableSet: tableStateMap{},
+ viewSet: viewStateMap{},
+ extensionSet: extensionStateMap{},
+ },
+ },
+ },
+ },
+ {
+ statement: `INSERT INTO test values (1)`,
+ want: &DatabaseState{
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ characterSet: "",
+ collation: "",
+ dbType: db.MySQL,
+ schemaSet: schemaStateMap{
+ "": {
+ ctx: &FinderContext{CheckIntegrity: false},
+ name: "",
+ tableSet: tableStateMap{},
+ viewSet: viewStateMap{},
+ extensionSet: extensionStateMap{},
+ },
+ },
},
},
}
-
for _, test := range tests {
- state := newDatabaseState(test.origin, &FinderContext{CheckIntegrity: false})
- err := state.WalkThrough(test.statement)
+ finder := NewEmptyFinder(&FinderContext{CheckIntegrity: false}, db.MySQL)
+ err := finder.WalkThrough(test.statement)
if test.err != nil {
require.Equal(t, err, test.err)
continue
}
require.NoError(t, err)
- want := newDatabaseState(test.want, &FinderContext{CheckIntegrity: false})
- require.Equal(t, want, state, test.statement)
+ require.Equal(t, test.want, finder.Final, test.statement)
}
}
diff --git a/plugin/advisor/mysql/advisor_column_disallow_changing_type.go b/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
index 2a84f8e3f3..cf76a0a3d1 100644
--- a/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
+++ b/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
@@ -7,8 +7,6 @@ import (
"strings"
"github.com/pingcap/tidb/parser/ast"
- "github.com/pingcap/tidb/parser/mysql"
- "github.com/pingcap/tidb/parser/types"
"github.com/bytebase/bytebase/plugin/advisor"
"github.com/bytebase/bytebase/plugin/advisor/catalog"
@@ -79,9 +77,9 @@ func (checker *columnDisallowChangingTypeChecker) Enter(in ast.Node) (ast.Node,
for _, spec := range node.Specs {
switch spec.Tp {
case ast.AlterTableChangeColumn:
- changeType = checker.changeColumnType(node.Table.Name.O, spec.OldColumnName.Name.O, getTypeString(spec.NewColumns[0].Tp))
+ changeType = checker.changeColumnType(node.Table.Name.O, spec.OldColumnName.Name.O, spec.NewColumns[0].Tp.String())
case ast.AlterTableModifyColumn:
- changeType = checker.changeColumnType(node.Table.Name.O, spec.NewColumns[0].Name.Name.O, getTypeString(spec.NewColumns[0].Tp))
+ changeType = checker.changeColumnType(node.Table.Name.O, spec.NewColumns[0].Name.Name.O, spec.NewColumns[0].Tp.String())
}
if changeType {
break
@@ -107,18 +105,30 @@ func (*columnDisallowChangingTypeChecker) Leave(in ast.Node) (ast.Node, bool) {
return in, true
}
-func getTypeString(tp *types.FieldType) string {
- switch tp.GetType() {
- case mysql.TypeTiny, mysql.TypeShort, mysql.TypeInt24, mysql.TypeLong, mysql.TypeLonglong:
- // Referring this issue tidb#6688, the integer max display length is deprecated in MySQL 8.0.
- // Since the length doesn't take any effect in TiDB storage or showing result, we remove it here.
- s := tp.String()
- if idx := strings.Index(s, "("); idx != -1 {
- s = s[:idx]
- }
- return s
+func normalizeColumnType(tp string) string {
+ switch strings.ToLower(tp) {
+ case "tinyint":
+ return "tinyint(4)"
+ case "tinyint unsigned":
+ return "tinyint(4) unsigned"
+ case "smallint":
+ return "smallint(6)"
+ case "smallint unsigned":
+ return "smallint(6) unsigned"
+ case "mediumint":
+ return "mediumint(9)"
+ case "mediumint unsigned":
+ return "mediumint(9) unsigned"
+ case "int":
+ return "int(11)"
+ case "int unsigned":
+ return "int(11) unsigned"
+ case "bigint":
+ return "bigint(20)"
+ case "bigint unsigned":
+ return "bigint(20) unsigned"
default:
- return tp.String()
+ return strings.ToLower(tp)
}
}
@@ -132,5 +142,5 @@ func (checker *columnDisallowChangingTypeChecker) changeColumnType(tableName str
return false
}
- return !strings.EqualFold(column.Type, newType)
+ return normalizeColumnType(column.Type()) != normalizeColumnType(newType)
}
diff --git a/plugin/advisor/mysql/advisor_column_disallow_changing_type_test.go b/plugin/advisor/mysql/advisor_column_disallow_changing_type_test.go
index a4f51b8b6d..89246945cf 100644
--- a/plugin/advisor/mysql/advisor_column_disallow_changing_type_test.go
+++ b/plugin/advisor/mysql/advisor_column_disallow_changing_type_test.go
@@ -10,6 +10,18 @@ import (
func TestColumnDisallowChangingType(t *testing.T) {
tests := []advisor.TestCase{
+ {
+ Statement: `ALTER TABLE tech_book MODIFY id INTEGER UNSIGNED`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.ChangeColumnType,
+ Title: "column.disallow-change-type",
+ Content: "\"ALTER TABLE tech_book MODIFY id INTEGER UNSIGNED\" changes column type",
+ Line: 1,
+ },
+ },
+ },
{
Statement: `ALTER TABLE tech_book MODIFY id int`,
Want: []advisor.Advice{
diff --git a/plugin/advisor/mysql/advisor_column_no_null.go b/plugin/advisor/mysql/advisor_column_no_null.go
index 9ffeee2f7f..0975b00592 100644
--- a/plugin/advisor/mysql/advisor_column_no_null.go
+++ b/plugin/advisor/mysql/advisor_column_no_null.go
@@ -75,7 +75,7 @@ func (checker columnNoNullChecker) generateAdvice() []advisor.Advice {
TableName: column.tableName,
ColumnName: column.columnName,
})
- if col != nil && col.Nullable {
+ if col != nil && col.Nullable() {
checker.adviceList = append(checker.adviceList, advisor.Advice{
Status: checker.level,
Code: advisor.ColumnCanNotNull,
diff --git a/plugin/advisor/mysql/advisor_index_pk_type.go b/plugin/advisor/mysql/advisor_index_pk_type.go
index 142131d556..6d4dca5144 100644
--- a/plugin/advisor/mysql/advisor_index_pk_type.go
+++ b/plugin/advisor/mysql/advisor_index_pk_type.go
@@ -229,7 +229,7 @@ func (v *indexPkTypeChecker) getPKColumnType(tableName string, columnName string
ColumnName: columnName,
})
if column != nil {
- return column.Type, nil
+ return column.Type(), nil
}
return "", errors.Errorf("cannot find the type of `%s`.`%s`", tableName, columnName)
}
diff --git a/plugin/advisor/mysql/advisor_index_type_no_blob.go b/plugin/advisor/mysql/advisor_index_type_no_blob.go
index b44ef6cba9..83c7ec0e16 100644
--- a/plugin/advisor/mysql/advisor_index_type_no_blob.go
+++ b/plugin/advisor/mysql/advisor_index_type_no_blob.go
@@ -225,7 +225,7 @@ func (v *indexTypeNoBlobChecker) getColumnType(tableName string, columnName stri
ColumnName: columnName,
})
if column != nil {
- return column.Type, nil
+ return column.Type(), nil
}
return "", errors.Errorf("cannot find the type of `%s`.`%s`", tableName, columnName)
}
diff --git a/plugin/advisor/mysql/advisor_naming_index_convention.go b/plugin/advisor/mysql/advisor_naming_index_convention.go
index 473a2186b4..8d65596c45 100644
--- a/plugin/advisor/mysql/advisor_naming_index_convention.go
+++ b/plugin/advisor/mysql/advisor_naming_index_convention.go
@@ -161,12 +161,12 @@ func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*ind
if index == nil {
continue
}
- if index.Unique {
+ if index.Unique() {
// Unique index naming convention should in advisor_naming_unique_key_convention.go
continue
}
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: node.Table.Name.String(),
}
res = append(res, &indexMetaData{
diff --git a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go b/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
index 0fbffbd1bb..3a742671bb 100644
--- a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
+++ b/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
@@ -153,12 +153,12 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
if index == nil {
continue
}
- if !index.Unique {
+ if !index.Unique() {
// Index naming convention should in advisor_naming_index_convention.go
continue
}
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: node.Table.Name.String(),
}
res = append(res, &indexMetaData{
diff --git a/plugin/advisor/mysql/advisor_table_require_pk.go b/plugin/advisor/mysql/advisor_table_require_pk.go
index 5f3d0035ed..8892197e26 100644
--- a/plugin/advisor/mysql/advisor_table_require_pk.go
+++ b/plugin/advisor/mysql/advisor_table_require_pk.go
@@ -176,7 +176,7 @@ func (v *tableRequirePKChecker) dropColumn(table string, column string) bool {
if pk == nil {
return false
}
- v.tables[table] = newColumnSet(pk.ExpressionList)
+ v.tables[table] = newColumnSet(pk.ExpressionList())
}
pk := v.tables[table]
diff --git a/plugin/advisor/pg/advisor_column_no_null.go b/plugin/advisor/pg/advisor_column_no_null.go
index fc92795936..722cdb82a5 100644
--- a/plugin/advisor/pg/advisor_column_no_null.go
+++ b/plugin/advisor/pg/advisor_column_no_null.go
@@ -155,7 +155,7 @@ func (checker *columnNoNullChecker) removeColumnByConstraintList(table *ast.Tabl
if index == nil {
continue
}
- for _, expression := range index.ExpressionList {
+ for _, expression := range index.ExpressionList() {
checker.removeColumn(table, expression)
}
}
diff --git a/plugin/advisor/pg/advisor_naming_index_convention.go b/plugin/advisor/pg/advisor_naming_index_convention.go
index d8f66e3c29..607e64c169 100644
--- a/plugin/advisor/pg/advisor_naming_index_convention.go
+++ b/plugin/advisor/pg/advisor_naming_index_convention.go
@@ -137,9 +137,9 @@ func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*ind
TableName: "",
IndexName: node.IndexName,
})
- if index != nil && !index.Unique {
+ if index != nil && !index.Unique() {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: tableName,
}
res = append(res, &indexMetaData{
diff --git a/plugin/advisor/pg/advisor_naming_primary_key_convention.go b/plugin/advisor/pg/advisor_naming_primary_key_convention.go
index dcce6583bc..e0180e332a 100644
--- a/plugin/advisor/pg/advisor_naming_primary_key_convention.go
+++ b/plugin/advisor/pg/advisor_naming_primary_key_convention.go
@@ -145,9 +145,9 @@ func (checker *namingPKConventionChecker) getMetaDataList(in ast.Node) []*indexM
}
case *ast.RenameConstraintStmt:
tableName, index := checker.findIndex(node.Table.Schema, node.Table.Name, node.ConstraintName)
- if index != nil && index.Primary {
+ if index != nil && index.Primary() {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: tableName,
}
res = append(res, &indexMetaData{
@@ -160,9 +160,9 @@ func (checker *namingPKConventionChecker) getMetaDataList(in ast.Node) []*indexM
case *ast.RenameIndexStmt:
// "ALTER INDEX name RENAME TO new_name" doesn't take a table name
tableName, index := checker.findIndex(node.Table.Schema, "", node.IndexName)
- if index != nil && index.Primary {
+ if index != nil && index.Primary() {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: tableName,
}
res = append(res, &indexMetaData{
@@ -194,7 +194,7 @@ func (checker *namingPKConventionChecker) getPrimaryKeyMetadata(schemaName strin
tableName, index := checker.findIndex(schemaName, tableName, constraint.IndexName)
if index != nil {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: tableName,
}
return &indexMetaData{
@@ -209,7 +209,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) {
+func (checker *namingPKConventionChecker) findIndex(schemaName string, tableName string, indexName string) (string, *catalog.IndexState) {
return checker.catalog.Origin.FindIndex(&catalog.IndexFind{
SchemaName: normalizeSchemaName(schemaName),
TableName: tableName,
diff --git a/plugin/advisor/pg/advisor_naming_unique_key_convention.go b/plugin/advisor/pg/advisor_naming_unique_key_convention.go
index d269f001be..c6a5daf538 100644
--- a/plugin/advisor/pg/advisor_naming_unique_key_convention.go
+++ b/plugin/advisor/pg/advisor_naming_unique_key_convention.go
@@ -162,9 +162,9 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
}
case *ast.RenameConstraintStmt:
tableName, index := checker.findIndex(node.Table.Schema, node.Table.Name, node.ConstraintName)
- if index != nil && index.Unique && !index.Primary {
+ if index != nil && index.Unique() && !index.Primary() {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: tableName,
}
res = append(res, &indexMetaData{
@@ -177,9 +177,9 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
case *ast.RenameIndexStmt:
// "ALTER INDEX name RENAME TO new_name" doesn't take a table name
tableName, index := checker.findIndex(node.Table.Schema, "", node.IndexName)
- if index != nil && index.Unique && !index.Primary {
+ if index != nil && index.Unique() && !index.Primary() {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: tableName,
}
res = append(res, &indexMetaData{
@@ -211,7 +211,7 @@ func (checker *namingUKConventionChecker) getUniqueKeyMetadata(schemaName string
tableName, index := checker.findIndex(schemaName, tableName, constraint.IndexName)
if index != nil {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
advisor.TableNameTemplateToken: tableName,
}
return &indexMetaData{
@@ -226,7 +226,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) {
+func (checker *namingUKConventionChecker) findIndex(schemaName string, tableName string, indexName string) (string, *catalog.IndexState) {
return checker.catalog.Origin.FindIndex(&catalog.IndexFind{
SchemaName: normalizeSchemaName(schemaName),
TableName: tableName,
diff --git a/plugin/advisor/pg/advisor_table_require_pk.go b/plugin/advisor/pg/advisor_table_require_pk.go
index 3fd729d664..d63c8d4b08 100644
--- a/plugin/advisor/pg/advisor_table_require_pk.go
+++ b/plugin/advisor/pg/advisor_table_require_pk.go
@@ -89,7 +89,7 @@ func (checker *tableRequirePKChecker) Visit(node ast.Node) ast.Visitor {
TableName: n.Table.Name,
IndexName: n.ConstraintName,
})
- if index != nil && index.Primary {
+ if index != nil && index.Primary() {
missingPK = n.Table
}
// DROP COLUMN
@@ -99,7 +99,7 @@ func (checker *tableRequirePKChecker) Visit(node ast.Node) ast.Visitor {
TableName: n.Table.Name,
})
if pk != nil {
- for _, column := range pk.ExpressionList {
+ for _, column := range pk.ExpressionList() {
if column == n.ColumnName {
missingPK = n.Table
}