-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
logical_plan_builder.go
7690 lines (7216 loc) · 264 KB
/
logical_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,
// 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 (
"context"
"fmt"
"math"
"math/bits"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/pkg/domain"
"github.com/pingcap/tidb/pkg/errctx"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/expression/aggregation"
exprctx "github.com/pingcap/tidb/pkg/expression/context"
"github.com/pingcap/tidb/pkg/infoschema"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/charset"
"github.com/pingcap/tidb/pkg/parser/format"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/parser/opcode"
"github.com/pingcap/tidb/pkg/parser/terror"
"github.com/pingcap/tidb/pkg/planner/core/base"
core_metrics "github.com/pingcap/tidb/pkg/planner/core/metrics"
fd "github.com/pingcap/tidb/pkg/planner/funcdep"
"github.com/pingcap/tidb/pkg/planner/property"
"github.com/pingcap/tidb/pkg/planner/util"
"github.com/pingcap/tidb/pkg/planner/util/coreusage"
"github.com/pingcap/tidb/pkg/planner/util/debugtrace"
"github.com/pingcap/tidb/pkg/planner/util/fixcontrol"
"github.com/pingcap/tidb/pkg/planner/util/tablesampler"
"github.com/pingcap/tidb/pkg/privilege"
"github.com/pingcap/tidb/pkg/sessionctx"
"github.com/pingcap/tidb/pkg/sessionctx/variable"
"github.com/pingcap/tidb/pkg/statistics"
"github.com/pingcap/tidb/pkg/table"
"github.com/pingcap/tidb/pkg/table/tables"
"github.com/pingcap/tidb/pkg/table/temptable"
"github.com/pingcap/tidb/pkg/types"
driver "github.com/pingcap/tidb/pkg/types/parser_driver"
util2 "github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/collate"
"github.com/pingcap/tidb/pkg/util/dbterror"
"github.com/pingcap/tidb/pkg/util/dbterror/plannererrors"
"github.com/pingcap/tidb/pkg/util/hack"
h "github.com/pingcap/tidb/pkg/util/hint"
"github.com/pingcap/tidb/pkg/util/intest"
"github.com/pingcap/tidb/pkg/util/intset"
"github.com/pingcap/tidb/pkg/util/logutil"
"github.com/pingcap/tidb/pkg/util/plancodec"
"github.com/pingcap/tidb/pkg/util/set"
"github.com/pingcap/tidb/pkg/util/size"
"github.com/pingcap/tipb/go-tipb"
)
const (
// ErrExprInSelect is in select fields for the error of ErrFieldNotInGroupBy
ErrExprInSelect = "SELECT list"
// ErrExprInOrderBy is in order by items for the error of ErrFieldNotInGroupBy
ErrExprInOrderBy = "ORDER BY"
)
// aggOrderByResolver is currently resolving expressions of order by clause
// in aggregate function GROUP_CONCAT.
type aggOrderByResolver struct {
ctx base.PlanContext
err error
args []ast.ExprNode
exprDepth int // exprDepth is the depth of current expression in expression tree.
}
func (a *aggOrderByResolver) Enter(inNode ast.Node) (ast.Node, bool) {
a.exprDepth++
if n, ok := inNode.(*driver.ParamMarkerExpr); ok {
if a.exprDepth == 1 {
_, isNull, isExpectedType := getUintFromNode(a.ctx, n, false)
// For constant uint expression in top level, it should be treated as position expression.
if !isNull && isExpectedType {
return expression.ConstructPositionExpr(n), true
}
}
}
return inNode, false
}
func (a *aggOrderByResolver) Leave(inNode ast.Node) (ast.Node, bool) {
if v, ok := inNode.(*ast.PositionExpr); ok {
pos, isNull, err := expression.PosFromPositionExpr(a.ctx.GetExprCtx(), a.ctx, v)
if err != nil {
a.err = err
}
if err != nil || isNull {
return inNode, false
}
if pos < 1 || pos > len(a.args) {
errPos := strconv.Itoa(pos)
if v.P != nil {
errPos = "?"
}
a.err = plannererrors.ErrUnknownColumn.FastGenByArgs(errPos, "order clause")
return inNode, false
}
ret := a.args[pos-1]
return ret, true
}
return inNode, true
}
func (b *PlanBuilder) buildExpand(p base.LogicalPlan, gbyItems []expression.Expression) (base.LogicalPlan, []expression.Expression, error) {
b.optFlag |= flagResolveExpand
// Rollup syntax require expand OP to do the data expansion, different data replica supply the different grouping layout.
distinctGbyExprs, gbyExprsRefPos := expression.DeduplicateGbyExpression(gbyItems)
// build another projection below.
proj := LogicalProjection{Exprs: make([]expression.Expression, 0, p.Schema().Len()+len(distinctGbyExprs))}.Init(b.ctx, b.getSelectOffset())
// project: child's output and distinct GbyExprs in advance. (make every group-by item to be a column)
projSchema := p.Schema().Clone()
names := p.OutputNames()
for _, col := range projSchema.Columns {
proj.Exprs = append(proj.Exprs, col)
}
distinctGbyColNames := make(types.NameSlice, 0, len(distinctGbyExprs))
distinctGbyCols := make([]*expression.Column, 0, len(distinctGbyExprs))
for _, expr := range distinctGbyExprs {
// distinct group expr has been resolved in resolveGby.
proj.Exprs = append(proj.Exprs, expr)
// add the newly appended names.
var name *types.FieldName
if c, ok := expr.(*expression.Column); ok {
name = buildExpandFieldName(c, names[p.Schema().ColumnIndex(c)], "")
} else {
name = buildExpandFieldName(expr, nil, "")
}
names = append(names, name)
distinctGbyColNames = append(distinctGbyColNames, name)
// since we will change the nullability of source col, proj it with a new col id.
col := &expression.Column{
UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
// clone it rather than using it directly,
RetType: expr.GetType().Clone(),
}
projSchema.Append(col)
distinctGbyCols = append(distinctGbyCols, col)
}
proj.SetSchema(projSchema)
proj.SetChildren(p)
// since expand will ref original col and make some change, do the copy in executor rather than ref the same chunk.column.
proj.AvoidColumnEvaluator = true
proj.Proj4Expand = true
newGbyItems := expression.RestoreGbyExpression(distinctGbyCols, gbyExprsRefPos)
// build expand.
rollupGroupingSets := expression.RollupGroupingSets(newGbyItems)
// eg: <a,b,c> with rollup => {},{a},{a,b},{a,b,c}
// for every grouping set above, we should individually set those not-needed grouping-set col as null value.
// eg: let's say base schema is <a,b,c,d>, d is unrelated col, keep it real in every grouping set projection.
// for grouping set {a,b,c}, project it as: [a, b, c, d, gid]
// for grouping set {a,b}, project it as: [a, b, null, d, gid]
// for grouping set {a}, project it as: [a, null, null, d, gid]
// for grouping set {}, project it as: [null, null, null, d, gid]
expandSchema := proj.Schema().Clone()
expression.AdjustNullabilityFromGroupingSets(rollupGroupingSets, expandSchema)
expand := LogicalExpand{
rollupGroupingSets: rollupGroupingSets,
distinctGroupByCol: distinctGbyCols,
distinctGbyColNames: distinctGbyColNames,
// for resolving grouping function args.
distinctGbyExprs: distinctGbyExprs,
// fill the gen col names when building level projections.
}.Init(b.ctx, b.getSelectOffset())
// if we want to use bitAnd for the quick computation of grouping function, then the maximum capacity of num of grouping is about 64.
expand.GroupingMode = tipb.GroupingMode_ModeBitAnd
if len(expand.rollupGroupingSets) > 64 {
expand.GroupingMode = tipb.GroupingMode_ModeNumericSet
}
expand.distinctSize, expand.rollupGroupingIDs, expand.rollupID2GIDS = expand.rollupGroupingSets.DistinctSize()
hasDuplicateGroupingSet := len(expand.rollupGroupingSets) != expand.distinctSize
// append the generated column for logical Expand.
tp := types.NewFieldType(mysql.TypeLonglong)
tp.SetFlag(mysql.UnsignedFlag | mysql.NotNullFlag)
gid := &expression.Column{
UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
RetType: tp,
OrigName: "gid",
}
expand.GID = gid
expandSchema.Append(gid)
expand.ExtraGroupingColNames = append(expand.ExtraGroupingColNames, gid.OrigName)
names = append(names, buildExpandFieldName(gid, nil, "gid_"))
expand.GIDName = names[len(names)-1]
if hasDuplicateGroupingSet {
// the last two col of the schema should be gid & gpos
gpos := &expression.Column{
UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
RetType: tp.Clone(),
OrigName: "gpos",
}
expand.GPos = gpos
expandSchema.Append(gpos)
expand.ExtraGroupingColNames = append(expand.ExtraGroupingColNames, gpos.OrigName)
names = append(names, buildExpandFieldName(gpos, nil, "gpos_"))
expand.GPosName = names[len(names)-1]
}
expand.SetChildren(proj)
expand.SetSchema(expandSchema)
expand.SetOutputNames(names)
// register current rollup Expand operator in current select block.
b.currentBlockExpand = expand
// defer generating level-projection as last logical optimization rule.
return expand, newGbyItems, nil
}
func (b *PlanBuilder) buildAggregation(ctx context.Context, p base.LogicalPlan, aggFuncList []*ast.AggregateFuncExpr, gbyItems []expression.Expression,
correlatedAggMap map[*ast.AggregateFuncExpr]int) (base.LogicalPlan, map[int]int, error) {
b.optFlag |= flagBuildKeyInfo
b.optFlag |= flagPushDownAgg
// We may apply aggregation eliminate optimization.
// So we add the flagMaxMinEliminate to try to convert max/min to topn and flagPushDownTopN to handle the newly added topn operator.
b.optFlag |= flagMaxMinEliminate
b.optFlag |= flagPushDownTopN
// when we eliminate the max and min we may add `is not null` filter.
b.optFlag |= flagPredicatePushDown
b.optFlag |= flagEliminateAgg
b.optFlag |= flagEliminateProjection
if b.ctx.GetSessionVars().EnableSkewDistinctAgg {
b.optFlag |= flagSkewDistinctAgg
}
// flag it if cte contain aggregation
if b.buildingCTE {
b.outerCTEs[len(b.outerCTEs)-1].containAggOrWindow = true
}
var rollupExpand *LogicalExpand
if expand, ok := p.(*LogicalExpand); ok {
rollupExpand = expand
}
plan4Agg := LogicalAggregation{AggFuncs: make([]*aggregation.AggFuncDesc, 0, len(aggFuncList))}.Init(b.ctx, b.getSelectOffset())
if hintinfo := b.TableHints(); hintinfo != nil {
plan4Agg.PreferAggType = hintinfo.PreferAggType
plan4Agg.PreferAggToCop = hintinfo.PreferAggToCop
}
schema4Agg := expression.NewSchema(make([]*expression.Column, 0, len(aggFuncList)+p.Schema().Len())...)
names := make(types.NameSlice, 0, len(aggFuncList)+p.Schema().Len())
// aggIdxMap maps the old index to new index after applying common aggregation functions elimination.
aggIndexMap := make(map[int]int)
allAggsFirstRow := true
for i, aggFunc := range aggFuncList {
newArgList := make([]expression.Expression, 0, len(aggFunc.Args))
for _, arg := range aggFunc.Args {
newArg, np, err := b.rewrite(ctx, arg, p, nil, true)
if err != nil {
return nil, nil, err
}
p = np
newArgList = append(newArgList, newArg)
}
newFunc, err := aggregation.NewAggFuncDesc(b.ctx.GetExprCtx(), aggFunc.F, newArgList, aggFunc.Distinct)
if err != nil {
return nil, nil, err
}
if newFunc.Name != ast.AggFuncFirstRow {
allAggsFirstRow = false
}
if aggFunc.Order != nil {
trueArgs := aggFunc.Args[:len(aggFunc.Args)-1] // the last argument is SEPARATOR, remote it.
resolver := &aggOrderByResolver{
ctx: b.ctx,
args: trueArgs,
}
for _, byItem := range aggFunc.Order.Items {
resolver.exprDepth = 0
resolver.err = nil
retExpr, _ := byItem.Expr.Accept(resolver)
if resolver.err != nil {
return nil, nil, errors.Trace(resolver.err)
}
newByItem, np, err := b.rewrite(ctx, retExpr.(ast.ExprNode), p, nil, true)
if err != nil {
return nil, nil, err
}
p = np
newFunc.OrderByItems = append(newFunc.OrderByItems, &util.ByItems{Expr: newByItem, Desc: byItem.Desc})
}
}
// combine identical aggregate functions
combined := false
for j := 0; j < i; j++ {
oldFunc := plan4Agg.AggFuncs[aggIndexMap[j]]
if oldFunc.Equal(b.ctx.GetExprCtx().GetEvalCtx(), newFunc) {
aggIndexMap[i] = aggIndexMap[j]
combined = true
if _, ok := correlatedAggMap[aggFunc]; ok {
if _, ok = b.correlatedAggMapper[aggFuncList[j]]; !ok {
b.correlatedAggMapper[aggFuncList[j]] = &expression.CorrelatedColumn{
Column: *schema4Agg.Columns[aggIndexMap[j]],
Data: new(types.Datum),
}
}
b.correlatedAggMapper[aggFunc] = b.correlatedAggMapper[aggFuncList[j]]
}
break
}
}
// create new columns for aggregate functions which show up first
if !combined {
position := len(plan4Agg.AggFuncs)
aggIndexMap[i] = position
plan4Agg.AggFuncs = append(plan4Agg.AggFuncs, newFunc)
column := expression.Column{
UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
RetType: newFunc.RetTp,
}
schema4Agg.Append(&column)
names = append(names, types.EmptyName)
if _, ok := correlatedAggMap[aggFunc]; ok {
b.correlatedAggMapper[aggFunc] = &expression.CorrelatedColumn{
Column: column,
Data: new(types.Datum),
}
}
}
}
for i, col := range p.Schema().Columns {
newFunc, err := aggregation.NewAggFuncDesc(b.ctx.GetExprCtx(), ast.AggFuncFirstRow, []expression.Expression{col}, false)
if err != nil {
return nil, nil, err
}
plan4Agg.AggFuncs = append(plan4Agg.AggFuncs, newFunc)
newCol, _ := col.Clone().(*expression.Column)
newCol.RetType = newFunc.RetTp
schema4Agg.Append(newCol)
names = append(names, p.OutputNames()[i])
}
var (
join *LogicalJoin
isJoin bool
isSelectionJoin bool
)
join, isJoin = p.(*LogicalJoin)
selection, isSelection := p.(*LogicalSelection)
if isSelection {
join, isSelectionJoin = selection.Children()[0].(*LogicalJoin)
}
if (isJoin && join.fullSchema != nil) || (isSelectionJoin && join.fullSchema != nil) {
for i, col := range join.fullSchema.Columns {
if p.Schema().Contains(col) {
continue
}
newFunc, err := aggregation.NewAggFuncDesc(b.ctx.GetExprCtx(), ast.AggFuncFirstRow, []expression.Expression{col}, false)
if err != nil {
return nil, nil, err
}
plan4Agg.AggFuncs = append(plan4Agg.AggFuncs, newFunc)
newCol, _ := col.Clone().(*expression.Column)
newCol.RetType = newFunc.RetTp
schema4Agg.Append(newCol)
names = append(names, join.fullNames[i])
}
}
hasGroupBy := len(gbyItems) > 0
for i, aggFunc := range plan4Agg.AggFuncs {
err := aggFunc.UpdateNotNullFlag4RetType(hasGroupBy, allAggsFirstRow)
if err != nil {
return nil, nil, err
}
schema4Agg.Columns[i].RetType = aggFunc.RetTp
}
plan4Agg.names = names
plan4Agg.SetChildren(p)
if rollupExpand != nil {
// append gid and gpos as the group keys if any.
plan4Agg.GroupByItems = append(gbyItems, rollupExpand.GID)
if rollupExpand.GPos != nil {
plan4Agg.GroupByItems = append(plan4Agg.GroupByItems, rollupExpand.GPos)
}
} else {
plan4Agg.GroupByItems = gbyItems
}
plan4Agg.SetSchema(schema4Agg)
return plan4Agg, aggIndexMap, nil
}
func (b *PlanBuilder) buildTableRefs(ctx context.Context, from *ast.TableRefsClause) (p base.LogicalPlan, err error) {
if from == nil {
p = b.buildTableDual()
return
}
defer func() {
// After build the resultSetNode, need to reset it so that it can be referenced by outer level.
for _, cte := range b.outerCTEs {
cte.recursiveRef = false
}
}()
return b.buildResultSetNode(ctx, from.TableRefs, false)
}
func (b *PlanBuilder) buildResultSetNode(ctx context.Context, node ast.ResultSetNode, isCTE bool) (p base.LogicalPlan, err error) {
//If it is building the CTE queries, we will mark them.
b.isCTE = isCTE
switch x := node.(type) {
case *ast.Join:
return b.buildJoin(ctx, x)
case *ast.TableSource:
var isTableName bool
switch v := x.Source.(type) {
case *ast.SelectStmt:
ci := b.prepareCTECheckForSubQuery()
defer resetCTECheckForSubQuery(ci)
b.optFlag = b.optFlag | flagConstantPropagation
p, err = b.buildSelect(ctx, v)
case *ast.SetOprStmt:
ci := b.prepareCTECheckForSubQuery()
defer resetCTECheckForSubQuery(ci)
p, err = b.buildSetOpr(ctx, v)
case *ast.TableName:
p, err = b.buildDataSource(ctx, v, &x.AsName)
isTableName = true
default:
err = plannererrors.ErrUnsupportedType.GenWithStackByArgs(v)
}
if err != nil {
return nil, err
}
for _, name := range p.OutputNames() {
if name.Hidden {
continue
}
if x.AsName.L != "" {
name.TblName = x.AsName
}
}
// `TableName` is not a select block, so we do not need to handle it.
var plannerSelectBlockAsName []ast.HintTable
if p := b.ctx.GetSessionVars().PlannerSelectBlockAsName.Load(); p != nil {
plannerSelectBlockAsName = *p
}
if len(plannerSelectBlockAsName) > 0 && !isTableName {
plannerSelectBlockAsName[p.QueryBlockOffset()] = ast.HintTable{DBName: p.OutputNames()[0].DBName, TableName: p.OutputNames()[0].TblName}
}
// Duplicate column name in one table is not allowed.
// "select * from (select 1, 1) as a;" is duplicate
dupNames := make(map[string]struct{}, len(p.Schema().Columns))
for _, name := range p.OutputNames() {
colName := name.ColName.O
if _, ok := dupNames[colName]; ok {
return nil, plannererrors.ErrDupFieldName.GenWithStackByArgs(colName)
}
dupNames[colName] = struct{}{}
}
return p, nil
case *ast.SelectStmt:
return b.buildSelect(ctx, x)
case *ast.SetOprStmt:
return b.buildSetOpr(ctx, x)
default:
return nil, plannererrors.ErrUnsupportedType.GenWithStack("Unsupported ast.ResultSetNode(%T) for buildResultSetNode()", x)
}
}
// pushDownConstExpr checks if the condition is from filter condition, if true, push it down to both
// children of join, whatever the join type is; if false, push it down to inner child of outer join,
// and both children of non-outer-join.
func (p *LogicalJoin) pushDownConstExpr(expr expression.Expression, leftCond []expression.Expression,
rightCond []expression.Expression, filterCond bool) ([]expression.Expression, []expression.Expression) {
switch p.JoinType {
case LeftOuterJoin, LeftOuterSemiJoin, AntiLeftOuterSemiJoin:
if filterCond {
leftCond = append(leftCond, expr)
// Append the expr to right join condition instead of `rightCond`, to make it able to be
// pushed down to children of join.
p.RightConditions = append(p.RightConditions, expr)
} else {
rightCond = append(rightCond, expr)
}
case RightOuterJoin:
if filterCond {
rightCond = append(rightCond, expr)
p.LeftConditions = append(p.LeftConditions, expr)
} else {
leftCond = append(leftCond, expr)
}
case SemiJoin, InnerJoin:
leftCond = append(leftCond, expr)
rightCond = append(rightCond, expr)
case AntiSemiJoin:
if filterCond {
leftCond = append(leftCond, expr)
}
rightCond = append(rightCond, expr)
}
return leftCond, rightCond
}
func (p *LogicalJoin) extractOnCondition(conditions []expression.Expression, deriveLeft bool,
deriveRight bool) (eqCond []*expression.ScalarFunction, leftCond []expression.Expression,
rightCond []expression.Expression, otherCond []expression.Expression) {
return p.ExtractOnCondition(conditions, p.Children()[0].Schema(), p.Children()[1].Schema(), deriveLeft, deriveRight)
}
// ExtractOnCondition divide conditions in CNF of join node into 4 groups.
// These conditions can be where conditions, join conditions, or collection of both.
// If deriveLeft/deriveRight is set, we would try to derive more conditions for left/right plan.
func (p *LogicalJoin) ExtractOnCondition(
conditions []expression.Expression,
leftSchema *expression.Schema,
rightSchema *expression.Schema,
deriveLeft bool,
deriveRight bool) (eqCond []*expression.ScalarFunction, leftCond []expression.Expression,
rightCond []expression.Expression, otherCond []expression.Expression) {
ctx := p.SCtx()
for _, expr := range conditions {
// For queries like `select a in (select a from s where s.b = t.b) from t`,
// if subquery is empty caused by `s.b = t.b`, the result should always be
// false even if t.a is null or s.a is null. To make this join "empty aware",
// we should differentiate `t.a = s.a` from other column equal conditions, so
// we put it into OtherConditions instead of EqualConditions of join.
if expression.IsEQCondFromIn(expr) {
otherCond = append(otherCond, expr)
continue
}
binop, ok := expr.(*expression.ScalarFunction)
if ok && len(binop.GetArgs()) == 2 {
arg0, lOK := binop.GetArgs()[0].(*expression.Column)
arg1, rOK := binop.GetArgs()[1].(*expression.Column)
if lOK && rOK {
leftCol := leftSchema.RetrieveColumn(arg0)
rightCol := rightSchema.RetrieveColumn(arg1)
if leftCol == nil || rightCol == nil {
leftCol = leftSchema.RetrieveColumn(arg1)
rightCol = rightSchema.RetrieveColumn(arg0)
arg0, arg1 = arg1, arg0
}
if leftCol != nil && rightCol != nil {
if deriveLeft {
if util.IsNullRejected(ctx, leftSchema, expr) && !mysql.HasNotNullFlag(leftCol.RetType.GetFlag()) {
notNullExpr := expression.BuildNotNullExpr(ctx.GetExprCtx(), leftCol)
leftCond = append(leftCond, notNullExpr)
}
}
if deriveRight {
if util.IsNullRejected(ctx, rightSchema, expr) && !mysql.HasNotNullFlag(rightCol.RetType.GetFlag()) {
notNullExpr := expression.BuildNotNullExpr(ctx.GetExprCtx(), rightCol)
rightCond = append(rightCond, notNullExpr)
}
}
if binop.FuncName.L == ast.EQ {
cond := expression.NewFunctionInternal(ctx.GetExprCtx(), ast.EQ, types.NewFieldType(mysql.TypeTiny), arg0, arg1)
eqCond = append(eqCond, cond.(*expression.ScalarFunction))
continue
}
}
}
}
columns := expression.ExtractColumns(expr)
// `columns` may be empty, if the condition is like `correlated_column op constant`, or `constant`,
// push this kind of constant condition down according to join type.
if len(columns) == 0 {
leftCond, rightCond = p.pushDownConstExpr(expr, leftCond, rightCond, deriveLeft || deriveRight)
continue
}
allFromLeft, allFromRight := true, true
for _, col := range columns {
if !leftSchema.Contains(col) {
allFromLeft = false
}
if !rightSchema.Contains(col) {
allFromRight = false
}
}
if allFromRight {
rightCond = append(rightCond, expr)
} else if allFromLeft {
leftCond = append(leftCond, expr)
} else {
// Relax expr to two supersets: leftRelaxedCond and rightRelaxedCond, the expression now is
// `expr AND leftRelaxedCond AND rightRelaxedCond`. Motivation is to push filters down to
// children as much as possible.
if deriveLeft {
leftRelaxedCond := expression.DeriveRelaxedFiltersFromDNF(ctx.GetExprCtx(), expr, leftSchema)
if leftRelaxedCond != nil {
leftCond = append(leftCond, leftRelaxedCond)
}
}
if deriveRight {
rightRelaxedCond := expression.DeriveRelaxedFiltersFromDNF(ctx.GetExprCtx(), expr, rightSchema)
if rightRelaxedCond != nil {
rightCond = append(rightCond, rightRelaxedCond)
}
}
otherCond = append(otherCond, expr)
}
}
return
}
// extractTableAlias returns table alias of the base.LogicalPlan's columns.
// It will return nil when there are multiple table alias, because the alias is only used to check if
// the base.LogicalPlan Match some optimizer hints, and hints are not expected to take effect in this case.
func extractTableAlias(p base.Plan, parentOffset int) *h.HintedTable {
if len(p.OutputNames()) > 0 && p.OutputNames()[0].TblName.L != "" {
firstName := p.OutputNames()[0]
for _, name := range p.OutputNames() {
if name.TblName.L != firstName.TblName.L ||
(name.DBName.L != "" && firstName.DBName.L != "" && name.DBName.L != firstName.DBName.L) { // DBName can be nil, see #46160
return nil
}
}
qbOffset := p.QueryBlockOffset()
var blockAsNames []ast.HintTable
if p := p.SCtx().GetSessionVars().PlannerSelectBlockAsName.Load(); p != nil {
blockAsNames = *p
}
// For sub-queries like `(select * from t) t1`, t1 should belong to its surrounding select block.
if qbOffset != parentOffset && blockAsNames != nil && blockAsNames[qbOffset].TableName.L != "" {
qbOffset = parentOffset
}
dbName := firstName.DBName
if dbName.L == "" {
dbName = model.NewCIStr(p.SCtx().GetSessionVars().CurrentDB)
}
return &h.HintedTable{DBName: dbName, TblName: firstName.TblName, SelectOffset: qbOffset}
}
return nil
}
func (p *LogicalJoin) setPreferredJoinTypeAndOrder(hintInfo *h.PlanHints) {
if hintInfo == nil {
return
}
lhsAlias := extractTableAlias(p.Children()[0], p.QueryBlockOffset())
rhsAlias := extractTableAlias(p.Children()[1], p.QueryBlockOffset())
if hintInfo.IfPreferMergeJoin(lhsAlias) {
p.preferJoinType |= h.PreferMergeJoin
p.leftPreferJoinType |= h.PreferMergeJoin
}
if hintInfo.IfPreferMergeJoin(rhsAlias) {
p.preferJoinType |= h.PreferMergeJoin
p.rightPreferJoinType |= h.PreferMergeJoin
}
if hintInfo.IfPreferNoMergeJoin(lhsAlias) {
p.preferJoinType |= h.PreferNoMergeJoin
p.leftPreferJoinType |= h.PreferNoMergeJoin
}
if hintInfo.IfPreferNoMergeJoin(rhsAlias) {
p.preferJoinType |= h.PreferNoMergeJoin
p.rightPreferJoinType |= h.PreferNoMergeJoin
}
if hintInfo.IfPreferBroadcastJoin(lhsAlias) {
p.preferJoinType |= h.PreferBCJoin
p.leftPreferJoinType |= h.PreferBCJoin
}
if hintInfo.IfPreferBroadcastJoin(rhsAlias) {
p.preferJoinType |= h.PreferBCJoin
p.rightPreferJoinType |= h.PreferBCJoin
}
if hintInfo.IfPreferShuffleJoin(lhsAlias) {
p.preferJoinType |= h.PreferShuffleJoin
p.leftPreferJoinType |= h.PreferShuffleJoin
}
if hintInfo.IfPreferShuffleJoin(rhsAlias) {
p.preferJoinType |= h.PreferShuffleJoin
p.rightPreferJoinType |= h.PreferShuffleJoin
}
if hintInfo.IfPreferHashJoin(lhsAlias) {
p.preferJoinType |= h.PreferHashJoin
p.leftPreferJoinType |= h.PreferHashJoin
}
if hintInfo.IfPreferHashJoin(rhsAlias) {
p.preferJoinType |= h.PreferHashJoin
p.rightPreferJoinType |= h.PreferHashJoin
}
if hintInfo.IfPreferNoHashJoin(lhsAlias) {
p.preferJoinType |= h.PreferNoHashJoin
p.leftPreferJoinType |= h.PreferNoHashJoin
}
if hintInfo.IfPreferNoHashJoin(rhsAlias) {
p.preferJoinType |= h.PreferNoHashJoin
p.rightPreferJoinType |= h.PreferNoHashJoin
}
if hintInfo.IfPreferINLJ(lhsAlias) {
p.preferJoinType |= h.PreferLeftAsINLJInner
p.leftPreferJoinType |= h.PreferINLJ
}
if hintInfo.IfPreferINLJ(rhsAlias) {
p.preferJoinType |= h.PreferRightAsINLJInner
p.rightPreferJoinType |= h.PreferINLJ
}
if hintInfo.IfPreferINLHJ(lhsAlias) {
p.preferJoinType |= h.PreferLeftAsINLHJInner
p.leftPreferJoinType |= h.PreferINLHJ
}
if hintInfo.IfPreferINLHJ(rhsAlias) {
p.preferJoinType |= h.PreferRightAsINLHJInner
p.rightPreferJoinType |= h.PreferINLHJ
}
if hintInfo.IfPreferINLMJ(lhsAlias) {
p.preferJoinType |= h.PreferLeftAsINLMJInner
p.leftPreferJoinType |= h.PreferINLMJ
}
if hintInfo.IfPreferINLMJ(rhsAlias) {
p.preferJoinType |= h.PreferRightAsINLMJInner
p.rightPreferJoinType |= h.PreferINLMJ
}
if hintInfo.IfPreferNoIndexJoin(lhsAlias) {
p.preferJoinType |= h.PreferNoIndexJoin
p.leftPreferJoinType |= h.PreferNoIndexJoin
}
if hintInfo.IfPreferNoIndexJoin(rhsAlias) {
p.preferJoinType |= h.PreferNoIndexJoin
p.rightPreferJoinType |= h.PreferNoIndexJoin
}
if hintInfo.IfPreferNoIndexHashJoin(lhsAlias) {
p.preferJoinType |= h.PreferNoIndexHashJoin
p.leftPreferJoinType |= h.PreferNoIndexHashJoin
}
if hintInfo.IfPreferNoIndexHashJoin(rhsAlias) {
p.preferJoinType |= h.PreferNoIndexHashJoin
p.rightPreferJoinType |= h.PreferNoIndexHashJoin
}
if hintInfo.IfPreferNoIndexMergeJoin(lhsAlias) {
p.preferJoinType |= h.PreferNoIndexMergeJoin
p.leftPreferJoinType |= h.PreferNoIndexMergeJoin
}
if hintInfo.IfPreferNoIndexMergeJoin(rhsAlias) {
p.preferJoinType |= h.PreferNoIndexMergeJoin
p.rightPreferJoinType |= h.PreferNoIndexMergeJoin
}
if hintInfo.IfPreferHJBuild(lhsAlias) {
p.preferJoinType |= h.PreferLeftAsHJBuild
p.leftPreferJoinType |= h.PreferHJBuild
}
if hintInfo.IfPreferHJBuild(rhsAlias) {
p.preferJoinType |= h.PreferRightAsHJBuild
p.rightPreferJoinType |= h.PreferHJBuild
}
if hintInfo.IfPreferHJProbe(lhsAlias) {
p.preferJoinType |= h.PreferLeftAsHJProbe
p.leftPreferJoinType |= h.PreferHJProbe
}
if hintInfo.IfPreferHJProbe(rhsAlias) {
p.preferJoinType |= h.PreferRightAsHJProbe
p.rightPreferJoinType |= h.PreferHJProbe
}
hasConflict := false
if !p.SCtx().GetSessionVars().EnableAdvancedJoinHint || p.SCtx().GetSessionVars().StmtCtx.StraightJoinOrder {
if containDifferentJoinTypes(p.preferJoinType) {
hasConflict = true
}
} else if p.SCtx().GetSessionVars().EnableAdvancedJoinHint {
if containDifferentJoinTypes(p.leftPreferJoinType) || containDifferentJoinTypes(p.rightPreferJoinType) {
hasConflict = true
}
}
if hasConflict {
p.SCtx().GetSessionVars().StmtCtx.SetHintWarning(
"Join hints are conflict, you can only specify one type of join")
p.preferJoinType = 0
}
// set the join order
if hintInfo.LeadingJoinOrder != nil {
p.preferJoinOrder = hintInfo.MatchTableName([]*h.HintedTable{lhsAlias, rhsAlias}, hintInfo.LeadingJoinOrder)
}
// set hintInfo for further usage if this hint info can be used.
if p.preferJoinType != 0 || p.preferJoinOrder {
p.hintInfo = hintInfo
}
}
func setPreferredJoinTypeFromOneSide(preferJoinType uint, isLeft bool) (resJoinType uint) {
if preferJoinType == 0 {
return
}
if preferJoinType&h.PreferINLJ > 0 {
preferJoinType &= ^h.PreferINLJ
if isLeft {
resJoinType |= h.PreferLeftAsINLJInner
} else {
resJoinType |= h.PreferRightAsINLJInner
}
}
if preferJoinType&h.PreferINLHJ > 0 {
preferJoinType &= ^h.PreferINLHJ
if isLeft {
resJoinType |= h.PreferLeftAsINLHJInner
} else {
resJoinType |= h.PreferRightAsINLHJInner
}
}
if preferJoinType&h.PreferINLMJ > 0 {
preferJoinType &= ^h.PreferINLMJ
if isLeft {
resJoinType |= h.PreferLeftAsINLMJInner
} else {
resJoinType |= h.PreferRightAsINLMJInner
}
}
if preferJoinType&h.PreferHJBuild > 0 {
preferJoinType &= ^h.PreferHJBuild
if isLeft {
resJoinType |= h.PreferLeftAsHJBuild
} else {
resJoinType |= h.PreferRightAsHJBuild
}
}
if preferJoinType&h.PreferHJProbe > 0 {
preferJoinType &= ^h.PreferHJProbe
if isLeft {
resJoinType |= h.PreferLeftAsHJProbe
} else {
resJoinType |= h.PreferRightAsHJProbe
}
}
resJoinType |= preferJoinType
return
}
// setPreferredJoinType generates hint information for the logicalJoin based on the hint information of its left and right children.
func (p *LogicalJoin) setPreferredJoinType() {
if p.leftPreferJoinType == 0 && p.rightPreferJoinType == 0 {
return
}
p.preferJoinType = setPreferredJoinTypeFromOneSide(p.leftPreferJoinType, true) | setPreferredJoinTypeFromOneSide(p.rightPreferJoinType, false)
if containDifferentJoinTypes(p.preferJoinType) {
p.SCtx().GetSessionVars().StmtCtx.SetHintWarning(
"Join hints conflict after join reorder phase, you can only specify one type of join")
p.preferJoinType = 0
}
}
func (ds *DataSource) setPreferredStoreType(hintInfo *h.PlanHints) {
if hintInfo == nil {
return
}
var alias *h.HintedTable
if len(ds.TableAsName.L) != 0 {
alias = &h.HintedTable{DBName: ds.DBName, TblName: *ds.TableAsName, SelectOffset: ds.QueryBlockOffset()}
} else {
alias = &h.HintedTable{DBName: ds.DBName, TblName: ds.tableInfo.Name, SelectOffset: ds.QueryBlockOffset()}
}
if hintTbl := hintInfo.IfPreferTiKV(alias); hintTbl != nil {
for _, path := range ds.possibleAccessPaths {
if path.StoreType == kv.TiKV {
ds.preferStoreType |= h.PreferTiKV
ds.preferPartitions[h.PreferTiKV] = hintTbl.Partitions
break
}
}
if ds.preferStoreType&h.PreferTiKV == 0 {
errMsg := fmt.Sprintf("No available path for table %s.%s with the store type %s of the hint /*+ read_from_storage */, "+
"please check the status of the table replica and variable value of tidb_isolation_read_engines(%v)",
ds.DBName.O, ds.table.Meta().Name.O, kv.TiKV.Name(), ds.SCtx().GetSessionVars().GetIsolationReadEngines())
ds.SCtx().GetSessionVars().StmtCtx.SetHintWarning(errMsg)
} else {
ds.SCtx().GetSessionVars().RaiseWarningWhenMPPEnforced("MPP mode may be blocked because you have set a hint to read table `" + hintTbl.TblName.O + "` from TiKV.")
}
}
if hintTbl := hintInfo.IfPreferTiFlash(alias); hintTbl != nil {
// `ds.preferStoreType != 0`, which means there's a hint hit the both TiKV value and TiFlash value for table.
// We can't support read a table from two different storages, even partition table.
if ds.preferStoreType != 0 {
ds.SCtx().GetSessionVars().StmtCtx.SetHintWarning(
fmt.Sprintf("Storage hints are conflict, you can only specify one storage type of table %s.%s",
alias.DBName.L, alias.TblName.L))
ds.preferStoreType = 0
return
}
for _, path := range ds.possibleAccessPaths {
if path.StoreType == kv.TiFlash {
ds.preferStoreType |= h.PreferTiFlash
ds.preferPartitions[h.PreferTiFlash] = hintTbl.Partitions
break
}
}
if ds.preferStoreType&h.PreferTiFlash == 0 {
errMsg := fmt.Sprintf("No available path for table %s.%s with the store type %s of the hint /*+ read_from_storage */, "+
"please check the status of the table replica and variable value of tidb_isolation_read_engines(%v)",
ds.DBName.O, ds.table.Meta().Name.O, kv.TiFlash.Name(), ds.SCtx().GetSessionVars().GetIsolationReadEngines())
ds.SCtx().GetSessionVars().StmtCtx.SetHintWarning(errMsg)
}
}
}
func resetNotNullFlag(schema *expression.Schema, start, end int) {
for i := start; i < end; i++ {
col := *schema.Columns[i]
newFieldType := *col.RetType
newFieldType.DelFlag(mysql.NotNullFlag)
col.RetType = &newFieldType
schema.Columns[i] = &col
}
}
func (b *PlanBuilder) buildJoin(ctx context.Context, joinNode *ast.Join) (base.LogicalPlan, error) {
// We will construct a "Join" node for some statements like "INSERT",
// "DELETE", "UPDATE", "REPLACE". For this scenario "joinNode.Right" is nil
// and we only build the left "ResultSetNode".
if joinNode.Right == nil {
return b.buildResultSetNode(ctx, joinNode.Left, false)
}
b.optFlag = b.optFlag | flagPredicatePushDown
// Add join reorder flag regardless of inner join or outer join.
b.optFlag = b.optFlag | flagJoinReOrder
b.optFlag |= flagPredicateSimplification
b.optFlag |= flagConvertOuterToInnerJoin
leftPlan, err := b.buildResultSetNode(ctx, joinNode.Left, false)
if err != nil {
return nil, err
}
rightPlan, err := b.buildResultSetNode(ctx, joinNode.Right, false)
if err != nil {
return nil, err
}
// The recursive part in CTE must not be on the right side of a LEFT JOIN.
if lc, ok := rightPlan.(*LogicalCTETable); ok && joinNode.Tp == ast.LeftJoin {
return nil, plannererrors.ErrCTERecursiveForbiddenJoinOrder.GenWithStackByArgs(lc.name)
}
handleMap1 := b.handleHelper.popMap()
handleMap2 := b.handleHelper.popMap()
b.handleHelper.mergeAndPush(handleMap1, handleMap2)
joinPlan := LogicalJoin{StraightJoin: joinNode.StraightJoin || b.inStraightJoin}.Init(b.ctx, b.getSelectOffset())
joinPlan.SetChildren(leftPlan, rightPlan)
joinPlan.SetSchema(expression.MergeSchema(leftPlan.Schema(), rightPlan.Schema()))
joinPlan.names = make([]*types.FieldName, leftPlan.Schema().Len()+rightPlan.Schema().Len())
copy(joinPlan.names, leftPlan.OutputNames())
copy(joinPlan.names[leftPlan.Schema().Len():], rightPlan.OutputNames())
// Set join type.
switch joinNode.Tp {
case ast.LeftJoin:
// left outer join need to be checked elimination
b.optFlag = b.optFlag | flagEliminateOuterJoin
joinPlan.JoinType = LeftOuterJoin
resetNotNullFlag(joinPlan.schema, leftPlan.Schema().Len(), joinPlan.schema.Len())
case ast.RightJoin:
// right outer join need to be checked elimination
b.optFlag = b.optFlag | flagEliminateOuterJoin
joinPlan.JoinType = RightOuterJoin
resetNotNullFlag(joinPlan.schema, 0, leftPlan.Schema().Len())
default:
joinPlan.JoinType = InnerJoin
}
// Merge sub-plan's fullSchema into this join plan.
// Please read the comment of LogicalJoin.fullSchema for the details.
var (
lFullSchema, rFullSchema *expression.Schema
lFullNames, rFullNames types.NameSlice
)
if left, ok := leftPlan.(*LogicalJoin); ok && left.fullSchema != nil {
lFullSchema = left.fullSchema
lFullNames = left.fullNames
} else {
lFullSchema = leftPlan.Schema()
lFullNames = leftPlan.OutputNames()
}
if right, ok := rightPlan.(*LogicalJoin); ok && right.fullSchema != nil {
rFullSchema = right.fullSchema
rFullNames = right.fullNames