forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplanbuilder.go
3743 lines (3503 loc) · 136 KB
/
planbuilder.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 2015 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 core
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"strings"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/parser"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/charset"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/opcode"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/planner/property"
"github.com/pingcap/tidb/planner/util"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/store/tikv"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/types"
driver "github.com/pingcap/tidb/types/parser_driver"
util2 "github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/execdetails"
"github.com/pingcap/tidb/util/hint"
"github.com/pingcap/tidb/util/logutil"
utilparser "github.com/pingcap/tidb/util/parser"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/set"
"github.com/cznic/mathutil"
"github.com/pingcap/tidb/table/tables"
"go.uber.org/zap"
)
type visitInfo struct {
privilege mysql.PrivilegeType
db string
table string
column string
err error
alterWritable bool
}
type indexNestedLoopJoinTables struct {
inljTables []hintTableInfo
inlhjTables []hintTableInfo
inlmjTables []hintTableInfo
}
type tableHintInfo struct {
indexNestedLoopJoinTables
sortMergeJoinTables []hintTableInfo
broadcastJoinTables []hintTableInfo
broadcastJoinPreferredLocal []hintTableInfo
hashJoinTables []hintTableInfo
indexHintList []indexHintInfo
tiflashTables []hintTableInfo
tikvTables []hintTableInfo
aggHints aggHintInfo
indexMergeHintList []indexHintInfo
timeRangeHint ast.HintTimeRange
limitHints limitHintInfo
}
type limitHintInfo struct {
preferLimitToCop bool
}
type hintTableInfo struct {
dbName model.CIStr
tblName model.CIStr
partitions []model.CIStr
selectOffset int
matched bool
}
type indexHintInfo struct {
dbName model.CIStr
tblName model.CIStr
partitions []model.CIStr
indexHint *ast.IndexHint
// Matched indicates whether this index hint
// has been successfully applied to a DataSource.
// If an indexHintInfo is not matched after building
// a Select statement, we will generate a warning for it.
matched bool
}
func (hint *indexHintInfo) hintTypeString() string {
switch hint.indexHint.HintType {
case ast.HintUse:
return "use_index"
case ast.HintIgnore:
return "ignore_index"
case ast.HintForce:
return "force_index"
}
return ""
}
// indexString formats the indexHint as dbName.tableName[, indexNames].
func (hint *indexHintInfo) indexString() string {
var indexListString string
indexList := make([]string, len(hint.indexHint.IndexNames))
for i := range hint.indexHint.IndexNames {
indexList[i] = hint.indexHint.IndexNames[i].L
}
if len(indexList) > 0 {
indexListString = fmt.Sprintf(", %s", strings.Join(indexList, ", "))
}
return fmt.Sprintf("%s.%s%s", hint.dbName, hint.tblName, indexListString)
}
type aggHintInfo struct {
preferAggType uint
preferAggToCop bool
}
// QueryTimeRange represents a time range specified by TIME_RANGE hint
type QueryTimeRange struct {
From time.Time
To time.Time
}
// Condition returns a WHERE clause base on it's value
func (tr *QueryTimeRange) Condition() string {
return fmt.Sprintf("where time>='%s' and time<='%s'", tr.From.Format(MetricTableTimeFormat), tr.To.Format(MetricTableTimeFormat))
}
func tableNames2HintTableInfo(ctx sessionctx.Context, hintName string, hintTables []ast.HintTable, p *hint.BlockHintProcessor, currentOffset int) []hintTableInfo {
if len(hintTables) == 0 {
return nil
}
hintTableInfos := make([]hintTableInfo, 0, len(hintTables))
defaultDBName := model.NewCIStr(ctx.GetSessionVars().CurrentDB)
isInapplicable := false
for _, hintTable := range hintTables {
tableInfo := hintTableInfo{
dbName: hintTable.DBName,
tblName: hintTable.TableName,
partitions: hintTable.PartitionList,
selectOffset: p.GetHintOffset(hintTable.QBName, currentOffset),
}
if tableInfo.dbName.L == "" {
tableInfo.dbName = defaultDBName
}
switch hintName {
case TiDBMergeJoin, HintSMJ, TiDBIndexNestedLoopJoin, HintINLJ, HintINLHJ, HintINLMJ, TiDBHashJoin, HintHJ:
if len(tableInfo.partitions) > 0 {
isInapplicable = true
}
}
hintTableInfos = append(hintTableInfos, tableInfo)
}
if isInapplicable {
ctx.GetSessionVars().StmtCtx.AppendWarning(
errors.New(fmt.Sprintf("Optimizer Hint %s is inapplicable on specified partitions",
restore2JoinHint(hintName, hintTableInfos))))
return nil
}
return hintTableInfos
}
// ifPreferAsLocalInBCJoin checks if there is a data source specified as local read by hint
func (info *tableHintInfo) ifPreferAsLocalInBCJoin(p LogicalPlan, blockOffset int) bool {
alias := extractTableAlias(p, blockOffset)
if alias != nil {
tableNames := make([]*hintTableInfo, 1)
tableNames[0] = alias
return info.matchTableName(tableNames, info.broadcastJoinPreferredLocal)
}
for _, c := range p.Children() {
if info.ifPreferAsLocalInBCJoin(c, blockOffset) {
return true
}
}
return false
}
func (info *tableHintInfo) ifPreferMergeJoin(tableNames ...*hintTableInfo) bool {
return info.matchTableName(tableNames, info.sortMergeJoinTables)
}
func (info *tableHintInfo) ifPreferBroadcastJoin(tableNames ...*hintTableInfo) bool {
return info.matchTableName(tableNames, info.broadcastJoinTables)
}
func (info *tableHintInfo) ifPreferHashJoin(tableNames ...*hintTableInfo) bool {
return info.matchTableName(tableNames, info.hashJoinTables)
}
func (info *tableHintInfo) ifPreferINLJ(tableNames ...*hintTableInfo) bool {
return info.matchTableName(tableNames, info.indexNestedLoopJoinTables.inljTables)
}
func (info *tableHintInfo) ifPreferINLHJ(tableNames ...*hintTableInfo) bool {
return info.matchTableName(tableNames, info.indexNestedLoopJoinTables.inlhjTables)
}
func (info *tableHintInfo) ifPreferINLMJ(tableNames ...*hintTableInfo) bool {
return info.matchTableName(tableNames, info.indexNestedLoopJoinTables.inlmjTables)
}
func (info *tableHintInfo) ifPreferTiFlash(tableName *hintTableInfo) *hintTableInfo {
if tableName == nil {
return nil
}
for i, tbl := range info.tiflashTables {
if tableName.dbName.L == tbl.dbName.L && tableName.tblName.L == tbl.tblName.L && tbl.selectOffset == tableName.selectOffset {
info.tiflashTables[i].matched = true
return &tbl
}
}
return nil
}
func (info *tableHintInfo) ifPreferTiKV(tableName *hintTableInfo) *hintTableInfo {
if tableName == nil {
return nil
}
for i, tbl := range info.tikvTables {
if tableName.dbName.L == tbl.dbName.L && tableName.tblName.L == tbl.tblName.L && tbl.selectOffset == tableName.selectOffset {
info.tikvTables[i].matched = true
return &tbl
}
}
return nil
}
// matchTableName checks whether the hint hit the need.
// Only need either side matches one on the list.
// Even though you can put 2 tables on the list,
// it doesn't mean optimizer will reorder to make them
// join directly.
// Which it joins on with depend on sequence of traverse
// and without reorder, user might adjust themselves.
// This is similar to MySQL hints.
func (info *tableHintInfo) matchTableName(tables []*hintTableInfo, hintTables []hintTableInfo) bool {
hintMatched := false
for _, table := range tables {
for i, curEntry := range hintTables {
if table == nil {
continue
}
if curEntry.dbName.L == table.dbName.L && curEntry.tblName.L == table.tblName.L && table.selectOffset == curEntry.selectOffset {
hintTables[i].matched = true
hintMatched = true
break
}
}
}
return hintMatched
}
func restore2TableHint(hintTables ...hintTableInfo) string {
buffer := bytes.NewBufferString("")
for i, table := range hintTables {
buffer.WriteString(table.tblName.L)
if len(table.partitions) > 0 {
buffer.WriteString(" PARTITION(")
for j, partition := range table.partitions {
if j > 0 {
buffer.WriteString(", ")
}
buffer.WriteString(partition.L)
}
buffer.WriteString(")")
}
if i < len(hintTables)-1 {
buffer.WriteString(", ")
}
}
return buffer.String()
}
func restore2JoinHint(hintType string, hintTables []hintTableInfo) string {
buffer := bytes.NewBufferString("/*+ ")
buffer.WriteString(strings.ToUpper(hintType))
buffer.WriteString("(")
buffer.WriteString(restore2TableHint(hintTables...))
buffer.WriteString(") */")
return buffer.String()
}
func restore2IndexHint(hintType string, hintIndex indexHintInfo) string {
buffer := bytes.NewBufferString("/*+ ")
buffer.WriteString(strings.ToUpper(hintType))
buffer.WriteString("(")
buffer.WriteString(restore2TableHint(hintTableInfo{
dbName: hintIndex.dbName,
tblName: hintIndex.tblName,
partitions: hintIndex.partitions,
}))
if hintIndex.indexHint != nil && len(hintIndex.indexHint.IndexNames) > 0 {
for i, indexName := range hintIndex.indexHint.IndexNames {
if i > 0 {
buffer.WriteString(",")
}
buffer.WriteString(" " + indexName.L)
}
}
buffer.WriteString(") */")
return buffer.String()
}
func restore2StorageHint(tiflashTables, tikvTables []hintTableInfo) string {
buffer := bytes.NewBufferString("/*+ ")
buffer.WriteString(strings.ToUpper(HintReadFromStorage))
buffer.WriteString("(")
if len(tiflashTables) > 0 {
buffer.WriteString("tiflash[")
buffer.WriteString(restore2TableHint(tiflashTables...))
buffer.WriteString("]")
if len(tikvTables) > 0 {
buffer.WriteString(", ")
}
}
if len(tikvTables) > 0 {
buffer.WriteString("tikv[")
buffer.WriteString(restore2TableHint(tikvTables...))
buffer.WriteString("]")
}
buffer.WriteString(") */")
return buffer.String()
}
func extractUnmatchedTables(hintTables []hintTableInfo) []string {
var tableNames []string
for _, table := range hintTables {
if !table.matched {
tableNames = append(tableNames, table.tblName.O)
}
}
return tableNames
}
// clauseCode indicates in which clause the column is currently.
type clauseCode int
const (
unknowClause clauseCode = iota
fieldList
havingClause
onClause
orderByClause
whereClause
groupByClause
showStatement
globalOrderByClause
expressionClause
windowOrderByClause
partitionByClause
)
var clauseMsg = map[clauseCode]string{
unknowClause: "",
fieldList: "field list",
havingClause: "having clause",
onClause: "on clause",
orderByClause: "order clause",
whereClause: "where clause",
groupByClause: "group statement",
showStatement: "show statement",
globalOrderByClause: "global ORDER clause",
expressionClause: "expression",
windowOrderByClause: "window order by",
partitionByClause: "window partition by",
}
type capFlagType = uint64
const (
_ capFlagType = iota
// canExpandAST indicates whether the origin AST can be expanded during plan
// building. ONLY used for `CreateViewStmt` now.
canExpandAST
// renameView indicates a view is being renamed, so we cannot use the origin
// definition of that view.
renameView
)
// PlanBuilder builds Plan from an ast.Node.
// It just builds the ast node straightforwardly.
type PlanBuilder struct {
ctx sessionctx.Context
is infoschema.InfoSchema
outerSchemas []*expression.Schema
outerNames [][]*types.FieldName
// colMapper stores the column that must be pre-resolved.
colMapper map[*ast.ColumnNameExpr]int
// visitInfo is used for privilege check.
visitInfo []visitInfo
tableHintInfo []tableHintInfo
// optFlag indicates the flags of the optimizer rules.
optFlag uint64
// capFlag indicates the capability flags.
capFlag capFlagType
curClause clauseCode
// rewriterPool stores the expressionRewriter we have created to reuse it if it has been released.
// rewriterCounter counts how many rewriter is being used.
rewriterPool []*expressionRewriter
rewriterCounter int
windowSpecs map[string]*ast.WindowSpec
inUpdateStmt bool
inDeleteStmt bool
// inStraightJoin represents whether the current "SELECT" statement has
// "STRAIGHT_JOIN" option.
inStraightJoin bool
// handleHelper records the handle column position for tables. Delete/Update/SelectLock/UnionScan may need this information.
// It collects the information by the following procedure:
// Since we build the plan tree from bottom to top, we maintain a stack to record the current handle information.
// If it's a dataSource/tableDual node, we create a new map.
// If it's a aggregation, we pop the map and push a nil map since no handle information left.
// If it's a union, we pop all children's and push a nil map.
// If it's a join, we pop its children's out then merge them and push the new map to stack.
// If we meet a subquery, it's clearly that it's a independent problem so we just pop one map out when we finish building the subquery.
handleHelper *handleColHelper
hintProcessor *hint.BlockHintProcessor
// selectOffset is the offsets of current processing select stmts.
selectOffset []int
// SelectLock need this information to locate the lock on partitions.
partitionedTable []table.PartitionedTable
// buildingViewStack is used to check whether there is a recursive view.
buildingViewStack set.StringSet
// renamingViewName is the name of the view which is being renamed.
renamingViewName string
// evalDefaultExpr needs this information to find the corresponding column.
// It stores the OutputNames before buildProjection.
allNames [][]*types.FieldName
// isSampling indicates whether the query is sampling.
isSampling bool
// correlatedAggMapper stores columns for correlated aggregates which should be evaluated in outer query.
correlatedAggMapper map[*ast.AggregateFuncExpr]*expression.CorrelatedColumn
// cache ResultSetNodes and HandleHelperMap to avoid rebuilding.
cachedResultSetNodes map[*ast.Join]LogicalPlan
cachedHandleHelperMap map[*ast.Join]map[int64][]HandleCols
// isForUpdateRead should be true in either of the following situations
// 1. use `inside insert`, `update`, `delete` or `select for update` statement
// 2. isolation level is RC
isForUpdateRead bool
}
type handleColHelper struct {
id2HandleMapStack []map[int64][]HandleCols
stackTail int
}
func (hch *handleColHelper) appendColToLastMap(tblID int64, handleCols HandleCols) {
tailMap := hch.id2HandleMapStack[hch.stackTail-1]
tailMap[tblID] = append(tailMap[tblID], handleCols)
}
func (hch *handleColHelper) popMap() map[int64][]HandleCols {
ret := hch.id2HandleMapStack[hch.stackTail-1]
hch.stackTail--
hch.id2HandleMapStack = hch.id2HandleMapStack[:hch.stackTail]
return ret
}
func (hch *handleColHelper) pushMap(m map[int64][]HandleCols) {
hch.id2HandleMapStack = append(hch.id2HandleMapStack, m)
hch.stackTail++
}
func (hch *handleColHelper) mergeAndPush(m1, m2 map[int64][]HandleCols) {
newMap := make(map[int64][]HandleCols, mathutil.Max(len(m1), len(m2)))
for k, v := range m1 {
newMap[k] = make([]HandleCols, len(v))
copy(newMap[k], v)
}
for k, v := range m2 {
if _, ok := newMap[k]; ok {
newMap[k] = append(newMap[k], v...)
} else {
newMap[k] = make([]HandleCols, len(v))
copy(newMap[k], v)
}
}
hch.pushMap(newMap)
}
func (hch *handleColHelper) tailMap() map[int64][]HandleCols {
return hch.id2HandleMapStack[hch.stackTail-1]
}
// GetVisitInfo gets the visitInfo of the PlanBuilder.
func (b *PlanBuilder) GetVisitInfo() []visitInfo {
return b.visitInfo
}
// GetDBTableInfo gets the accessed dbs and tables info.
func (b *PlanBuilder) GetDBTableInfo() []stmtctx.TableEntry {
var tables []stmtctx.TableEntry
existsFunc := func(tbls []stmtctx.TableEntry, tbl *stmtctx.TableEntry) bool {
for _, t := range tbls {
if t == *tbl {
return true
}
}
return false
}
for _, v := range b.visitInfo {
tbl := &stmtctx.TableEntry{DB: v.db, Table: v.table}
if !existsFunc(tables, tbl) {
tables = append(tables, *tbl)
}
}
return tables
}
// GetOptFlag gets the optFlag of the PlanBuilder.
func (b *PlanBuilder) GetOptFlag() uint64 {
if b.isSampling {
// Disable logical optimization to avoid the optimizer
// push down/eliminate operands like Selection, Limit or Sort.
return 0
}
return b.optFlag
}
func (b *PlanBuilder) getSelectOffset() int {
if len(b.selectOffset) > 0 {
return b.selectOffset[len(b.selectOffset)-1]
}
return -1
}
func (b *PlanBuilder) pushSelectOffset(offset int) {
b.selectOffset = append(b.selectOffset, offset)
}
func (b *PlanBuilder) popSelectOffset() {
b.selectOffset = b.selectOffset[:len(b.selectOffset)-1]
}
// NewPlanBuilder creates a new PlanBuilder. Return the original PlannerSelectBlockAsName as well, callers decide if
// PlannerSelectBlockAsName should be restored after using this builder.
func NewPlanBuilder(sctx sessionctx.Context, is infoschema.InfoSchema, processor *hint.BlockHintProcessor) (*PlanBuilder, []ast.HintTable) {
savedBlockNames := sctx.GetSessionVars().PlannerSelectBlockAsName
if processor == nil {
sctx.GetSessionVars().PlannerSelectBlockAsName = nil
} else {
sctx.GetSessionVars().PlannerSelectBlockAsName = make([]ast.HintTable, processor.MaxSelectStmtOffset()+1)
}
return &PlanBuilder{
ctx: sctx,
is: is,
colMapper: make(map[*ast.ColumnNameExpr]int),
handleHelper: &handleColHelper{id2HandleMapStack: make([]map[int64][]HandleCols, 0)},
hintProcessor: processor,
correlatedAggMapper: make(map[*ast.AggregateFuncExpr]*expression.CorrelatedColumn),
cachedResultSetNodes: make(map[*ast.Join]LogicalPlan),
cachedHandleHelperMap: make(map[*ast.Join]map[int64][]HandleCols),
isForUpdateRead: sctx.GetSessionVars().IsPessimisticReadConsistency(),
}, savedBlockNames
}
// Build builds the ast node to a Plan.
func (b *PlanBuilder) Build(ctx context.Context, node ast.Node) (Plan, error) {
b.optFlag |= flagPrunColumns
switch x := node.(type) {
case *ast.AdminStmt:
return b.buildAdmin(ctx, x)
case *ast.DeallocateStmt:
return &Deallocate{Name: x.Name}, nil
case *ast.DeleteStmt:
return b.buildDelete(ctx, x)
case *ast.ExecuteStmt:
return b.buildExecute(ctx, x)
case *ast.ExplainStmt:
return b.buildExplain(ctx, x)
case *ast.ExplainForStmt:
return b.buildExplainFor(x)
case *ast.TraceStmt:
return b.buildTrace(x)
case *ast.InsertStmt:
return b.buildInsert(ctx, x)
case *ast.LoadDataStmt:
return b.buildLoadData(ctx, x)
case *ast.LoadStatsStmt:
return b.buildLoadStats(x), nil
case *ast.IndexAdviseStmt:
return b.buildIndexAdvise(x), nil
case *ast.PrepareStmt:
return b.buildPrepare(x), nil
case *ast.SelectStmt:
if x.SelectIntoOpt != nil {
return b.buildSelectInto(ctx, x)
}
return b.buildSelect(ctx, x)
case *ast.SetOprStmt:
return b.buildSetOpr(ctx, x)
case *ast.UpdateStmt:
return b.buildUpdate(ctx, x)
case *ast.ShowStmt:
return b.buildShow(ctx, x)
case *ast.DoStmt:
return b.buildDo(ctx, x)
case *ast.SetStmt:
return b.buildSet(ctx, x)
case *ast.SetConfigStmt:
return b.buildSetConfig(ctx, x)
case *ast.AnalyzeTableStmt:
return b.buildAnalyze(x)
case *ast.BinlogStmt, *ast.FlushStmt, *ast.UseStmt, *ast.BRIEStmt,
*ast.BeginStmt, *ast.CommitStmt, *ast.RollbackStmt, *ast.CreateUserStmt, *ast.SetPwdStmt, *ast.AlterInstanceStmt,
*ast.GrantStmt, *ast.DropUserStmt, *ast.AlterUserStmt, *ast.RevokeStmt, *ast.KillStmt, *ast.DropStatsStmt,
*ast.GrantRoleStmt, *ast.RevokeRoleStmt, *ast.SetRoleStmt, *ast.SetDefaultRoleStmt, *ast.ShutdownStmt:
return b.buildSimple(node.(ast.StmtNode))
case ast.DDLNode:
return b.buildDDL(ctx, x)
case *ast.CreateBindingStmt:
return b.buildCreateBindPlan(x)
case *ast.DropBindingStmt:
return b.buildDropBindPlan(x)
case *ast.ChangeStmt:
return b.buildChange(x)
case *ast.SplitRegionStmt:
return b.buildSplitRegion(x)
}
return nil, ErrUnsupportedType.GenWithStack("Unsupported type %T", node)
}
func (b *PlanBuilder) buildSetConfig(ctx context.Context, v *ast.SetConfigStmt) (Plan, error) {
privErr := ErrSpecificAccessDenied.GenWithStackByArgs("CONFIG")
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.ConfigPriv, "", "", "", privErr)
mockTablePlan := LogicalTableDual{}.Init(b.ctx, b.getSelectOffset())
expr, _, err := b.rewrite(ctx, v.Value, mockTablePlan, nil, true)
return &SetConfig{Name: v.Name, Type: v.Type, Instance: v.Instance, Value: expr}, err
}
func (b *PlanBuilder) buildChange(v *ast.ChangeStmt) (Plan, error) {
exe := &Change{
ChangeStmt: v,
}
return exe, nil
}
func (b *PlanBuilder) buildExecute(ctx context.Context, v *ast.ExecuteStmt) (Plan, error) {
vars := make([]expression.Expression, 0, len(v.UsingVars))
for _, expr := range v.UsingVars {
newExpr, _, err := b.rewrite(ctx, expr, nil, nil, true)
if err != nil {
return nil, err
}
vars = append(vars, newExpr)
}
exe := &Execute{Name: v.Name, UsingVars: vars, ExecID: v.ExecID}
if v.BinaryArgs != nil {
exe.PrepareParams = v.BinaryArgs.([]types.Datum)
}
return exe, nil
}
func (b *PlanBuilder) buildDo(ctx context.Context, v *ast.DoStmt) (Plan, error) {
var p LogicalPlan
dual := LogicalTableDual{RowCount: 1}.Init(b.ctx, b.getSelectOffset())
dual.SetSchema(expression.NewSchema())
p = dual
proj := LogicalProjection{Exprs: make([]expression.Expression, 0, len(v.Exprs))}.Init(b.ctx, b.getSelectOffset())
proj.names = make([]*types.FieldName, len(v.Exprs))
schema := expression.NewSchema(make([]*expression.Column, 0, len(v.Exprs))...)
for _, astExpr := range v.Exprs {
expr, np, err := b.rewrite(ctx, astExpr, p, nil, true)
if err != nil {
return nil, err
}
p = np
proj.Exprs = append(proj.Exprs, expr)
schema.Append(&expression.Column{
UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
RetType: expr.GetType(),
})
}
proj.SetChildren(p)
proj.self = proj
proj.SetSchema(schema)
proj.CalculateNoDelay = true
return proj, nil
}
func (b *PlanBuilder) buildSet(ctx context.Context, v *ast.SetStmt) (Plan, error) {
p := &Set{}
for _, vars := range v.Variables {
if vars.IsGlobal {
err := ErrSpecificAccessDenied.GenWithStackByArgs("SUPER")
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.SuperPriv, "", "", "", err)
}
assign := &expression.VarAssignment{
Name: vars.Name,
IsGlobal: vars.IsGlobal,
IsSystem: vars.IsSystem,
}
if _, ok := vars.Value.(*ast.DefaultExpr); !ok {
if cn, ok2 := vars.Value.(*ast.ColumnNameExpr); ok2 && cn.Name.Table.L == "" {
// Convert column name expression to string value expression.
char, col := b.ctx.GetSessionVars().GetCharsetInfo()
vars.Value = ast.NewValueExpr(cn.Name.Name.O, char, col)
}
mockTablePlan := LogicalTableDual{}.Init(b.ctx, b.getSelectOffset())
var err error
assign.Expr, _, err = b.rewrite(ctx, vars.Value, mockTablePlan, nil, true)
if err != nil {
return nil, err
}
} else {
assign.IsDefault = true
}
if vars.ExtendValue != nil {
assign.ExtendValue = &expression.Constant{
Value: vars.ExtendValue.(*driver.ValueExpr).Datum,
RetType: &vars.ExtendValue.(*driver.ValueExpr).Type,
}
}
p.VarAssigns = append(p.VarAssigns, assign)
}
return p, nil
}
func (b *PlanBuilder) buildDropBindPlan(v *ast.DropBindingStmt) (Plan, error) {
p := &SQLBindPlan{
SQLBindOp: OpSQLBindDrop,
NormdOrigSQL: parser.Normalize(utilparser.RestoreWithDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB)),
IsGlobal: v.GlobalScope,
Db: utilparser.GetDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB),
}
if v.HintedNode != nil {
p.BindSQL = utilparser.RestoreWithDefaultDB(v.HintedNode, b.ctx.GetSessionVars().CurrentDB)
}
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.SuperPriv, "", "", "", nil)
return p, nil
}
func checkHintedSQL(sql, charset, collation, db string) error {
p := parser.New()
hintsSet, _, warns, err := hint.ParseHintsSet(p, sql, charset, collation, db)
if err != nil {
return err
}
hintsStr, err := hintsSet.Restore()
if err != nil {
return err
}
// For `create global binding for select * from t using select * from t`, we allow it though hintsStr is empty.
// For `create global binding for select * from t using select /*+ non_exist_hint() */ * from t`,
// the hint is totally invalid, we escalate warning to error.
if hintsStr == "" && len(warns) > 0 {
return warns[0]
}
return nil
}
func (b *PlanBuilder) buildCreateBindPlan(v *ast.CreateBindingStmt) (Plan, error) {
charSet, collation := b.ctx.GetSessionVars().GetCharsetInfo()
// Because we use HintedNode.Restore instead of HintedNode.Text, so we need do some check here
// For example, if HintedNode.Text is `select /*+ non_exist_hint() */ * from t` and the current DB is `test`,
// the HintedNode.Restore will be `select * from test . t`.
// In other words, illegal hints will be deleted during restore. We can't check hinted SQL after restore.
// So we need check here.
if err := checkHintedSQL(v.HintedNode.Text(), charSet, collation, b.ctx.GetSessionVars().CurrentDB); err != nil {
return nil, err
}
p := &SQLBindPlan{
SQLBindOp: OpSQLBindCreate,
NormdOrigSQL: parser.Normalize(utilparser.RestoreWithDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB)),
BindSQL: utilparser.RestoreWithDefaultDB(v.HintedNode, b.ctx.GetSessionVars().CurrentDB),
IsGlobal: v.GlobalScope,
BindStmt: v.HintedNode,
Db: utilparser.GetDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB),
Charset: charSet,
Collation: collation,
}
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.SuperPriv, "", "", "", nil)
return p, nil
}
// detectSelectAgg detects an aggregate function or GROUP BY clause.
func (b *PlanBuilder) detectSelectAgg(sel *ast.SelectStmt) bool {
if sel.GroupBy != nil {
return true
}
for _, f := range sel.Fields.Fields {
if f.WildCard != nil {
continue
}
if ast.HasAggFlag(f.Expr) {
return true
}
}
if sel.Having != nil {
if ast.HasAggFlag(sel.Having.Expr) {
return true
}
}
if sel.OrderBy != nil {
for _, item := range sel.OrderBy.Items {
if ast.HasAggFlag(item.Expr) {
return true
}
}
}
return false
}
func (b *PlanBuilder) detectSelectWindow(sel *ast.SelectStmt) bool {
for _, f := range sel.Fields.Fields {
if ast.HasWindowFlag(f.Expr) {
return true
}
}
if sel.OrderBy != nil {
for _, item := range sel.OrderBy.Items {
if ast.HasWindowFlag(item.Expr) {
return true
}
}
}
return false
}
func getPathByIndexName(paths []*util.AccessPath, idxName model.CIStr, tblInfo *model.TableInfo) *util.AccessPath {
var tablePath *util.AccessPath
for _, path := range paths {
if path.IsTablePath() {
tablePath = path
continue
}
if path.Index.Name.L == idxName.L {
return path
}
}
if isPrimaryIndex(idxName) && (tblInfo.PKIsHandle || tblInfo.IsCommonHandle) {
return tablePath
}
return nil
}
func isPrimaryIndex(indexName model.CIStr) bool {
return indexName.L == "primary"
}
func genTiFlashPath(tblInfo *model.TableInfo, isGlobalRead bool) *util.AccessPath {
tiFlashPath := &util.AccessPath{StoreType: kv.TiFlash, IsTiFlashGlobalRead: isGlobalRead}
fillContentForTablePath(tiFlashPath, tblInfo)
return tiFlashPath
}
func fillContentForTablePath(tablePath *util.AccessPath, tblInfo *model.TableInfo) {
if tblInfo.IsCommonHandle {
tablePath.IsCommonHandlePath = true
for _, index := range tblInfo.Indices {
if index.Primary {
tablePath.Index = index
break
}
}
} else {
tablePath.IsIntHandlePath = true
}
}
// isForUpdateReadSelectLock checks if the lock type need to use forUpdateRead
func isForUpdateReadSelectLock(lock *ast.SelectLockInfo) bool {
if lock == nil {
return false
}
return lock.LockType == ast.SelectLockForUpdate ||
lock.LockType == ast.SelectLockForUpdateNoWait ||
lock.LockType == ast.SelectLockForUpdateWaitN
}
// getLatestIndexInfo gets the index info of latest schema version from given table id,
// it returns nil if the schema version is not changed
func getLatestIndexInfo(ctx sessionctx.Context, id int64, startVer int64) (map[int64]*model.IndexInfo, bool, error) {
dom := domain.GetDomain(ctx)
if dom == nil {
return nil, false, errors.New("domain not found for ctx")
}
is := dom.InfoSchema()
if is.SchemaMetaVersion() == startVer {
return nil, false, nil
}
latestIndexes := make(map[int64]*model.IndexInfo)
latestTbl, exist := is.TableByID(id)
if exist {
latestTblInfo := latestTbl.Meta()
for _, index := range latestTblInfo.Indices {
latestIndexes[index.ID] = index
}
}
return latestIndexes, true, nil
}
func getPossibleAccessPaths(ctx sessionctx.Context, tableHints *tableHintInfo, indexHints []*ast.IndexHint, tbl table.Table, dbName, tblName model.CIStr, check bool, startVer int64) ([]*util.AccessPath, error) {
tblInfo := tbl.Meta()
publicPaths := make([]*util.AccessPath, 0, len(tblInfo.Indices)+2)
tp := kv.TiKV
if tbl.Type().IsClusterTable() {
tp = kv.TiDB
}
tablePath := &util.AccessPath{StoreType: tp}
fillContentForTablePath(tablePath, tblInfo)
publicPaths = append(publicPaths, tablePath)
if tblInfo.TiFlashReplica != nil && tblInfo.TiFlashReplica.Available {
publicPaths = append(publicPaths, genTiFlashPath(tblInfo, false))
publicPaths = append(publicPaths, genTiFlashPath(tblInfo, true))
}
optimizerUseInvisibleIndexes := ctx.GetSessionVars().OptimizerUseInvisibleIndexes
check = check && ctx.GetSessionVars().ConnectionID > 0
var latestIndexes map[int64]*model.IndexInfo
var err error
for _, index := range tblInfo.Indices {
if index.State == model.StatePublic {
// Filter out invisible index, because they are not visible for optimizer
if !optimizerUseInvisibleIndexes && index.Invisible {
continue
}
if tblInfo.IsCommonHandle && index.Primary {
continue
}
if check && latestIndexes == nil {
latestIndexes, check, err = getLatestIndexInfo(ctx, tblInfo.ID, 0)
if err != nil {
return nil, err
}
}
if check {
if latestIndex, ok := latestIndexes[index.ID]; !ok || latestIndex.State != model.StatePublic {
continue
}
}
publicPaths = append(publicPaths, &util.AccessPath{Index: index})
}
}
hasScanHint, hasUseOrForce := false, false
available := make([]*util.AccessPath, 0, len(publicPaths))
ignored := make([]*util.AccessPath, 0, len(publicPaths))
// Extract comment-style index hint like /*+ INDEX(t, idx1, idx2) */.
indexHintsLen := len(indexHints)
if tableHints != nil {
for i, hint := range tableHints.indexHintList {
if hint.dbName.L == dbName.L && hint.tblName.L == tblName.L {
indexHints = append(indexHints, hint.indexHint)
tableHints.indexHintList[i].matched = true
}
}
}
_, isolationReadEnginesHasTiKV := ctx.GetSessionVars().GetIsolationReadEngines()[kv.TiKV]
for i, hint := range indexHints {
if hint.HintScope != ast.HintForScan {
continue
}
hasScanHint = true
if !isolationReadEnginesHasTiKV {
if hint.IndexNames != nil {