forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logical_plan_builder.go
1699 lines (1594 loc) · 50.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"
"strings"
"unicode"
"github.com/cznic/mathutil"
"github.com/juju/errors"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/expression/aggregation"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/util/types"
)
const (
// TiDBMergeJoin is hint enforce merge join.
TiDBMergeJoin = "tidb_smj"
// TiDBIndexNestedLoopJoin is hint enforce index nested loop join.
TiDBIndexNestedLoopJoin = "tidb_inlj"
)
type idAllocator struct {
id int
}
func (a *idAllocator) allocID() int {
a.id++
return a.id
}
func (p *LogicalAggregation) collectGroupByColumns() {
p.groupByCols = p.groupByCols[:0]
for _, item := range p.GroupByItems {
if col, ok := item.(*expression.Column); ok {
p.groupByCols = append(p.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
agg := LogicalAggregation{AggFuncs: make([]aggregation.Aggregation, 0, len(aggFuncList))}.init(b.allocator, b.ctx)
schema := 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 {
var newArgList []expression.Expression
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.NewAggFunction(aggFunc.F, newArgList, aggFunc.Distinct)
combined := false
for j, oldFunc := range agg.AggFuncs {
if oldFunc.Equal(newFunc, b.ctx) {
aggIndexMap[i] = j
combined = true
break
}
}
if !combined {
position := len(agg.AggFuncs)
aggIndexMap[i] = position
agg.AggFuncs = append(agg.AggFuncs, newFunc)
schema.Append(&expression.Column{
FromID: agg.id,
ColName: model.NewCIStr(fmt.Sprintf("%d_col_%d", agg.id, position)),
Position: position,
IsAggOrSubq: true,
RetType: newFunc.GetType()})
}
}
for _, col := range p.Schema().Columns {
newFunc := aggregation.NewAggFunction(ast.AggFuncFirstRow, []expression.Expression{col.Clone()}, false)
agg.AggFuncs = append(agg.AggFuncs, newFunc)
schema.Append(col.Clone().(*expression.Column))
}
setParentAndChildren(agg, p)
agg.GroupByItems = gbyItems
agg.SetSchema(schema)
agg.collectGroupByColumns()
return agg, 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.Gen("unsupported table source type %T", v)
return nil
}
if b.err != nil {
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("")
}
}
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 dataSource, ok := p.(*DataSource); ok {
if dataSource.TableAsName.L != "" {
return dataSource.TableAsName
}
return &dataSource.tableInfo.Name
} else if len(p.Schema().Columns) > 0 {
if p.Schema().Columns[0].TblName.L != "" {
return &(p.Schema().Columns[0].TblName)
}
}
return nil
}
func (b *planBuilder) buildJoin(join *ast.Join) LogicalPlan {
if join.Right == nil {
return b.buildResultSetNode(join.Left)
}
b.optFlag = b.optFlag | flagPredicatePushDown
leftPlan := b.buildResultSetNode(join.Left)
rightPlan := b.buildResultSetNode(join.Right)
leftAlias := extractTableAlias(leftPlan)
rightAlias := extractTableAlias(rightPlan)
newSchema := expression.MergeSchema(leftPlan.Schema(), rightPlan.Schema())
joinPlan := LogicalJoin{}.init(b.allocator, b.ctx)
setParentAndChildren(joinPlan, leftPlan, rightPlan)
joinPlan.SetSchema(newSchema)
// 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)
if b.TableHints() != nil {
joinPlan.preferMergeJoin = b.TableHints().ifPreferMergeJoin(leftAlias, rightAlias)
if b.TableHints().ifPreferINLJ(leftAlias) {
joinPlan.preferINLJ = joinPlan.preferINLJ | preferLeftAsOuter
}
if b.TableHints().ifPreferINLJ(rightAlias) {
joinPlan.preferINLJ = joinPlan.preferINLJ | preferRightAsOuter
}
if joinPlan.preferMergeJoin && joinPlan.preferINLJ > 0 {
b.err = errors.New("Optimizer Hints is conflict")
return nil
}
}
if join.NaturalJoin {
if err := b.buildNaturalJoin(joinPlan, leftPlan, rightPlan, join); err != nil {
b.err = err
return nil
}
} else if join.Using != nil {
if err := b.buildUsingClause(joinPlan, leftPlan, rightPlan, join); err != nil {
b.err = err
return nil
}
} else if join.On != nil {
onExpr, _, err := b.rewrite(join.On.Expr, joinPlan, nil, false)
if err != nil {
b.err = err
return nil
}
if onExpr.IsCorrelated() {
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 {
joinPlan.cartesianJoin = true
}
if join.Tp == ast.LeftJoin {
joinPlan.JoinType = LeftOuterJoin
} else if join.Tp == ast.RightJoin {
joinPlan.JoinType = RightOuterJoin
} else {
joinPlan.JoinType = InnerJoin
}
return joinPlan
}
// buildUsingClause do redundant column elimination and column ordering based on using clause.
// According to standard SQL, producing this display order:
// First, coalesced common columns of the two joined tables, in the order in which they occur in the first table.
// Second, columns unique to the first table, in order in which they occur in that table.
// Third, columns unique to the second table, in order in which they occur in that table.
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 build natural join output schema. It find 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
conditions := splitWhere(where)
expressions := make([]expression.Expression, 0, len(conditions))
selection := Selection{}.init(b.allocator, 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(expression.CNFExprs{con}, nil, b.ctx)
if err != nil || ret {
continue
} else {
// If there is condition which is always false, return dual plan directly.
dual := TableDual{}.init(b.allocator, b.ctx)
dual.SetSchema(p.Schema().Clone())
return dual
}
}
expressions = append(expressions, item)
}
}
if len(expressions) == 0 {
return p
}
selection.Conditions = expressions
selection.SetSchema(p.Schema().Clone())
setParentAndChildren(selection, 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
proj := Projection{Exprs: make([]expression.Expression, 0, len(fields))}.init(b.allocator, 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)
setParentAndChildren(proj, p)
return proj, oldLen
}
func (b *planBuilder) buildDistinct(child LogicalPlan, length int) LogicalPlan {
b.optFlag = b.optFlag | flagBuildKeyInfo
b.optFlag = b.optFlag | flagAggregationOptimize
agg := LogicalAggregation{
AggFuncs: make([]aggregation.Aggregation, 0, child.Schema().Len()),
GroupByItems: expression.Column2Exprs(child.Schema().Clone().Columns[:length]),
}.init(b.allocator, b.ctx)
agg.collectGroupByColumns()
for _, col := range child.Schema().Columns {
agg.AggFuncs = append(agg.AggFuncs, aggregation.NewAggFunction(ast.AggFuncFirstRow, []expression.Expression{col}, false))
}
setParentAndChildren(agg, child)
agg.SetSchema(child.Schema().Clone())
return agg
}
// 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
resultTp.Charset = a.Charset
resultTp.Collate = a.Collate
expression.SetBinFlagOrBinStr(b, resultTp)
return resultTp
}
func (b *planBuilder) buildUnion(union *ast.UnionStmt) LogicalPlan {
u := Union{}.init(b.allocator, b.ctx)
u.children = make([]Plan, len(union.SelectList.Selects))
for i, sel := range union.SelectList.Selects {
u.children[i] = b.buildSelect(sel)
if b.err != nil {
return nil
}
}
firstSchema := u.children[0].Schema().Clone()
for i, sel := range u.children {
if firstSchema.Len() != sel.Schema().Len() {
b.err = errors.New("The used SELECT statements have a different number of columns")
return nil
}
if _, ok := sel.(*Projection); !ok {
b.optFlag |= flagEliminateProjection
proj := Projection{Exprs: expression.Column2Exprs(sel.Schema().Columns)}.init(b.allocator, b.ctx)
schema := sel.Schema().Clone()
for _, col := range schema.Columns {
col.FromID = proj.ID()
}
proj.SetSchema(schema)
setParentAndChildren(proj, sel)
sel = proj
u.children[i] = proj
}
sel.SetParents(u)
}
// infer union type
for i, col := range firstSchema.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
}
for _, v := range firstSchema.Columns {
v.FromID = u.id
v.DBName = model.NewCIStr("")
}
u.SetSchema(firstSchema)
var p LogicalPlan = u
if union.Distinct {
p = b.buildDistinct(u, u.Schema().Len())
}
if union.OrderBy != nil {
p = b.buildSort(p, union.OrderBy.Items, nil)
}
if union.Limit != nil {
p = b.buildLimit(p, union.Limit)
}
return p
}
// 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 {
sort := Sort{}.init(b.allocator, 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
setParentAndChildren(sort, p)
sort.SetSchema(p.Schema().Clone())
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 *variable.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 Limit/Offset", val)
}
func (b *planBuilder) buildLimit(src LogicalPlan, limit *ast.Limit) LogicalPlan {
if UseDAGPlanBuilder(b.ctx) {
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
return nil
}
}
if limit.Count != nil {
count, err = getUintForLimitOffset(sc, limit.Count.GetValue())
if err != nil {
b.err = ErrWrongArguments
return nil
}
}
li := Limit{
Offset: offset,
Count: count,
}.init(b.allocator, b.ctx)
setParentAndChildren(li, src)
li.SetSchema(src.Schema().Clone())
return li
}
// colMatch(a,b) 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)
}
}
}
return
}
// AggregateFuncExtractor 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
}
// 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) {
switch v := n.(type) {
case *ast.AggregateFuncExpr:
a.inAggFunc = false
a.aggMapper[v] = len(a.selectFields)
a.selectFields = append(a.selectFields, &ast.SelectField{
Auxiliary: true,
Expr: v,
AsName: model.NewCIStr(fmt.Sprintf("sel_agg_%d", len(a.selectFields))),
})
case *ast.ColumnNameExpr:
resolveFieldsFirst := true
if a.inAggFunc || (a.orderBy && a.inExpr) {
resolveFieldsFirst = false
}
if !a.inAggFunc && !a.orderBy {
for _, item := range a.gbyItems {
if col, ok := item.Expr.(*ast.ColumnNameExpr); ok &&
(colMatch(v.Name, col.Name) || colMatch(col.Name, v.Name)) {
resolveFieldsFirst = false
break
}
}
}
index := -1
if resolveFieldsFirst {
index, a.err = resolveFromSelectFields(v, a.selectFields, false)
if a.err != nil {
return node, false
}
if index == -1 {
if a.orderBy {
index, a.err = a.resolveFromSchema(v, a.p.Schema())
} else {
index, a.err = resolveFromSelectFields(v, a.selectFields, true)
}
}
} else {
// We should ignore the err when resolving from schema. Because we could resolve successfully
// when considering select fields.
var err error
index, err = a.resolveFromSchema(v, a.p.Schema())
_ = err
if index == -1 {
index, a.err = resolveFromSelectFields(v, a.selectFields, false)
}
}
if a.err != nil {
return node, false
}
if index == -1 {
// If we can't find it any where, it may be a correlated columns.
for _, schema := range a.outerSchemas {
col, err1 := schema.FindColumn(v.Name)
if err1 != nil {
a.err = errors.Trace(err1)
return node, false
}
if col != nil {
return n, true
}
}
a.err = errors.Errorf("Unknown Column %s", v.Name.Name.L)
return node, false
}
if a.inAggFunc {
return a.selectFields[index].Expr, true
}
a.colMapper[v] = index
}
return n, true
}
// resolveHavingAndOrderBy will process aggregate functions and resolve the columns that don't exist in select fields.
// If we found some columns that are not in select fields, we will append it to select fields and update the colMapper.
// When we rewrite the order by / having expression, we will find column in map at first.
func (b *planBuilder) resolveHavingAndOrderBy(sel *ast.SelectStmt, p LogicalPlan) (
map[*ast.AggregateFuncExpr]int, map[*ast.AggregateFuncExpr]int) {
extractor := &havingAndOrderbyExprResolver{
p: p,
selectFields: sel.Fields.Fields,
aggMapper: make(map[*ast.AggregateFuncExpr]int),
colMapper: b.colMapper,
outerSchemas: b.outerSchemas,
}
if sel.GroupBy != nil {
extractor.gbyItems = sel.GroupBy.Items
}
// Extract agg funcs from having clause.
if sel.Having != nil {
n, ok := sel.Having.Expr.Accept(extractor)
if !ok {
b.err = errors.Trace(extractor.err)
return nil, nil
}
sel.Having.Expr = n.(ast.ExprNode)
}
havingAggMapper := extractor.aggMapper
extractor.aggMapper = make(map[*ast.AggregateFuncExpr]int)
extractor.orderBy = true
extractor.inExpr = false
// Extract agg funcs from order by clause.
if sel.OrderBy != nil {
for _, item := range sel.OrderBy.Items {
n, ok := item.Expr.Accept(extractor)
if !ok {
b.err = errors.Trace(extractor.err)
return nil, nil
}
item.Expr = n.(ast.ExprNode)
}
}
sel.Fields.Fields = extractor.selectFields
return havingAggMapper, extractor.aggMapper
}
func (b *planBuilder) extractAggFuncs(fields []*ast.SelectField) ([]*ast.AggregateFuncExpr, map[*ast.AggregateFuncExpr]int) {
extractor := &AggregateFuncExtractor{}
for _, f := range fields {
n, _ := f.Expr.Accept(extractor)
f.Expr = n.(ast.ExprNode)
}
aggList := extractor.AggFuncs
totalAggMapper := make(map[*ast.AggregateFuncExpr]int)
for i, agg := range aggList {
totalAggMapper[agg] = i
}
return aggList, totalAggMapper
}
// gbyResolver resolves group by items from select fields.
type gbyResolver struct {
fields []*ast.SelectField
schema *expression.Schema
err error
inExpr bool
}
func (g *gbyResolver) Enter(inNode ast.Node) (ast.Node, bool) {
switch inNode.(type) {
case *ast.SubqueryExpr, *ast.CompareSubqueryExpr, *ast.ExistsSubqueryExpr:
return inNode, true
case *ast.ValueExpr, *ast.ColumnNameExpr, *ast.ParenthesesExpr, *ast.ColumnName:
default:
g.inExpr = true
}
return inNode, false
}
func (g *gbyResolver) Leave(inNode ast.Node) (ast.Node, bool) {
switch v := inNode.(type) {
case *ast.ColumnNameExpr:
col, err := g.schema.FindColumn(v.Name)
if col == nil || !g.inExpr {
var index = -1
index, g.err = resolveFromSelectFields(v, g.fields, false)
if g.err != nil {
return inNode, false
}
if col != nil {
return inNode, true
}
if index != -1 {
return g.fields[index].Expr, true
}
g.err = errors.Trace(err)
return inNode, false
}
case *ast.PositionExpr:
if v.N >= 1 && v.N <= len(g.fields) {
return g.fields[v.N-1].Expr, true
}
g.err = errors.Errorf("Unknown column '%d' in 'group statement'", v.N)
return inNode, false
}