forked from src-d/go-mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimization_rules.go
449 lines (369 loc) · 10.4 KB
/
optimization_rules.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
package analyzer
import (
"gopkg.in/src-d/go-errors.v1"
"gopkg.in/src-d/go-mysql-server.v0/sql"
"gopkg.in/src-d/go-mysql-server.v0/sql/expression"
"gopkg.in/src-d/go-mysql-server.v0/sql/plan"
)
func eraseProjection(ctx *sql.Context, a *Analyzer, node sql.Node) (sql.Node, error) {
span, _ := ctx.Span("erase_projection")
defer span.Finish()
if !node.Resolved() {
return node, nil
}
a.Log("erase projection, node of type: %T", node)
return node.TransformUp(func(node sql.Node) (sql.Node, error) {
project, ok := node.(*plan.Project)
if ok && project.Schema().Equals(project.Child.Schema()) {
a.Log("project erased")
return project.Child, nil
}
return node, nil
})
}
func optimizeDistinct(ctx *sql.Context, a *Analyzer, node sql.Node) (sql.Node, error) {
span, _ := ctx.Span("optimize_distinct")
defer span.Finish()
a.Log("optimize distinct, node of type: %T", node)
if node, ok := node.(*plan.Distinct); ok {
var isSorted bool
_, _ = node.TransformUp(func(node sql.Node) (sql.Node, error) {
a.Log("checking for optimization in node of type: %T", node)
if _, ok := node.(*plan.Sort); ok {
isSorted = true
}
return node, nil
})
if isSorted {
a.Log("distinct optimized for ordered output")
return plan.NewOrderedDistinct(node.Child), nil
}
}
return node, nil
}
var errInvalidNodeType = errors.NewKind("reorder projection: invalid node of type: %T")
func reorderProjection(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, ctx := ctx.Span("reorder_projection")
defer span.Finish()
if n.Resolved() {
return n, nil
}
a.Log("reorder projection, node of type: %T", n)
// Then we transform the projection
return n.TransformUp(func(node sql.Node) (sql.Node, error) {
project, ok := node.(*plan.Project)
// When we transform the projection, the children will always be
// unresolved in the case we want to fix, as the reorder happens just
// so some columns can be resolved.
// For that, we need to account for NaturalJoin, whose schema can't be
// obtained until it's resolved and ignore the projection for the
// moment until the resolve_natural_joins has finished resolving the
// node and we can tackle it in the next iteration.
// Without this check, it would cause a panic, because NaturalJoin's
// schema method is just a placeholder that should not be called.
if !ok || hasNaturalJoin(project.Child) {
return node, nil
}
// We must find all columns that may need to be moved inside the
// projection.
var newColumns = make(map[string]sql.Expression)
for _, col := range project.Projections {
alias, ok := col.(*expression.Alias)
if ok {
newColumns[alias.Name()] = col
}
}
// And add projection nodes where needed in the child tree.
var didNeedReorder bool
child, err := project.Child.TransformUp(func(node sql.Node) (sql.Node, error) {
var requiredColumns []string
switch node := node.(type) {
case *plan.Sort, *plan.Filter:
for _, expr := range node.(sql.Expressioner).Expressions() {
expression.Inspect(expr, func(e sql.Expression) bool {
if e != nil && e.Resolved() {
return true
}
uc, ok := e.(column)
if ok && uc.Table() == "" {
if _, ok := newColumns[uc.Name()]; ok {
requiredColumns = append(requiredColumns, uc.Name())
}
}
return true
})
}
default:
return node, nil
}
if len(requiredColumns) == 0 {
return node, nil
}
didNeedReorder = true
// Only add the required columns for that node in the projection.
child := node.Children()[0]
schema := child.Schema()
var projections = make([]sql.Expression, 0, len(schema)+len(requiredColumns))
for i, col := range schema {
projections = append(projections, expression.NewGetFieldWithTable(
i, col.Type, col.Source, col.Name, col.Nullable,
))
}
for _, col := range requiredColumns {
if c, ok := newColumns[col]; ok {
projections = append(projections, c)
delete(newColumns, col)
}
}
child = plan.NewProject(projections, child)
switch node := node.(type) {
case *plan.Filter:
return plan.NewFilter(node.Expression, child), nil
case *plan.Sort:
return plan.NewSort(node.SortFields, child), nil
default:
return nil, errInvalidNodeType.New(node)
}
})
if err != nil {
return nil, err
}
if !didNeedReorder {
return project, nil
}
child, err = resolveColumns(ctx, a, child)
if err != nil {
return nil, err
}
childSchema := child.Schema()
// Finally, replace the columns we moved with GetFields since they
// have already been projected.
var projections = make([]sql.Expression, len(project.Projections))
for i, p := range project.Projections {
if alias, ok := p.(*expression.Alias); ok {
var found bool
for idx, col := range childSchema {
if col.Name == alias.Name() {
projections[i] = expression.NewGetField(
idx, col.Type, col.Name, col.Nullable,
)
found = true
break
}
}
if !found {
projections[i] = p
}
} else {
projections[i] = p
}
}
return plan.NewProject(projections, child), nil
})
}
func moveJoinConditionsToFilter(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
if !n.Resolved() {
a.Log("node is not resolved, skip moving join conditions to filter")
return n, nil
}
a.Log("moving join conditions to filter, node of type: %T", n)
return n.TransformUp(func(n sql.Node) (sql.Node, error) {
join, ok := n.(*plan.InnerJoin)
if !ok {
return n, nil
}
leftSources := nodeSources(join.Left)
rightSources := nodeSources(join.Right)
var leftFilters, rightFilters, condFilters []sql.Expression
for _, e := range splitExpression(join.Cond) {
sources := expressionSources(e)
canMoveLeft := containsSources(leftSources, sources)
if canMoveLeft {
leftFilters = append(leftFilters, e)
}
canMoveRight := containsSources(rightSources, sources)
if canMoveRight {
rightFilters = append(rightFilters, e)
}
if !canMoveLeft && !canMoveRight {
condFilters = append(condFilters, e)
}
}
var left, right sql.Node = join.Left, join.Right
if len(leftFilters) > 0 {
leftFilters, err := fixFieldIndexes(left.Schema(), expression.JoinAnd(leftFilters...))
if err != nil {
return nil, err
}
left = plan.NewFilter(leftFilters, left)
}
if len(rightFilters) > 0 {
rightFilters, err := fixFieldIndexes(right.Schema(), expression.JoinAnd(rightFilters...))
if err != nil {
return nil, err
}
right = plan.NewFilter(rightFilters, right)
}
if len(condFilters) > 0 {
return plan.NewInnerJoin(
left, right,
expression.JoinAnd(condFilters...),
), nil
}
// if there are no cond filters left we can just convert it to a cross join
return plan.NewCrossJoin(left, right), nil
})
}
func removeUnnecessaryConverts(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, _ := ctx.Span("remove_unnecessary_converts")
defer span.Finish()
if !n.Resolved() {
return n, nil
}
a.Log("removing unnecessary converts, node of type: %T", n)
return n.TransformExpressionsUp(func(e sql.Expression) (sql.Expression, error) {
if c, ok := e.(*expression.Convert); ok && c.Child.Type() == c.Type() {
return c.Child, nil
}
return e, nil
})
}
// containsSources checks that all `needle` sources are contained inside `haystack`.
func containsSources(haystack, needle []string) bool {
for _, s := range needle {
var found bool
for _, s2 := range haystack {
if s2 == s {
found = true
break
}
}
if !found {
return false
}
}
return true
}
func nodeSources(node sql.Node) []string {
var sources = make(map[string]struct{})
var result []string
for _, col := range node.Schema() {
if _, ok := sources[col.Source]; !ok {
sources[col.Source] = struct{}{}
result = append(result, col.Source)
}
}
return result
}
func expressionSources(expr sql.Expression) []string {
var sources = make(map[string]struct{})
var result []string
expression.Inspect(expr, func(expr sql.Expression) bool {
f, ok := expr.(*expression.GetField)
if ok {
if _, ok := sources[f.Table()]; !ok {
sources[f.Table()] = struct{}{}
result = append(result, f.Table())
}
}
return true
})
return result
}
func evalFilter(ctx *sql.Context, a *Analyzer, node sql.Node) (sql.Node, error) {
if !node.Resolved() {
return node, nil
}
a.Log("evaluating filters, node of type: %T", node)
return node.TransformUp(func(node sql.Node) (sql.Node, error) {
filter, ok := node.(*plan.Filter)
if !ok {
return node, nil
}
e, err := filter.Expression.TransformUp(func(e sql.Expression) (sql.Expression, error) {
switch e := e.(type) {
case *expression.Or:
if isTrue(e.Left) {
return e.Left, nil
}
if isTrue(e.Right) {
return e.Right, nil
}
if isFalse(e.Left) {
return e.Right, nil
}
if isFalse(e.Right) {
return e.Left, nil
}
return e, nil
case *expression.And:
if isFalse(e.Left) {
return e.Left, nil
}
if isFalse(e.Right) {
return e.Right, nil
}
if isTrue(e.Left) {
return e.Right, nil
}
if isTrue(e.Right) {
return e.Left, nil
}
return e, nil
default:
if !isEvaluable(e) {
return e, nil
}
if _, ok := e.(*expression.Literal); ok {
return e, nil
}
val, err := e.Eval(ctx, nil)
if err != nil {
return nil, err
}
val, err = sql.Boolean.Convert(val)
if err != nil {
// don't make it fail because of this, just return the
// original expression
return e, nil
}
return expression.NewLiteral(val.(bool), sql.Boolean), nil
}
})
if err != nil {
return nil, err
}
if isFalse(e) {
return plan.EmptyTable, nil
}
if isTrue(e) {
return filter.Child, nil
}
return plan.NewFilter(e, filter.Child), nil
})
}
func isFalse(e sql.Expression) bool {
lit, ok := e.(*expression.Literal)
return ok &&
lit.Type() == sql.Boolean &&
!lit.Value().(bool)
}
func isTrue(e sql.Expression) bool {
lit, ok := e.(*expression.Literal)
return ok &&
lit.Type() == sql.Boolean &&
lit.Value().(bool)
}
// hasNaturalJoin checks whether there is a natural join at some point in the
// given node and its children.
func hasNaturalJoin(node sql.Node) bool {
var found bool
plan.Inspect(node, func(node sql.Node) bool {
if _, ok := node.(*plan.NaturalJoin); ok {
found = true
return false
}
return true
})
return found
}