-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathplanbuilder.go
5493 lines (5143 loc) · 212 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"context"
"encoding/binary"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/br/pkg/storage"
"github.com/pingcap/tidb/pkg/bindinfo"
"github.com/pingcap/tidb/pkg/bindinfo/norm"
"github.com/pingcap/tidb/pkg/config"
"github.com/pingcap/tidb/pkg/domain"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/infoschema"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/auth"
"github.com/pingcap/tidb/pkg/parser/charset"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/parser/opcode"
"github.com/pingcap/tidb/pkg/parser/terror"
"github.com/pingcap/tidb/pkg/planner/core/base"
"github.com/pingcap/tidb/pkg/planner/property"
"github.com/pingcap/tidb/pkg/planner/util"
"github.com/pingcap/tidb/pkg/privilege"
"github.com/pingcap/tidb/pkg/sessionctx"
"github.com/pingcap/tidb/pkg/sessionctx/stmtctx"
"github.com/pingcap/tidb/pkg/sessionctx/variable"
"github.com/pingcap/tidb/pkg/sessiontxn/staleread"
"github.com/pingcap/tidb/pkg/statistics"
"github.com/pingcap/tidb/pkg/table"
"github.com/pingcap/tidb/pkg/table/tables"
"github.com/pingcap/tidb/pkg/table/temptable"
"github.com/pingcap/tidb/pkg/types"
driver "github.com/pingcap/tidb/pkg/types/parser_driver"
util2 "github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/dbterror"
"github.com/pingcap/tidb/pkg/util/dbterror/exeerrors"
"github.com/pingcap/tidb/pkg/util/dbterror/plannererrors"
"github.com/pingcap/tidb/pkg/util/execdetails"
"github.com/pingcap/tidb/pkg/util/hint"
"github.com/pingcap/tidb/pkg/util/logutil"
utilparser "github.com/pingcap/tidb/pkg/util/parser"
"github.com/pingcap/tidb/pkg/util/ranger"
"github.com/pingcap/tidb/pkg/util/sem"
"github.com/pingcap/tidb/pkg/util/set"
"github.com/pingcap/tidb/pkg/util/sqlexec"
"github.com/pingcap/tidb/pkg/util/stmtsummary"
"github.com/tikv/client-go/v2/oracle"
"go.uber.org/zap"
)
type visitInfo struct {
privilege mysql.PrivilegeType
db string
table string
column string
err error
alterWritable bool
// if multiple privileges is provided, user should
// have at least one privilege to pass the check.
dynamicPrivs []string
dynamicWithGrant bool
}
func (v *visitInfo) Equals(other *visitInfo) bool {
return v.privilege == other.privilege &&
v.db == other.db &&
v.table == other.table &&
v.column == other.column &&
v.err == other.err &&
v.alterWritable == other.alterWritable &&
reflect.DeepEqual(v.dynamicPrivs, other.dynamicPrivs) &&
v.dynamicWithGrant == other.dynamicWithGrant
}
// 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
)
type cteInfo struct {
def *ast.CommonTableExpression
// nonRecursive is used to decide if a CTE is visible. If a CTE start with `WITH RECURSIVE`, then nonRecursive is false,
// so it is visible in its definition.
nonRecursive bool
// useRecursive is used to record if a subSelect in CTE's definition refer to itself. This help us to identify the seed part and recursive part.
useRecursive bool
isBuilding bool
// isDistinct indicates if the union between seed part and recursive part is distinct or not.
isDistinct bool
// seedLP is the seed part's logical plan.
seedLP base.LogicalPlan
// recurLP is the recursive part's logical plan.
recurLP base.LogicalPlan
// storageID for this CTE.
storageID int
// optFlag is the optFlag for the whole CTE.
optFlag uint64
// enterSubquery and recursiveRef are used to check "recursive table must be referenced only once, and not in any subquery".
enterSubquery bool
recursiveRef bool
limitLP base.LogicalPlan
// seedStat is shared between logicalCTE and logicalCTETable.
seedStat *property.StatsInfo
// The LogicalCTEs that reference the same table should share the same CteClass.
cteClass *CTEClass
// isInline will determine whether it can be inlined when **CTE is used**
isInline bool
// forceInlineByHintOrVar will be true when CTE is hint by merge() or session variable "tidb_opt_force_inline_cte=true"
forceInlineByHintOrVar bool
// If CTE contain aggregation or window function in query (Indirect references to other cte containing agg or window in the query are also counted.)
containAggOrWindow bool
// Compute in preprocess phase. Record how many consumers the current CTE has
consumerCount int
}
type subQueryCtx = uint64
const (
notHandlingSubquery subQueryCtx = iota
handlingExistsSubquery
handlingCompareSubquery
handlingInSubquery
handlingScalarSubquery
)
// PlanBuilder builds Plan from an ast.Node.
// It just builds the ast node straightforwardly.
type PlanBuilder struct {
ctx base.PlanContext
is infoschema.InfoSchema
outerSchemas []*expression.Schema
outerNames [][]*types.FieldName
outerCTEs []*cteInfo
// outerBlockExpand register current Expand OP for rollup syntax in every select query block.
outerBlockExpand []*LogicalExpand
currentBlockExpand *LogicalExpand
// colMapper stores the column that must be pre-resolved.
colMapper map[*ast.ColumnNameExpr]int
// visitInfo is used for privilege check.
visitInfo []visitInfo
tableHintInfo []*hint.PlanHints
// 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.QBHintHandler
// qbOffset is the offsets of current processing select stmts.
qbOffset []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
// isCreateView indicates whether the query is create view.
isCreateView bool
// 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
// 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
allocIDForCTEStorage int
buildingRecursivePartForCTE bool
buildingCTE bool
//Check whether the current building query is a CTE
isCTE bool
// subQueryCtx and subQueryHintFlags are for handling subquery related hints.
// Note: "subquery" here only contains subqueries that are handled by the expression rewriter, i.e., [NOT] IN,
// [NOT] EXISTS, compare + ANY/ALL and scalar subquery. Derived table doesn't belong to this.
// We need these fields to passing information because:
// 1. We know what kind of subquery is this only when we're in the outer query block.
// 2. We know if there are such hints only when we're in the subquery block.
// 3. These hints are only applicable when they are in a subquery block. And for some hints, they are only
// applicable for some kinds of subquery.
// 4. If a hint is set and is applicable, the corresponding logic is handled in the outer query block.
// Example SQL: select * from t where exists(select /*+ SEMI_JOIN_REWRITE() */ 1 from t1 where t.a=t1.a)
// subQueryCtx indicates if we are handling a subquery, and what kind of subquery is it.
subQueryCtx subQueryCtx
// subQueryHintFlags stores subquery related hints that are set and applicable in the query block.
// It's for returning information to buildSubquery().
subQueryHintFlags uint64 // TODO: move this field to hint.PlanHints
// disableSubQueryPreprocessing indicates whether to pre-process uncorrelated sub-queries in rewriting stage.
disableSubQueryPreprocessing bool
// allowBuildCastArray indicates whether allow cast(... as ... array).
allowBuildCastArray bool
}
type handleColHelper struct {
id2HandleMapStack []map[int64][]util.HandleCols
stackTail int
}
func (hch *handleColHelper) resetForReuse() {
*hch = handleColHelper{
id2HandleMapStack: hch.id2HandleMapStack[:0],
}
}
func (hch *handleColHelper) popMap() map[int64][]util.HandleCols {
ret := hch.id2HandleMapStack[hch.stackTail-1]
hch.stackTail--
hch.id2HandleMapStack = hch.id2HandleMapStack[:hch.stackTail]
return ret
}
func (hch *handleColHelper) pushMap(m map[int64][]util.HandleCols) {
hch.id2HandleMapStack = append(hch.id2HandleMapStack, m)
hch.stackTail++
}
func (hch *handleColHelper) mergeAndPush(m1, m2 map[int64][]util.HandleCols) {
newMap := make(map[int64][]util.HandleCols, max(len(m1), len(m2)))
for k, v := range m1 {
newMap[k] = make([]util.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([]util.HandleCols, len(v))
copy(newMap[k], v)
}
}
hch.pushMap(newMap)
}
func (hch *handleColHelper) tailMap() map[int64][]util.HandleCols {
return hch.id2HandleMapStack[hch.stackTail-1]
}
// GetVisitInfo gets the visitInfo of the PlanBuilder.
func (b *PlanBuilder) GetVisitInfo() []visitInfo {
return b.visitInfo
}
// GetIsForUpdateRead gets if the PlanBuilder use forUpdateRead
func (b *PlanBuilder) GetIsForUpdateRead() bool {
return b.isForUpdateRead
}
// GetDBTableInfo gets the accessed dbs and tables info.
func GetDBTableInfo(visitInfo []visitInfo) []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 visitInfo {
if v.db == "" && v.table == "" {
// when v.db == "" and v.table == "", it means this visitInfo is for dynamic privilege,
// so it is not related to any database or table.
continue
}
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.qbOffset) > 0 {
return b.qbOffset[len(b.qbOffset)-1]
}
return -1
}
func (b *PlanBuilder) pushSelectOffset(offset int) {
b.qbOffset = append(b.qbOffset, offset)
}
func (b *PlanBuilder) popSelectOffset() {
b.qbOffset = b.qbOffset[:len(b.qbOffset)-1]
}
// PlanBuilderOpt is used to adjust the plan builder.
type PlanBuilderOpt interface {
Apply(builder *PlanBuilder)
}
// PlanBuilderOptNoExecution means the plan builder should not run any executor during Build().
type PlanBuilderOptNoExecution struct{}
// Apply implements the interface PlanBuilderOpt.
func (PlanBuilderOptNoExecution) Apply(builder *PlanBuilder) {
builder.disableSubQueryPreprocessing = true
}
// PlanBuilderOptAllowCastArray means the plan builder should allow build cast(... as ... array).
type PlanBuilderOptAllowCastArray struct{}
// Apply implements the interface PlanBuilderOpt.
func (PlanBuilderOptAllowCastArray) Apply(builder *PlanBuilder) {
builder.allowBuildCastArray = true
}
// NewPlanBuilder creates a new PlanBuilder.
func NewPlanBuilder(opts ...PlanBuilderOpt) *PlanBuilder {
builder := &PlanBuilder{
outerCTEs: make([]*cteInfo, 0),
colMapper: make(map[*ast.ColumnNameExpr]int),
handleHelper: &handleColHelper{id2HandleMapStack: make([]map[int64][]util.HandleCols, 0)},
correlatedAggMapper: make(map[*ast.AggregateFuncExpr]*expression.CorrelatedColumn),
}
for _, opt := range opts {
opt.Apply(builder)
}
return builder
}
// Init initialize a PlanBuilder.
// Return the original PlannerSelectBlockAsName as well, callers decide if
// PlannerSelectBlockAsName should be restored after using this builder.
// This is The comman code pattern to use it:
// NewPlanBuilder().Init(sctx, is, processor)
func (b *PlanBuilder) Init(sctx base.PlanContext, is infoschema.InfoSchema, processor *hint.QBHintHandler) (*PlanBuilder, []ast.HintTable) {
savedBlockNames := sctx.GetSessionVars().PlannerSelectBlockAsName.Load()
if processor == nil {
sctx.GetSessionVars().PlannerSelectBlockAsName.Store(&[]ast.HintTable{})
} else {
newPlannerSelectBlockAsName := make([]ast.HintTable, processor.MaxSelectStmtOffset()+1)
sctx.GetSessionVars().PlannerSelectBlockAsName.Store(&newPlannerSelectBlockAsName)
}
b.ctx = sctx
b.is = is
b.hintProcessor = processor
b.isForUpdateRead = sctx.GetSessionVars().IsPessimisticReadConsistency()
if savedBlockNames == nil {
return b, nil
}
return b, *savedBlockNames
}
// ResetForReuse reset the plan builder, put it into pool for reuse.
// After reset for reuse, the object should be equal to a object returned by NewPlanBuilder().
func (b *PlanBuilder) ResetForReuse() *PlanBuilder {
// Save some fields for reuse.
saveOuterCTEs := b.outerCTEs[:0]
saveColMapper := b.colMapper
for k := range saveColMapper {
delete(saveColMapper, k)
}
saveHandleHelper := b.handleHelper
saveHandleHelper.resetForReuse()
saveCorrelateAggMapper := b.correlatedAggMapper
for k := range saveCorrelateAggMapper {
delete(saveCorrelateAggMapper, k)
}
// Reset ALL the fields.
*b = PlanBuilder{}
// Reuse part of the fields.
// It's a bit conservative but easier to get right.
b.outerCTEs = saveOuterCTEs
b.colMapper = saveColMapper
b.handleHelper = saveHandleHelper
b.correlatedAggMapper = saveCorrelateAggMapper
// Add more fields if they are safe to be reused.
return b
}
// Build builds the ast node to a Plan.
func (b *PlanBuilder) Build(ctx context.Context, node ast.Node) (base.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.ImportIntoStmt:
return b.buildImportInto(ctx, x)
case *ast.LoadDataStmt:
return b.buildLoadData(ctx, x)
case *ast.LoadStatsStmt:
return b.buildLoadStats(x), nil
case *ast.LockStatsStmt:
return b.buildLockStats(x), nil
case *ast.UnlockStatsStmt:
return b.buildUnlockStats(x), nil
case *ast.IndexAdviseStmt:
return b.buildIndexAdvise(x), nil
case *ast.PlanReplayerStmt:
return b.buildPlanReplayer(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.SavepointStmt, *ast.ReleaseSavepointStmt, *ast.RollbackStmt, *ast.CreateUserStmt, *ast.SetPwdStmt, *ast.AlterInstanceStmt,
*ast.GrantStmt, *ast.DropUserStmt, *ast.AlterUserStmt, *ast.AlterRangeStmt, *ast.RevokeStmt, *ast.KillStmt, *ast.DropStatsStmt,
*ast.GrantRoleStmt, *ast.RevokeRoleStmt, *ast.SetRoleStmt, *ast.SetDefaultRoleStmt, *ast.ShutdownStmt,
*ast.RenameUserStmt, *ast.NonTransactionalDMLStmt, *ast.SetSessionStatesStmt, *ast.SetResourceGroupStmt,
*ast.ImportIntoActionStmt, *ast.CalibrateResourceStmt, *ast.AddQueryWatchStmt, *ast.DropQueryWatchStmt:
return b.buildSimple(ctx, 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.SetBindingStmt:
return b.buildSetBindingStatusPlan(x)
case *ast.ChangeStmt:
return b.buildChange(x)
case *ast.SplitRegionStmt:
return b.buildSplitRegion(x)
case *ast.CompactTableStmt:
return b.buildCompactTable(x)
}
return nil, plannererrors.ErrUnsupportedType.GenWithStack("Unsupported type %T", node)
}
func (b *PlanBuilder) buildSetConfig(ctx context.Context, v *ast.SetConfigStmt) (base.Plan, error) {
privErr := plannererrors.ErrSpecificAccessDenied.GenWithStackByArgs("CONFIG")
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.ConfigPriv, "", "", "", privErr)
mockTablePlan := LogicalTableDual{}.Init(b.ctx, b.getSelectOffset())
if _, ok := v.Value.(*ast.DefaultExpr); ok {
return nil, errors.New("Unknown DEFAULT for SET CONFIG")
}
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 (*PlanBuilder) buildChange(v *ast.ChangeStmt) (base.Plan, error) {
exe := &Change{
ChangeStmt: v,
}
return exe, nil
}
func (b *PlanBuilder) buildExecute(ctx context.Context, v *ast.ExecuteStmt) (base.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)
}
prepStmt, err := GetPreparedStmt(v, b.ctx.GetSessionVars())
if err != nil {
return nil, err
}
exe := &Execute{Name: v.Name, Params: vars, PrepStmt: prepStmt}
if v.BinaryArgs != nil {
exe.Params = v.BinaryArgs.([]expression.Expression)
}
return exe, nil
}
func (b *PlanBuilder) buildDo(ctx context.Context, v *ast.DoStmt) (base.Plan, error) {
var p base.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.SetOutputNames(make([]*types.FieldName, len(v.Exprs)))
schema := expression.NewSchema(make([]*expression.Column, 0, len(v.Exprs))...)
// Since do statement only contain expression list, and it may contain aggFunc, detecting to build the aggMapper firstly.
var (
err error
aggFuncs []*ast.AggregateFuncExpr
totalMap map[*ast.AggregateFuncExpr]int
)
hasAgg := b.detectAggInExprNode(v.Exprs)
needBuildAgg := hasAgg
if hasAgg {
if b.buildingRecursivePartForCTE {
return nil, plannererrors.ErrCTERecursiveForbidsAggregation.GenWithStackByArgs(b.genCTETableNameForError())
}
aggFuncs, totalMap = b.extractAggFuncsInExprs(v.Exprs)
if len(aggFuncs) == 0 {
needBuildAgg = false
}
}
if needBuildAgg {
var aggIndexMap map[int]int
p, aggIndexMap, err = b.buildAggregation(ctx, p, aggFuncs, nil, nil)
if err != nil {
return nil, err
}
for agg, idx := range totalMap {
totalMap[agg] = aggIndexMap[idx]
}
}
for _, astExpr := range v.Exprs {
expr, np, err := b.rewrite(ctx, astExpr, p, totalMap, 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(b.ctx.GetExprCtx().GetEvalCtx()),
})
}
proj.SetChildren(p)
proj.SetSelf(proj)
proj.SetSchema(schema)
proj.CalculateNoDelay = true
return proj, nil
}
func (b *PlanBuilder) buildSet(ctx context.Context, v *ast.SetStmt) (base.Plan, error) {
p := &Set{}
for _, vars := range v.Variables {
if vars.IsGlobal {
err := plannererrors.ErrSpecificAccessDenied.GenWithStackByArgs("SUPER or SYSTEM_VARIABLES_ADMIN")
b.visitInfo = appendDynamicVisitInfo(b.visitInfo, []string{"SYSTEM_VARIABLES_ADMIN"}, false, err)
}
if sem.IsEnabled() && sem.IsInvisibleSysVar(strings.ToLower(vars.Name)) {
err := plannererrors.ErrSpecificAccessDenied.GenWithStackByArgs("RESTRICTED_VARIABLES_ADMIN")
b.visitInfo = appendDynamicVisitInfo(b.visitInfo, []string{"RESTRICTED_VARIABLES_ADMIN"}, false, 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)
}
// The mocked plan need one output for the complex cases.
// See the following IF branch.
mockTablePlan := LogicalTableDual{RowCount: 1}.Init(b.ctx, b.getSelectOffset())
var err error
var possiblePlan base.LogicalPlan
assign.Expr, possiblePlan, err = b.rewrite(ctx, vars.Value, mockTablePlan, nil, true)
if err != nil {
return nil, err
}
// It's possible that the subquery of the SET_VAR is a complex one so we need to get the result by evaluating the plan.
if _, ok := possiblePlan.(*LogicalTableDual); !ok {
physicalPlan, _, err := DoOptimize(ctx, b.ctx, b.optFlag, possiblePlan)
if err != nil {
return nil, err
}
row, err := EvalSubqueryFirstRow(ctx, physicalPlan, b.is, b.ctx)
if err != nil {
return nil, err
}
constant := &expression.Constant{
Value: row[0],
RetType: assign.Expr.GetType(b.ctx.GetExprCtx().GetEvalCtx()),
}
assign.Expr = constant
}
} 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) (base.Plan, error) {
var p *SQLBindPlan
if v.OriginNode != nil {
normdOrigSQL, sqlDigestWithDB := norm.NormalizeStmtForBinding(v.OriginNode, norm.WithSpecifiedDB(b.ctx.GetSessionVars().CurrentDB))
p = &SQLBindPlan{
SQLBindOp: OpSQLBindDrop,
NormdOrigSQL: normdOrigSQL,
IsGlobal: v.GlobalScope,
Db: utilparser.GetDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB),
SQLDigest: sqlDigestWithDB,
}
if v.HintedNode != nil {
p.BindSQL = utilparser.RestoreWithDefaultDB(v.HintedNode, b.ctx.GetSessionVars().CurrentDB, v.HintedNode.Text())
}
} else {
p = &SQLBindPlan{
SQLBindOp: OpSQLBindDropByDigest,
IsGlobal: v.GlobalScope,
SQLDigest: v.SQLDigest,
}
}
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.SuperPriv, "", "", "", nil)
return p, nil
}
func (b *PlanBuilder) buildSetBindingStatusPlan(v *ast.SetBindingStmt) (base.Plan, error) {
var p *SQLBindPlan
if v.OriginNode != nil {
p = &SQLBindPlan{
SQLBindOp: OpSetBindingStatus,
NormdOrigSQL: parser.NormalizeForBinding(utilparser.RestoreWithDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB, v.OriginNode.Text()), false),
Db: utilparser.GetDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB),
}
} else if v.SQLDigest != "" {
p = &SQLBindPlan{
SQLBindOp: OpSetBindingStatusByDigest,
SQLDigest: v.SQLDigest,
}
} else {
return nil, errors.New("sql digest is empty")
}
switch v.BindingStatusType {
case ast.BindingStatusTypeEnabled:
p.NewStatus = bindinfo.Enabled
case ast.BindingStatusTypeDisabled:
p.NewStatus = bindinfo.Disabled
}
if v.HintedNode != nil {
p.BindSQL = utilparser.RestoreWithDefaultDB(v.HintedNode, b.ctx.GetSessionVars().CurrentDB, v.HintedNode.Text())
}
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 fetchRecordFromClusterStmtSummary(sctx base.PlanContext, planDigest string) ([]chunk.Row, error) {
ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnBindInfo)
exec := sctx.GetSQLExecutor()
fields := "stmt_type, schema_name, digest_text, sample_user, prepared, query_sample_text, charset, collation, plan_hint, plan_digest"
sql := fmt.Sprintf("select %s from information_schema.cluster_statements_summary where plan_digest = '%s' union distinct ", fields, planDigest) +
fmt.Sprintf("select %s from information_schema.cluster_statements_summary_history where plan_digest = '%s' ", fields, planDigest) +
"order by length(plan_digest) desc"
rs, err := exec.ExecuteInternal(ctx, sql)
if rs == nil {
return nil, errors.New("can't find any records for '" + planDigest + "' in statement summary")
}
if err != nil {
return nil, err
}
var rows []chunk.Row
defer terror.Call(rs.Close)
if rows, err = sqlexec.DrainRecordSet(ctx, rs, 8); err != nil {
return nil, err
}
return rows, nil
}
func (b *PlanBuilder) buildCreateBindPlanFromPlanDigest(v *ast.CreateBindingStmt) (base.Plan, error) {
if v.PlanDigest == "" {
return nil, errors.New("plan digest is empty")
}
rows, err := fetchRecordFromClusterStmtSummary(b.ctx, v.PlanDigest)
if err != nil {
return nil, err
}
bindableStmt := stmtsummary.GetBindableStmtFromCluster(rows)
if bindableStmt == nil {
return nil, errors.New("can't find any plans for '" + v.PlanDigest + "'")
}
parser4binding := parser.New()
originNode, err := parser4binding.ParseOneStmt(bindableStmt.Query, bindableStmt.Charset, bindableStmt.Collation)
if err != nil {
return nil, errors.Errorf("binding failed: %v", err)
}
if complete, reason := hint.CheckBindingFromHistoryComplete(originNode, bindableStmt.PlanHint); !complete {
b.ctx.GetSessionVars().StmtCtx.AppendWarning(errors.NewNoStackError(reason))
}
bindSQL := bindinfo.GenerateBindingSQL(originNode, bindableStmt.PlanHint, true, bindableStmt.Schema)
var hintNode ast.StmtNode
hintNode, err = parser4binding.ParseOneStmt(bindSQL, bindableStmt.Charset, bindableStmt.Collation)
if err != nil {
return nil, errors.Errorf("binding failed: %v", err)
}
restoredSQL := utilparser.RestoreWithDefaultDB(originNode, bindableStmt.Schema, bindableStmt.Query)
bindSQL = utilparser.RestoreWithDefaultDB(hintNode, bindableStmt.Schema, hintNode.Text())
db := utilparser.GetDefaultDB(originNode, bindableStmt.Schema)
normdOrigSQL, sqlDigestWithDB := parser.NormalizeDigestForBinding(restoredSQL)
p := &SQLBindPlan{
SQLBindOp: OpSQLBindCreate,
NormdOrigSQL: normdOrigSQL,
BindSQL: bindSQL,
IsGlobal: v.GlobalScope,
BindStmt: hintNode,
Db: db,
Charset: bindableStmt.Charset,
Collation: bindableStmt.Collation,
Source: bindinfo.History,
SQLDigest: sqlDigestWithDB.String(),
PlanDigest: v.PlanDigest,
}
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.SuperPriv, "", "", "", nil)
return p, nil
}
func (b *PlanBuilder) buildCreateBindPlan(v *ast.CreateBindingStmt) (base.Plan, error) {
if v.OriginNode == nil {
return b.buildCreateBindPlanFromPlanDigest(v)
}
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
}
restoredSQL := utilparser.RestoreWithDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB, v.OriginNode.Text())
bindSQL := utilparser.RestoreWithDefaultDB(v.HintedNode, b.ctx.GetSessionVars().CurrentDB, v.HintedNode.Text())
db := utilparser.GetDefaultDB(v.OriginNode, b.ctx.GetSessionVars().CurrentDB)
normdOrigSQL, sqlDigestWithDB := parser.NormalizeDigestForBinding(restoredSQL)
p := &SQLBindPlan{
SQLBindOp: OpSQLBindCreate,
NormdOrigSQL: normdOrigSQL,
BindSQL: bindSQL,
IsGlobal: v.GlobalScope,
BindStmt: v.HintedNode,
Db: db,
Charset: charSet,
Collation: collation,
Source: bindinfo.Manual,
SQLDigest: sqlDigestWithDB.String(),
}
b.visitInfo = appendVisitInfo(b.visitInfo, mysql.SuperPriv, "", "", "", nil)
return p, nil
}
// detectAggInExprNode detects an aggregate function in its exprs.
func (*PlanBuilder) detectAggInExprNode(exprs []ast.ExprNode) bool {
for _, expr := range exprs {
if ast.HasAggFlag(expr) {
return true
}
}
return false
}
// detectSelectAgg detects an aggregate function or GROUP BY clause.
func (*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 (*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 primaryIdxPath, indexPrefixPath *util.AccessPath
prefixMatches := 0
for _, path := range paths {
if path.StoreType == kv.TiFlash {
continue
}
if path.IsTablePath() {
primaryIdxPath = path
continue
}
if path.Index.Name.L == idxName.L {
return path
}
if strings.HasPrefix(path.Index.Name.L, idxName.L) {
indexPrefixPath = path
prefixMatches++
}
}
if isPrimaryIndex(idxName) && tblInfo.HasClusteredIndex() {
return primaryIdxPath
}
// Return only unique prefix matches
if prefixMatches == 1 {
return indexPrefixPath
}
return nil
}
func isPrimaryIndex(indexName model.CIStr) bool {
return indexName.L == "primary"
}
func genTiFlashPath(tblInfo *model.TableInfo) *util.AccessPath {
tiFlashPath := &util.AccessPath{StoreType: kv.TiFlash}
fillContentForTablePath(tiFlashPath, tblInfo)
return tiFlashPath
}