forked from dolthub/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dml.go
513 lines (471 loc) · 13 KB
/
dml.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Copyright 2014, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package planbuilder
import (
"errors"
"fmt"
"strconv"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/vt/schema"
"github.com/youtube/vitess/go/vt/sqlparser"
)
func analyzeUpdate(upd *sqlparser.Update, getTable TableGetter) (plan *ExecPlan, err error) {
plan = &ExecPlan{
PlanId: PLAN_PASS_DML,
FullQuery: GenerateFullQuery(upd),
}
tableName := sqlparser.GetTableName(upd.Table)
if tableName == "" {
plan.Reason = REASON_TABLE
return plan, nil
}
tableInfo, err := plan.setTableInfo(tableName, getTable)
if err != nil {
return nil, err
}
if len(tableInfo.Indexes) == 0 || tableInfo.Indexes[0].Name != "PRIMARY" {
log.Warningf("no primary key for table %s", tableName)
plan.Reason = REASON_TABLE_NOINDEX
return plan, nil
}
plan.SecondaryPKValues, err = analyzeUpdateExpressions(upd.Exprs, tableInfo.Indexes[0])
if err != nil {
if err == ErrTooComplex {
plan.Reason = REASON_PK_CHANGE
return plan, nil
}
return nil, err
}
plan.OuterQuery = GenerateUpdateOuterQuery(upd)
if conditions := analyzeWhere(upd.Where); conditions != nil {
pkValues, err := getPKValues(conditions, tableInfo.Indexes[0])
if err != nil {
return nil, err
}
if pkValues != nil {
plan.PlanId = PLAN_DML_PK
plan.PKValues = pkValues
return plan, nil
}
}
plan.PlanId = PLAN_DML_SUBQUERY
plan.Subquery = GenerateUpdateSubquery(upd, tableInfo)
return plan, nil
}
func analyzeDelete(del *sqlparser.Delete, getTable TableGetter) (plan *ExecPlan, err error) {
plan = &ExecPlan{
PlanId: PLAN_PASS_DML,
FullQuery: GenerateFullQuery(del),
}
tableName := sqlparser.GetTableName(del.Table)
if tableName == "" {
plan.Reason = REASON_TABLE
return plan, nil
}
tableInfo, err := plan.setTableInfo(tableName, getTable)
if err != nil {
return nil, err
}
if len(tableInfo.Indexes) == 0 || tableInfo.Indexes[0].Name != "PRIMARY" {
log.Warningf("no primary key for table %s", tableName)
plan.Reason = REASON_TABLE_NOINDEX
return plan, nil
}
plan.OuterQuery = GenerateDeleteOuterQuery(del)
if conditions := analyzeWhere(del.Where); conditions != nil {
pkValues, err := getPKValues(conditions, tableInfo.Indexes[0])
if err != nil {
return nil, err
}
if pkValues != nil {
plan.PlanId = PLAN_DML_PK
plan.PKValues = pkValues
return plan, nil
}
}
plan.PlanId = PLAN_DML_SUBQUERY
plan.Subquery = GenerateDeleteSubquery(del, tableInfo)
return plan, nil
}
func analyzeSet(set *sqlparser.Set) (plan *ExecPlan) {
plan = &ExecPlan{
PlanId: PLAN_SET,
FullQuery: GenerateFullQuery(set),
}
if len(set.Exprs) > 1 { // Multiple set values
return plan
}
updateExpr := set.Exprs[0]
plan.SetKey = string(updateExpr.Name.Name)
numExpr, ok := updateExpr.Expr.(sqlparser.NumVal)
if !ok {
return plan
}
val := string(numExpr)
if ival, err := strconv.ParseInt(val, 0, 64); err == nil {
plan.SetValue = ival
} else if fval, err := strconv.ParseFloat(val, 64); err == nil {
plan.SetValue = fval
}
return plan
}
func analyzeUpdateExpressions(exprs sqlparser.UpdateExprs, pkIndex *schema.Index) (pkValues []interface{}, err error) {
for _, expr := range exprs {
index := pkIndex.FindColumn(sqlparser.GetColName(expr.Name))
if index == -1 {
continue
}
if !sqlparser.IsValue(expr.Expr) {
log.Warningf("expression is too complex %v", expr)
return nil, ErrTooComplex
}
if pkValues == nil {
pkValues = make([]interface{}, len(pkIndex.Columns))
}
var err error
pkValues[index], err = sqlparser.AsInterface(expr.Expr)
if err != nil {
return nil, err
}
}
return pkValues, nil
}
func analyzeSelect(sel *sqlparser.Select, getTable TableGetter) (plan *ExecPlan, err error) {
// Default plan
plan = &ExecPlan{
PlanId: PLAN_PASS_SELECT,
FieldQuery: GenerateFieldQuery(sel),
FullQuery: GenerateSelectLimitQuery(sel),
}
// from
tableName, hasHints := analyzeFrom(sel.From)
if tableName == "" {
plan.Reason = REASON_TABLE
return plan, nil
}
tableInfo, err := plan.setTableInfo(tableName, getTable)
if err != nil {
return nil, err
}
// There are bind variables in the SELECT list
if plan.FieldQuery == nil {
plan.Reason = REASON_SELECT_LIST
return plan, nil
}
if sel.Distinct != "" || sel.GroupBy != nil || sel.Having != nil {
plan.Reason = REASON_SELECT
return plan, nil
}
// Don't improve the plan if the select is locking the row
if sel.Lock != "" {
plan.Reason = REASON_LOCK
return plan, nil
}
// Further improvements possible only if table is row-cached
if tableInfo.CacheType == schema.CACHE_NONE || tableInfo.CacheType == schema.CACHE_W {
plan.Reason = REASON_NOCACHE
return plan, nil
}
// Select expressions
selects, err := analyzeSelectExprs(sel.SelectExprs, tableInfo)
if err != nil {
return nil, err
}
if selects == nil {
plan.Reason = REASON_SELECT_LIST
return plan, nil
}
plan.ColumnNumbers = selects
// where
conditions := analyzeWhere(sel.Where)
if conditions == nil {
plan.Reason = REASON_WHERE
return plan, nil
}
// order
if sel.OrderBy != nil {
plan.Reason = REASON_ORDER
return plan, nil
}
// This check should never fail because we only cache tables with primary keys.
if len(tableInfo.Indexes) == 0 || tableInfo.Indexes[0].Name != "PRIMARY" {
panic("unexpected")
}
pkValues, err := getPKValues(conditions, tableInfo.Indexes[0])
if err != nil {
return nil, err
}
if pkValues != nil {
plan.IndexUsed = "PRIMARY"
offset, rowcount, err := sel.Limit.Limits()
if err != nil {
return nil, err
}
if offset != nil {
plan.Reason = REASON_LIMIT
return plan, nil
}
plan.Limit = rowcount
plan.PlanId = PLAN_PK_IN
plan.OuterQuery = GenerateSelectOuterQuery(sel, tableInfo)
plan.PKValues = pkValues
return plan, nil
}
// TODO: Analyze hints to improve plan.
if hasHints {
plan.Reason = REASON_HAS_HINTS
return plan, nil
}
indexUsed := getIndexMatch(conditions, tableInfo.Indexes)
if indexUsed == nil {
plan.Reason = REASON_NOINDEX_MATCH
return plan, nil
}
plan.IndexUsed = indexUsed.Name
if plan.IndexUsed == "PRIMARY" {
plan.Reason = REASON_PKINDEX
return plan, nil
}
var missing bool
for _, cnum := range selects {
if indexUsed.FindDataColumn(tableInfo.Columns[cnum].Name) != -1 {
continue
}
missing = true
break
}
if !missing {
plan.Reason = REASON_COVERING
return plan, nil
}
plan.PlanId = PLAN_SELECT_SUBQUERY
plan.OuterQuery = GenerateSelectOuterQuery(sel, tableInfo)
plan.Subquery = GenerateSelectSubquery(sel, tableInfo, plan.IndexUsed)
return plan, nil
}
func analyzeSelectExprs(exprs sqlparser.SelectExprs, table *schema.Table) (selects []int, err error) {
selects = make([]int, 0, len(exprs))
for _, expr := range exprs {
switch expr := expr.(type) {
case *sqlparser.StarExpr:
// Append all columns.
for colIndex := range table.Columns {
selects = append(selects, colIndex)
}
case *sqlparser.NonStarExpr:
name := sqlparser.GetColName(expr.Expr)
if name == "" {
// Not a simple column name.
return nil, nil
}
colIndex := table.FindColumn(name)
if colIndex == -1 {
return nil, fmt.Errorf("column %s not found in table %s", name, table.Name)
}
selects = append(selects, colIndex)
default:
panic("unreachable")
}
}
return selects, nil
}
func analyzeFrom(tableExprs sqlparser.TableExprs) (tablename string, hasHints bool) {
if len(tableExprs) > 1 {
return "", false
}
node, ok := tableExprs[0].(*sqlparser.AliasedTableExpr)
if !ok {
return "", false
}
return sqlparser.GetTableName(node.Expr), node.Hints != nil
}
func analyzeWhere(node *sqlparser.Where) (conditions []sqlparser.BoolExpr) {
if node == nil {
return nil
}
return analyzeBoolean(node.Expr)
}
func analyzeBoolean(node sqlparser.BoolExpr) (conditions []sqlparser.BoolExpr) {
switch node := node.(type) {
case *sqlparser.AndExpr:
left := analyzeBoolean(node.Left)
right := analyzeBoolean(node.Right)
if left == nil || right == nil {
return nil
}
if sqlparser.HasINClause(left) && sqlparser.HasINClause(right) {
return nil
}
return append(left, right...)
case *sqlparser.ParenBoolExpr:
return analyzeBoolean(node.Expr)
case *sqlparser.ComparisonExpr:
switch {
case sqlparser.StringIn(
node.Operator,
sqlparser.AST_EQ,
sqlparser.AST_LT,
sqlparser.AST_GT,
sqlparser.AST_LE,
sqlparser.AST_GE,
sqlparser.AST_NSE,
sqlparser.AST_LIKE):
if sqlparser.IsColName(node.Left) && sqlparser.IsValue(node.Right) {
return []sqlparser.BoolExpr{node}
}
case node.Operator == sqlparser.AST_IN:
if sqlparser.IsColName(node.Left) && sqlparser.IsSimpleTuple(node.Right) {
return []sqlparser.BoolExpr{node}
}
}
case *sqlparser.RangeCond:
if node.Operator != sqlparser.AST_BETWEEN {
return nil
}
if sqlparser.IsColName(node.Left) && sqlparser.IsValue(node.From) && sqlparser.IsValue(node.To) {
return []sqlparser.BoolExpr{node}
}
}
return nil
}
func analyzeInsert(ins *sqlparser.Insert, getTable TableGetter) (plan *ExecPlan, err error) {
plan = &ExecPlan{
PlanId: PLAN_PASS_DML,
FullQuery: GenerateFullQuery(ins),
}
tableName := sqlparser.GetTableName(ins.Table)
if tableName == "" {
plan.Reason = REASON_TABLE
return plan, nil
}
tableInfo, err := plan.setTableInfo(tableName, getTable)
if err != nil {
return nil, err
}
if len(tableInfo.Indexes) == 0 || tableInfo.Indexes[0].Name != "PRIMARY" {
log.Warningf("no primary key for table %s", tableName)
plan.Reason = REASON_TABLE_NOINDEX
return plan, nil
}
pkColumnNumbers := getInsertPKColumns(ins.Columns, tableInfo)
if sel, ok := ins.Rows.(sqlparser.SelectStatement); ok {
if ins.OnDup != nil {
// Upserts not allowed for subqueries.
// http://bugs.mysql.com/bug.php?id=58637
plan.Reason = REASON_UPSERT
return plan, nil
}
plan.PlanId = PLAN_INSERT_SUBQUERY
plan.OuterQuery = GenerateInsertOuterQuery(ins)
plan.Subquery = GenerateSelectLimitQuery(sel)
if len(ins.Columns) != 0 {
plan.ColumnNumbers, err = analyzeSelectExprs(sqlparser.SelectExprs(ins.Columns), tableInfo)
if err != nil {
return nil, err
}
} else {
// StarExpr node will expand into all columns
n := sqlparser.SelectExprs{&sqlparser.StarExpr{}}
plan.ColumnNumbers, err = analyzeSelectExprs(n, tableInfo)
if err != nil {
return nil, err
}
}
plan.SubqueryPKColumns = pkColumnNumbers
return plan, nil
}
// If it's not a sqlparser.SelectStatement, it's Values.
rowList := ins.Rows.(sqlparser.Values)
pkValues, err := getInsertPKValues(pkColumnNumbers, rowList, tableInfo)
if err != nil {
return nil, err
}
if pkValues == nil {
plan.Reason = REASON_COMPLEX_EXPR
return plan, nil
}
plan.PKValues = pkValues
if ins.OnDup == nil {
plan.PlanId = PLAN_INSERT_PK
plan.OuterQuery = sqlparser.GenerateParsedQuery(ins)
return plan, nil
}
if len(rowList) > 1 {
// Upsert supported only for single row inserts.
plan.Reason = REASON_UPSERT
return plan, nil
}
plan.SecondaryPKValues, err = analyzeUpdateExpressions(sqlparser.UpdateExprs(ins.OnDup), tableInfo.Indexes[0])
if err != nil {
if err == ErrTooComplex {
plan.Reason = REASON_PK_CHANGE
return plan, nil
}
return nil, err
}
plan.PlanId = PLAN_UPSERT_PK
newins := *ins
newins.Ignore = ""
newins.OnDup = nil
plan.OuterQuery = sqlparser.GenerateParsedQuery(&newins)
upd := &sqlparser.Update{
Comments: ins.Comments,
Table: ins.Table,
Exprs: sqlparser.UpdateExprs(ins.OnDup),
}
plan.UpsertQuery = GenerateUpdateOuterQuery(upd)
return plan, nil
}
func getInsertPKColumns(columns sqlparser.Columns, tableInfo *schema.Table) (pkColumnNumbers []int) {
if len(columns) == 0 {
return tableInfo.PKColumns
}
pkIndex := tableInfo.Indexes[0]
pkColumnNumbers = make([]int, len(pkIndex.Columns))
for i := range pkColumnNumbers {
pkColumnNumbers[i] = -1
}
for i, column := range columns {
index := pkIndex.FindColumn(sqlparser.GetColName(column.(*sqlparser.NonStarExpr).Expr))
if index == -1 {
continue
}
pkColumnNumbers[index] = i
}
return pkColumnNumbers
}
func getInsertPKValues(pkColumnNumbers []int, rowList sqlparser.Values, tableInfo *schema.Table) (pkValues []interface{}, err error) {
pkValues = make([]interface{}, len(pkColumnNumbers))
for index, columnNumber := range pkColumnNumbers {
if columnNumber == -1 {
pkValues[index] = tableInfo.GetPKColumn(index).Default
continue
}
values := make([]interface{}, len(rowList))
for j := 0; j < len(rowList); j++ {
if _, ok := rowList[j].(*sqlparser.Subquery); ok {
return nil, errors.New("row subquery not supported for inserts")
}
row := rowList[j].(sqlparser.ValTuple)
if columnNumber >= len(row) {
return nil, errors.New("column count doesn't match value count")
}
node := row[columnNumber]
if !sqlparser.IsValue(node) {
return nil, nil
}
var err error
values[j], err = sqlparser.AsInterface(node)
if err != nil {
return nil, err
}
}
if len(values) == 1 {
pkValues[index] = values[0]
} else {
pkValues[index] = values
}
}
return pkValues, nil
}