-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
exhaust_physical_plans.go
2039 lines (1923 loc) · 76 KB
/
exhaust_physical_plans.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 2017 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"bytes"
"fmt"
"math"
"sort"
"github.com/pingcap/failpoint"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/expression/aggregation"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/planner/property"
"github.com/pingcap/tidb/planner/util"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/plancodec"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/set"
"go.uber.org/zap"
)
func (p *LogicalUnionScan) exhaustPhysicalPlans(prop *property.PhysicalProperty) ([]PhysicalPlan, bool) {
if prop.IsFlashOnlyProp() {
return nil, true
}
childProp := prop.Clone()
us := PhysicalUnionScan{
Conditions: p.conditions,
HandleCols: p.handleCols,
}.Init(p.ctx, p.stats, p.blockOffset, childProp)
return []PhysicalPlan{us}, true
}
func getMaxSortPrefix(sortCols, allCols []*expression.Column) []int {
tmpSchema := expression.NewSchema(allCols...)
sortColOffsets := make([]int, 0, len(sortCols))
for _, sortCol := range sortCols {
offset := tmpSchema.ColumnIndex(sortCol)
if offset == -1 {
return sortColOffsets
}
sortColOffsets = append(sortColOffsets, offset)
}
return sortColOffsets
}
func findMaxPrefixLen(candidates [][]*expression.Column, keys []*expression.Column) int {
maxLen := 0
for _, candidateKeys := range candidates {
matchedLen := 0
for i := range keys {
if i < len(candidateKeys) && keys[i].Equal(nil, candidateKeys[i]) {
matchedLen++
} else {
break
}
}
if matchedLen > maxLen {
maxLen = matchedLen
}
}
return maxLen
}
func (p *LogicalJoin) moveEqualToOtherConditions(offsets []int) []expression.Expression {
// Construct used equal condition set based on the equal condition offsets.
usedEqConds := set.NewIntSet()
for _, eqCondIdx := range offsets {
usedEqConds.Insert(eqCondIdx)
}
// Construct otherConds, which is composed of the original other conditions
// and the remained unused equal conditions.
numOtherConds := len(p.OtherConditions) + len(p.EqualConditions) - len(usedEqConds)
otherConds := make([]expression.Expression, len(p.OtherConditions), numOtherConds)
copy(otherConds, p.OtherConditions)
for eqCondIdx := range p.EqualConditions {
if !usedEqConds.Exist(eqCondIdx) {
otherConds = append(otherConds, p.EqualConditions[eqCondIdx])
}
}
return otherConds
}
// Only if the input required prop is the prefix fo join keys, we can pass through this property.
func (p *PhysicalMergeJoin) tryToGetChildReqProp(prop *property.PhysicalProperty) ([]*property.PhysicalProperty, bool) {
all, desc := prop.AllSameOrder()
lProp := property.NewPhysicalProperty(property.RootTaskType, p.LeftJoinKeys, desc, math.MaxFloat64, false)
rProp := property.NewPhysicalProperty(property.RootTaskType, p.RightJoinKeys, desc, math.MaxFloat64, false)
if !prop.IsEmpty() {
// sort merge join fits the cases of massive ordered data, so desc scan is always expensive.
if !all {
return nil, false
}
if !prop.IsPrefix(lProp) && !prop.IsPrefix(rProp) {
return nil, false
}
if prop.IsPrefix(rProp) && p.JoinType == LeftOuterJoin {
return nil, false
}
if prop.IsPrefix(lProp) && p.JoinType == RightOuterJoin {
return nil, false
}
}
return []*property.PhysicalProperty{lProp, rProp}, true
}
func (p *LogicalJoin) checkJoinKeyCollation(leftKeys, rightKeys []*expression.Column) bool {
// if a left key and its corresponding right key have different collation, don't use MergeJoin since
// the their children may sort their records in different ways
for i := range leftKeys {
lt := leftKeys[i].RetType
rt := rightKeys[i].RetType
if (lt.EvalType() == types.ETString && rt.EvalType() == types.ETString) &&
(leftKeys[i].RetType.Charset != rightKeys[i].RetType.Charset ||
leftKeys[i].RetType.Collate != rightKeys[i].RetType.Collate) {
return false
}
}
return true
}
// GetMergeJoin convert the logical join to physical merge join based on the physical property.
func (p *LogicalJoin) GetMergeJoin(prop *property.PhysicalProperty, schema *expression.Schema, statsInfo *property.StatsInfo, leftStatsInfo *property.StatsInfo, rightStatsInfo *property.StatsInfo) []PhysicalPlan {
joins := make([]PhysicalPlan, 0, len(p.leftProperties)+1)
// The leftProperties caches all the possible properties that are provided by its children.
leftJoinKeys, rightJoinKeys := p.GetJoinKeys()
for _, lhsChildProperty := range p.leftProperties {
offsets := getMaxSortPrefix(lhsChildProperty, leftJoinKeys)
if len(offsets) == 0 {
continue
}
leftKeys := lhsChildProperty[:len(offsets)]
rightKeys := expression.NewSchema(rightJoinKeys...).ColumnsByIndices(offsets)
prefixLen := findMaxPrefixLen(p.rightProperties, rightKeys)
if prefixLen == 0 {
continue
}
leftKeys = leftKeys[:prefixLen]
rightKeys = rightKeys[:prefixLen]
if !p.checkJoinKeyCollation(leftKeys, rightKeys) {
continue
}
offsets = offsets[:prefixLen]
baseJoin := basePhysicalJoin{
JoinType: p.JoinType,
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
DefaultValues: p.DefaultValues,
LeftJoinKeys: leftKeys,
RightJoinKeys: rightKeys,
}
mergeJoin := PhysicalMergeJoin{basePhysicalJoin: baseJoin}.Init(p.ctx, statsInfo.ScaleByExpectCnt(prop.ExpectedCnt), p.blockOffset)
mergeJoin.SetSchema(schema)
mergeJoin.OtherConditions = p.moveEqualToOtherConditions(offsets)
mergeJoin.initCompareFuncs()
if reqProps, ok := mergeJoin.tryToGetChildReqProp(prop); ok {
// Adjust expected count for children nodes.
if prop.ExpectedCnt < statsInfo.RowCount {
expCntScale := prop.ExpectedCnt / statsInfo.RowCount
reqProps[0].ExpectedCnt = leftStatsInfo.RowCount * expCntScale
reqProps[1].ExpectedCnt = rightStatsInfo.RowCount * expCntScale
}
mergeJoin.childrenReqProps = reqProps
_, desc := prop.AllSameOrder()
mergeJoin.Desc = desc
joins = append(joins, mergeJoin)
}
}
// If TiDB_SMJ hint is existed, it should consider enforce merge join,
// because we can't trust lhsChildProperty completely.
if (p.preferJoinType & preferMergeJoin) > 0 {
joins = append(joins, p.getEnforcedMergeJoin(prop, schema, statsInfo)...)
}
return joins
}
// Change JoinKeys order, by offsets array
// offsets array is generate by prop check
func getNewJoinKeysByOffsets(oldJoinKeys []*expression.Column, offsets []int) []*expression.Column {
newKeys := make([]*expression.Column, 0, len(oldJoinKeys))
for _, offset := range offsets {
newKeys = append(newKeys, oldJoinKeys[offset])
}
for pos, key := range oldJoinKeys {
isExist := false
for _, p := range offsets {
if p == pos {
isExist = true
break
}
}
if !isExist {
newKeys = append(newKeys, key)
}
}
return newKeys
}
func (p *LogicalJoin) getEnforcedMergeJoin(prop *property.PhysicalProperty, schema *expression.Schema, statsInfo *property.StatsInfo) []PhysicalPlan {
// Check whether SMJ can satisfy the required property
leftJoinKeys, rightJoinKeys := p.GetJoinKeys()
offsets := make([]int, 0, len(leftJoinKeys))
all, desc := prop.AllSameOrder()
if !all {
return nil
}
for _, item := range prop.Items {
isExist := false
for joinKeyPos := 0; joinKeyPos < len(leftJoinKeys); joinKeyPos++ {
var key *expression.Column
if item.Col.Equal(p.ctx, leftJoinKeys[joinKeyPos]) {
key = leftJoinKeys[joinKeyPos]
}
if item.Col.Equal(p.ctx, rightJoinKeys[joinKeyPos]) {
key = rightJoinKeys[joinKeyPos]
}
if key == nil {
continue
}
for i := 0; i < len(offsets); i++ {
if offsets[i] == joinKeyPos {
isExist = true
break
}
}
if !isExist {
offsets = append(offsets, joinKeyPos)
}
isExist = true
break
}
if !isExist {
return nil
}
}
// Generate the enforced sort merge join
leftKeys := getNewJoinKeysByOffsets(leftJoinKeys, offsets)
rightKeys := getNewJoinKeysByOffsets(rightJoinKeys, offsets)
otherConditions := make([]expression.Expression, len(p.OtherConditions), len(p.OtherConditions)+len(p.EqualConditions))
copy(otherConditions, p.OtherConditions)
if !p.checkJoinKeyCollation(leftKeys, rightKeys) {
// if the join keys' collation are conflicted, we use the empty join key
// and move EqualConditions to OtherConditions.
leftKeys = nil
rightKeys = nil
otherConditions = append(otherConditions, expression.ScalarFuncs2Exprs(p.EqualConditions)...)
}
lProp := property.NewPhysicalProperty(property.RootTaskType, leftKeys, desc, math.MaxFloat64, true)
rProp := property.NewPhysicalProperty(property.RootTaskType, rightKeys, desc, math.MaxFloat64, true)
baseJoin := basePhysicalJoin{
JoinType: p.JoinType,
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
DefaultValues: p.DefaultValues,
LeftJoinKeys: leftKeys,
RightJoinKeys: rightKeys,
OtherConditions: otherConditions,
}
enforcedPhysicalMergeJoin := PhysicalMergeJoin{basePhysicalJoin: baseJoin, Desc: desc}.Init(p.ctx, statsInfo.ScaleByExpectCnt(prop.ExpectedCnt), p.blockOffset)
enforcedPhysicalMergeJoin.SetSchema(schema)
enforcedPhysicalMergeJoin.childrenReqProps = []*property.PhysicalProperty{lProp, rProp}
enforcedPhysicalMergeJoin.initCompareFuncs()
return []PhysicalPlan{enforcedPhysicalMergeJoin}
}
func (p *PhysicalMergeJoin) initCompareFuncs() {
p.CompareFuncs = make([]expression.CompareFunc, 0, len(p.LeftJoinKeys))
for i := range p.LeftJoinKeys {
p.CompareFuncs = append(p.CompareFuncs, expression.GetCmpFunction(p.ctx, p.LeftJoinKeys[i], p.RightJoinKeys[i]))
}
}
// ForceUseOuterBuild4Test is a test option to control forcing use outer input as build.
// TODO: use hint and remove this variable
var ForceUseOuterBuild4Test = false
// ForcedHashLeftJoin4Test is a test option to force using HashLeftJoin
// TODO: use hint and remove this variable
var ForcedHashLeftJoin4Test = false
func (p *LogicalJoin) getHashJoins(prop *property.PhysicalProperty) []PhysicalPlan {
if !prop.IsEmpty() { // hash join doesn't promise any orders
return nil
}
joins := make([]PhysicalPlan, 0, 2)
switch p.JoinType {
case SemiJoin, AntiSemiJoin, LeftOuterSemiJoin, AntiLeftOuterSemiJoin:
joins = append(joins, p.getHashJoin(prop, 1, false))
case LeftOuterJoin:
if ForceUseOuterBuild4Test {
joins = append(joins, p.getHashJoin(prop, 1, true))
} else {
joins = append(joins, p.getHashJoin(prop, 1, false))
joins = append(joins, p.getHashJoin(prop, 1, true))
}
case RightOuterJoin:
if ForceUseOuterBuild4Test {
joins = append(joins, p.getHashJoin(prop, 0, true))
} else {
joins = append(joins, p.getHashJoin(prop, 0, false))
joins = append(joins, p.getHashJoin(prop, 0, true))
}
case InnerJoin:
if ForcedHashLeftJoin4Test {
joins = append(joins, p.getHashJoin(prop, 1, false))
} else {
joins = append(joins, p.getHashJoin(prop, 1, false))
joins = append(joins, p.getHashJoin(prop, 0, false))
}
}
return joins
}
func (p *LogicalJoin) getHashJoin(prop *property.PhysicalProperty, innerIdx int, useOuterToBuild bool) *PhysicalHashJoin {
chReqProps := make([]*property.PhysicalProperty, 2)
chReqProps[innerIdx] = &property.PhysicalProperty{ExpectedCnt: math.MaxFloat64}
chReqProps[1-innerIdx] = &property.PhysicalProperty{ExpectedCnt: math.MaxFloat64}
if prop.ExpectedCnt < p.stats.RowCount {
expCntScale := prop.ExpectedCnt / p.stats.RowCount
chReqProps[1-innerIdx].ExpectedCnt = p.children[1-innerIdx].statsInfo().RowCount * expCntScale
}
hashJoin := NewPhysicalHashJoin(p, innerIdx, useOuterToBuild, p.stats.ScaleByExpectCnt(prop.ExpectedCnt), chReqProps...)
hashJoin.SetSchema(p.schema)
return hashJoin
}
// When inner plan is TableReader, the parameter `ranges` will be nil. Because pk only have one column. So all of its range
// is generated during execution time.
func (p *LogicalJoin) constructIndexJoin(
prop *property.PhysicalProperty,
outerIdx int,
innerTask task,
ranges []*ranger.Range,
keyOff2IdxOff []int,
path *util.AccessPath,
compareFilters *ColWithCmpFuncManager,
) []PhysicalPlan {
joinType := p.JoinType
var (
innerJoinKeys []*expression.Column
outerJoinKeys []*expression.Column
)
if outerIdx == 0 {
outerJoinKeys, innerJoinKeys = p.GetJoinKeys()
} else {
innerJoinKeys, outerJoinKeys = p.GetJoinKeys()
}
chReqProps := make([]*property.PhysicalProperty, 2)
chReqProps[outerIdx] = &property.PhysicalProperty{TaskTp: property.RootTaskType, ExpectedCnt: math.MaxFloat64, Items: prop.Items}
if prop.ExpectedCnt < p.stats.RowCount {
expCntScale := prop.ExpectedCnt / p.stats.RowCount
chReqProps[outerIdx].ExpectedCnt = p.children[outerIdx].statsInfo().RowCount * expCntScale
}
newInnerKeys := make([]*expression.Column, 0, len(innerJoinKeys))
newOuterKeys := make([]*expression.Column, 0, len(outerJoinKeys))
newKeyOff := make([]int, 0, len(keyOff2IdxOff))
newOtherConds := make([]expression.Expression, len(p.OtherConditions), len(p.OtherConditions)+len(p.EqualConditions))
copy(newOtherConds, p.OtherConditions)
for keyOff, idxOff := range keyOff2IdxOff {
if keyOff2IdxOff[keyOff] < 0 {
newOtherConds = append(newOtherConds, p.EqualConditions[keyOff])
continue
}
newInnerKeys = append(newInnerKeys, innerJoinKeys[keyOff])
newOuterKeys = append(newOuterKeys, outerJoinKeys[keyOff])
newKeyOff = append(newKeyOff, idxOff)
}
baseJoin := basePhysicalJoin{
InnerChildIdx: 1 - outerIdx,
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
OtherConditions: newOtherConds,
JoinType: joinType,
OuterJoinKeys: newOuterKeys,
InnerJoinKeys: newInnerKeys,
DefaultValues: p.DefaultValues,
}
join := PhysicalIndexJoin{
basePhysicalJoin: baseJoin,
innerTask: innerTask,
KeyOff2IdxOff: newKeyOff,
Ranges: ranges,
CompareFilters: compareFilters,
}.Init(p.ctx, p.stats.ScaleByExpectCnt(prop.ExpectedCnt), p.blockOffset, chReqProps...)
if path != nil {
join.IdxColLens = path.IdxColLens
}
join.SetSchema(p.schema)
return []PhysicalPlan{join}
}
func (p *LogicalJoin) constructIndexMergeJoin(
prop *property.PhysicalProperty,
outerIdx int,
innerTask task,
ranges []*ranger.Range,
keyOff2IdxOff []int,
path *util.AccessPath,
compareFilters *ColWithCmpFuncManager,
) []PhysicalPlan {
indexJoins := p.constructIndexJoin(prop, outerIdx, innerTask, ranges, keyOff2IdxOff, path, compareFilters)
indexMergeJoins := make([]PhysicalPlan, 0, len(indexJoins))
for _, plan := range indexJoins {
join := plan.(*PhysicalIndexJoin)
hasPrefixCol := false
for _, l := range join.IdxColLens {
if l != types.UnspecifiedLength {
hasPrefixCol = true
break
}
}
// If index column has prefix length, the merge join can not guarantee the relevance
// between index and join keys. So we should skip this case.
// For more details, please check the following code and comments.
if hasPrefixCol {
continue
}
// keyOff2KeyOffOrderByIdx is map the join keys offsets to [0, len(joinKeys)) ordered by the
// join key position in inner index.
keyOff2KeyOffOrderByIdx := make([]int, len(join.OuterJoinKeys))
keyOffMapList := make([]int, len(join.KeyOff2IdxOff))
copy(keyOffMapList, join.KeyOff2IdxOff)
keyOffMap := make(map[int]int, len(keyOffMapList))
for i, idxOff := range keyOffMapList {
keyOffMap[idxOff] = i
}
sort.Slice(keyOffMapList, func(i, j int) bool { return keyOffMapList[i] < keyOffMapList[j] })
keyIsIndexPrefix := true
for keyOff, idxOff := range keyOffMapList {
if keyOff != idxOff {
keyIsIndexPrefix = false
break
}
keyOff2KeyOffOrderByIdx[keyOffMap[idxOff]] = keyOff
}
if !keyIsIndexPrefix {
continue
}
// isOuterKeysPrefix means whether the outer join keys are the prefix of the prop items.
isOuterKeysPrefix := len(join.OuterJoinKeys) <= len(prop.Items)
compareFuncs := make([]expression.CompareFunc, 0, len(join.OuterJoinKeys))
outerCompareFuncs := make([]expression.CompareFunc, 0, len(join.OuterJoinKeys))
for i := range join.KeyOff2IdxOff {
if isOuterKeysPrefix && !prop.Items[i].Col.Equal(nil, join.OuterJoinKeys[keyOff2KeyOffOrderByIdx[i]]) {
isOuterKeysPrefix = false
}
compareFuncs = append(compareFuncs, expression.GetCmpFunction(p.ctx, join.OuterJoinKeys[i], join.InnerJoinKeys[i]))
outerCompareFuncs = append(outerCompareFuncs, expression.GetCmpFunction(p.ctx, join.OuterJoinKeys[i], join.OuterJoinKeys[i]))
}
// canKeepOuterOrder means whether the prop items are the prefix of the outer join keys.
canKeepOuterOrder := len(prop.Items) <= len(join.OuterJoinKeys)
for i := 0; canKeepOuterOrder && i < len(prop.Items); i++ {
if !prop.Items[i].Col.Equal(nil, join.OuterJoinKeys[keyOff2KeyOffOrderByIdx[i]]) {
canKeepOuterOrder = false
}
}
// Since index merge join requires prop items the prefix of outer join keys
// or outer join keys the prefix of the prop items. So we need `canKeepOuterOrder` or
// `isOuterKeysPrefix` to be true.
if canKeepOuterOrder || isOuterKeysPrefix {
indexMergeJoin := PhysicalIndexMergeJoin{
PhysicalIndexJoin: *join,
KeyOff2KeyOffOrderByIdx: keyOff2KeyOffOrderByIdx,
NeedOuterSort: !isOuterKeysPrefix,
CompareFuncs: compareFuncs,
OuterCompareFuncs: outerCompareFuncs,
Desc: !prop.IsEmpty() && prop.Items[0].Desc,
}.Init(p.ctx)
indexMergeJoins = append(indexMergeJoins, indexMergeJoin)
}
}
return indexMergeJoins
}
func (p *LogicalJoin) constructIndexHashJoin(
prop *property.PhysicalProperty,
outerIdx int,
innerTask task,
ranges []*ranger.Range,
keyOff2IdxOff []int,
path *util.AccessPath,
compareFilters *ColWithCmpFuncManager,
) []PhysicalPlan {
indexJoins := p.constructIndexJoin(prop, outerIdx, innerTask, ranges, keyOff2IdxOff, path, compareFilters)
indexHashJoins := make([]PhysicalPlan, 0, len(indexJoins))
for _, plan := range indexJoins {
join := plan.(*PhysicalIndexJoin)
indexHashJoin := PhysicalIndexHashJoin{
PhysicalIndexJoin: *join,
// Prop is empty means that the parent operator does not need the
// join operator to provide any promise of the output order.
KeepOuterOrder: !prop.IsEmpty(),
}.Init(p.ctx)
indexHashJoins = append(indexHashJoins, indexHashJoin)
}
return indexHashJoins
}
// getIndexJoinByOuterIdx will generate index join by outerIndex. OuterIdx points out the outer child.
// First of all, we'll check whether the inner child is DataSource.
// Then, we will extract the join keys of p's equal conditions. Then check whether all of them are just the primary key
// or match some part of on index. If so we will choose the best one and construct a index join.
func (p *LogicalJoin) getIndexJoinByOuterIdx(prop *property.PhysicalProperty, outerIdx int) (joins []PhysicalPlan) {
outerChild, innerChild := p.children[outerIdx], p.children[1-outerIdx]
all, _ := prop.AllSameOrder()
// If the order by columns are not all from outer child, index join cannot promise the order.
if !prop.AllColsFromSchema(outerChild.Schema()) || !all {
return nil
}
var (
innerJoinKeys []*expression.Column
outerJoinKeys []*expression.Column
)
if outerIdx == 0 {
outerJoinKeys, innerJoinKeys = p.GetJoinKeys()
} else {
innerJoinKeys, outerJoinKeys = p.GetJoinKeys()
}
ds, isDataSource := innerChild.(*DataSource)
us, isUnionScan := innerChild.(*LogicalUnionScan)
if (!isDataSource && !isUnionScan) || (isDataSource && ds.preferStoreType&preferTiFlash != 0) {
return nil
}
if isUnionScan {
// The child of union scan may be union all for partition table.
ds, isDataSource = us.Children()[0].(*DataSource)
if !isDataSource {
return nil
}
// If one of the union scan children is a TiFlash table, then we can't choose index join.
for _, child := range us.Children() {
if ds, ok := child.(*DataSource); ok && ds.preferStoreType&preferTiFlash != 0 {
return nil
}
}
}
var avgInnerRowCnt float64
if outerChild.statsInfo().RowCount > 0 {
avgInnerRowCnt = p.equalCondOutCnt / outerChild.statsInfo().RowCount
}
joins = p.buildIndexJoinInner2TableScan(prop, ds, innerJoinKeys, outerJoinKeys, outerIdx, us, avgInnerRowCnt)
if joins != nil {
return
}
return p.buildIndexJoinInner2IndexScan(prop, ds, innerJoinKeys, outerJoinKeys, outerIdx, us, avgInnerRowCnt)
}
func (p *LogicalJoin) getIndexJoinBuildHelper(ds *DataSource, innerJoinKeys []*expression.Column,
checkPathValid func(path *util.AccessPath) bool) (*indexJoinBuildHelper, []int) {
helper := &indexJoinBuildHelper{join: p}
for _, path := range ds.possibleAccessPaths {
if checkPathValid(path) {
emptyRange, err := helper.analyzeLookUpFilters(path, ds, innerJoinKeys)
if emptyRange {
return nil, nil
}
if err != nil {
logutil.BgLogger().Warn("build index join failed", zap.Error(err))
}
}
}
if helper.chosenPath == nil {
return nil, nil
}
keyOff2IdxOff := make([]int, len(innerJoinKeys))
for i := range keyOff2IdxOff {
keyOff2IdxOff[i] = -1
}
for idxOff, keyOff := range helper.idxOff2KeyOff {
if keyOff != -1 {
keyOff2IdxOff[keyOff] = idxOff
}
}
return helper, keyOff2IdxOff
}
// buildIndexJoinInner2TableScan builds a TableScan as the inner child for an
// IndexJoin if possible.
// If the inner side of a index join is a TableScan, only one tuple will be
// fetched from the inner side for every tuple from the outer side. This will be
// promised to be no worse than building IndexScan as the inner child.
func (p *LogicalJoin) buildIndexJoinInner2TableScan(
prop *property.PhysicalProperty, ds *DataSource, innerJoinKeys, outerJoinKeys []*expression.Column,
outerIdx int, us *LogicalUnionScan, avgInnerRowCnt float64) (joins []PhysicalPlan) {
var tblPath *util.AccessPath
for _, path := range ds.possibleAccessPaths {
if path.IsTablePath() && path.StoreType == kv.TiKV {
tblPath = path
break
}
}
if tblPath == nil {
return nil
}
keyOff2IdxOff := make([]int, len(innerJoinKeys))
newOuterJoinKeys := make([]*expression.Column, 0)
var ranges []*ranger.Range
var innerTask, innerTask2 task
var helper *indexJoinBuildHelper
if ds.tableInfo.IsCommonHandle {
helper, keyOff2IdxOff = p.getIndexJoinBuildHelper(ds, innerJoinKeys, func(path *util.AccessPath) bool { return path.IsCommonHandlePath })
if helper == nil {
return nil
}
innerTask = p.constructInnerTableScanTask(ds, nil, outerJoinKeys, us, false, false, avgInnerRowCnt)
// The index merge join's inner plan is different from index join, so we
// should construct another inner plan for it.
// Because we can't keep order for union scan, if there is a union scan in inner task,
// we can't construct index merge join.
if us == nil {
innerTask2 = p.constructInnerTableScanTask(ds, nil, outerJoinKeys, us, true, !prop.IsEmpty() && prop.Items[0].Desc, avgInnerRowCnt)
}
ranges = helper.chosenRanges
} else {
pkMatched := false
pkCol := ds.getPKIsHandleCol()
if pkCol == nil {
return nil
}
for i, key := range innerJoinKeys {
if !key.Equal(nil, pkCol) {
keyOff2IdxOff[i] = -1
continue
}
pkMatched = true
keyOff2IdxOff[i] = 0
// Add to newOuterJoinKeys only if conditions contain inner primary key. For issue #14822.
newOuterJoinKeys = append(newOuterJoinKeys, outerJoinKeys[i])
}
outerJoinKeys = newOuterJoinKeys
if !pkMatched {
return nil
}
innerTask = p.constructInnerTableScanTask(ds, pkCol, outerJoinKeys, us, false, false, avgInnerRowCnt)
// The index merge join's inner plan is different from index join, so we
// should construct another inner plan for it.
// Because we can't keep order for union scan, if there is a union scan in inner task,
// we can't construct index merge join.
if us == nil {
innerTask2 = p.constructInnerTableScanTask(ds, pkCol, outerJoinKeys, us, true, !prop.IsEmpty() && prop.Items[0].Desc, avgInnerRowCnt)
}
}
joins = make([]PhysicalPlan, 0, 3)
failpoint.Inject("MockOnlyEnableIndexHashJoin", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(p.constructIndexHashJoin(prop, outerIdx, innerTask, nil, keyOff2IdxOff, nil, nil))
}
})
joins = append(joins, p.constructIndexJoin(prop, outerIdx, innerTask, ranges, keyOff2IdxOff, nil, nil)...)
// We can reuse the `innerTask` here since index nested loop hash join
// do not need the inner child to promise the order.
joins = append(joins, p.constructIndexHashJoin(prop, outerIdx, innerTask, ranges, keyOff2IdxOff, nil, nil)...)
if innerTask2 != nil {
joins = append(joins, p.constructIndexMergeJoin(prop, outerIdx, innerTask2, ranges, keyOff2IdxOff, nil, nil)...)
}
return joins
}
func (p *LogicalJoin) buildIndexJoinInner2IndexScan(
prop *property.PhysicalProperty, ds *DataSource, innerJoinKeys, outerJoinKeys []*expression.Column,
outerIdx int, us *LogicalUnionScan, avgInnerRowCnt float64) (joins []PhysicalPlan) {
helper, keyOff2IdxOff := p.getIndexJoinBuildHelper(ds, innerJoinKeys, func(path *util.AccessPath) bool { return !path.IsTablePath() })
if helper == nil {
return nil
}
joins = make([]PhysicalPlan, 0, 3)
rangeInfo := helper.buildRangeDecidedByInformation(helper.chosenPath.IdxCols, outerJoinKeys)
maxOneRow := false
if helper.chosenPath.Index.Unique && helper.maxUsedCols == len(helper.chosenPath.FullIdxCols) {
l := len(helper.chosenAccess)
if l == 0 {
maxOneRow = true
} else {
sf, ok := helper.chosenAccess[l-1].(*expression.ScalarFunction)
maxOneRow = ok && (sf.FuncName.L == ast.EQ)
}
}
innerTask := p.constructInnerIndexScanTask(ds, helper.chosenPath, helper.chosenRemained, outerJoinKeys, us, rangeInfo, false, false, avgInnerRowCnt, maxOneRow)
failpoint.Inject("MockOnlyEnableIndexHashJoin", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(p.constructIndexHashJoin(prop, outerIdx, innerTask, helper.chosenRanges, keyOff2IdxOff, helper.chosenPath, helper.lastColManager))
}
})
joins = append(joins, p.constructIndexJoin(prop, outerIdx, innerTask, helper.chosenRanges, keyOff2IdxOff, helper.chosenPath, helper.lastColManager)...)
// We can reuse the `innerTask` here since index nested loop hash join
// do not need the inner child to promise the order.
joins = append(joins, p.constructIndexHashJoin(prop, outerIdx, innerTask, helper.chosenRanges, keyOff2IdxOff, helper.chosenPath, helper.lastColManager)...)
// The index merge join's inner plan is different from index join, so we
// should construct another inner plan for it.
// Because we can't keep order for union scan, if there is a union scan in inner task,
// we can't construct index merge join.
if us == nil {
innerTask2 := p.constructInnerIndexScanTask(ds, helper.chosenPath, helper.chosenRemained, outerJoinKeys, us, rangeInfo, true, !prop.IsEmpty() && prop.Items[0].Desc, avgInnerRowCnt, maxOneRow)
joins = append(joins, p.constructIndexMergeJoin(prop, outerIdx, innerTask2, helper.chosenRanges, keyOff2IdxOff, helper.chosenPath, helper.lastColManager)...)
}
return joins
}
type indexJoinBuildHelper struct {
join *LogicalJoin
chosenIndexInfo *model.IndexInfo
maxUsedCols int
chosenAccess []expression.Expression
chosenRemained []expression.Expression
idxOff2KeyOff []int
lastColManager *ColWithCmpFuncManager
chosenRanges []*ranger.Range
chosenPath *util.AccessPath
curPossibleUsedKeys []*expression.Column
curNotUsedIndexCols []*expression.Column
curNotUsedColLens []int
curIdxOff2KeyOff []int
}
func (ijHelper *indexJoinBuildHelper) buildRangeDecidedByInformation(idxCols []*expression.Column, outerJoinKeys []*expression.Column) string {
buffer := bytes.NewBufferString("[")
isFirst := true
for idxOff, keyOff := range ijHelper.idxOff2KeyOff {
if keyOff == -1 {
continue
}
if !isFirst {
buffer.WriteString(" ")
} else {
isFirst = false
}
buffer.WriteString(fmt.Sprintf("eq(%v, %v)", idxCols[idxOff], outerJoinKeys[keyOff]))
}
for _, access := range ijHelper.chosenAccess {
if !isFirst {
buffer.WriteString(" ")
} else {
isFirst = false
}
buffer.WriteString(fmt.Sprintf("%v", access))
}
buffer.WriteString("]")
return buffer.String()
}
// constructInnerTableScanTask is specially used to construct the inner plan for PhysicalIndexJoin.
func (p *LogicalJoin) constructInnerTableScanTask(
ds *DataSource,
pk *expression.Column,
outerJoinKeys []*expression.Column,
us *LogicalUnionScan,
keepOrder bool,
desc bool,
rowCount float64,
) task {
var ranges []*ranger.Range
// pk is nil means the table uses the common handle.
if pk == nil {
ranges = ranger.FullRange()
} else {
ranges = ranger.FullIntRange(mysql.HasUnsignedFlag(pk.RetType.Flag))
}
ts := PhysicalTableScan{
Table: ds.tableInfo,
Columns: ds.Columns,
TableAsName: ds.TableAsName,
DBName: ds.DBName,
filterCondition: ds.pushedDownConds,
Ranges: ranges,
rangeDecidedBy: outerJoinKeys,
KeepOrder: keepOrder,
Desc: desc,
}.Init(ds.ctx, ds.blockOffset)
ts.SetSchema(ds.schema.Clone())
if rowCount <= 0 {
rowCount = float64(1)
}
selectivity := float64(1)
countAfterAccess := rowCount
if len(ts.filterCondition) > 0 {
var err error
selectivity, _, err = ds.tableStats.HistColl.Selectivity(ds.ctx, ts.filterCondition, ds.possibleAccessPaths)
if err != nil || selectivity <= 0 {
logutil.BgLogger().Debug("unexpected selectivity, use selection factor", zap.Float64("selectivity", selectivity), zap.String("table", ts.TableAsName.L))
selectivity = SelectionFactor
}
// rowCount is computed from result row count of join, which has already accounted the filters on DataSource,
// i.e, rowCount equals to `countAfterAccess * selectivity`.
countAfterAccess = rowCount / selectivity
}
ts.stats = &property.StatsInfo{
// TableScan as inner child of IndexJoin can return at most 1 tuple for each outer row.
RowCount: math.Min(1.0, countAfterAccess),
StatsVersion: ds.stats.StatsVersion,
// Cardinality would not be used in cost computation of IndexJoin, set leave it as default nil.
}
rowSize := ds.TblColHists.GetTableAvgRowSize(p.ctx, ds.TblCols, ts.StoreType, true)
sessVars := ds.ctx.GetSessionVars()
copTask := &copTask{
tablePlan: ts,
indexPlanFinished: true,
cst: sessVars.ScanFactor * rowSize * ts.stats.RowCount,
tblColHists: ds.TblColHists,
keepOrder: ts.KeepOrder,
}
selStats := ts.stats.Scale(selectivity)
ts.addPushedDownSelection(copTask, selStats)
t := finishCopTask(ds.ctx, copTask).(*rootTask)
reader := t.p
t.p = p.constructInnerUnionScan(us, reader)
return t
}
func (p *LogicalJoin) constructInnerUnionScan(us *LogicalUnionScan, reader PhysicalPlan) PhysicalPlan {
if us == nil {
return reader
}
// Use `reader.stats` instead of `us.stats` because it should be more accurate. No need to specify
// childrenReqProps now since we have got reader already.
physicalUnionScan := PhysicalUnionScan{
Conditions: us.conditions,
HandleCols: us.handleCols,
}.Init(us.ctx, reader.statsInfo(), us.blockOffset, nil)
physicalUnionScan.SetChildren(reader)
return physicalUnionScan
}
// constructInnerIndexScanTask is specially used to construct the inner plan for PhysicalIndexJoin.
func (p *LogicalJoin) constructInnerIndexScanTask(
ds *DataSource,
path *util.AccessPath,
filterConds []expression.Expression,
outerJoinKeys []*expression.Column,
us *LogicalUnionScan,
rangeInfo string,
keepOrder bool,
desc bool,
rowCount float64,
maxOneRow bool,
) task {
is := PhysicalIndexScan{
Table: ds.tableInfo,
TableAsName: ds.TableAsName,
DBName: ds.DBName,
Columns: ds.Columns,
Index: path.Index,
IdxCols: path.IdxCols,
IdxColLens: path.IdxColLens,
dataSourceSchema: ds.schema,
KeepOrder: keepOrder,
Ranges: ranger.FullRange(),
rangeInfo: rangeInfo,
Desc: desc,
isPartition: ds.isPartition,
physicalTableID: ds.physicalTableID,
}.Init(ds.ctx, ds.blockOffset)
cop := &copTask{
indexPlan: is,
tblColHists: ds.TblColHists,
tblCols: ds.TblCols,
keepOrder: is.KeepOrder,
}
if !ds.isCoveringIndex(ds.schema.Columns, path.FullIdxCols, path.FullIdxColLens, is.Table) {
// On this way, it's double read case.
ts := PhysicalTableScan{
Columns: ds.Columns,
Table: is.Table,
TableAsName: ds.TableAsName,
isPartition: ds.isPartition,
physicalTableID: ds.physicalTableID,
}.Init(ds.ctx, ds.blockOffset)
ts.schema = is.dataSourceSchema.Clone()
if ds.tableInfo.IsCommonHandle {
cop.commonHandleCols = ds.commonHandleCols
}
// If inner cop task need keep order, the extraHandleCol should be set.
if cop.keepOrder {
cop.extraHandleCol, cop.doubleReadNeedProj = ts.appendExtraHandleCol(ds)
}
cop.tablePlan = ts
}
is.initSchema(append(path.FullIdxCols, ds.commonHandleCols...), cop.tablePlan != nil)
indexConds, tblConds := ds.splitIndexFilterConditions(filterConds, path.FullIdxCols, path.FullIdxColLens, ds.tableInfo)
// Specially handle cases when input rowCount is 0, which can only happen in 2 scenarios:
// - estimated row count of outer plan is 0;
// - estimated row count of inner "DataSource + filters" is 0;
// if it is the first case, it does not matter what row count we set for inner task, since the cost of index join would
// always be 0 then;
// if it is the second case, HashJoin should always be cheaper than IndexJoin then, so we set row count of inner task
// to table size, to simply make it more expensive.
if rowCount <= 0 {
rowCount = ds.tableStats.RowCount
}
if maxOneRow {
// Theoretically, this line is unnecessary because row count estimation of join should guarantee rowCount is not larger
// than 1.0; however, there may be rowCount larger than 1.0 in reality, e.g, pseudo statistics cases, which does not reflect
// unique constraint in NDV.
rowCount = math.Min(rowCount, 1.0)
}
tmpPath := &util.AccessPath{
IndexFilters: indexConds,
TableFilters: tblConds,
CountAfterIndex: rowCount,
CountAfterAccess: rowCount,
}
// Assume equal conditions used by index join and other conditions are independent.
if len(tblConds) > 0 {
selectivity, _, err := ds.tableStats.HistColl.Selectivity(ds.ctx, tblConds, ds.possibleAccessPaths)
if err != nil || selectivity <= 0 {
logutil.BgLogger().Debug("unexpected selectivity, use selection factor", zap.Float64("selectivity", selectivity), zap.String("table", ds.TableAsName.L))
selectivity = SelectionFactor
}
// rowCount is computed from result row count of join, which has already accounted the filters on DataSource,
// i.e, rowCount equals to `countAfterIndex * selectivity`.
cnt := rowCount / selectivity
if maxOneRow {
cnt = math.Min(cnt, 1.0)
}
tmpPath.CountAfterIndex = cnt
tmpPath.CountAfterAccess = cnt
}
if len(indexConds) > 0 {
selectivity, _, err := ds.tableStats.HistColl.Selectivity(ds.ctx, indexConds, ds.possibleAccessPaths)
if err != nil || selectivity <= 0 {
logutil.BgLogger().Debug("unexpected selectivity, use selection factor", zap.Float64("selectivity", selectivity), zap.String("table", ds.TableAsName.L))
selectivity = SelectionFactor
}
cnt := tmpPath.CountAfterIndex / selectivity
if maxOneRow {
cnt = math.Min(cnt, 1.0)
}
tmpPath.CountAfterAccess = cnt
}
is.stats = ds.tableStats.ScaleByExpectCnt(tmpPath.CountAfterAccess)
rowSize := is.indexScanRowSize(path.Index, ds, true)
sessVars := ds.ctx.GetSessionVars()
cop.cst = tmpPath.CountAfterAccess * rowSize * sessVars.ScanFactor
finalStats := ds.tableStats.ScaleByExpectCnt(rowCount)
is.addPushedDownSelection(cop, ds, tmpPath, finalStats)
t := finishCopTask(ds.ctx, cop).(*rootTask)
reader := t.p
t.p = p.constructInnerUnionScan(us, reader)
return t
}
var symmetricOp = map[string]string{
ast.LT: ast.GT,
ast.GE: ast.LE,
ast.GT: ast.LT,
ast.LE: ast.GE,
}
// ColWithCmpFuncManager is used in index join to handle the column with compare functions(>=, >, <, <=).
// It stores the compare functions and build ranges in execution phase.
type ColWithCmpFuncManager struct {
TargetCol *expression.Column
colLength int
OpType []string
opArg []expression.Expression
TmpConstant []*expression.Constant
affectedColSchema *expression.Schema
compareFuncs []chunk.CompareFunc
}
func (cwc *ColWithCmpFuncManager) appendNewExpr(opName string, arg expression.Expression, affectedCols []*expression.Column) {
cwc.OpType = append(cwc.OpType, opName)
cwc.opArg = append(cwc.opArg, arg)
cwc.TmpConstant = append(cwc.TmpConstant, &expression.Constant{RetType: cwc.TargetCol.RetType})
for _, col := range affectedCols {
if cwc.affectedColSchema.Contains(col) {
continue
}
cwc.compareFuncs = append(cwc.compareFuncs, chunk.GetCompareFunc(col.RetType))
cwc.affectedColSchema.Append(col)