Skip to content

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

feat: impl schema design for tidb (#8457)

zll600b93abecc237c
diff --git a/backend/api/v1/schema_design_transformer.go b/backend/api/v1/schema_design_transformer.go
index 7ea911e67d..adcb117fc8 100644
--- a/backend/api/v1/schema_design_transformer.go
+++ b/backend/api/v1/schema_design_transformer.go
@@ -31,6 +31,8 @@ func transformSchemaStringToDatabaseMetadata(engine v1pb.Engine, schema string)
switch engine {
case v1pb.Engine_MYSQL:
return parseMySQLSchemaStringToDatabaseMetadata(schema)
+ case v1pb.Engine_TIDB:
+ return parseTiDBSchemaStringToDatabaseMetadata(schema)
default:
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("unsupported engine: %v", engine))
}
@@ -684,7 +686,13 @@ func getDesignSchema(engine v1pb.Engine, baselineSchema string, to *v1pb.Databas
case v1pb.Engine_MYSQL:
result, err := getMySQLDesignSchema(baselineSchema, to)
if err != nil {
- return "", status.Errorf(codes.Internal, "failed to generate design schema: %v", err)
+ return "", status.Errorf(codes.Internal, "failed to generate mysql design schema: %v", err)
+ }
+ return result, nil
+ case v1pb.Engine_TIDB:
+ result, err := getTiDBDesignSchema(baselineSchema, to)
+ if err != nil {
+ return "", status.Errorf(codes.Internal, "failed to generate tidb design schema: %v", err)
}
return result, nil
default:
@@ -1293,12 +1301,12 @@ func checkDatabaseMetadata(engine v1pb.Engine, metadata *v1pb.DatabaseMetadata)
referencedColumns []string
}
fkMap := make(map[string][]*fkMetadata)
- if engine != v1pb.Engine_MYSQL {
- return errors.Errorf("only mysql is supported")
+ if engine != v1pb.Engine_MYSQL && engine != v1pb.Engine_TIDB {
+ return errors.Errorf("only mysql and tidb are supported")
}
for _, schema := range metadata.Schemas {
if schema.Name != "" {
- return errors.Errorf("schema name should be empty for MySQL")
+ return errors.Errorf("schema name should be empty for MySQL and TiDB")
}
tableNameMap := make(map[string]bool)
for _, table := range schema.Tables {
@@ -1323,7 +1331,7 @@ func checkDatabaseMetadata(engine v1pb.Engine, metadata *v1pb.DatabaseMetadata)
return errors.Errorf("column %s type should not be empty in table %s", column.Name, table.Name)
}
- if !checkMySQLColumnType(column.Type) {
+ if !checkColumnType(engine, column.Type) {
return errors.Errorf("column %s type %s is invalid in table %s", column.Name, column.Type, table.Name)
}
}
@@ -1422,6 +1430,17 @@ func checkDatabaseMetadata(engine v1pb.Engine, metadata *v1pb.DatabaseMetadata)
return nil
}
+func checkColumnType(engine v1pb.Engine, tp string) bool {
+ switch engine {
+ case v1pb.Engine_MYSQL:
+ return checkMySQLColumnType(tp)
+ case v1pb.Engine_TIDB:
+ return checkTiDBColumnType(tp)
+ default:
+ return false
+ }
+}
+
func checkMySQLColumnType(tp string) bool {
_, err := parser.ParseMySQL(fmt.Sprintf("CREATE TABLE t (a %s NOT NULL)", tp))
return err == nil
diff --git a/backend/api/v1/schema_design_transformer_tidb.go b/backend/api/v1/schema_design_transformer_tidb.go
new file mode 100644
index 0000000000..c7ba8025f4
--- /dev/null
+++ b/backend/api/v1/schema_design_transformer_tidb.go
@@ -0,0 +1,875 @@
+package v1
+
+import (
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/pkg/errors"
+
+ tidbast "github.com/pingcap/tidb/parser/ast"
+ tidbformat "github.com/pingcap/tidb/parser/format"
+ tidbmysql "github.com/pingcap/tidb/parser/mysql"
+ tidbtypes "github.com/pingcap/tidb/parser/types"
+
+ parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+)
+
+func checkTiDBColumnType(tp string) bool {
+ _, err := parser.ParseTiDB(fmt.Sprintf("CREATE TABLE t (a %s NOT NULL)", tp), "", "")
+ return err == nil
+}
+
+type tidbTransformer struct {
+ tidbast.StmtNode
+
+ state *databaseState
+ err error
+}
+
+func parseTiDBSchemaStringToDatabaseMetadata(schema string) (*v1pb.DatabaseMetadata, error) {
+ stmts, err := parser.ParseTiDB(schema, "", "")
+ if err != nil {
+ return nil, err
+ }
+
+ transformer := &tidbTransformer{
+ state: newDatabaseState(),
+ }
+ transformer.state.schemas[""] = newSchemaState()
+
+ for _, stmt := range stmts {
+ (stmt).Accept(transformer)
+ }
+ return transformer.state.convertToDatabaseMetadata(), transformer.err
+}
+
+func (t *tidbTransformer) Enter(in tidbast.Node) (tidbast.Node, bool) {
+ if node, ok := in.(*tidbast.CreateTableStmt); ok {
+ dbInfo := node.Table.DBInfo
+ databaseName := ""
+ if dbInfo != nil {
+ databaseName = dbInfo.Name.String()
+ }
+ if databaseName != "" {
+ if t.state.name == "" {
+ t.state.name = databaseName
+ } else if t.state.name != databaseName {
+ t.err = errors.New("multiple database names found: " + t.state.name + ", " + databaseName)
+ return in, true
+ }
+ }
+
+ tableName := node.Table.Name.String()
+ schema := t.state.schemas[""]
+ if _, ok := schema.tables[tableName]; ok {
+ t.err = errors.New("multiple table names found: " + tableName)
+ return in, true
+ }
+ schema.tables[tableName] = newTableState(len(schema.tables), tableName)
+
+ table := t.state.schemas[""].tables[tableName]
+
+ // column definition
+ for _, column := range node.Cols {
+ dataType := columnTypeStr(column.Tp)
+ columnName := column.Name.Name.String()
+ if _, ok := table.columns[columnName]; ok {
+ t.err = errors.New("multiple column names found: " + columnName + " in table " + tableName)
+ return in, true
+ }
+ defaultValue, err := columnDefaultValue(column)
+ if err != nil {
+ t.err = err
+ return in, true
+ }
+ comment, err := columnComment(column)
+ if err != nil {
+ t.err = err
+ return in, true
+ }
+ columnState := &columnState{
+ id: len(table.columns),
+ name: columnName,
+ tp: dataType,
+ defaultValue: defaultValue,
+ comment: comment,
+ nullable: tidbColumnCanNull(column),
+ }
+
+ table.columns[columnName] = columnState
+ }
+
+ // primary and foreign key definition
+ for _, constraint := range node.Constraints {
+ switch constraint.Tp {
+ case tidbast.ConstraintPrimaryKey:
+ var pkList []string
+ for _, constraint := range node.Constraints {
+ if constraint.Tp == tidbast.ConstraintPrimaryKey {
+ var pks []string
+ for _, key := range constraint.Keys {
+ columnName := key.Column.Name.String()
+ pks = append(pks, columnName)
+ }
+ pkList = append(pkList, pks...)
+ }
+ }
+
+ table.indexes["PRIMARY"] = &indexState{
+ id: len(table.indexes),
+ name: "PRIMARY",
+ keys: pkList,
+ primary: true,
+ unique: true,
+ }
+ case tidbast.ConstraintForeignKey:
+ var referencingColumnList []string
+ for _, key := range constraint.Keys {
+ referencingColumnList = append(referencingColumnList, key.Column.Name.String())
+ }
+ var referencedColumnList []string
+ for _, spec := range constraint.Refer.IndexPartSpecifications {
+ referencedColumnList = append(referencedColumnList, spec.Column.Name.String())
+ }
+
+ fkName := constraint.Name
+ if fkName == "" {
+ t.err = errors.New("empty foreign key name")
+ return in, true
+ }
+ if table.foreignKeys[fkName] != nil {
+ t.err = errors.New("multiple foreign keys found: " + fkName)
+ return in, true
+ }
+
+ fk := &foreignKeyState{
+ id: len(table.foreignKeys),
+ name: fkName,
+ columns: referencingColumnList,
+ referencedTable: constraint.Refer.Table.Name.String(),
+ referencedColumns: referencedColumnList,
+ }
+ table.foreignKeys[fkName] = fk
+ }
+ }
+ }
+ return in, false
+}
+
+// getIntOrBigIntStr returns the type string of tp.
+func columnTypeStr(tp *tidbtypes.FieldType) string {
+ switch tp.GetType() {
+ // https://pkg.go.dev/github.com/pingcap/tidb/parser/mysql#TypeLong
+ case tidbmysql.TypeLong:
+ // tp.String() return int(11)
+ return "int"
+ // https://pkg.go.dev/github.com/pingcap/tidb/parser/mysql#TypeLonglong
+ case tidbmysql.TypeLonglong:
+ // tp.String() return bigint(20)
+ return "bigint"
+ default:
+ return tp.String()
+ }
+}
+
+func tidbColumnCanNull(column *tidbast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == tidbast.ColumnOptionNotNull || option.Tp == tidbast.ColumnOptionPrimaryKey {
+ return false
+ }
+ }
+ return true
+}
+
+func columnDefaultValue(column *tidbast.ColumnDef) (*string, error) {
+ for _, option := range column.Options {
+ if option.Tp == tidbast.ColumnOptionDefaultValue {
+ defaultValue, err := tidbRestoreNode(option.Expr, tidbformat.RestoreStringSingleQuotes|tidbformat.RestoreStringWithoutCharset)
+ if err != nil {
+ return nil, err
+ }
+ return &defaultValue, nil
+ }
+ }
+ // no default value.
+ return nil, nil
+}
+
+func columnComment(column *tidbast.ColumnDef) (string, error) {
+ for _, option := range column.Options {
+ if option.Tp == tidbast.ColumnOptionComment {
+ comment, err := tidbRestoreNode(option.Expr, tidbformat.RestoreStringWithoutCharset)
+ if err != nil {
+ return "", err
+ }
+ return comment, nil
+ }
+ }
+
+ return "", nil
+}
+
+func tidbRestoreNode(node tidbast.Node, flag tidbformat.RestoreFlags) (string, error) {
+ var buffer strings.Builder
+ ctx := tidbformat.NewRestoreCtx(flag, &buffer)
+ if err := node.Restore(ctx); err != nil {
+ return "", err
+ }
+ return buffer.String(), nil
+}
+func tidbRestoreNodeDefault(node tidbast.Node) (string, error) {
+ return tidbRestoreNode(node, tidbformat.DefaultRestoreFlags)
+}
+
+func tidbRestoreFieldType(fieldType *tidbtypes.FieldType) (string, error) {
+ var buffer strings.Builder
+ flag := tidbformat.RestoreKeyWordLowercase
+ ctx := tidbformat.NewRestoreCtx(flag, &buffer)
+ if err := fieldType.Restore(ctx); err != nil {
+ return "", err
+ }
+ return buffer.String(), nil
+}
+
+func tidbRestoreTableOption(tableOption *tidbast.TableOption) (string, error) {
+ var buffer strings.Builder
+ flag := tidbformat.DefaultRestoreFlags
+ ctx := tidbformat.NewRestoreCtx(flag, &buffer)
+ if err := tableOption.Restore(ctx); err != nil {
+ return "", err
+ }
+ return buffer.String(), nil
+}
+
+func (*tidbTransformer) Leave(in tidbast.Node) (tidbast.Node, bool) {
+ return in, true
+}
+
+func getTiDBDesignSchema(baselineSchema string, to *v1pb.DatabaseMetadata) (string, error) {
+ toState := convertToDatabaseState(to)
+ stmts, err := parser.ParseTiDB(baselineSchema, "", "")
+ if err != nil {
+ return "", err
+ }
+
+ generator := &tidbDesignSchemaGenerator{
+ to: toState,
+ }
+
+ for _, stmt := range stmts {
+ switch stmt.(type) {
+ case *tidbast.CreateTableStmt:
+ stmt.Accept(generator)
+ default:
+ if _, err := generator.result.WriteString(stmt.OriginalText() + "\n"); err != nil {
+ return "", err
+ }
+ }
+ }
+ if generator.err != nil {
+ return "", generator.err
+ }
+
+ firstTable := true
+ for _, schema := range to.Schemas {
+ schemaState, ok := toState.schemas[schema.Name]
+ if !ok {
+ continue
+ }
+ for _, table := range schema.Tables {
+ table, ok := schemaState.tables[table.Name]
+ if !ok {
+ continue
+ }
+ if firstTable {
+ firstTable = false
+ if _, err := generator.result.WriteString("\n"); err != nil {
+ return "", err
+ }
+ }
+ if err := table.toString(&generator.result); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ return generator.result.String(), nil
+}
+
+type tidbDesignSchemaGenerator struct {
+ tidbast.Node
+
+ to *databaseState
+ result strings.Builder
+ currentTable *tableState
+ firstElementInTable bool
+ columnDefine strings.Builder
+ tableConstraints strings.Builder
+ err error
+}
+
+func (g *tidbDesignSchemaGenerator) Enter(in tidbast.Node) (tidbast.Node, bool) {
+ if g.err != nil {
+ return in, true
+ }
+
+ if node, ok := in.(*tidbast.CreateTableStmt); ok {
+ dbInfo := node.Table.DBInfo
+ databaseName := ""
+ if dbInfo != nil {
+ databaseName = dbInfo.Name.String()
+ }
+ if databaseName != "" && g.to.name != "" && databaseName != g.to.name {
+ g.err = errors.New("multiple database names found: " + g.to.name + ", " + databaseName)
+ return in, true
+ }
+
+ schema, ok := g.to.schemas[""]
+ if !ok || schema == nil {
+ return in, true
+ }
+
+ tableName := node.Table.Name.String()
+ table, ok := schema.tables[tableName]
+ if !ok {
+ return in, true
+ }
+ g.currentTable = table
+ g.firstElementInTable = true
+ g.columnDefine.Reset()
+ g.tableConstraints.Reset()
+
+ delete(schema.tables, tableName)
+
+ // Start constructing sql.
+ // Temporary keyword.
+ var temporaryKeyword string
+ switch node.TemporaryKeyword {
+ case tidbast.TemporaryNone:
+ temporaryKeyword = "CREATE TABLE "
+ case tidbast.TemporaryGlobal:
+ temporaryKeyword = "CREATE GLOBAL TEMPORARY TABLE "
+ case tidbast.TemporaryLocal:
+ temporaryKeyword = "CREATE TEMPORARY TABLE "
+ }
+ if _, err := g.result.WriteString(temporaryKeyword); err != nil {
+ g.err = err
+ return in, true
+ }
+
+ // if not exists
+ if node.IfNotExists {
+ if _, err := g.result.WriteString("IF NOT EXISTS "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ if tableNameStr, err := tidbRestoreNodeDefault(tidbast.Node(node.Table)); err == nil {
+ if _, err := g.result.WriteString(tableNameStr + " "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ if node.ReferTable != nil {
+ if _, err := g.result.WriteString(" LIKE "); err != nil {
+ g.err = err
+ return in, true
+ }
+ if referTableStr, err := tidbRestoreNodeDefault(tidbast.Node(node.ReferTable)); err == nil {
+ if _, err := g.result.WriteString(referTableStr + " "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+
+ if _, err := g.result.WriteString("(\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+
+ // Column definition.
+ for _, column := range node.Cols {
+ columnName := column.Name.Name.String()
+ stateColumn, ok := g.currentTable.columns[columnName]
+ if !ok {
+ continue
+ }
+
+ delete(g.currentTable.columns, columnName)
+
+ if g.firstElementInTable {
+ g.firstElementInTable = false
+ } else {
+ if _, err := g.columnDefine.WriteString(",\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ // Column name.
+ if columnNameStr, err := tidbRestoreNodeDefault(tidbast.Node(column.Name)); err == nil {
+ if _, err := g.columnDefine.WriteString(columnNameStr + " "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ // Compare column types.
+ dataType := columnTypeStr(column.Tp)
+ if !strings.EqualFold(dataType, stateColumn.tp) {
+ // write lower case column type for tidb
+ column.Tp = tidbNewFieldType(stateColumn.tp)
+ }
+ if typeStr, err := tidbRestoreFieldType(column.Tp); err == nil {
+ if _, err := g.columnDefine.WriteString(typeStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ // Column attributes.
+ newAttr := tidbExtractNewAttrs(stateColumn, column.Options)
+ for _, option := range column.Options {
+ attrOrder := tidbGetAttrOrder(option)
+ for ; len(newAttr) > 0 && newAttr[0].order < attrOrder; newAttr = newAttr[1:] {
+ if _, err := g.columnDefine.WriteString(" " + newAttr[0].text); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ switch option.Tp {
+ case tidbast.ColumnOptionNull, tidbast.ColumnOptionNotNull:
+ sameNullable := option.Tp == tidbast.ColumnOptionNull && stateColumn.nullable
+ sameNullable = sameNullable || (option.Tp == tidbast.ColumnOptionNotNull && !stateColumn.nullable)
+
+ if sameNullable {
+ if optionStr, err := tidbRestoreNodeDefault(tidbast.Node(option)); err == nil {
+ if _, err := g.columnDefine.WriteString(" " + optionStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ } else {
+ if stateColumn.nullable {
+ if _, err := g.columnDefine.WriteString(" NULL"); err != nil {
+ g.err = err
+ return in, true
+ }
+ } else {
+ if _, err := g.columnDefine.WriteString(" NOT NULL"); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+ case tidbast.ColumnOptionDefaultValue:
+ defaultValue, err := columnDefaultValue(column)
+ if err != nil {
+ g.err = err
+ return in, true
+ }
+ if stateColumn.defaultValue != nil && *stateColumn.defaultValue == *defaultValue {
+ if defaultStr, err := tidbRestoreNodeDefault(option); err == nil {
+ if _, err := g.columnDefine.WriteString(" " + defaultStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ } else if stateColumn.defaultValue != nil {
+ if _, err := g.columnDefine.WriteString("DEFAULT"); err != nil {
+ g.err = err
+ return in, true
+ }
+ if _, err := g.columnDefine.WriteString(*stateColumn.defaultValue); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ case tidbast.ColumnOptionComment:
+ commentValue, err := columnComment(column)
+ if err != nil {
+ g.err = err
+ return in, true
+ }
+ if stateColumn.comment == commentValue {
+ if commentStr, err := tidbRestoreNodeDefault(option); err == nil {
+ if _, err := g.columnDefine.WriteString(" " + commentStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ } else if stateColumn.comment != "" {
+ if _, err := g.columnDefine.WriteString("COMMENT" + " "); err != nil {
+ g.err = err
+ return in, true
+ }
+ if _, err := g.columnDefine.WriteString(fmt.Sprintf("'%s'", stateColumn.comment)); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ default:
+ if optionStr, err := tidbRestoreNodeDefault(option); err == nil {
+ if _, err := g.columnDefine.WriteString(" " + optionStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+ }
+
+ for _, attr := range newAttr {
+ if _, err := g.columnDefine.WriteString(" " + attr.text); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+
+ // Table Constraint.
+ for _, constraint := range node.Constraints {
+ switch constraint.Tp {
+ case tidbast.ConstraintPrimaryKey:
+ if g.currentTable.indexes["PRIMARY"] != nil {
+ if g.firstElementInTable {
+ g.firstElementInTable = false
+ } else {
+ if _, err := g.tableConstraints.WriteString(",\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ var keys []string
+ for _, key := range constraint.Keys {
+ keys = append(keys, key.Column.Name.String())
+ }
+ if equalKeys(keys, g.currentTable.indexes["PRIMARY"].keys) {
+ if constraintStr, err := tidbRestoreNodeDefault(constraint); err == nil {
+ if _, err := g.tableConstraints.WriteString(constraintStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ } else {
+ if err := g.currentTable.indexes["PRIMARY"].toString(&g.tableConstraints); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ delete(g.currentTable.indexes, "PRIMARY")
+ }
+ case tidbast.ConstraintForeignKey:
+ fkName := constraint.Name
+ if fkName == "" {
+ g.err = errors.New("empty foreign key name")
+ return in, true
+ }
+ if g.currentTable.foreignKeys[fkName] != nil {
+ if g.firstElementInTable {
+ g.firstElementInTable = false
+ } else {
+ if _, err := g.tableConstraints.WriteString(",\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ fk := g.currentTable.foreignKeys[fkName]
+
+ var columns []string
+ for _, key := range constraint.Keys {
+ columns = append(columns, key.Column.Name.String())
+ }
+
+ var referencedColumnList []string
+ for _, spec := range constraint.Refer.IndexPartSpecifications {
+ referencedColumnList = append(referencedColumnList, spec.Column.Name.String())
+ }
+ referencedTable := constraint.Refer.Table.Name.String()
+ if equalKeys(columns, fk.columns) && referencedTable == fk.referencedTable && equalKeys(referencedColumnList, fk.referencedColumns) {
+ if constraintStr, err := tidbRestoreNodeDefault(constraint); err == nil {
+ if _, err := g.tableConstraints.WriteString(constraintStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ } else {
+ if err := fk.toString(&g.tableConstraints); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ delete(g.currentTable.foreignKeys, fkName)
+ }
+ default:
+ if g.firstElementInTable {
+ g.firstElementInTable = false
+ } else {
+ if _, err := g.tableConstraints.WriteString(",\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ if constraintStr, err := tidbRestoreNodeDefault(constraint); err == nil {
+ if _, err := g.tableConstraints.WriteString(constraintStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+ }
+ }
+
+ return in, false
+}
+
+func (g *tidbDesignSchemaGenerator) Leave(in tidbast.Node) (tidbast.Node, bool) {
+ if g.err != nil || g.currentTable == nil {
+ return in, true
+ }
+ if node, ok := in.(*tidbast.CreateTableStmt); ok {
+ // Column definition.
+ var columnList []*columnState
+ for _, column := range g.currentTable.columns {
+ columnList = append(columnList, column)
+ }
+ sort.Slice(columnList, func(i, j int) bool {
+ return columnList[i].id < columnList[j].id
+ })
+ for _, column := range columnList {
+ if g.firstElementInTable {
+ g.firstElementInTable = false
+ } else {
+ if _, err := g.columnDefine.WriteString(",\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ if err := column.toString(&g.columnDefine); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+
+ // Primary key definition.
+ if g.currentTable.indexes["PRIMARY"] != nil {
+ if g.firstElementInTable {
+ g.firstElementInTable = false
+ } else {
+ if _, err := g.columnDefine.WriteString(",\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ if err := g.currentTable.indexes["PRIMARY"].toString(&g.tableConstraints); err != nil {
+ return in, true
+ }
+ }
+
+ // Foreign key definition.
+ var fks []*foreignKeyState
+ for _, fk := range g.currentTable.foreignKeys {
+ fks = append(fks, fk)
+ }
+ sort.Slice(fks, func(i, j int) bool {
+ return fks[i].id < fks[j].id
+ })
+ for _, fk := range fks {
+ if g.firstElementInTable {
+ g.firstElementInTable = false
+ } else {
+ if _, err := g.columnDefine.WriteString(",\n "); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ if err := fk.toString(&g.tableConstraints); err != nil {
+ return in, true
+ }
+ }
+
+ if _, err := g.result.WriteString(g.columnDefine.String()); err != nil {
+ g.err = err
+ return in, true
+ }
+ if _, err := g.result.WriteString(g.tableConstraints.String()); err != nil {
+ g.err = err
+ return in, true
+ }
+ if _, err := g.result.WriteString("\n)"); err != nil {
+ g.err = err
+ return in, true
+ }
+
+ // Table option.
+ for _, option := range node.Options {
+ if optionStr, err := tidbRestoreTableOption(option); err == nil {
+ if _, err := g.result.WriteString(" " + optionStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+
+ // Table partition.
+ if node.Partition != nil {
+ if partitionStr, err := tidbRestoreNodeDefault(node.Partition); err == nil {
+ if _, err := g.result.WriteString(" " + partitionStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+
+ // Table select.
+ if node.Select != nil {
+ duplicateStr := ""
+ switch node.OnDuplicate {
+ case tidbast.OnDuplicateKeyHandlingError:
+ duplicateStr = " AS "
+ case tidbast.OnDuplicateKeyHandlingIgnore:
+ duplicateStr = " IGNORE AS "
+ case tidbast.OnDuplicateKeyHandlingReplace:
+ duplicateStr = " REPLACE AS "
+ }
+
+ if selectStr, err := tidbRestoreNodeDefault(node.Select); err == nil {
+ if _, err := g.result.WriteString(duplicateStr + selectStr); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+
+ if node.TemporaryKeyword == tidbast.TemporaryGlobal {
+ if node.OnCommitDelete {
+ if _, err := g.result.WriteString(" ON COMMIT DELETE ROWS"); err != nil {
+ g.err = err
+ return in, true
+ }
+ } else {
+ if _, err := g.result.WriteString(" ON COMMIT PRESERVE ROWS"); err != nil {
+ g.err = err
+ return in, true
+ }
+ }
+ }
+ if _, err := g.result.WriteString(";\n"); err != nil {
+ g.err = err
+ return in, true
+ }
+
+ g.currentTable = nil
+ g.firstElementInTable = false
+ }
+ return in, true
+}
+
+func tidbExtractNewAttrs(column *columnState, options []*tidbast.ColumnOption) []columnAttr {
+ var result []columnAttr
+ nullExists := false
+ defaultExists := false
+ commentExists := false
+
+ for _, option := range options {
+ switch option.Tp {
+ case tidbast.ColumnOptionNull, tidbast.ColumnOptionNotNull:
+ nullExists = true
+ case tidbast.ColumnOptionDefaultValue:
+ defaultExists = true
+ case tidbast.ColumnOptionComment:
+ commentExists = true
+ }
+ }
+
+ if !nullExists && !column.nullable {
+ result = append(result, columnAttr{
+ text: "NOT NULL",
+ order: columnAttrOrder["NULL"],
+ })
+ }
+ if !defaultExists && column.defaultValue != nil {
+ result = append(result, columnAttr{
+ text: "DEFAULT " + *column.defaultValue,
+ order: columnAttrOrder["DEFAULT"],
+ })
+ }
+ if !commentExists && column.comment != "" {
+ result = append(result, columnAttr{
+ text: "COMMENT '" + column.comment + "'",
+ order: columnAttrOrder["COMMENT"],
+ })
+ }
+ return result
+}
+
+func tidbGetAttrOrder(option *tidbast.ColumnOption) int {
+ switch option.Tp {
+ case tidbast.ColumnOptionDefaultValue:
+ return columnAttrOrder["DEFAULT"]
+ case tidbast.ColumnOptionNull, tidbast.ColumnOptionNotNull:
+ return columnAttrOrder["NULL"]
+ case tidbast.ColumnOptionUniqKey:
+ return columnAttrOrder["UNIQUE"]
+ case tidbast.ColumnOptionColumnFormat:
+ return columnAttrOrder["COLUMN_FORMAT"]
+ case tidbast.ColumnOptionAutoIncrement:
+ return columnAttrOrder["AUTO_INCREMENT"]
+ case tidbast.ColumnOptionComment:
+ return columnAttrOrder["COMMENT"]
+ case tidbast.ColumnOptionCollate:
+ return columnAttrOrder["COLLATE"]
+ case tidbast.ColumnOptionStorage:
+ return columnAttrOrder["STORAGE"]
+ case tidbast.ColumnOptionCheck:
+ return columnAttrOrder["CHECK"]
+ }
+ if option.Enforced {
+ return columnAttrOrder["ENFORCED"]
+ }
+ return len(columnAttrOrder) + 1
+}
+
+func tidbNewFieldType(tp string) *tidbtypes.FieldType {
+ tpStr := strings.ToLower(tp)
+ var s []byte
+ var flen []byte
+ var decimal []byte
+ stage := 1
+ for i := 0; i < len(tpStr); i++ {
+ if tpStr[i] == '(' {
+ stage = 2
+ continue
+ } else if tpStr[i] == ',' {
+ stage = 3
+ continue
+ } else if tpStr[i] == ')' {
+ continue
+ }
+
+ if stage == 1 {
+ s = append(s, tpStr[i])
+ } else if stage == 2 {
+ flen = append(flen, tpStr[i])
+ } else if stage == 3 {
+ decimal = append(decimal, tpStr[i])
+ }
+ }
+ ft := tidbtypes.NewFieldType(tidbtypes.StrToType(string(s)))
+ flenInt, _ := strconv.Atoi(string(flen))
+ if flenInt > 0 {
+ ft.SetFlen(flenInt)
+ }
+ decimalInt, _ := strconv.Atoi(string(decimal))
+ if decimalInt > 0 {
+ ft.SetDecimal(decimalInt)
+ }
+ return ft
+}
diff --git a/backend/api/v1/schema_design_transformer_tidb_test.go b/backend/api/v1/schema_design_transformer_tidb_test.go
new file mode 100644
index 0000000000..de949aa16c
--- /dev/null
+++ b/backend/api/v1/schema_design_transformer_tidb_test.go
@@ -0,0 +1,125 @@
+package v1
+
+import (
+ "io"
+ "os"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
+)
+
+func TestTiDBTransformSchemaString(t *testing.T) {
+ const (
+ record = false
+ )
+ var (
+ filepath = "testdata/tidb/schema.yaml"
+ )
+
+ a := require.New(t)
+ yamlFile, err := os.Open(filepath)
+ a.NoError(err)
+
+ tests := []transformTest{}
+ byteValue, err := io.ReadAll(yamlFile)
+ a.NoError(yamlFile.Close())
+ a.NoError(err)
+ a.NoError(yaml.Unmarshal(byteValue, &tests))
+
+ for i, t := range tests {
+ result, err := transformSchemaStringToDatabaseMetadata(t.Engine, t.Schema)
+ a.NoError(err)
+ if record {
+ tests[i].Metadata = result
+ } else {
+ a.Equal(t.Metadata, result)
+ }
+ }
+
+ if record {
+ byteValue, err := yaml.Marshal(tests)
+ a.NoError(err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ a.NoError(err)
+ }
+}
+
+func TestTiDBGetDesignSchema(t *testing.T) {
+ const (
+ record = false
+ )
+ var (
+ filepath = "testdata/tidb/design.yaml"
+ )
+
+ a := require.New(t)
+ yamlFile, err := os.Open(filepath)
+ a.NoError(err)
+
+ tests := []designTest{}
+ byteValue, err := io.ReadAll(yamlFile)
+ a.NoError(yamlFile.Close())
+ a.NoError(err)
+ a.NoError(yaml.Unmarshal(byteValue, &tests))
+
+ for i, t := range tests {
+ result, err := getDesignSchema(t.Engine, t.Baseline, t.Target)
+ a.NoError(err)
+ if record {
+ tests[i].Result = result
+ } else {
+ a.Equal(t.Result, result)
+ }
+ }
+
+ if record {
+ byteValue, err := yaml.Marshal(tests)
+ a.NoError(err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ a.NoError(err)
+ }
+}
+
+func TestTiDBCheckDatabaseMetadata(t *testing.T) {
+ const (
+ record = false
+ )
+ var (
+ filepath = "testdata/tidb/check.yaml"
+ )
+
+ a := require.New(t)
+ yamlFile, err := os.Open(filepath)
+ a.NoError(err)
+
+ tests := []checkTest{}
+ byteValue, err := io.ReadAll(yamlFile)
+ a.NoError(yamlFile.Close())
+ a.NoError(err)
+ a.NoError(yaml.Unmarshal(byteValue, &tests))
+
+ for i, t := range tests {
+ err := checkDatabaseMetadata(t.Engine, t.Metadata)
+ if record {
+ if err != nil {
+ tests[i].Err = err.Error()
+ } else {
+ tests[i].Err = ""
+ }
+ } else {
+ if t.Err == "" {
+ a.NoError(err)
+ } else {
+ a.Equal(t.Err, err.Error())
+ }
+ }
+ }
+
+ if record {
+ byteValue, err := yaml.Marshal(tests)
+ a.NoError(err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ a.NoError(err)
+ }
+}
diff --git a/backend/api/v1/testdata/tidb/check.yaml b/backend/api/v1/testdata/tidb/check.yaml
new file mode 100644
index 0000000000..03ea0cf650
--- /dev/null
+++ b/backend/api/v1/testdata/tidb/check.yaml
@@ -0,0 +1,510 @@
+- engine: 6
+ metadata:
+ name: ""
+ schemas:
+ - name: ""
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 0
+ default:
+ value: "1"
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: abcdefg
+ classification: ""
+ usercomment: ""
+ - name: b
+ position: 0
+ default:
+ value: "'NULL'"
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - a
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - a
+ referencedschema: ""
+ referencedtable: t2
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default:
+ value: "NULL"
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ views: []
+ functions: []
+ streams: []
+ tasks: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: ""
+- engine: 6
+ metadata:
+ name: ""
+ schemas:
+ - name: ""
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 0
+ default:
+ value: "1"
+ nullable: true
+ type: abcd
+ characterset: ""
+ collation: ""
+ comment: abcdefg
+ classification: ""
+ usercomment: ""
+ - name: b
+ position: 0
+ default:
+ value: "'NULL'"
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - a
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - a
+ referencedschema: ""
+ referencedtable: t2
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default:
+ value: "NULL"
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ views: []
+ functions: []
+ streams: []
+ tasks: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: column a type abcd is invalid in table t
+- engine: 6
+ metadata:
+ name: ""
+ schemas:
+ - name: ""
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 0
+ default:
+ value: "1"
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: abcdefg
+ classification: ""
+ usercomment: ""
+ - name: b
+ position: 0
+ default:
+ value: "'NULL'"
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - a
+ - c
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - a
+ referencedschema: ""
+ referencedtable: t2
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default:
+ value: "NULL"
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ views: []
+ functions: []
+ streams: []
+ tasks: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: primary key column c not found in table t
+- engine: 6
+ metadata:
+ name: ""
+ schemas:
+ - name: ""
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 0
+ default:
+ value: "1"
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: abcdefg
+ classification: ""
+ usercomment: ""
+ - name: b
+ position: 0
+ default:
+ value: "'NULL'"
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - a
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - a
+ referencedschema: ""
+ referencedtable: t2
+ referencedcolumns:
+ - a
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default:
+ value: "NULL"
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ views: []
+ functions: []
+ streams: []
+ tasks: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: foreign key fk1 in table t references column a in table t2 but not found
+- engine: 6
+ metadata:
+ name: ""
+ schemas:
+ - name: ""
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 0
+ default:
+ value: "1"
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: abcdefg
+ classification: ""
+ usercomment: ""
+ - name: b
+ position: 0
+ default:
+ value: "'NULL'"
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - a
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - a
+ referencedschema: ""
+ referencedtable: t3
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default:
+ value: "NULL"
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ views: []
+ functions: []
+ streams: []
+ tasks: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: foreign key fk1 in table t references table t3 but not found
diff --git a/backend/api/v1/testdata/tidb/design.yaml b/backend/api/v1/testdata/tidb/design.yaml
new file mode 100644
index 0000000000..78f45cadb7
--- /dev/null
+++ b/backend/api/v1/testdata/tidb/design.yaml
@@ -0,0 +1,229 @@
+- engine: 6
+ baseline: |-
+ CREATE TABLE `t` (
+ `a` int,
+ PRIMARY KEY (`a`),
+ CONSTRAINT fk1 FOREIGN KEY (`a`) REFERENCES `t2` (`b`)
+ );
+ CREATE TABLE `t3` (
+ `a` int
+ );
+ CREATE TABLE `t4` (
+ `a` int,
+ `c` int,
+ `d` int,
+ `e` char(10) NOT NULL DEFAULT 'NULL' comment 'this is comment',
+ PRIMARY KEY (`a`, `c`, `d`),
+ CONSTRAINT fk1 FOREIGN KEY (`a`) REFERENCES `t2` (`b`)
+ );
+ CREATE TABLE `users` (
+ `id` int(11) NOT NULL COMMENT 'ID',
+ PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
+ target:
+ name: ""
+ schemas:
+ - name: ""
+ tables:
+ - name: users
+ columns:
+ - name: id
+ position: 0
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: "ID"
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - id
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ - name: t
+ columns:
+ - name: a
+ position: 0
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ - name: t4
+ columns:
+ - name: a
+ position: 0
+ default:
+ value: "'default value'"
+ nullable: false
+ type: varchar(10)
+ characterset: ""
+ collation: ""
+ comment: this is comment, aha
+ classification: ""
+ usercomment: ""
+ - name: b
+ position: 0
+ default: null
+ nullable: false
+ type: char(10)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ - name: c
+ position: 0
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ - name: e
+ position: 0
+ default: null
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - a
+ - b
+ - c
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - b
+ referencedschema: ""
+ referencedtable: t2
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default: null
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ - name: a
+ position: 0
+ default: null
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - b
+ referencedschema: ""
+ referencedtable: t4
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ views: []
+ functions: []
+ streams: []
+ tasks: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ result: |
+ CREATE TABLE `t` (
+ `a` int NOT NULL
+ );
+ CREATE TABLE `t4` (
+ `a` varchar(10) NOT NULL DEFAULT 'default value' COMMENT 'this is comment, aha',
+ `c` int NOT NULL,
+ `e` int NULL,
+ `b` char(10) NOT NULL,
+ PRIMARY KEY (`a`, `b`, `c`),
+ CONSTRAINT `fk1` FOREIGN KEY (`b`) REFERENCES `t2` (`b`)
+ );
+ CREATE TABLE `users` (
+ `id` int(11) NOT NULL COMMENT 'ID',
+ PRIMARY KEY(`id`) CLUSTERED
+ ) ENGINE = InnoDB DEFAULT CHARACTER SET = UTF8MB4 DEFAULT COLLATE = UTF8MB4_BIN;
+
+ CREATE TABLE `t2` (
+ `b` int NULL,
+ `a` int NULL,
+ PRIMARY KEY (`b`),
+ CONSTRAINT `fk1` FOREIGN KEY (`b`) REFERENCES `t4` (`b`)
+ );
diff --git a/backend/api/v1/testdata/tidb/schema.yaml b/backend/api/v1/testdata/tidb/schema.yaml
new file mode 100644
index 0000000000..c1673f53fe
--- /dev/null
+++ b/backend/api/v1/testdata/tidb/schema.yaml
@@ -0,0 +1,121 @@
+- engine: 6
+ schema: |
+ create table t
+ (
+ c int,
+ a int default 1 comment 'abcdefg',
+ b varchar(20) default 'NULL' comment '',
+ primary key (a, b),
+ constraint fk1 foreign key (a) references t2 (b)
+ );
+ create table t2(b int NOT NULL default NULL, primary key (b));
+ metadata:
+ name: ""
+ schemas:
+ - name: ""
+ tables:
+ - name: t
+ columns:
+ - name: c
+ position: 0
+ default: null
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ - name: a
+ position: 0
+ default:
+ value: "1"
+ nullable: true
+ type: int
+ characterset: ""
+ collation: ""
+ comment: abcdefg
+ classification: ""
+ usercomment: abcdefg
+ - name: b
+ position: 0
+ default:
+ value: "'NULL'"
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - a
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: fk1
+ columns:
+ - a
+ referencedschema: ""
+ referencedtable: t2
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default:
+ value: "NULL"
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ indexes:
+ - name: PRIMARY
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ views: []
+ functions: []
+ streams: []
+ tasks: []
+ characterset: ""
+ collation: ""
+ extensions: []
diff --git a/frontend/src/components/Branch/BaselineSchemaSelector.vue b/frontend/src/components/Branch/BaselineSchemaSelector.vue
index b10265dabb..570f086382 100644
--- a/frontend/src/components/Branch/BaselineSchemaSelector.vue
+++ b/frontend/src/components/Branch/BaselineSchemaSelector.vue
@@ -234,7 +234,7 @@ watch(() => state.changeHistory, prepareFullViewChangeHistory, {
deep: true,
});
-const allowedEngineTypeList: Engine[] = [Engine.MYSQL];
+const allowedEngineTypeList: Engine[] = [Engine.MYSQL, Engine.TIDB];
const allowedMigrationTypeList: ChangeHistory_Type[] = [
ChangeHistory_Type.BASELINE,
ChangeHistory_Type.MIGRATE,
diff --git a/frontend/src/components/SchemaEditorV1/Aside/BranchTree.vue b/frontend/src/components/SchemaEditorV1/Aside/BranchTree.vue
index 8fc7d9a4bc..03b448cc45 100644
--- a/frontend/src/components/SchemaEditorV1/Aside/BranchTree.vue
+++ b/frontend/src/components/SchemaEditorV1/Aside/BranchTree.vue
@@ -163,7 +163,7 @@ const tableList = computed(() =>
);
const treeData = computed(() => {
const treeNodeList: TreeNode[] = [];
- if (engine.value === Engine.MYSQL) {
+ if (engine.value === Engine.MYSQL || engine.value === Engine.TIDB) {
const schema = schemaList.value[0];
if (!schema) {
return;
diff --git a/frontend/src/utils/schemaEditor/index.ts b/frontend/src/utils/schemaEditor/index.ts
index 8ed215ded8..aa496eb64b 100644
--- a/frontend/src/utils/schemaEditor/index.ts
+++ b/frontend/src/utils/schemaEditor/index.ts
@@ -18,7 +18,7 @@ export const allowUsingSchemaEditorV1 = (
};
export const getDataTypeSuggestionList = (engine: Engine = Engine.MYSQL) => {
- if (engine === Engine.MYSQL) {
+ if (engine === Engine.MYSQL || engine === Engine.TIDB) {
return [
"BIT",
"BOOLEAN",