-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
exhaust_physical_plans.go
3000 lines (2824 loc) · 120 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,
// 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 core
import (
"fmt"
"math"
"slices"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/expression/aggregation"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/planner/cardinality"
"github.com/pingcap/tidb/pkg/planner/core/base"
"github.com/pingcap/tidb/pkg/planner/core/cost"
"github.com/pingcap/tidb/pkg/planner/core/operator/logicalop"
"github.com/pingcap/tidb/pkg/planner/property"
"github.com/pingcap/tidb/pkg/planner/util"
"github.com/pingcap/tidb/pkg/planner/util/fixcontrol"
"github.com/pingcap/tidb/pkg/statistics"
"github.com/pingcap/tidb/pkg/types"
h "github.com/pingcap/tidb/pkg/util/hint"
"github.com/pingcap/tidb/pkg/util/logutil"
"github.com/pingcap/tidb/pkg/util/plancodec"
"github.com/pingcap/tidb/pkg/util/ranger"
"github.com/pingcap/tidb/pkg/util/set"
"github.com/pingcap/tipb/go-tipb"
"go.uber.org/zap"
)
func exhaustPhysicalPlans4LogicalUnionScan(p *LogicalUnionScan, prop *property.PhysicalProperty) ([]base.PhysicalPlan, bool, error) {
if prop.IsFlashProp() {
p.SCtx().GetSessionVars().RaiseWarningWhenMPPEnforced(
"MPP mode may be blocked because operator `UnionScan` is not supported now.")
return nil, true, nil
}
childProp := prop.CloneEssentialFields()
us := PhysicalUnionScan{
Conditions: p.Conditions,
HandleCols: p.HandleCols,
}.Init(p.SCtx(), p.StatsInfo(), p.QueryBlockOffset(), childProp)
return []base.PhysicalPlan{us}, true, nil
}
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].EqualColumn(candidateKeys[i])) {
break
}
matchedLen++
}
if matchedLen > maxLen {
maxLen = matchedLen
}
}
return maxLen
}
func moveEqualToOtherConditions(p *LogicalJoin, 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)
lProp.CTEProducerStatus = prop.CTEProducerStatus
rProp.CTEProducerStatus = prop.CTEProducerStatus
if !prop.IsSortItemEmpty() {
// 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 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.GetCharset() != rightKeys[i].RetType.GetCharset() ||
leftKeys[i].RetType.GetCollate() != rightKeys[i].RetType.GetCollate()) {
return false
}
}
return true
}
// GetMergeJoin convert the logical join to physical merge join based on the physical property.
func GetMergeJoin(p *LogicalJoin, prop *property.PhysicalProperty, schema *expression.Schema, statsInfo *property.StatsInfo, leftStatsInfo *property.StatsInfo, rightStatsInfo *property.StatsInfo) []base.PhysicalPlan {
joins := make([]base.PhysicalPlan, 0, len(p.LeftProperties)+1)
// The LeftProperties caches all the possible properties that are provided by its children.
leftJoinKeys, rightJoinKeys, isNullEQ, hasNullEQ := p.GetJoinKeys()
// EnumType/SetType Unsupported: merge join conflicts with index order.
// ref: https://github.com/pingcap/tidb/issues/24473, https://github.com/pingcap/tidb/issues/25669
for _, leftKey := range leftJoinKeys {
if leftKey.RetType.GetType() == mysql.TypeEnum || leftKey.RetType.GetType() == mysql.TypeSet {
return nil
}
}
for _, rightKey := range rightJoinKeys {
if rightKey.RetType.GetType() == mysql.TypeEnum || rightKey.RetType.GetType() == mysql.TypeSet {
return nil
}
}
// TODO: support null equal join keys for merge join
if hasNullEQ {
return nil
}
for _, lhsChildProperty := range p.LeftProperties {
offsets := util.GetMaxSortPrefix(lhsChildProperty, leftJoinKeys)
// If not all equal conditions hit properties. We ban merge join heuristically. Because in this case, merge join
// may get a very low performance. In executor, executes join results before other conditions filter it.
if len(offsets) < len(leftJoinKeys) {
continue
}
leftKeys := lhsChildProperty[:len(offsets)]
rightKeys := expression.NewSchema(rightJoinKeys...).ColumnsByIndices(offsets)
newIsNullEQ := make([]bool, 0, len(offsets))
for _, offset := range offsets {
newIsNullEQ = append(newIsNullEQ, isNullEQ[offset])
}
prefixLen := findMaxPrefixLen(p.RightProperties, rightKeys)
if prefixLen == 0 {
continue
}
leftKeys = leftKeys[:prefixLen]
rightKeys = rightKeys[:prefixLen]
newIsNullEQ = newIsNullEQ[:prefixLen]
if !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,
IsNullEQ: newIsNullEQ,
}
mergeJoin := PhysicalMergeJoin{basePhysicalJoin: baseJoin}.Init(p.SCtx(), statsInfo.ScaleByExpectCnt(prop.ExpectedCnt), p.QueryBlockOffset())
mergeJoin.SetSchema(schema)
mergeJoin.OtherConditions = moveEqualToOtherConditions(p, 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 p.PreferJoinType&h.PreferNoMergeJoin > 0 {
if p.PreferJoinType&h.PreferMergeJoin == 0 {
return nil
}
p.SCtx().GetSessionVars().StmtCtx.SetHintWarning(
"Some MERGE_JOIN and NO_MERGE_JOIN hints conflict, NO_MERGE_JOIN is ignored")
}
// If TiDB_SMJ hint is existed, it should consider enforce merge join,
// because we can't trust lhsChildProperty completely.
if (p.PreferJoinType&h.PreferMergeJoin) > 0 ||
shouldSkipHashJoin(p) { // if hash join is not allowed, generate as many other types of join as possible to avoid 'cant-find-plan' error.
joins = append(joins, getEnforcedMergeJoin(p, 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 getNewNullEQByOffsets(oldNullEQ []bool, offsets []int) []bool {
newNullEQ := make([]bool, 0, len(oldNullEQ))
for _, offset := range offsets {
newNullEQ = append(newNullEQ, oldNullEQ[offset])
}
for pos, key := range oldNullEQ {
isExist := false
for _, p := range offsets {
if p == pos {
isExist = true
break
}
}
if !isExist {
newNullEQ = append(newNullEQ, key)
}
}
return newNullEQ
}
func getEnforcedMergeJoin(p *LogicalJoin, prop *property.PhysicalProperty, schema *expression.Schema, statsInfo *property.StatsInfo) []base.PhysicalPlan {
// Check whether SMJ can satisfy the required property
leftJoinKeys, rightJoinKeys, isNullEQ, hasNullEQ := p.GetJoinKeys()
// TODO: support null equal join keys for merge join
if hasNullEQ {
return nil
}
offsets := make([]int, 0, len(leftJoinKeys))
all, desc := prop.AllSameOrder()
if !all {
return nil
}
evalCtx := p.SCtx().GetExprCtx().GetEvalCtx()
for _, item := range prop.SortItems {
isExist, hasLeftColInProp, hasRightColInProp := false, false, false
for joinKeyPos := 0; joinKeyPos < len(leftJoinKeys); joinKeyPos++ {
var key *expression.Column
if item.Col.Equal(evalCtx, leftJoinKeys[joinKeyPos]) {
key = leftJoinKeys[joinKeyPos]
hasLeftColInProp = true
}
if item.Col.Equal(evalCtx, rightJoinKeys[joinKeyPos]) {
key = rightJoinKeys[joinKeyPos]
hasRightColInProp = true
}
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
}
// If the output wants the order of the inner side. We should reject it since we might add null-extend rows of that side.
if p.JoinType == LeftOuterJoin && hasRightColInProp {
return nil
}
if p.JoinType == RightOuterJoin && hasLeftColInProp {
return nil
}
}
// Generate the enforced sort merge join
leftKeys := getNewJoinKeysByOffsets(leftJoinKeys, offsets)
rightKeys := getNewJoinKeysByOffsets(rightJoinKeys, offsets)
newNullEQ := getNewNullEQByOffsets(isNullEQ, offsets)
otherConditions := make([]expression.Expression, len(p.OtherConditions), len(p.OtherConditions)+len(p.EqualConditions))
copy(otherConditions, p.OtherConditions)
if !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
newNullEQ = 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,
IsNullEQ: newNullEQ,
OtherConditions: otherConditions,
}
enforcedPhysicalMergeJoin := PhysicalMergeJoin{basePhysicalJoin: baseJoin, Desc: desc}.Init(p.SCtx(), statsInfo.ScaleByExpectCnt(prop.ExpectedCnt), p.QueryBlockOffset())
enforcedPhysicalMergeJoin.SetSchema(schema)
enforcedPhysicalMergeJoin.childrenReqProps = []*property.PhysicalProperty{lProp, rProp}
enforcedPhysicalMergeJoin.initCompareFuncs()
return []base.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.SCtx().GetExprCtx(), p.LeftJoinKeys[i], p.RightJoinKeys[i]))
}
}
func shouldSkipHashJoin(p *LogicalJoin) bool {
return (p.PreferJoinType&h.PreferNoHashJoin) > 0 || (p.SCtx().GetSessionVars().DisableHashJoin)
}
func getHashJoins(p *LogicalJoin, prop *property.PhysicalProperty) (joins []base.PhysicalPlan, forced bool) {
if !prop.IsSortItemEmpty() { // hash join doesn't promise any orders
return
}
forceLeftToBuild := ((p.PreferJoinType & h.PreferLeftAsHJBuild) > 0) || ((p.PreferJoinType & h.PreferRightAsHJProbe) > 0)
forceRightToBuild := ((p.PreferJoinType & h.PreferRightAsHJBuild) > 0) || ((p.PreferJoinType & h.PreferLeftAsHJProbe) > 0)
if forceLeftToBuild && forceRightToBuild {
p.SCtx().GetSessionVars().StmtCtx.SetHintWarning("Some HASH_JOIN_BUILD and HASH_JOIN_PROBE hints are conflicts, please check the hints")
forceLeftToBuild = false
forceRightToBuild = false
}
joins = make([]base.PhysicalPlan, 0, 2)
switch p.JoinType {
case SemiJoin, AntiSemiJoin, LeftOuterSemiJoin, AntiLeftOuterSemiJoin:
joins = append(joins, getHashJoin(p, prop, 1, false))
if forceLeftToBuild || forceRightToBuild {
// Do not support specifying the build and probe side for semi join.
p.SCtx().GetSessionVars().StmtCtx.SetHintWarning(fmt.Sprintf("We can't use the HASH_JOIN_BUILD or HASH_JOIN_PROBE hint for %s, please check the hint", p.JoinType))
forceLeftToBuild = false
forceRightToBuild = false
}
case LeftOuterJoin:
if !forceLeftToBuild {
joins = append(joins, getHashJoin(p, prop, 1, false))
}
if !forceRightToBuild {
joins = append(joins, getHashJoin(p, prop, 1, true))
}
case RightOuterJoin:
if !forceLeftToBuild {
joins = append(joins, getHashJoin(p, prop, 0, true))
}
if !forceRightToBuild {
joins = append(joins, getHashJoin(p, prop, 0, false))
}
case InnerJoin:
if forceLeftToBuild {
joins = append(joins, getHashJoin(p, prop, 0, false))
} else if forceRightToBuild {
joins = append(joins, getHashJoin(p, prop, 1, false))
} else {
joins = append(joins, getHashJoin(p, prop, 1, false))
joins = append(joins, getHashJoin(p, prop, 0, false))
}
}
forced = (p.PreferJoinType&h.PreferHashJoin > 0) || forceLeftToBuild || forceRightToBuild
shouldSkipHashJoin := shouldSkipHashJoin(p)
if !forced && shouldSkipHashJoin {
return nil, false
} else if forced && shouldSkipHashJoin {
p.SCtx().GetSessionVars().StmtCtx.SetHintWarning(
"A conflict between the HASH_JOIN hint and the NO_HASH_JOIN hint, " +
"or the tidb_opt_enable_hash_join system variable, the HASH_JOIN hint will take precedence.")
}
return
}
func getHashJoin(p *LogicalJoin, prop *property.PhysicalProperty, innerIdx int, useOuterToBuild bool) *PhysicalHashJoin {
chReqProps := make([]*property.PhysicalProperty, 2)
chReqProps[innerIdx] = &property.PhysicalProperty{ExpectedCnt: math.MaxFloat64, CTEProducerStatus: prop.CTEProducerStatus}
chReqProps[1-innerIdx] = &property.PhysicalProperty{ExpectedCnt: math.MaxFloat64, CTEProducerStatus: prop.CTEProducerStatus}
if prop.ExpectedCnt < p.StatsInfo().RowCount {
expCntScale := prop.ExpectedCnt / p.StatsInfo().RowCount
chReqProps[1-innerIdx].ExpectedCnt = p.Children()[1-innerIdx].StatsInfo().RowCount * expCntScale
}
hashJoin := NewPhysicalHashJoin(p, innerIdx, useOuterToBuild, p.StatsInfo().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 constructIndexJoin(
p *LogicalJoin,
prop *property.PhysicalProperty,
outerIdx int,
innerTask base.Task,
ranges ranger.MutableRanges,
keyOff2IdxOff []int,
path *util.AccessPath,
compareFilters *ColWithCmpFuncManager,
extractOtherEQ bool,
) []base.PhysicalPlan {
if ranges == nil {
ranges = ranger.Ranges{} // empty range
}
joinType := p.JoinType
var (
innerJoinKeys []*expression.Column
outerJoinKeys []*expression.Column
isNullEQ []bool
hasNullEQ bool
)
if outerIdx == 0 {
outerJoinKeys, innerJoinKeys, isNullEQ, hasNullEQ = p.GetJoinKeys()
} else {
innerJoinKeys, outerJoinKeys, isNullEQ, hasNullEQ = p.GetJoinKeys()
}
// TODO: support null equal join keys for index join
if hasNullEQ {
return nil
}
chReqProps := make([]*property.PhysicalProperty, 2)
chReqProps[outerIdx] = &property.PhysicalProperty{TaskTp: property.RootTaskType, ExpectedCnt: math.MaxFloat64, SortItems: prop.SortItems, CTEProducerStatus: prop.CTEProducerStatus}
if prop.ExpectedCnt < p.StatsInfo().RowCount {
expCntScale := prop.ExpectedCnt / p.StatsInfo().RowCount
chReqProps[outerIdx].ExpectedCnt = p.Children()[outerIdx].StatsInfo().RowCount * expCntScale
}
newInnerKeys := make([]*expression.Column, 0, len(innerJoinKeys))
newOuterKeys := make([]*expression.Column, 0, len(outerJoinKeys))
newIsNullEQ := make([]bool, 0, len(isNullEQ))
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])
newIsNullEQ = append(newIsNullEQ, isNullEQ[keyOff])
newKeyOff = append(newKeyOff, idxOff)
}
var outerHashKeys, innerHashKeys []*expression.Column
outerHashKeys, innerHashKeys = make([]*expression.Column, len(newOuterKeys)), make([]*expression.Column, len(newInnerKeys))
copy(outerHashKeys, newOuterKeys)
copy(innerHashKeys, newInnerKeys)
// we can use the `col <eq> col` in `OtherCondition` to build the hashtable to avoid the unnecessary calculating.
for i := len(newOtherConds) - 1; extractOtherEQ && i >= 0; i = i - 1 {
switch c := newOtherConds[i].(type) {
case *expression.ScalarFunction:
if c.FuncName.L == ast.EQ {
lhs, ok1 := c.GetArgs()[0].(*expression.Column)
rhs, ok2 := c.GetArgs()[1].(*expression.Column)
if ok1 && ok2 {
if lhs.InOperand || rhs.InOperand {
// if this other-cond is from a `[not] in` sub-query, do not convert it into eq-cond since
// IndexJoin cannot deal with NULL correctly in this case; please see #25799 for more details.
continue
}
outerSchema, innerSchema := p.Children()[outerIdx].Schema(), p.Children()[1-outerIdx].Schema()
if outerSchema.Contains(lhs) && innerSchema.Contains(rhs) {
outerHashKeys = append(outerHashKeys, lhs) // nozero
innerHashKeys = append(innerHashKeys, rhs) // nozero
} else if innerSchema.Contains(lhs) && outerSchema.Contains(rhs) {
outerHashKeys = append(outerHashKeys, rhs) // nozero
innerHashKeys = append(innerHashKeys, lhs) // nozero
}
newOtherConds = append(newOtherConds[:i], newOtherConds[i+1:]...)
}
}
default:
continue
}
}
baseJoin := basePhysicalJoin{
InnerChildIdx: 1 - outerIdx,
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
OtherConditions: newOtherConds,
JoinType: joinType,
OuterJoinKeys: newOuterKeys,
InnerJoinKeys: newInnerKeys,
IsNullEQ: newIsNullEQ,
DefaultValues: p.DefaultValues,
}
join := PhysicalIndexJoin{
basePhysicalJoin: baseJoin,
innerPlan: innerTask.Plan(),
KeyOff2IdxOff: newKeyOff,
Ranges: ranges,
CompareFilters: compareFilters,
OuterHashKeys: outerHashKeys,
InnerHashKeys: innerHashKeys,
}.Init(p.SCtx(), p.StatsInfo().ScaleByExpectCnt(prop.ExpectedCnt), p.QueryBlockOffset(), chReqProps...)
if path != nil {
join.IdxColLens = path.IdxColLens
}
join.SetSchema(p.Schema())
return []base.PhysicalPlan{join}
}
func constructIndexMergeJoin(
p *LogicalJoin,
prop *property.PhysicalProperty,
outerIdx int,
innerTask base.Task,
ranges ranger.MutableRanges,
keyOff2IdxOff []int,
path *util.AccessPath,
compareFilters *ColWithCmpFuncManager,
) []base.PhysicalPlan {
hintExists := false
if (outerIdx == 1 && (p.PreferJoinType&h.PreferLeftAsINLMJInner) > 0) || (outerIdx == 0 && (p.PreferJoinType&h.PreferRightAsINLMJInner) > 0) {
hintExists = true
}
indexJoins := constructIndexJoin(p, prop, outerIdx, innerTask, ranges, keyOff2IdxOff, path, compareFilters, !hintExists)
indexMergeJoins := make([]base.PhysicalPlan, 0, len(indexJoins))
for _, plan := range indexJoins {
join := plan.(*PhysicalIndexJoin)
// Index merge join can't handle hash keys. So we ban it heuristically.
if len(join.InnerHashKeys) > len(join.InnerJoinKeys) {
return nil
}
// EnumType/SetType Unsupported: merge join conflicts with index order.
// ref: https://github.com/pingcap/tidb/issues/24473, https://github.com/pingcap/tidb/issues/25669
for _, innerKey := range join.InnerJoinKeys {
if innerKey.RetType.GetType() == mysql.TypeEnum || innerKey.RetType.GetType() == mysql.TypeSet {
return nil
}
}
for _, outerKey := range join.OuterJoinKeys {
if outerKey.RetType.GetType() == mysql.TypeEnum || outerKey.RetType.GetType() == mysql.TypeSet {
return nil
}
}
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
}
slices.Sort(keyOffMapList)
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.SortItems)
compareFuncs := make([]expression.CompareFunc, 0, len(join.OuterJoinKeys))
outerCompareFuncs := make([]expression.CompareFunc, 0, len(join.OuterJoinKeys))
for i := range join.KeyOff2IdxOff {
if isOuterKeysPrefix && !prop.SortItems[i].Col.EqualColumn(join.OuterJoinKeys[keyOff2KeyOffOrderByIdx[i]]) {
isOuterKeysPrefix = false
}
compareFuncs = append(compareFuncs, expression.GetCmpFunction(p.SCtx().GetExprCtx(), join.OuterJoinKeys[i], join.InnerJoinKeys[i]))
outerCompareFuncs = append(outerCompareFuncs, expression.GetCmpFunction(p.SCtx().GetExprCtx(), join.OuterJoinKeys[i], join.OuterJoinKeys[i]))
}
// canKeepOuterOrder means whether the prop items are the prefix of the outer join keys.
canKeepOuterOrder := len(prop.SortItems) <= len(join.OuterJoinKeys)
for i := 0; canKeepOuterOrder && i < len(prop.SortItems); i++ {
if !prop.SortItems[i].Col.EqualColumn(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.IsSortItemEmpty() && prop.SortItems[0].Desc,
}.Init(p.SCtx())
indexMergeJoins = append(indexMergeJoins, indexMergeJoin)
}
}
return indexMergeJoins
}
func constructIndexHashJoin(
p *LogicalJoin,
prop *property.PhysicalProperty,
outerIdx int,
innerTask base.Task,
ranges ranger.MutableRanges,
keyOff2IdxOff []int,
path *util.AccessPath,
compareFilters *ColWithCmpFuncManager,
) []base.PhysicalPlan {
indexJoins := constructIndexJoin(p, prop, outerIdx, innerTask, ranges, keyOff2IdxOff, path, compareFilters, true)
indexHashJoins := make([]base.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.IsSortItemEmpty(),
}.Init(p.SCtx())
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 getIndexJoinByOuterIdx(p *LogicalJoin, prop *property.PhysicalProperty, outerIdx int) (joins []base.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()
}
innerChildWrapper := extractIndexJoinInnerChildPattern(p, innerChild)
if innerChildWrapper == nil {
return nil
}
var avgInnerRowCnt float64
if outerChild.StatsInfo().RowCount > 0 {
avgInnerRowCnt = p.EqualCondOutCnt / outerChild.StatsInfo().RowCount
}
joins = buildIndexJoinInner2TableScan(p, prop, innerChildWrapper, innerJoinKeys, outerJoinKeys, outerIdx, avgInnerRowCnt)
if joins != nil {
return
}
return buildIndexJoinInner2IndexScan(p, prop, innerChildWrapper, innerJoinKeys, outerJoinKeys, outerIdx, avgInnerRowCnt)
}
// indexJoinInnerChildWrapper is a wrapper for the inner child of an index join.
// It contains the lowest DataSource operator and other inner child operator
// which is flattened into a list structure from tree structure .
// For example, the inner child of an index join is a tree structure like:
//
// Projection
// Aggregation
// Selection
// DataSource
//
// The inner child wrapper will be:
// DataSource: the lowest DataSource operator.
// hasDitryWrite: whether the inner child contains dirty data.
// zippedChildren: [Projection, Aggregation, Selection]
type indexJoinInnerChildWrapper struct {
ds *DataSource
hasDitryWrite bool
zippedChildren []base.LogicalPlan
}
func extractIndexJoinInnerChildPattern(p *LogicalJoin, innerChild base.LogicalPlan) *indexJoinInnerChildWrapper {
wrapper := &indexJoinInnerChildWrapper{}
nextChild := func(pp base.LogicalPlan) base.LogicalPlan {
if len(pp.Children()) != 1 {
return nil
}
return pp.Children()[0]
}
childLoop:
for curChild := innerChild; curChild != nil; curChild = nextChild(curChild) {
switch child := curChild.(type) {
case *DataSource:
wrapper.ds = child
break childLoop
case *logicalop.LogicalProjection, *LogicalSelection, *LogicalAggregation:
if !p.SCtx().GetSessionVars().EnableINLJoinInnerMultiPattern {
return nil
}
wrapper.zippedChildren = append(wrapper.zippedChildren, child)
case *LogicalUnionScan:
wrapper.hasDitryWrite = true
wrapper.zippedChildren = append(wrapper.zippedChildren, child)
default:
return nil
}
}
if wrapper.ds == nil || wrapper.ds.PreferStoreType&h.PreferTiFlash != 0 {
return nil
}
return wrapper
}
// 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 buildIndexJoinInner2TableScan(
p *LogicalJoin,
prop *property.PhysicalProperty, wrapper *indexJoinInnerChildWrapper,
innerJoinKeys, outerJoinKeys []*expression.Column,
outerIdx int, avgInnerRowCnt float64) (joins []base.PhysicalPlan) {
ds := wrapper.ds
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.MutableRanges = ranger.Ranges{}
var innerTask, innerTask2 base.Task
var indexJoinResult *indexJoinPathResult
if ds.TableInfo.IsCommonHandle {
indexJoinResult, keyOff2IdxOff = getBestIndexJoinPathResult(p, ds, innerJoinKeys, outerJoinKeys, func(path *util.AccessPath) bool { return path.IsCommonHandlePath })
if indexJoinResult == nil {
return nil
}
rangeInfo := indexJoinPathRangeInfo(p.SCtx(), outerJoinKeys, indexJoinResult)
innerTask = constructInnerTableScanTask(p, wrapper, indexJoinResult.chosenRanges.Range(), outerJoinKeys, rangeInfo, 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 !wrapper.hasDitryWrite {
innerTask2 = constructInnerTableScanTask(p, wrapper, indexJoinResult.chosenRanges.Range(), outerJoinKeys, rangeInfo, true, !prop.IsSortItemEmpty() && prop.SortItems[0].Desc, avgInnerRowCnt)
}
ranges = indexJoinResult.chosenRanges
} else {
pkMatched := false
pkCol := ds.getPKIsHandleCol()
if pkCol == nil {
return nil
}
for i, key := range innerJoinKeys {
if !key.EqualColumn(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
}
ranges := ranger.FullIntRange(mysql.HasUnsignedFlag(pkCol.RetType.GetFlag()))
var buffer strings.Builder
buffer.WriteString("[")
for i, key := range outerJoinKeys {
if i != 0 {
buffer.WriteString(" ")
}
buffer.WriteString(key.StringWithCtx(p.SCtx().GetExprCtx().GetEvalCtx(), errors.RedactLogDisable))
}
buffer.WriteString("]")
rangeInfo := buffer.String()
innerTask = constructInnerTableScanTask(p, wrapper, ranges, outerJoinKeys, rangeInfo, 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 !wrapper.hasDitryWrite {
innerTask2 = constructInnerTableScanTask(p, wrapper, ranges, outerJoinKeys, rangeInfo, true, !prop.IsSortItemEmpty() && prop.SortItems[0].Desc, avgInnerRowCnt)
}
}
var (
path *util.AccessPath
lastColMng *ColWithCmpFuncManager
)
if indexJoinResult != nil {
path = indexJoinResult.chosenPath
lastColMng = indexJoinResult.lastColManager
}
joins = make([]base.PhysicalPlan, 0, 3)
failpoint.Inject("MockOnlyEnableIndexHashJoin", func(val failpoint.Value) {
if val.(bool) && !p.SCtx().GetSessionVars().InRestrictedSQL {
failpoint.Return(constructIndexHashJoin(p, prop, outerIdx, innerTask, nil, keyOff2IdxOff, path, lastColMng))
}
})
joins = append(joins, constructIndexJoin(p, prop, outerIdx, innerTask, ranges, keyOff2IdxOff, path, lastColMng, true)...)
// 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, constructIndexHashJoin(p, prop, outerIdx, innerTask, ranges, keyOff2IdxOff, path, lastColMng)...)
if innerTask2 != nil {
joins = append(joins, constructIndexMergeJoin(p, prop, outerIdx, innerTask2, ranges, keyOff2IdxOff, path, lastColMng)...)
}
return joins
}
func buildIndexJoinInner2IndexScan(
p *LogicalJoin,
prop *property.PhysicalProperty, wrapper *indexJoinInnerChildWrapper, innerJoinKeys, outerJoinKeys []*expression.Column,
outerIdx int, avgInnerRowCnt float64) (joins []base.PhysicalPlan) {
ds := wrapper.ds
indexValid := func(path *util.AccessPath) bool {
if path.IsTablePath() {
return false
}
// if path is index path. index path currently include two kind of, one is normal, and the other is mv index.
// for mv index like mvi(a, json, b), if driving condition is a=1, and we build a prefix scan with range [1,1]
// on mvi, it will return many index rows which breaks handle-unique attribute here.
//
// the basic rule is that: mv index can be and can only be accessed by indexMerge operator. (embedded handle duplication)
if !isMVIndexPath(path) {
return true // not a MVIndex path, it can successfully be index join probe side.
}
return false
}
indexJoinResult, keyOff2IdxOff := getBestIndexJoinPathResult(p, ds, innerJoinKeys, outerJoinKeys, indexValid)
if indexJoinResult == nil {
return nil
}
joins = make([]base.PhysicalPlan, 0, 3)
rangeInfo := indexJoinPathRangeInfo(p.SCtx(), outerJoinKeys, indexJoinResult)
maxOneRow := false
if indexJoinResult.chosenPath.Index.Unique && indexJoinResult.usedColsLen == len(indexJoinResult.chosenPath.FullIdxCols) {
l := len(indexJoinResult.chosenAccess)
if l == 0 {
maxOneRow = true
} else {
sf, ok := indexJoinResult.chosenAccess[l-1].(*expression.ScalarFunction)
maxOneRow = ok && (sf.FuncName.L == ast.EQ)
}
}
innerTask := constructInnerIndexScanTask(p, wrapper, indexJoinResult.chosenPath, indexJoinResult.chosenRanges.Range(), indexJoinResult.chosenRemained, innerJoinKeys, indexJoinResult.idxOff2KeyOff, rangeInfo, false, false, avgInnerRowCnt, maxOneRow)
failpoint.Inject("MockOnlyEnableIndexHashJoin", func(val failpoint.Value) {
if val.(bool) && !p.SCtx().GetSessionVars().InRestrictedSQL && innerTask != nil {
failpoint.Return(constructIndexHashJoin(p, prop, outerIdx, innerTask, indexJoinResult.chosenRanges, keyOff2IdxOff, indexJoinResult.chosenPath, indexJoinResult.lastColManager))
}
})
if innerTask != nil {
joins = append(joins, constructIndexJoin(p, prop, outerIdx, innerTask, indexJoinResult.chosenRanges, keyOff2IdxOff, indexJoinResult.chosenPath, indexJoinResult.lastColManager, true)...)
// 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, constructIndexHashJoin(p, prop, outerIdx, innerTask, indexJoinResult.chosenRanges, keyOff2IdxOff, indexJoinResult.chosenPath, indexJoinResult.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 !wrapper.hasDitryWrite {
innerTask2 := constructInnerIndexScanTask(p, wrapper, indexJoinResult.chosenPath, indexJoinResult.chosenRanges.Range(), indexJoinResult.chosenRemained, innerJoinKeys, indexJoinResult.idxOff2KeyOff, rangeInfo, true, !prop.IsSortItemEmpty() && prop.SortItems[0].Desc, avgInnerRowCnt, maxOneRow)
if innerTask2 != nil {
joins = append(joins, constructIndexMergeJoin(p, prop, outerIdx, innerTask2, indexJoinResult.chosenRanges, keyOff2IdxOff, indexJoinResult.chosenPath, indexJoinResult.lastColManager)...)
}
}
return joins
}
// constructInnerTableScanTask is specially used to construct the inner plan for PhysicalIndexJoin.
func constructInnerTableScanTask(
p *LogicalJoin,
wrapper *indexJoinInnerChildWrapper,
ranges ranger.Ranges,
_ []*expression.Column,
rangeInfo string,
keepOrder bool,
desc bool,
rowCount float64,
) base.Task {
ds := wrapper.ds
// If `ds.TableInfo.GetPartitionInfo() != nil`,
// it means the data source is a partition table reader.
// If the inner task need to keep order, the partition table reader can't satisfy it.
if keepOrder && ds.TableInfo.GetPartitionInfo() != nil {
return nil
}
ts := PhysicalTableScan{
Table: ds.TableInfo,
Columns: ds.Columns,
TableAsName: ds.TableAsName,
DBName: ds.DBName,
filterCondition: ds.PushedDownConds,
Ranges: ranges,
rangeInfo: rangeInfo,
KeepOrder: keepOrder,
Desc: desc,
physicalTableID: ds.PhysicalTableID,
isPartition: ds.PartitionDefIdx != nil,
tblCols: ds.TblCols,
tblColHists: ds.TblColHists,
}.Init(ds.SCtx(), ds.QueryBlockOffset())
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 = cardinality.Selectivity(ds.SCtx(), ds.TableStats.HistColl, 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 = cost.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.SetStats(&property.StatsInfo{