-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
logical_plans.go
2007 lines (1810 loc) · 73.3 KB
/
logical_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 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,
// 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 (
"math"
"unsafe"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/expression/aggregation"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/auth"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
fd "github.com/pingcap/tidb/planner/funcdep"
"github.com/pingcap/tidb/planner/property"
"github.com/pingcap/tidb/planner/util"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/size"
"go.uber.org/zap"
)
var (
_ LogicalPlan = &LogicalJoin{}
_ LogicalPlan = &LogicalAggregation{}
_ LogicalPlan = &LogicalProjection{}
_ LogicalPlan = &LogicalSelection{}
_ LogicalPlan = &LogicalApply{}
_ LogicalPlan = &LogicalMaxOneRow{}
_ LogicalPlan = &LogicalTableDual{}
_ LogicalPlan = &DataSource{}
_ LogicalPlan = &TiKVSingleGather{}
_ LogicalPlan = &LogicalTableScan{}
_ LogicalPlan = &LogicalIndexScan{}
_ LogicalPlan = &LogicalUnionAll{}
_ LogicalPlan = &LogicalSort{}
_ LogicalPlan = &LogicalLock{}
_ LogicalPlan = &LogicalLimit{}
_ LogicalPlan = &LogicalWindow{}
)
// JoinType contains CrossJoin, InnerJoin, LeftOuterJoin, RightOuterJoin, FullOuterJoin, SemiJoin.
type JoinType int
const (
// InnerJoin means inner join.
InnerJoin JoinType = iota
// LeftOuterJoin means left join.
LeftOuterJoin
// RightOuterJoin means right join.
RightOuterJoin
// SemiJoin means if row a in table A matches some rows in B, just output a.
SemiJoin
// AntiSemiJoin means if row a in table A does not match any row in B, then output a.
AntiSemiJoin
// LeftOuterSemiJoin means if row a in table A matches some rows in B, output (a, true), otherwise, output (a, false).
LeftOuterSemiJoin
// AntiLeftOuterSemiJoin means if row a in table A matches some rows in B, output (a, false), otherwise, output (a, true).
AntiLeftOuterSemiJoin
)
// IsOuterJoin returns if this joiner is an outer joiner
func (tp JoinType) IsOuterJoin() bool {
return tp == LeftOuterJoin || tp == RightOuterJoin ||
tp == LeftOuterSemiJoin || tp == AntiLeftOuterSemiJoin
}
// IsSemiJoin returns if this joiner is a semi/anti-semi joiner
func (tp JoinType) IsSemiJoin() bool {
return tp == SemiJoin || tp == AntiSemiJoin ||
tp == LeftOuterSemiJoin || tp == AntiLeftOuterSemiJoin
}
func (tp JoinType) String() string {
switch tp {
case InnerJoin:
return "inner join"
case LeftOuterJoin:
return "left outer join"
case RightOuterJoin:
return "right outer join"
case SemiJoin:
return "semi join"
case AntiSemiJoin:
return "anti semi join"
case LeftOuterSemiJoin:
return "left outer semi join"
case AntiLeftOuterSemiJoin:
return "anti left outer semi join"
}
return "unsupported join type"
}
const (
preferLeftAsINLJInner uint = 1 << iota
preferRightAsINLJInner
preferLeftAsINLHJInner
preferRightAsINLHJInner
preferLeftAsINLMJInner
preferRightAsINLMJInner
preferHashJoin
preferLeftAsHJBuild
preferRightAsHJBuild
preferLeftAsHJProbe
preferRightAsHJProbe
preferMergeJoin
preferBCJoin
preferShuffleJoin
preferRewriteSemiJoin
preferHashAgg
preferStreamAgg
preferMPP1PhaseAgg
preferMPP2PhaseAgg
)
const (
preferTiKV = 1 << iota
preferTiFlash
)
// LogicalJoin is the logical join plan.
type LogicalJoin struct {
logicalSchemaProducer
JoinType JoinType
reordered bool
cartesianJoin bool
StraightJoin bool
// hintInfo stores the join algorithm hint information specified by client.
hintInfo *tableHintInfo
preferJoinType uint
preferJoinOrder bool
EqualConditions []*expression.ScalarFunction
NAEQConditions []*expression.ScalarFunction
LeftConditions expression.CNFExprs
RightConditions expression.CNFExprs
OtherConditions expression.CNFExprs
leftProperties [][]*expression.Column
rightProperties [][]*expression.Column
// DefaultValues is only used for left/right outer join, which is values the inner row's should be when the outer table
// doesn't match any inner table's row.
// That it's nil just means the default values is a slice of NULL.
// Currently, only `aggregation push down` phase will set this.
DefaultValues []types.Datum
// fullSchema contains all the columns that the Join can output. It's ordered as [outer schema..., inner schema...].
// This is useful for natural joins and "using" joins. In these cases, the join key columns from the
// inner side (or the right side when it's an inner join) will not be in the schema of Join.
// But upper operators should be able to find those "redundant" columns, and the user also can specifically select
// those columns, so we put the "redundant" columns here to make them be able to be found.
//
// For example:
// create table t1(a int, b int); create table t2(a int, b int);
// select * from t1 join t2 using (b);
// schema of the Join will be [t1.b, t1.a, t2.a]; fullSchema will be [t1.a, t1.b, t2.a, t2.b].
//
// We record all columns and keep them ordered is for correctly handling SQLs like
// select t1.*, t2.* from t1 join t2 using (b);
// (*PlanBuilder).unfoldWildStar() handles the schema for such case.
fullSchema *expression.Schema
fullNames types.NameSlice
// equalCondOutCnt indicates the estimated count of joined rows after evaluating `EqualConditions`.
equalCondOutCnt float64
}
func (p *LogicalJoin) isNAAJ() bool {
return len(p.NAEQConditions) > 0
}
// Shallow shallow copies a LogicalJoin struct.
func (p *LogicalJoin) Shallow() *LogicalJoin {
join := *p
return join.Init(p.ctx, p.blockOffset)
}
// ExtractFD implements the interface LogicalPlan.
func (p *LogicalJoin) ExtractFD() *fd.FDSet {
switch p.JoinType {
case InnerJoin:
return p.extractFDForInnerJoin(nil)
case LeftOuterJoin, RightOuterJoin:
return p.extractFDForOuterJoin(nil)
case SemiJoin:
return p.extractFDForSemiJoin(nil)
default:
return &fd.FDSet{HashCodeToUniqueID: make(map[string]int)}
}
}
func (p *LogicalJoin) extractFDForSemiJoin(filtersFromApply []expression.Expression) *fd.FDSet {
// 1: since semi join will keep the part or all rows of the outer table, it's outer FD can be saved.
// 2: the un-projected column will be left for the upper layer projection or already be pruned from bottom up.
outerFD, _ := p.children[0].ExtractFD(), p.children[1].ExtractFD()
fds := outerFD
eqCondSlice := expression.ScalarFuncs2Exprs(p.EqualConditions)
allConds := append(eqCondSlice, p.OtherConditions...)
allConds = append(allConds, filtersFromApply...)
notNullColsFromFilters := extractNotNullFromConds(allConds, p)
constUniqueIDs := extractConstantCols(p.LeftConditions, p.SCtx(), fds)
fds.MakeNotNull(notNullColsFromFilters)
fds.AddConstants(constUniqueIDs)
p.fdSet = fds
return fds
}
func (p *LogicalJoin) extractFDForInnerJoin(filtersFromApply []expression.Expression) *fd.FDSet {
leftFD, rightFD := p.children[0].ExtractFD(), p.children[1].ExtractFD()
fds := leftFD
fds.MakeCartesianProduct(rightFD)
eqCondSlice := expression.ScalarFuncs2Exprs(p.EqualConditions)
// some join eq conditions are stored in the OtherConditions.
allConds := append(eqCondSlice, p.OtherConditions...)
allConds = append(allConds, filtersFromApply...)
notNullColsFromFilters := extractNotNullFromConds(allConds, p)
constUniqueIDs := extractConstantCols(allConds, p.SCtx(), fds)
equivUniqueIDs := extractEquivalenceCols(allConds, p.SCtx(), fds)
fds.MakeNotNull(notNullColsFromFilters)
fds.AddConstants(constUniqueIDs)
for _, equiv := range equivUniqueIDs {
fds.AddEquivalence(equiv[0], equiv[1])
}
// merge the not-null-cols/registered-map from both side together.
fds.NotNullCols.UnionWith(rightFD.NotNullCols)
if fds.HashCodeToUniqueID == nil {
fds.HashCodeToUniqueID = rightFD.HashCodeToUniqueID
} else {
for k, v := range rightFD.HashCodeToUniqueID {
// If there's same constant in the different subquery, we might go into this IF branch.
if _, ok := fds.HashCodeToUniqueID[k]; ok {
continue
}
fds.HashCodeToUniqueID[k] = v
}
}
for i, ok := rightFD.GroupByCols.Next(0); ok; i, ok = rightFD.GroupByCols.Next(i + 1) {
fds.GroupByCols.Insert(i)
}
fds.HasAggBuilt = fds.HasAggBuilt || rightFD.HasAggBuilt
p.fdSet = fds
return fds
}
func (p *LogicalJoin) extractFDForOuterJoin(filtersFromApply []expression.Expression) *fd.FDSet {
outerFD, innerFD := p.children[0].ExtractFD(), p.children[1].ExtractFD()
innerCondition := p.RightConditions
outerCondition := p.LeftConditions
outerCols, innerCols := fd.NewFastIntSet(), fd.NewFastIntSet()
for _, col := range p.children[0].Schema().Columns {
outerCols.Insert(int(col.UniqueID))
}
for _, col := range p.children[1].Schema().Columns {
innerCols.Insert(int(col.UniqueID))
}
if p.JoinType == RightOuterJoin {
innerFD, outerFD = outerFD, innerFD
innerCondition = p.LeftConditions
outerCondition = p.RightConditions
innerCols, outerCols = outerCols, innerCols
}
eqCondSlice := expression.ScalarFuncs2Exprs(p.EqualConditions)
allConds := append(eqCondSlice, p.OtherConditions...)
allConds = append(allConds, innerCondition...)
allConds = append(allConds, outerCondition...)
allConds = append(allConds, filtersFromApply...)
notNullColsFromFilters := extractNotNullFromConds(allConds, p)
filterFD := &fd.FDSet{HashCodeToUniqueID: make(map[string]int)}
constUniqueIDs := extractConstantCols(allConds, p.SCtx(), filterFD)
equivUniqueIDs := extractEquivalenceCols(allConds, p.SCtx(), filterFD)
filterFD.AddConstants(constUniqueIDs)
equivOuterUniqueIDs := fd.NewFastIntSet()
equivAcrossNum := 0
for _, equiv := range equivUniqueIDs {
filterFD.AddEquivalence(equiv[0], equiv[1])
if equiv[0].SubsetOf(outerCols) && equiv[1].SubsetOf(innerCols) {
equivOuterUniqueIDs.UnionWith(equiv[0])
equivAcrossNum++
continue
}
if equiv[0].SubsetOf(innerCols) && equiv[1].SubsetOf(outerCols) {
equivOuterUniqueIDs.UnionWith(equiv[1])
equivAcrossNum++
}
}
filterFD.MakeNotNull(notNullColsFromFilters)
// pre-perceive the filters for the convenience judgement of 3.3.1.
var opt fd.ArgOpts
if equivAcrossNum > 0 {
// find the equivalence FD across left and right cols.
var outConditionCols []*expression.Column
if len(outerCondition) != 0 {
outConditionCols = append(outConditionCols, expression.ExtractColumnsFromExpressions(nil, outerCondition, nil)...)
}
if len(p.OtherConditions) != 0 {
// other condition may contain right side cols, it doesn't affect the judgement of intersection of non-left-equiv cols.
outConditionCols = append(outConditionCols, expression.ExtractColumnsFromExpressions(nil, p.OtherConditions, nil)...)
}
outerConditionUniqueIDs := fd.NewFastIntSet()
for _, col := range outConditionCols {
outerConditionUniqueIDs.Insert(int(col.UniqueID))
}
// judge whether left filters is on non-left-equiv cols.
if outerConditionUniqueIDs.Intersects(outerCols.Difference(equivOuterUniqueIDs)) {
opt.SkipFDRule331 = true
}
} else {
// if there is none across equivalence condition, skip rule 3.3.1.
opt.SkipFDRule331 = true
}
opt.OnlyInnerFilter = len(eqCondSlice) == 0 && len(outerCondition) == 0 && len(p.OtherConditions) == 0
if opt.OnlyInnerFilter {
// if one of the inner condition is constant false, the inner side are all null, left make constant all of that.
for _, one := range innerCondition {
if c, ok := one.(*expression.Constant); ok && c.DeferredExpr == nil && c.ParamMarker == nil {
if isTrue, err := c.Value.ToBool(p.ctx.GetSessionVars().StmtCtx); err == nil {
if isTrue == 0 {
// c is false
opt.InnerIsFalse = true
}
}
}
}
}
fds := outerFD
fds.MakeOuterJoin(innerFD, filterFD, outerCols, innerCols, &opt)
p.fdSet = fds
return fds
}
// GetJoinKeys extracts join keys(columns) from EqualConditions. It returns left join keys, right
// join keys and an `isNullEQ` array which means the `joinKey[i]` is a `NullEQ` function. The `hasNullEQ`
// means whether there is a `NullEQ` of a join key.
func (p *LogicalJoin) GetJoinKeys() (leftKeys, rightKeys []*expression.Column, isNullEQ []bool, hasNullEQ bool) {
for _, expr := range p.EqualConditions {
leftKeys = append(leftKeys, expr.GetArgs()[0].(*expression.Column))
rightKeys = append(rightKeys, expr.GetArgs()[1].(*expression.Column))
isNullEQ = append(isNullEQ, expr.FuncName.L == ast.NullEQ)
hasNullEQ = hasNullEQ || expr.FuncName.L == ast.NullEQ
}
return
}
// GetNAJoinKeys extracts join keys(columns) from NAEqualCondition.
func (p *LogicalJoin) GetNAJoinKeys() (leftKeys, rightKeys []*expression.Column) {
for _, expr := range p.NAEQConditions {
leftKeys = append(leftKeys, expr.GetArgs()[0].(*expression.Column))
rightKeys = append(rightKeys, expr.GetArgs()[1].(*expression.Column))
}
return
}
// GetPotentialPartitionKeys return potential partition keys for join, the potential partition keys are
// the join keys of EqualConditions
func (p *LogicalJoin) GetPotentialPartitionKeys() (leftKeys, rightKeys []*property.MPPPartitionColumn) {
for _, expr := range p.EqualConditions {
_, coll := expr.CharsetAndCollation()
collateID := property.GetCollateIDByNameForPartition(coll)
leftKeys = append(leftKeys, &property.MPPPartitionColumn{Col: expr.GetArgs()[0].(*expression.Column), CollateID: collateID})
rightKeys = append(rightKeys, &property.MPPPartitionColumn{Col: expr.GetArgs()[1].(*expression.Column), CollateID: collateID})
}
return
}
// decorrelate eliminate the correlated column with if the col is in schema.
func (p *LogicalJoin) decorrelate(schema *expression.Schema) {
for i, cond := range p.LeftConditions {
p.LeftConditions[i] = cond.Decorrelate(schema)
}
for i, cond := range p.RightConditions {
p.RightConditions[i] = cond.Decorrelate(schema)
}
for i, cond := range p.OtherConditions {
p.OtherConditions[i] = cond.Decorrelate(schema)
}
for i, cond := range p.EqualConditions {
p.EqualConditions[i] = cond.Decorrelate(schema).(*expression.ScalarFunction)
}
}
// columnSubstituteAll is used in projection elimination in apply de-correlation.
// Substitutions for all conditions should be successful, otherwise, we should keep all conditions unchanged.
func (p *LogicalJoin) columnSubstituteAll(schema *expression.Schema, exprs []expression.Expression) (hasFail bool) {
// make a copy of exprs for convenience of substitution (may change/partially change the expr tree)
cpLeftConditions := make(expression.CNFExprs, len(p.LeftConditions))
cpRightConditions := make(expression.CNFExprs, len(p.RightConditions))
cpOtherConditions := make(expression.CNFExprs, len(p.OtherConditions))
cpEqualConditions := make([]*expression.ScalarFunction, len(p.EqualConditions))
copy(cpLeftConditions, p.LeftConditions)
copy(cpRightConditions, p.RightConditions)
copy(cpOtherConditions, p.OtherConditions)
copy(cpEqualConditions, p.EqualConditions)
// try to substitute columns in these condition.
for i, cond := range cpLeftConditions {
if hasFail, cpLeftConditions[i] = expression.ColumnSubstituteAll(cond, schema, exprs); hasFail {
return
}
}
for i, cond := range cpRightConditions {
if hasFail, cpRightConditions[i] = expression.ColumnSubstituteAll(cond, schema, exprs); hasFail {
return
}
}
for i, cond := range cpOtherConditions {
if hasFail, cpOtherConditions[i] = expression.ColumnSubstituteAll(cond, schema, exprs); hasFail {
return
}
}
for i, cond := range cpEqualConditions {
var tmp expression.Expression
if hasFail, tmp = expression.ColumnSubstituteAll(cond, schema, exprs); hasFail {
return
}
cpEqualConditions[i] = tmp.(*expression.ScalarFunction)
}
// if all substituted, change them atomically here.
p.LeftConditions = cpLeftConditions
p.RightConditions = cpRightConditions
p.OtherConditions = cpOtherConditions
p.EqualConditions = cpEqualConditions
for i := len(p.EqualConditions) - 1; i >= 0; i-- {
newCond := p.EqualConditions[i]
// If the columns used in the new filter all come from the left child,
// we can push this filter to it.
if expression.ExprFromSchema(newCond, p.children[0].Schema()) {
p.LeftConditions = append(p.LeftConditions, newCond)
p.EqualConditions = append(p.EqualConditions[:i], p.EqualConditions[i+1:]...)
continue
}
// If the columns used in the new filter all come from the right
// child, we can push this filter to it.
if expression.ExprFromSchema(newCond, p.children[1].Schema()) {
p.RightConditions = append(p.RightConditions, newCond)
p.EqualConditions = append(p.EqualConditions[:i], p.EqualConditions[i+1:]...)
continue
}
_, lhsIsCol := newCond.GetArgs()[0].(*expression.Column)
_, rhsIsCol := newCond.GetArgs()[1].(*expression.Column)
// If the columns used in the new filter are not all expression.Column,
// we can not use it as join's equal condition.
if !(lhsIsCol && rhsIsCol) {
p.OtherConditions = append(p.OtherConditions, newCond)
p.EqualConditions = append(p.EqualConditions[:i], p.EqualConditions[i+1:]...)
continue
}
p.EqualConditions[i] = newCond
}
return false
}
// AttachOnConds extracts on conditions for join and set the `EqualConditions`, `LeftConditions`, `RightConditions` and
// `OtherConditions` by the result of extract.
func (p *LogicalJoin) AttachOnConds(onConds []expression.Expression) {
eq, left, right, other := p.extractOnCondition(onConds, false, false)
p.AppendJoinConds(eq, left, right, other)
}
// AppendJoinConds appends new join conditions.
func (p *LogicalJoin) AppendJoinConds(eq []*expression.ScalarFunction, left, right, other []expression.Expression) {
p.EqualConditions = append(eq, p.EqualConditions...)
p.LeftConditions = append(left, p.LeftConditions...)
p.RightConditions = append(right, p.RightConditions...)
p.OtherConditions = append(other, p.OtherConditions...)
}
// ExtractCorrelatedCols implements LogicalPlan interface.
func (p *LogicalJoin) ExtractCorrelatedCols() []*expression.CorrelatedColumn {
corCols := make([]*expression.CorrelatedColumn, 0, len(p.EqualConditions)+len(p.LeftConditions)+len(p.RightConditions)+len(p.OtherConditions))
for _, fun := range p.EqualConditions {
corCols = append(corCols, expression.ExtractCorColumns(fun)...)
}
for _, fun := range p.LeftConditions {
corCols = append(corCols, expression.ExtractCorColumns(fun)...)
}
for _, fun := range p.RightConditions {
corCols = append(corCols, expression.ExtractCorColumns(fun)...)
}
for _, fun := range p.OtherConditions {
corCols = append(corCols, expression.ExtractCorColumns(fun)...)
}
return corCols
}
// ExtractJoinKeys extract join keys as a schema for child with childIdx.
func (p *LogicalJoin) ExtractJoinKeys(childIdx int) *expression.Schema {
joinKeys := make([]*expression.Column, 0, len(p.EqualConditions))
for _, eqCond := range p.EqualConditions {
joinKeys = append(joinKeys, eqCond.GetArgs()[childIdx].(*expression.Column))
}
return expression.NewSchema(joinKeys...)
}
// LogicalProjection represents a select fields plan.
type LogicalProjection struct {
logicalSchemaProducer
Exprs []expression.Expression
// CalculateNoDelay indicates this Projection is the root Plan and should be
// calculated without delay and will not return any result to client.
// Currently it is "true" only when the current sql query is a "DO" statement.
// See "https://dev.mysql.com/doc/refman/5.7/en/do.html" for more detail.
CalculateNoDelay bool
// AvoidColumnEvaluator is a temporary variable which is ONLY used to avoid
// building columnEvaluator for the expressions of Projection which is
// built by buildProjection4Union.
// This can be removed after column pool being supported.
// Related issue: TiDB#8141(https://github.com/pingcap/tidb/issues/8141)
AvoidColumnEvaluator bool
}
// ExtractFD implements the logical plan interface, extracting the FD from bottom up.
func (p *LogicalProjection) ExtractFD() *fd.FDSet {
// basically extract the children's fdSet.
fds := p.logicalSchemaProducer.ExtractFD()
// collect the output columns' unique ID.
outputColsUniqueIDs := fd.NewFastIntSet()
notnullColsUniqueIDs := fd.NewFastIntSet()
outputColsUniqueIDsArray := make([]int, 0, len(p.Schema().Columns))
// here schema extended columns may contain expr, const and column allocated with uniqueID.
for _, one := range p.Schema().Columns {
outputColsUniqueIDs.Insert(int(one.UniqueID))
outputColsUniqueIDsArray = append(outputColsUniqueIDsArray, int(one.UniqueID))
}
// map the expr hashCode with its unique ID.
for idx, expr := range p.Exprs {
switch x := expr.(type) {
case *expression.Column:
continue
case *expression.CorrelatedColumn:
// t1(a,b,c), t2(m,n)
// select a, (select c from t2 where m=b) from t1;
// take c as constant column here.
continue
case *expression.Constant:
hashCode := string(x.HashCode(p.ctx.GetSessionVars().StmtCtx))
var (
ok bool
constantUniqueID int
)
if constantUniqueID, ok = fds.IsHashCodeRegistered(hashCode); !ok {
constantUniqueID = outputColsUniqueIDsArray[idx]
fds.RegisterUniqueID(string(x.HashCode(p.ctx.GetSessionVars().StmtCtx)), constantUniqueID)
}
fds.AddConstants(fd.NewFastIntSet(constantUniqueID))
case *expression.ScalarFunction:
// t1(a,b,c), t2(m,n)
// select a, (select c+n from t2 where m=b) from t1;
// expr(c+n) contains correlated column , but we can treat it as constant here.
hashCode := string(x.HashCode(p.ctx.GetSessionVars().StmtCtx))
var (
ok bool
scalarUniqueID int
)
// If this function is not deterministic, we skip it since it not a stable value.
if expression.CheckNonDeterministic(x) {
if scalarUniqueID, ok = fds.IsHashCodeRegistered(hashCode); !ok {
fds.RegisterUniqueID(hashCode, scalarUniqueID)
}
continue
}
if scalarUniqueID, ok = fds.IsHashCodeRegistered(hashCode); !ok {
scalarUniqueID = outputColsUniqueIDsArray[idx]
fds.RegisterUniqueID(hashCode, scalarUniqueID)
} else {
// since the scalar's hash code has been registered before, the equivalence exists between the unique ID
// allocated by phase of building-projection-for-scalar and that of previous registered unique ID.
fds.AddEquivalence(fd.NewFastIntSet(scalarUniqueID), fd.NewFastIntSet(outputColsUniqueIDsArray[idx]))
}
determinants := fd.NewFastIntSet()
extractedColumns := expression.ExtractColumns(x)
extractedCorColumns := expression.ExtractCorColumns(x)
for _, one := range extractedColumns {
determinants.Insert(int(one.UniqueID))
// the dependent columns in scalar function should be also considered as output columns as well.
outputColsUniqueIDs.Insert(int(one.UniqueID))
}
for _, one := range extractedCorColumns {
determinants.Insert(int(one.UniqueID))
// the dependent columns in scalar function should be also considered as output columns as well.
outputColsUniqueIDs.Insert(int(one.UniqueID))
}
notnull := isNullRejected(p.ctx, p.schema, x)
if notnull || determinants.SubsetOf(fds.NotNullCols) {
notnullColsUniqueIDs.Insert(scalarUniqueID)
}
fds.AddStrictFunctionalDependency(determinants, fd.NewFastIntSet(scalarUniqueID))
}
}
// apply operator's characteristic's FD setting.
// since the distinct attribute is built as firstRow agg func, we don't need to think about it here.
// let the fds itself to trace the not null, because after the outer join, some not null column can be nullable.
fds.MakeNotNull(notnullColsUniqueIDs)
// select max(a) from t group by b, we should project both `a` & `b` to maintain the FD down here, even if select-fields only contain `a`.
fds.ProjectCols(outputColsUniqueIDs.Union(fds.GroupByCols))
// just trace it down in every operator for test checking.
p.fdSet = fds
return fds
}
// ExtractCorrelatedCols implements LogicalPlan interface.
func (p *LogicalProjection) ExtractCorrelatedCols() []*expression.CorrelatedColumn {
corCols := make([]*expression.CorrelatedColumn, 0, len(p.Exprs))
for _, expr := range p.Exprs {
corCols = append(corCols, expression.ExtractCorColumns(expr)...)
}
return corCols
}
// GetUsedCols extracts all of the Columns used by proj.
func (p *LogicalProjection) GetUsedCols() (usedCols []*expression.Column) {
for _, expr := range p.Exprs {
usedCols = append(usedCols, expression.ExtractColumns(expr)...)
}
return usedCols
}
// LogicalAggregation represents an aggregate plan.
type LogicalAggregation struct {
logicalSchemaProducer
AggFuncs []*aggregation.AggFuncDesc
GroupByItems []expression.Expression
// aggHints stores aggregation hint information.
aggHints aggHintInfo
possibleProperties [][]*expression.Column
inputCount float64 // inputCount is the input count of this plan.
// noCopPushDown indicates if planner must not push this agg down to coprocessor.
// It is true when the agg is in the outer child tree of apply.
noCopPushDown bool
}
// HasDistinct shows whether LogicalAggregation has functions with distinct.
func (la *LogicalAggregation) HasDistinct() bool {
for _, aggFunc := range la.AggFuncs {
if aggFunc.HasDistinct {
return true
}
}
return false
}
// HasOrderBy shows whether LogicalAggregation has functions with order-by items.
func (la *LogicalAggregation) HasOrderBy() bool {
for _, aggFunc := range la.AggFuncs {
if len(aggFunc.OrderByItems) > 0 {
return true
}
}
return false
}
// ExtractFD implements the logical plan interface, extracting the FD from bottom up.
// 1:
// In most of the cases, using FDs to check the only_full_group_by problem should be done in the buildAggregation phase
// by extracting the bottom-up FDs graph from the `p` --- the sub plan tree that has already been built.
//
// 2:
// and this requires that some conditions push-down into the `p` like selection should be done before building aggregation,
// otherwise, 'a=1 and a can occur in the select lists of a group by' will be miss-checked because it doesn't be implied in the known FDs graph.
//
// 3:
// when a logical agg is built, it's schema columns indicates what the permitted-non-agg columns is. Therefore, we shouldn't
// depend on logicalAgg.ExtractFD() to finish the only_full_group_by checking problem rather than by 1 & 2.
func (la *LogicalAggregation) ExtractFD() *fd.FDSet {
// basically extract the children's fdSet.
fds := la.logicalSchemaProducer.ExtractFD()
// collect the output columns' unique ID.
outputColsUniqueIDs := fd.NewFastIntSet()
notnullColsUniqueIDs := fd.NewFastIntSet()
groupByColsUniqueIDs := fd.NewFastIntSet()
groupByColsOutputCols := fd.NewFastIntSet()
// Since the aggregation is build ahead of projection, the latter one will reuse the column with UniqueID allocated in aggregation
// via aggMapper, so we don't need unnecessarily maintain the <aggDes, UniqueID> mapping in the FDSet like expr did, just treating
// it as normal column.
for _, one := range la.Schema().Columns {
outputColsUniqueIDs.Insert(int(one.UniqueID))
}
// For one like sum(a), we don't need to build functional dependency from a --> sum(a), cause it's only determined by the
// group-by-item (group-by-item --> sum(a)).
for _, expr := range la.GroupByItems {
switch x := expr.(type) {
case *expression.Column:
groupByColsUniqueIDs.Insert(int(x.UniqueID))
case *expression.CorrelatedColumn:
// shouldn't be here, intercepted by plan builder as unknown column.
continue
case *expression.Constant:
// shouldn't be here, interpreted as pos param by plan builder.
continue
case *expression.ScalarFunction:
hashCode := string(x.HashCode(la.ctx.GetSessionVars().StmtCtx))
var (
ok bool
scalarUniqueID int
)
if scalarUniqueID, ok = fds.IsHashCodeRegistered(hashCode); ok {
groupByColsUniqueIDs.Insert(scalarUniqueID)
} else {
// retrieve unique plan column id. 1: completely new one, allocating new unique id. 2: registered by projection earlier, using it.
if scalarUniqueID, ok = la.ctx.GetSessionVars().MapHashCode2UniqueID4ExtendedCol[hashCode]; !ok {
scalarUniqueID = int(la.ctx.GetSessionVars().AllocPlanColumnID())
}
fds.RegisterUniqueID(hashCode, scalarUniqueID)
groupByColsUniqueIDs.Insert(scalarUniqueID)
}
determinants := fd.NewFastIntSet()
extractedColumns := expression.ExtractColumns(x)
extractedCorColumns := expression.ExtractCorColumns(x)
for _, one := range extractedColumns {
determinants.Insert(int(one.UniqueID))
groupByColsOutputCols.Insert(int(one.UniqueID))
}
for _, one := range extractedCorColumns {
determinants.Insert(int(one.UniqueID))
groupByColsOutputCols.Insert(int(one.UniqueID))
}
notnull := isNullRejected(la.ctx, la.schema, x)
if notnull || determinants.SubsetOf(fds.NotNullCols) {
notnullColsUniqueIDs.Insert(scalarUniqueID)
}
fds.AddStrictFunctionalDependency(determinants, fd.NewFastIntSet(scalarUniqueID))
}
}
// Some details:
// For now, select max(a) from t group by c, tidb will see `max(a)` as Max aggDes and `a,b,c` as firstRow aggDes,
// and keep them all in the schema columns before projection does the pruning. If we build the fake FD eg: {c} ~~> {b}
// here since we have seen b as firstRow aggDes, for the upper layer projection of `select max(a), b from t group by c`,
// it will take b as valid projection field of group by statement since it has existed in the FD with {c} ~~> {b}.
//
// and since any_value will NOT be pushed down to agg schema, which means every firstRow aggDes in the agg logical operator
// is meaningless to build the FD with. Let's only store the non-firstRow FD down: {group by items} ~~> {real aggDes}
realAggFuncUniqueID := fd.NewFastIntSet()
for i, aggDes := range la.AggFuncs {
if aggDes.Name != "firstrow" {
realAggFuncUniqueID.Insert(int(la.schema.Columns[i].UniqueID))
}
}
// apply operator's characteristic's FD setting.
if len(la.GroupByItems) == 0 {
// 1: as the details shown above, output cols (normal column seen as firstrow) of group by are not validated.
// we couldn't merge them as constant FD with origin constant FD together before projection done.
// fds.MaxOneRow(outputColsUniqueIDs.Union(groupByColsOutputCols))
//
// 2: for the convenience of later judgement, when there is no group by items, we will store a FD: {0} -> {real aggDes}
// 0 unique id is only used for here.
groupByColsUniqueIDs.Insert(0)
for i, ok := realAggFuncUniqueID.Next(0); ok; i, ok = realAggFuncUniqueID.Next(i + 1) {
fds.AddStrictFunctionalDependency(groupByColsUniqueIDs, fd.NewFastIntSet(i))
}
} else {
// eliminating input columns that are un-projected.
fds.ProjectCols(outputColsUniqueIDs.Union(groupByColsOutputCols).Union(groupByColsUniqueIDs))
// note: {a} --> {b,c} is not same with {a} --> {b} and {a} --> {c}
for i, ok := realAggFuncUniqueID.Next(0); ok; i, ok = realAggFuncUniqueID.Next(i + 1) {
// group by phrase always produce strict FD.
// 1: it can always distinguish and group the all-null/part-null group column rows.
// 2: the rows with all/part null group column are unique row after group operation.
// 3: there won't be two same group key with different agg values, so strict FD secured.
fds.AddStrictFunctionalDependency(groupByColsUniqueIDs, fd.NewFastIntSet(i))
}
// agg funcDes has been tag not null flag when building aggregation.
fds.MakeNotNull(notnullColsUniqueIDs)
}
fds.GroupByCols = groupByColsUniqueIDs
fds.HasAggBuilt = true
// just trace it down in every operator for test checking.
la.fdSet = fds
return fds
}
// CopyAggHints copies the aggHints from another LogicalAggregation.
func (la *LogicalAggregation) CopyAggHints(agg *LogicalAggregation) {
// TODO: Copy the hint may make the un-applicable hint throw the
// same warning message more than once. We'd better add a flag for
// `HaveThrownWarningMessage` to avoid this. Besides, finalAgg and
// partialAgg (in cascades planner) should share the same hint, instead
// of a copy.
la.aggHints = agg.aggHints
}
// IsPartialModeAgg returns if all of the AggFuncs are partialMode.
func (la *LogicalAggregation) IsPartialModeAgg() bool {
// Since all of the AggFunc share the same AggMode, we only need to check the first one.
return la.AggFuncs[0].Mode == aggregation.Partial1Mode
}
// IsCompleteModeAgg returns if all of the AggFuncs are CompleteMode.
func (la *LogicalAggregation) IsCompleteModeAgg() bool {
// Since all of the AggFunc share the same AggMode, we only need to check the first one.
return la.AggFuncs[0].Mode == aggregation.CompleteMode
}
// GetGroupByCols returns the columns that are group-by items.
// For example, `group by a, b, c+d` will return [a, b].
func (la *LogicalAggregation) GetGroupByCols() []*expression.Column {
groupByCols := make([]*expression.Column, 0, len(la.GroupByItems))
for _, item := range la.GroupByItems {
if col, ok := item.(*expression.Column); ok {
groupByCols = append(groupByCols, col)
}
}
return groupByCols
}
// GetPotentialPartitionKeys return potential partition keys for aggregation, the potential partition keys are the group by keys
func (la *LogicalAggregation) GetPotentialPartitionKeys() []*property.MPPPartitionColumn {
groupByCols := make([]*property.MPPPartitionColumn, 0, len(la.GroupByItems))
for _, item := range la.GroupByItems {
if col, ok := item.(*expression.Column); ok {
groupByCols = append(groupByCols, &property.MPPPartitionColumn{
Col: col,
CollateID: property.GetCollateIDByNameForPartition(col.GetType().GetCollate()),
})
}
}
return groupByCols
}
// ExtractCorrelatedCols implements LogicalPlan interface.
func (la *LogicalAggregation) ExtractCorrelatedCols() []*expression.CorrelatedColumn {
corCols := make([]*expression.CorrelatedColumn, 0, len(la.GroupByItems)+len(la.AggFuncs))
for _, expr := range la.GroupByItems {
corCols = append(corCols, expression.ExtractCorColumns(expr)...)
}
for _, fun := range la.AggFuncs {
for _, arg := range fun.Args {
corCols = append(corCols, expression.ExtractCorColumns(arg)...)
}
for _, arg := range fun.OrderByItems {
corCols = append(corCols, expression.ExtractCorColumns(arg.Expr)...)
}
}
return corCols
}
// GetUsedCols extracts all of the Columns used by agg including GroupByItems and AggFuncs.
func (la *LogicalAggregation) GetUsedCols() (usedCols []*expression.Column) {
for _, groupByItem := range la.GroupByItems {
usedCols = append(usedCols, expression.ExtractColumns(groupByItem)...)
}
for _, aggDesc := range la.AggFuncs {
for _, expr := range aggDesc.Args {
usedCols = append(usedCols, expression.ExtractColumns(expr)...)
}
for _, expr := range aggDesc.OrderByItems {
usedCols = append(usedCols, expression.ExtractColumns(expr.Expr)...)
}
}
return usedCols
}
// LogicalSelection represents a where or having predicate.
type LogicalSelection struct {
baseLogicalPlan
// Originally the WHERE or ON condition is parsed into a single expression,
// but after we converted to CNF(Conjunctive normal form), it can be
// split into a list of AND conditions.
Conditions []expression.Expression
}
func extractNotNullFromConds(Conditions []expression.Expression, p LogicalPlan) fd.FastIntSet {
// extract the column NOT NULL rejection characteristic from selection condition.
// CNF considered only, DNF doesn't have its meanings (cause that condition's eval may don't take effect)
//
// Take this case: select * from t where (a = 1) and (b is null):
//
// If we wanna where phrase eval to true, two pre-condition: {a=1} and {b is null} both need to be true.
// Hence, we assert that:
//
// 1: `a` must not be null since `NULL = 1` is evaluated as NULL.
// 2: `b` must be null since only `NULL is NULL` is evaluated as true.
//
// As a result, `a` will be extracted as not-null column to abound the FDSet.
notnullColsUniqueIDs := fd.NewFastIntSet()
for _, condition := range Conditions {
var cols []*expression.Column
cols = expression.ExtractColumnsFromExpressions(cols, []expression.Expression{condition}, nil)
if isNullRejected(p.SCtx(), p.Schema(), condition) {
for _, col := range cols {
notnullColsUniqueIDs.Insert(int(col.UniqueID))
}
}
}
return notnullColsUniqueIDs
}
func extractConstantCols(Conditions []expression.Expression, sctx sessionctx.Context, fds *fd.FDSet) fd.FastIntSet {
// extract constant cols
// eg: where a=1 and b is null and (1+c)=5.
// TODO: Some columns can only be determined to be constant from multiple constraints (e.g. x <= 1 AND x >= 1)
var (
constObjs []expression.Expression
constUniqueIDs = fd.NewFastIntSet()
)
constObjs = expression.ExtractConstantEqColumnsOrScalar(sctx, constObjs, Conditions)
for _, constObj := range constObjs {
switch x := constObj.(type) {
case *expression.Column:
constUniqueIDs.Insert(int(x.UniqueID))
case *expression.ScalarFunction:
hashCode := string(x.HashCode(sctx.GetSessionVars().StmtCtx))
if uniqueID, ok := fds.IsHashCodeRegistered(hashCode); ok {
constUniqueIDs.Insert(uniqueID)
} else {
scalarUniqueID := int(sctx.GetSessionVars().AllocPlanColumnID())
fds.RegisterUniqueID(string(x.HashCode(sctx.GetSessionVars().StmtCtx)), scalarUniqueID)
constUniqueIDs.Insert(scalarUniqueID)
}
}
}
return constUniqueIDs
}
func extractEquivalenceCols(Conditions []expression.Expression, sctx sessionctx.Context, fds *fd.FDSet) [][]fd.FastIntSet {
var equivObjsPair [][]expression.Expression
equivObjsPair = expression.ExtractEquivalenceColumns(equivObjsPair, Conditions)
equivUniqueIDs := make([][]fd.FastIntSet, 0, len(equivObjsPair))
for _, equivObjPair := range equivObjsPair {
// lhs of equivalence.
var (
lhsUniqueID int
rhsUniqueID int
)
switch x := equivObjPair[0].(type) {
case *expression.Column:
lhsUniqueID = int(x.UniqueID)
case *expression.ScalarFunction:
hashCode := string(x.HashCode(sctx.GetSessionVars().StmtCtx))
if uniqueID, ok := fds.IsHashCodeRegistered(hashCode); ok {
lhsUniqueID = uniqueID
} else {
scalarUniqueID := int(sctx.GetSessionVars().AllocPlanColumnID())
fds.RegisterUniqueID(string(x.HashCode(sctx.GetSessionVars().StmtCtx)), scalarUniqueID)
lhsUniqueID = scalarUniqueID
}
}
// rhs of equivalence.
switch x := equivObjPair[1].(type) {
case *expression.Column:
rhsUniqueID = int(x.UniqueID)
case *expression.ScalarFunction:
hashCode := string(x.HashCode(sctx.GetSessionVars().StmtCtx))