-
-
Notifications
You must be signed in to change notification settings - Fork 195
/
indexed_joins.go
1387 lines (1258 loc) · 40.2 KB
/
indexed_joins.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020-2021 Dolthub, Inc.
//
// 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 analyzer
import (
"errors"
"fmt"
"strings"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/expression"
"github.com/dolthub/go-mysql-server/sql/memo"
"github.com/dolthub/go-mysql-server/sql/plan"
"github.com/dolthub/go-mysql-server/sql/transform"
"github.com/dolthub/go-mysql-server/sql/types"
)
// optimizeJoins finds an optimal table ordering and access plan
// for the tables in the query.
func optimizeJoins(ctx *sql.Context, a *Analyzer, n sql.Node, scope *plan.Scope, sel RuleSelector) (sql.Node, transform.TreeIdentity, error) {
span, ctx := ctx.Span("construct_join_plan")
defer span.End()
if !n.Resolved() {
return n, transform.SameTree, nil
}
if plan.IsNoRowNode(n) {
return n, transform.SameTree, nil
}
_, isUpdate := n.(*plan.Update)
ret, same, err := inOrderReplanJoin(ctx, a, scope, nil, n, isUpdate)
if err != nil {
return n, transform.SameTree, err
}
if same {
// try index plans only
return costedIndexScans(ctx, a, n)
}
return ret, transform.NewTree, nil
}
// inOrderReplanJoin replans the first join node found
func inOrderReplanJoin(ctx *sql.Context, a *Analyzer, scope *plan.Scope, sch sql.Schema, n sql.Node, isUpdate bool) (sql.Node, transform.TreeIdentity, error) {
if _, ok := n.(sql.OpaqueNode); ok {
return n, transform.SameTree, nil
}
children := n.Children()
var newChildren []sql.Node
allSame := transform.SameTree
j, ok := n.(*plan.JoinNode)
if !ok {
for i := range children {
newChild, same, err := inOrderReplanJoin(ctx, a, scope, sch, children[i], isUpdate)
if err != nil {
return n, transform.SameTree, err
}
if !same {
if len(newChildren) == 0 {
newChildren = make([]sql.Node, len(children))
copy(newChildren, children)
}
newChildren[i] = newChild
allSame = transform.NewTree
}
}
if allSame {
return n, transform.SameTree, nil
}
ret, err := n.WithChildren(newChildren...)
if err != nil {
return nil, transform.SameTree, nil
}
return ret, transform.NewTree, err
}
scope.SetJoin(true)
scope.SetLateralJoin(j.Op.IsLateral())
ret, err := replanJoin(ctx, j, a, scope)
if err != nil {
return nil, transform.SameTree, fmt.Errorf("failed to replan join: %w", err)
}
if isUpdate {
// we pass schema separately because individual nodes do not capture
// left join nullability
ret = plan.NewProject(recSchemaToGetFields(n, n.Schema()), ret)
}
return ret, transform.NewTree, nil
}
// recSchemaToGetFields creates a set of projection get fields for a node
// considering column ids and left join nullability.
func recSchemaToGetFields(n sql.Node, sch sql.Schema) []sql.Expression {
if len(n.Schema()) != len(sch) {
// Projector nodes can return more or fewer columns than child.
// In this case we will return the subset of get fields with column
// ids from the child. This does not matter currently for the context
// this function is used.
// todo: all projector node columns should have column ids
sch = n.Schema()
}
switch n := n.(type) {
case *plan.JoinNode:
switch {
case n.Op.IsPartial():
return recSchemaToGetFields(n.Left(), sch[:len(n.Schema())])
default:
l := recSchemaToGetFields(n.Left(), sch[:len(n.Left().Schema())])
r := recSchemaToGetFields(n.Right(), sch[len(n.Left().Schema()):])
return append(l, r...)
}
case plan.TableIdNode:
return expression.SchemaToGetFields(sch, n.Columns())
default:
if plan.IsUnary(n) {
return recSchemaToGetFields(n.Children()[0], sch)
}
return nil
}
}
func replanJoin(ctx *sql.Context, n *plan.JoinNode, a *Analyzer, scope *plan.Scope) (ret sql.Node, err error) {
m := memo.NewMemo(ctx, a.Catalog, scope, len(scope.Schema()), a.Coster)
defer func() {
if r := recover(); r != nil {
switch r := r.(type) {
case memo.MemoErr:
err = r.Err
if errors.Is(err, memo.ErrUnsupportedReorderNode) {
err = nil
ret = n
}
default:
panic(r)
}
}
}()
j := memo.NewJoinOrderBuilder(m)
j.ReorderJoin(n)
err = addIndexScans(m)
if err != nil {
return nil, err
}
err = convertSemiToInnerJoin(m)
if err != nil {
return nil, err
}
err = convertAntiToLeftJoin(m)
if err != nil {
return nil, err
}
err = addRightSemiJoins(m)
if err != nil {
return nil, err
}
err = addLookupJoins(m)
if err != nil {
return nil, err
}
err = addMergeJoins(m)
if err != nil {
return nil, err
}
memo.CardMemoGroups(m.Root())
err = addCrossHashJoins(m)
if err != nil {
return nil, err
}
err = addHashJoins(m)
if err != nil {
return nil, err
}
err = addRangeHeapJoin(m)
if err != nil {
return nil, err
}
hints := memo.ExtractJoinHint(n)
for _, h := range hints {
// this should probably happen earlier, but the root is not
// populated before reordering
m.ApplyHint(h)
}
err = m.OptimizeRoot()
if err != nil {
return nil, err
}
if a.Verbose && a.Debug {
a.Log(m.String())
}
return m.BestRootPlan(ctx)
}
// addLookupJoins prefixes memo join group expressions with indexed join
// alternatives to join plans added by joinOrderBuilder. We can assume that a
// join with a non-nil join filter is not degenerate, and we can apply indexed
// joins for any join plan where the right child is i) an indexable relation,
// ii) with an index that matches a prefix of the indexable relation's free
// attributes in the join filter. Costing is responsible for choosing the most
// appropriate execution plan among options added to an expression group.
func addLookupJoins(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
var right *memo.ExprGroup
var join *memo.JoinBase
// ANTI_JOIN is not a valid lookup acceptor. We need to tell the
// difference between when the RHS relation is non-empty (return no
// rows), vs there are no lookup matches (return rows).
switch e := e.(type) {
case *memo.InnerJoin:
right = e.Right
join = e.JoinBase
case *memo.LeftJoin:
right = e.Right
join = e.JoinBase
//TODO fullouterjoin
case *memo.SemiJoin:
right = e.Right
join = e.JoinBase
default:
return nil
}
if len(join.Filter) == 0 {
return nil
}
tableId, indexes, extraFilters := lookupCandidates(right.First, false)
var rt sql.TableNode
var aliasName string
switch n := right.RelProps.TableIdNodes()[0].(type) {
case sql.TableNode:
rt = n
case *plan.TableAlias:
var ok bool
rt, ok = n.Child.(sql.TableNode)
if !ok {
return nil
}
aliasName = n.Name()
default:
return nil
}
if or, ok := join.Filter[0].(*expression.Or); ok && len(join.Filter) == 1 {
// Special case disjoint filter. The execution plan will perform an index
// lookup for each predicate leaf in the OR tree.
// TODO: memoize equality expressions, index lookup, concat so that we
// can consider multiple index options. Otherwise the search space blows
// up.
conds := expression.SplitDisjunction(or)
var concat []*memo.IndexScan
for _, on := range conds {
filters := expression.SplitConjunction(on)
for _, idx := range indexes {
keyExprs, _, nullmask := keyExprsForIndex(tableId, idx.Cols(), append(filters, extraFilters...))
if keyExprs != nil {
ita, err := plan.NewIndexedAccessForTableNode(rt, plan.NewLookupBuilder(idx.SqlIdx(), keyExprs, nullmask))
if err != nil {
return err
}
lookup := &memo.IndexScan{
Table: ita,
Index: idx,
Alias: aliasName,
}
concat = append(concat, lookup)
break
}
}
}
if len(concat) != len(conds) {
return nil
}
m.MemoizeConcatLookupJoin(e.Group(), join.Left, join.Right, join.Op, join.Filter, concat)
return nil
}
for _, idx := range indexes {
keyExprs, matchedFilters, nullmask := keyExprsForIndex(tableId, idx.Cols(), append(join.Filter, extraFilters...))
if keyExprs == nil {
continue
}
ita, err := plan.NewIndexedAccessForTableNode(rt, plan.NewLookupBuilder(idx.SqlIdx(), keyExprs, nullmask))
if err != nil {
return err
}
lookup := &memo.IndexScan{
Table: ita,
Alias: aliasName,
Index: idx,
}
var filters []sql.Expression
for _, filter := range join.Filter {
found := false
for _, matchedFilter := range matchedFilters {
if filter == matchedFilter {
found = true
}
}
if !found {
filters = append(filters, filter)
}
}
m.MemoizeLookupJoin(e.Group(), join.Left, join.Right, join.Op, filters, lookup)
}
return nil
})
}
// keyExprsForIndex returns a list of expression groups that compute a lookup
// key into the given index. The key fields will either be equality filters
// (from ON conditions) or constants.
func keyExprsForIndex(tableId sql.TableId, idxExprs []sql.ColumnId, filters []sql.Expression) (keyExprs, matchedFilters []sql.Expression, nullmask []bool) {
for _, col := range idxExprs {
key, filter, nullable := keyForExpr(col, tableId, filters)
if key == nil {
break
}
keyExprs = append(keyExprs, key)
matchedFilters = append(matchedFilters, filter)
nullmask = append(nullmask, nullable)
}
if len(keyExprs) == 0 {
return nil, nil, nil
}
return keyExprs, matchedFilters, nullmask
}
// keyForExpr returns an equivalence or constant value to satisfy the
// lookup index expression.
func keyForExpr(targetCol sql.ColumnId, tableId sql.TableId, filters []sql.Expression) (key sql.Expression, filter sql.Expression, nullable bool) {
for _, f := range filters {
var left sql.Expression
var right sql.Expression
switch e := f.(type) {
case *expression.Equals:
left = e.Left()
right = e.Right()
case *expression.NullSafeEquals:
nullable = true
left = e.Left()
right = e.Right()
default:
}
if ref, ok := left.(*expression.GetField); ok && ref.Id() == targetCol {
key = right
} else if ref, ok := right.(*expression.GetField); ok && ref.Id() == targetCol {
key = left
} else {
continue
}
if sq, ok := key.(*plan.Subquery); ok && !sq.Correlated().Empty() {
continue
}
// expression key can be arbitrarily complex (or simple), but cannot
// reference the lookup table
if !exprRefsTable(key, tableId) {
return key, f, nullable
}
}
return nil, nil, false
}
func exprRefsTable(e sql.Expression, tableId sql.TableId) bool {
return transform.InspectExpr(e, func(e sql.Expression) bool {
gf, _ := e.(*expression.GetField)
if gf != nil {
return gf.TableId() == tableId
}
return false
})
}
// convertSemiToInnerJoin adds inner join alternatives for semi joins.
// The inner join plans can be explored (optimized) further.
// Example: semiJoin(xy ab) => project(xy) -> innerJoin(xy, distinct(ab))
// Ref section 2.1.1 of:
// https://www.researchgate.net/publication/221311318_Cost-Based_Query_Transformation_in_Oracle
// TODO: need more elegant way to extend the number of groups, interner
func convertSemiToInnerJoin(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
semi, ok := e.(*memo.SemiJoin)
if !ok {
return nil
}
rightOutTables := semi.Right.RelProps.OutputTables()
var projectExpressions []sql.Expression
var err error
for _, f := range semi.Filter {
if transform.InspectExpr(f, func(e sql.Expression) bool {
switch e := e.(type) {
case *expression.GetField:
if rightOutTables.Contains(int(e.TableId())) {
projectExpressions = append(projectExpressions, e)
}
case *expression.Literal, *expression.And, *expression.Or, *expression.Equals, *expression.Arithmetic, *expression.BindVar, expression.Tuple:
default:
return true
}
return false
}) {
return err
}
}
if len(projectExpressions) == 0 {
p := expression.NewLiteral(1, types.Int64)
projectExpressions = append(projectExpressions, p)
}
// project is a new group
rightGrp := m.MemoizeProject(nil, semi.Right, projectExpressions)
if _, ok := semi.Right.First.(*memo.Distinct); !ok {
rightGrp.RelProps.Distinct = memo.HashDistinctOp
}
// join and its commute are a new group
joinGrp := m.MemoizeInnerJoin(nil, semi.Left, rightGrp, plan.JoinTypeInner, semi.Filter)
// TODO: can't commute if right SubqueryAlias references outside scope (OuterScopeVisibility/IsLateral)
m.MemoizeInnerJoin(joinGrp, rightGrp, semi.Left, plan.JoinTypeInner, semi.Filter)
// project belongs to the original group
leftCols := semi.Left.RelProps.OutputCols()
var projections []sql.Expression
for colId, hasNext := leftCols.Next(1); hasNext; colId, hasNext = leftCols.Next(colId + 1) {
var srcNode plan.TableIdNode
for _, n := range semi.Left.RelProps.TableIdNodes() {
if n.Columns().Contains(colId) {
srcNode = n
break
}
}
if srcNode == nil {
break
return fmt.Errorf("table for column not found: %d", colId)
}
sch := srcNode.Schema()
var table sql.Table
if tw, ok := srcNode.(sql.TableNode); ok {
table = tw.UnderlyingTable()
}
if pkt, ok := table.(sql.PrimaryKeyTable); ok {
sch = pkt.PrimaryKeySchema().Schema
}
firstCol, _ := srcNode.Columns().Next(1)
idx := int(colId - firstCol)
col := sch[idx]
projections = append(projections, expression.NewGetFieldWithTable(int(colId), int(srcNode.Id()), col.Type, col.DatabaseSource, col.Source, col.Name, col.Nullable))
}
if len(projections) == 0 {
p := expression.NewLiteral(1, types.Int64)
projections = []sql.Expression{p}
}
m.MemoizeProject(e.Group(), joinGrp, projections)
return nil
})
}
// convertAntiToLeftJoin adds left join alternatives for anti join
// ANTI_JOIN(left, right) => PROJECT(left sch) -> FILTER(right attr IS NULL) -> LEFT_JOIN(left, right)
func convertAntiToLeftJoin(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
anti, ok := e.(*memo.AntiJoin)
if !ok {
return nil
}
rightOutTables := anti.Right.RelProps.OutputTables()
var projectExpressions []sql.Expression
var nullify []sql.Expression
var err error
for _, f := range anti.Filter {
if transform.InspectExpr(f, func(e sql.Expression) bool {
switch e := e.(type) {
case *expression.GetField:
if rightOutTables.Contains(int(e.TableId())) {
projectExpressions = append(projectExpressions, e)
nullify = append(nullify, e)
}
case *expression.Literal, *expression.And, *expression.Or, *expression.Equals, *expression.Arithmetic, *expression.BindVar, expression.Tuple:
default:
return true
}
return false
}) {
return err
}
}
if len(projectExpressions) == 0 {
p := expression.NewLiteral(1, types.Int64)
projectExpressions = append(projectExpressions, p)
gf := expression.NewGetField(0, types.Int64, "1", true)
nullify = append(nullify, gf)
}
// project is a new group
rightGrp := m.MemoizeProject(nil, anti.Right, projectExpressions)
// join is a new group
joinGrp := m.MemoizeLeftJoin(nil, anti.Left, rightGrp, plan.JoinTypeLeftOuterExcludeNulls, anti.Filter)
// drop null projected columns on right table
nullFilters := make([]sql.Expression, len(nullify))
for i, e := range nullify {
nullFilters[i] = expression.NewIsNull(e)
}
filterGrp := m.MemoizeFilter(nil, joinGrp, nullFilters)
// project belongs to the original group
leftCols := anti.Left.RelProps.OutputCols()
var projections []sql.Expression
for colId, hasNext := leftCols.Next(1); hasNext; colId, hasNext = leftCols.Next(colId + 1) {
// we have ids and need to get the table back?
// search in tables
var srcNode plan.TableIdNode
for _, n := range anti.Left.RelProps.TableIdNodes() {
if n.Columns().Contains(colId) {
srcNode = n
break
}
}
if srcNode == nil {
break
}
sch := srcNode.Schema()
var table sql.Table
if tw, ok := srcNode.(sql.TableNode); ok {
table = tw.UnderlyingTable()
}
if pkt, ok := table.(sql.PrimaryKeyTable); ok {
sch = pkt.PrimaryKeySchema().Schema
}
firstCol, _ := srcNode.Columns().Next(1)
idx := int(colId - firstCol)
col := sch[idx]
projections = append(projections, expression.NewGetFieldWithTable(int(colId), int(srcNode.Id()), col.Type, col.DatabaseSource, col.Source, col.Name, col.Nullable))
}
if len(projections) == 0 {
p := expression.NewLiteral(1, types.Int64)
projections = []sql.Expression{p}
}
m.MemoizeProject(e.Group(), filterGrp, projections)
return nil
})
}
// addRightSemiJoins allows for a reversed semiJoin operator when
// the join attributes of the left side are provably unique.
func addRightSemiJoins(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
semi, ok := e.(*memo.SemiJoin)
if !ok {
return nil
}
if len(semi.Filter) == 0 {
return nil
}
tableId, indexes, filters := lookupCandidates(semi.Left.First, false)
leftTab := semi.Left.RelProps.TableIdNodes()[0]
var aliasName string
var leftRt sql.TableNode
switch n := leftTab.(type) {
case *plan.TableAlias:
aliasName = n.Name()
leftRt = n.Child.(sql.TableNode)
case sql.TableNode:
leftRt = n
}
rightOutTables := semi.Right.RelProps.OutputTables()
var projectExpressions []sql.Expression
var err error
for _, f := range semi.Filter {
if transform.InspectExpr(f, func(e sql.Expression) bool {
switch e := e.(type) {
case *expression.GetField:
if rightOutTables.Contains(int(e.TableId())) {
projectExpressions = append(projectExpressions, e)
}
case *expression.Literal, *expression.And, *expression.Or, *expression.Equals, *expression.Arithmetic, *expression.BindVar:
default:
return true
}
return false
}) {
return err
}
}
for _, idx := range indexes {
if !semi.Group().RelProps.FuncDeps().ColsAreStrictKey(idx.ColSet()) {
continue
}
keyExprs, _, nullmask := keyExprsForIndex(tableId, idx.Cols(), append(semi.Filter, filters...))
if keyExprs == nil {
continue
}
rGroup := m.MemoizeProject(nil, semi.Right, projectExpressions)
if _, ok := semi.Right.First.(*memo.Distinct); !ok {
rGroup.RelProps.Distinct = memo.HashDistinctOp
}
ita, err := plan.NewIndexedAccessForTableNode(leftRt, plan.NewLookupBuilder(idx.SqlIdx(), keyExprs, nullmask))
if err != nil {
return err
}
lookup := &memo.IndexScan{
Table: ita,
Alias: aliasName,
Index: idx,
}
m.MemoizeLookupJoin(e.Group(), rGroup, semi.Left, plan.JoinTypeLookup, semi.Filter, lookup)
}
return nil
})
}
// lookupCandidates extracts source relation information required to check for
// index lookups, including the source relation TableId, the list of Indexes,
// and the list of table filters.
func lookupCandidates(rel memo.RelExpr, limitOk bool) (sql.TableId, []*memo.Index, []sql.Expression) {
id, indexes, filters, _ := dfsLookupCandidates(rel, limitOk)
return id, indexes, filters
}
func dfsLookupCandidates(rel memo.RelExpr, limitOk bool) (sql.TableId, []*memo.Index, []sql.Expression, bool) {
if rel == nil {
return 0, nil, nil, false
}
if !limitOk && rel.Group().RelProps.Limit != nil {
// LOOKUP through a LIMIT is invalid
return 0, nil, nil, false
}
for n := rel; n != nil; n = n.Next() {
switch n := n.(type) {
case *memo.TableAlias:
tabId, _ := n.Group().RelProps.OutputTables().Next(1)
return sql.TableId(tabId), n.Indexes(), nil, true
case *memo.TableScan:
tabId, _ := n.Group().RelProps.OutputTables().Next(1)
return sql.TableId(tabId), n.Indexes(), nil, true
case *memo.IndexScan:
// The presence of an indexScan suggests that there is a valid
// table lookup, but returning here would fail to return filters
// that have been pushed into the indexScan. Continue until we
// find the full Filter->Tablescan path.
continue
case *memo.Filter:
id, indexes, filters, ok := dfsLookupCandidates(n.Child.First, limitOk)
if ok {
return id, indexes, append(filters, n.Filters...), ok
}
case *memo.Distinct:
return dfsLookupCandidates(n.Child.First, limitOk)
case *memo.Project:
return dfsLookupCandidates(n.Child.First, limitOk)
default:
}
}
return 0, nil, nil, false
}
func addCrossHashJoins(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
switch e.(type) {
case *memo.CrossJoin:
default:
return nil
}
join := e.(memo.JoinRel).JoinPrivate()
if len(join.Filter) > 0 {
return nil
}
// Only apply cross hash join if there is a subquery alias in the group.
hasSqa := false
for _, tbl := range e.Group().RelProps.TableIdNodes() {
if _, ok := tbl.(*plan.SubqueryAlias); ok {
hasSqa = true
break
}
}
if !hasSqa {
return nil
}
rel := &memo.HashJoin{
JoinBase: join.Copy(),
LeftAttrs: nil,
RightAttrs: nil,
}
rel.Op = rel.Op.AsHash()
e.Group().Prepend(rel)
return nil
})
}
func addHashJoins(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
switch e.(type) {
case *memo.InnerJoin, *memo.LeftJoin:
default:
return nil
}
join := e.(memo.JoinRel).JoinPrivate()
if len(join.Filter) == 0 {
return nil
}
var fromExpr, toExpr []sql.Expression
for _, f := range join.Filter {
switch f := f.(type) {
case *expression.Equals:
if satisfiesScalarRefs(f.Left(), join.Left.RelProps.OutputTables()) &&
satisfiesScalarRefs(f.Right(), join.Right.RelProps.OutputTables()) {
fromExpr = append(fromExpr, f.Right())
toExpr = append(toExpr, f.Left())
} else if satisfiesScalarRefs(f.Right(), join.Left.RelProps.OutputTables()) &&
satisfiesScalarRefs(f.Left(), join.Right.RelProps.OutputTables()) {
fromExpr = append(fromExpr, f.Left())
toExpr = append(toExpr, f.Right())
} else {
return nil
}
default:
return nil
}
}
switch join.Right.First.(type) {
case *memo.RecursiveTable:
return nil
}
m.MemoizeHashJoin(e.Group(), join, toExpr, fromExpr)
return nil
})
}
type rangeFilter struct {
value, min, max sql.Expression
closedOnLowerBound, closedOnUpperBound bool
}
// getRangeFilters takes the filter expressions on a join and identifies "ranges" where a given expression
// is constrained between two other expressions. (For instance, detecting "x > 5" and "x <= 10" and creating a range
// object representing "5 < x <= 10". See range_filter_test.go for examples.
func getRangeFilters(filters []sql.Expression) (ranges []rangeFilter) {
type candidateMap struct {
group sql.Expression
isClosed bool
}
lowerToUpper := make(map[string][]candidateMap)
upperToLower := make(map[string][]candidateMap)
findUpperBounds := func(value, min sql.Expression, closedOnLowerBound bool) {
for _, max := range lowerToUpper[value.String()] {
ranges = append(ranges, rangeFilter{
value: value,
min: min,
max: max.group,
closedOnLowerBound: closedOnLowerBound,
closedOnUpperBound: max.isClosed})
}
}
findLowerBounds := func(value, max sql.Expression, closedOnUpperBound bool) {
for _, min := range upperToLower[value.String()] {
ranges = append(ranges, rangeFilter{
value: value,
min: min.group,
max: max,
closedOnLowerBound: min.isClosed,
closedOnUpperBound: closedOnUpperBound})
}
}
addBounds := func(lower, upper sql.Expression, isClosed bool) {
lowerStr := lower.String()
lowerToUpper[lowerStr] = append(lowerToUpper[lowerStr], candidateMap{
group: upper,
isClosed: isClosed,
})
upperStr := upper.String()
upperToLower[upperStr] = append(upperToLower[upperStr], candidateMap{
group: lower,
isClosed: isClosed,
})
}
for _, filter := range filters {
switch f := filter.(type) {
case *expression.Between:
ranges = append(ranges, rangeFilter{f.Val, f.Lower, f.Upper, true, true})
case *expression.GreaterThan:
findUpperBounds(f.Left(), f.Right(), false)
findLowerBounds(f.Right(), f.Left(), false)
addBounds(f.Right(), f.Left(), false)
case *expression.GreaterThanOrEqual:
findUpperBounds(f.Left(), f.Right(), true)
findLowerBounds(f.Right(), f.Left(), true)
addBounds(f.Right(), f.Left(), true)
case *expression.LessThan:
findLowerBounds(f.Left(), f.Right(), false)
findUpperBounds(f.Right(), f.Left(), false)
addBounds(f.Left(), f.Right(), false)
case *expression.LessThanOrEqual:
findLowerBounds(f.Left(), f.Right(), true)
findUpperBounds(f.Right(), f.Left(), true)
addBounds(f.Left(), f.Right(), true)
}
}
return ranges
}
// addRangeHeapJoin checks whether the join can be implemented as a RangeHeap, and if so, prefixes a memo.RangeHeap plan
// to the memo join group. We can apply a range heap join for any join plan where a filter (or pair of filters) restricts a column the left child
// to be between two columns the right child.
//
// Some example joins that can be implemented as RangeHeap joins:
// - SELECT * FROM a JOIN b on a.value BETWEEN b.min AND b.max
// - SELECT * FROM a JOIN b on b.min <= a.value AND a.value < b.max
func addRangeHeapJoin(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
switch e.(type) {
case *memo.InnerJoin, *memo.LeftJoin:
default:
return nil
}
join := e.(memo.JoinRel).JoinPrivate()
// TODO: allow joins over filters
switch join.Right.First.(type) {
case *memo.TableScan, *memo.TableAlias, *memo.SubqueryAlias:
default:
return nil
}
_, lIndexes, lFilters := lookupCandidates(join.Left.First, true)
_, rIndexes, rFilters := lookupCandidates(join.Right.First, true)
leftTab := join.Left.RelProps.TableIdNodes()[0]
rightTab := join.Right.RelProps.TableIdNodes()[0]
for _, filter := range getRangeFilters(join.Filter) {
if !(satisfiesScalarRefs(filter.value, join.Left.RelProps.OutputTables()) &&
satisfiesScalarRefs(filter.min, join.Right.RelProps.OutputTables()) &&
satisfiesScalarRefs(filter.max, join.Right.RelProps.OutputTables())) {
return nil
}
// For now, only match expressions that are exactly a column reference.
// TODO: We may be able to match more complicated expressions if they meet the necessary criteria, such as:
// - References exactly one column
// - Is monotonically increasing
valueColRef, ok := filter.value.(*expression.GetField)
if !ok {
return nil
}
minColRef, ok := filter.min.(*expression.GetField)
if !ok {
return nil
}
maxColRef, ok := filter.max.(*expression.GetField)
if !ok {
return nil
}
leftIndexScans, err := sortedIndexScansForTableCol(m.Ctx, m.StatsProvider(), leftTab, lIndexes, valueColRef, join.Left.RelProps.FuncDeps().Constants(), lFilters)
if err != nil {
return err
}
if leftIndexScans == nil {
leftIndexScans = []*memo.IndexScan{nil}
}
for _, lIdx := range leftIndexScans {
rightIndexScans, err := sortedIndexScansForTableCol(m.Ctx, m.StatsProvider(), rightTab, rIndexes, minColRef, join.Right.RelProps.FuncDeps().Constants(), rFilters)
if err != nil {
return err
}
if rightIndexScans == nil {
rightIndexScans = []*memo.IndexScan{nil}
}
for _, rIdx := range rightIndexScans {
rel := &memo.RangeHeapJoin{
JoinBase: join.Copy(),
}
rel.RangeHeap = &memo.RangeHeap{
ValueIndex: lIdx,
MinIndex: rIdx,
ValueExpr: filter.value,
MinExpr: filter.min,
ValueCol: valueColRef,
MinColRef: minColRef,
MaxColRef: maxColRef,
Parent: rel.JoinBase,
RangeClosedOnLowerBound: filter.closedOnLowerBound,
RangeClosedOnUpperBound: filter.closedOnUpperBound,
}
rel.Op = rel.Op.AsRangeHeap()
e.Group().Prepend(rel)
}
}
}
return nil
})
}
// satisfiesScalarRefs returns true if all GetFields in the expression
// are columns provided by |tables|
func satisfiesScalarRefs(e sql.Expression, tables sql.FastIntSet) bool {
// |grp| provides all tables referenced in |e|
return !transform.InspectExpr(e, func(e sql.Expression) bool {
gf, _ := e.(*expression.GetField)
if gf != nil {
if !tables.Contains(int(gf.TableId())) {
return true
}
}
return false
})
}
// addMergeJoins will add merge join operators to join relations
// with native indexes providing sort enforcement on an equality
// filter.
// TODO: sort-merge joins
func addMergeJoins(m *memo.Memo) error {
return memo.DfsRel(m.Root(), func(e memo.RelExpr) error {
var join *memo.JoinBase
switch e := e.(type) {
case *memo.InnerJoin:
join = e.JoinBase
case *memo.LeftJoin:
join = e.JoinBase
//TODO semijoin, antijoin, fullouterjoin
default:
return nil
}
if len(join.Filter) == 0 {
return nil
}
leftTabId, lIndexes, lFilters := lookupCandidates(join.Left.First, true)
rightTabId, rIndexes, rFilters := lookupCandidates(join.Right.First, true)
if leftTabId == 0 || rightTabId == 0 {
return nil
}