-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
join_funcs.go
1776 lines (1617 loc) · 68.8 KB
/
join_funcs.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 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package xform
import (
"fmt"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/constraint"
"github.com/cockroachdb/cockroach/pkg/sql/opt/invertedidx"
"github.com/cockroachdb/cockroach/pkg/sql/opt/lookupjoin"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/opt/ordering"
"github.com/cockroachdb/cockroach/pkg/sql/opt/partition"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/errors"
)
// GenerateMergeJoins spawns MergeJoinOps, based on any interesting orderings.
func (c *CustomFuncs) GenerateMergeJoins(
grp memo.RelExpr,
originalOp opt.Operator,
left, right memo.RelExpr,
on memo.FiltersExpr,
joinPrivate *memo.JoinPrivate,
) {
if joinPrivate.Flags.Has(memo.DisallowMergeJoin) {
return
}
leftProps := left.Relational()
rightProps := right.Relational()
leftEq, rightEq, _ := memo.ExtractJoinEqualityColumns(
leftProps.OutputCols, rightProps.OutputCols, on,
)
n := len(leftEq)
if n == 0 {
return
}
// We generate MergeJoin expressions based on interesting orderings from the
// left side. The CommuteJoin rule will ensure that we actually try both
// sides.
orders := ordering.DeriveInterestingOrderings(left).Copy()
leftCols, leftFDs := leftEq.ToSet(), &left.Relational().FuncDeps
orders.RestrictToCols(leftCols, leftFDs)
var mustGenerateMergeJoin bool
if len(orders) == 0 && leftCols.SubsetOf(leftFDs.ConstantCols()) {
// All left equality columns are constant, so we can trivially create
// an ordering.
mustGenerateMergeJoin = true
}
if !c.NoJoinHints(joinPrivate) || c.e.evalCtx.SessionData().ReorderJoinsLimit == 0 {
// If we are using a hint, or the join limit is set to zero, the join won't
// be commuted. Add the orderings from the right side.
rightOrders := ordering.DeriveInterestingOrderings(right).Copy()
rightOrders.RestrictToCols(rightEq.ToSet(), &right.Relational().FuncDeps)
orders = append(orders, rightOrders...)
// If we don't allow hash join, we must do our best to generate a merge
// join, even if it means sorting both sides.
mustGenerateMergeJoin = true
}
if mustGenerateMergeJoin {
// We append an arbitrary ordering, in case the interesting orderings don't
// result in any merge joins.
o := make(opt.Ordering, len(leftEq))
for i := range o {
o[i] = opt.MakeOrderingColumn(leftEq[i], false /* descending */)
}
var oc props.OrderingChoice
oc.FromOrdering(o)
orders.Add(&oc)
}
if len(orders) == 0 {
return
}
getEqCols := func(col opt.ColumnID) (left, right opt.ColumnID) {
// Assume that col is in either leftEq or rightEq.
for eqIdx := 0; eqIdx < len(leftEq); eqIdx++ {
if leftEq[eqIdx] == col || rightEq[eqIdx] == col {
return leftEq[eqIdx], rightEq[eqIdx]
}
}
panic(errors.AssertionFailedf("failed to find eqIdx for merge join"))
}
var remainingFilters memo.FiltersExpr
for _, o := range orders {
if remainingFilters == nil {
remainingFilters = memo.ExtractRemainingJoinFilters(on, leftEq, rightEq)
}
merge := memo.MergeJoinExpr{Left: left, Right: right, On: remainingFilters}
merge.JoinPrivate = *joinPrivate
merge.JoinType = originalOp
merge.LeftEq = make(opt.Ordering, 0, n)
merge.RightEq = make(opt.Ordering, 0, n)
merge.LeftOrdering.Columns = make([]props.OrderingColumnChoice, 0, n)
merge.RightOrdering.Columns = make([]props.OrderingColumnChoice, 0, n)
addCol := func(col opt.ColumnID, descending bool) {
l, r := getEqCols(col)
merge.LeftEq = append(merge.LeftEq, opt.MakeOrderingColumn(l, descending))
merge.RightEq = append(merge.RightEq, opt.MakeOrderingColumn(r, descending))
merge.LeftOrdering.AppendCol(l, descending)
merge.RightOrdering.AppendCol(r, descending)
}
// Add the required ordering columns.
for i := range o.Columns {
c := &o.Columns[i]
c.Group.ForEach(func(col opt.ColumnID) {
addCol(col, c.Descending)
})
}
// Add the remaining columns in an arbitrary order.
remaining := leftCols.Difference(merge.LeftEq.ColSet())
remaining.ForEach(func(col opt.ColumnID) {
addCol(col, false /* descending */)
})
// Simplify the orderings with the corresponding FD sets.
merge.LeftOrdering.Simplify(&leftProps.FuncDeps)
merge.RightOrdering.Simplify(&rightProps.FuncDeps)
c.e.mem.AddMergeJoinToGroup(&merge, grp)
}
}
// GenerateLookupJoins looks at the possible indexes and creates lookup join
// expressions in the current group. A lookup join can be created when the ON
// condition has equality constraints on a prefix of the index columns.
//
// There are two cases:
//
// 1. The index has all the columns we need; this is the simple case, where we
// generate a LookupJoin expression in the current group:
//
// Join LookupJoin(t@idx)
// / \ |
// / \ -> |
// Input Scan(t) Input
//
//
// 2. The index is not covering, but we can fully evaluate the ON condition
// using the index, or we are doing an InnerJoin. We have to generate
// an index join above the lookup join. Note that this index join is also
// implemented as a LookupJoin, because an IndexJoin can only output
// columns from one table, whereas we also need to output columns from
// Input.
//
// Join LookupJoin(t@primary)
// / \ |
// / \ -> |
// Input Scan(t) LookupJoin(t@idx)
// |
// |
// Input
//
// For example:
// CREATE TABLE abc (a INT PRIMARY KEY, b INT, c INT)
// CREATE TABLE xyz (x INT PRIMARY KEY, y INT, z INT, INDEX (y))
// SELECT * FROM abc JOIN xyz ON a=y
//
// We want to first join abc with the index on y (which provides columns y, x)
// and then use a lookup join to retrieve column z. The "index join" (top
// LookupJoin) will produce columns a,b,c,x,y,z; the lookup columns are just z
// (the original lookup join produced a,b,c,x,y).
//
// Note that the top LookupJoin "sees" column IDs from the table on both
// "sides" (in this example x,y on the left and z on the right) but there is
// no overlap.
//
// 3. The index is not covering and we cannot fully evaluate the ON condition
// using the index, and we are doing a LeftJoin/SemiJoin/AntiJoin. This is
// handled using a lower-upper pair of joins that are further specialized
// as paired-joins. The first (lower) join outputs a continuation column
// that is used by the second (upper) join. Like case 2, both are lookup
// joins, but paired-joins explicitly know their role in the pair and
// behave accordingly.
//
// For example, using the same tables in the example for case 2:
// SELECT * FROM abc LEFT JOIN xyz ON a=y AND b=z
//
// The first join will evaluate a=y and produce columns a,b,c,x,y,cont
// where cont is the continuation column used to group together rows that
// correspond to the same original a,b,c. The second join will fetch z from
// the primary index, evaluate b=z, and produce columns a,b,c,x,y,z. A
// similar approach works for anti-joins and semi-joins.
//
//
// A lookup join can be created when the ON condition or implicit filters from
// CHECK constraints and computed columns constrain a prefix of the index
// columns to non-ranging constant values. To support this, the constant values
// are cross-joined with the input and used as key columns for the parent lookup
// join.
//
// For example, consider the tables and query below.
//
// CREATE TABLE abc (a INT PRIMARY KEY, b INT, c INT)
// CREATE TABLE xyz (
// x INT PRIMARY KEY,
// y INT,
// z INT NOT NULL,
// CHECK z IN (1, 2, 3),
// INDEX (z, y)
// )
// SELECT a, x FROM abc JOIN xyz ON a=y
//
// GenerateLookupJoins will perform the following transformation.
//
// Join LookupJoin(t@idx)
// / \ |
// / \ -> |
// Input Scan(t) Join
// / \
// / \
// Input Values(1, 2, 3)
//
// If a column is constrained to a single constant value, inlining normalization
// rules will reduce the cross join into a project.
//
// Join LookupJoin(t@idx)
// / \ |
// / \ -> |
// Input Scan(t) Project
// |
// |
// Input
//
func (c *CustomFuncs) GenerateLookupJoins(
grp memo.RelExpr,
joinType opt.Operator,
input memo.RelExpr,
scanPrivate *memo.ScanPrivate,
on memo.FiltersExpr,
joinPrivate *memo.JoinPrivate,
) {
c.generateLookupJoinsImpl(
grp, joinType,
input,
scanPrivate.Cols,
opt.ColSet{}, /* projectedVirtualCols */
scanPrivate,
on,
joinPrivate,
)
}
// GenerateLookupJoinsWithVirtualCols is similar to GenerateLookupJoins but
// generates lookup joins into indexes that contain virtual columns.
//
// In a canonical plan a virtual column is produced with a Project expression on
// top of a Scan. This is necessary because virtual columns aren't stored in the
// primary index. When a virtual column is indexed, a lookup join can be
// generated that both uses the virtual column as a lookup column and produces
// the column directly from the index without a Project.
//
// For example:
//
// Join LookupJoin(t@idx)
// / \ |
// / \ -> |
// Input Project Input
// |
// |
// Scan(t)
//
// This function and its associated rule currently require that:
//
// 1. The join is an inner join.
// 2. The right side projects only virtual computed columns.
// 3. All the projected virtual columns are covered by a single index.
//
// It should be possible to support semi- and anti- joins. Left joins may be
// possible with additional complexity.
//
// It should also be possible to support cases where all the virtual columns are
// not covered by a single index by wrapping the lookup join in a Project that
// produces the non-covered virtual columns.
func (c *CustomFuncs) GenerateLookupJoinsWithVirtualCols(
grp memo.RelExpr,
joinType opt.Operator,
input memo.RelExpr,
rightCols opt.ColSet,
projectedVirtualCols opt.ColSet,
scanPrivate *memo.ScanPrivate,
on memo.FiltersExpr,
joinPrivate *memo.JoinPrivate,
) {
c.generateLookupJoinsImpl(
grp, joinType,
input,
rightCols,
projectedVirtualCols,
scanPrivate,
on,
joinPrivate,
)
}
// canGenerateLookupJoins makes a best-effort to filter out cases where no
// joins can be constructed based on the join's filters and flags. It may miss
// some cases that will be filtered out later.
func canGenerateLookupJoins(
input memo.RelExpr, joinFlags memo.JoinFlags, leftCols, rightCols opt.ColSet, on memo.FiltersExpr,
) bool {
if joinFlags.Has(memo.DisallowLookupJoinIntoRight) {
return false
}
if leftEq, _, _ := memo.ExtractJoinEqualityColumns(leftCols, rightCols, on); len(leftEq) > 0 {
// There is at least one valid equality between left and right columns.
return true
}
// There are no valid equality conditions, but there may be an inequality that
// can be used for lookups. Since the current implementation does not
// deduplicate the resulting spans, only plan a lookup join with no equalities
// when the input has one row, or if a lookup join is forced.
if input.Relational().Cardinality.IsZeroOrOne() ||
joinFlags.Has(memo.AllowOnlyLookupJoinIntoRight) {
cmp, _, _ := memo.ExtractJoinConditionColumns(leftCols, rightCols, on, true /* inequality */)
return len(cmp) > 0
}
return false
}
// generateLookupJoinsImpl is the general implementation for generating lookup
// joins. The rightCols argument must be the columns output by the right side of
// matched join expression. projectedVirtualCols is the set of virtual columns
// projected on the right side of the matched join expression.
//
// See GenerateLookupJoins and GenerateLookupJoinsWithVirtualCols for
// more details.
func (c *CustomFuncs) generateLookupJoinsImpl(
grp memo.RelExpr,
joinType opt.Operator,
input memo.RelExpr,
rightCols opt.ColSet,
projectedVirtualCols opt.ColSet,
scanPrivate *memo.ScanPrivate,
on memo.FiltersExpr,
joinPrivate *memo.JoinPrivate,
) {
md := c.e.mem.Metadata()
inputProps := input.Relational()
if !canGenerateLookupJoins(input, joinPrivate.Flags, inputProps.OutputCols, rightCols, on) {
return
}
var cb lookupjoin.ConstraintBuilder
cb.Init(
c.e.f,
c.e.mem.Metadata(),
c.e.evalCtx,
scanPrivate.Table,
inputProps.OutputCols,
rightCols,
)
// Generate implicit filters from CHECK constraints and computed columns as
// optional filters to help generate lookup join keys.
optionalFilters := c.checkConstraintFilters(scanPrivate.Table)
computedColFilters := c.computedColFilters(scanPrivate, on, optionalFilters)
optionalFilters = append(optionalFilters, computedColFilters...)
var pkCols opt.ColList
var newScanPrivate *memo.ScanPrivate
var iter scanIndexIter
iter.Init(c.e.evalCtx, c.e.f, c.e.mem, &c.im, scanPrivate, on, rejectInvertedIndexes)
iter.ForEach(func(index cat.Index, onFilters memo.FiltersExpr, indexCols opt.ColSet, _ bool, _ memo.ProjectionsExpr) {
// Skip indexes that do no cover all virtual projection columns, if
// there are any. This can happen when there are multiple virtual
// columns indexed in different indexes.
//
// TODO(mgartner): It should be possible to plan a lookup join in this
// case by producing the covered virtual columns from the lookup join
// and producing the rest in a Project that wraps the join.
if !projectedVirtualCols.SubsetOf(indexCols) {
return
}
lookupConstraint, foundEqualityCols := cb.Build(index, onFilters, optionalFilters)
if lookupConstraint.IsUnconstrained() {
// We couldn't find equality columns or a lookup expression to
// perform a lookup join on this index.
return
}
if !foundEqualityCols && !inputProps.Cardinality.IsZeroOrOne() &&
!joinPrivate.Flags.Has(memo.AllowOnlyLookupJoinIntoRight) {
// Avoid planning an inequality-only lookup when the input has more than
// one row unless the lookup join is forced (see canGenerateLookupJoins
// for a brief explanation).
return
}
lookupJoin := memo.LookupJoinExpr{Input: input}
lookupJoin.JoinPrivate = *joinPrivate
lookupJoin.JoinType = joinType
lookupJoin.Table = scanPrivate.Table
lookupJoin.Index = index.Ordinal()
lookupJoin.Locking = scanPrivate.Locking
lookupJoin.KeyCols = lookupConstraint.KeyCols
lookupJoin.LookupExpr = lookupConstraint.LookupExpr
lookupJoin.On = lookupConstraint.RemainingFilters
lookupJoin.ConstFilters = lookupConstraint.ConstFilters
// Wrap the input in a Project if any projections are required. The
// lookup join will project away these synthesized columns.
if len(lookupConstraint.InputProjections) > 0 {
lookupJoin.Input = c.e.f.ConstructProject(
lookupJoin.Input,
lookupConstraint.InputProjections,
lookupJoin.Input.Relational().OutputCols,
)
}
tableFDs := memo.MakeTableFuncDep(md, scanPrivate.Table)
// A lookup join will drop any input row which contains NULLs, so a lax key
// is sufficient.
lookupJoin.LookupColsAreTableKey = tableFDs.ColsAreLaxKey(lookupConstraint.RightSideCols.ToSet())
// Add input columns and lookup expression columns, since these will be
// needed for all join types and cases. Exclude synthesized projection
// columns.
var projectionCols opt.ColSet
for i := range lookupConstraint.InputProjections {
projectionCols.Add(lookupConstraint.InputProjections[i].Col)
}
lookupJoin.Cols = lookupJoin.LookupExpr.OuterCols().Difference(projectionCols)
lookupJoin.Cols.UnionWith(inputProps.OutputCols)
// At this point the filter may have been reduced by partial index
// predicate implication and by removing parts of the filter that are
// represented by the key columns. If there are any outer columns of the
// filter that are not output columns of the right side of the join, we
// skip this index.
//
// This is possible when GenerateLookupJoinsWithVirtualColsAndFilter
// matches an expression on the right side of the join in the form
// (Project (Select (Scan))). The Select's filters may reference columns
// that are not passed through in the Project.
//
// TODO(mgartner): We could handle this by wrapping the lookup join in
// an index join to fetch these columns and filter by them, then
// wrapping the index join in a project that removes the columns.
filterColsFromRight := lookupJoin.On.OuterCols().Difference(inputProps.OutputCols)
if !filterColsFromRight.SubsetOf(rightCols) {
return
}
isCovering := rightCols.SubsetOf(indexCols)
if isCovering {
// Case 1 (see function comment).
lookupJoin.Cols.UnionWith(rightCols)
// If some optional filters were used to build the lookup expression, we
// may need to wrap the final expression with a project. We don't need to
// do this for semi or anti joins, since they have an implicit projection
// that removes all right-side columns.
needsProject := joinType != opt.SemiJoinOp && joinType != opt.AntiJoinOp &&
!lookupJoin.Cols.SubsetOf(grp.Relational().OutputCols)
if !needsProject {
c.e.mem.AddLookupJoinToGroup(&lookupJoin, grp)
return
}
var project memo.ProjectExpr
project.Input = c.e.f.ConstructLookupJoin(
lookupJoin.Input,
lookupJoin.On,
&lookupJoin.LookupJoinPrivate,
)
project.Passthrough = grp.Relational().OutputCols
c.e.mem.AddProjectToGroup(&project, grp)
return
}
_, isPartial := index.Predicate()
if isPartial && (joinType == opt.SemiJoinOp || joinType == opt.AntiJoinOp) {
// Typically, the index must cover all columns from the right in
// order to generate a lookup join without an additional index join
// (case 1, see function comment). However, if the index is a
// partial index, the filters remaining after proving
// filter-predicate implication may no longer reference some
// columns. A lookup semi- or anti-join can be generated if the
// columns in the new filters from the right side of the join are
// covered by the index. Consider the example:
//
// CREATE TABLE a (a INT)
// CREATE TABLE xy (x INT, y INT, INDEX (x) WHERE y > 0)
//
// SELECT a FROM a WHERE EXISTS (SELECT 1 FROM xyz WHERE a = x AND y > 0)
//
// The original ON filters of the semi-join are (a = x AND y > 0).
// The (y > 0) expression in the filter is an exact match to the
// partial index predicate, so the remaining ON filters are (a = x).
// Column y is no longer referenced, so a lookup semi-join can be
// created despite the partial index not covering y.
//
// Note that this is a special case that only works for semi- and
// anti-joins because they never include columns from the right side
// in their output columns. Other joins include columns from the
// right side in their output columns, so even if the ON filters no
// longer reference an un-covered column, they must be fetched (case
// 2, see function comment).
filterColsFromRight := rightCols.Intersection(onFilters.OuterCols())
if filterColsFromRight.SubsetOf(indexCols) {
lookupJoin.Cols.UnionWith(filterColsFromRight)
c.e.mem.AddLookupJoinToGroup(&lookupJoin, grp)
return
}
}
// All code that follows is for cases 2 and 3 (see function comment).
// We need to generate two joins: a lower join followed by an upper join.
// In case 3, this lower-upper pair of joins is further specialized into
// paired-joins where we refer to the lower as first and upper as second.
if scanPrivate.Flags.NoIndexJoin {
return
}
pairedJoins := false
continuationCol := opt.ColumnID(0)
lowerJoinType := joinType
if joinType == opt.SemiJoinOp {
// Case 3: Semi joins are converted to a pair consisting of an inner
// lookup join and semi lookup join.
pairedJoins = true
lowerJoinType = opt.InnerJoinOp
} else if joinType == opt.AntiJoinOp {
// Case 3: Anti joins are converted to a pair consisting of a left
// lookup join and anti lookup join.
pairedJoins = true
lowerJoinType = opt.LeftJoinOp
}
if pkCols == nil {
pkCols = c.getPkCols(scanPrivate.Table)
}
// The lower LookupJoin must return all PK columns (they are needed as key
// columns for the index join).
lookupJoin.Cols.UnionWith(rightCols.Intersection(indexCols))
for i := range pkCols {
lookupJoin.Cols.Add(pkCols[i])
}
var indexJoin memo.LookupJoinExpr
// onCols are the columns that the ON condition in the (lower) lookup join
// can refer to: input columns, or columns available in the index.
onCols := indexCols.Union(inputProps.OutputCols)
if c.FiltersBoundBy(lookupJoin.On, onCols) {
// Case 2.
// The ON condition refers only to the columns available in the index.
//
// For LeftJoin, both LookupJoins perform a LeftJoin. A null-extended row
// from the lower LookupJoin will not have any matches in the top
// LookupJoin (it has NULLs on key columns) and will get null-extended
// there as well.
indexJoin.On = memo.TrueFilter
} else {
// ON has some conditions that are bound by the columns in the index (at
// the very least, the equality conditions we used for KeyCols), and some
// conditions that refer to other columns. We can put the former in the
// lower LookupJoin and the latter in the index join.
//
// This works in a straightforward manner for InnerJoin but not for
// LeftJoin because of a technicality: if an input (left) row has
// matches in the lower LookupJoin but has no matches in the index join,
// only the columns looked up by the top index join get NULL-extended.
// Additionally if none of the lower matches are matches in the index
// join, we want to output only one NULL-extended row. To accomplish
// this, we need to use paired-joins.
if joinType == opt.LeftJoinOp {
// Case 3.
pairedJoins = true
// The lowerJoinType continues to be LeftJoinOp.
}
// We have already set pairedJoins=true for SemiJoin, AntiJoin earlier,
// and we don't need to do that for InnerJoin. The following sets up the
// ON conditions for both Case 2 and Case 3, when doing 2 joins that
// will each evaluate part of the ON condition.
conditions := lookupJoin.On
lookupJoin.On = c.ExtractBoundConditions(conditions, onCols)
indexJoin.On = c.ExtractUnboundConditions(conditions, onCols)
}
if pairedJoins {
// Create a new ScanPrivate, which will be used below for the first lookup
// join in the pair. Note: this must happen before the continuation column
// is created to ensure that the continuation column will have the highest
// column ID.
//
// See the comment where this newScanPrivate is used below in mapLookupJoin
// for details about why it's needed.
if newScanPrivate == nil {
newScanPrivate = c.DuplicateScanPrivate(scanPrivate)
}
lookupJoin.JoinType = lowerJoinType
continuationCol = c.constructContinuationColumnForPairedJoin()
lookupJoin.IsFirstJoinInPairedJoiner = true
lookupJoin.ContinuationCol = continuationCol
lookupJoin.Cols.Add(continuationCol)
// Map the lookup join to use the new table and column IDs from the
// newScanPrivate created above. We want to make sure that the column IDs
// returned by the lookup join are different from the IDs that will be
// returned by the top level index join.
//
// In addition to avoiding subtle bugs in the optimizer when the same
// column ID is reused, this mapping is also essential for correct behavior
// at execution time in the case of a left paired join. This is because a
// row that matches in the first left join (the lookup join) might be a
// false positive and fail to match in the second left join (the index
// join). If an original left row has no matches after the second left join,
// it must appear as a null-extended row with all right-hand columns null.
// If one of the right-hand columns comes from the lookup join, however,
// it might incorrectly show up as non-null (see #58892 and #81968).
c.mapLookupJoin(&lookupJoin, indexCols, newScanPrivate)
}
indexJoin.Input = c.e.f.ConstructLookupJoin(
lookupJoin.Input,
lookupJoin.On,
&lookupJoin.LookupJoinPrivate,
)
indexJoin.JoinType = joinType
indexJoin.Table = scanPrivate.Table
indexJoin.Index = cat.PrimaryIndex
indexJoin.KeyCols = c.getPkCols(lookupJoin.Table)
indexJoin.Cols = rightCols.Union(inputProps.OutputCols)
indexJoin.LookupColsAreTableKey = true
indexJoin.Locking = scanPrivate.Locking
if pairedJoins {
indexJoin.IsSecondJoinInPairedJoiner = true
}
// If this is a semi- or anti-join, ensure the columns do not include any
// unneeded right-side columns.
if joinType == opt.SemiJoinOp || joinType == opt.AntiJoinOp {
indexJoin.Cols = inputProps.OutputCols.Union(indexJoin.On.OuterCols())
}
// Create the LookupJoin for the index join in the same group.
c.e.mem.AddLookupJoinToGroup(&indexJoin, grp)
})
}
// constructContinuationColumnForPairedJoin constructs a continuation column
// ID for the paired-joiners used for left outer/semi/anti joins when the
// first join generates false positives (due to an inverted index or
// non-covering index). The first join will be either a left outer join or
// an inner join.
func (c *CustomFuncs) constructContinuationColumnForPairedJoin() opt.ColumnID {
return c.e.f.Metadata().AddColumn("continuation", c.BoolType())
}
// mapLookupJoin maps the given lookup join to use the table and columns
// provided in newScanPrivate. The lookup join is modified in place. indexCols
// contains the pre-calculated index columns used by the given lookupJoin.
//
// Note that columns from the input are not mapped. For example, KeyCols
// does not need to be mapped below since it only contains input columns.
func (c *CustomFuncs) mapLookupJoin(
lookupJoin *memo.LookupJoinExpr, indexCols opt.ColSet, newScanPrivate *memo.ScanPrivate,
) {
tabID := lookupJoin.Table
newTabID := newScanPrivate.Table
// Get the new index columns.
newIndexCols := c.e.mem.Metadata().TableMeta(newTabID).IndexColumns(lookupJoin.Index)
// Create a map from the source columns to the destination columns.
var srcColsToDstCols opt.ColMap
for srcCol, ok := indexCols.Next(0); ok; srcCol, ok = indexCols.Next(srcCol + 1) {
ord := tabID.ColumnOrdinal(srcCol)
dstCol := newTabID.ColumnID(ord)
srcColsToDstCols.Set(int(srcCol), int(dstCol))
}
lookupJoin.Table = newTabID
lookupExpr := c.e.f.RemapCols(&lookupJoin.LookupExpr, srcColsToDstCols).(*memo.FiltersExpr)
lookupJoin.LookupExpr = *lookupExpr
remoteLookupExpr := c.e.f.RemapCols(&lookupJoin.RemoteLookupExpr, srcColsToDstCols).(*memo.FiltersExpr)
lookupJoin.RemoteLookupExpr = *remoteLookupExpr
lookupJoin.Cols = lookupJoin.Cols.Difference(indexCols).Union(newIndexCols)
constFilters := c.e.f.RemapCols(&lookupJoin.ConstFilters, srcColsToDstCols).(*memo.FiltersExpr)
lookupJoin.ConstFilters = *constFilters
on := c.e.f.RemapCols(&lookupJoin.On, srcColsToDstCols).(*memo.FiltersExpr)
lookupJoin.On = *on
}
// GenerateInvertedJoins is similar to GenerateLookupJoins, but instead
// of generating lookup joins with regular indexes, it generates lookup joins
// with inverted indexes. Similar to GenerateLookupJoins, there are two cases
// depending on whether or not the index is covering. See the comment above
// GenerateLookupJoins for details.
func (c *CustomFuncs) GenerateInvertedJoins(
grp memo.RelExpr,
joinType opt.Operator,
input memo.RelExpr,
scanPrivate *memo.ScanPrivate,
on memo.FiltersExpr,
joinPrivate *memo.JoinPrivate,
) {
if joinPrivate.Flags.Has(memo.DisallowInvertedJoinIntoRight) {
return
}
inputCols := input.Relational().OutputCols
var pkCols opt.ColList
var newScanPrivate *memo.ScanPrivate
eqColsAndOptionalFiltersCalculated := false
var leftEqCols opt.ColList
var rightEqCols opt.ColList
var optionalFilters memo.FiltersExpr
var iter scanIndexIter
iter.Init(c.e.evalCtx, c.e.f, c.e.mem, &c.im, scanPrivate, on, rejectNonInvertedIndexes)
iter.ForEach(func(index cat.Index, onFilters memo.FiltersExpr, indexCols opt.ColSet, _ bool, _ memo.ProjectionsExpr) {
invertedJoin := memo.InvertedJoinExpr{Input: input}
numPrefixCols := index.NonInvertedPrefixColumnCount()
var allFilters memo.FiltersExpr
if numPrefixCols > 0 {
// Only calculate the left and right equality columns and optional
// filters if there is a multi-column inverted index.
if !eqColsAndOptionalFiltersCalculated {
inputProps := input.Relational()
leftEqCols, rightEqCols, _ = memo.ExtractJoinEqualityColumns(inputProps.OutputCols, scanPrivate.Cols, onFilters)
// Generate implicit filters from CHECK constraints and computed
// columns as optional filters. We build the computed column
// optional filters from the original on filters, not the
// filters within the context of the iter.ForEach callback. The
// latter may be reduced during partial index implication and
// using them here would result in a reduced set of optional
// filters.
optionalFilters = c.checkConstraintFilters(scanPrivate.Table)
computedColFilters := c.computedColFilters(scanPrivate, on, optionalFilters)
optionalFilters = append(optionalFilters, computedColFilters...)
eqColsAndOptionalFiltersCalculated = true
}
// Combine the ON filters and optional filters together. This set of
// filters will be used to attempt to constrain non-inverted prefix
// columns of the multi-column inverted index.
allFilters = append(onFilters, optionalFilters...)
}
// The non-inverted prefix columns of a multi-column inverted index must
// be constrained in order to perform an inverted join. We attempt to
// constrain each prefix column to non-ranging constant values. These
// values are joined with the input to create key columns for the
// InvertedJoin, similar to GenerateLookupJoins.
var constFilters memo.FiltersExpr
var rightSideCols opt.ColList
for i := 0; i < numPrefixCols; i++ {
prefixCol := scanPrivate.Table.IndexColumnID(index, i)
// Check if prefixCol is constrained by an equality constraint.
if eqIdx, ok := rightEqCols.Find(prefixCol); ok {
invertedJoin.PrefixKeyCols = append(invertedJoin.PrefixKeyCols, leftEqCols[eqIdx])
rightSideCols = append(rightSideCols, prefixCol)
continue
}
// Try to constrain prefixCol to constant, non-ranging values.
foundVals, allIdx, ok := lookupjoin.FindJoinFilterConstants(allFilters, prefixCol, c.e.evalCtx)
if !ok {
// Cannot constrain prefix column and therefore cannot generate
// an inverted join.
return
}
if len(foundVals) > 1 &&
(joinType == opt.LeftJoinOp || joinType == opt.SemiJoinOp || joinType == opt.AntiJoinOp) {
// We cannot create an inverted join in this case, because
// constructing a cross join with foundVals will increase the
// size of the input. As a result, matching input rows will show
// up more than once in the output of a semi-join, and
// non-matching input rows will show up more than once in the
// output of a left or anti join, which is incorrect (see #59615
// and #78681).
// TODO(rytaft,mgartner): find a way to create an inverted join for this
// case.
return
}
// We will join these constant values with the input to make
// equality columns for the inverted join.
if constFilters == nil {
constFilters = make(memo.FiltersExpr, 0, numPrefixCols)
}
prefixColType := c.e.f.Metadata().ColumnMeta(prefixCol).Type
constColAlias := fmt.Sprintf("inverted_join_const_col_@%d", prefixCol)
join, constColID := c.constructJoinWithConstants(
invertedJoin.Input,
foundVals,
prefixColType,
constColAlias,
)
invertedJoin.Input = join
invertedJoin.PrefixKeyCols = append(invertedJoin.PrefixKeyCols, constColID)
constFilters = append(constFilters, allFilters[allIdx])
rightSideCols = append(rightSideCols, prefixCol)
}
// Remove redundant filters from the ON condition if non-inverted prefix
// columns were constrained by equality filters or constant filters.
onFilters = memo.ExtractRemainingJoinFilters(onFilters, invertedJoin.PrefixKeyCols, rightSideCols)
onFilters = onFilters.Difference(constFilters)
invertedJoin.ConstFilters = constFilters
// Check whether the filter can constrain the inverted column.
invertedExpr := invertedidx.TryJoinInvertedIndex(
c.e.evalCtx.Context, c.e.f, onFilters, scanPrivate.Table, index, inputCols,
)
if invertedExpr == nil {
return
}
// All geospatial and JSON inverted joins that are currently supported
// are not covering, so we must wrap them in an index join.
// TODO(rytaft): Avoid adding an index join if possible for Array
// inverted joins.
if scanPrivate.Flags.NoIndexJoin {
return
}
if pkCols == nil {
pkCols = c.getPkCols(scanPrivate.Table)
}
// Though the index is marked as containing the column being indexed, it
// doesn't actually, and it is only valid to extract the primary key
// columns and non-inverted prefix columns from it.
indexCols = pkCols.ToSet()
for i, n := 0, index.NonInvertedPrefixColumnCount(); i < n; i++ {
prefixCol := scanPrivate.Table.IndexColumnID(index, i)
indexCols.Add(prefixCol)
}
// Create a new ScanPrivate, which will be used below for the inverted join.
// Note: this must happen before the continuation column is created to ensure
// that the continuation column will have the highest column ID.
//
// See the comment where this newScanPrivate is used below in mapInvertedJoin
// for details about why it's needed.
if newScanPrivate == nil {
newScanPrivate = c.DuplicateScanPrivate(scanPrivate)
}
continuationCol := opt.ColumnID(0)
invertedJoinType := joinType
// Anti joins are converted to a pair consisting of a left inverted join
// and anti lookup join.
if joinType == opt.LeftJoinOp || joinType == opt.AntiJoinOp {
continuationCol = c.constructContinuationColumnForPairedJoin()
invertedJoinType = opt.LeftJoinOp
} else if joinType == opt.SemiJoinOp {
// Semi joins are converted to a pair consisting of an inner inverted
// join and semi lookup join.
continuationCol = c.constructContinuationColumnForPairedJoin()
invertedJoinType = opt.InnerJoinOp
}
invertedJoin.JoinPrivate = *joinPrivate
invertedJoin.JoinType = invertedJoinType
invertedJoin.Table = scanPrivate.Table
invertedJoin.Index = index.Ordinal()
invertedJoin.InvertedExpr = invertedExpr
invertedJoin.Cols = indexCols.Union(inputCols)
invertedJoin.Locking = scanPrivate.Locking
if continuationCol != 0 {
invertedJoin.Cols.Add(continuationCol)
invertedJoin.IsFirstJoinInPairedJoiner = true
invertedJoin.ContinuationCol = continuationCol
}
var indexJoin memo.LookupJoinExpr
// ON may have some conditions that are bound by the columns in the index
// and some conditions that refer to other columns. We can put the former
// in the InvertedJoin and the latter in the index join.
invertedJoin.On = c.ExtractBoundConditions(onFilters, invertedJoin.Cols)
indexJoin.On = c.ExtractUnboundConditions(onFilters, invertedJoin.Cols)
// Map the inverted join to use the new table and column IDs from the
// newScanPrivate created above. We want to make sure that the column IDs
// returned by the inverted join are different from the IDs that will be
// returned by the top level index join.
//
// In addition to avoiding subtle bugs in the optimizer when the same
// column ID is reused, this mapping is also essential for correct behavior
// at execution time in the case of a left paired join. This is because a
// row that matches in the first left join (the inverted join) might be a
// false positive and fail to match in the second left join (the lookup
// join). If an original left row has no matches after the second left join,
// it must appear as a null-extended row with all right-hand columns null.
// If one of the right-hand columns comes from the inverted join, however,
// it might incorrectly show up as non-null (see #58892).
c.mapInvertedJoin(&invertedJoin, indexCols, newScanPrivate)
indexJoin.Input = c.e.f.ConstructInvertedJoin(
invertedJoin.Input,
invertedJoin.On,
&invertedJoin.InvertedJoinPrivate,
)
indexJoin.JoinType = joinType
indexJoin.Table = scanPrivate.Table
indexJoin.Index = cat.PrimaryIndex
indexJoin.KeyCols = c.getPkCols(invertedJoin.Table)
indexJoin.Cols = scanPrivate.Cols.Union(inputCols)
indexJoin.LookupColsAreTableKey = true
indexJoin.Locking = scanPrivate.Locking
if continuationCol != 0 {
indexJoin.IsSecondJoinInPairedJoiner = true
}
// If this is a semi- or anti-join, ensure the columns do not include any
// unneeded right-side columns.
if joinType == opt.SemiJoinOp || joinType == opt.AntiJoinOp {
indexJoin.Cols = inputCols.Union(indexJoin.On.OuterCols())
}
// Create the LookupJoin for the index join in the same group.
c.e.mem.AddLookupJoinToGroup(&indexJoin, grp)
})
}
// getPkCols gets the primary key columns for the given table as a ColList.
func (c *CustomFuncs) getPkCols(tabID opt.TableID) opt.ColList {
tab := c.e.mem.Metadata().Table(tabID)
pkIndex := tab.Index(cat.PrimaryIndex)
pkCols := make(opt.ColList, pkIndex.KeyColumnCount())
for i := range pkCols {
pkCols[i] = tabID.IndexColumnID(pkIndex, i)
}
return pkCols
}
// mapInvertedJoin maps the given inverted join to use the table and columns
// provided in newScanPrivate. The inverted join is modified in place. indexCols
// contains the pre-calculated index columns used by the given invertedJoin.
//
// Note that columns from the input are not mapped. For example, PrefixKeyCols
// does not need to be mapped below since it only contains input columns.
func (c *CustomFuncs) mapInvertedJoin(
invertedJoin *memo.InvertedJoinExpr, indexCols opt.ColSet, newScanPrivate *memo.ScanPrivate,
) {
tabID := invertedJoin.Table
newTabID := newScanPrivate.Table
// Get the catalog index (same for both new and old tables).
index := c.e.mem.Metadata().TableMeta(tabID).Table.Index(invertedJoin.Index)
// Though the index is marked as containing the column being indexed, it
// doesn't actually, and it is only valid to extract the primary key
// columns and non-inverted prefix columns from it.
newPkCols := c.getPkCols(newTabID)
newIndexCols := newPkCols.ToSet()
for i, n := 0, index.NonInvertedPrefixColumnCount(); i < n; i++ {
prefixCol := newTabID.IndexColumnID(index, i)
newIndexCols.Add(prefixCol)
}
// Create a map from the source columns to the destination columns,
// including the inverted source columns which will be used in the
// invertedExpr.
var srcColsToDstCols opt.ColMap
for srcCol, ok := indexCols.Next(0); ok; srcCol, ok = indexCols.Next(srcCol + 1) {
ord := tabID.ColumnOrdinal(srcCol)
dstCol := newTabID.ColumnID(ord)
srcColsToDstCols.Set(int(srcCol), int(dstCol))