-
Notifications
You must be signed in to change notification settings - Fork 2k
/
query_planner.go
458 lines (395 loc) · 13.5 KB
/
query_planner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
Copyright 2021 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vexec
import (
"errors"
"fmt"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vttablet/tmclient"
)
var ( // Query planning errors.
// ErrCannotUpdateImmutableColumn is returned when attempting to plan a
// query that updates a column that should be treated as immutable.
ErrCannotUpdateImmutableColumn = errors.New("cannot update immutable column")
// ErrUnsupportedQueryConstruct is returned when a particular query
// construct is unsupported by a QueryPlanner, despite the more general kind
// of query being supported.
//
// For example, VReplication supports DELETEs, but does not support DELETEs
// with LIMIT clauses, so planning a "DELETE ... LIMIT" will return
// ErrUnsupportedQueryConstruct rather than a "CREATE TABLE", which would
// return an ErrUnsupportedQuery.
ErrUnsupportedQueryConstruct = errors.New("unsupported query construct")
)
var ( // Query execution errors.
// ErrUnpreparedQuery is returned when attempting to execute an unprepared
// QueryPlan.
ErrUnpreparedQuery = errors.New("attempted to execute unprepared query")
)
// QueryPlanner defines the interface that VExec uses to build QueryPlans for
// various vexec workflows. A given vexec table, which is to say a table in the
// "_vt" database, will have at most one QueryPlanner implementation, which is
// responsible for defining both what queries are supported for that table, as
// well as how to build plans for those queries.
//
// VReplicationQueryPlanner is a good example implementation to refer to.
type QueryPlanner interface {
// (NOTE:@ajm188) I don't think this method fits on the query planner. To
// me, especially given that it's only implemented by the vrep query planner
// in the old implementation (the schema migration query planner no-ops this
// method), this fits better on our workflow.Manager struct, probably as a
// method called something like "VReplicationExec(ctx, query, Options{DryRun: true})"
// DryRun(ctx context.Context) error
// PlanQuery constructs and returns a QueryPlan for a given statement. The
// resulting QueryPlan is suitable for repeated, concurrent use.
PlanQuery(stmt sqlparser.Statement) (QueryPlan, error)
// QueryParams returns a struct of column parameters the QueryPlanner uses.
// It is used primarily to abstract the adding of default WHERE clauses to
// queries by a private function of this package, and may be removed from
// the interface later.
QueryParams() QueryParams
}
// QueryParams is a struct that QueryPlanner implementations can provide to
// control the addition of default WHERE clauses to their queries.
type QueryParams struct {
// DBName is the value that the column referred to by DBNameColumn should
// equal in a WHERE clause, if set.
DBName string
// DBNameColumn is the name of the column that DBName should equal in a
// WHERE clause, if set.
DBNameColumn string
// Workflow is the value that the column referred to by WorkflowColumn
// should equal in a WHERE clause, if set.
Workflow string
// WorkflowColumn is the name of the column that Workflow should equal in a
// WHERE clause, if set.
WorkflowColumn string
}
// VReplicationQueryPlanner implements the QueryPlanner interface for queries on
// the _vt.vreplication table.
type VReplicationQueryPlanner struct {
tmc tmclient.TabletManagerClient
dbname string
workflow string
}
// NewVReplicationQueryPlanner returns a new VReplicationQueryPlanner. It is
// valid to pass empty strings for both the dbname and workflow parameters.
func NewVReplicationQueryPlanner(tmc tmclient.TabletManagerClient, workflow string, dbname string) *VReplicationQueryPlanner {
return &VReplicationQueryPlanner{
tmc: tmc,
dbname: dbname,
workflow: workflow,
}
}
// PlanQuery is part of the QueryPlanner interface.
//
// For vreplication query planners, only SELECT, UPDATE, and DELETE queries are
// supported.
//
// For UPDATE queries, ORDER BY and LIMIT clauses are not supported. Attempting
// to update vreplication.id is an error.
//
// For DELETE queries, USING, PARTITION, ORDER BY, and LIMIT clauses are not
// supported.
func (planner *VReplicationQueryPlanner) PlanQuery(stmt sqlparser.Statement) (plan QueryPlan, err error) {
switch stmt := stmt.(type) {
case *sqlparser.Select:
plan, err = planner.planSelect(stmt)
case *sqlparser.Insert:
err = ErrUnsupportedQuery
case *sqlparser.Update:
plan, err = planner.planUpdate(stmt)
case *sqlparser.Delete:
plan, err = planner.planDelete(stmt)
default:
err = ErrUnsupportedQuery
}
if err != nil {
return nil, fmt.Errorf("%w: %s", err, sqlparser.String(stmt))
}
return plan, nil
}
// QueryParams is part of the QueryPlanner interface. A VReplicationQueryPlanner
// will attach the following WHERE clauses iff (a) DBName, Workflow are set,
// respectively, and (b) db_name and workflow do not appear in the original
// query's WHERE clause:
//
// WHERE (db_name = {{ .DBName }} AND)? (workflow = {{ .Workflow }} AND)? {{ .OriginalWhere }}
func (planner *VReplicationQueryPlanner) QueryParams() QueryParams {
return QueryParams{
DBName: planner.dbname,
DBNameColumn: "db_name",
Workflow: planner.workflow,
WorkflowColumn: "workflow",
}
}
func (planner *VReplicationQueryPlanner) planDelete(del *sqlparser.Delete) (*FixedQueryPlan, error) {
if del.Targets != nil {
return nil, fmt.Errorf(
"%w: DELETE must not have USING clause (have: %v): %v",
ErrUnsupportedQueryConstruct,
del.Targets,
sqlparser.String(del),
)
}
if del.Partitions != nil {
return nil, fmt.Errorf(
"%w: DELETE must not have explicit partitions (have: %v): %v",
ErrUnsupportedQueryConstruct,
del.Partitions,
sqlparser.String(del),
)
}
if del.OrderBy != nil || del.Limit != nil {
return nil, fmt.Errorf(
"%w: DELETE must not have explicit ordering (have: %v) or limit clauses (have: %v): %v",
ErrUnsupportedQueryConstruct,
del.OrderBy,
del.Limit,
sqlparser.String(del),
)
}
del.Where = addDefaultWheres(planner, del.Where)
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("%v", del)
return &FixedQueryPlan{
ParsedQuery: buf.ParsedQuery(),
workflow: planner.workflow,
tmc: planner.tmc,
}, nil
}
func (planner *VReplicationQueryPlanner) planSelect(sel *sqlparser.Select) (*FixedQueryPlan, error) {
sel.Where = addDefaultWheres(planner, sel.Where)
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("%v", sel)
return &FixedQueryPlan{
ParsedQuery: buf.ParsedQuery(),
workflow: planner.workflow,
tmc: planner.tmc,
}, nil
}
func (planner *VReplicationQueryPlanner) planUpdate(upd *sqlparser.Update) (*FixedQueryPlan, error) {
if upd.OrderBy != nil || upd.Limit != nil {
return nil, fmt.Errorf(
"%w: UPDATE must not have explicit ordering (have: %v) or limit clauses (have: %v): %v",
ErrUnsupportedQueryConstruct,
upd.OrderBy,
upd.Limit,
sqlparser.String(upd),
)
}
// For updates on the _vt.vreplication table, we ban updates to the `id`
// column, and allow updates to all other columns.
for _, expr := range upd.Exprs {
if expr.Name.Name.EqualString("id") {
return nil, fmt.Errorf(
"%w %+v: %v",
ErrCannotUpdateImmutableColumn,
expr.Name.Name,
sqlparser.String(expr),
)
}
}
upd.Where = addDefaultWheres(planner, upd.Where)
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("%v", upd)
return &FixedQueryPlan{
ParsedQuery: buf.ParsedQuery(),
workflow: planner.workflow,
tmc: planner.tmc,
}, nil
}
// VReplicationLogQueryPlanner implements the QueryPlanner interface for queries
// on the _vt.vreplication_log table.
type VReplicationLogQueryPlanner struct {
tmc tmclient.TabletManagerClient
tabletStreamIDs map[string][]int64
}
// NewVReplicationLogQueryPlanner returns a new VReplicationLogQueryPlanner. The
// tabletStreamIDs map determines what stream_ids are expected to have vrep_log
// rows, keyed by tablet alias string.
func NewVReplicationLogQueryPlanner(tmc tmclient.TabletManagerClient, tabletStreamIDs map[string][]int64) *VReplicationLogQueryPlanner {
return &VReplicationLogQueryPlanner{
tmc: tmc,
tabletStreamIDs: tabletStreamIDs,
}
}
// PlanQuery is part of the QueryPlanner interface.
//
// For vreplication_log query planners, only SELECT queries are supported.
func (planner *VReplicationLogQueryPlanner) PlanQuery(stmt sqlparser.Statement) (plan QueryPlan, err error) {
switch stmt := stmt.(type) {
case *sqlparser.Select:
plan, err = planner.planSelect(stmt)
case *sqlparser.Insert:
err = ErrUnsupportedQuery
case *sqlparser.Update:
err = ErrUnsupportedQuery
case *sqlparser.Delete:
err = ErrUnsupportedQuery
default:
err = ErrUnsupportedQuery
}
if err != nil {
return nil, fmt.Errorf("%w: %s", err, sqlparser.String(stmt))
}
return plan, nil
}
// QueryParams is part of the QueryPlanner interface.
func (planner *VReplicationLogQueryPlanner) QueryParams() QueryParams {
return QueryParams{}
}
func (planner *VReplicationLogQueryPlanner) planSelect(sel *sqlparser.Select) (QueryPlan, error) {
where := sel.Where
cols := extractWhereComparisonColumns(where)
hasVReplIDCol := false
for _, col := range cols {
if col == "vrepl_id" {
hasVReplIDCol = true
}
}
if hasVReplIDCol { // we're not injecting per-target parameters, return a Fixed plan
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("%v", sel)
return &FixedQueryPlan{
ParsedQuery: buf.ParsedQuery(),
tmc: planner.tmc,
}, nil
}
// Construct a where clause to filter by vrepl_id, parameterized by target
// streamIDs.
queriesByTarget := make(map[string]*sqlparser.ParsedQuery, len(planner.tabletStreamIDs))
for target, streamIDs := range planner.tabletStreamIDs {
targetWhere := &sqlparser.Where{
Type: sqlparser.WhereClause,
}
var expr sqlparser.Expr
switch len(streamIDs) {
case 0: // WHERE vreplication_log.vrepl_id IN () => WHERE 1 != 1
one := sqlparser.NewIntLiteral("1")
expr = &sqlparser.ComparisonExpr{
Operator: sqlparser.NotEqualOp,
Left: one,
Right: one,
}
case 1: // WHERE vreplication_log.vrepl_id = ?
expr = &sqlparser.ComparisonExpr{
Operator: sqlparser.EqualOp,
Left: &sqlparser.ColName{
Name: sqlparser.NewIdentifierCI("vrepl_id"),
},
Right: sqlparser.NewIntLiteral(fmt.Sprintf("%d", streamIDs[0])),
}
default: // WHERE vreplication_log.vrepl_id IN (?)
vals := []sqlparser.Expr{}
for _, streamID := range streamIDs {
vals = append(vals, sqlparser.NewIntLiteral(fmt.Sprintf("%d", streamID)))
}
var tuple sqlparser.ValTuple = vals
expr = &sqlparser.ComparisonExpr{
Operator: sqlparser.InOp,
Left: &sqlparser.ColName{
Name: sqlparser.NewIdentifierCI("vrepl_id"),
},
Right: tuple,
}
}
switch where {
case nil:
targetWhere.Expr = expr
default:
targetWhere.Expr = &sqlparser.AndExpr{
Left: expr,
Right: where.Expr,
}
}
sel.Where = targetWhere
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("%v", sel)
queriesByTarget[target] = buf.ParsedQuery()
}
return &PerTargetQueryPlan{
ParsedQueries: queriesByTarget,
tmc: planner.tmc,
}, nil
}
func addDefaultWheres(planner QueryPlanner, where *sqlparser.Where) *sqlparser.Where {
cols := extractWhereComparisonColumns(where)
params := planner.QueryParams()
hasDBNameCol := false
hasWorkflowCol := false
for _, col := range cols {
switch col {
case params.DBNameColumn:
hasDBNameCol = true
case params.WorkflowColumn:
hasWorkflowCol = true
}
}
newWhere := where
if !hasDBNameCol {
expr := &sqlparser.ComparisonExpr{
Left: &sqlparser.ColName{
Name: sqlparser.NewIdentifierCI(params.DBNameColumn),
},
Operator: sqlparser.EqualOp,
Right: sqlparser.NewStrLiteral(params.DBName),
}
switch newWhere {
case nil:
newWhere = &sqlparser.Where{
Type: sqlparser.WhereClause,
Expr: expr,
}
default:
newWhere.Expr = &sqlparser.AndExpr{
Left: newWhere.Expr,
Right: expr,
}
}
}
if !hasWorkflowCol && params.Workflow != "" {
expr := &sqlparser.ComparisonExpr{
Left: &sqlparser.ColName{
Name: sqlparser.NewIdentifierCI(params.WorkflowColumn),
},
Operator: sqlparser.EqualOp,
Right: sqlparser.NewStrLiteral(params.Workflow),
}
newWhere.Expr = &sqlparser.AndExpr{
Left: newWhere.Expr,
Right: expr,
}
}
return newWhere
}
// extractWhereComparisonColumns extracts the column names used in AND-ed
// comparison expressions in a where clause, given the following assumptions:
// - (1) The column name is always the left-hand side of the comparison.
// - (2) There are no compound expressions within the where clause involving OR.
func extractWhereComparisonColumns(where *sqlparser.Where) []string {
if where == nil {
return nil
}
exprs := sqlparser.SplitAndExpression(nil, where.Expr)
cols := make([]string, 0, len(exprs))
for _, expr := range exprs {
switch expr := expr.(type) {
case *sqlparser.ComparisonExpr:
if qualifiedName, ok := expr.Left.(*sqlparser.ColName); ok {
cols = append(cols, qualifiedName.Name.String())
}
}
}
return cols
}