-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
logical_plan_builder.go
2358 lines (2208 loc) · 69.4 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package plan
import (
"fmt"
"math"
"math/bits"
"reflect"
"strings"
"unicode"
"github.com/cznic/mathutil"
"github.com/juju/errors"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/expression/aggregation"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/opcode"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/types"
)
const (
// TiDBMergeJoin is hint enforce merge join.
TiDBMergeJoin = "tidb_smj"
// TiDBIndexNestedLoopJoin is hint enforce index nested loop join.
TiDBIndexNestedLoopJoin = "tidb_inlj"
// TiDBHashJoin is hint enforce hash join.
TiDBHashJoin = "tidb_hj"
)
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"
)
func (la *LogicalAggregation) collectGroupByColumns() {
la.groupByCols = la.groupByCols[:0]
for _, item := range la.GroupByItems {
if col, ok := item.(*expression.Column); ok {
la.groupByCols = append(la.groupByCols, col)
}
}
}
func (b *planBuilder) buildAggregation(p LogicalPlan, aggFuncList []*ast.AggregateFuncExpr, gbyItems []expression.Expression) (LogicalPlan, map[int]int) {
b.optFlag = b.optFlag | flagBuildKeyInfo
b.optFlag = b.optFlag | flagAggregationOptimize
// 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 = b.optFlag | flagMaxMinEliminate
b.optFlag = b.optFlag | flagPushDownTopN
// when we eliminate the max and min we may add `is not null` filter.
b.optFlag = b.optFlag | flagPredicatePushDown
plan4Agg := LogicalAggregation{AggFuncs: make([]*aggregation.AggFuncDesc, 0, len(aggFuncList))}.init(b.ctx)
schema4Agg := expression.NewSchema(make([]*expression.Column, 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)
for i, aggFunc := range aggFuncList {
newArgList := make([]expression.Expression, 0, len(aggFunc.Args))
for _, arg := range aggFunc.Args {
newArg, np, err := b.rewrite(arg, p, nil, true)
if err != nil {
b.err = errors.Trace(err)
return nil, nil
}
p = np
newArgList = append(newArgList, newArg)
}
newFunc := aggregation.NewAggFuncDesc(b.ctx, aggFunc.F, newArgList, aggFunc.Distinct)
combined := false
for j, oldFunc := range plan4Agg.AggFuncs {
if oldFunc.Equal(b.ctx, newFunc) {
aggIndexMap[i] = j
combined = true
break
}
}
if !combined {
position := len(plan4Agg.AggFuncs)
aggIndexMap[i] = position
plan4Agg.AggFuncs = append(plan4Agg.AggFuncs, newFunc)
schema4Agg.Append(&expression.Column{
FromID: plan4Agg.id,
ColName: model.NewCIStr(fmt.Sprintf("%d_col_%d", plan4Agg.id, position)),
Position: position,
IsAggOrSubq: true,
RetType: newFunc.RetTp})
}
}
for _, col := range p.Schema().Columns {
newFunc := aggregation.NewAggFuncDesc(b.ctx, ast.AggFuncFirstRow, []expression.Expression{col.Clone()}, false)
plan4Agg.AggFuncs = append(plan4Agg.AggFuncs, newFunc)
schema4Agg.Append(col.Clone().(*expression.Column))
}
plan4Agg.SetChildren(p)
plan4Agg.GroupByItems = gbyItems
plan4Agg.SetSchema(schema4Agg)
// TODO: Add a Projection if any argument of aggregate funcs or group by items are scalar functions.
// plan4Agg.buildProjectionIfNecessary()
// b.optFlag = b.optFlag | flagEliminateProjection
plan4Agg.collectGroupByColumns()
return plan4Agg, aggIndexMap
}
func (b *planBuilder) buildResultSetNode(node ast.ResultSetNode) LogicalPlan {
switch x := node.(type) {
case *ast.Join:
return b.buildJoin(x)
case *ast.TableSource:
var p LogicalPlan
switch v := x.Source.(type) {
case *ast.SelectStmt:
p = b.buildSelect(v)
case *ast.UnionStmt:
p = b.buildUnion(v)
case *ast.TableName:
p = b.buildDataSource(v)
default:
b.err = ErrUnsupportedType.GenByArgs(v)
}
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
if v, ok := p.(*DataSource); ok {
v.TableAsName = &x.AsName
}
for _, col := range p.Schema().Columns {
col.OrigTblName = col.TblName
if x.AsName.L != "" {
col.TblName = x.AsName
col.DBName = model.NewCIStr("")
}
}
// 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 _, col := range p.Schema().Columns {
name := col.ColName.O
if _, ok := dupNames[name]; ok {
b.err = ErrDupFieldName.GenByArgs(name)
return nil
}
dupNames[name] = struct{}{}
}
return p
case *ast.SelectStmt:
return b.buildSelect(x)
case *ast.UnionStmt:
return b.buildUnion(x)
default:
b.err = ErrUnsupportedType.Gen("unsupported table source type %T", x)
return nil
}
}
func extractCorColumns(expr expression.Expression) (cols []*expression.CorrelatedColumn) {
switch v := expr.(type) {
case *expression.CorrelatedColumn:
return []*expression.CorrelatedColumn{v}
case *expression.ScalarFunction:
for _, arg := range v.GetArgs() {
cols = append(cols, extractCorColumns(arg)...)
}
}
return
}
func extractOnCondition(conditions []expression.Expression, left LogicalPlan, right LogicalPlan) (
eqCond []*expression.ScalarFunction, leftCond []expression.Expression, rightCond []expression.Expression,
otherCond []expression.Expression) {
for _, expr := range conditions {
binop, ok := expr.(*expression.ScalarFunction)
if ok && binop.FuncName.L == ast.EQ {
ln, lOK := binop.GetArgs()[0].(*expression.Column)
rn, rOK := binop.GetArgs()[1].(*expression.Column)
if lOK && rOK {
if left.Schema().Contains(ln) && right.Schema().Contains(rn) {
eqCond = append(eqCond, binop)
continue
}
if left.Schema().Contains(rn) && right.Schema().Contains(ln) {
cond := expression.NewFunctionInternal(binop.GetCtx(), ast.EQ, types.NewFieldType(mysql.TypeTiny), rn, ln)
eqCond = append(eqCond, cond.(*expression.ScalarFunction))
continue
}
}
}
columns := expression.ExtractColumns(expr)
allFromLeft, allFromRight := true, true
for _, col := range columns {
if !left.Schema().Contains(col) {
allFromLeft = false
}
if !right.Schema().Contains(col) {
allFromRight = false
}
}
if allFromRight {
rightCond = append(rightCond, expr)
} else if allFromLeft {
leftCond = append(leftCond, expr)
} else {
otherCond = append(otherCond, expr)
}
}
return
}
func extractTableAlias(p LogicalPlan) *model.CIStr {
if p.Schema().Len() > 0 && p.Schema().Columns[0].TblName.L != "" {
return &(p.Schema().Columns[0].TblName)
}
return nil
}
func (p *LogicalJoin) setPreferredJoinType(hintInfo *tableHintInfo) error {
if hintInfo == nil {
return nil
}
lhsAlias := extractTableAlias(p.children[0])
rhsAlias := extractTableAlias(p.children[1])
if hintInfo.ifPreferMergeJoin(lhsAlias, rhsAlias) {
p.preferJoinType |= preferMergeJoin
}
if hintInfo.ifPreferHashJoin(lhsAlias, rhsAlias) {
p.preferJoinType |= preferHashJoin
}
if hintInfo.ifPreferINLJ(lhsAlias) {
p.preferJoinType |= preferLeftAsIndexOuter
}
if hintInfo.ifPreferINLJ(rhsAlias) {
p.preferJoinType |= preferRightAsIndexOuter
}
// If there're multiple join types and one of them is not index join hint,
// then there is a conflict of join types.
if bits.OnesCount(p.preferJoinType) > 1 && (p.preferJoinType^preferRightAsIndexOuter^preferLeftAsIndexOuter) > 0 {
return errors.New("Join hints are conflict, you can only specify one type of join")
}
return nil
}
func (b *planBuilder) buildJoin(joinNode *ast.Join) LogicalPlan {
// 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(joinNode.Left)
}
b.optFlag = b.optFlag | flagPredicatePushDown
leftPlan := b.buildResultSetNode(joinNode.Left)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
rightPlan := b.buildResultSetNode(joinNode.Right)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
joinPlan := LogicalJoin{StraightJoin: joinNode.StraightJoin || b.inStraightJoin}.init(b.ctx)
joinPlan.SetChildren(leftPlan, rightPlan)
joinPlan.SetSchema(expression.MergeSchema(leftPlan.Schema(), rightPlan.Schema()))
// Set join type.
switch joinNode.Tp {
case ast.LeftJoin:
joinPlan.JoinType = LeftOuterJoin
case ast.RightJoin:
joinPlan.JoinType = RightOuterJoin
default:
joinPlan.JoinType = InnerJoin
}
// Merge sub join's redundantSchema into this join plan. When handle query like
// select t2.a from (t1 join t2 using (a)) join t3 using (a);
// we can simply search in the top level join plan to find redundant column.
var lRedundant, rRedundant *expression.Schema
if left, ok := leftPlan.(*LogicalJoin); ok && left.redundantSchema != nil {
lRedundant = left.redundantSchema
}
if right, ok := rightPlan.(*LogicalJoin); ok && right.redundantSchema != nil {
rRedundant = right.redundantSchema
}
joinPlan.redundantSchema = expression.MergeSchema(lRedundant, rRedundant)
// Set preferred join algorithm if some join hints is specified by user.
err := joinPlan.setPreferredJoinType(b.TableHints())
if err != nil {
b.err = errors.Trace(err)
return nil
}
// "NATURAL JOIN" doesn't have "ON" or "USING" conditions.
//
// The "NATURAL [LEFT] JOIN" of two tables is defined to be semantically
// equivalent to an "INNER JOIN" or a "LEFT JOIN" with a "USING" clause
// that names all columns that exist in both tables.
//
// See https://dev.mysql.com/doc/refman/5.7/en/join.html for more detail.
if joinNode.NaturalJoin {
if err = b.buildNaturalJoin(joinPlan, leftPlan, rightPlan, joinNode); err != nil {
b.err = errors.Trace(err)
return nil
}
} else if joinNode.Using != nil {
if err = b.buildUsingClause(joinPlan, leftPlan, rightPlan, joinNode); err != nil {
b.err = errors.Trace(err)
return nil
}
} else if joinNode.On != nil {
b.curClause = onClause
onExpr, newPlan, err := b.rewrite(joinNode.On.Expr, joinPlan, nil, false)
if err != nil {
b.err = errors.Trace(err)
return nil
}
if newPlan != joinPlan {
b.err = errors.New("ON condition doesn't support subqueries yet")
return nil
}
onCondition := expression.SplitCNFItems(onExpr)
joinPlan.attachOnConds(onCondition)
} else if joinPlan.JoinType == InnerJoin {
// If a inner join without "ON" or "USING" clause, it's a cartesian
// product over the join tables.
joinPlan.cartesianJoin = true
}
return joinPlan
}
// buildUsingClause eliminate the redundant columns and ordering columns based
// on the "USING" clause.
//
// According to the standard SQL, columns are ordered in the following way:
// 1. coalesced common columns of "leftPlan" and "rightPlan", in the order they
// appears in "leftPlan".
// 2. the rest columns in "leftPlan", in the order they appears in "leftPlan".
// 3. the rest columns in "rightPlan", in the order they appears in "rightPlan".
func (b *planBuilder) buildUsingClause(p *LogicalJoin, leftPlan, rightPlan LogicalPlan, join *ast.Join) error {
filter := make(map[string]bool, len(join.Using))
for _, col := range join.Using {
filter[col.Name.L] = true
}
return b.coalesceCommonColumns(p, leftPlan, rightPlan, join.Tp == ast.RightJoin, filter)
}
// buildNaturalJoin builds natural join output schema. It finds out all the common columns
// then using the same mechanism as buildUsingClause to eliminate redundant columns and build join conditions.
// According to standard SQL, producing this display order:
// All the common columns
// Every column in the first (left) table that is not a common column
// Every column in the second (right) table that is not a common column
func (b *planBuilder) buildNaturalJoin(p *LogicalJoin, leftPlan, rightPlan LogicalPlan, join *ast.Join) error {
return b.coalesceCommonColumns(p, leftPlan, rightPlan, join.Tp == ast.RightJoin, nil)
}
// coalesceCommonColumns is used by buildUsingClause and buildNaturalJoin. The filter is used by buildUsingClause.
func (b *planBuilder) coalesceCommonColumns(p *LogicalJoin, leftPlan, rightPlan LogicalPlan, rightJoin bool, filter map[string]bool) error {
lsc := leftPlan.Schema().Clone()
rsc := rightPlan.Schema().Clone()
lColumns, rColumns := lsc.Columns, rsc.Columns
if rightJoin {
lColumns, rColumns = rsc.Columns, lsc.Columns
}
// Find out all the common columns and put them ahead.
commonLen := 0
for i, lCol := range lColumns {
for j := commonLen; j < len(rColumns); j++ {
if lCol.ColName.L != rColumns[j].ColName.L {
continue
}
if len(filter) > 0 {
if !filter[lCol.ColName.L] {
break
}
// Mark this column exist.
filter[lCol.ColName.L] = false
}
col := lColumns[i]
copy(lColumns[commonLen+1:i+1], lColumns[commonLen:i])
lColumns[commonLen] = col
col = rColumns[j]
copy(rColumns[commonLen+1:j+1], rColumns[commonLen:j])
rColumns[commonLen] = col
commonLen++
break
}
}
if len(filter) > 0 && len(filter) != commonLen {
for col, notExist := range filter {
if notExist {
return ErrUnknownColumn.GenByArgs(col, "from clause")
}
}
}
schemaCols := make([]*expression.Column, len(lColumns)+len(rColumns)-commonLen)
copy(schemaCols[:len(lColumns)], lColumns)
copy(schemaCols[len(lColumns):], rColumns[commonLen:])
conds := make([]expression.Expression, 0, commonLen)
for i := 0; i < commonLen; i++ {
lc, rc := lsc.Columns[i], rsc.Columns[i]
cond, err := expression.NewFunction(b.ctx, ast.EQ, types.NewFieldType(mysql.TypeTiny), lc, rc)
if err != nil {
return errors.Trace(err)
}
conds = append(conds, cond)
}
p.SetSchema(expression.NewSchema(schemaCols...))
p.redundantSchema = expression.MergeSchema(p.redundantSchema, expression.NewSchema(rColumns[:commonLen]...))
p.OtherConditions = append(conds, p.OtherConditions...)
return nil
}
func (b *planBuilder) buildSelection(p LogicalPlan, where ast.ExprNode, AggMapper map[*ast.AggregateFuncExpr]int) LogicalPlan {
b.optFlag = b.optFlag | flagPredicatePushDown
if b.curClause != havingClause {
b.curClause = whereClause
}
conditions := splitWhere(where)
expressions := make([]expression.Expression, 0, len(conditions))
selection := LogicalSelection{}.init(b.ctx)
for _, cond := range conditions {
expr, np, err := b.rewrite(cond, p, AggMapper, false)
if err != nil {
b.err = err
return nil
}
p = np
if expr == nil {
continue
}
cnfItems := expression.SplitCNFItems(expr)
for _, item := range cnfItems {
if con, ok := item.(*expression.Constant); ok {
ret, err := expression.EvalBool(b.ctx, expression.CNFExprs{con}, nil)
if err != nil || ret {
continue
} else {
// If there is condition which is always false, return dual plan directly.
dual := LogicalTableDual{}.init(b.ctx)
dual.SetSchema(p.Schema())
return dual
}
}
expressions = append(expressions, item)
}
}
if len(expressions) == 0 {
return p
}
selection.Conditions = expressions
selection.SetChildren(p)
return selection
}
// buildProjectionFieldNameFromColumns builds the field name, table name and database name when field expression is a column reference.
func (b *planBuilder) buildProjectionFieldNameFromColumns(field *ast.SelectField, c *expression.Column) (colName, tblName, origTblName, dbName model.CIStr) {
if astCol, ok := getInnerFromParentheses(field.Expr).(*ast.ColumnNameExpr); ok {
colName, tblName, dbName = astCol.Name.Name, astCol.Name.Table, astCol.Name.Schema
}
if field.AsName.L != "" {
colName = field.AsName
}
if tblName.L == "" {
tblName = c.TblName
}
if dbName.L == "" {
dbName = c.DBName
}
return colName, tblName, c.OrigTblName, c.DBName
}
// buildProjectionFieldNameFromExpressions builds the field name when field expression is a normal expression.
func (b *planBuilder) buildProjectionFieldNameFromExpressions(field *ast.SelectField) model.CIStr {
if agg, ok := field.Expr.(*ast.AggregateFuncExpr); ok && agg.F == ast.AggFuncFirstRow {
// When the query is select t.a from t group by a; The Column Name should be a but not t.a;
return agg.Args[0].(*ast.ColumnNameExpr).Name.Name
}
innerExpr := getInnerFromParentheses(field.Expr)
valueExpr, isValueExpr := innerExpr.(*ast.ValueExpr)
// Non-literal: Output as inputed, except that comments need to be removed.
if !isValueExpr {
return model.NewCIStr(parser.SpecFieldPattern.ReplaceAllStringFunc(field.Text(), parser.TrimComment))
}
// Literal: Need special processing
switch valueExpr.Kind() {
case types.KindString:
projName := valueExpr.GetString()
projOffset := valueExpr.GetProjectionOffset()
if projOffset >= 0 {
projName = projName[:projOffset]
}
// See #3686, #3994:
// For string literals, string content is used as column name. Non-graph initial characters are trimmed.
fieldName := strings.TrimLeftFunc(projName, func(r rune) bool {
return !unicode.IsOneOf(mysql.RangeGraph, r)
})
return model.NewCIStr(fieldName)
case types.KindNull:
// See #4053, #3685
return model.NewCIStr("NULL")
default:
// Keep as it is.
if innerExpr.Text() != "" {
return model.NewCIStr(innerExpr.Text())
}
return model.NewCIStr(field.Text())
}
}
// buildProjectionField builds the field object according to SelectField in projection.
func (b *planBuilder) buildProjectionField(id, position int, field *ast.SelectField, expr expression.Expression) *expression.Column {
var origTblName, tblName, colName, dbName model.CIStr
if c, ok := expr.(*expression.Column); ok && !c.IsAggOrSubq {
// Field is a column reference.
colName, tblName, origTblName, dbName = b.buildProjectionFieldNameFromColumns(field, c)
} else if field.AsName.L != "" {
// Field has alias.
colName = field.AsName
} else {
// Other: field is an expression.
colName = b.buildProjectionFieldNameFromExpressions(field)
}
return &expression.Column{
FromID: id,
Position: position,
TblName: tblName,
OrigTblName: origTblName,
ColName: colName,
DBName: dbName,
RetType: expr.GetType(),
}
}
// buildProjection returns a Projection plan and non-aux columns length.
func (b *planBuilder) buildProjection(p LogicalPlan, fields []*ast.SelectField, mapper map[*ast.AggregateFuncExpr]int) (LogicalPlan, int) {
b.optFlag |= flagEliminateProjection
b.curClause = fieldList
proj := LogicalProjection{Exprs: make([]expression.Expression, 0, len(fields))}.init(b.ctx)
schema := expression.NewSchema(make([]*expression.Column, 0, len(fields))...)
oldLen := 0
for _, field := range fields {
newExpr, np, err := b.rewrite(field.Expr, p, mapper, true)
if err != nil {
b.err = errors.Trace(err)
return nil, oldLen
}
p = np
proj.Exprs = append(proj.Exprs, newExpr)
col := b.buildProjectionField(proj.id, schema.Len()+1, field, newExpr)
schema.Append(col)
if !field.Auxiliary {
oldLen++
}
}
proj.SetSchema(schema)
proj.SetChildren(p)
return proj, oldLen
}
func (b *planBuilder) buildDistinct(child LogicalPlan, length int) LogicalPlan {
b.optFlag = b.optFlag | flagBuildKeyInfo
b.optFlag = b.optFlag | flagAggregationOptimize
plan4Agg := LogicalAggregation{
AggFuncs: make([]*aggregation.AggFuncDesc, 0, child.Schema().Len()),
GroupByItems: expression.Column2Exprs(child.Schema().Clone().Columns[:length]),
}.init(b.ctx)
plan4Agg.collectGroupByColumns()
for _, col := range child.Schema().Columns {
aggDesc := aggregation.NewAggFuncDesc(b.ctx, ast.AggFuncFirstRow, []expression.Expression{col}, false)
plan4Agg.AggFuncs = append(plan4Agg.AggFuncs, aggDesc)
}
plan4Agg.SetChildren(child)
plan4Agg.SetSchema(child.Schema().Clone())
// TODO: Add a Projection if any argument of aggregate funcs or group by items are scalar functions.
// plan4Agg.buildProjectionIfNecessary()
// b.optFlag = b.optFlag | flagEliminateProjection
return plan4Agg
}
// joinFieldType finds the type which can carry the given types.
func joinFieldType(a, b *types.FieldType) *types.FieldType {
resultTp := types.NewFieldType(types.MergeFieldType(a.Tp, b.Tp))
resultTp.Decimal = mathutil.Max(a.Decimal, b.Decimal)
// `Flen - Decimal` is the fraction before '.'
resultTp.Flen = mathutil.Max(a.Flen-a.Decimal, b.Flen-b.Decimal) + resultTp.Decimal
if resultTp.EvalType() != types.ETInt && (a.EvalType() == types.ETInt || b.EvalType() == types.ETInt) && resultTp.Flen < mysql.MaxIntWidth {
resultTp.Flen = mysql.MaxIntWidth
}
resultTp.Charset = a.Charset
resultTp.Collate = a.Collate
expression.SetBinFlagOrBinStr(b, resultTp)
return resultTp
}
func (b *planBuilder) buildProjection4Union(u *LogicalUnionAll) {
unionSchema := u.children[0].Schema().Clone()
// Infer union result types by its children's schema.
for i, col := range unionSchema.Columns {
var resultTp *types.FieldType
for j, child := range u.children {
childTp := child.Schema().Columns[i].RetType
if j == 0 {
resultTp = childTp
} else {
resultTp = joinFieldType(resultTp, childTp)
}
}
col.RetType = resultTp
col.TblName = model.NewCIStr("")
col.DBName = model.NewCIStr("")
}
// If the types of some child don't match the types of union, we add a projection with cast function.
for childID, child := range u.children {
exprs := make([]expression.Expression, len(child.Schema().Columns))
needProjection := false
for i, srcCol := range child.Schema().Columns {
dstType := unionSchema.Columns[i].RetType
srcType := srcCol.RetType
if !srcType.Equal(dstType) {
exprs[i] = expression.BuildCastFunction(b.ctx, srcCol.Clone(), dstType)
needProjection = true
} else {
exprs[i] = srcCol.Clone()
}
}
if _, isProj := child.(*LogicalProjection); needProjection || !isProj {
b.optFlag |= flagEliminateProjection
proj := LogicalProjection{Exprs: exprs, avoidColumnEvaluator: true}.init(b.ctx)
if childID == 0 {
for _, col := range unionSchema.Columns {
col.FromID = proj.ID()
}
}
proj.SetChildren(child)
u.children[childID] = proj
}
u.children[childID].(*LogicalProjection).SetSchema(unionSchema.Clone())
}
}
func (b *planBuilder) buildUnion(union *ast.UnionStmt) LogicalPlan {
distinctSelectPlans, allSelectPlans := b.divideUnionSelectPlans(union.SelectList.Selects)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
unionDistinctPlan := b.buildSubUnion(distinctSelectPlans)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
if unionDistinctPlan != nil {
unionDistinctPlan = b.buildDistinct(unionDistinctPlan, unionDistinctPlan.Schema().Len())
if len(allSelectPlans) > 0 {
// Can't change the statements order in order to get the correct column info.
allSelectPlans = append([]LogicalPlan{unionDistinctPlan}, allSelectPlans...)
}
}
unionAllPlan := b.buildSubUnion(allSelectPlans)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
unionPlan := unionDistinctPlan
if unionAllPlan != nil {
unionPlan = unionAllPlan
}
oldLen := unionPlan.Schema().Len()
if union.OrderBy != nil {
unionPlan = b.buildSort(unionPlan, union.OrderBy.Items, nil)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
}
if union.Limit != nil {
unionPlan = b.buildLimit(unionPlan, union.Limit)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil
}
}
// Fix issue #8189 (https://github.com/pingcap/tidb/issues/8189).
// If there are extra expressions generated from `ORDER BY` clause, generate a `Projection` to remove them.
if oldLen != unionPlan.Schema().Len() {
proj := LogicalProjection{Exprs: expression.Column2Exprs(unionPlan.Schema().Columns[:oldLen])}.init(b.ctx)
proj.SetChildren(unionPlan)
schema := expression.NewSchema(unionPlan.Schema().Clone().Columns[:oldLen]...)
for _, col := range schema.Columns {
col.FromID = proj.ID()
}
proj.SetSchema(schema)
return proj
}
return unionPlan
}
// divideUnionSelectPlans resolves union's select stmts to logical plans.
// and divide result plans into "union-distinct" and "union-all" parts.
// divide rule ref: https://dev.mysql.com/doc/refman/5.7/en/union.html
// "Mixed UNION types are treated such that a DISTINCT union overrides any ALL union to its left."
func (b *planBuilder) divideUnionSelectPlans(selects []*ast.SelectStmt) (distinctSelects []LogicalPlan, allSelects []LogicalPlan) {
firstUnionAllIdx, columnNums := 0, -1
// The last slot is reserved for appending distinct union outside this function.
children := make([]LogicalPlan, len(selects), len(selects)+1)
for i := len(selects) - 1; i >= 0; i-- {
stmt := selects[i]
if firstUnionAllIdx == 0 && stmt.IsAfterUnionDistinct {
firstUnionAllIdx = i + 1
}
selectPlan := b.buildSelect(stmt)
if b.err != nil {
b.err = errors.Trace(b.err)
return nil, nil
}
if columnNums == -1 {
columnNums = selectPlan.Schema().Len()
}
if selectPlan.Schema().Len() != columnNums {
b.err = ErrWrongNumberOfColumnsInSelect.GenByArgs()
return nil, nil
}
children[i] = selectPlan
}
return children[:firstUnionAllIdx], children[firstUnionAllIdx:]
}
func (b *planBuilder) buildSubUnion(subPlan []LogicalPlan) LogicalPlan {
if len(subPlan) == 0 {
return nil
}
u := LogicalUnionAll{}.init(b.ctx)
u.children = subPlan
b.buildProjection4Union(u)
return u
}
// ByItems wraps a "by" item.
type ByItems struct {
Expr expression.Expression
Desc bool
}
// String implements fmt.Stringer interface.
func (by *ByItems) String() string {
if by.Desc {
return fmt.Sprintf("%s true", by.Expr)
}
return by.Expr.String()
}
// Clone makes a copy of ByItems.
func (by *ByItems) Clone() *ByItems {
return &ByItems{Expr: by.Expr.Clone(), Desc: by.Desc}
}
func (b *planBuilder) buildSort(p LogicalPlan, byItems []*ast.ByItem, aggMapper map[*ast.AggregateFuncExpr]int) LogicalPlan {
if _, isUnion := p.(*LogicalUnionAll); isUnion {
b.curClause = globalOrderByClause
} else {
b.curClause = orderByClause
}
sort := LogicalSort{}.init(b.ctx)
exprs := make([]*ByItems, 0, len(byItems))
for _, item := range byItems {
it, np, err := b.rewrite(item.Expr, p, aggMapper, true)
if err != nil {
b.err = err
return nil
}
p = np
exprs = append(exprs, &ByItems{Expr: it, Desc: item.Desc})
}
sort.ByItems = exprs
sort.SetChildren(p)
return sort
}
// getUintForLimitOffset gets uint64 value for limit/offset.
// For ordinary statement, limit/offset should be uint64 constant value.
// For prepared statement, limit/offset is string. We should convert it to uint64.
func getUintForLimitOffset(sc *stmtctx.StatementContext, val interface{}) (uint64, error) {
switch v := val.(type) {
case uint64:
return v, nil
case int64:
if v >= 0 {
return uint64(v), nil
}
case string:
uVal, err := types.StrToUint(sc, v)
return uVal, errors.Trace(err)
}
return 0, errors.Errorf("Invalid type %T for LogicalLimit/Offset", val)
}
func (b *planBuilder) buildLimit(src LogicalPlan, limit *ast.Limit) LogicalPlan {
b.optFlag = b.optFlag | flagPushDownTopN
var (
offset, count uint64
err error
)
sc := b.ctx.GetSessionVars().StmtCtx
if limit.Offset != nil {
offset, err = getUintForLimitOffset(sc, limit.Offset.GetValue())
if err != nil {
b.err = ErrWrongArguments.GenByArgs("LIMIT")
return nil
}
}
if limit.Count != nil {
count, err = getUintForLimitOffset(sc, limit.Count.GetValue())
if err != nil {
b.err = ErrWrongArguments.GenByArgs("LIMIT")
return nil
}
}
if count > math.MaxUint64-offset {
count = math.MaxUint64 - offset
}
if offset+count == 0 {
tableDual := LogicalTableDual{RowCount: 0}.init(b.ctx)
tableDual.schema = src.Schema()
return tableDual
}
li := LogicalLimit{
Offset: offset,
Count: count,
}.init(b.ctx)
li.SetChildren(src)
return li
}
// colMatch means that if a match b, e.g. t.a can match test.t.a but test.t.a can't match t.a.
// Because column a want column from database test exactly.
func colMatch(a *ast.ColumnName, b *ast.ColumnName) bool {
if a.Schema.L == "" || a.Schema.L == b.Schema.L {
if a.Table.L == "" || a.Table.L == b.Table.L {
return a.Name.L == b.Name.L
}
}
return false
}
func matchField(f *ast.SelectField, col *ast.ColumnNameExpr, ignoreAsName bool) bool {
// if col specify a table name, resolve from table source directly.
if col.Name.Table.L == "" {
if f.AsName.L == "" || ignoreAsName {
if curCol, isCol := f.Expr.(*ast.ColumnNameExpr); isCol {
return curCol.Name.Name.L == col.Name.Name.L
}
// a expression without as name can't be matched.
return false
}
return f.AsName.L == col.Name.Name.L
}
return false
}
func resolveFromSelectFields(v *ast.ColumnNameExpr, fields []*ast.SelectField, ignoreAsName bool) (index int, err error) {
var matchedExpr ast.ExprNode
index = -1
for i, field := range fields {
if field.Auxiliary {
continue
}
if matchField(field, v, ignoreAsName) {
curCol, isCol := field.Expr.(*ast.ColumnNameExpr)
if !isCol {
return i, nil
}
if matchedExpr == nil {
matchedExpr = curCol
index = i
} else if !colMatch(matchedExpr.(*ast.ColumnNameExpr).Name, curCol.Name) &&
!colMatch(curCol.Name, matchedExpr.(*ast.ColumnNameExpr).Name) {
return -1, ErrAmbiguous.GenByArgs(curCol.Name.Name.L, clauseMsg[fieldList])
}
}
}
return
}
// havingAndOrderbyExprResolver visits Expr tree.
// It converts ColunmNameExpr to AggregateFuncExpr and collects AggregateFuncExpr.
type havingAndOrderbyExprResolver struct {
inAggFunc bool
inExpr bool
orderBy bool
err error
p LogicalPlan
selectFields []*ast.SelectField
aggMapper map[*ast.AggregateFuncExpr]int
colMapper map[*ast.ColumnNameExpr]int
gbyItems []*ast.ByItem
outerSchemas []*expression.Schema
curClause clauseCode
}
// Enter implements Visitor interface.
func (a *havingAndOrderbyExprResolver) Enter(n ast.Node) (node ast.Node, skipChildren bool) {
switch n.(type) {
case *ast.AggregateFuncExpr:
a.inAggFunc = true
case *ast.ParamMarkerExpr, *ast.ColumnNameExpr, *ast.ColumnName:
case *ast.SubqueryExpr, *ast.ExistsSubqueryExpr:
// Enter a new context, skip it.
// For example: select sum(c) + c + exists(select c from t) from t;
return n, true
default:
a.inExpr = true
}
return n, false
}
func (a *havingAndOrderbyExprResolver) resolveFromSchema(v *ast.ColumnNameExpr, schema *expression.Schema) (int, error) {
col, err := schema.FindColumn(v.Name)
if err != nil {
return -1, errors.Trace(err)
}
if col == nil {
return -1, nil
}
newColName := &ast.ColumnName{
Schema: col.DBName,
Table: col.TblName,
Name: col.ColName,
}
for i, field := range a.selectFields {
if c, ok := field.Expr.(*ast.ColumnNameExpr); ok && colMatch(newColName, c.Name) {
return i, nil
}
}
sf := &ast.SelectField{
Expr: &ast.ColumnNameExpr{Name: newColName},
Auxiliary: true,
}
sf.Expr.SetType(col.GetType())
a.selectFields = append(a.selectFields, sf)
return len(a.selectFields) - 1, nil
}
// Leave implements Visitor interface.
func (a *havingAndOrderbyExprResolver) Leave(n ast.Node) (node ast.Node, ok bool) {