forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
physical_plan_builder.go
1577 lines (1507 loc) · 47.5 KB
/
physical_plan_builder.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 2016 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 plan
import (
"math"
log "github.com/Sirupsen/logrus"
"github.com/juju/errors"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/expression/aggregation"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/types"
)
const (
netWorkFactor = 1.5
netWorkStartFactor = 20.0
scanFactor = 2.0
descScanFactor = 5 * scanFactor
memoryFactor = 5.0
hashAggMemFactor = 2.0
selectionFactor = 0.8
distinctFactor = 0.8
cpuFactor = 0.9
aggFactor = 0.1
joinFactor = 0.3
)
// JoinConcurrency means the number of goroutines that participate in joining.
var JoinConcurrency = 5
func (p *DataSource) convert2TableScan(prop *requiredProperty) (*physicalPlanInfo, error) {
client := p.ctx.GetClient()
ts := PhysicalTableScan{
Table: p.tableInfo,
Columns: p.Columns,
DBName: p.DBName,
physicalTableSource: physicalTableSource{
client: client,
NeedColHandle: p.NeedColHandle,
unionScanSchema: p.unionScanSchema,
},
}.init(p.allocator, p.ctx)
ts.SetSchema(p.schema)
if p.ctx.Txn() != nil {
ts.readOnly = p.ctx.Txn().IsReadOnly()
} else {
ts.readOnly = true
}
var resultPlan PhysicalPlan = ts
table := p.tableInfo
sc := p.ctx.GetSessionVars().StmtCtx
ts.Ranges = []types.IntColumnRange{{LowVal: math.MinInt64, HighVal: math.MaxInt64}}
if len(p.parents) > 0 {
if sel, ok := p.parents[0].(*Selection); ok {
newSel := sel.Copy().(*Selection)
conds := make([]expression.Expression, 0, len(sel.Conditions))
for _, cond := range sel.Conditions {
conds = append(conds, cond.Clone())
}
ts.AccessCondition, newSel.Conditions = ranger.DetachColumnConditions(conds, table.GetPkName())
ts.TableConditionPBExpr, ts.tableFilterConditions, newSel.Conditions =
expression.ExpressionsToPB(sc, newSel.Conditions, client)
ranges, err := ranger.BuildTableRange(ts.AccessCondition, sc)
if err != nil {
return nil, errors.Trace(err)
}
ts.Ranges = ranges
if len(newSel.Conditions) > 0 {
newSel.SetChildren(ts)
newSel.onTable = true
resultPlan = newSel
}
}
}
statsTbl := p.statisticTable
rowCount := float64(statsTbl.Count)
if table.PKIsHandle {
for i, colInfo := range ts.Columns {
if mysql.HasPriKeyFlag(colInfo.Flag) {
ts.pkCol = p.Schema().Columns[i]
var err error
rowCount, err = statsTbl.GetRowCountByIntColumnRanges(sc, ts.pkCol.ID, ts.Ranges)
if err != nil {
return nil, errors.Trace(err)
}
break
}
}
}
if ts.TableConditionPBExpr != nil {
rowCount = rowCount * selectionFactor
}
return resultPlan.matchProperty(prop, &physicalPlanInfo{count: rowCount, reliable: !statsTbl.Pseudo}), nil
}
func (p *DataSource) convert2IndexScan(prop *requiredProperty, index *model.IndexInfo) (*physicalPlanInfo, error) {
client := p.ctx.GetClient()
is := PhysicalIndexScan{
Index: index,
Table: p.tableInfo,
Columns: p.Columns,
OutOfOrder: true,
DBName: p.DBName,
physicalTableSource: physicalTableSource{
client: client,
NeedColHandle: p.NeedColHandle,
unionScanSchema: p.unionScanSchema,
},
}.init(p.allocator, p.ctx)
is.SetSchema(p.schema)
if p.ctx.Txn() != nil {
is.readOnly = p.ctx.Txn().IsReadOnly()
} else {
is.readOnly = true
}
var resultPlan PhysicalPlan = is
statsTbl := p.statisticTable
rowCount := float64(statsTbl.Count)
sc := p.ctx.GetSessionVars().StmtCtx
is.Ranges = ranger.FullIndexRange()
if len(p.parents) > 0 {
if sel, ok := p.parents[0].(*Selection); ok {
newSel := sel.Copy().(*Selection)
conds := make([]expression.Expression, 0, len(sel.Conditions))
for _, cond := range sel.Conditions {
conds = append(conds, cond.Clone())
}
is.AccessCondition, newSel.Conditions, is.accessEqualCount, is.accessInAndEqCount = ranger.DetachIndexScanConditions(conds, is.Index)
memDB := infoschema.IsMemoryDB(p.DBName.L)
isDistReq := !memDB && client != nil && client.IsRequestTypeSupported(kv.ReqTypeIndex, 0)
if isDistReq {
idxConds, tblConds := ranger.DetachIndexFilterConditions(newSel.Conditions, is.Index.Columns, is.Table)
is.IndexConditionPBExpr, is.indexFilterConditions, idxConds = expression.ExpressionsToPB(sc, idxConds, client)
is.TableConditionPBExpr, is.tableFilterConditions, tblConds = expression.ExpressionsToPB(sc, tblConds, client)
newSel.Conditions = append(idxConds, tblConds...)
}
var err error
is.Ranges, err = ranger.BuildIndexRange(p.ctx.GetSessionVars().StmtCtx, is.Table, is.Index, is.accessInAndEqCount, is.AccessCondition)
if err != nil {
if !types.ErrTruncated.Equal(err) {
return nil, errors.Trace(err)
}
log.Warn("truncate error in buildIndexRange")
}
rowCount, err = statsTbl.GetRowCountByIndexRanges(sc, is.Index.ID, is.Ranges)
if err != nil {
return nil, errors.Trace(err)
}
if len(newSel.Conditions) > 0 {
newSel.SetChildren(is)
newSel.onTable = true
resultPlan = newSel
}
}
}
is.DoubleRead = !isCoveringIndex(is.Columns, is.Index.Columns, is.Table.PKIsHandle)
return resultPlan.matchProperty(prop, &physicalPlanInfo{count: rowCount, reliable: !statsTbl.Pseudo}), nil
}
func isCoveringIndex(columns []*model.ColumnInfo, indexColumns []*model.IndexColumn, pkIsHandle bool) bool {
for _, colInfo := range columns {
if pkIsHandle && mysql.HasPriKeyFlag(colInfo.Flag) {
continue
}
if colInfo.ID == model.ExtraHandleID {
continue
}
isIndexColumn := false
for _, indexCol := range indexColumns {
isFullLen := indexCol.Length == types.UnspecifiedLength || indexCol.Length == colInfo.Flen
if colInfo.Name.L == indexCol.Name.L && isFullLen {
isIndexColumn = true
break
}
}
if !isIndexColumn {
return false
}
}
return true
}
func (p *DataSource) need2ConsiderIndex(prop *requiredProperty) bool {
if len(p.parents) == 0 {
return len(prop.props) > 0
}
if _, ok := p.parents[0].(*Selection); ok || len(prop.props) > 0 {
return true
}
return false
}
// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
// If there is no index that matches the required property, the returned physicalPlanInfo
// will be table scan and has the cost of MaxInt64. But this can be ignored because the parent will call
// convert2PhysicalPlan again with an empty *requiredProperty, so the plan with the lowest
// cost will be chosen.
func (p *DataSource) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
info, err := p.getPlanInfo(prop)
if err != nil {
return nil, errors.Trace(err)
}
if info != nil {
return info, nil
}
info, err = p.tryToConvert2DummyScan(prop)
if info != nil || err != nil {
return info, errors.Trace(err)
}
client := p.ctx.GetClient()
memDB := infoschema.IsMemoryDB(p.DBName.L)
isDistReq := !memDB && client != nil && client.IsRequestTypeSupported(kv.ReqTypeSelect, 0)
if !isDistReq {
memTable := PhysicalMemTable{
DBName: p.DBName,
Table: p.tableInfo,
Columns: p.Columns,
}.init(p.allocator, p.ctx)
memTable.SetSchema(p.schema)
memTable.Ranges = ranger.FullIntRange()
info = &physicalPlanInfo{p: memTable}
info = enforceProperty(prop, info)
return info, errors.Trace(p.storePlanInfo(prop, info))
}
indices, includeTableScan := availableIndices(p.indexHints, p.tableInfo)
if includeTableScan {
info, err = p.convert2TableScan(prop)
if err != nil {
return nil, errors.Trace(err)
}
}
if !includeTableScan || p.need2ConsiderIndex(prop) {
for _, index := range indices {
indexInfo, err := p.convert2IndexScan(prop, index)
if err != nil {
return nil, errors.Trace(err)
}
if info == nil || indexInfo.cost < info.cost {
info = indexInfo
}
}
}
return info, errors.Trace(p.storePlanInfo(prop, info))
}
// tryToConvert2DummyScan is an optimization which checks if its parent is a selection with a constant condition
// that evaluates to false. If it is, there is no need for a real physical scan, a dummy scan will do.
func (p *DataSource) tryToConvert2DummyScan(prop *requiredProperty) (*physicalPlanInfo, error) {
if len(p.Parents()) == 0 {
return nil, nil
}
sel, isSel := p.parents[0].(*Selection)
if !isSel {
return nil, nil
}
for _, cond := range sel.Conditions {
if con, ok := cond.(*expression.Constant); ok {
result, err := expression.EvalBool([]expression.Expression{con}, nil, p.ctx)
if err != nil {
return nil, errors.Trace(err)
}
if !result {
dual := TableDual{}.init(p.allocator, p.ctx)
dual.SetSchema(p.schema)
info := &physicalPlanInfo{p: dual}
return info, errors.Trace(p.storePlanInfo(prop, info))
}
}
}
return nil, nil
}
// addPlanToResponse creates a *physicalPlanInfo that adds p as the parent of info.
func addPlanToResponse(parent PhysicalPlan, info *physicalPlanInfo) *physicalPlanInfo {
np := parent.Copy()
np.SetChildren(info.p)
ret := &physicalPlanInfo{p: np, cost: info.cost, count: info.count, reliable: info.reliable}
if _, ok := parent.(*MaxOneRow); ok {
ret.count = 1
ret.reliable = true
}
return ret
}
// enforceProperty creates a *physicalPlanInfo that satisfies the required property by adding
// sort or limit as the parent of the given physical plan.
func enforceProperty(prop *requiredProperty, info *physicalPlanInfo) *physicalPlanInfo {
if info.p == nil {
return info
}
if len(prop.props) != 0 {
items := make([]*ByItems, 0, len(prop.props))
for _, col := range prop.props {
items = append(items, &ByItems{Expr: col.col, Desc: col.desc})
}
sort := Sort{
ByItems: items,
ExecLimit: prop.limit,
}.init(info.p.Allocator(), info.p.context())
sort.SetSchema(info.p.Schema())
info = addPlanToResponse(sort, info)
count := info.count
if prop.limit != nil {
count = float64(prop.limit.Offset + prop.limit.Count)
info.reliable = true
}
info.cost += sortCost(count)
} else if prop.limit != nil {
limit := Limit{Offset: prop.limit.Offset, Count: prop.limit.Count}.init(info.p.Allocator(), info.p.context())
limit.SetSchema(info.p.Schema())
info = addPlanToResponse(limit, info)
info.reliable = true
}
if prop.limit != nil && float64(prop.limit.Count) < info.count {
info.count = float64(prop.limit.Count)
}
return info
}
func sortCost(cnt float64) float64 {
if cnt == 0 {
// If cnt is 0, the log(cnt) will be NAN.
return 0.0
}
return cnt*math.Log2(cnt)*cpuFactor + memoryFactor*cnt
}
// removeLimit removes the limit from prop.
func removeLimit(prop *requiredProperty) *requiredProperty {
ret := &requiredProperty{
props: prop.props,
sortKeyLen: prop.sortKeyLen,
}
return ret
}
func removeSortOrder(prop *requiredProperty) *requiredProperty {
ret := &requiredProperty{
limit: prop.limit,
}
return ret
}
// convertLimitOffsetToCount changes the limit(offset, count) in prop to limit(0, offset + count).
func convertLimitOffsetToCount(prop *requiredProperty) *requiredProperty {
ret := &requiredProperty{
props: prop.props,
sortKeyLen: prop.sortKeyLen,
}
if prop.limit != nil {
ret.limit = &Limit{
Count: prop.limit.Offset + prop.limit.Count,
}
}
return ret
}
func limitProperty(limit *Limit) *requiredProperty {
return &requiredProperty{limit: limit}
}
// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *Limit) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
info, err := p.getPlanInfo(prop)
if err != nil {
return nil, errors.Trace(err)
}
if info != nil {
return info, nil
}
info, err = p.children[0].(LogicalPlan).convert2PhysicalPlan(limitProperty(&Limit{Offset: p.Offset, Count: p.Count}))
if err != nil {
return nil, errors.Trace(err)
}
info = enforceProperty(prop, info)
return info, errors.Trace(p.storePlanInfo(prop, info))
}
// convert2PhysicalPlanSemi converts the semi join to *physicalPlanInfo.
func (p *LogicalJoin) convert2PhysicalPlanSemi(prop *requiredProperty) (*physicalPlanInfo, error) {
lChild := p.children[0].(LogicalPlan)
rChild := p.children[1].(LogicalPlan)
allLeft := true
for _, col := range prop.props {
if !lChild.Schema().Contains(col.col) {
allLeft = false
}
}
join := PhysicalHashSemiJoin{
WithAux: LeftOuterSemiJoin == p.JoinType,
EqualConditions: p.EqualConditions,
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
OtherConditions: p.OtherConditions,
Anti: p.anti,
}.init(p.allocator, p.ctx)
join.SetSchema(p.schema)
lProp := prop
if !allLeft {
lProp = &requiredProperty{}
}
if p.JoinType == SemiJoin {
lProp = removeLimit(lProp)
}
lInfo, err := lChild.convert2PhysicalPlan(lProp)
if err != nil {
return nil, errors.Trace(err)
}
rInfo, err := rChild.convert2PhysicalPlan(&requiredProperty{})
if err != nil {
return nil, errors.Trace(err)
}
resultInfo := join.matchProperty(prop, lInfo, rInfo)
if p.JoinType == SemiJoin {
resultInfo.count = lInfo.count * selectionFactor
} else {
resultInfo.count = lInfo.count
}
if !allLeft {
resultInfo = enforceProperty(prop, resultInfo)
} else if p.JoinType == SemiJoin {
resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
}
return resultInfo, nil
}
// convert2PhysicalPlanLeft converts the left join to *physicalPlanInfo.
func (p *LogicalJoin) convert2PhysicalPlanLeft(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
lChild := p.children[0].(LogicalPlan)
rChild := p.children[1].(LogicalPlan)
allLeft := true
for _, col := range prop.props {
if !lChild.Schema().Contains(col.col) {
allLeft = false
}
}
join := PhysicalHashJoin{
EqualConditions: p.EqualConditions,
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
OtherConditions: p.OtherConditions,
SmallTable: 1,
// TODO: decide concurrency by data size.
Concurrency: JoinConcurrency,
DefaultValues: p.DefaultValues,
}.init(p.allocator, p.ctx)
join.SetSchema(p.schema)
if innerJoin {
join.JoinType = InnerJoin
} else {
join.JoinType = LeftOuterJoin
}
lProp := prop
if !allLeft {
lProp = &requiredProperty{}
}
var lInfo *physicalPlanInfo
var err error
if innerJoin {
lInfo, err = lChild.convert2PhysicalPlan(removeLimit(lProp))
} else {
lInfo, err = lChild.convert2PhysicalPlan(convertLimitOffsetToCount(lProp))
}
if err != nil {
return nil, errors.Trace(err)
}
rInfo, err := rChild.convert2PhysicalPlan(&requiredProperty{})
if err != nil {
return nil, errors.Trace(err)
}
resultInfo := join.matchProperty(prop, lInfo, rInfo)
if !allLeft {
resultInfo = enforceProperty(prop, resultInfo)
} else {
resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
}
return resultInfo, nil
}
// replaceColsInPropBySchema replaces the columns in original prop with the columns in schema.
func replaceColsInPropBySchema(prop *requiredProperty, schema *expression.Schema) *requiredProperty {
newProps := make([]*columnProp, 0, len(prop.props))
for _, p := range prop.props {
idx := schema.ColumnIndex(p.col)
if idx == -1 {
log.Errorf("Can't find column %s in schema", p.col)
}
newProps = append(newProps, &columnProp{col: schema.Columns[idx], desc: p.desc})
}
return &requiredProperty{
props: newProps,
sortKeyLen: prop.sortKeyLen,
limit: prop.limit,
}
}
// convert2PhysicalPlanRight converts the right join to *physicalPlanInfo.
func (p *LogicalJoin) convert2PhysicalPlanRight(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
lChild := p.children[0].(LogicalPlan)
rChild := p.children[1].(LogicalPlan)
allRight := true
for _, col := range prop.props {
if !rChild.Schema().Contains(col.col) {
allRight = false
}
}
join := PhysicalHashJoin{
EqualConditions: p.EqualConditions,
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
OtherConditions: p.OtherConditions,
// TODO: decide concurrency by data size.
Concurrency: JoinConcurrency,
DefaultValues: p.DefaultValues,
}.init(p.allocator, p.ctx)
join.SetSchema(p.schema)
if innerJoin {
join.JoinType = InnerJoin
} else {
join.JoinType = RightOuterJoin
}
lInfo, err := lChild.convert2PhysicalPlan(&requiredProperty{})
if err != nil {
return nil, errors.Trace(err)
}
rProp := prop
if !allRight {
rProp = &requiredProperty{}
} else {
rProp = replaceColsInPropBySchema(rProp, rChild.Schema())
}
var rInfo *physicalPlanInfo
if innerJoin {
rInfo, err = rChild.convert2PhysicalPlan(removeLimit(rProp))
} else {
rInfo, err = rChild.convert2PhysicalPlan(convertLimitOffsetToCount(rProp))
}
if err != nil {
return nil, errors.Trace(err)
}
resultInfo := join.matchProperty(prop, lInfo, rInfo)
if !allRight {
resultInfo = enforceProperty(prop, resultInfo)
} else {
resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
}
return resultInfo, nil
}
// buildSelectionWithConds will build a selection use the conditions of join and convert one side's column to correlated column.
// If the inner side is one selection then one data source, the inner child should be the data source other than the selection.
// This is called when build nested loop join.
func (p *LogicalJoin) buildSelectionWithConds(leftAsOuter bool) (*Selection, []*expression.CorrelatedColumn) {
var (
outerSchema *expression.Schema
innerChild Plan
innerConditions []expression.Expression
)
if leftAsOuter {
outerSchema = p.children[0].Schema()
innerConditions = p.RightConditions
innerChild = p.children[1]
} else {
outerSchema = p.children[1].Schema()
innerConditions = p.LeftConditions
innerChild = p.children[0]
}
if sel, ok := innerChild.(*Selection); ok {
innerConditions = append(innerConditions, sel.Conditions...)
innerChild = sel.children[0]
}
corCols := make([]*expression.CorrelatedColumn, 0, outerSchema.Len())
for _, col := range outerSchema.Columns {
corCol := &expression.CorrelatedColumn{Column: *col, Data: new(types.Datum)}
corCol.Column.ResolveIndices(outerSchema)
corCols = append(corCols, corCol)
}
selection := Selection{}.init(p.allocator, p.ctx)
selection.SetSchema(innerChild.Schema().Clone())
selection.SetChildren(innerChild)
conds := make([]expression.Expression, 0, len(p.EqualConditions)+len(innerConditions)+len(p.OtherConditions))
for _, cond := range p.EqualConditions {
newCond := expression.ConvertCol2CorCol(cond, corCols, outerSchema)
conds = append(conds, newCond)
}
selection.Conditions = conds
conds = append(conds, innerConditions...)
for _, cond := range p.OtherConditions {
newCond := expression.ConvertCol2CorCol(cond, corCols, outerSchema)
newCond.ResolveIndices(innerChild.Schema())
conds = append(conds, newCond)
}
selection.Conditions = conds
return selection, corCols
}
// outerTableCouldINLJ will check the whether is forced to build index nested loop join or outer info is reliable
// and the count satisfies the condition.
func (p *LogicalJoin) outerTableCouldINLJ(outerInfo *physicalPlanInfo, leftAsOuter bool) bool {
var forced bool
if leftAsOuter {
forced = (p.preferINLJ&preferLeftAsOuter) > 0 && p.hasEqualConds()
} else {
forced = (p.preferINLJ&preferRightAsOuter) > 0 && p.hasEqualConds()
}
return forced || (outerInfo.reliable && outerInfo.count <= float64(p.ctx.GetSessionVars().MaxRowCountForINLJ))
}
func (p *LogicalJoin) convert2IndexNestedLoopJoinLeft(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
lChild := p.children[0].(LogicalPlan)
switch x := p.children[1].(type) {
case *DataSource:
case *Selection:
if _, ok := x.children[0].(*DataSource); !ok {
return nil, nil
}
default:
return nil, nil
}
allLeft := true
for _, col := range prop.props {
if !lChild.Schema().Contains(col.col) {
allLeft = false
}
}
lProp := prop
if !allLeft {
lProp = &requiredProperty{}
} else {
lProp = replaceColsInPropBySchema(prop, lChild.Schema())
}
var lInfo *physicalPlanInfo
var err error
if innerJoin {
lInfo, err = lChild.convert2PhysicalPlan(removeLimit(lProp))
} else {
lInfo, err = lChild.convert2PhysicalPlan(convertLimitOffsetToCount(lProp))
}
if err != nil {
return nil, errors.Trace(err)
}
if lInfo.p == nil {
return nil, nil
}
// If the outer table's row count is reliable and don't exceed the MaxRowCountForINLJ or we use hint to force
// choosing index nested loop join, we will continue building. Otherwise we just break and return nil.
if !p.outerTableCouldINLJ(lInfo, true) {
return nil, nil
}
selection, corCols := p.buildSelectionWithConds(true)
if selection == nil {
return nil, nil
}
rInfo := selection.makeScanController()
join := PhysicalHashJoin{
LeftConditions: p.LeftConditions,
// TODO: decide concurrency by data size.
Concurrency: JoinConcurrency,
DefaultValues: p.DefaultValues,
SmallTable: 1,
}.init(p.allocator, p.ctx)
join.SetChildren(lInfo.p, rInfo.p)
if innerJoin {
join.JoinType = InnerJoin
} else {
join.JoinType = LeftOuterJoin
}
join.SetSchema(p.Schema())
resultInfo := join.matchProperty(prop, lInfo, rInfo)
ap := PhysicalApply{
PhysicalJoin: resultInfo.p,
OuterSchema: corCols,
}.init(p.allocator, p.ctx)
ap.SetChildren(resultInfo.p.Children()...)
ap.SetSchema(resultInfo.p.Schema())
resultInfo.p = ap
if !allLeft {
resultInfo = enforceProperty(prop, resultInfo)
} else {
resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
}
return resultInfo, nil
}
func (p *LogicalJoin) convert2IndexNestedLoopJoinRight(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
rChild := p.children[1].(LogicalPlan)
switch x := p.children[0].(type) {
case *DataSource:
case *Selection:
if _, ok := x.children[0].(*DataSource); !ok {
return nil, nil
}
default:
return nil, nil
}
allRight := true
for _, col := range prop.props {
if !rChild.Schema().Contains(col.col) {
allRight = false
}
}
rProp := prop
if !allRight {
rProp = &requiredProperty{}
} else {
rProp = replaceColsInPropBySchema(prop, rChild.Schema())
}
var rInfo *physicalPlanInfo
var err error
if innerJoin {
rInfo, err = rChild.convert2PhysicalPlan(removeLimit(rProp))
} else {
rInfo, err = rChild.convert2PhysicalPlan(convertLimitOffsetToCount(rProp))
}
if err != nil {
return nil, errors.Trace(err)
}
if rInfo.p == nil {
return nil, nil
}
// If the outer table's row count is reliable and don't exceed the MaxRowCountForINLJ or we use hint to force
// choosing index nested loop join, we will continue building. Otherwise we just break and return nil.
if !p.outerTableCouldINLJ(rInfo, false) {
return nil, nil
}
selection, corCols := p.buildSelectionWithConds(false)
if selection == nil {
return nil, nil
}
lInfo := selection.makeScanController()
join := PhysicalHashJoin{
RightConditions: p.RightConditions,
// TODO: decide concurrency by data size.
Concurrency: JoinConcurrency,
DefaultValues: p.DefaultValues,
}.init(p.allocator, p.ctx)
join.SetChildren(lInfo.p, rInfo.p)
if innerJoin {
join.JoinType = InnerJoin
} else {
join.JoinType = RightOuterJoin
}
join.SetSchema(p.Schema())
resultInfo := join.matchProperty(prop, lInfo, rInfo)
ap := PhysicalApply{
PhysicalJoin: resultInfo.p,
OuterSchema: corCols,
}.init(p.allocator, p.ctx)
ap.SetChildren(resultInfo.p.Children()...)
ap.SetSchema(resultInfo.p.Schema())
resultInfo.p = ap
if !allRight {
resultInfo = enforceProperty(prop, resultInfo)
} else {
resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
}
return resultInfo, nil
}
func generateJoinProp(column *expression.Column) *requiredProperty {
return &requiredProperty{
props: []*columnProp{{column, false}},
sortKeyLen: 1,
}
}
func compareTypeForOrder(lhs *types.FieldType, rhs *types.FieldType) bool {
if lhs.Tp != rhs.Tp {
return false
}
if lhs.EvalType().IsStringKind() && (lhs.Charset != rhs.Charset || lhs.Collate != rhs.Collate) {
return false
}
return true
}
// constructPropertyByJoin generates all possible combinations from join conditions for cost evaluation
// It will try all keys in join conditions
func constructPropertyByJoin(join *LogicalJoin) ([][]*requiredProperty, []int, error) {
var result [][]*requiredProperty
var condIndex []int
if join.EqualConditions == nil {
return nil, nil, nil
}
for i, cond := range join.EqualConditions {
if len(cond.GetArgs()) != 2 {
return nil, nil, errors.New("unexpected argument count for equal expression")
}
lExpr, rExpr := cond.GetArgs()[0], cond.GetArgs()[1]
// Only consider raw column reference and cowardly ignore calculations
// since we don't know if the function call preserve order
lColumn, lOK := lExpr.(*expression.Column)
rColumn, rOK := rExpr.(*expression.Column)
if lOK && rOK && compareTypeForOrder(lColumn.RetType, rColumn.RetType) {
result = append(result, []*requiredProperty{generateJoinProp(lColumn), generateJoinProp(rColumn)})
condIndex = append(condIndex, i)
} else {
continue
}
}
if len(result) == 0 {
return nil, nil, nil
}
return result, condIndex, nil
}
// convert2PhysicalMergeJoin converts the merge join to *physicalPlanInfo.
// TODO: Refactor and merge with hash join
func (p *LogicalJoin) convert2PhysicalMergeJoin(parentProp *requiredProperty, lProp *requiredProperty, rProp *requiredProperty, condIndex int, joinType JoinType) (*physicalPlanInfo, error) {
lChild := p.children[0].(LogicalPlan)
rChild := p.children[1].(LogicalPlan)
newEQConds := make([]*expression.ScalarFunction, 0, len(p.EqualConditions)-1)
for i, cond := range p.EqualConditions {
if i == condIndex {
continue
}
// prevent further index contamination
newCond := cond.Clone()
newCond.ResolveIndices(p.schema)
newEQConds = append(newEQConds, newCond.(*expression.ScalarFunction))
}
eqCond := p.EqualConditions[condIndex]
otherFilter := append(expression.ScalarFuncs2Exprs(newEQConds), p.OtherConditions...)
join := PhysicalMergeJoin{
EqualConditions: []*expression.ScalarFunction{eqCond},
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
OtherConditions: otherFilter,
DefaultValues: p.DefaultValues,
// Assume order for both side are the same
Desc: lProp.props[0].desc,
}.init(p.allocator, p.ctx)
join.SetSchema(p.schema)
join.JoinType = joinType
var lInfo *physicalPlanInfo
var rInfo *physicalPlanInfo
// Try no sort first
lInfoEnforceSort, err := lChild.convert2PhysicalPlan(&requiredProperty{})
if err != nil {
return nil, errors.Trace(err)
}
lInfoEnforceSort = enforceProperty(lProp, lInfoEnforceSort)
lInfoNoSorted, err := lChild.convert2PhysicalPlan(lProp)
if err != nil {
return nil, errors.Trace(err)
}
if lInfoNoSorted.cost < lInfoEnforceSort.cost {
lInfo = lInfoNoSorted
} else {
lInfo = lInfoEnforceSort
}
rInfoEnforceSort, err := rChild.convert2PhysicalPlan(&requiredProperty{})
if err != nil {
return nil, errors.Trace(err)
}
rInfoEnforceSort = enforceProperty(rProp, rInfoEnforceSort)
rInfoNoSorted, err := rChild.convert2PhysicalPlan(rProp)
if err != nil {
return nil, errors.Trace(err)
}
if rInfoEnforceSort.cost < rInfoNoSorted.cost {
rInfo = rInfoEnforceSort
} else {
rInfo = rInfoNoSorted
}
parentProp = join.tryConsumeOrder(parentProp, eqCond)
resultInfo := join.matchProperty(parentProp, lInfo, rInfo)
// TODO: Considering keeping order in join to remove at least
// one ordering property
resultInfo = enforceProperty(parentProp, resultInfo)
return resultInfo, nil
}
func (p *LogicalJoin) convert2PhysicalMergeJoinOnCost(prop *requiredProperty) (*physicalPlanInfo, error) {
var info *physicalPlanInfo
reqPropPairs, condIndex, err := constructPropertyByJoin(p)
if err != nil {
return nil, errors.Trace(err)
}
if reqPropPairs == nil {
return nil, nil
}
minCost := math.MaxFloat64
var minInfo *physicalPlanInfo
for i, reqPropPair := range reqPropPairs {
info, err = p.convert2PhysicalMergeJoin(prop, reqPropPair[0], reqPropPair[1], condIndex[i], p.JoinType)
if err != nil {
return nil, errors.Trace(err)
}
// Force to choose first instead of nil if all Inf cost
// TODO: Consider cost instead of force merge
if minInfo == nil {
minInfo = info
minCost = info.cost
} else {
if info.cost <= minCost {
minInfo = info
minCost = info.cost
}
}
}
return minInfo, nil
}
func (p *LogicalJoin) hasEqualConds() bool {
return len(p.EqualConditions) != 0
}
// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *LogicalJoin) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
info, err := p.getPlanInfo(prop)
if err != nil {
return nil, errors.Trace(err)
}
if info != nil {
return info, nil
}
switch p.JoinType {
case SemiJoin, LeftOuterSemiJoin:
info, err = p.convert2PhysicalPlanSemi(prop)
if err != nil {
return nil, errors.Trace(err)
}
case LeftOuterJoin:
if p.preferMergeJoin && p.hasEqualConds() {
info, err = p.convert2PhysicalMergeJoinOnCost(prop)
if err != nil {
return nil, errors.Trace(err)
}
if info != nil {
break
}
}
var nljInfo *physicalPlanInfo
nljInfo, err = p.convert2IndexNestedLoopJoinLeft(prop, false)
if err != nil {
return nil, errors.Trace(err)
}
if nljInfo != nil {
info = nljInfo
break
}
// Otherwise fall into hash join
info, err = p.convert2PhysicalPlanLeft(prop, false)
if err != nil {
return nil, errors.Trace(err)
}
case RightOuterJoin:
if p.preferMergeJoin && p.hasEqualConds() {
info, err = p.convert2PhysicalMergeJoinOnCost(prop)
if err != nil {
return nil, errors.Trace(err)
}
if info != nil {
break
}
}
var nljInfo *physicalPlanInfo
nljInfo, err = p.convert2IndexNestedLoopJoinRight(prop, false)
if err != nil {
return nil, errors.Trace(err)
}
if nljInfo != nil {