Skip to content

Commit 78cb734

Browse files
committed
refactor the rewriter
1 parent 40c180d commit 78cb734

3 files changed

Lines changed: 153 additions & 169 deletions

File tree

‎downstreamadapter/routing/ddl_query_rewriter.go‎

Lines changed: 45 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import (
2222
"github.com/pingcap/tidb/pkg/parser"
2323
"github.com/pingcap/tidb/pkg/parser/ast"
2424
"github.com/pingcap/tidb/pkg/parser/format"
25-
"github.com/pingcap/tidb/pkg/util/filter"
2625
)
2726

2827
// rewriteParserBackedDDLQuery rewrites a parser-supported DDL query by applying routing rules.
@@ -40,14 +39,13 @@ func (r Router) rewriteParserBackedDDLQuery(ddl *commonEvent.DDLEvent) (string,
4039
}
4140
}
4241

43-
defaultSchema := ddl.GetSchemaName()
4442
var (
4543
builder strings.Builder
4644
routed bool
4745
)
4846
for i := range queries {
4947
query := queries[i]
50-
newQuery, changed, err := r.rewriteSingleDDLQuery(query, defaultSchema)
48+
newQuery, changed, err := r.rewriteSingleDDLQuery(query)
5149
if err != nil {
5250
return "", err
5351
}
@@ -67,48 +65,45 @@ func (r Router) rewriteParserBackedDDLQuery(ddl *commonEvent.DDLEvent) (string,
6765
return builder.String(), nil
6866
}
6967

70-
func (r Router) rewriteSingleDDLQuery(query string, defaultSchema string) (string, bool, error) {
68+
func (r Router) rewriteSingleDDLQuery(query string) (string, bool, error) {
7169
p := parser.New()
7270
stmt, err := p.ParseOneStmt(query, "", "")
7371
if err != nil {
7472
return "", false, errors.WrapError(errors.ErrTableRoutingFailed, err)
7573
}
7674

77-
sourceTables, err := fetchDDLTables(defaultSchema, stmt)
78-
if err != nil {
79-
return "", false, err
80-
}
75+
sourceTables := extractTableNames(stmt)
8176
if len(sourceTables) == 0 {
8277
return query, false, nil
8378
}
8479

8580
var (
8681
routed bool
87-
targetTables = make([]*filter.Table, 0, len(sourceTables))
82+
targetTables = make([]commonEvent.SchemaTableName, 0, len(sourceTables))
8883
)
8984
for _, srcTable := range sourceTables {
90-
targetSchema, targetTable, changed, err := r.route(srcTable.Schema, srcTable.Name)
85+
targetSchema, targetTable, changed, err := r.route(srcTable.SchemaName, srcTable.TableName)
9186
if err != nil {
9287
return "", false, err
9388
}
9489
if changed {
9590
routed = true
9691
}
97-
targetTables = append(targetTables, &filter.Table{
98-
Schema: targetSchema,
99-
Name: targetTable,
92+
targetTables = append(targetTables, commonEvent.SchemaTableName{
93+
SchemaName: targetSchema,
94+
TableName: targetTable,
10095
})
10196
}
10297

10398
if !routed {
10499
return query, false, nil
105100
}
106101

107-
rewritten, err := rewriteDDLStmtTables(stmt, targetTables)
102+
newQuery, err := rewriteDDLStmtTables(stmt, targetTables)
108103
if err != nil {
109104
return "", false, err
110105
}
111-
return rewritten, true, nil
106+
return newQuery, true, nil
112107
}
113108

114109
func (r Router) rewriteAddFullTextIndexQuery(query, targetSchema, targetTable string) (string, error) {
@@ -137,8 +132,7 @@ func (r Router) rewriteAddFullTextIndexQuery(query, targetSchema, targetTable st
137132
}
138133
addIndexStart += tableStart
139134

140-
suffix := strings.TrimLeft(query[addIndexStart:], " \n\r\t\f")
141-
return query[:tableStart] + " " + targetTableName + " " + suffix, nil
135+
return query[:tableStart] + " " + targetTableName + " " + query[addIndexStart:], nil
142136
}
143137

144138
func (r Router) rewriteCreateHybridIndexQuery(query, targetSchema, targetTable string) (string, error) {
@@ -164,8 +158,7 @@ func (r Router) rewriteCreateHybridIndexQuery(query, targetSchema, targetTable s
164158
return "", errors.ErrTableRoutingFailed.GenWithStack(
165159
"rewrite parser unsupported ddl query failed, query: %s", query)
166160
}
167-
suffix := strings.TrimLeft(query[columnListStart:], " \n\r\t\f")
168-
return query[:tableStart] + targetTableName + suffix, nil
161+
return query[:tableStart] + targetTableName + query[columnListStart:], nil
169162
}
170163

171164
// quoteDDLIdentifier quotes routed target names so route-generated identifiers are always valid SQL.
@@ -176,17 +169,12 @@ func quoteDDLIdentifier(name string) string {
176169
// tableNameExtractor extracts table names from DDL AST nodes.
177170
// ref: https://github.com/pingcap/tidb/blob/09feccb529be2830944e11f5fed474020f50370f/server/sql_info_fetcher.go#L46
178171
type tableNameExtractor struct {
179-
curDB string
180-
names []*filter.Table
172+
names []commonEvent.SchemaTableName
181173
}
182174

183175
func (tne *tableNameExtractor) Enter(in ast.Node) (ast.Node, bool) {
184176
if t, ok := in.(*ast.TableName); ok {
185-
tb := &filter.Table{Schema: t.Schema.O, Name: t.Name.O}
186-
if tb.Schema == "" {
187-
tb.Schema = tne.curDB
188-
}
189-
tne.names = append(tne.names, tb)
177+
tne.names = append(tne.names, commonEvent.SchemaTableName{SchemaName: t.Schema.O, TableName: t.Name.O})
190178
return in, true
191179
}
192180
return in, false
@@ -196,48 +184,42 @@ func (tne *tableNameExtractor) Leave(in ast.Node) (ast.Node, bool) {
196184
return in, true
197185
}
198186

199-
// fetchDDLTables returns tables in DDL statement.
187+
// extractTableNames returns tables in DDL statement.
200188
// Because we use visitor pattern, first tableName is always upper-most table in AST.
201189
// Specifically:
202190
// - for `CREATE TABLE ... LIKE` DDL, result contains [sourceTable, sourceRefTable]
203191
// - for RENAME TABLE DDL, result contains [old1, new1, old2, new2, old3, new3, ...] because of TiDB parser
204192
// - for other DDL, order of tableName is the node visit order.
205-
func fetchDDLTables(schema string, stmt ast.StmtNode) ([]*filter.Table, error) {
206-
switch stmt.(type) {
207-
case ast.DDLNode:
208-
default:
209-
return nil, errors.ErrTableRoutingFailed.GenWithStack(
210-
"fetch ddl tables got non ddl statement: %T", stmt)
211-
}
212-
193+
func extractTableNames(stmt ast.StmtNode) []commonEvent.SchemaTableName {
213194
// Special cases: schema related SQLs don't have tableName
214195
switch v := stmt.(type) {
215196
case *ast.AlterDatabaseStmt:
216-
dbName := v.Name.O
217-
if dbName == "" {
218-
dbName = schema
219-
}
220-
return []*filter.Table{{Schema: dbName, Name: ""}}, nil
197+
return []commonEvent.SchemaTableName{{SchemaName: v.Name.O, TableName: ""}}
221198
case *ast.CreateDatabaseStmt:
222-
return []*filter.Table{{Schema: v.Name.O, Name: ""}}, nil
199+
return []commonEvent.SchemaTableName{{SchemaName: v.Name.O, TableName: ""}}
223200
case *ast.DropDatabaseStmt:
224-
return []*filter.Table{{Schema: v.Name.O, Name: ""}}, nil
201+
return []commonEvent.SchemaTableName{{SchemaName: v.Name.O, TableName: ""}}
225202
}
226203

227204
e := &tableNameExtractor{
228-
curDB: schema,
229-
names: make([]*filter.Table, 0),
205+
names: make([]commonEvent.SchemaTableName, 0),
230206
}
231207
stmt.Accept(e)
232208

233-
return e.names, nil
209+
return e.names
234210
}
235211

236-
// tableRenameVisitor renames tables in DDL AST nodes.
212+
// tableRenameVisitor rewrites *ast.TableName nodes in the same traversal order
213+
// used by tableNameExtractor. Each visited table consumes one entry from
214+
// targetNames, so the caller can detect too few or too many target names after
215+
// traversal.
237216
type tableRenameVisitor struct {
238-
targetNames []*filter.Table
239-
i int
240-
hasErr bool
217+
// targetNames contains routed names aligned with tableNameExtractor output.
218+
targetNames []commonEvent.SchemaTableName
219+
// i is the next targetNames index to consume.
220+
i int
221+
// hasErr records targetNames exhaustion because ast.Visitor cannot return an error.
222+
hasErr bool
241223
}
242224

243225
func (v *tableRenameVisitor) Enter(in ast.Node) (ast.Node, bool) {
@@ -249,8 +231,8 @@ func (v *tableRenameVisitor) Enter(in ast.Node) (ast.Node, bool) {
249231
v.hasErr = true
250232
return in, true
251233
}
252-
t.Schema = ast.NewCIStr(v.targetNames[v.i].Schema)
253-
t.Name = ast.NewCIStr(v.targetNames[v.i].Name)
234+
t.Schema = ast.NewCIStr(v.targetNames[v.i].SchemaName)
235+
t.Name = ast.NewCIStr(v.targetNames[v.i].TableName)
254236
v.i++
255237
return in, true
256238
}
@@ -265,35 +247,28 @@ func (v *tableRenameVisitor) Leave(in ast.Node) (ast.Node, bool) {
265247
}
266248

267249
// rewriteDDLStmtTables renames tables in DDL by given `targetTables`.
268-
// Argument `targetTables` should have the same structure as the return value of fetchDDLTables.
250+
// Argument `targetTables` should have the same structure as the return value of extractTableNames.
269251
// Returned DDL is formatted like StringSingleQuotes, KeyWordUppercase and NameBackQuotes.
270-
func rewriteDDLStmtTables(stmt ast.StmtNode, targetTables []*filter.Table) (string, error) {
271-
switch stmt.(type) {
272-
case ast.DDLNode:
273-
default:
274-
return "", errors.ErrTableRoutingFailed.GenWithStack(
275-
"rewrite ddl query got non ddl statement: %T", stmt)
276-
}
277-
252+
func rewriteDDLStmtTables(stmt ast.StmtNode, targetTables []commonEvent.SchemaTableName) (string, error) {
278253
switch v := stmt.(type) {
279254
case *ast.AlterDatabaseStmt:
280255
if len(targetTables) != 1 {
281256
return "", errors.ErrTableRoutingFailed.GenWithStack(
282257
"rewrite ddl query got unexpected target table count: expected 1, got %d", len(targetTables))
283258
}
284-
v.Name = ast.NewCIStr(targetTables[0].Schema)
259+
v.Name = ast.NewCIStr(targetTables[0].SchemaName)
285260
case *ast.CreateDatabaseStmt:
286261
if len(targetTables) != 1 {
287262
return "", errors.ErrTableRoutingFailed.GenWithStack(
288263
"rewrite ddl query got unexpected target table count: expected 1, got %d", len(targetTables))
289264
}
290-
v.Name = ast.NewCIStr(targetTables[0].Schema)
265+
v.Name = ast.NewCIStr(targetTables[0].SchemaName)
291266
case *ast.DropDatabaseStmt:
292267
if len(targetTables) != 1 {
293268
return "", errors.ErrTableRoutingFailed.GenWithStack(
294269
"rewrite ddl query got unexpected target table count: expected 1, got %d", len(targetTables))
295270
}
296-
v.Name = ast.NewCIStr(targetTables[0].Schema)
271+
v.Name = ast.NewCIStr(targetTables[0].SchemaName)
297272
default:
298273
visitor := &tableRenameVisitor{
299274
targetNames: targetTables,
@@ -312,6 +287,13 @@ func rewriteDDLStmtTables(stmt ast.StmtNode, targetTables []*filter.Table) (stri
312287

313288
bf := &bytes.Buffer{}
314289
err := stmt.Restore(&format.RestoreCtx{
290+
// TiDB stores the original SQL in sessionctx.QueryString and copies it into
291+
// DDL job.Query:
292+
// https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/session/session.go#L2905
293+
// https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/ddl/executor.go#L6952-L6957
294+
// After routing mutates the AST, CDC must serialize it again. Keep the
295+
// parser's standard restore style, TiDB special comments, and default
296+
// charset handling consistent with CDC's DDL query normalization.
315297
Flags: format.DefaultRestoreFlags | format.RestoreTiDBSpecialComment | format.RestoreStringWithoutDefaultCharset,
316298
In: bf,
317299
})

0 commit comments

Comments
 (0)