-
Notifications
You must be signed in to change notification settings - Fork 0
/
transformation_rules.go
2590 lines (2320 loc) · 98.2 KB
/
transformation_rules.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 2018 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 cascades
import (
"math"
"github.com/wuhuizuo/tidb6/expression"
"github.com/wuhuizuo/tidb6/expression/aggregation"
"github.com/wuhuizuo/tidb6/kv"
"github.com/wuhuizuo/tidb6/parser/ast"
"github.com/wuhuizuo/tidb6/parser/mysql"
plannercore "github.com/wuhuizuo/tidb6/planner/core"
"github.com/wuhuizuo/tidb6/planner/memo"
"github.com/wuhuizuo/tidb6/planner/util"
"github.com/wuhuizuo/tidb6/sessionctx"
"github.com/wuhuizuo/tidb6/types"
"github.com/wuhuizuo/tidb6/util/ranger"
"github.com/wuhuizuo/tidb6/util/set"
)
// Transformation defines the interface for the transformation rules.
type Transformation interface {
// GetPattern gets the cached pattern of the rule.
GetPattern() *memo.Pattern
// Match is used to check whether the GroupExpr satisfies all the requirements of the transformation rule.
//
// The pattern only identifies the operator type, some transformation rules also need
// detailed information for certain plan operators to decide whether it is applicable.
Match(expr *memo.ExprIter) bool
// OnTransform does the real work of the optimization rule.
//
// newExprs indicates the new GroupExprs generated by the transformationrule. Multiple GroupExprs may be
// returned, e.g, EnumeratePath would convert DataSource to several possible assess paths.
//
// eraseOld indicates that the returned GroupExpr must be better than the old one, so we can remove it from Group.
//
// eraseAll indicates that the returned GroupExpr must be better than all other candidates in the Group, e.g, we can
// prune all other access paths if we found the filter is constantly false.
OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error)
}
// TransformationRuleBatch is a batch of transformation rules.
type TransformationRuleBatch map[memo.Operand][]Transformation
// DefaultRuleBatches contain all the transformation rules.
// Each batch will be applied to the memo independently.
var DefaultRuleBatches = []TransformationRuleBatch{
TiDBLayerOptimizationBatch,
TiKVLayerOptimizationBatch,
PostTransformationBatch,
}
// TiDBLayerOptimizationBatch does the optimization in the TiDB layer.
var TiDBLayerOptimizationBatch = TransformationRuleBatch{
memo.OperandSelection: {
NewRulePushSelDownSort(),
NewRulePushSelDownProjection(),
NewRulePushSelDownAggregation(),
NewRulePushSelDownJoin(),
NewRulePushSelDownUnionAll(),
NewRulePushSelDownWindow(),
NewRuleMergeAdjacentSelection(),
},
memo.OperandAggregation: {
NewRuleMergeAggregationProjection(),
NewRuleEliminateSingleMaxMin(),
NewRuleEliminateOuterJoinBelowAggregation(),
NewRuleTransformAggregateCaseToSelection(),
NewRuleTransformAggToProj(),
},
memo.OperandLimit: {
NewRuleTransformLimitToTopN(),
NewRulePushLimitDownProjection(),
NewRulePushLimitDownUnionAll(),
NewRulePushLimitDownOuterJoin(),
NewRuleMergeAdjacentLimit(),
NewRuleTransformLimitToTableDual(),
},
memo.OperandProjection: {
NewRuleEliminateProjection(),
NewRuleMergeAdjacentProjection(),
NewRuleEliminateOuterJoinBelowProjection(),
},
memo.OperandTopN: {
NewRulePushTopNDownProjection(),
NewRulePushTopNDownOuterJoin(),
NewRulePushTopNDownUnionAll(),
NewRuleMergeAdjacentTopN(),
},
memo.OperandApply: {
NewRuleTransformApplyToJoin(),
NewRulePullSelectionUpApply(),
},
memo.OperandJoin: {
NewRuleTransformJoinCondToSel(),
},
memo.OperandWindow: {
NewRuleMergeAdjacentWindow(),
},
}
// TiKVLayerOptimizationBatch does the optimization related to TiKV layer.
// For example, rules about pushing down Operators like Selection, Limit,
// Aggregation into TiKV layer should be inside this batch.
var TiKVLayerOptimizationBatch = TransformationRuleBatch{
memo.OperandDataSource: {
NewRuleEnumeratePaths(),
},
memo.OperandSelection: {
NewRulePushSelDownTiKVSingleGather(),
NewRulePushSelDownTableScan(),
NewRulePushSelDownIndexScan(),
NewRuleMergeAdjacentSelection(),
},
memo.OperandAggregation: {
NewRulePushAggDownGather(),
},
memo.OperandLimit: {
NewRulePushLimitDownTiKVSingleGather(),
},
memo.OperandTopN: {
NewRulePushTopNDownTiKVSingleGather(),
},
}
// PostTransformationBatch does the transformation which is related to
// the constraints of the execution engine of TiDB.
// For example, TopN/Sort only support `order by` columns in TiDB layer,
// as for scalar functions, we need to inject a Projection for them
// below the TopN/Sort.
var PostTransformationBatch = TransformationRuleBatch{
memo.OperandProjection: {
NewRuleEliminateProjection(),
NewRuleMergeAdjacentProjection(),
},
memo.OperandAggregation: {
NewRuleInjectProjectionBelowAgg(),
},
memo.OperandTopN: {
NewRuleInjectProjectionBelowTopN(),
},
}
type baseRule struct {
pattern *memo.Pattern
}
// Match implements Transformation Interface.
func (*baseRule) Match(_ *memo.ExprIter) bool {
return true
}
// GetPattern implements Transformation Interface.
func (r *baseRule) GetPattern() *memo.Pattern {
return r.pattern
}
// PushSelDownTableScan pushes the selection down to TableScan.
type PushSelDownTableScan struct {
baseRule
}
// NewRulePushSelDownTableScan creates a new Transformation PushSelDownTableScan.
// The pattern of this rule is: `Selection -> TableScan`
func NewRulePushSelDownTableScan() Transformation {
rule := &PushSelDownTableScan{}
ts := memo.NewPattern(memo.OperandTableScan, memo.EngineTiKVOrTiFlash)
p := memo.BuildPattern(memo.OperandSelection, memo.EngineTiKVOrTiFlash, ts)
rule.pattern = p
return rule
}
// OnTransform implements Transformation interface.
//
// It transforms `sel -> ts` to one of the following new exprs:
// 1. `newSel -> newTS`
// 2. `newTS`
//
// Filters of the old `sel` operator are removed if they are used to calculate
// the key ranges of the `ts` operator.
func (*PushSelDownTableScan) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
ts := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalTableScan)
if ts.HandleCols == nil {
return nil, false, false, nil
}
accesses, remained := ranger.DetachCondsForColumn(ts.SCtx(), sel.Conditions, ts.HandleCols.GetCol(0))
if accesses == nil {
return nil, false, false, nil
}
newTblScan := plannercore.LogicalTableScan{
Source: ts.Source,
HandleCols: ts.HandleCols,
AccessConds: ts.AccessConds.Shallow(),
}.Init(ts.SCtx(), ts.SelectBlockOffset())
newTblScan.AccessConds = append(newTblScan.AccessConds, accesses...)
tblScanExpr := memo.NewGroupExpr(newTblScan)
if len(remained) == 0 {
// `sel -> ts` is transformed to `newTS`.
return []*memo.GroupExpr{tblScanExpr}, true, false, nil
}
schema := old.GetExpr().Group.Prop.Schema
tblScanGroup := memo.NewGroupWithSchema(tblScanExpr, schema)
newSel := plannercore.LogicalSelection{Conditions: remained}.Init(sel.SCtx(), sel.SelectBlockOffset())
selExpr := memo.NewGroupExpr(newSel)
selExpr.Children = append(selExpr.Children, tblScanGroup)
// `sel -> ts` is transformed to `newSel ->newTS`.
return []*memo.GroupExpr{selExpr}, true, false, nil
}
// PushSelDownIndexScan pushes a Selection down to IndexScan.
type PushSelDownIndexScan struct {
baseRule
}
// NewRulePushSelDownIndexScan creates a new Transformation PushSelDownIndexScan.
// The pattern of this rule is `Selection -> IndexScan`.
func NewRulePushSelDownIndexScan() Transformation {
rule := &PushSelDownIndexScan{}
rule.pattern = memo.BuildPattern(
memo.OperandSelection,
memo.EngineTiKVOnly,
memo.NewPattern(memo.OperandIndexScan, memo.EngineTiKVOnly),
)
return rule
}
// OnTransform implements Transformation interface.
// It will transform `Selection -> IndexScan` to:
//
// `IndexScan(with a new access range)` or
// `Selection -> IndexScan(with a new access range)`
// or just keep the two GroupExprs unchanged.
func (*PushSelDownIndexScan) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
is := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalIndexScan)
if len(is.IdxCols) == 0 {
return nil, false, false, nil
}
conditions := sel.Conditions
if is.AccessConds != nil {
// If we have already pushed some conditions down here,
// we merge old AccessConds with new conditions,
// to make sure this rule can be applied more than once.
conditions = make([]expression.Expression, len(sel.Conditions)+len(is.AccessConds))
copy(conditions, sel.Conditions)
copy(conditions[len(sel.Conditions):], is.AccessConds)
}
res, err := ranger.DetachCondAndBuildRangeForIndex(is.SCtx(), conditions, is.IdxCols, is.IdxColLens, is.SCtx().GetSessionVars().RangeMaxSize)
if err != nil {
return nil, false, false, err
}
if len(res.AccessConds) == len(is.AccessConds) {
// There is no condition can be pushed down as range,
// or the pushed down conditions are the same with before.
sameConds := true
for i := range res.AccessConds {
if !res.AccessConds[i].Equal(is.SCtx(), is.AccessConds[i]) {
sameConds = false
break
}
}
if sameConds {
return nil, false, false, nil
}
}
// TODO: `res` still has some unused fields: EqOrInCount, IsDNFCond.
newIs := plannercore.LogicalIndexScan{
Source: is.Source,
IsDoubleRead: is.IsDoubleRead,
EqCondCount: res.EqCondCount,
AccessConds: res.AccessConds,
Ranges: res.Ranges,
Index: is.Index,
Columns: is.Columns,
FullIdxCols: is.FullIdxCols,
FullIdxColLens: is.FullIdxColLens,
IdxCols: is.IdxCols,
IdxColLens: is.IdxColLens,
}.Init(is.SCtx(), is.SelectBlockOffset())
isExpr := memo.NewGroupExpr(newIs)
if len(res.RemainedConds) == 0 {
return []*memo.GroupExpr{isExpr}, true, false, nil
}
isGroup := memo.NewGroupWithSchema(isExpr, old.Children[0].GetExpr().Group.Prop.Schema)
newSel := plannercore.LogicalSelection{Conditions: res.RemainedConds}.Init(sel.SCtx(), sel.SelectBlockOffset())
selExpr := memo.NewGroupExpr(newSel)
selExpr.SetChildren(isGroup)
return []*memo.GroupExpr{selExpr}, true, false, nil
}
// PushSelDownTiKVSingleGather pushes the selection down to child of TiKVSingleGather.
type PushSelDownTiKVSingleGather struct {
baseRule
}
// NewRulePushSelDownTiKVSingleGather creates a new Transformation PushSelDownTiKVSingleGather.
// The pattern of this rule is `Selection -> TiKVSingleGather -> Any`.
func NewRulePushSelDownTiKVSingleGather() Transformation {
any1 := memo.NewPattern(memo.OperandAny, memo.EngineTiKVOrTiFlash)
tg := memo.BuildPattern(memo.OperandTiKVSingleGather, memo.EngineTiDBOnly, any1)
p := memo.BuildPattern(memo.OperandSelection, memo.EngineTiDBOnly, tg)
rule := &PushSelDownTiKVSingleGather{}
rule.pattern = p
return rule
}
// OnTransform implements Transformation interface.
//
// It transforms `oldSel -> oldTg -> any` to one of the following new exprs:
// 1. `newTg -> pushedSel -> any`
// 2. `remainedSel -> newTg -> pushedSel -> any`
func (*PushSelDownTiKVSingleGather) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
sg := old.Children[0].GetExpr().ExprNode.(*plannercore.TiKVSingleGather)
childGroup := old.Children[0].Children[0].Group
var pushed, remained []expression.Expression
sctx := sg.SCtx()
pushed, remained = expression.PushDownExprs(sctx.GetSessionVars().StmtCtx, sel.Conditions, sctx.GetClient(), kv.TiKV)
if len(pushed) == 0 {
return nil, false, false, nil
}
pushedSel := plannercore.LogicalSelection{Conditions: pushed}.Init(sctx, sel.SelectBlockOffset())
pushedSelExpr := memo.NewGroupExpr(pushedSel)
pushedSelExpr.Children = append(pushedSelExpr.Children, childGroup)
pushedSelGroup := memo.NewGroupWithSchema(pushedSelExpr, childGroup.Prop.Schema).SetEngineType(childGroup.EngineType)
// The field content of TiKVSingleGather would not be modified currently, so we
// just reference the same tg instead of making a copy of it.
//
// TODO: if we save pushed filters later in TiKVSingleGather, in order to do partition
// pruning or skyline pruning, we need to make a copy of the TiKVSingleGather here.
tblGatherExpr := memo.NewGroupExpr(sg)
tblGatherExpr.Children = append(tblGatherExpr.Children, pushedSelGroup)
if len(remained) == 0 {
// `oldSel -> oldTg -> any` is transformed to `newTg -> pushedSel -> any`.
return []*memo.GroupExpr{tblGatherExpr}, true, false, nil
}
tblGatherGroup := memo.NewGroupWithSchema(tblGatherExpr, pushedSelGroup.Prop.Schema)
remainedSel := plannercore.LogicalSelection{Conditions: remained}.Init(sel.SCtx(), sel.SelectBlockOffset())
remainedSelExpr := memo.NewGroupExpr(remainedSel)
remainedSelExpr.Children = append(remainedSelExpr.Children, tblGatherGroup)
// `oldSel -> oldTg -> any` is transformed to `remainedSel -> newTg -> pushedSel -> any`.
return []*memo.GroupExpr{remainedSelExpr}, true, false, nil
}
// EnumeratePaths converts DataSource to table scan and index scans.
type EnumeratePaths struct {
baseRule
}
// NewRuleEnumeratePaths creates a new Transformation EnumeratePaths.
// The pattern of this rule is: `DataSource`.
func NewRuleEnumeratePaths() Transformation {
rule := &EnumeratePaths{}
rule.pattern = memo.NewPattern(memo.OperandDataSource, memo.EngineTiDBOnly)
return rule
}
// OnTransform implements Transformation interface.
func (*EnumeratePaths) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
ds := old.GetExpr().ExprNode.(*plannercore.DataSource)
gathers := ds.Convert2Gathers()
for _, gather := range gathers {
expr := memo.Convert2GroupExpr(gather)
expr.Children[0].SetEngineType(memo.EngineTiKV)
newExprs = append(newExprs, expr)
}
return newExprs, true, false, nil
}
// PushAggDownGather splits Aggregation to two stages, final and partial1,
// and pushed the partial Aggregation down to the child of TiKVSingleGather.
type PushAggDownGather struct {
baseRule
}
// NewRulePushAggDownGather creates a new Transformation PushAggDownGather.
// The pattern of this rule is: `Aggregation -> TiKVSingleGather`.
func NewRulePushAggDownGather() Transformation {
rule := &PushAggDownGather{}
rule.pattern = memo.BuildPattern(
memo.OperandAggregation,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandTiKVSingleGather, memo.EngineTiDBOnly),
)
return rule
}
// Match implements Transformation interface.
func (r *PushAggDownGather) Match(expr *memo.ExprIter) bool {
if expr.GetExpr().HasAppliedRule(r) {
return false
}
agg := expr.GetExpr().ExprNode.(*plannercore.LogicalAggregation)
for _, aggFunc := range agg.AggFuncs {
if aggFunc.Mode != aggregation.CompleteMode {
return false
}
}
if agg.HasDistinct() {
// TODO: remove this logic after the cost estimation of distinct pushdown is implemented.
// If AllowDistinctAggPushDown is set to true, we should not consider RootTask.
if !agg.SCtx().GetSessionVars().AllowDistinctAggPushDown {
return false
}
}
childEngine := expr.Children[0].GetExpr().Children[0].EngineType
if childEngine != memo.EngineTiKV {
// TODO: Remove this check when we have implemented TiFlashAggregation.
return false
}
return plannercore.CheckAggCanPushCop(agg.SCtx(), agg.AggFuncs, agg.GroupByItems, kv.TiKV)
}
// OnTransform implements Transformation interface.
// It will transform `Agg->Gather` to `Agg(Final) -> Gather -> Agg(Partial1)`.
func (r *PushAggDownGather) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
agg := old.GetExpr().ExprNode.(*plannercore.LogicalAggregation)
aggSchema := old.GetExpr().Group.Prop.Schema
gather := old.Children[0].GetExpr().ExprNode.(*plannercore.TiKVSingleGather)
childGroup := old.Children[0].GetExpr().Children[0]
// The old Aggregation should stay unchanged for other transformation.
// So we build a new LogicalAggregation for the partialAgg.
aggFuncs := make([]*aggregation.AggFuncDesc, len(agg.AggFuncs))
for i := range agg.AggFuncs {
aggFuncs[i] = agg.AggFuncs[i].Clone()
}
gbyItems := make([]expression.Expression, len(agg.GroupByItems))
copy(gbyItems, agg.GroupByItems)
partialPref, finalPref, firstRowFuncMap := plannercore.BuildFinalModeAggregation(agg.SCtx(),
&plannercore.AggInfo{
AggFuncs: aggFuncs,
GroupByItems: gbyItems,
Schema: aggSchema,
}, true, false)
if partialPref == nil {
return nil, false, false, nil
}
// Remove unnecessary FirstRow.
partialPref.AggFuncs =
plannercore.RemoveUnnecessaryFirstRow(agg.SCtx(), finalPref.GroupByItems, partialPref.AggFuncs, partialPref.GroupByItems, partialPref.Schema, firstRowFuncMap)
partialAgg := plannercore.LogicalAggregation{
AggFuncs: partialPref.AggFuncs,
GroupByItems: partialPref.GroupByItems,
}.Init(agg.SCtx(), agg.SelectBlockOffset())
partialAgg.CopyAggHints(agg)
finalAgg := plannercore.LogicalAggregation{
AggFuncs: finalPref.AggFuncs,
GroupByItems: finalPref.GroupByItems,
}.Init(agg.SCtx(), agg.SelectBlockOffset())
finalAgg.CopyAggHints(agg)
partialAggExpr := memo.NewGroupExpr(partialAgg)
partialAggExpr.SetChildren(childGroup)
partialAggGroup := memo.NewGroupWithSchema(partialAggExpr, partialPref.Schema).SetEngineType(childGroup.EngineType)
gatherExpr := memo.NewGroupExpr(gather)
gatherExpr.SetChildren(partialAggGroup)
gatherGroup := memo.NewGroupWithSchema(gatherExpr, partialPref.Schema)
finalAggExpr := memo.NewGroupExpr(finalAgg)
finalAggExpr.SetChildren(gatherGroup)
finalAggExpr.AddAppliedRule(r)
// We don't erase the old complete mode Aggregation because
// this transformation would not always be better.
return []*memo.GroupExpr{finalAggExpr}, false, false, nil
}
// PushSelDownSort pushes the Selection down to the child of Sort.
type PushSelDownSort struct {
baseRule
}
// NewRulePushSelDownSort creates a new Transformation PushSelDownSort.
// The pattern of this rule is: `Selection -> Sort`.
func NewRulePushSelDownSort() Transformation {
rule := &PushSelDownSort{}
rule.pattern = memo.BuildPattern(
memo.OperandSelection,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandSort, memo.EngineTiDBOnly),
)
return rule
}
// OnTransform implements Transformation interface.
// It will transform `sel->sort->x` to `sort->sel->x`.
func (*PushSelDownSort) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
sort := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalSort)
childGroup := old.Children[0].GetExpr().Children[0]
newSelExpr := memo.NewGroupExpr(sel)
newSelExpr.Children = append(newSelExpr.Children, childGroup)
newSelGroup := memo.NewGroupWithSchema(newSelExpr, childGroup.Prop.Schema)
newSortExpr := memo.NewGroupExpr(sort)
newSortExpr.Children = append(newSortExpr.Children, newSelGroup)
return []*memo.GroupExpr{newSortExpr}, true, false, nil
}
// PushSelDownProjection pushes the Selection down to the child of Projection.
type PushSelDownProjection struct {
baseRule
}
// NewRulePushSelDownProjection creates a new Transformation PushSelDownProjection.
// The pattern of this rule is: `Selection -> Projection`.
func NewRulePushSelDownProjection() Transformation {
rule := &PushSelDownProjection{}
rule.pattern = memo.BuildPattern(
memo.OperandSelection,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandProjection, memo.EngineTiDBOnly),
)
return rule
}
// OnTransform implements Transformation interface.
// It will transform `selection -> projection -> x` to
// 1. `projection -> selection -> x` or
// 2. `selection -> projection -> selection -> x` or
// 3. just keep unchanged.
func (*PushSelDownProjection) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
proj := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalProjection)
projSchema := old.Children[0].Prop.Schema
childGroup := old.Children[0].GetExpr().Children[0]
for _, expr := range proj.Exprs {
if expression.HasAssignSetVarFunc(expr) {
return nil, false, false, nil
}
}
canBePushed := make([]expression.Expression, 0, len(sel.Conditions))
canNotBePushed := make([]expression.Expression, 0, len(sel.Conditions))
for _, cond := range sel.Conditions {
substituted, hasFailed, newFilter := expression.ColumnSubstituteImpl(cond, projSchema, proj.Exprs, true)
if substituted && !hasFailed && !expression.HasGetSetVarFunc(newFilter) {
canBePushed = append(canBePushed, newFilter)
} else {
canNotBePushed = append(canNotBePushed, cond)
}
}
if len(canBePushed) == 0 {
return nil, false, false, nil
}
newBottomSel := plannercore.LogicalSelection{Conditions: canBePushed}.Init(sel.SCtx(), sel.SelectBlockOffset())
newBottomSelExpr := memo.NewGroupExpr(newBottomSel)
newBottomSelExpr.SetChildren(childGroup)
newBottomSelGroup := memo.NewGroupWithSchema(newBottomSelExpr, childGroup.Prop.Schema)
newProjExpr := memo.NewGroupExpr(proj)
newProjExpr.SetChildren(newBottomSelGroup)
if len(canNotBePushed) == 0 {
return []*memo.GroupExpr{newProjExpr}, true, false, nil
}
newProjGroup := memo.NewGroupWithSchema(newProjExpr, projSchema)
newTopSel := plannercore.LogicalSelection{Conditions: canNotBePushed}.Init(sel.SCtx(), sel.SelectBlockOffset())
newTopSelExpr := memo.NewGroupExpr(newTopSel)
newTopSelExpr.SetChildren(newProjGroup)
return []*memo.GroupExpr{newTopSelExpr}, true, false, nil
}
// PushSelDownAggregation pushes Selection down to the child of Aggregation.
type PushSelDownAggregation struct {
baseRule
}
// NewRulePushSelDownAggregation creates a new Transformation PushSelDownAggregation.
// The pattern of this rule is `Selection -> Aggregation`.
func NewRulePushSelDownAggregation() Transformation {
rule := &PushSelDownAggregation{}
rule.pattern = memo.BuildPattern(
memo.OperandSelection,
memo.EngineAll,
memo.NewPattern(memo.OperandAggregation, memo.EngineAll),
)
return rule
}
// OnTransform implements Transformation interface.
// It will transform `sel->agg->x` to `agg->sel->x` or `sel->agg->sel->x`
// or just keep the selection unchanged.
func (*PushSelDownAggregation) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
agg := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalAggregation)
aggSchema := old.Children[0].Prop.Schema
var pushedExprs []expression.Expression
var remainedExprs []expression.Expression
groupByColumns := expression.NewSchema(agg.GetGroupByCols()...)
for _, cond := range sel.Conditions {
switch cond.(type) {
case *expression.Constant:
// Consider SQL list "select sum(b) from t group by a having 1=0". "1=0" is a constant predicate which should be
// retained and pushed down at the same time. Because we will get a wrong query result that contains one column
// with value 0 rather than an empty query result.
pushedExprs = append(pushedExprs, cond)
remainedExprs = append(remainedExprs, cond)
case *expression.ScalarFunction:
extractedCols := expression.ExtractColumns(cond)
canPush := true
for _, col := range extractedCols {
if !groupByColumns.Contains(col) {
canPush = false
break
}
}
if canPush {
pushedExprs = append(pushedExprs, cond)
} else {
remainedExprs = append(remainedExprs, cond)
}
default:
remainedExprs = append(remainedExprs, cond)
}
}
// If no condition can be pushed, keep the selection unchanged.
if len(pushedExprs) == 0 {
return nil, false, false, nil
}
sctx := sel.SCtx()
childGroup := old.Children[0].GetExpr().Children[0]
pushedSel := plannercore.LogicalSelection{Conditions: pushedExprs}.Init(sctx, sel.SelectBlockOffset())
pushedGroupExpr := memo.NewGroupExpr(pushedSel)
pushedGroupExpr.SetChildren(childGroup)
pushedGroup := memo.NewGroupWithSchema(pushedGroupExpr, childGroup.Prop.Schema)
aggGroupExpr := memo.NewGroupExpr(agg)
aggGroupExpr.SetChildren(pushedGroup)
if len(remainedExprs) == 0 {
return []*memo.GroupExpr{aggGroupExpr}, true, false, nil
}
aggGroup := memo.NewGroupWithSchema(aggGroupExpr, aggSchema)
remainedSel := plannercore.LogicalSelection{Conditions: remainedExprs}.Init(sctx, sel.SelectBlockOffset())
remainedGroupExpr := memo.NewGroupExpr(remainedSel)
remainedGroupExpr.SetChildren(aggGroup)
return []*memo.GroupExpr{remainedGroupExpr}, true, false, nil
}
// PushSelDownWindow pushes Selection down to the child of Window.
type PushSelDownWindow struct {
baseRule
}
// NewRulePushSelDownWindow creates a new Transformation PushSelDownWindow.
// The pattern of this rule is `Selection -> Window`.
func NewRulePushSelDownWindow() Transformation {
rule := &PushSelDownWindow{}
rule.pattern = memo.BuildPattern(
memo.OperandSelection,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandWindow, memo.EngineAll),
)
return rule
}
// OnTransform implements Transformation interface.
// This rule will transform `sel -> window -> x` to
// 1. `window -> sel -> x` or
// 2. `sel -> window -> sel -> x` or
// 3. just keep unchanged.
func (*PushSelDownWindow) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
window := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalWindow)
windowSchema := old.Children[0].Prop.Schema
childGroup := old.Children[0].GetExpr().Children[0]
canBePushed := make([]expression.Expression, 0, len(sel.Conditions))
canNotBePushed := make([]expression.Expression, 0, len(sel.Conditions))
// get partition Columns' Schema
partitionColsSchema := expression.NewSchema(window.GetPartitionByCols()...)
for _, cond := range sel.Conditions {
if expression.ExprFromSchema(cond, partitionColsSchema) {
canBePushed = append(canBePushed, cond)
} else {
canNotBePushed = append(canNotBePushed, cond)
}
}
// Nothing can be pushed!
if len(canBePushed) == 0 {
return nil, false, false, nil
}
// construct return GroupExpr
newBottomSel := plannercore.LogicalSelection{Conditions: canBePushed}.Init(sel.SCtx(), sel.SelectBlockOffset())
newBottomSelExpr := memo.NewGroupExpr(newBottomSel)
newBottomSelExpr.SetChildren(childGroup)
newBottomSelGroup := memo.NewGroupWithSchema(newBottomSelExpr, childGroup.Prop.Schema)
newWindowExpr := memo.NewGroupExpr(window)
newWindowExpr.SetChildren(newBottomSelGroup)
if len(canNotBePushed) == 0 {
return []*memo.GroupExpr{newWindowExpr}, true, false, nil
}
newWindowGroup := memo.NewGroupWithSchema(newWindowExpr, windowSchema)
newTopSel := plannercore.LogicalSelection{Conditions: canNotBePushed}.Init(sel.SCtx(), sel.SelectBlockOffset())
newTopSelExpr := memo.NewGroupExpr(newTopSel)
newTopSelExpr.SetChildren(newWindowGroup)
return []*memo.GroupExpr{newTopSelExpr}, true, false, nil
}
// TransformLimitToTopN transforms Limit+Sort to TopN.
type TransformLimitToTopN struct {
baseRule
}
// NewRuleTransformLimitToTopN creates a new Transformation TransformLimitToTopN.
// The pattern of this rule is `Limit -> Sort`.
func NewRuleTransformLimitToTopN() Transformation {
rule := &TransformLimitToTopN{}
rule.pattern = memo.BuildPattern(
memo.OperandLimit,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandSort, memo.EngineTiDBOnly),
)
return rule
}
// OnTransform implements Transformation interface.
// This rule will transform `Limit -> Sort -> x` to `TopN -> x`.
func (*TransformLimitToTopN) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
limit := old.GetExpr().ExprNode.(*plannercore.LogicalLimit)
sort := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalSort)
childGroup := old.Children[0].GetExpr().Children[0]
topN := plannercore.LogicalTopN{
ByItems: sort.ByItems,
Offset: limit.Offset,
Count: limit.Count,
}.Init(limit.SCtx(), limit.SelectBlockOffset())
topNExpr := memo.NewGroupExpr(topN)
topNExpr.SetChildren(childGroup)
return []*memo.GroupExpr{topNExpr}, true, false, nil
}
// PushLimitDownProjection pushes Limit to Projection.
type PushLimitDownProjection struct {
baseRule
}
// NewRulePushLimitDownProjection creates a new Transformation.
// The pattern of this rule is `Limit->Projection->X` to `Projection->Limit->X`.
func NewRulePushLimitDownProjection() Transformation {
rule := &PushLimitDownProjection{}
rule.pattern = memo.BuildPattern(
memo.OperandLimit,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandProjection, memo.EngineTiDBOnly),
)
return rule
}
// Match implements Transformation interface.
func (*PushLimitDownProjection) Match(expr *memo.ExprIter) bool {
proj := expr.Children[0].GetExpr().ExprNode.(*plannercore.LogicalProjection)
for _, expr := range proj.Exprs {
if expression.HasAssignSetVarFunc(expr) {
return false
}
}
return true
}
// OnTransform implements Transformation interface.
// This rule tries to pushes the Limit through Projection.
func (*PushLimitDownProjection) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
limit := old.GetExpr().ExprNode.(*plannercore.LogicalLimit)
proj := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalProjection)
childGroup := old.Children[0].GetExpr().Children[0]
projExpr := memo.NewGroupExpr(proj)
limitExpr := memo.NewGroupExpr(limit)
limitExpr.SetChildren(childGroup)
limitGroup := memo.NewGroupWithSchema(limitExpr, childGroup.Prop.Schema)
projExpr.SetChildren(limitGroup)
return []*memo.GroupExpr{projExpr}, true, false, nil
}
// PushLimitDownUnionAll pushes limit to union all.
type PushLimitDownUnionAll struct {
baseRule
}
// NewRulePushLimitDownUnionAll creates a new Transformation PushLimitDownUnionAll.
// The pattern of this rule is `Limit->UnionAll->X`.
func NewRulePushLimitDownUnionAll() Transformation {
rule := &PushLimitDownUnionAll{}
rule.pattern = memo.BuildPattern(
memo.OperandLimit,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandUnionAll, memo.EngineTiDBOnly),
)
return rule
}
// Match implements Transformation interface.
// Use appliedRuleSet in GroupExpr to avoid re-apply rules.
func (r *PushLimitDownUnionAll) Match(expr *memo.ExprIter) bool {
return !expr.GetExpr().HasAppliedRule(r)
}
// OnTransform implements Transformation interface.
// It will transform `Limit->UnionAll->X` to `Limit->UnionAll->Limit->X`.
func (r *PushLimitDownUnionAll) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
limit := old.GetExpr().ExprNode.(*plannercore.LogicalLimit)
unionAll := old.Children[0].GetExpr().ExprNode.(*plannercore.LogicalUnionAll)
unionAllSchema := old.Children[0].Group.Prop.Schema
newLimit := plannercore.LogicalLimit{
Count: limit.Count + limit.Offset,
}.Init(limit.SCtx(), limit.SelectBlockOffset())
newUnionAllExpr := memo.NewGroupExpr(unionAll)
for _, childGroup := range old.Children[0].GetExpr().Children {
newLimitExpr := memo.NewGroupExpr(newLimit)
newLimitExpr.Children = append(newLimitExpr.Children, childGroup)
newLimitGroup := memo.NewGroupWithSchema(newLimitExpr, childGroup.Prop.Schema)
newUnionAllExpr.Children = append(newUnionAllExpr.Children, newLimitGroup)
}
newLimitExpr := memo.NewGroupExpr(limit)
newUnionAllGroup := memo.NewGroupWithSchema(newUnionAllExpr, unionAllSchema)
newLimitExpr.SetChildren(newUnionAllGroup)
newLimitExpr.AddAppliedRule(r)
return []*memo.GroupExpr{newLimitExpr}, true, false, nil
}
type pushDownJoin struct {
}
func (*pushDownJoin) predicatePushDown(
sctx sessionctx.Context,
predicates []expression.Expression,
join *plannercore.LogicalJoin,
leftSchema *expression.Schema,
rightSchema *expression.Schema,
) (
leftCond []expression.Expression,
rightCond []expression.Expression,
remainCond []expression.Expression,
dual plannercore.LogicalPlan,
) {
var equalCond []*expression.ScalarFunction
var leftPushCond, rightPushCond, otherCond []expression.Expression
switch join.JoinType {
case plannercore.SemiJoin, plannercore.InnerJoin:
tempCond := make([]expression.Expression, 0,
len(join.LeftConditions)+len(join.RightConditions)+len(join.EqualConditions)+len(join.OtherConditions)+len(predicates))
tempCond = append(tempCond, join.LeftConditions...)
tempCond = append(tempCond, join.RightConditions...)
tempCond = append(tempCond, expression.ScalarFuncs2Exprs(join.EqualConditions)...)
tempCond = append(tempCond, join.OtherConditions...)
tempCond = append(tempCond, predicates...)
tempCond = expression.ExtractFiltersFromDNFs(sctx, tempCond)
tempCond = expression.PropagateConstant(sctx, tempCond)
// Return table dual when filter is constant false or null.
dual := plannercore.Conds2TableDual(join, tempCond)
if dual != nil {
return leftCond, rightCond, remainCond, dual
}
equalCond, leftPushCond, rightPushCond, otherCond = join.ExtractOnCondition(tempCond, leftSchema, rightSchema, true, true)
join.LeftConditions = nil
join.RightConditions = nil
join.EqualConditions = equalCond
join.OtherConditions = otherCond
leftCond = leftPushCond
rightCond = rightPushCond
case plannercore.LeftOuterJoin, plannercore.LeftOuterSemiJoin, plannercore.AntiLeftOuterSemiJoin,
plannercore.RightOuterJoin:
lenJoinConds := len(join.EqualConditions) + len(join.LeftConditions) + len(join.RightConditions) + len(join.OtherConditions)
joinConds := make([]expression.Expression, 0, lenJoinConds)
for _, equalCond := range join.EqualConditions {
joinConds = append(joinConds, equalCond)
}
joinConds = append(joinConds, join.LeftConditions...)
joinConds = append(joinConds, join.RightConditions...)
joinConds = append(joinConds, join.OtherConditions...)
join.EqualConditions = nil
join.LeftConditions = nil
join.RightConditions = nil
join.OtherConditions = nil
remainCond = make([]expression.Expression, len(predicates))
copy(remainCond, predicates)
nullSensitive := join.JoinType == plannercore.AntiLeftOuterSemiJoin || join.JoinType == plannercore.LeftOuterSemiJoin
if join.JoinType == plannercore.RightOuterJoin {
joinConds, remainCond = expression.PropConstOverOuterJoin(join.SCtx(), joinConds, remainCond, rightSchema, leftSchema, nullSensitive)
} else {
joinConds, remainCond = expression.PropConstOverOuterJoin(join.SCtx(), joinConds, remainCond, leftSchema, rightSchema, nullSensitive)
}
eq, left, right, other := join.ExtractOnCondition(joinConds, leftSchema, rightSchema, false, false)
join.AppendJoinConds(eq, left, right, other)
// Return table dual when filter is constant false or null.
dual := plannercore.Conds2TableDual(join, remainCond)
if dual != nil {
return leftCond, rightCond, remainCond, dual
}
if join.JoinType == plannercore.RightOuterJoin {
remainCond = expression.ExtractFiltersFromDNFs(join.SCtx(), remainCond)
// Only derive right where condition, because left where condition cannot be pushed down
equalCond, leftPushCond, rightPushCond, otherCond = join.ExtractOnCondition(remainCond, leftSchema, rightSchema, false, true)
rightCond = rightPushCond
// Handle join conditions, only derive left join condition, because right join condition cannot be pushed down
derivedLeftJoinCond, _ := plannercore.DeriveOtherConditions(join, leftSchema, rightSchema, true, false)
leftCond = append(join.LeftConditions, derivedLeftJoinCond...)
join.LeftConditions = nil
remainCond = append(expression.ScalarFuncs2Exprs(equalCond), otherCond...)
remainCond = append(remainCond, leftPushCond...) // nozero
} else {
remainCond = expression.ExtractFiltersFromDNFs(join.SCtx(), remainCond)
// Only derive left where condition, because right where condition cannot be pushed down
equalCond, leftPushCond, rightPushCond, otherCond = join.ExtractOnCondition(remainCond, leftSchema, rightSchema, true, false)
leftCond = leftPushCond
// Handle join conditions, only derive right join condition, because left join condition cannot be pushed down
_, derivedRightJoinCond := plannercore.DeriveOtherConditions(join, leftSchema, rightSchema, false, true)
rightCond = append(join.RightConditions, derivedRightJoinCond...)
join.RightConditions = nil
remainCond = append(expression.ScalarFuncs2Exprs(equalCond), otherCond...)
remainCond = append(remainCond, rightPushCond...) // nozero
}
default:
// TODO: Enhance this rule to deal with Semi/SmiAnti Joins.
}
leftCond = expression.RemoveDupExprs(sctx, leftCond)
rightCond = expression.RemoveDupExprs(sctx, rightCond)
return
}
// PushSelDownJoin pushes Selection through Join.
type PushSelDownJoin struct {
baseRule
pushDownJoin
}
// NewRulePushSelDownJoin creates a new Transformation PushSelDownJoin.
// The pattern of this rule is `Selection -> Join`.
func NewRulePushSelDownJoin() Transformation {
rule := &PushSelDownJoin{}
rule.pattern = memo.BuildPattern(
memo.OperandSelection,
memo.EngineTiDBOnly,
memo.NewPattern(memo.OperandJoin, memo.EngineTiDBOnly),
)
return rule
}
// Match implements Transformation interface.
func (r *PushSelDownJoin) Match(expr *memo.ExprIter) bool {
return !expr.GetExpr().HasAppliedRule(r)
}
// buildChildSelectionGroup builds a new childGroup if the pushed down condition is not empty.
func buildChildSelectionGroup(
sctx sessionctx.Context,
blockOffset int,
conditions []expression.Expression,
childGroup *memo.Group) *memo.Group {
if len(conditions) == 0 {
return childGroup
}
newSel := plannercore.LogicalSelection{Conditions: conditions}.Init(sctx, blockOffset)
groupExpr := memo.NewGroupExpr(newSel)
groupExpr.SetChildren(childGroup)
newChild := memo.NewGroupWithSchema(groupExpr, childGroup.Prop.Schema)
return newChild
}
// OnTransform implements Transformation interface.
// This rule tries to pushes the Selection through Join. Besides, this rule fulfills the `XXXConditions` field of Join.
func (r *PushSelDownJoin) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) {
sel := old.GetExpr().ExprNode.(*plannercore.LogicalSelection)
joinExpr := old.Children[0].GetExpr()
join := joinExpr.ExprNode.(*plannercore.LogicalJoin)
newJoin := join.Shallow()
sctx := sel.SCtx()
leftGroup := old.Children[0].GetExpr().Children[0]
rightGroup := old.Children[0].GetExpr().Children[1]
leftCond, rightCond, remainCond, dual := r.predicatePushDown(sctx, sel.Conditions, newJoin, leftGroup.Prop.Schema, rightGroup.Prop.Schema)
if dual != nil {
return []*memo.GroupExpr{memo.NewGroupExpr(dual)}, true, true, nil
}