Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: copy mysql parse to metadata to tidb (#13482)
h3n4l2f1d438b4240
diff --git a/backend/plugin/parser/tidb/split.go b/backend/plugin/parser/tidb/split.goindex f80cbac7c6..57c0b87c25 100644--- a/backend/plugin/parser/tidb/split.go+++ b/backend/plugin/parser/tidb/split.go@@ -1,6 +1,10 @@package tidbimport (+ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/mysql-parser"+ "github.com/pkg/errors"+"github.com/bytebase/bytebase/backend/plugin/parser/base""github.com/bytebase/bytebase/backend/plugin/parser/tokenizer"storepb "github.com/bytebase/bytebase/proto/generated-go/store"@@ -30,3 +34,324 @@ func SplitSQLKeepEmptyBlocks(statement string) ([]base.SingleSQL, error) {}return list, nil}++func hasDelimiterStatement(stream *antlr.CommonTokenStream) bool {+ tokens := stream.GetAllTokens()+ for _, token := range tokens {+ if token.GetChannel() == antlr.TokenDefaultChannel && token.GetTokenType() == parser.MySQLLexerDELIMITER_SYMBOL {+ return true+ }+ }+ return false+}++func tryMatchDelimiter(stream *antlr.CommonTokenStream, pos int, delimiter string) (int, bool) {+ matchPos := 0+ length := len(stream.GetAllTokens())+ for i := pos; i < length; i++ {+ text := stream.GetTextFromInterval(antlr.Interval{Start: i, Stop: i})+ for j := 0; j < len(text); j++ {+ if j+matchPos >= len(delimiter) || text[j] != delimiter[j+matchPos] {+ return 0, false+ }+ matchPos+++ if matchPos == len(delimiter) {+ return i + 1, true+ }+ }+ }++ return 0, false+}++func extractDelimiterStatement(stream *antlr.CommonTokenStream, pos int) (int, string) {+ length := len(stream.GetAllTokens())+ for i := pos; i < length; i++ {+ if (stream.Get(i).GetTokenType() == parser.MySQLLexerWHITESPACE && stream.Get(i).GetText() == "\n") ||+ (stream.Get(i).GetTokenType() == antlr.TokenEOF) {+ return i + 1, stream.GetTextFromTokens(stream.Get(pos), stream.Get(i-1))+ }+ }++ // never reach here+ return length, stream.GetTextFromTokens(stream.Get(pos), stream.Get(length-1))+}++func splitDelimiterModeSQL(stream *antlr.CommonTokenStream) ([]base.SingleSQL, error) {+ var result []base.SingleSQL+ delimiter := ";"+ tokens := stream.GetAllTokens()+ start := 0++ i := 0+ for {+ if i >= len(tokens) {+ break+ }+ token := tokens[i]+ // Deal with delimiter statement.+ if token.GetChannel() == antlr.TokenDefaultChannel && token.GetTokenType() == parser.MySQLLexerDELIMITER_SYMBOL {+ newStart, delimiterStatement := extractDelimiterStatement(stream, i)+ var err error+ delimiter, err = ExtractDelimiter(delimiterStatement)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to extract delimiter from statement: %s", delimiterStatement)+ }+ start = newStart+ i = newStart+ continue+ }++ // Deal with normal statement.+ if delimiter == ";" && token.GetTokenType() == parser.MySQLLexerSEMICOLON_SYMBOL {+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start : i+1])+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ result = append(result, base.SingleSQL{+ Text: stream.GetTextFromTokens(tokens[start], tokens[i]),+ BaseLine: tokens[start].GetLine() - 1,+ LastLine: tokens[i].GetLine() - 1,+ LastColumn: tokens[i].GetColumn(),+ FirstStatementLine: line,+ FirstStatementColumn: col,+ Empty: base.IsEmpty(tokens[start:i+1], parser.MySQLLexerSEMICOLON_SYMBOL),+ })+ i+++ start = i+ continue+ }++ if token.GetChannel() != antlr.TokenDefaultChannel {+ i+++ continue+ }++ if newStart, ok := tryMatchDelimiter(stream, i, delimiter); ok {+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start:newStart])+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ result = append(result, base.SingleSQL{+ // Use a single semicolon instead of the user defined delimiter.+ Text: stream.GetTextFromTokens(tokens[start], tokens[i-1]) + ";",+ BaseLine: tokens[start].GetLine() - 1,+ LastLine: tokens[newStart-1].GetLine() - 1,+ LastColumn: tokens[newStart-1].GetColumn(),+ FirstStatementLine: line,+ FirstStatementColumn: col,+ Empty: base.IsEmpty(tokens[start:i], parser.MySQLLexerSEMICOLON_SYMBOL),+ })+ i = newStart+ start = newStart+ continue+ }++ i+++ }++ endPos := len(tokens) - 1+ if start < endPos {+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start:])+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ result = append(result, base.SingleSQL{+ Text: stream.GetTextFromTokens(tokens[start], tokens[endPos-1]),+ BaseLine: tokens[start].GetLine() - 1,+ LastLine: tokens[endPos-1].GetLine() - 1,+ LastColumn: tokens[endPos-1].GetColumn(),+ FirstStatementLine: line,+ FirstStatementColumn: col,+ Empty: base.IsEmpty(tokens[start:endPos], parser.MySQLLexerSEMICOLON_SYMBOL),+ })+ }++ return result, nil+}++type openParenthesis struct {+ tokenType int+ pos int+}++func splitTiDBStatement(stream *antlr.CommonTokenStream) ([]base.SingleSQL, error) {+ stream.Fill()+ if hasDelimiterStatement(stream) {+ return splitDelimiterModeSQL(stream)+ }++ var result []base.SingleSQL+ tokens := stream.GetAllTokens()++ var beginCaseStack, ifStack, loopStack, whileStack, repeatStack []*openParenthesis++ var semicolonStack []int++ for i, token := range tokens {+ switch token.GetTokenType() {+ case parser.MySQLParserBEGIN_SYMBOL:+ isBeginWork := base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserWORK_SYMBOL+ isBeginWork = isBeginWork || (base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserSEMICOLON_SYMBOL)+ isBeginWork = isBeginWork || (base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserEOF)+ if isBeginWork {+ continue+ }++ isXa := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserXA_SYMBOL+ if isXa {+ continue+ }++ beginCaseStack = append(beginCaseStack, &openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})+ case parser.MySQLParserCASE_SYMBOL:+ isEndCase := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ if isEndCase {+ continue+ }++ beginCaseStack = append(beginCaseStack, &openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})+ case parser.MySQLParserIF_SYMBOL:+ isEndIf := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ if isEndIf {+ continue+ }++ isIfExists := base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserEXISTS_SYMBOL+ if isIfExists {+ continue+ }++ ifStack = append(ifStack, &openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})+ case parser.MySQLParserLOOP_SYMBOL:+ isEndLoop := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ if isEndLoop {+ continue+ }++ loopStack = append(loopStack, &openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})+ case parser.MySQLParserWHILE_SYMBOL:+ isEndWhile := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ if isEndWhile {+ continue+ }++ whileStack = append(whileStack, &openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})+ case parser.MySQLParserREPEAT_SYMBOL:+ isEndRepeat := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserUNTIL_SYMBOL+ if isEndRepeat {+ continue+ }++ repeatStack = append(repeatStack, &openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})+ case parser.MySQLParserEND_SYMBOL:+ isXa := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserXA_SYMBOL+ if isXa {+ continue+ }++ nextDefaultChannelTokenType := base.GetDefaultChannelTokenType(tokens, i, 1)+ switch nextDefaultChannelTokenType {+ case parser.MySQLParserIF_SYMBOL:+ // There are two types of IF statement:+ // 1. IF(expr1,expr2,expr3)+ // 2. IF search_condition THEN statement_list [ELSEIF search_condition THEN statement_list] ... [ELSE statement_list] END IF+ // For the first type, we will meet single IF symbol without END IF symbol.+ if len(ifStack) == 0 {+ return nil, errors.New("invalid statement: failed to split multiple statements")+ }+ semicolonStack = popSemicolonStack(semicolonStack, ifStack[0].pos)+ ifStack = ifStack[:len(ifStack)-1]+ case parser.MySQLParserLOOP_SYMBOL:+ // For the LOOP symbol, MySQL only has LOOP with END LOOP statement.+ // Other cases are invalid.+ // So we only need to do the simple parenthesis matching.+ if len(loopStack) == 0 {+ return nil, errors.New("invalid statement: failed to split multiple statements")+ }+ semicolonStack = popSemicolonStack(semicolonStack, loopStack[len(loopStack)-1].pos)+ loopStack = loopStack[:len(loopStack)-1]+ case parser.MySQLParserWHILE_SYMBOL:+ // For the WHILE symbol, MySQL only has WHILE with END WHILE statement.+ // Other cases are invalid.+ // So we only need to do the simple parenthesis matching.+ if len(whileStack) == 0 {+ return nil, errors.New("invalid statement: failed to split multiple statements")+ }+ semicolonStack = popSemicolonStack(semicolonStack, whileStack[len(whileStack)-1].pos)+ whileStack = whileStack[:len(whileStack)-1]+ case parser.MySQLParserREPEAT_SYMBOL:+ // The are two types of REPEAT statement:+ // 1. REPEAT(expr,expr)+ // 2. REPEAT statement_list UNTIL search_condition END REPEAT+ // For the first type, we will meet single REPEAT symbol without END REPEAT symbol.+ if len(repeatStack) == 0 {+ return nil, errors.New("invalid statement: failed to split multiple statements")+ }+ semicolonStack = popSemicolonStack(semicolonStack, repeatStack[0].pos)+ repeatStack = repeatStack[:len(repeatStack)-1]+ case parser.MySQLParserCASE_SYMBOL:+ if len(beginCaseStack) == 0 {+ return nil, errors.New("invalid statement: failed to split multiple statements")+ }+ semicolonStack = popSemicolonStack(semicolonStack, beginCaseStack[len(beginCaseStack)-1].pos)+ beginCaseStack = beginCaseStack[:len(beginCaseStack)-1]+ default:+ // is BEGIN ... END or CASE .. END case+ if len(beginCaseStack) == 0 {+ return nil, errors.New("invalid statement: failed to split multiple statements")+ }+ semicolonStack = popSemicolonStack(semicolonStack, beginCaseStack[len(beginCaseStack)-1].pos)+ beginCaseStack = beginCaseStack[:len(beginCaseStack)-1]+ }+ case parser.MySQLParserSEMICOLON_SYMBOL:+ semicolonStack = append(semicolonStack, i)+ }+ }++ start := 0+ for _, pos := range semicolonStack {+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start : pos+1])+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ result = append(result, base.SingleSQL{+ Text: stream.GetTextFromTokens(tokens[start], tokens[pos]),+ BaseLine: tokens[start].GetLine() - 1,+ LastLine: tokens[pos].GetLine() - 1,+ LastColumn: tokens[pos].GetColumn(),+ FirstStatementLine: line,+ FirstStatementColumn: col,+ Empty: base.IsEmpty(tokens[start:pos+1], parser.MySQLLexerSEMICOLON_SYMBOL),+ })+ start = pos + 1+ }+ // For the last statement, it may not end with semicolon symbol, EOF symbol instead.+ eofPos := len(tokens) - 1+ if start < eofPos {+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start:])+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ result = append(result, base.SingleSQL{+ Text: stream.GetTextFromTokens(tokens[start], tokens[eofPos-1]),+ BaseLine: tokens[start].GetLine() - 1,+ LastLine: tokens[eofPos-1].GetLine() - 1,+ LastColumn: tokens[eofPos-1].GetColumn(),+ FirstStatementLine: line,+ FirstStatementColumn: col,+ Empty: base.IsEmpty(tokens[start:eofPos], parser.MySQLLexerSEMICOLON_SYMBOL),+ })+ }++ return result, nil+}++func popSemicolonStack(stack []int, openParPos int) []int {+ if len(stack) == 0 {+ return stack+ }++ for i := len(stack) - 1; i >= 0; i-- {+ if stack[i] < openParPos {+ return stack[:i+1]+ }+ }++ return []int{}+}diff --git a/backend/plugin/parser/tidb/tidb.go b/backend/plugin/parser/tidb/tidb.goindex cf845366de..a992033da5 100644--- a/backend/plugin/parser/tidb/tidb.go+++ b/backend/plugin/parser/tidb/tidb.go@@ -1,17 +1,23 @@package tidbimport (+ "fmt"+ "log/slog""regexp""strconv""strings"+ "github.com/antlr4-go/antlr/v4"tidbparser "github.com/pingcap/tidb/pkg/parser""github.com/pingcap/tidb/pkg/parser/ast""github.com/pingcap/tidb/pkg/parser/mysql"+ "github.com/pkg/errors"// The packege parser_driver has to be imported._ "github.com/pingcap/tidb/pkg/types/parser_driver"+ parser "github.com/bytebase/tidb-parser"+"github.com/bytebase/bytebase/backend/plugin/parser/base""github.com/bytebase/bytebase/backend/plugin/parser/tokenizer")@@ -31,6 +37,172 @@ func ParseTiDB(sql string, charset string, collation string) ([]ast.StmtNode, erreturn nodes, nil}+// ParseResult is the result of parsing a MySQL statement.+type ParseResult struct {+ Tree antlr.Tree+ Tokens *antlr.CommonTokenStream+ BaseLine int+}++func ANTLRParseTiDB(statement string, options ...tokenizer.Option) ([]*ParseResult, error) {+ statement, err := DealWithDelimiter(statement, options...)+ if err != nil {+ return nil, err+ }+ list, err := parseInputStream(antlr.NewInputStream(statement))+ // HACK(p0ny): the callee may end up in an infinite loop, we print the statement here to help debug.+ if err != nil && strings.Contains(err.Error(), "split SQL statement timed out") {+ slog.Info("split SQL statement timed out", "statement", statement)+ }+ return list, err+}++func parseSingleStatement(baseLine int, statement string) (antlr.Tree, *antlr.CommonTokenStream, error) {+ input := antlr.NewInputStream(statement)+ lexer := parser.NewTiDBLexer(input)+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)++ p := parser.NewTiDBParser(stream)++ lexerErrorListener := &base.ParseErrorListener{+ BaseLine: baseLine,+ }+ lexer.RemoveErrorListeners()+ lexer.AddErrorListener(lexerErrorListener)++ parserErrorListener := &base.ParseErrorListener{+ BaseLine: baseLine,+ }+ p.RemoveErrorListeners()+ p.AddErrorListener(parserErrorListener)++ p.BuildParseTrees = true++ tree := p.Script()++ if lexerErrorListener.Err != nil {+ return nil, nil, lexerErrorListener.Err+ }++ if parserErrorListener.Err != nil {+ return nil, nil, parserErrorListener.Err+ }++ return tree, stream, nil+}++func parseInputStream(input *antlr.InputStream) ([]*ParseResult, error) {+ var result []*ParseResult+ lexer := parser.NewTiDBLexer(input)+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)++ list, err := splitTiDBStatement(stream)+ if err != nil {+ return nil, err+ }++ if len(list) > 0 {+ list[len(list)-1].Text = tidbAddSemicolonIfNeeded(list[len(list)-1].Text)+ }++ baseLine := 0+ for _, s := range list {+ tree, tokens, err := parseSingleStatement(baseLine, s.Text)+ if err != nil {+ return nil, err+ }++ if isEmptyStatement(tokens) {+ continue+ }++ result = append(result, &ParseResult{+ Tree: tree,+ Tokens: tokens,+ BaseLine: s.BaseLine,+ })+ baseLine = s.LastLine+ }++ return result, nil+}++func isEmptyStatement(tokens *antlr.CommonTokenStream) bool {+ for _, token := range tokens.GetAllTokens() {+ if token.GetChannel() == antlr.TokenDefaultChannel && token.GetTokenType() != parser.TiDBParserSEMICOLON_SYMBOL && token.GetTokenType() != parser.TiDBParserEOF {+ return false+ }+ }+ return true+}++// DealWithDelimiter converts the delimiter statement to comment, also converts the following statement's delimiter to semicolon(`;`).+func DealWithDelimiter(statement string, options ...tokenizer.Option) (string, error) {+ has, list, err := hasDelimiter(statement, options...)+ if err != nil {+ return "", err+ }+ if has {+ var result []string+ delimiter := `;`+ for _, sql := range list {+ if IsDelimiter(sql.Text) {+ delimiter, err = ExtractDelimiter(sql.Text)+ if err != nil {+ return "", err+ }+ result = append(result, "-- "+sql.Text)+ continue+ }+ // TODO(rebelice): after deal with delimiter, we may cannot get the right line number, fix it.+ if delimiter != ";" && !sql.Empty {+ result = append(result, fmt.Sprintf("%s;", strings.TrimSuffix(sql.Text, delimiter)))+ } else {+ result = append(result, sql.Text)+ }+ }++ statement = strings.Join(result, "\n")+ }+ return statement, nil+}++// IsDelimiter returns true if the statement is a delimiter statement.+func IsDelimiter(stmt string) bool {+ delimiterRegex := `(?i)^\s*DELIMITER\s+`+ re := regexp.MustCompile(delimiterRegex)+ return re.MatchString(stmt)+}++// ExtractDelimiter extracts the delimiter from the delimiter statement.+func ExtractDelimiter(stmt string) (string, error) {+ delimiterRegex := `(?i)^\s*DELIMITER\s+(?P<DELIMITER>[^\s\\]+)\s*`+ re := regexp.MustCompile(delimiterRegex)+ matchList := re.FindStringSubmatch(stmt)+ index := re.SubexpIndex("DELIMITER")+ if index >= 0 && index < len(matchList) {+ return matchList[index], nil+ }+ return "", errors.Errorf("cannot extract delimiter from %q", stmt)+}++func hasDelimiter(statement string, options ...tokenizer.Option) (bool, []base.SingleSQL, error) {+ // use splitTiDBMultiSQL to check if the statement has delimiter+ t := tokenizer.NewTokenizer(statement, options...)+ list, err := t.SplitTiDBMultiSQL()+ if err != nil {+ return false, nil, errors.Errorf("failed to split multi sql: %v", err)+ }++ for _, sql := range list {+ if IsDelimiter(sql.Text) {+ return true, list, nil+ }+ }++ return false, list, nil+}+var (lineColumnRegex = regexp.MustCompile(`line (\d+) column (\d+)`))@@ -125,3 +297,34 @@ func TypeString(tp byte) string {}return "unknown"}++func tidbAddSemicolonIfNeeded(sql string) string {+ lexer := parser.NewTiDBLexer(antlr.NewInputStream(sql))+ lexerErrorListener := &base.ParseErrorListener{}+ lexer.RemoveErrorListeners()+ lexer.AddErrorListener(lexerErrorListener)+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)+ stream.Fill()+ if lexerErrorListener.Err != nil {+ // If the lexer fails, we cannot add semicolon.+ return sql+ }+ tokens := stream.GetAllTokens()+ for i := len(tokens) - 1; i >= 0; i-- {+ if tokens[i].GetChannel() != antlr.TokenDefaultChannel || tokens[i].GetTokenType() == parser.TiDBParserEOF {+ continue+ }++ // The last default channel token is a semicolon.+ if tokens[i].GetTokenType() == parser.TiDBParserSEMICOLON_SYMBOL {+ return sql+ }++ var result []string+ result = append(result, stream.GetTextFromInterval(antlr.NewInterval(0, tokens[i].GetTokenIndex())))+ result = append(result, ";")+ result = append(result, stream.GetTextFromInterval(antlr.NewInterval(tokens[i].GetTokenIndex()+1, tokens[len(tokens)-1].GetTokenIndex())))+ return strings.Join(result, "")+ }+ return sql+}diff --git a/backend/plugin/parser/tidb/util.go b/backend/plugin/parser/tidb/util.goindex 2f283a6a84..20ec45b45e 100644--- a/backend/plugin/parser/tidb/util.go+++ b/backend/plugin/parser/tidb/util.go@@ -1,6 +1,8 @@package tidbimport (+ "fmt"+tidbast "github.com/pingcap/tidb/pkg/parser/ast")@@ -29,3 +31,24 @@ func extractFieldName(in *tidbast.SelectField) string {}return ""}++type PartitionDefaultNameGenerator struct {+ parentName string+ count int+}++func NewPartitionDefaultNameGenerator(parentName string) *PartitionDefaultNameGenerator {+ return &PartitionDefaultNameGenerator{+ parentName: parentName,+ count: -1,+ }+}++func (g *PartitionDefaultNameGenerator) Next() string {+ g.count++++ if g.parentName == "" {+ return fmt.Sprintf("p%d", g.count)+ }+ return fmt.Sprintf("%ssp%d", g.parentName, g.count)+}diff --git a/backend/plugin/schema/tidb/parse_to_metadata.go b/backend/plugin/schema/tidb/parse_to_metadata.goindex 9692275879..bd7a99923f 100644--- a/backend/plugin/schema/tidb/parse_to_metadata.go+++ b/backend/plugin/schema/tidb/parse_to_metadata.go@@ -2,14 +2,13 @@ package tidbimport ("fmt"+ "strconv""strings"+ "github.com/antlr4-go/antlr/v4""github.com/pkg/errors"- tidbast "github.com/pingcap/tidb/pkg/parser/ast"- tidbformat "github.com/pingcap/tidb/pkg/parser/format"- "github.com/pingcap/tidb/pkg/parser/mysql"- tidbtypes "github.com/pingcap/tidb/pkg/parser/types"+ tidb "github.com/bytebase/tidb-parser"tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb""github.com/bytebase/bytebase/backend/plugin/schema"@@ -20,299 +19,560 @@ func init() {schema.RegisterParseToMetadatas(storepb.Engine_TIDB, ParseToMetadata)}-const (- autoIncrementSymbol = "AUTO_INCREMENT"- autoRandSymbol = "AUTO_RANDOM"-)-+// ParseToMetadata converts a schema string to database metadata.func ParseToMetadata(_, schema string) (*storepb.DatabaseSchemaMetadata, error) {- stmts, err := tidbparser.ParseTiDB(schema, "", "")+ list, err := tidbparser.ANTLRParseTiDB(schema)if err != nil {return nil, err}- transformer := &tidbTransformer{+ listener := &tidbTransformer{state: newDatabaseState(),}- transformer.state.schemas[""] = newSchemaState()+ listener.state.schemas[""] = newSchemaState()- for _, stmt := range stmts {- (stmt).Accept(transformer)+ for _, stmt := range list {+ antlr.ParseTreeWalkerDefault.Walk(listener, stmt.Tree)}- return transformer.state.convertToDatabaseMetadata(), transformer.err++ return listener.state.convertToDatabaseMetadata(), listener.err}type tidbTransformer struct {- tidbast.StmtNode+ *tidb.BaseTiDBParserListener- state *databaseState- err error+ state *databaseState+ currentTable string+ err error}-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()+// EnterCreateTable is called when production createTable is entered.+func (t *tidbTransformer) EnterCreateTable(ctx *tidb.CreateTableContext) {+ if t.err != nil {+ return+ }+ databaseName, tableName := tidbparser.NormalizeTiDBTableName(ctx.TableName())+ 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}- 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- }+ }++ schema := t.state.schemas[""]+ if _, ok := schema.tables[tableName]; ok {+ t.err = errors.New("multiple table names found: " + tableName)+ return+ }++ schema.tables[tableName] = newTableState(len(schema.tables), tableName)+ t.currentTable = tableName+}++// ExitCreateTable is called when production createTable is exited.+func (t *tidbTransformer) ExitCreateTable(_ *tidb.CreateTableContext) {+ t.currentTable = ""+}++// EnterCreateTableOption is called when production createTableOption is entered.+func (t *tidbTransformer) EnterCreateTableOption(ctx *tidb.CreateTableOptionContext) {+ if t.err != nil || t.currentTable == "" {+ return+ }++ if ctx.ENGINE_SYMBOL() != nil {+ engineString := ctx.EngineRef().TextOrIdentifier().GetParser().GetTokenStream().GetTextFromRuleContext(ctx.EngineRef().TextOrIdentifier())+ schema := t.state.schemas[""]+ table, ok := schema.tables[t.currentTable]+ if !ok {+ // This should never happen.+ return}+ table.engine = engineString+ }- tableName := node.Table.Name.String()+ if defaultCollation := ctx.DefaultCollation(); defaultCollation != nil {+ collationString := defaultCollation.CollationName().GetParser().GetTokenStream().GetTextFromRuleContext(defaultCollation.CollationName())schema := t.state.schemas[""]- if _, ok := schema.tables[tableName]; ok {- t.err = errors.New("multiple table names found: " + tableName)- return in, true+ table, ok := schema.tables[t.currentTable]+ if !ok {+ // This should never happen.+ return}- 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- }-- columnState := &columnState{- id: len(table.columns),- name: columnName,- tp: dataType,- comment: "",- nullable: tidbColumnCanNull(column),- }-- for _, option := range column.Options {- switch option.Tp {- case tidbast.ColumnOptionDefaultValue:- defaultValue, err := restoreExpr(option.Expr)- if err != nil {- t.err = err- return in, true- }- if defaultValue != nil {- switch {- case strings.EqualFold(*defaultValue, "NULL"):- columnState.defaultValue = &defaultValueNull{}- case strings.HasPrefix(*defaultValue, "'") && strings.HasSuffix(*defaultValue, "'"):- columnState.defaultValue = &defaultValueString{value: strings.ReplaceAll((*defaultValue)[1:len(*defaultValue)-1], "''", "'")}- default:- columnState.defaultValue = &defaultValueExpression{value: *defaultValue}- }- }- case tidbast.ColumnOptionComment:- comment, err := restoreComment(option.Expr)- if err != nil {- t.err = err- return in, true- }- columnState.comment = comment- case tidbast.ColumnOptionAutoIncrement:- defaultValue := autoIncrementSymbol- columnState.defaultValue = &defaultValueExpression{value: defaultValue}- case tidbast.ColumnOptionAutoRandom:- defaultValue := autoRandSymbol- unspecifiedLength := -1- if option.AutoRandOpt.ShardBits != unspecifiedLength {- if option.AutoRandOpt.RangeBits != unspecifiedLength {- defaultValue += fmt.Sprintf("(%d, %d)", option.AutoRandOpt.ShardBits, option.AutoRandOpt.RangeBits)- } else {- defaultValue += fmt.Sprintf("(%d)", option.AutoRandOpt.ShardBits)- }- }+ table.collation = collationString+ }++ if ctx.COMMENT_SYMBOL() != nil {+ commentString := ctx.TextStringLiteral().GetText()+ if len(commentString) > 2 {+ quotes := commentString[0]+ escape := fmt.Sprintf("%c%c", quotes, quotes)+ commentString = strings.ReplaceAll(commentString[1:len(commentString)-1], escape, string(quotes))+ }++ schema := t.state.schemas[""]+ table, ok := schema.tables[t.currentTable]+ if !ok {+ // This should never happen.+ return+ }+ table.comment = commentString+ }+}++// EnterColumnDefinition is called when production columnDefinition is entered.+func (t *tidbTransformer) EnterColumnDef(ctx *tidb.ColumnDefContext) {+ if t.err != nil || t.currentTable == "" {+ return+ }++ _, _, columnName := tidbparser.NormalizeTiDBColumnName(ctx.ColumnName())+ dataType := getDataTypePlainText(ctx.DataType())+ table := t.state.schemas[""].tables[t.currentTable]+ if _, ok := table.columns[columnName]; ok {+ t.err = errors.New("multiple column names found: " + columnName + " in table " + t.currentTable)+ return+ }+ columnState := &columnState{+ id: len(table.columns),+ name: columnName,+ tp: dataType,+ defaultValue: nil,+ comment: "",+ nullable: true,+ }++ if v := ctx.ColumnOptionList(); v != nil {+ for _, attribute := range v.AllColumnOption() {+ switch {+ case attribute.NULL_SYMBOL() != nil && attribute.NOT_SYMBOL() != nil:+ columnState.nullable = false+ case attribute.DEFAULT_SYMBOL() != nil && attribute.SERIAL_SYMBOL() == nil:+ defaultValueStart := nextDefaultChannelTokenIndex(ctx.GetParser().GetTokenStream(), attribute.DEFAULT_SYMBOL().GetSymbol().GetTokenIndex())+ defaultValue := attribute.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: defaultValueStart,+ Stop: attribute.GetStop().GetTokenIndex(),+ })+ switch {+ case strings.EqualFold(defaultValue, "NULL"):+ columnState.defaultValue = &defaultValueNull{}+ case strings.HasPrefix(defaultValue, "'") && strings.HasSuffix(defaultValue, "'"):+ columnState.defaultValue = &defaultValueString{value: strings.ReplaceAll(defaultValue[1:len(defaultValue)-1], "''", "'")}+ case strings.HasPrefix(defaultValue, "\"") && strings.HasSuffix(defaultValue, "\""):+ columnState.defaultValue = &defaultValueString{value: strings.ReplaceAll(defaultValue[1:len(defaultValue)-1], "\"\"", "\"")}+ default:columnState.defaultValue = &defaultValueExpression{value: defaultValue}- case tidbast.ColumnOptionOnUpdate:- onUpdate, err := restoreExpr(option.Expr)- if err != nil {- t.err = err- return in, true- }- columnState.onUpdate = *onUpdate}+ case attribute.COMMENT_SYMBOL() != nil:+ commentStart := nextDefaultChannelTokenIndex(ctx.GetParser().GetTokenStream(), attribute.COMMENT_SYMBOL().GetSymbol().GetTokenIndex())+ comment := attribute.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: commentStart,+ Stop: attribute.GetStop().GetTokenIndex(),+ })+ if comment != `''` && len(comment) > 2 {+ columnState.comment = comment[1 : len(comment)-1]+ }+ // todo(zp): refactor column attribute.+ case attribute.AUTO_INCREMENT_SYMBOL() != nil:+ defaultValue := autoIncrementSymbol+ columnState.defaultValue = &defaultValueExpression{value: defaultValue}+ case attribute.ON_SYMBOL() != nil && attribute.UPDATE_SYMBOL() != nil:+ onUpdateValue := ""+ if attribute.TimeFunctionParameters() != nil && attribute.TimeFunctionParameters().FractionalPrecision() != nil {+ onUpdateValue = "CURRENT_TIMESTAMP(" + attribute.TimeFunctionParameters().FractionalPrecision().GetText() + ")"+ } else {+ onUpdateValue = "CURRENT_TIMESTAMP"+ }+ columnState.onUpdate = onUpdateValue}- table.columns[columnName] = columnState}- for _, tableOption := range node.Options {- switch tableOption.Tp {- case tidbast.TableOptionComment:- table.comment = tableComment(tableOption)- case tidbast.TableOptionEngine:- table.engine = tableOption.StrValue- case tidbast.TableOptionCollate:- table.collation = tableOption.StrValue+ }++ if columnState.defaultValue == nil && columnState.nullable {+ columnState.defaultValue = &defaultValueNull{}+ }++ table.columns[columnName] = columnState+}++// EnterTableConstraintDef is called when production tableConstraintDef is entered.+func (t *tidbTransformer) EnterTableConstraintDef(ctx *tidb.TableConstraintDefContext) {+ if t.err != nil || t.currentTable == "" {+ return+ }++ if ctx.GetType_() != nil {+ symbol := strings.ToUpper(ctx.GetType_().GetText())+ switch symbol {+ case "PRIMARY":+ keys, keyLengths := extractKeyListVariants(ctx.KeyListVariants())+ table := t.state.schemas[""].tables[t.currentTable]+ table.indexes["PRIMARY"] = &indexState{+ id: len(table.indexes),+ name: "PRIMARY",+ keys: keys,+ lengths: keyLengths,+ primary: true,+ unique: true,+ }+ case "FOREIGN":+ var name string+ if ctx.ConstraintName() != nil && ctx.ConstraintName().Identifier() != nil {+ name = tidbparser.NormalizeTiDBIdentifier(ctx.ConstraintName().Identifier())+ } else if ctx.IndexName() != nil {+ name = tidbparser.NormalizeTiDBIdentifier(ctx.IndexName().Identifier())+ }+ keys, _ := extractKeyList(ctx.KeyList())+ table := t.state.schemas[""].tables[t.currentTable]+ if table.foreignKeys[name] != nil {+ t.err = errors.New("multiple foreign keys found: " + name)+ return+ }+ referencedTable, referencedColumns := extractReference(ctx.References())+ fk := &foreignKeyState{+ id: len(table.foreignKeys),+ name: name,+ columns: keys,+ referencedTable: referencedTable,+ referencedColumns: referencedColumns,+ }+ table.foreignKeys[name] = fk+ case "FULLTEXT":+ var name string+ if ctx.IndexName() != nil {+ name = tidbparser.NormalizeTiDBIdentifier(ctx.IndexName().Identifier())+ }+ keys, keyLengths := extractKeyListVariants(ctx.KeyListVariants())+ table := t.state.schemas[""].tables[t.currentTable]+ if table.indexes[name] != nil {+ t.err = errors.New("multiple indexes found: " + name)+ return+ }+ idx := &indexState{+ id: len(table.indexes),+ name: name,+ keys: keys,+ lengths: keyLengths,+ primary: false,+ unique: false,+ tp: symbol,+ }+ table.indexes[name] = idx+ case "SPATIAL":+ var name string+ if ctx.IndexName() != nil {+ name = tidbparser.NormalizeTiDBIdentifier(ctx.IndexName().Identifier())+ }+ keys, keyLengths := extractKeyListVariants(ctx.KeyListVariants())+ table := t.state.schemas[""].tables[t.currentTable]+ if table.indexes[name] != nil {+ t.err = errors.New("multiple indexes found: " + name)+ return+ }+ idx := &indexState{+ id: len(table.indexes),+ name: name,+ keys: keys,+ lengths: keyLengths,+ primary: false,+ unique: false,+ tp: symbol,+ }+ table.indexes[name] = idx+ case "KEY", "INDEX", "UNIQUE":+ var name string+ if v := ctx.IndexNameAndType(); v != nil {+ name = tidbparser.NormalizeTiDBIdentifier(v.IndexName().Identifier())+ } else {+ t.err = errors.New("index name not found")+ }+ keys, keyLengths := extractKeyListVariants(ctx.KeyListVariants())+ table := t.state.schemas[""].tables[t.currentTable]+ if table.indexes[name] != nil {+ t.err = errors.New("multiple indexes found: " + name)+ return+ }+ tp := "BTREE"+ if v := ctx.IndexNameAndType(); v != nil && v.IndexType() != nil {+ tp = strings.ToUpper(v.IndexType().GetText())+ }+ idx := &indexState{+ id: len(table.indexes),+ name: name,+ keys: keys,+ lengths: keyLengths,+ primary: false,+ unique: symbol == "UNIQUE",+ tp: tp,}+ table.indexes[name] = idx}+ }+}- // primary and foreign key definition- for _, constraint := range node.Constraints {- constraintType := constraint.Tp- switch constraintType {- 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...)- }- }+func (t *tidbTransformer) EnterPartitionClause(ctx *tidb.PartitionClauseContext) {+ if t.err != nil {+ return+ }+ if _, parentIsCreateTable := ctx.GetParent().(*tidb.CreateTableContext); !parentIsCreateTable {+ return+ }+ if t.currentTable == "" {+ return+ }+ table := t.state.schemas[""].tables[t.currentTable]+ if table == nil {+ return+ }- table.indexes["PRIMARY"] = &indexState{- id: len(table.indexes),- name: "PRIMARY",- keys: pkList,- primary: true,- unique: true,+ parititonInfo := partitionInfo{}++ iTypeDefCtx := ctx.PartitionTypeDef()+ if iTypeDefCtx != nil {+ switch typeDefCtx := iTypeDefCtx.(type) {+ case *tidb.PartitionDefKeyContext:+ parititonInfo.tp = storepb.TablePartitionMetadata_KEY+ if typeDefCtx.LINEAR_SYMBOL() != nil {+ parititonInfo.tp = storepb.TablePartitionMetadata_LINEAR_KEY+ }+ // TODO(zp): handle the key algorithm+ if typeDefCtx.IdentifierList() != nil {+ identifiers := extractIdentifierList(typeDefCtx.IdentifierList())+ for i, identifier := range identifiers {+ identifier := strings.TrimSpace(identifier)+ if !strings.HasPrefix(identifier, "`") || !strings.HasSuffix(identifier, "`") {+ identifiers[i] = fmt.Sprintf("`%s`", identifier)+ }}- case tidbast.ConstraintForeignKey:- var referencingColumnList []string- for _, key := range constraint.Keys {- referencingColumnList = append(referencingColumnList, key.Column.Name.String())+ parititonInfo.expr = strings.Join(identifiers, ",")+ }+ case *tidb.PartitionDefHashContext:+ parititonInfo.tp = storepb.TablePartitionMetadata_HASH+ if typeDefCtx.LINEAR_SYMBOL() != nil {+ parititonInfo.tp = storepb.TablePartitionMetadata_LINEAR_HASH+ }+ bitExprText := typeDefCtx.GetParser().GetTokenStream().GetTextFromRuleContext(typeDefCtx.BitExpr())+ bitExprFields := strings.Split(bitExprText, ",")+ for i, bitExprField := range bitExprFields {+ bitExprField := strings.TrimSpace(bitExprField)+ if !strings.HasPrefix(bitExprField, "`") || !strings.HasSuffix(bitExprField, "`") {+ bitExprFields[i] = fmt.Sprintf("`%s`", bitExprField)}- var referencedColumnList []string- for _, spec := range constraint.Refer.IndexPartSpecifications {- referencedColumnList = append(referencedColumnList, spec.Column.Name.String())+ }+ parititonInfo.expr = strings.Join(bitExprFields, ",")+ case *tidb.PartitionDefRangeListContext:+ if typeDefCtx.RANGE_SYMBOL() != nil {+ parititonInfo.tp = storepb.TablePartitionMetadata_RANGE+ } else {+ parititonInfo.tp = storepb.TablePartitionMetadata_LIST+ }+ if typeDefCtx.COLUMNS_SYMBOL() != nil {+ if parititonInfo.tp == storepb.TablePartitionMetadata_RANGE {+ parititonInfo.tp = storepb.TablePartitionMetadata_RANGE_COLUMNS+ } else {+ parititonInfo.tp = storepb.TablePartitionMetadata_LIST_COLUMNS}- fkName := constraint.Name- if fkName == "" {- t.err = errors.New("empty foreign key name")- return in, true+ identifierList := extractIdentifierList(typeDefCtx.IdentifierList())+ for i, identifier := range identifierList {+ identifier := strings.TrimSpace(identifier)+ if !strings.HasPrefix(identifier, "`") || !strings.HasSuffix(identifier, "`") {+ identifierList[i] = fmt.Sprintf("`%s`", identifier)+ }}- if table.foreignKeys[fkName] != nil {- t.err = errors.New("multiple foreign keys found: " + fkName)- return in, true+ parititonInfo.expr = strings.Join(identifierList, ",")+ } else {+ bitExprText := typeDefCtx.GetParser().GetTokenStream().GetTextFromRuleContext(typeDefCtx.BitExpr())+ bitExprFields := strings.Split(bitExprText, ",")+ for i, bitExprField := range bitExprFields {+ bitExprField := strings.TrimSpace(bitExprField)+ if !strings.HasPrefix(bitExprField, "`") || !strings.HasSuffix(bitExprField, "`") {+ bitExprFields[i] = fmt.Sprintf("`%s`", bitExprField)+ }}+ parititonInfo.expr = strings.Join(bitExprFields, ",")+ }+ default:+ t.err = errors.New("unknown partition type")+ return+ }+ }++ if n := ctx.Real_ulong_number(); n != nil {+ number, err := strconv.ParseInt(n.GetText(), 10, 64)+ if err != nil {+ t.err = errors.Wrap(err, "failed to parse partition number")+ return+ }+ parititonInfo.useDefault = int(number)+ }- fk := &foreignKeyState{- id: len(table.foreignKeys),- name: fkName,- columns: referencingColumnList,- referencedTable: constraint.Refer.Table.Name.String(),- referencedColumns: referencedColumnList,+ var subInfo *partitionInfo+ if subPartitionCtx := ctx.SubPartitions(); subPartitionCtx != nil {+ subInfo = new(partitionInfo)+ if subPartitionCtx.HASH_SYMBOL() != nil {+ subInfo.tp = storepb.TablePartitionMetadata_HASH+ if subPartitionCtx.LINEAR_SYMBOL() != nil {+ subInfo.tp = storepb.TablePartitionMetadata_LINEAR_HASH+ }+ if bitExprCtx := subPartitionCtx.BitExpr(); bitExprCtx != nil {+ bitExprText := bitExprCtx.GetParser().GetTokenStream().GetTextFromRuleContext(bitExprCtx)+ bitExprFields := strings.Split(bitExprText, ",")+ for i, bitExprField := range bitExprFields {+ bitExprField := strings.TrimSpace(bitExprField)+ if !strings.HasPrefix(bitExprField, "`") || !strings.HasSuffix(bitExprField, "`") {+ bitExprFields[i] = fmt.Sprintf("`%s`", bitExprField)+ }}- table.foreignKeys[fkName] = fk- case tidbast.ConstraintIndex, tidbast.ConstraintUniq, tidbast.ConstraintUniqKey, tidbast.ConstraintUniqIndex, tidbast.ConstraintKey:- var referencingColumnList []string- var lengthList []int64- for _, spec := range constraint.Keys {- var specString string- var err error- if spec.Column != nil {- specString = spec.Column.Name.String()- if spec.Length > 0 {- lengthList = append(lengthList, int64(spec.Length))- } else {- lengthList = append(lengthList, -1)- }- } else {- specString, err = tidbRestoreNode(spec, tidbformat.RestoreKeyWordLowercase|tidbformat.RestoreStringSingleQuotes|tidbformat.RestoreNameBackQuotes)- if err != nil {- t.err = err- return in, true- }+ subInfo.expr = strings.Join(bitExprFields, ",")+ }+ } else if subPartitionCtx.KEY_SYMBOL() != nil {+ subInfo.tp = storepb.TablePartitionMetadata_KEY+ if subPartitionCtx.LINEAR_SYMBOL() != nil {+ subInfo.tp = storepb.TablePartitionMetadata_LINEAR_KEY+ }+ if identifierListParensCtx := subPartitionCtx.IdentifierListWithParentheses(); identifierListParensCtx != nil {+ identifiers := extractIdentifierList(identifierListParensCtx.IdentifierList())+ for i, identifier := range identifiers {+ identifier := strings.TrimSpace(identifier)+ if !strings.HasPrefix(identifier, "`") || !strings.HasSuffix(identifier, "`") {+ identifiers[i] = fmt.Sprintf("`%s`", identifier)}- referencingColumnList = append(referencingColumnList, specString)}+ subInfo.expr = strings.Join(identifiers, ",")+ }+ }- var indexName string- if constraint.Name != "" {- indexName = constraint.Name- } else {- t.err = errors.New("empty index name")- return in, true+ if n := subPartitionCtx.Real_ulong_number(); n != nil {+ number, err := strconv.ParseInt(n.GetText(), 10, 64)+ if err != nil {+ t.err = errors.Wrap(err, "failed to parse sub partition number")+ return+ }+ subInfo.useDefault = int(number)+ }+ }++ partitionDefinitions := make(map[string]*partitionDefinition)+ var allPartDefs []tidb.IPartitionDefinitionContext+ if v := ctx.PartitionDefinitions(); v != nil {+ allPartDefs = ctx.PartitionDefinitions().AllPartitionDefinition()+ }+ for i, partDef := range allPartDefs {+ pd := &partitionDefinition{+ id: i + 1,+ name: tidbparser.NormalizeTiDBIdentifier(partDef.Identifier()),+ }+ switch parititonInfo.tp {+ case storepb.TablePartitionMetadata_RANGE_COLUMNS, storepb.TablePartitionMetadata_RANGE:+ if partDef.LESS_SYMBOL() == nil {+ t.err = errors.New("RANGE partition but no LESS THAN clause")+ return+ }+ if partDef.PartitionValueItemListParen() != nil {+ itemsText := partDef.PartitionValueItemListParen().GetParser().GetTokenStream().GetTextFromInterval(+ antlr.NewInterval(+ partDef.PartitionValueItemListParen().OPEN_PAR_SYMBOL().GetSymbol().GetTokenIndex()+1,+ partDef.PartitionValueItemListParen().CLOSE_PAR_SYMBOL().GetSymbol().GetTokenIndex()-1,+ ),+ )+ itemsTextFields := strings.Split(itemsText, ",")+ for i, itemsTextField := range itemsTextFields {+ itemsTextField := strings.TrimSpace(itemsTextField)+ if strings.HasPrefix(itemsTextField, "`") && strings.HasSuffix(itemsTextField, "`") {+ itemsTextField = itemsTextField[1 : len(itemsTextField)-1]+ }+ itemsTextFields[i] = itemsTextField}+ pd.value = strings.Join(itemsTextFields, ",")+ } else {+ pd.value = "MAXVALUE"+ }+ case storepb.TablePartitionMetadata_LIST_COLUMNS, storepb.TablePartitionMetadata_LIST:+ if partDef.PartitionValuesIn() == nil {+ t.err = errors.New("COLUMNS partition but no partition value item in IN clause")+ return+ }+ var itemsText string+ if partDef.PartitionValuesIn().OPEN_PAR_SYMBOL() != nil {+ itemsText = partDef.PartitionValuesIn().GetParser().GetTokenStream().GetTextFromInterval(+ antlr.NewInterval(+ partDef.PartitionValuesIn().OPEN_PAR_SYMBOL().GetSymbol().GetTokenIndex()+1,+ partDef.PartitionValuesIn().CLOSE_PAR_SYMBOL().GetSymbol().GetTokenIndex()-1,+ ),+ )+ } else {+ itemsText = partDef.PartitionValuesIn().GetParser().GetTokenStream().GetTextFromRuleContext(partDef.PartitionValuesIn().PartitionValueItemListParen(0))+ }- if table.indexes[indexName] != nil {- t.err = errors.New("multiple foreign keys found: " + indexName)- return in, true+ itemsTextFields := strings.Split(itemsText, ",")+ for i, itemsTextField := range itemsTextFields {+ itemsTextField := strings.TrimSpace(itemsTextField)+ if strings.HasPrefix(itemsTextField, "`") && strings.HasSuffix(itemsTextField, "`") {+ itemsTextField = itemsTextField[1 : len(itemsTextField)-1]}+ itemsTextFields[i] = itemsTextField+ }+ pd.value = strings.Join(itemsTextFields, ",")+ case storepb.TablePartitionMetadata_HASH, storepb.TablePartitionMetadata_LINEAR_HASH, storepb.TablePartitionMetadata_KEY, storepb.TablePartitionMetadata_LINEAR_KEY:+ default:+ t.err = errors.New("unknown partition type")+ return+ }- table.indexes[indexName] = &indexState{- id: len(table.indexes),- name: indexName,- keys: referencingColumnList,- length: lengthList,- primary: false,- unique: constraintType == tidbast.ConstraintUniq || constraintType == tidbast.ConstraintUniqKey || constraintType == tidbast.ConstraintUniqIndex,+ if subInfo != nil {+ allSubpartitions := partDef.AllSubpartitionDefinition()+ if subInfo.tp == storepb.TablePartitionMetadata_TYPE_UNSPECIFIED && len(allSubpartitions) > 0 {+ t.err = errors.New("specify subpartition definition but no subpartition type specified")+ return+ }+ subPartitionDefinitions := make(map[string]*partitionDefinition)+ for i, sub := range allSubpartitions {+ subpd := &partitionDefinition{+ id: i + 1,+ name: tidbparser.NormalizeTiDBTextOrIdentifier(sub.TextOrIdentifier()),}+ subPartitionDefinitions[subpd.name] = subpd}+ pd.subpartitions = subPartitionDefinitions}- }- return in, false-}-// columnTypeStr returns the type string of tp.-func columnTypeStr(tp *tidbtypes.FieldType) string {- // This logic is copy from tidb/pkg/parser/model/model.go:GetTypeDesc()- // DO NOT TOUCH!- desc := tp.CompactStr()- if mysql.HasUnsignedFlag(tp.GetFlag()) && tp.GetType() != mysql.TypeBit && tp.GetType() != mysql.TypeYear {- desc += " unsigned"- }- if mysql.HasZerofillFlag(tp.GetFlag()) && tp.GetType() != mysql.TypeYear {- desc += " zerofill"+ partitionDefinitions[pd.name] = pd}- return desc-}-func tidbColumnCanNull(column *tidbast.ColumnDef) bool {- for _, option := range column.Options {- if option.Tp == tidbast.ColumnOptionNotNull || option.Tp == tidbast.ColumnOptionPrimaryKey {- return false- }+ table.partition = &partitionState{+ info: parititonInfo,+ subInfo: subInfo,+ partitions: partitionDefinitions,}- return true}-func restoreExpr(expr tidbast.ExprNode) (*string, error) {- if expr == nil {- return nil, nil- }- result, err := tidbRestoreNode(expr, tidbformat.RestoreStringSingleQuotes|tidbformat.RestoreStringWithoutCharset)- if err != nil {- return nil, err- }- if result == "CURRENT_TIMESTAMP()" {- result = "CURRENT_TIMESTAMP"+func (t *tidbTransformer) EnterCreateView(ctx *tidb.CreateViewContext) {+ if t.err != nil {+ return}- return &result, nil-}--func tableComment(option *tidbast.TableOption) string {- return option.StrValue-}-func restoreComment(expr tidbast.ExprNode) (string, error) {- comment, err := tidbRestoreNode(expr, tidbformat.RestoreStringWithoutCharset)- if err != nil {- return "", err+ databaseName, viewName := tidbparser.NormalizeTiDBViewName(ctx.ViewName())+ if databaseName != "" && t.state.name != "" && databaseName != t.state.name {+ t.err = errors.New("multiple database names found: " + t.state.name + ", " + databaseName)+ return}- return comment, 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+ schema, ok := t.state.schemas[""]+ if !ok || schema == nil {+ t.state.schemas[""] = newSchemaState()+ schema = t.state.schemas[""]}- return buffer.String(), nil-}-func (*tidbTransformer) Leave(in tidbast.Node) (tidbast.Node, bool) {- return in, true+ definition := ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: ctx.ViewTail().ViewSelect().GetStart().GetTokenIndex(),+ Stop: ctx.ViewTail().ViewSelect().GetStop().GetTokenIndex(),+ })+ schema.views[viewName] = &viewState{+ id: len(schema.views),+ name: viewName,+ definition: definition,+ }}diff --git a/backend/plugin/schema/tidb/parse_to_metadata_test.go b/backend/plugin/schema/tidb/parse_to_metadata_test.goindex c619830fb0..f36b12e735 100644--- a/backend/plugin/schema/tidb/parse_to_metadata_test.go+++ b/backend/plugin/schema/tidb/parse_to_metadata_test.go@@ -48,7 +48,7 @@ func TestParseToMetadata(t *testing.T) {err = common.ProtojsonUnmarshaler.Unmarshal([]byte(t.Metadata), want)a.NoError(err)diff := cmp.Diff(want, result, protocmp.Transform())- a.Equal("", diff)+ a.Empty(diff)}}diff --git a/backend/plugin/schema/tidb/state.go b/backend/plugin/schema/tidb/state.goindex 17789129f3..e6522c9662 100644--- a/backend/plugin/schema/tidb/state.go+++ b/backend/plugin/schema/tidb/state.go@@ -3,13 +3,20 @@ package tidbimport ("fmt""io"+ "log/slog""regexp""sort"+ "strconv""strings""google.golang.org/protobuf/types/known/wrapperspb"+ "github.com/antlr4-go/antlr/v4"+ tidbparser "github.com/bytebase/tidb-parser"+ "github.com/pkg/errors"+"github.com/bytebase/bytebase/backend/plugin/db/tidb"+ tidbparserraw "github.com/bytebase/bytebase/backend/plugin/parser/tidb"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -124,6 +131,7 @@ type tableState struct {// Engine and collation are only supported in ParseToMetadata.engine stringcollation string+ partition *partitionState}func (t *tableState) toString(buf *strings.Builder) error {@@ -214,6 +222,12 @@ func (t *tableState) toString(buf *strings.Builder) error {}}+ if t.partition != nil {+ if err := t.partition.toString(buf, nil); err != nil {+ return err+ }+ }+if _, err := buf.WriteString(";\n"); err != nil {return err}@@ -244,6 +258,7 @@ func convertToTableState(id int, table *storepb.TableMetadata) *tableState {for i, fk := range table.ForeignKeys {state.foreignKeys[fk.Name] = convertToForeignKeyState(i, fk)}+ state.partition = convertToPartitionState(table.Partitions)return state}@@ -288,6 +303,11 @@ func (t *tableState) convertToTableMetadata() *storepb.TableMetadata {fks = append(fks, fk.convertToForeignKeyMetadata())}+ var partitions []*storepb.TablePartitionMetadata+ if t.partition != nil {+ partitions = t.partition.convertToPartitionMetadata()+ }+return &storepb.TableMetadata{Name: t.name,Columns: columns,@@ -297,6 +317,7 @@ func (t *tableState) convertToTableMetadata() *storepb.TableMetadata {Comment: t.comment,Engine: t.engine,Collation: t.collation,+ Partitions: partitions,}}@@ -388,20 +409,22 @@ type indexState struct {id intname stringkeys []string- length []int64+ lengths []int64primary boolunique bool+ tp string}func (i *indexState) convertToIndexMetadata() *storepb.IndexMetadata {return &storepb.IndexMetadata{Name: i.name,Expressions: i.keys,- KeyLength: i.length,+ KeyLength: i.lengths,Primary: i.primary,Unique: i.unique,// Unsupported, for tests only.Visible: true,+ Type: i.tp,}}@@ -410,9 +433,10 @@ func convertToIndexState(id int, index *storepb.IndexMetadata) *indexState {id: id,name: index.Name,keys: index.Expressions,- length: index.KeyLength,+ lengths: index.KeyLength,primary: index.Primary,unique: index.Unique,+ tp: index.Type,}}@@ -435,7 +459,15 @@ func (i *indexState) toString(buf *strings.Builder) error {return err}} else {- if i.unique {+ if strings.ToUpper(i.tp) == "FULLTEXT" {+ if _, err := buf.WriteString("FULLTEXT KEY "); err != nil {+ return err+ }+ } else if strings.ToUpper(i.tp) == "SPATIAL" {+ if _, err := buf.WriteString("SPATIAL KEY "); err != nil {+ return err+ }+ } else if i.unique {if _, err := buf.WriteString("UNIQUE KEY "); err != nil {return err}@@ -461,8 +493,8 @@ func (i *indexState) toString(buf *strings.Builder) error {}} else {columnText := fmt.Sprintf("`%s`", key)- if len(i.length) > j && i.length[j] > 0 {- columnText = fmt.Sprintf("`%s`(%d)", key, i.length[j])+ if len(i.lengths) > j && i.lengths[j] > 0 {+ columnText = fmt.Sprintf("`%s`(%d)", key, i.lengths[j])}if _, err := buf.WriteString(columnText); err != nil {return err@@ -476,6 +508,632 @@ func (i *indexState) toString(buf *strings.Builder) error {return nil}+type partitionState struct {+ info partitionInfo+ subInfo *partitionInfo+ partitions map[string]*partitionDefinition+}++type partitionInfo struct {+ tp storepb.TablePartitionMetadata_Type+ useDefault int+ expr string+}++type partitionDefinition struct {+ id int+ name string+ value string+ subpartitions map[string]*partitionDefinition+}++func (p *partitionState) isValid() error {+ if p.info.useDefault == 0 && len(p.partitions) == 0 {+ return errors.New("empty partition list")+ }++ if p.info.useDefault != 0 && len(p.partitions) > 0 {+ return errors.New("specify partitions clause and use default partition are not allowed at the same time")+ }++ if p.info.tp == storepb.TablePartitionMetadata_TYPE_UNSPECIFIED {+ return errors.New("invalid partition type")+ }++ if p.subInfo != nil {+ if p.subInfo.tp == storepb.TablePartitionMetadata_TYPE_UNSPECIFIED {+ return errors.New("invalid subpartition type")+ }++ anySpecificPartition := len(p.partitions) > 0+ if anySpecificPartition {+ var anySpecificSubpartition bool+ for _, partition := range p.partitions {+ if len(partition.subpartitions) > 0 {+ anySpecificSubpartition = true+ break+ }+ }++ if anySpecificSubpartition && p.subInfo.useDefault != 0 {+ return errors.New("specify subpartitions clause and use default subpartition are not allowed at the same time")+ }+ }+ }++ return nil+}++func convertToPartitionState(partitions []*storepb.TablePartitionMetadata) *partitionState {+ if len(partitions) == 0 {+ return nil+ }+ state := &partitionState{+ partitions: make(map[string]*partitionDefinition),+ }+ for i, partition := range partitions {+ if i == 0 {+ state.info.tp = partition.Type+ state.info.expr = partition.Expression+ if partition.UseDefault != "" {+ var err error+ state.info.useDefault, err = strconv.Atoi(partition.UseDefault)+ if err != nil {+ slog.Warn(err.Error())+ }+ }+ }+ partitionDef := &partitionDefinition{+ id: i,+ name: partition.Name,+ value: partition.Value,+ subpartitions: make(map[string]*partitionDefinition),+ }++ for j, subPartition := range partition.Subpartitions {+ if j == 0 {+ state.subInfo = &partitionInfo{+ tp: subPartition.Type,+ expr: subPartition.Expression,+ }+ if subPartition.UseDefault != "" {+ var err error+ state.subInfo.useDefault, err = strconv.Atoi(subPartition.UseDefault)+ if err != nil {+ slog.Warn(err.Error())+ }+ }+ }+ partitionDef.subpartitions[subPartition.Name] = &partitionDefinition{+ id: j,+ name: subPartition.Name,+ value: subPartition.Value,+ }+ }+ state.partitions[partition.Name] = partitionDef+ }+ return state+}++func (p *partitionState) convertToPartitionMetadata() []*storepb.TablePartitionMetadata {+ // There are `useDefault` fields in partitionInfo structure, which may use with empty parititions fields.+ // For example, `PARTITION BY HASH (id) PARTITIONS 4 SUBPARTITION BY KEY(id) SUBPARTITIONS 5;` may cause the `partitions` field to be empty.+ // To be compatible with our protobuf definition, which requires at least one partition, we need to generate the default partition name. And, value+ // is not important, because only the KEY and HASH partition type support PARTITIONS clause.+ // TODO(parser-group): recheck the MySQL behavior of generating the default partition name and value.+ if err := p.isValid(); err != nil {+ slog.Warn(err.Error())+ return nil+ }+ var partitions []*storepb.TablePartitionMetadata+ if p.info.useDefault != 0 {+ generator := tidbparserraw.NewPartitionDefaultNameGenerator("")+ for i := 0; i < p.info.useDefault; i++ {+ partitions = append(partitions, &storepb.TablePartitionMetadata{+ Name: generator.Next(),+ Type: p.info.tp,+ Expression: p.info.expr,+ Value: "",+ UseDefault: strconv.Itoa(p.info.useDefault),+ })+ }+ // The reason of we do not consider subUseDefault in this case is that MySQL does not support+ // subpartitions for HASH and KEY partitioning, and they are the only partitioning types that support+ // the PARTITIONS clause.+ } else {+ sortedPartitions := make([]*partitionDefinition, 0, len(p.partitions))+ for _, partition := range p.partitions {+ sortedPartitions = append(sortedPartitions, partition)+ }+ sort.Slice(sortedPartitions, func(i, j int) bool {+ return sortedPartitions[i].id < sortedPartitions[j].id+ })+ for _, partition := range sortedPartitions {+ partitionMetadata := &storepb.TablePartitionMetadata{+ Name: partition.name,+ Type: p.info.tp,+ Expression: p.info.expr,+ Value: partition.value,+ }+ if p.subInfo != nil {+ if p.subInfo.useDefault != 0 {+ subUseDefault := strconv.Itoa(p.subInfo.useDefault)+ generator := tidbparserraw.NewPartitionDefaultNameGenerator(partition.name)+ for i := 0; i < p.subInfo.useDefault; i++ {+ partitionMetadata.Subpartitions = append(partitionMetadata.Subpartitions, &storepb.TablePartitionMetadata{+ Name: generator.Next(),+ Type: p.subInfo.tp,+ Expression: p.subInfo.expr,+ UseDefault: subUseDefault,+ Value: "",+ })+ }+ } else {+ sortedSubpartitions := make([]*partitionDefinition, 0, len(partition.subpartitions))+ for _, subPartition := range partition.subpartitions {+ sortedSubpartitions = append(sortedSubpartitions, subPartition)+ }+ sort.Slice(sortedSubpartitions, func(i, j int) bool {+ return sortedSubpartitions[i].id < sortedSubpartitions[j].id+ })+ for _, subPartition := range sortedSubpartitions {+ partitionMetadata.Subpartitions = append(partitionMetadata.Subpartitions, &storepb.TablePartitionMetadata{+ Name: subPartition.name,+ Type: p.subInfo.tp,+ Expression: p.subInfo.expr,+ Value: subPartition.value,+ })+ }+ }+ }+ partitions = append(partitions, partitionMetadata)+ }+ }++ return partitions+}++// toString() writes the partition state as SHOW CREATE TABLE syntax to buf, referencing MySQL source code:+// https://sourcegraph.com/github.com/mysql/mysql-server@824e2b4064053f7daf17d7f3f84b7a3ed92e5fb4/-/blob/sql/sql_show.cc?L2528-2550+// partitionClauseCtx is use to minimize the difference between the original one and the output, it is safe to pass nil.+func (p *partitionState) toString(buf io.StringWriter, partitionClauseCtx tidbparser.IPartitionClauseContext) error {+ // Write version specific comment.+ vsc := p.getVersionSpecificComment(partitionClauseCtx)+ curComment := vsc+ if _, err := buf.WriteString(vsc); err != nil {+ return err+ }+ if _, err := buf.WriteString(" PARTITION BY "); err != nil {+ return err+ }++ switch p.info.tp {+ case storepb.TablePartitionMetadata_RANGE, storepb.TablePartitionMetadata_RANGE_COLUMNS:+ if _, err := buf.WriteString("RANGE "); err != nil {+ return err+ }+ if p.info.tp == storepb.TablePartitionMetadata_RANGE {+ fields := splitPartitionExprIntoFields(p.info.expr)+ for i, field := range fields {+ if !strings.Contains(field, "(") {+ fields[i] = fmt.Sprintf("`%s`", field)+ }+ }+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ } else {+ // I think MySQL need to write "COLUMNS " instead of " COLUMNS" here...+ if _, err := buf.WriteString(" COLUMNS"); err != nil {+ return err+ }+ fields := splitPartitionExprIntoFields(p.info.expr)+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ }+ case storepb.TablePartitionMetadata_LIST, storepb.TablePartitionMetadata_LIST_COLUMNS:+ if _, err := buf.WriteString("LIST "); err != nil {+ return err+ }+ if p.info.tp == storepb.TablePartitionMetadata_LIST {+ fields := splitPartitionExprIntoFields(p.info.expr)+ for i, field := range fields {+ if !strings.Contains(field, "(") {+ fields[i] = fmt.Sprintf("`%s`", field)+ }+ }+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ } else {+ // I think MySQL need to write "COLUMNS " instead of " COLUMNS" here...+ if _, err := buf.WriteString(" COLUMNS"); err != nil {+ return err+ }+ fields := splitPartitionExprIntoFields(p.info.expr)+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ }+ case storepb.TablePartitionMetadata_HASH, storepb.TablePartitionMetadata_KEY, storepb.TablePartitionMetadata_LINEAR_HASH, storepb.TablePartitionMetadata_LINEAR_KEY:+ if p.info.tp == storepb.TablePartitionMetadata_LINEAR_HASH || p.info.tp == storepb.TablePartitionMetadata_LINEAR_KEY {+ if _, err := buf.WriteString("LINEAR "); err != nil {+ return err+ }+ }+ if p.info.tp == storepb.TablePartitionMetadata_KEY || p.info.tp == storepb.TablePartitionMetadata_LINEAR_KEY {+ if _, err := buf.WriteString("KEY "); err != nil {+ return err+ }+ // NOTE: MySQL supports an ALGORITHM option with [SUB]PARTITION BY [LINEAR KEY]. ALGORITHM=1 causes the server to use the same key-hashing function as MYSQL 5.1, and ALGORITHM=1 is the only possible output in+ // the following code. Sadly, I do not know how to get the key_algorithm from the INFORMATION_SCHEMA, AND 5.1 IS TOO LEGACY TO SUPPORT! So use the original one.+ /*+ current_comment_start is given when called from SHOW CREATE TABLE,+ Then only add ALGORITHM = 1, not the default 2 or non-set 0!+ For .frm current_comment_start is NULL, then add ALGORITHM if != 0.+ */+ // if (part_info->key_algorithm ==+ // enum_key_algorithm::KEY_ALGORITHM_51 || // SHOW+ // (!current_comment_start && // .frm+ // (part_info->key_algorithm != enum_key_algorithm::KEY_ALGORITHM_NONE))) {+ // /* If we already are within a comment, end that comment first. */+ // if (current_comment_start) err += add_string(fptr, "*/ ");+ // err += add_string(fptr, "/*!50611 ");+ // err += add_part_key_word(fptr, partition_keywords[PKW_ALGORITHM].str);+ // err += add_equal(fptr);+ // err += add_space(fptr);+ // err += add_int(fptr, static_cast<longlong>(part_info->key_algorithm));+ // err += add_space(fptr);+ // err += add_string(fptr, "*/ ");+ // if (current_comment_start) {+ // /* Skip new line. */+ // if (current_comment_start[0] == '\n') current_comment_start++;+ // err += add_string(fptr, current_comment_start);+ // err += add_space(fptr);+ // }+ // }+ if partitionClauseCtx != nil && partitionClauseCtx.PartitionTypeDef() != nil {+ v := partitionClauseCtx.PartitionTypeDef()+ partitionDefKeyCtx, ok := v.(*tidbparser.PartitionDefKeyContext)+ if ok && partitionDefKeyCtx.PartitionKeyAlgorithm() != nil {+ numText := partitionDefKeyCtx.PartitionKeyAlgorithm().Real_ulong_number().GetText()+ num, err := strconv.Atoi(numText)+ if err != nil {+ slog.Warn(err.Error())+ } else if num == 1 || (num == 0 && len(curComment) == 0) {+ if _, err := buf.WriteString(fmt.Sprintf("*/ /*!50611 ALGORITHM = %d */ ", num)); err != nil {+ return err+ }+ if len(curComment) > 0 {+ s := curComment+ if curComment[0] == '\n' {+ s = curComment[1:]+ }+ if _, err := buf.WriteString(fmt.Sprintf("%s ", s)); err != nil {+ return err+ }+ }+ }+ }+ }+ // HACK(zp): Write the part field list. In the MySQL source code, it calls append_identifier(), which considers the quote character. We should figure out the logic of it later.+ // Currently, I just found that if the expr contains more than one field, it would not be quoted by '`'.+ // KEY and LINEAR KEY can take the field list.+ // While MySQL calls append_field_list() to write the field list, it unmasks the OPTION_QUOTE_SHOW_CREATE flag,+ // for us, we do the best effort to split the expr by ',' and trim the leading and trailing '`', and write it to the buffer after joining them with ','.+ fields := splitPartitionExprIntoFields(p.info.expr)+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ } else {+ if _, err := buf.WriteString("HASH "); err != nil {+ return err+ }+ fields := splitPartitionExprIntoFields(p.info.expr)+ for i, field := range fields {+ if !strings.Contains(field, "(") {+ fields[i] = fmt.Sprintf("`%s`", field)+ }+ }+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ }+ default:+ return errors.Errorf("unsupported partition type: %v", p.info.tp)+ }++ // NOTE: MySQL writes the default partitions in the following code, which means that the server+ // takes the responsibility to generate the partitions. Sadly, we cannot get whether the user+ // use this or not in the metadata. So we skip it.+ /*+ if ((!part_info->use_default_num_partitions) &&+ part_info->use_default_partitions) {+ err += add_string(fptr, "\n");+ err += add_string(fptr, "PARTITIONS ");+ err += add_int(fptr, part_info->num_parts);+ }+ */+ if p.info.useDefault != 0 {+ if _, err := buf.WriteString(fmt.Sprintf("\nPARTITIONS %d", p.info.useDefault)); err != nil {+ return err+ }+ }++ isSubpartitioned := p.subInfo != nil && p.subInfo.tp != storepb.TablePartitionMetadata_TYPE_UNSPECIFIED+ if isSubpartitioned {+ if _, err := buf.WriteString("\nSUBPARTITION BY "); err != nil {+ return err+ }+ }+ // Subpartition must be hash or key.+ if isSubpartitioned {+ switch p.subInfo.tp {+ case storepb.TablePartitionMetadata_HASH, storepb.TablePartitionMetadata_LINEAR_HASH:+ if p.subInfo.tp == storepb.TablePartitionMetadata_LINEAR_HASH {+ if _, err := buf.WriteString("LINEAR "); err != nil {+ return err+ }+ }+ if _, err := buf.WriteString("HASH "); err != nil {+ return err+ }+ fields := splitPartitionExprIntoFields(p.subInfo.expr)+ for i, field := range fields {+ if !strings.Contains(field, "(") {+ fields[i] = fmt.Sprintf("`%s`", field)+ }+ }+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ case storepb.TablePartitionMetadata_KEY, storepb.TablePartitionMetadata_LINEAR_KEY:+ if p.subInfo.tp == storepb.TablePartitionMetadata_LINEAR_KEY {+ if _, err := buf.WriteString("LINEAR "); err != nil {+ return err+ }+ }+ if _, err := buf.WriteString("KEY "); err != nil {+ return err+ }+ if partitionClauseCtx != nil && partitionClauseCtx.SubPartitions() != nil {+ if v := partitionClauseCtx.SubPartitions().PartitionKeyAlgorithm(); v != nil {+ numText := v.Real_ulong_number().GetText()+ num, err := strconv.Atoi(numText)+ if err != nil {+ slog.Warn(err.Error())+ } else if num == 1 || (num == 0 && len(curComment) == 0) {+ if _, err := buf.WriteString(fmt.Sprintf("*/ /*!50611 ALGORITHM = %d */ ", num)); err != nil {+ return err+ }+ if len(curComment) > 0 {+ s := curComment+ if curComment[0] == '\n' {+ s = curComment[1:]+ }+ if _, err := buf.WriteString(fmt.Sprintf("%s ", s)); err != nil {+ return err+ }+ }+ }+ }+ }+ fields := splitPartitionExprIntoFields(p.subInfo.expr)+ if _, err := buf.WriteString(fmt.Sprintf("(%s)", strings.Join(fields, ","))); err != nil {+ return err+ }+ default:+ return errors.Errorf("invalid subpartition type: %v", p.subInfo.tp)+ }+ }++ // TODO(zp): MySQL writes the default subpartitions in the following code, which means that the server+ // takes the responsibility to generate the subpartitions. Sadly, we cannot get whether the user+ // use this or not in the metadata. So we skip it.+ /*+ if ((!part_info->use_default_num_subpartitions) &&+ part_info->use_default_subpartitions) {+ err += add_string(fptr, "\n");+ err += add_string(fptr, "SUBPARTITIONS ");+ err += add_int(fptr, part_info->num_subparts);+ }+ */+ if isSubpartitioned && p.subInfo.useDefault != 0 {+ if _, err := buf.WriteString(fmt.Sprintf("\nSUBPARTITIONS %d", p.subInfo.useDefault)); err != nil {+ return err+ }+ }++ if p.info.useDefault == 0 {+ // Write the partition list.+ if len(p.partitions) == 0 {+ return errors.New("empty partition list")+ }+ sortedPartitions := make([]*partitionDefinition, 0, len(p.partitions))+ for _, partition := range p.partitions {+ sortedPartitions = append(sortedPartitions, partition)+ }+ sort.Slice(sortedPartitions, func(i, j int) bool {+ return sortedPartitions[i].id < sortedPartitions[j].id+ })+ if _, err := buf.WriteString("\n("); err != nil {+ return err+ }+ preposition, err := getPrepositionByType(p.info.tp)+ if err != nil {+ return err+ }+ for i, partition := range sortedPartitions {+ if i != 0 {+ if _, err := buf.WriteString(",\n "); err != nil {+ return err+ }+ }+ if _, err := buf.WriteString(fmt.Sprintf("PARTITION %s", partition.name)); err != nil {+ return err+ }+ if preposition != "" {+ if partition.value != "MAXVALUE" {+ if _, err := buf.WriteString(fmt.Sprintf(" VALUES %s (%s)", preposition, partition.value)); err != nil {+ return err+ }+ } else {+ if _, err := buf.WriteString(fmt.Sprintf(" VALUES %s %s", preposition, partition.value)); err != nil {+ return err+ }+ }+ }++ if isSubpartitioned && p.subInfo.useDefault == 0 {+ if len(partition.subpartitions) == 0 {+ return errors.New("empty subpartition list")+ }+ if _, err := buf.WriteString("\n ("); err != nil {+ return err+ }+ sortedSubpartitions := make([]*partitionDefinition, 0, len(partition.subpartitions))+ for _, subPartition := range partition.subpartitions {+ sortedSubpartitions = append(sortedSubpartitions, subPartition)+ }+ sort.Slice(sortedSubpartitions, func(i, j int) bool {+ return sortedSubpartitions[i].id < sortedSubpartitions[j].id+ })+ for j, subPartition := range sortedSubpartitions {+ if _, err := buf.WriteString(fmt.Sprintf("SUBPARTITION %s", subPartition.name)); err != nil {+ return err+ }+ if err := writePartitionOptions(buf); err != nil {+ return err+ }+ if j == len(sortedSubpartitions)-1 {+ if _, err := buf.WriteString(")"); err != nil {+ return err+ }+ } else {+ if _, err := buf.WriteString(",\n "); err != nil {+ return err+ }+ }+ }+ } else {+ if err := writePartitionOptions(buf); err != nil {+ return err+ }+ }++ if i == len(sortedPartitions)-1 {+ if _, err := buf.WriteString(")"); err != nil {+ return err+ }+ }+ }+ }++ if _, err := buf.WriteString(" */"); err != nil {+ return err+ }++ return nil+}++func writePartitionOptions(buf io.StringWriter) error {+ /*+ int err = 0;+ err += add_space(fptr);+ if (p_elem->tablespace_name) {+ err += add_string(fptr, "TABLESPACE = ");+ err += add_ident_string(fptr, p_elem->tablespace_name);+ err += add_space(fptr);+ }+ if (p_elem->nodegroup_id != UNDEF_NODEGROUP)+ err += add_keyword_int(fptr, "NODEGROUP", (longlong)p_elem->nodegroup_id);+ if (p_elem->part_max_rows)+ err += add_keyword_int(fptr, "MAX_ROWS", (longlong)p_elem->part_max_rows);+ if (p_elem->part_min_rows)+ err += add_keyword_int(fptr, "MIN_ROWS", (longlong)p_elem->part_min_rows);+ if (!(current_thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE)) {+ if (p_elem->data_file_name)+ err += add_keyword_path(fptr, "DATA DIRECTORY", p_elem->data_file_name);+ if (p_elem->index_file_name)+ err += add_keyword_path(fptr, "INDEX DIRECTORY", p_elem->index_file_name);+ }+ if (p_elem->part_comment)+ err += add_keyword_string(fptr, "COMMENT", true, p_elem->part_comment);+ return err + add_engine(fptr, p_elem->engine_type);+ */+ // TODO(zp): Get all the partition options from the metadata is too complex, just write ENGINE=InnoDB for now.+ if _, err := buf.WriteString(" ENGINE=InnoDB"); err != nil {+ return err+ }++ return nil+}++// getVersionSpecificComment is the go code equivalent of MySQL void partition_info::set_show_version_string(String *packet).+// partitionClauseCtx is use to minimize the difference between the original one and the output, it is safe to pass nil.+func (p *partitionState) getVersionSpecificComment(partitionClauseCtx tidbparser.IPartitionClauseContext) string {+ if p.info.tp == storepb.TablePartitionMetadata_RANGE_COLUMNS || p.info.tp == storepb.TablePartitionMetadata_LIST_COLUMNS {+ // MySQL introduce columns partitioning in 5.5+.+ return "\n/*!50500"+ } else if partitionClauseCtx != nil {+ /*+ if (part_expr)+ part_expr->walk(&Item::intro_version, enum_walk::POSTFIX,+ (uchar *)&version);+ if (subpart_expr)+ subpart_expr->walk(&Item::intro_version, enum_walk::POSTFIX,+ (uchar *)&version);+ */+ tokenStream := partitionClauseCtx.GetParser().GetTokenStream()+ startPos := partitionClauseCtx.GetStart().GetTokenIndex()+ if tokenStream != nil {+ if startPos-2 > 0 && tokenStream.Size() > startPos-2 {+ regexp := regexp.MustCompile(`\/\*![0-9]+`)+ for i := 0; i < 2; i++ {+ if tokenStream.Get(startPos-i-1).GetChannel() == antlr.TokenHiddenChannel {+ if regexp.MatchString(tokenStream.Get(startPos - i - 1).GetText()) {+ return fmt.Sprintf("\n%s", tokenStream.Get(startPos-i-1).GetText())+ }+ }+ }+ }+ }+ }+ // NOTE: Users can use function in partition expr or subpartition expr, and the intro version of function should be the infimum of the version.+ // But sadly, it's a huge work for us to copy the intro version for each function in MySQL. So we use the original one.+ return "\n/*!50100"+}++func getPrepositionByType(tp storepb.TablePartitionMetadata_Type) (string, error) {+ switch tp {+ case storepb.TablePartitionMetadata_RANGE:+ return "LESS THAN", nil+ case storepb.TablePartitionMetadata_RANGE_COLUMNS:+ return "LESS THAN", nil+ case storepb.TablePartitionMetadata_LIST:+ return "IN", nil+ case storepb.TablePartitionMetadata_LIST_COLUMNS:+ return "IN", nil+ case storepb.TablePartitionMetadata_HASH, storepb.TablePartitionMetadata_KEY, storepb.TablePartitionMetadata_LINEAR_HASH, storepb.TablePartitionMetadata_LINEAR_KEY:+ return "", nil+ default:+ return "", errors.Errorf("unsupported partition type: %v", tp)+ }+}++// splitPartitioNExprIntoFields splits the partition expression by ',', and trims the leading and trailing '`' for each element.+func splitPartitionExprIntoFields(expr string) []string {+ // We do not support the expression contains parentheses, so we can split the expression by ','.+ ss := strings.Split(expr, ",")+ for i, s := range ss {+ if strings.HasPrefix(s, "`") && strings.HasSuffix(s, "`") {+ ss[i] = s[1 : len(s)-1]+ }+ }+ return ss+}+type defaultValue interface {toString() string}@@ -524,18 +1182,23 @@ func (c *columnState) toString(buf *strings.Builder) error {}}if c.defaultValue != nil {- // todo(zp): refactor column attribute.- if strings.EqualFold(c.defaultValue.toString(), autoIncrementSymbol) {- if _, err := buf.WriteString(fmt.Sprintf(" %s", autoIncrementSymbol)); err != nil {- return err- }- } else if strings.Contains(strings.ToUpper(c.defaultValue.toString()), autoRandSymbol) {- if _, err := buf.WriteString(fmt.Sprintf(" /*T![auto_rand] %s */", c.defaultValue.toString())); err != nil {- return err- }- } else {- if _, err := buf.WriteString(fmt.Sprintf(" DEFAULT %s", c.defaultValue.toString())); err != nil {- return err+ _, isDefaultNull := c.defaultValue.(*defaultValueNull)+ dontWriteDefaultNull := isDefaultNull && c.nullable && expressionDefaultOnlyTypes[strings.ToUpper(c.tp)]+ // Some types do not default to NULL, but support default expressions.+ if !dontWriteDefaultNull {+ // todo(zp): refactor column attribute.+ if strings.EqualFold(c.defaultValue.toString(), autoIncrementSymbol) {+ if _, err := buf.WriteString(" " + autoIncrementSymbol); err != nil {+ return err+ }+ } else if strings.Contains(strings.ToUpper(c.defaultValue.toString()), autoRandSymbol) {+ if _, err := buf.WriteString(fmt.Sprintf(" /*T![auto_rand] %s */", c.defaultValue.toString())); err != nil {+ return err+ }+ } else {+ if _, err := buf.WriteString(fmt.Sprintf(" DEFAULT %s", c.defaultValue.toString())); err != nil {+ return err+ }}}}@@ -652,3 +1315,31 @@ func (v *viewState) toString(buf io.StringWriter) error {}return nil}++// getDataTypePlainText returns the plain text of the data type,+// which excludes the charset candidate.+// For example, for "varchar(10) CHARACTER SET utf8mb4",+// it returns "varchar(10)".+func getDataTypePlainText(typeCtx tidbparser.IDataTypeContext) string {+ begin := typeCtx.GetStart().GetTokenIndex()+ end := typeCtx.GetStop().GetTokenIndex()+ if typeCtx.CharsetWithOptBinary() != nil {+ end = typeCtx.CharsetWithOptBinary().GetStart().GetTokenIndex() - 1+ }+ // To skip the trailing spaces, we iterate the token stream reversely and find the first default channel token index.+ for i := end; i >= begin; i-- {+ if typeCtx.GetParser().GetTokenStream().Get(i).GetChannel() == antlr.TokenDefaultChannel {+ end = i+ break+ }+ }++ if end < begin {+ return ""+ }++ return typeCtx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: begin,+ Stop: end,+ })+}diff --git a/backend/plugin/schema/tidb/testdata/parse_to_metadata.yaml b/backend/plugin/schema/tidb/testdata/parse_to_metadata.yamlindex 55958f4bb5..b834ae8534 100644--- a/backend/plugin/schema/tidb/testdata/parse_to_metadata.yaml+++ b/backend/plugin/schema/tidb/testdata/parse_to_metadata.yaml@@ -13,89 +13,98 @@) ENGINE=InnoDB DEFAULT COLLATE=utf8mb4_bin COMMENT 'this is comment with '' escaped';metadata: |-{- "schemas": [+ "schemas": [{- "tables": [+ "tables": [{- "name": "t",- "columns": [+ "name": "t",+ "columns": [{- "name": "a",- "position": 1,- "type": "int(11)",- "comment": "this is comment",- "userComment": "this is comment"+ "name": "a",+ "position": 1,+ "type": "int",+ "comment": "this is comment",+ "userComment": "this is comment"},{- "name": "b",- "position": 2,- "type": "varchar(20)"+ "name": "b",+ "position": 2,+ "type": "VARCHAR(20)"},{- "name": "c",- "position": 3,- "defaultExpression": "CURRENT_TIMESTAMP(3)",- "onUpdate": "CURRENT_TIMESTAMP(3)",- "type": "timestamp(3)"+ "name": "c",+ "position": 3,+ "defaultExpression": "CURRENT_TIMESTAMP(3)",+ "onUpdate": "CURRENT_TIMESTAMP(3)",+ "type": "timestamp(3)"},{- "name": "d",- "position": 4,- "defaultExpression": "CURRENT_TIMESTAMP",- "onUpdate": "CURRENT_TIMESTAMP",- "type": "datetime"+ "name": "d",+ "position": 4,+ "defaultExpression": "CURRENT_TIMESTAMP",+ "onUpdate": "CURRENT_TIMESTAMP",+ "type": "datetime"},{- "name": "e",- "position": 5,- "defaultExpression": "CURRENT_TIMESTAMP",- "onUpdate": "CURRENT_TIMESTAMP",- "type": "datetime"+ "name": "e",+ "position": 5,+ "defaultExpression": "CURRENT_TIMESTAMP()",+ "onUpdate": "CURRENT_TIMESTAMP",+ "type": "datetime"}],- "indexes": [+ "indexes": [{- "name": "idx",- "expressions": [- "((`a`+20))"+ "name": "idx",+ "expressions": [+ "((`a` + 20))"],- "visible": true+ "keyLength": [+ "-1"+ ],+ "type": "BTREE",+ "visible": true},{- "name": "idx2",- "expressions": [+ "name": "idx2",+ "expressions": ["a"],- "keyLength": [+ "keyLength": ["-1"],- "unique": true,- "visible": true+ "type": "BTREE",+ "unique": true,+ "visible": true},{- "name": "idx_length",- "expressions": [+ "name": "idx_length",+ "expressions": ["b"],- "keyLength": [+ "keyLength": ["10"],- "visible": true+ "type": "BTREE",+ "visible": true},{- "name": "PRIMARY",- "expressions": [+ "name": "PRIMARY",+ "expressions": ["a"],- "unique": true,- "primary": true,- "visible": true+ "keyLength": [+ "-1"+ ],+ "unique": true,+ "primary": true,+ "visible": true}],- "engine": "InnoDB",- "collation": "utf8mb4_bin",- "comment": "this is comment with ' escaped",- "userComment": "this is comment with ' escaped"+ "engine": "InnoDB",+ "collation": "utf8mb4_bin",+ "comment": "this is comment with ' escaped",+ "userComment": "this is comment with ' escaped"}]}@@ -124,193 +133,215 @@create table t5(a bigint NOT NULL /*T![auto_rand] AUTO_RANDOM(6, 54) */, primary key (a));metadata: |-{- "schemas": [+ "schemas": [{- "tables": [+ "tables": [{- "name": "t",- "columns": [+ "name": "t",+ "columns": [{- "name": "c",- "position": 1,- "nullable": true,- "type": "int(11)"+ "name": "c",+ "position": 1,+ "defaultNull": true,+ "nullable": true,+ "type": "int"},{- "name": "a",- "position": 2,- "defaultExpression": "1",- "nullable": true,- "type": "int(11)",- "comment": "abcdefg",- "userComment": "abcdefg"+ "name": "a",+ "position": 2,+ "defaultExpression": "1",+ "nullable": true,+ "type": "int",+ "comment": "abcdefg",+ "userComment": "abcdefg"},{- "name": "b",- "position": 3,- "defaultNull": true,- "nullable": true,- "type": "varchar(20)"+ "name": "b",+ "position": 3,+ "defaultNull": true,+ "nullable": true,+ "type": "varchar(20)"},{- "name": "d",- "position": 4,- "nullable": true,- "type": "varbinary(500)"+ "name": "d",+ "position": 4,+ "defaultNull": true,+ "nullable": true,+ "type": "varbinary(500)"},{- "name": "e",- "position": 5,- "nullable": true,- "type": "binary(20)"+ "name": "e",+ "position": 5,+ "defaultNull": true,+ "nullable": true,+ "type": "binary(20)"},{- "name": "f",- "position": 6,- "nullable": true,- "type": "blob"+ "name": "f",+ "position": 6,+ "defaultNull": true,+ "nullable": true,+ "type": "blob"},{- "name": "g",- "position": 7,- "nullable": true,- "type": "tinyblob"+ "name": "g",+ "position": 7,+ "defaultNull": true,+ "nullable": true,+ "type": "tinyblob"},{- "name": "h",- "position": 8,- "nullable": true,- "type": "mediumblob"+ "name": "h",+ "position": 8,+ "defaultNull": true,+ "nullable": true,+ "type": "mediumblob"},{- "name": "i",- "position": 9,- "nullable": true,- "type": "longblob"+ "name": "i",+ "position": 9,+ "defaultNull": true,+ "nullable": true,+ "type": "longblob"},{- "name": "j",- "position": 10,- "nullable": true,- "type": "text"+ "name": "j",+ "position": 10,+ "defaultNull": true,+ "nullable": true,+ "type": "text"},{- "name": "k",- "position": 11,- "nullable": true,- "type": "tinytext"+ "name": "k",+ "position": 11,+ "defaultNull": true,+ "nullable": true,+ "type": "tinytext"}],- "indexes": [+ "indexes": [{- "name": "PRIMARY",- "expressions": [+ "name": "PRIMARY",+ "expressions": ["a","b"],- "unique": true,- "primary": true,- "visible": true+ "keyLength": [+ "-1",+ "-1"+ ],+ "unique": true,+ "primary": true,+ "visible": true}],- "foreignKeys": [+ "foreignKeys": [{- "name": "fk1",- "columns": [+ "name": "fk1",+ "columns": ["a"],- "referencedTable": "t2",- "referencedColumns": [+ "referencedTable": "t2",+ "referencedColumns": ["b"]}]},{- "name": "t2",- "columns": [+ "name": "t2",+ "columns": [{- "name": "b",- "position": 1,- "defaultNull": true,- "type": "int(11)"+ "name": "b",+ "position": 1,+ "defaultNull": true,+ "type": "int"}],- "indexes": [+ "indexes": [{- "name": "PRIMARY",- "expressions": [+ "name": "PRIMARY",+ "expressions": ["b"],- "unique": true,- "primary": true,- "visible": true+ "keyLength": [+ "-1"+ ],+ "unique": true,+ "primary": true,+ "visible": true}]},{- "name": "t3",- "columns": [+ "name": "t3",+ "columns": [{- "name": "a",- "position": 1,- "defaultExpression": "AUTO_RANDOM",- "type": "bigint(20)"+ "name": "a",+ "position": 1,+ "type": "bigint"}],- "indexes": [+ "indexes": [{- "name": "PRIMARY",- "expressions": [+ "name": "PRIMARY",+ "expressions": ["a"],- "unique": true,- "primary": true,- "visible": true+ "keyLength": [+ "-1"+ ],+ "unique": true,+ "primary": true,+ "visible": true}]},{- "name": "t4",- "columns": [+ "name": "t4",+ "columns": [{- "name": "a",- "position": 1,- "defaultExpression": "AUTO_RANDOM(6)",- "type": "bigint(20)"+ "name": "a",+ "position": 1,+ "type": "bigint"}],- "indexes": [+ "indexes": [{- "name": "PRIMARY",- "expressions": [+ "name": "PRIMARY",+ "expressions": ["a"],- "unique": true,- "primary": true,- "visible": true+ "keyLength": [+ "-1"+ ],+ "unique": true,+ "primary": true,+ "visible": true}]},{- "name": "t5",- "columns": [+ "name": "t5",+ "columns": [{- "name": "a",- "position": 1,- "defaultExpression": "AUTO_RANDOM(6, 54)",- "type": "bigint(20)"+ "name": "a",+ "position": 1,+ "type": "bigint"}],- "indexes": [+ "indexes": [{- "name": "PRIMARY",- "expressions": [+ "name": "PRIMARY",+ "expressions": ["a"],- "unique": true,- "primary": true,- "visible": true+ "keyLength": [+ "-1"+ ],+ "unique": true,+ "primary": true,+ "visible": true}]}diff --git a/backend/plugin/schema/tidb/utils.go b/backend/plugin/schema/tidb/utils.gonew file mode 100644index 0000000000..580ff3c8db--- /dev/null+++ b/backend/plugin/schema/tidb/utils.go@@ -0,0 +1,131 @@+package tidb++import (+ "strconv"++ "github.com/antlr4-go/antlr/v4"+ tidb "github.com/bytebase/tidb-parser"++ tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"+)++const (+ autoIncrementSymbol = "AUTO_INCREMENT"+ autoRandSymbol = "AUTO_RANDOM"+)++var (+ // https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html+ // expressionDefaultOnlyTypes is a list of types that only accept expression as default+ // value. While we restore the following types, we should not restore the default null.+ // +-------+--------------------------------------------------------------------++ // | Table | Create Table |+ // +-------+--------------------------------------------------------------------++ // | u | CREATE TABLE `u` ( |+ // | | `b` blob, |+ // | | `t` text, |+ // | | `g` geometry DEFAULT NULL, |+ // | | `j` json DEFAULT NULL |+ // | | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |+ // +-------+--------------------------------------------------------------------+.+ expressionDefaultOnlyTypes = map[string]bool{+ // BLOB & TEXT+ // https://dev.mysql.com/doc/refman/8.0/en/blob.html+ "TINYBLOB": true,+ "BLOB": true,+ "MEIDUMBLOB": true,+ "LONGBLOB": true,+ "TINYTEXT": true,+ "TEXT": true,+ "MEDIUMTEXT": true,+ "LONGTEXT": true,++ // In practice, the following types restore the default null by mysqldump.+ // // GEOMETRY+ // "GEOMETRY": true,+ // // JSON+ // // https://dev.mysql.com/doc/refman/8.0/en/json.html+ // "JSON": true,+ }+)++func extractReference(ctx tidb.IReferencesContext) (string, []string) {+ _, table := tidbparser.NormalizeTiDBTableRef(ctx.TableRef())+ if ctx.IdentifierListWithParentheses() != nil {+ columns := extractIdentifierList(ctx.IdentifierListWithParentheses().IdentifierList())+ return table, columns+ }+ return table, nil+}++func extractIdentifierList(ctx tidb.IIdentifierListContext) []string {+ var result []string+ for _, identifier := range ctx.AllIdentifier() {+ result = append(result, tidbparser.NormalizeTiDBIdentifier(identifier))+ }+ return result+}++func extractKeyListVariants(ctx tidb.IKeyListVariantsContext) ([]string, []int64) {+ if ctx.KeyList() != nil {+ return extractKeyList(ctx.KeyList())+ }+ if ctx.KeyListWithExpression() != nil {+ return extractKeyListWithExpression(ctx.KeyListWithExpression())+ }+ return nil, nil+}++func extractKeyListWithExpression(ctx tidb.IKeyListWithExpressionContext) ([]string, []int64) {+ var result []string+ var keyLengths []int64+ for _, key := range ctx.AllKeyPartOrExpression() {+ if key.KeyPart() != nil {+ keyText, keyLength := getKeyExpressionAndLengthFromKeyPart(key.KeyPart())+ result = append(result, keyText)+ keyLengths = append(keyLengths, keyLength)+ } else if key.ExprWithParentheses() != nil {+ keyText := key.GetParser().GetTokenStream().GetTextFromRuleContext(key.ExprWithParentheses())+ result = append(result, keyText)+ keyLengths = append(keyLengths, -1)+ }+ }+ return result, keyLengths+}++func extractKeyList(ctx tidb.IKeyListContext) ([]string, []int64) {+ var result []string+ var keyLengths []int64+ for _, key := range ctx.AllKeyPart() {+ keyText, keyLength := getKeyExpressionAndLengthFromKeyPart(key)+ result = append(result, keyText)+ keyLengths = append(keyLengths, keyLength)+ }+ return result, keyLengths+}++func getKeyExpressionAndLengthFromKeyPart(ctx tidb.IKeyPartContext) (string, int64) {+ keyText := tidbparser.NormalizeTiDBIdentifier(ctx.Identifier())+ keyLength := int64(-1)+ if ctx.FieldLength() != nil {+ l := ctx.FieldLength().GetText()+ if len(l) > 2 && l[0] == '(' && l[len(l)-1] == ')' {+ l = l[1 : len(l)-1]+ }+ length, err := strconv.ParseInt(l, 10, 64)+ if err != nil {+ length = -1+ }+ keyLength = length+ }+ return keyText, keyLength+}++func nextDefaultChannelTokenIndex(tokens antlr.TokenStream, currentIndex int) int {+ for i := currentIndex + 1; i < tokens.Size(); i++ {+ if tokens.Get(i).GetChannel() == antlr.TokenDefaultChannel {+ return i+ }+ }+ return 0+}