forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
4530 lines (4249 loc) · 144 KB
/
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 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 executor
import (
"bytes"
"context"
"sort"
"strconv"
"strings"
"sync"
"time"
"unsafe"
"github.com/cznic/mathutil"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/diagnosticspb"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/distsql"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/executor/aggfuncs"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/expression/aggregation"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/metrics"
plannercore "github.com/pingcap/tidb/planner/core"
plannerutil "github.com/pingcap/tidb/planner/util"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/table/temptable"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/admin"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/cteutil"
"github.com/pingcap/tidb/util/dbterror"
"github.com/pingcap/tidb/util/execdetails"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/rowcodec"
"github.com/pingcap/tidb/util/timeutil"
"github.com/pingcap/tipb/go-tipb"
"go.uber.org/zap"
)
var (
executorCounterMergeJoinExec = metrics.ExecutorCounter.WithLabelValues("MergeJoinExec")
executorCountHashJoinExec = metrics.ExecutorCounter.WithLabelValues("HashJoinExec")
executorCounterHashAggExec = metrics.ExecutorCounter.WithLabelValues("HashAggExec")
executorStreamAggExec = metrics.ExecutorCounter.WithLabelValues("StreamAggExec")
executorCounterSortExec = metrics.ExecutorCounter.WithLabelValues("SortExec")
executorCounterTopNExec = metrics.ExecutorCounter.WithLabelValues("TopNExec")
executorCounterNestedLoopApplyExec = metrics.ExecutorCounter.WithLabelValues("NestedLoopApplyExec")
executorCounterIndexLookUpJoin = metrics.ExecutorCounter.WithLabelValues("IndexLookUpJoin")
executorCounterIndexLookUpExecutor = metrics.ExecutorCounter.WithLabelValues("IndexLookUpExecutor")
executorCounterIndexMergeReaderExecutor = metrics.ExecutorCounter.WithLabelValues("IndexMergeReaderExecutor")
)
// executorBuilder builds an Executor from a Plan.
// The InfoSchema must not change during execution.
type executorBuilder struct {
ctx sessionctx.Context
is infoschema.InfoSchema
snapshotTS uint64 // The consistent snapshot timestamp for the executor to read data.
snapshotTSCached bool
err error // err is set when there is error happened during Executor building process.
hasLock bool
Ti *TelemetryInfo
// isStaleness means whether this statement use stale read.
isStaleness bool
txnScope string
}
// CTEStorages stores resTbl and iterInTbl for CTEExec.
// There will be a map[CTEStorageID]*CTEStorages in StmtCtx,
// which will store all CTEStorages to make all shared CTEs use same the CTEStorages.
type CTEStorages struct {
ResTbl cteutil.Storage
IterInTbl cteutil.Storage
}
func newExecutorBuilder(ctx sessionctx.Context, is infoschema.InfoSchema, ti *TelemetryInfo, snapshotTS uint64, isStaleness bool, txnScope string) *executorBuilder {
return &executorBuilder{
ctx: ctx,
is: is,
Ti: ti,
snapshotTS: snapshotTS,
isStaleness: isStaleness,
txnScope: txnScope,
}
}
// MockPhysicalPlan is used to return a specified executor in when build.
// It is mainly used for testing.
type MockPhysicalPlan interface {
plannercore.PhysicalPlan
GetExecutor() Executor
}
func (b *executorBuilder) build(p plannercore.Plan) Executor {
switch v := p.(type) {
case nil:
return nil
case *plannercore.Change:
return b.buildChange(v)
case *plannercore.CheckTable:
return b.buildCheckTable(v)
case *plannercore.RecoverIndex:
return b.buildRecoverIndex(v)
case *plannercore.CleanupIndex:
return b.buildCleanupIndex(v)
case *plannercore.CheckIndexRange:
return b.buildCheckIndexRange(v)
case *plannercore.ChecksumTable:
return b.buildChecksumTable(v)
case *plannercore.ReloadExprPushdownBlacklist:
return b.buildReloadExprPushdownBlacklist(v)
case *plannercore.ReloadOptRuleBlacklist:
return b.buildReloadOptRuleBlacklist(v)
case *plannercore.AdminPlugins:
return b.buildAdminPlugins(v)
case *plannercore.DDL:
return b.buildDDL(v)
case *plannercore.Deallocate:
return b.buildDeallocate(v)
case *plannercore.Delete:
return b.buildDelete(v)
case *plannercore.Execute:
return b.buildExecute(v)
case *plannercore.Trace:
return b.buildTrace(v)
case *plannercore.Explain:
return b.buildExplain(v)
case *plannercore.PointGetPlan:
return b.buildPointGet(v)
case *plannercore.BatchPointGetPlan:
return b.buildBatchPointGet(v)
case *plannercore.Insert:
return b.buildInsert(v)
case *plannercore.LoadData:
return b.buildLoadData(v)
case *plannercore.LoadStats:
return b.buildLoadStats(v)
case *plannercore.IndexAdvise:
return b.buildIndexAdvise(v)
case *plannercore.PlanRecreatorSingle:
return b.buildPlanRecreatorSingle(v)
case *plannercore.PhysicalLimit:
return b.buildLimit(v)
case *plannercore.Prepare:
return b.buildPrepare(v)
case *plannercore.PhysicalLock:
return b.buildSelectLock(v)
case *plannercore.CancelDDLJobs:
return b.buildCancelDDLJobs(v)
case *plannercore.ShowNextRowID:
return b.buildShowNextRowID(v)
case *plannercore.ShowDDL:
return b.buildShowDDL(v)
case *plannercore.PhysicalShowDDLJobs:
return b.buildShowDDLJobs(v)
case *plannercore.ShowDDLJobQueries:
return b.buildShowDDLJobQueries(v)
case *plannercore.ShowSlow:
return b.buildShowSlow(v)
case *plannercore.PhysicalShow:
return b.buildShow(v)
case *plannercore.Simple:
return b.buildSimple(v)
case *plannercore.PhysicalSimpleWrapper:
return b.buildSimple(&v.Inner)
case *plannercore.Set:
return b.buildSet(v)
case *plannercore.SetConfig:
return b.buildSetConfig(v)
case *plannercore.PhysicalSort:
return b.buildSort(v)
case *plannercore.PhysicalTopN:
return b.buildTopN(v)
case *plannercore.PhysicalUnionAll:
return b.buildUnionAll(v)
case *plannercore.Update:
return b.buildUpdate(v)
case *plannercore.PhysicalUnionScan:
return b.buildUnionScanExec(v)
case *plannercore.PhysicalHashJoin:
return b.buildHashJoin(v)
case *plannercore.PhysicalMergeJoin:
return b.buildMergeJoin(v)
case *plannercore.PhysicalIndexJoin:
return b.buildIndexLookUpJoin(v)
case *plannercore.PhysicalIndexMergeJoin:
return b.buildIndexLookUpMergeJoin(v)
case *plannercore.PhysicalIndexHashJoin:
return b.buildIndexNestedLoopHashJoin(v)
case *plannercore.PhysicalSelection:
return b.buildSelection(v)
case *plannercore.PhysicalHashAgg:
return b.buildHashAgg(v)
case *plannercore.PhysicalStreamAgg:
return b.buildStreamAgg(v)
case *plannercore.PhysicalProjection:
return b.buildProjection(v)
case *plannercore.PhysicalMemTable:
return b.buildMemTable(v)
case *plannercore.PhysicalTableDual:
return b.buildTableDual(v)
case *plannercore.PhysicalApply:
return b.buildApply(v)
case *plannercore.PhysicalMaxOneRow:
return b.buildMaxOneRow(v)
case *plannercore.Analyze:
return b.buildAnalyze(v)
case *plannercore.PhysicalTableReader:
return b.buildTableReader(v)
case *plannercore.PhysicalTableSample:
return b.buildTableSample(v)
case *plannercore.PhysicalIndexReader:
return b.buildIndexReader(v)
case *plannercore.PhysicalIndexLookUpReader:
return b.buildIndexLookUpReader(v)
case *plannercore.PhysicalWindow:
return b.buildWindow(v)
case *plannercore.PhysicalShuffle:
return b.buildShuffle(v)
case *plannercore.PhysicalShuffleReceiverStub:
return b.buildShuffleReceiverStub(v)
case *plannercore.SQLBindPlan:
return b.buildSQLBindExec(v)
case *plannercore.SplitRegion:
return b.buildSplitRegion(v)
case *plannercore.PhysicalIndexMergeReader:
return b.buildIndexMergeReader(v)
case *plannercore.SelectInto:
return b.buildSelectInto(v)
case *plannercore.AdminShowTelemetry:
return b.buildAdminShowTelemetry(v)
case *plannercore.AdminResetTelemetryID:
return b.buildAdminResetTelemetryID(v)
case *plannercore.PhysicalCTE:
return b.buildCTE(v)
case *plannercore.PhysicalCTETable:
return b.buildCTETableReader(v)
default:
if mp, ok := p.(MockPhysicalPlan); ok {
return mp.GetExecutor()
}
b.err = ErrUnknownPlan.GenWithStack("Unknown Plan %T", p)
return nil
}
}
func (b *executorBuilder) buildCancelDDLJobs(v *plannercore.CancelDDLJobs) Executor {
e := &CancelDDLJobsExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
jobIDs: v.JobIDs,
}
txn, err := e.ctx.Txn(true)
if err != nil {
b.err = err
return nil
}
e.errs, b.err = admin.CancelJobs(txn, e.jobIDs)
if b.err != nil {
return nil
}
return e
}
func (b *executorBuilder) buildChange(v *plannercore.Change) Executor {
return &ChangeExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
ChangeStmt: v.ChangeStmt,
}
}
func (b *executorBuilder) buildShowNextRowID(v *plannercore.ShowNextRowID) Executor {
e := &ShowNextRowIDExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
tblName: v.TableName,
}
return e
}
func (b *executorBuilder) buildShowDDL(v *plannercore.ShowDDL) Executor {
// We get DDLInfo here because for Executors that returns result set,
// next will be called after transaction has been committed.
// We need the transaction to get DDLInfo.
e := &ShowDDLExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
}
var err error
ownerManager := domain.GetDomain(e.ctx).DDL().OwnerManager()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
e.ddlOwnerID, err = ownerManager.GetOwnerID(ctx)
cancel()
if err != nil {
b.err = err
return nil
}
txn, err := e.ctx.Txn(true)
if err != nil {
b.err = err
return nil
}
ddlInfo, err := admin.GetDDLInfo(txn)
if err != nil {
b.err = err
return nil
}
e.ddlInfo = ddlInfo
e.selfID = ownerManager.ID()
return e
}
func (b *executorBuilder) buildShowDDLJobs(v *plannercore.PhysicalShowDDLJobs) Executor {
e := &ShowDDLJobsExec{
jobNumber: int(v.JobNumber),
is: b.is,
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
}
return e
}
func (b *executorBuilder) buildShowDDLJobQueries(v *plannercore.ShowDDLJobQueries) Executor {
e := &ShowDDLJobQueriesExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
jobIDs: v.JobIDs,
}
return e
}
func (b *executorBuilder) buildShowSlow(v *plannercore.ShowSlow) Executor {
e := &ShowSlowExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
ShowSlow: v.ShowSlow,
}
return e
}
// buildIndexLookUpChecker builds check information to IndexLookUpReader.
func buildIndexLookUpChecker(b *executorBuilder, p *plannercore.PhysicalIndexLookUpReader,
e *IndexLookUpExecutor) {
is := p.IndexPlans[0].(*plannercore.PhysicalIndexScan)
fullColLen := len(is.Index.Columns) + len(p.CommonHandleCols)
if !e.isCommonHandle() {
fullColLen += 1
}
e.dagPB.OutputOffsets = make([]uint32, fullColLen)
for i := 0; i < fullColLen; i++ {
e.dagPB.OutputOffsets[i] = uint32(i)
}
ts := p.TablePlans[0].(*plannercore.PhysicalTableScan)
e.handleIdx = ts.HandleIdx
e.ranges = ranger.FullRange()
tps := make([]*types.FieldType, 0, fullColLen)
for _, col := range is.Columns {
tps = append(tps, &col.FieldType)
}
if !e.isCommonHandle() {
tps = append(tps, types.NewFieldType(mysql.TypeLonglong))
}
e.checkIndexValue = &checkIndexValue{idxColTps: tps}
colNames := make([]string, 0, len(is.IdxCols))
for i := range is.IdxCols {
colNames = append(colNames, is.Columns[i].Name.L)
}
if cols, missingColOffset := table.FindColumns(e.table.Cols(), colNames, true); missingColOffset >= 0 {
b.err = plannercore.ErrUnknownColumn.GenWithStack("Unknown column %s", is.Columns[missingColOffset].Name.O)
} else {
e.idxTblCols = cols
}
}
func (b *executorBuilder) buildCheckTable(v *plannercore.CheckTable) Executor {
readerExecs := make([]*IndexLookUpExecutor, 0, len(v.IndexLookUpReaders))
for _, readerPlan := range v.IndexLookUpReaders {
readerExec, err := buildNoRangeIndexLookUpReader(b, readerPlan)
if err != nil {
b.err = errors.Trace(err)
return nil
}
buildIndexLookUpChecker(b, readerPlan, readerExec)
readerExecs = append(readerExecs, readerExec)
}
e := &CheckTableExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
dbName: v.DBName,
table: v.Table,
indexInfos: v.IndexInfos,
is: b.is,
srcs: readerExecs,
exitCh: make(chan struct{}),
retCh: make(chan error, len(readerExecs)),
checkIndex: v.CheckIndex,
}
return e
}
func buildIdxColsConcatHandleCols(tblInfo *model.TableInfo, indexInfo *model.IndexInfo) []*model.ColumnInfo {
handleLen := 1
var pkCols []*model.IndexColumn
if tblInfo.IsCommonHandle {
pkIdx := tables.FindPrimaryIndex(tblInfo)
pkCols = pkIdx.Columns
handleLen = len(pkIdx.Columns)
}
columns := make([]*model.ColumnInfo, 0, len(indexInfo.Columns)+handleLen)
for _, idxCol := range indexInfo.Columns {
columns = append(columns, tblInfo.Columns[idxCol.Offset])
}
if tblInfo.IsCommonHandle {
for _, c := range pkCols {
columns = append(columns, tblInfo.Columns[c.Offset])
}
return columns
}
handleOffset := len(columns)
handleColsInfo := &model.ColumnInfo{
ID: model.ExtraHandleID,
Name: model.ExtraHandleName,
Offset: handleOffset,
}
handleColsInfo.FieldType = *types.NewFieldType(mysql.TypeLonglong)
columns = append(columns, handleColsInfo)
return columns
}
func (b *executorBuilder) buildRecoverIndex(v *plannercore.RecoverIndex) Executor {
tblInfo := v.Table.TableInfo
t, err := b.is.TableByName(v.Table.Schema, tblInfo.Name)
if err != nil {
b.err = err
return nil
}
idxName := strings.ToLower(v.IndexName)
index := tables.GetWritableIndexByName(idxName, t)
if index == nil {
b.err = errors.Errorf("index `%v` is not found in table `%v`.", v.IndexName, v.Table.Name.O)
return nil
}
e := &RecoverIndexExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
columns: buildIdxColsConcatHandleCols(tblInfo, index.Meta()),
index: index,
table: t,
physicalID: t.Meta().ID,
}
sessCtx := e.ctx.GetSessionVars().StmtCtx
e.handleCols = buildHandleColsForExec(sessCtx, tblInfo, index.Meta(), e.columns)
return e
}
func buildHandleColsForExec(sctx *stmtctx.StatementContext, tblInfo *model.TableInfo,
idxInfo *model.IndexInfo, allColInfo []*model.ColumnInfo) plannercore.HandleCols {
if !tblInfo.IsCommonHandle {
extraColPos := len(allColInfo) - 1
intCol := &expression.Column{
Index: extraColPos,
RetType: types.NewFieldType(mysql.TypeLonglong),
}
return plannercore.NewIntHandleCols(intCol)
}
tblCols := make([]*expression.Column, len(tblInfo.Columns))
for i := 0; i < len(tblInfo.Columns); i++ {
c := tblInfo.Columns[i]
tblCols[i] = &expression.Column{
RetType: &c.FieldType,
ID: c.ID,
}
}
pkIdx := tables.FindPrimaryIndex(tblInfo)
for i, c := range pkIdx.Columns {
tblCols[c.Offset].Index = len(idxInfo.Columns) + i
}
return plannercore.NewCommonHandleCols(sctx, tblInfo, pkIdx, tblCols)
}
func (b *executorBuilder) buildCleanupIndex(v *plannercore.CleanupIndex) Executor {
tblInfo := v.Table.TableInfo
t, err := b.is.TableByName(v.Table.Schema, tblInfo.Name)
if err != nil {
b.err = err
return nil
}
idxName := strings.ToLower(v.IndexName)
var index table.Index
for _, idx := range t.Indices() {
if idx.Meta().State != model.StatePublic {
continue
}
if idxName == idx.Meta().Name.L {
index = idx
break
}
}
if index == nil {
b.err = errors.Errorf("index `%v` is not found in table `%v`.", v.IndexName, v.Table.Name.O)
return nil
}
e := &CleanupIndexExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
columns: buildIdxColsConcatHandleCols(tblInfo, index.Meta()),
index: index,
table: t,
physicalID: t.Meta().ID,
batchSize: 20000,
}
sessCtx := e.ctx.GetSessionVars().StmtCtx
e.handleCols = buildHandleColsForExec(sessCtx, tblInfo, index.Meta(), e.columns)
return e
}
func (b *executorBuilder) buildCheckIndexRange(v *plannercore.CheckIndexRange) Executor {
tb, err := b.is.TableByName(v.Table.Schema, v.Table.Name)
if err != nil {
b.err = err
return nil
}
e := &CheckIndexRangeExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
handleRanges: v.HandleRanges,
table: tb.Meta(),
is: b.is,
}
idxName := strings.ToLower(v.IndexName)
for _, idx := range tb.Indices() {
if idx.Meta().Name.L == idxName {
e.index = idx.Meta()
e.startKey = make([]types.Datum, len(e.index.Columns))
break
}
}
return e
}
func (b *executorBuilder) buildChecksumTable(v *plannercore.ChecksumTable) Executor {
e := &ChecksumTableExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
tables: make(map[int64]*checksumContext),
done: false,
}
startTs, err := b.getSnapshotTS()
if err != nil {
b.err = err
return nil
}
for _, t := range v.Tables {
e.tables[t.TableInfo.ID] = newChecksumContext(t.DBInfo, t.TableInfo, startTs)
}
return e
}
func (b *executorBuilder) buildReloadExprPushdownBlacklist(v *plannercore.ReloadExprPushdownBlacklist) Executor {
return &ReloadExprPushdownBlacklistExec{baseExecutor{ctx: b.ctx}}
}
func (b *executorBuilder) buildReloadOptRuleBlacklist(v *plannercore.ReloadOptRuleBlacklist) Executor {
return &ReloadOptRuleBlacklistExec{baseExecutor{ctx: b.ctx}}
}
func (b *executorBuilder) buildAdminPlugins(v *plannercore.AdminPlugins) Executor {
return &AdminPluginsExec{baseExecutor: baseExecutor{ctx: b.ctx}, Action: v.Action, Plugins: v.Plugins}
}
func (b *executorBuilder) buildDeallocate(v *plannercore.Deallocate) Executor {
base := newBaseExecutor(b.ctx, nil, v.ID())
base.initCap = chunk.ZeroCapacity
e := &DeallocateExec{
baseExecutor: base,
Name: v.Name,
}
return e
}
func (b *executorBuilder) buildSelectLock(v *plannercore.PhysicalLock) Executor {
b.hasLock = true
if b.err = b.updateForUpdateTSIfNeeded(v.Children()[0]); b.err != nil {
return nil
}
// Build 'select for update' using the 'for update' ts.
b.snapshotTS = b.ctx.GetSessionVars().TxnCtx.GetForUpdateTS()
src := b.build(v.Children()[0])
if b.err != nil {
return nil
}
if !b.ctx.GetSessionVars().InTxn() {
// Locking of rows for update using SELECT FOR UPDATE only applies when autocommit
// is disabled (either by beginning transaction with START TRANSACTION or by setting
// autocommit to 0. If autocommit is enabled, the rows matching the specification are not locked.
// See https://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html
return src
}
e := &SelectLockExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID(), src),
Lock: v.Lock,
tblID2Handle: v.TblID2Handle,
partitionedTable: v.PartitionedTable,
}
// filter out temporary tables because they do not store any record in tikv and should not write any lock
is := e.ctx.GetInfoSchema().(infoschema.InfoSchema)
for tblID := range e.tblID2Handle {
tblInfo, ok := is.TableByID(tblID)
if !ok {
b.err = errors.Errorf("Can not get table %d", tblID)
}
if tblInfo.Meta().TempTableType != model.TempTableNone {
delete(e.tblID2Handle, tblID)
}
}
if len(e.partitionedTable) > 0 {
schema := v.Schema()
e.tblID2PIDColumnIndex = make(map[int64]int)
for i := 0; i < len(v.ExtraPIDInfo.Columns); i++ {
col := v.ExtraPIDInfo.Columns[i]
tblID := v.ExtraPIDInfo.TblIDs[i]
offset := schema.ColumnIndex(col)
e.tblID2PIDColumnIndex[tblID] = offset
}
}
return e
}
func (b *executorBuilder) buildLimit(v *plannercore.PhysicalLimit) Executor {
childExec := b.build(v.Children()[0])
if b.err != nil {
return nil
}
n := int(mathutil.MinUint64(v.Count, uint64(b.ctx.GetSessionVars().MaxChunkSize)))
base := newBaseExecutor(b.ctx, v.Schema(), v.ID(), childExec)
base.initCap = n
e := &LimitExec{
baseExecutor: base,
begin: v.Offset,
end: v.Offset + v.Count,
}
childUsedSchema := markChildrenUsedCols(v.Schema(), v.Children()[0].Schema())[0]
e.columnIdxsUsedByChild = make([]int, 0, len(childUsedSchema))
for i, used := range childUsedSchema {
if used {
e.columnIdxsUsedByChild = append(e.columnIdxsUsedByChild, i)
}
}
if len(e.columnIdxsUsedByChild) == len(childUsedSchema) {
e.columnIdxsUsedByChild = nil // indicates that all columns are used. LimitExec will improve performance for this condition.
}
return e
}
func (b *executorBuilder) buildPrepare(v *plannercore.Prepare) Executor {
base := newBaseExecutor(b.ctx, v.Schema(), v.ID())
base.initCap = chunk.ZeroCapacity
return &PrepareExec{
baseExecutor: base,
name: v.Name,
sqlText: v.SQLText,
}
}
func (b *executorBuilder) buildExecute(v *plannercore.Execute) Executor {
b.snapshotTS = v.SnapshotTS
b.isStaleness = v.IsStaleness
b.txnScope = v.TxnScope
if b.snapshotTS != 0 {
b.is, b.err = domain.GetDomain(b.ctx).GetSnapshotInfoSchema(b.snapshotTS)
}
e := &ExecuteExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
is: b.is,
name: v.Name,
usingVars: v.UsingVars,
id: v.ExecID,
stmt: v.Stmt,
plan: v.Plan,
outputNames: v.OutputNames(),
}
failpoint.Inject("assertExecutePrepareStatementStalenessOption", func(val failpoint.Value) {
vs := strings.Split(val.(string), "_")
assertTS, assertTxnScope := vs[0], vs[1]
if strconv.FormatUint(b.snapshotTS, 10) != assertTS ||
assertTxnScope != b.txnScope {
panic("execute prepare statement have wrong staleness option")
}
})
return e
}
func (b *executorBuilder) buildShow(v *plannercore.PhysicalShow) Executor {
e := &ShowExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
Tp: v.Tp,
DBName: model.NewCIStr(v.DBName),
Table: v.Table,
Column: v.Column,
IndexName: v.IndexName,
Flag: v.Flag,
Roles: v.Roles,
User: v.User,
is: b.is,
Full: v.Full,
IfNotExists: v.IfNotExists,
GlobalScope: v.GlobalScope,
Extended: v.Extended,
}
if e.Tp == ast.ShowMasterStatus {
// show master status need start ts.
if _, err := e.ctx.Txn(true); err != nil {
b.err = err
}
}
return e
}
func (b *executorBuilder) buildSimple(v *plannercore.Simple) Executor {
switch s := v.Statement.(type) {
case *ast.GrantStmt:
return b.buildGrant(s)
case *ast.RevokeStmt:
return b.buildRevoke(s)
case *ast.BRIEStmt:
return b.buildBRIE(s, v.Schema())
}
base := newBaseExecutor(b.ctx, v.Schema(), v.ID())
base.initCap = chunk.ZeroCapacity
e := &SimpleExec{
baseExecutor: base,
Statement: v.Statement,
IsFromRemote: v.IsFromRemote,
is: b.is,
staleTxnStartTS: v.StaleTxnStartTS,
}
return e
}
func (b *executorBuilder) buildSet(v *plannercore.Set) Executor {
base := newBaseExecutor(b.ctx, v.Schema(), v.ID())
base.initCap = chunk.ZeroCapacity
e := &SetExecutor{
baseExecutor: base,
vars: v.VarAssigns,
}
return e
}
func (b *executorBuilder) buildSetConfig(v *plannercore.SetConfig) Executor {
return &SetConfigExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
p: v,
}
}
func (b *executorBuilder) buildInsert(v *plannercore.Insert) Executor {
if v.SelectPlan != nil {
// Try to update the forUpdateTS for insert/replace into select statements.
// Set the selectPlan parameter to nil to make it always update the forUpdateTS.
if b.err = b.updateForUpdateTSIfNeeded(nil); b.err != nil {
return nil
}
}
b.snapshotTS = b.ctx.GetSessionVars().TxnCtx.GetForUpdateTS()
selectExec := b.build(v.SelectPlan)
if b.err != nil {
return nil
}
var baseExec baseExecutor
if selectExec != nil {
baseExec = newBaseExecutor(b.ctx, nil, v.ID(), selectExec)
} else {
baseExec = newBaseExecutor(b.ctx, nil, v.ID())
}
baseExec.initCap = chunk.ZeroCapacity
ivs := &InsertValues{
baseExecutor: baseExec,
Table: v.Table,
Columns: v.Columns,
Lists: v.Lists,
SetList: v.SetList,
GenExprs: v.GenCols.Exprs,
allAssignmentsAreConstant: v.AllAssignmentsAreConstant,
hasRefCols: v.NeedFillDefaultValue,
SelectExec: selectExec,
rowLen: v.RowLen,
}
err := ivs.initInsertColumns()
if err != nil {
b.err = err
return nil
}
if v.IsReplace {
return b.buildReplace(ivs)
}
insert := &InsertExec{
InsertValues: ivs,
OnDuplicate: append(v.OnDuplicate, v.GenCols.OnDuplicates...),
}
return insert
}
func (b *executorBuilder) buildLoadData(v *plannercore.LoadData) Executor {
tbl, ok := b.is.TableByID(v.Table.TableInfo.ID)
if !ok {
b.err = errors.Errorf("Can not get table %d", v.Table.TableInfo.ID)
return nil
}
insertVal := &InsertValues{
baseExecutor: newBaseExecutor(b.ctx, nil, v.ID()),
Table: tbl,
Columns: v.Columns,
GenExprs: v.GenCols.Exprs,
isLoadData: true,
txnInUse: sync.Mutex{},
}
loadDataInfo := &LoadDataInfo{
row: make([]types.Datum, 0, len(insertVal.insertColumns)),
InsertValues: insertVal,
Path: v.Path,
Table: tbl,
FieldsInfo: v.FieldsInfo,
LinesInfo: v.LinesInfo,
IgnoreLines: v.IgnoreLines,
ColumnAssignments: v.ColumnAssignments,
ColumnsAndUserVars: v.ColumnsAndUserVars,
Ctx: b.ctx,
}
columnNames := loadDataInfo.initFieldMappings()
err := loadDataInfo.initLoadColumns(columnNames)
if err != nil {
b.err = err
return nil
}
loadDataExec := &LoadDataExec{
baseExecutor: newBaseExecutor(b.ctx, nil, v.ID()),
IsLocal: v.IsLocal,
OnDuplicate: v.OnDuplicate,
loadDataInfo: loadDataInfo,
}
var defaultLoadDataBatchCnt uint64 = 20000 // TODO this will be changed to variable in another pr
loadDataExec.loadDataInfo.InitQueues()
loadDataExec.loadDataInfo.SetMaxRowsInBatch(defaultLoadDataBatchCnt)
return loadDataExec
}
func (b *executorBuilder) buildLoadStats(v *plannercore.LoadStats) Executor {
e := &LoadStatsExec{
baseExecutor: newBaseExecutor(b.ctx, nil, v.ID()),
info: &LoadStatsInfo{v.Path, b.ctx},
}
return e
}
func (b *executorBuilder) buildIndexAdvise(v *plannercore.IndexAdvise) Executor {
e := &IndexAdviseExec{
baseExecutor: newBaseExecutor(b.ctx, nil, v.ID()),
IsLocal: v.IsLocal,
indexAdviseInfo: &IndexAdviseInfo{
Path: v.Path,
MaxMinutes: v.MaxMinutes,
MaxIndexNum: v.MaxIndexNum,
LinesInfo: v.LinesInfo,
Ctx: b.ctx,
},
}
return e
}
func (b *executorBuilder) buildPlanRecreatorSingle(v *plannercore.PlanRecreatorSingle) Executor {
e := &PlanRecreatorSingleExec{
baseExecutor: newBaseExecutor(b.ctx, nil, v.ID()),
info: &PlanRecreatorSingleInfo{v.ExecStmt, v.Analyze, v.Load, v.File, b.ctx},
}
return e
}
func (b *executorBuilder) buildReplace(vals *InsertValues) Executor {
replaceExec := &ReplaceExec{
InsertValues: vals,
}
return replaceExec
}
func (b *executorBuilder) buildGrant(grant *ast.GrantStmt) Executor {
e := &GrantExec{
baseExecutor: newBaseExecutor(b.ctx, nil, 0),
Privs: grant.Privs,
ObjectType: grant.ObjectType,
Level: grant.Level,
Users: grant.Users,
WithGrant: grant.WithGrant,
TLSOptions: grant.TLSOptions,
is: b.is,
}
return e
}
func (b *executorBuilder) buildRevoke(revoke *ast.RevokeStmt) Executor {
e := &RevokeExec{
baseExecutor: newBaseExecutor(b.ctx, nil, 0),
ctx: b.ctx,
Privs: revoke.Privs,
ObjectType: revoke.ObjectType,
Level: revoke.Level,
Users: revoke.Users,
is: b.is,
}
return e
}
func (b *executorBuilder) buildDDL(v *plannercore.DDL) Executor {
e := &DDLExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
stmt: v.Statement,
is: b.is,
tempTableDDL: temptable.GetTemporaryTableDDL(b.ctx),
}
return e
}
// buildTrace builds a TraceExec for future executing. This method will be called
// at build().
func (b *executorBuilder) buildTrace(v *plannercore.Trace) Executor {
t := &TraceExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
stmtNode: v.StmtNode,
builder: b,
format: v.Format,
}
if t.format == plannercore.TraceFormatLog {
return &SortExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID(), t),
ByItems: []*plannerutil.ByItems{
{Expr: &expression.Column{
Index: 0,
RetType: types.NewFieldType(mysql.TypeTimestamp),
}},
},
schema: v.Schema(),
}
}
return t
}
// buildExplain builds a explain executor. `e.rows` collects final result to `ExplainExec`.
func (b *executorBuilder) buildExplain(v *plannercore.Explain) Executor {
explainExec := &ExplainExec{
baseExecutor: newBaseExecutor(b.ctx, v.Schema(), v.ID()),
explain: v,
}
if v.Analyze {
if b.ctx.GetSessionVars().StmtCtx.RuntimeStatsColl == nil {
b.ctx.GetSessionVars().StmtCtx.RuntimeStatsColl = execdetails.NewRuntimeStatsColl(nil)
}
explainExec.analyzeExec = b.build(v.TargetPlan)
}
return explainExec
}
func (b *executorBuilder) buildSelectInto(v *plannercore.SelectInto) Executor {
child := b.build(v.TargetPlan)
if b.err != nil {