Skip to content

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

fix: tidb parse to metadata handle anto rand (#13498)

h3n4l4be1b1cd0f7c
diff --git a/backend/api/v1/branch_service.go b/backend/api/v1/branch_service.go
index 7f7c47c4f6..d2c10e9bf0 100644
--- a/backend/api/v1/branch_service.go
+++ b/backend/api/v1/branch_service.go
@@ -1014,6 +1014,17 @@ func filterDatabaseMetadataByEngine(metadata *storepb.DatabaseSchemaMetadata, en
filteredSchema.Tables = append(filteredSchema.Tables, filteredTable)
}
+ if engine == storepb.Engine_MYSQL || engine == storepb.Engine_TIDB {
+ for _, view := range schema.Views {
+ filteredView := &storepb.ViewMetadata{
+ Name: view.Name,
+ Comment: view.Comment,
+ Definition: view.Definition,
+ }
+ filteredSchema.Views = append(filteredSchema.Views, filteredView)
+ }
+ }
+
if engine == storepb.Engine_MYSQL {
for _, function := range schema.Functions {
filteredFunction := &storepb.FunctionMetadata{
@@ -1029,14 +1040,6 @@ func filterDatabaseMetadataByEngine(metadata *storepb.DatabaseSchemaMetadata, en
}
filteredSchema.Procedures = append(filteredSchema.Procedures, filteredProcedure)
}
- for _, view := range schema.Views {
- filteredView := &storepb.ViewMetadata{
- Name: view.Name,
- Comment: view.Comment,
- Definition: view.Definition,
- }
- filteredSchema.Views = append(filteredSchema.Views, filteredView)
- }
}
filteredDatabase.Schemas = append(filteredDatabase.Schemas, filteredSchema)
}
diff --git a/backend/plugin/schema/tidb/parse_to_metadata.go b/backend/plugin/schema/tidb/parse_to_metadata.go
index bd7a99923f..ada118d2b0 100644
--- a/backend/plugin/schema/tidb/parse_to_metadata.go
+++ b/backend/plugin/schema/tidb/parse_to_metadata.go
@@ -2,6 +2,7 @@ package tidb
import (
"fmt"
+ "regexp"
"strconv"
"strings"
@@ -194,6 +195,40 @@ func (t *tidbTransformer) EnterColumnDef(ctx *tidb.ColumnDefContext) {
columnState.defaultValue = &defaultValueNull{}
}
+ nextDefaultChannelTokenPos := ctx.GetStop().GetTokenIndex() + 1
+ for ; nextDefaultChannelTokenPos < ctx.GetParser().GetTokenStream().Size(); nextDefaultChannelTokenPos++ {
+ if ctx.GetParser().GetTokenStream().Get(nextDefaultChannelTokenPos).GetChannel() == antlr.LexerDefaultTokenChannel {
+ break
+ }
+ }
+ executableComments := scanTiDBExecutableComment(ctx.GetParser().GetTokenStream(), ctx.GetStart().GetTokenIndex(), nextDefaultChannelTokenPos)
+ for _, comment := range executableComments {
+ c := buildTiDBFeatureExecutableComment(comment)
+ if c == nil {
+ continue
+ }
+ if v, ok := c.(*autoRandomExecutableComment); ok {
+ defaultValueString := "AUTO_RANDOM"
+ canonicalShardBit := 5
+ if v.shardBit != 0 {
+ canonicalShardBit = v.shardBit
+ }
+ canonicalAllocationRange := 64
+ if v.allocationRange != 0 {
+ canonicalAllocationRange = v.allocationRange
+ }
+ suffix := fmt.Sprintf("(%d", canonicalShardBit)
+ if canonicalAllocationRange != 64 {
+ suffix = fmt.Sprintf("%s, %d", suffix, canonicalAllocationRange)
+ }
+ suffix = fmt.Sprintf("%s)", suffix)
+ defaultValueString += suffix
+ columnState.defaultValue = &defaultValueExpression{
+ value: defaultValueString,
+ }
+ }
+ }
+
table.columns[columnName] = columnState
}
@@ -576,3 +611,77 @@ func (t *tidbTransformer) EnterCreateView(ctx *tidb.CreateViewContext) {
definition: definition,
}
}
+
+type tidbFeatureExecutableComment interface {
+ isTiDBFeatureExecutableComment()
+}
+
+type autoRandomExecutableComment struct {
+ shardBit int
+ allocationRange int
+}
+
+func (*autoRandomExecutableComment) isTiDBFeatureExecutableComment() {}
+
+var (
+ autorandRegexp = regexp.MustCompile(`(?i)\[\s*auto_rand\s*\]\s*auto_random(\(\s*(?P<shardBit>(\d+))?\s*(,\s*(?P<allocationRange>(\d+)))?\s*\))?`)
+)
+
+func buildTiDBFeatureExecutableComment(innerText string) tidbFeatureExecutableComment {
+ // Syntax: [auto_rand] auto_random(5, 32)
+ innerText = strings.TrimSpace(innerText)
+ autoRandMatches := autorandRegexp.FindStringSubmatch(innerText)
+ if autoRandMatches != nil {
+ result := &autoRandomExecutableComment{}
+ for i, name := range autorandRegexp.SubexpNames() {
+ if name == "shardBit" {
+ if autoRandMatches[i] != "" {
+ shardBit, err := strconv.ParseInt(autoRandMatches[i], 10, 64)
+ if err != nil {
+ return nil
+ }
+ result.shardBit = int(shardBit)
+ }
+ } else if name == "allocationRange" {
+ if autoRandMatches[i] != "" {
+ allocationRange, err := strconv.ParseInt(autoRandMatches[i], 10, 64)
+ if err != nil {
+ return nil
+ }
+ result.allocationRange = int(allocationRange)
+ }
+ }
+ }
+ return result
+ }
+
+ return nil
+}
+
+// scanTiDBExecutableComment scans the TiDB executable comment in ts[beginPos:endPos).
+func scanTiDBExecutableComment(ts antlr.TokenStream, beginPos int, endPos int) []string {
+ tssz := ts.Size()
+ if tssz < beginPos {
+ return nil
+ }
+ if tssz < endPos {
+ endPos = tssz
+ }
+
+ var result []string
+
+ for i := beginPos; i < endPos; i++ {
+ token := ts.Get(i)
+ if token.GetChannel() != antlr.TokenHiddenChannel {
+ continue
+ }
+ text := token.GetText()
+ if strings.HasPrefix(text, "/*T!") && strings.HasSuffix(text, "*/") {
+ trimmedText := text[4:]
+ trimmedText = trimmedText[:len(trimmedText)-2]
+ result = append(result, trimmedText)
+ }
+ }
+
+ return result
+}
diff --git a/backend/plugin/schema/tidb/parse_to_metadata_test.go b/backend/plugin/schema/tidb/parse_to_metadata_test.go
index f36b12e735..0f2dc1c5bd 100644
--- a/backend/plugin/schema/tidb/parse_to_metadata_test.go
+++ b/backend/plugin/schema/tidb/parse_to_metadata_test.go
@@ -5,6 +5,8 @@ import (
"os"
"testing"
+ "github.com/antlr4-go/antlr/v4"
+ tidbparser "github.com/bytebase/tidb-parser"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
@@ -59,3 +61,35 @@ func TestParseToMetadata(t *testing.T) {
a.NoError(err)
}
}
+
+func TestScanTiDBExecutableComment(t *testing.T) {
+ testCases := []struct {
+ statement string
+ begin *int
+ end *int
+ want []string
+ }{
+ {
+ statement: `CREATE TABLE t(id BIGINT NOT NULL /*T![auto_rand] AUTO_RANDOM(10) */ PRIMARY KEY);`,
+ want: []string{
+ `[auto_rand] AUTO_RANDOM(10) `,
+ },
+ },
+ }
+ for _, tc := range testCases {
+ input := antlr.NewInputStream(tc.statement)
+ lexer := tidbparser.NewTiDBLexer(input)
+ stream := antlr.NewCommonTokenStream(lexer, 0)
+ stream.Fill()
+ begin := 0
+ if tc.begin != nil {
+ begin = *tc.begin
+ }
+ end := stream.Size()
+ if tc.end != nil {
+ end = *tc.end
+ }
+ got := scanTiDBExecutableComment(stream, begin, end)
+ require.Equal(t, tc.want, got)
+ }
+}
diff --git a/backend/plugin/schema/tidb/testdata/parse_to_metadata.yaml b/backend/plugin/schema/tidb/testdata/parse_to_metadata.yaml
index b834ae8534..a1f530c2fb 100644
--- a/backend/plugin/schema/tidb/testdata/parse_to_metadata.yaml
+++ b/backend/plugin/schema/tidb/testdata/parse_to_metadata.yaml
@@ -1,3 +1,44 @@
+- schema: |-
+ CREATE TABLE `t1` (
+ `id` bigint(20) NOT NULL /*T![auto_rand] AUTO_RANDOM(10) */,
+ PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
+ metadata: |-
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "t1",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "defaultExpression": "AUTO_RANDOM(10)",
+ "type": "bigint(20)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "keyLength": [
+ "-1"
+ ],
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "collation": "utf8mb4_bin"
+ }
+ ]
+ }
+ ]
+ }
- schema: |-
create table t
(
@@ -327,6 +368,7 @@
{
"name": "a",
"position": 1,
+ "defaultExpression": "AUTO_RANDOM(6, 54)",
"type": "bigint"
}
],