-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
point_get_plan.go
2148 lines (2007 loc) · 64.6 KB
/
point_get_plan.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 2018 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 (
math2 "math"
"strconv"
"strings"
"sync"
"unsafe"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/pkg/config"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/infoschema"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/parser/ast"
"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"
ptypes "github.com/pingcap/tidb/pkg/parser/types"
"github.com/pingcap/tidb/pkg/planner/core/base"
"github.com/pingcap/tidb/pkg/planner/core/operator/baseimpl"
"github.com/pingcap/tidb/pkg/planner/property"
"github.com/pingcap/tidb/pkg/planner/util"
"github.com/pingcap/tidb/pkg/planner/util/costusage"
"github.com/pingcap/tidb/pkg/planner/util/optimizetrace"
"github.com/pingcap/tidb/pkg/privilege"
"github.com/pingcap/tidb/pkg/sessionctx"
"github.com/pingcap/tidb/pkg/sessionctx/stmtctx"
"github.com/pingcap/tidb/pkg/sessiontxn"
"github.com/pingcap/tidb/pkg/table"
"github.com/pingcap/tidb/pkg/table/tables"
"github.com/pingcap/tidb/pkg/types"
driver "github.com/pingcap/tidb/pkg/types/parser_driver"
tidbutil "github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/collate"
"github.com/pingcap/tidb/pkg/util/dbterror/plannererrors"
"github.com/pingcap/tidb/pkg/util/execdetails"
"github.com/pingcap/tidb/pkg/util/intest"
"github.com/pingcap/tidb/pkg/util/logutil"
"github.com/pingcap/tidb/pkg/util/plancodec"
"github.com/pingcap/tidb/pkg/util/size"
"github.com/pingcap/tidb/pkg/util/stringutil"
"github.com/pingcap/tidb/pkg/util/tracing"
"github.com/pingcap/tipb/go-tipb"
tikvstore "github.com/tikv/client-go/v2/kv"
"go.uber.org/zap"
)
// GlobalWithoutColumnPos marks the index has no partition column.
const GlobalWithoutColumnPos = -1
// PointGetPlan is a fast plan for simple point get.
// When we detect that the statement has a unique equal access condition, this plan is used.
// This plan is much faster to build and to execute because it avoids the optimization and coprocessor cost.
type PointGetPlan struct {
baseimpl.Plan
dbName string
schema *expression.Schema
TblInfo *model.TableInfo
IndexInfo *model.IndexInfo
PartitionIdx *int
Handle kv.Handle
HandleConstant *expression.Constant
handleFieldType *types.FieldType
HandleColOffset int
IndexValues []types.Datum
IndexConstants []*expression.Constant
ColsFieldType []*types.FieldType
IdxCols []*expression.Column
IdxColLens []int
AccessConditions []expression.Expression
ctx base.PlanContext
UnsignedHandle bool
IsTableDual bool
Lock bool
outputNames []*types.FieldName
LockWaitTime int64
Columns []*model.ColumnInfo
cost float64
// required by cost model
planCostInit bool
planCost float64
planCostVer2 costusage.CostVer2
// accessCols represents actual columns the PointGet will access, which are used to calculate row-size
accessCols []*expression.Column
// probeParents records the IndexJoins and Applys with this operator in their inner children.
// Please see comments in PhysicalPlan for details.
probeParents []base.PhysicalPlan
// explicit partition selection
PartitionNames []model.CIStr
}
// GetEstRowCountForDisplay implements PhysicalPlan interface.
func (p *PointGetPlan) GetEstRowCountForDisplay() float64 {
if p == nil {
return 0
}
return p.StatsInfo().RowCount * getEstimatedProbeCntFromProbeParents(p.probeParents)
}
// GetActualProbeCnt implements PhysicalPlan interface.
func (p *PointGetPlan) GetActualProbeCnt(statsColl *execdetails.RuntimeStatsColl) int64 {
if p == nil {
return 1
}
return getActualProbeCntFromProbeParents(p.probeParents, statsColl)
}
// SetProbeParents implements PhysicalPlan interface.
func (p *PointGetPlan) SetProbeParents(probeParents []base.PhysicalPlan) {
p.probeParents = probeParents
}
type nameValuePair struct {
colName string
colFieldType *types.FieldType
value types.Datum
con *expression.Constant
}
// Schema implements the Plan interface.
func (p *PointGetPlan) Schema() *expression.Schema {
return p.schema
}
// Cost implements PhysicalPlan interface
func (p *PointGetPlan) Cost() float64 {
return p.cost
}
// SetCost implements PhysicalPlan interface
func (p *PointGetPlan) SetCost(cost float64) {
p.cost = cost
}
// Attach2Task makes the current physical plan as the father of task's physicalPlan and updates the cost of
// current task. If the child's task is cop task, some operator may close this task and return a new rootTask.
func (*PointGetPlan) Attach2Task(...base.Task) base.Task {
return nil
}
// ToPB converts physical plan to tipb executor.
func (*PointGetPlan) ToPB(_ *base.BuildPBContext, _ kv.StoreType) (*tipb.Executor, error) {
return nil, nil
}
// Clone implements PhysicalPlan interface.
func (p *PointGetPlan) Clone() (base.PhysicalPlan, error) {
return nil, errors.Errorf("%T doesn't support cloning", p)
}
// ExplainInfo implements Plan interface.
func (p *PointGetPlan) ExplainInfo() string {
accessObject, operatorInfo := p.AccessObject().String(), p.OperatorInfo(false)
if len(operatorInfo) == 0 {
return accessObject
}
return accessObject + ", " + operatorInfo
}
// ExplainNormalizedInfo implements Plan interface.
func (p *PointGetPlan) ExplainNormalizedInfo() string {
accessObject, operatorInfo := p.AccessObject().NormalizedString(), p.OperatorInfo(true)
if len(operatorInfo) == 0 {
return accessObject
}
return accessObject + ", " + operatorInfo
}
// OperatorInfo implements dataAccesser interface.
func (p *PointGetPlan) OperatorInfo(normalized bool) string {
if p.Handle == nil && !p.Lock {
return ""
}
var buffer strings.Builder
if p.Handle != nil {
if normalized {
buffer.WriteString("handle:?")
} else {
buffer.WriteString("handle:")
if p.UnsignedHandle {
buffer.WriteString(strconv.FormatUint(uint64(p.Handle.IntValue()), 10))
} else {
buffer.WriteString(p.Handle.String())
}
}
}
if p.Lock {
if p.Handle != nil {
buffer.WriteString(", lock")
} else {
buffer.WriteString("lock")
}
}
return buffer.String()
}
// ExtractCorrelatedCols implements PhysicalPlan interface.
func (*PointGetPlan) ExtractCorrelatedCols() []*expression.CorrelatedColumn {
return nil
}
// GetChildReqProps gets the required property by child index.
func (*PointGetPlan) GetChildReqProps(_ int) *property.PhysicalProperty {
return nil
}
// StatsCount will return the RowCount of property.StatsInfo for this plan.
func (*PointGetPlan) StatsCount() float64 {
return 1
}
// StatsInfo will return the RowCount of property.StatsInfo for this plan.
func (p *PointGetPlan) StatsInfo() *property.StatsInfo {
if p.Plan.StatsInfo() == nil {
p.Plan.SetStats(&property.StatsInfo{RowCount: 1})
}
return p.Plan.StatsInfo()
}
// Children gets all the children.
func (*PointGetPlan) Children() []base.PhysicalPlan {
return nil
}
// SetChildren sets the children for the plan.
func (*PointGetPlan) SetChildren(...base.PhysicalPlan) {}
// SetChild sets a specific child for the plan.
func (*PointGetPlan) SetChild(_ int, _ base.PhysicalPlan) {}
// ResolveIndices resolves the indices for columns. After doing this, the columns can evaluate the rows by their indices.
func (p *PointGetPlan) ResolveIndices() error {
return resolveIndicesForVirtualColumn(p.schema.Columns, p.schema)
}
// OutputNames returns the outputting names of each column.
func (p *PointGetPlan) OutputNames() types.NameSlice {
return p.outputNames
}
// SetOutputNames sets the outputting name by the given slice.
func (p *PointGetPlan) SetOutputNames(names types.NameSlice) {
p.outputNames = names
}
// AppendChildCandidate implements PhysicalPlan interface.
func (*PointGetPlan) AppendChildCandidate(_ *optimizetrace.PhysicalOptimizeOp) {}
const emptyPointGetPlanSize = int64(unsafe.Sizeof(PointGetPlan{}))
// MemoryUsage return the memory usage of PointGetPlan
func (p *PointGetPlan) MemoryUsage() (sum int64) {
if p == nil {
return
}
sum = emptyPointGetPlanSize + p.Plan.MemoryUsage() + int64(len(p.dbName)) + int64(cap(p.IdxColLens))*size.SizeOfInt +
int64(cap(p.IndexConstants)+cap(p.ColsFieldType)+cap(p.IdxCols)+cap(p.outputNames)+cap(p.Columns)+cap(p.accessCols))*size.SizeOfPointer
if p.schema != nil {
sum += p.schema.MemoryUsage()
}
if p.PartitionIdx != nil {
sum += size.SizeOfInt
}
if p.HandleConstant != nil {
sum += p.HandleConstant.MemoryUsage()
}
if p.handleFieldType != nil {
sum += p.handleFieldType.MemoryUsage()
}
for _, datum := range p.IndexValues {
sum += datum.MemUsage()
}
for _, idxConst := range p.IndexConstants {
sum += idxConst.MemoryUsage()
}
for _, ft := range p.ColsFieldType {
sum += ft.MemoryUsage()
}
for _, col := range p.IdxCols {
sum += col.MemoryUsage()
}
for _, cond := range p.AccessConditions {
sum += cond.MemoryUsage()
}
for _, name := range p.outputNames {
sum += name.MemoryUsage()
}
for _, col := range p.accessCols {
sum += col.MemoryUsage()
}
return
}
// LoadTableStats preloads the stats data for the physical table
func (p *PointGetPlan) LoadTableStats(ctx sessionctx.Context) {
tableID := p.TblInfo.ID
if idx := p.PartitionIdx; idx != nil {
if *idx < 0 {
// No matching partitions
return
}
if pi := p.TblInfo.GetPartitionInfo(); pi != nil {
tableID = pi.Definitions[*idx].ID
}
}
loadTableStats(ctx, p.TblInfo, tableID)
}
// PrunePartitions will check which partition to use
// returns true if no matching partition
func (p *PointGetPlan) PrunePartitions(sctx sessionctx.Context) bool {
pi := p.TblInfo.GetPartitionInfo()
if pi == nil {
return false
}
if p.IndexInfo != nil && p.IndexInfo.Global {
// reading for the Global Index / table id
return false
}
// If tryPointGetPlan did generate the plan,
// then PartitionIdx is not set and needs to be set here!
// There are two ways to get here from static mode partition pruning:
// 1) Converting a set of partitions into a Union scan
// - This should NOT be cached and should already be having PartitionIdx set!
// 2) Converted to PointGet from checkTblIndexForPointPlan
// and it does not have the PartitionIdx set
if !p.SCtx().GetSessionVars().StmtCtx.UseCache() &&
p.PartitionIdx != nil {
return false
}
is := sessiontxn.GetTxnManager(sctx).GetTxnInfoSchema()
tbl, ok := is.TableByID(p.TblInfo.ID)
if tbl == nil || !ok {
// Can this happen?
intest.Assert(false)
return false
}
pt := tbl.GetPartitionedTable()
if pt == nil {
// Can this happen?
intest.Assert(false)
return false
}
row := make([]types.Datum, len(p.TblInfo.Columns))
if p.HandleConstant == nil && len(p.IndexValues) > 0 {
for i := range p.IndexInfo.Columns {
// TODO: Skip copying non-partitioning columns?
p.IndexValues[i].Copy(&row[p.IndexInfo.Columns[i].Offset])
}
} else {
var dVal types.Datum
if p.UnsignedHandle {
dVal = types.NewUintDatum(uint64(p.Handle.IntValue()))
} else {
dVal = types.NewIntDatum(p.Handle.IntValue())
}
dVal.Copy(&row[p.HandleColOffset])
}
partIdx, err := pt.GetPartitionIdxByRow(sctx.GetExprCtx().GetEvalCtx(), row)
if err != nil {
partIdx = -1
p.PartitionIdx = &partIdx
return true
}
if len(p.PartitionNames) > 0 {
found := false
partName := pi.Definitions[partIdx].Name.L
for _, name := range p.PartitionNames {
if name.L == partName {
found = true
break
}
}
if !found {
partIdx = -1
p.PartitionIdx = &partIdx
return true
}
}
p.PartitionIdx = &partIdx
return false
}
// BatchPointGetPlan represents a physical plan which contains a bunch of
// keys reference the same table and use the same `unique key`
type BatchPointGetPlan struct {
baseSchemaProducer
ctx base.PlanContext
dbName string
TblInfo *model.TableInfo
IndexInfo *model.IndexInfo
Handles []kv.Handle
HandleType *types.FieldType
HandleParams []*expression.Constant // record all Parameters for Plan-Cache
IndexValues [][]types.Datum
IndexValueParams [][]*expression.Constant // record all Parameters for Plan-Cache
IndexColTypes []*types.FieldType
AccessConditions []expression.Expression
IdxCols []*expression.Column
IdxColLens []int
// Offset to column used for handle
HandleColOffset int
// Static prune mode converted to BatchPointGet
SinglePartition bool
// pre-calculated partition definition indexes
// for Handles or IndexValues
PartitionIdxs []int
KeepOrder bool
Desc bool
Lock bool
LockWaitTime int64
Columns []*model.ColumnInfo
cost float64
// required by cost model
planCostInit bool
planCost float64
planCostVer2 costusage.CostVer2
// accessCols represents actual columns the PointGet will access, which are used to calculate row-size
accessCols []*expression.Column
// probeParents records the IndexJoins and Applys with this operator in their inner children.
// Please see comments in PhysicalPlan for details.
probeParents []base.PhysicalPlan
// explicit partition selection
PartitionNames []model.CIStr
}
// GetEstRowCountForDisplay implements PhysicalPlan interface.
func (p *BatchPointGetPlan) GetEstRowCountForDisplay() float64 {
if p == nil {
return 0
}
return p.StatsInfo().RowCount * getEstimatedProbeCntFromProbeParents(p.probeParents)
}
// GetActualProbeCnt implements PhysicalPlan interface.
func (p *BatchPointGetPlan) GetActualProbeCnt(statsColl *execdetails.RuntimeStatsColl) int64 {
if p == nil {
return 1
}
return getActualProbeCntFromProbeParents(p.probeParents, statsColl)
}
// SetProbeParents implements PhysicalPlan interface.
func (p *BatchPointGetPlan) SetProbeParents(probeParents []base.PhysicalPlan) {
p.probeParents = probeParents
}
// Cost implements PhysicalPlan interface
func (p *BatchPointGetPlan) Cost() float64 {
return p.cost
}
// SetCost implements PhysicalPlan interface
func (p *BatchPointGetPlan) SetCost(cost float64) {
p.cost = cost
}
// Clone implements PhysicalPlan interface.
func (p *BatchPointGetPlan) Clone() (base.PhysicalPlan, error) {
return nil, errors.Errorf("%T doesn't support cloning", p)
}
// ExtractCorrelatedCols implements PhysicalPlan interface.
func (*BatchPointGetPlan) ExtractCorrelatedCols() []*expression.CorrelatedColumn {
return nil
}
// Attach2Task makes the current physical plan as the father of task's physicalPlan and updates the cost of
// current task. If the child's task is cop task, some operator may close this task and return a new rootTask.
func (*BatchPointGetPlan) Attach2Task(...base.Task) base.Task {
return nil
}
// ToPB converts physical plan to tipb executor.
func (*BatchPointGetPlan) ToPB(_ *base.BuildPBContext, _ kv.StoreType) (*tipb.Executor, error) {
return nil, nil
}
// ExplainInfo implements Plan interface.
func (p *BatchPointGetPlan) ExplainInfo() string {
return p.AccessObject().String() + ", " + p.OperatorInfo(false)
}
// ExplainNormalizedInfo implements Plan interface.
func (p *BatchPointGetPlan) ExplainNormalizedInfo() string {
return p.AccessObject().NormalizedString() + ", " + p.OperatorInfo(true)
}
// OperatorInfo implements dataAccesser interface.
func (p *BatchPointGetPlan) OperatorInfo(normalized bool) string {
var buffer strings.Builder
if p.IndexInfo == nil {
if normalized {
buffer.WriteString("handle:?, ")
} else {
buffer.WriteString("handle:[")
for i, handle := range p.Handles {
if i != 0 {
buffer.WriteString(" ")
}
buffer.WriteString(handle.String())
}
buffer.WriteString("], ")
}
}
buffer.WriteString("keep order:")
buffer.WriteString(strconv.FormatBool(p.KeepOrder))
buffer.WriteString(", desc:")
buffer.WriteString(strconv.FormatBool(p.Desc))
if p.Lock {
buffer.WriteString(", lock")
}
return buffer.String()
}
// GetChildReqProps gets the required property by child index.
func (*BatchPointGetPlan) GetChildReqProps(_ int) *property.PhysicalProperty {
return nil
}
// StatsCount will return the RowCount of property.StatsInfo for this plan.
func (p *BatchPointGetPlan) StatsCount() float64 {
return p.Plan.StatsInfo().RowCount
}
// StatsInfo will return the StatsInfo of property.StatsInfo for this plan.
func (p *BatchPointGetPlan) StatsInfo() *property.StatsInfo {
return p.Plan.StatsInfo()
}
// Children gets all the children.
func (*BatchPointGetPlan) Children() []base.PhysicalPlan {
return nil
}
// SetChildren sets the children for the plan.
func (*BatchPointGetPlan) SetChildren(...base.PhysicalPlan) {}
// SetChild sets a specific child for the plan.
func (*BatchPointGetPlan) SetChild(_ int, _ base.PhysicalPlan) {}
// ResolveIndices resolves the indices for columns. After doing this, the columns can evaluate the rows by their indices.
func (p *BatchPointGetPlan) ResolveIndices() error {
return resolveIndicesForVirtualColumn(p.schema.Columns, p.schema)
}
// OutputNames returns the outputting names of each column.
func (p *BatchPointGetPlan) OutputNames() types.NameSlice {
return p.names
}
// SetOutputNames sets the outputting name by the given slice.
func (p *BatchPointGetPlan) SetOutputNames(names types.NameSlice) {
p.names = names
}
// AppendChildCandidate implements PhysicalPlan interface.
func (*BatchPointGetPlan) AppendChildCandidate(_ *optimizetrace.PhysicalOptimizeOp) {}
const emptyBatchPointGetPlanSize = int64(unsafe.Sizeof(BatchPointGetPlan{}))
// MemoryUsage return the memory usage of BatchPointGetPlan
func (p *BatchPointGetPlan) MemoryUsage() (sum int64) {
if p == nil {
return
}
sum = emptyBatchPointGetPlanSize + p.baseSchemaProducer.MemoryUsage() + int64(len(p.dbName)) +
int64(cap(p.IdxColLens)+cap(p.PartitionIdxs))*size.SizeOfInt + int64(cap(p.Handles))*size.SizeOfInterface +
int64(cap(p.HandleParams)+cap(p.IndexColTypes)+cap(p.IdxCols)+cap(p.Columns)+cap(p.accessCols))*size.SizeOfPointer
if p.HandleType != nil {
sum += p.HandleType.MemoryUsage()
}
for _, constant := range p.HandleParams {
sum += constant.MemoryUsage()
}
for _, values := range p.IndexValues {
for _, value := range values {
sum += value.MemUsage()
}
}
for _, params := range p.IndexValueParams {
for _, param := range params {
sum += param.MemoryUsage()
}
}
for _, idxType := range p.IndexColTypes {
sum += idxType.MemoryUsage()
}
for _, cond := range p.AccessConditions {
sum += cond.MemoryUsage()
}
for _, col := range p.IdxCols {
sum += col.MemoryUsage()
}
for _, col := range p.accessCols {
sum += col.MemoryUsage()
}
return
}
// LoadTableStats preloads the stats data for the physical table
func (p *BatchPointGetPlan) LoadTableStats(ctx sessionctx.Context) {
// as a `BatchPointGet` can access multiple partitions, and we cannot distinguish how many rows come from each
// partitions in the existing statistics information, we treat all index usage through a `BatchPointGet` just
// like a normal global index.
loadTableStats(ctx, p.TblInfo, p.TblInfo.ID)
}
func isInExplicitPartitions(pi *model.PartitionInfo, idx int, names []model.CIStr) bool {
if len(names) == 0 {
return true
}
s := pi.Definitions[idx].Name.L
for _, name := range names {
if s == name.L {
return true
}
}
return false
}
// Map each index value to Partition ID
func (p *BatchPointGetPlan) getPartitionIdxs(sctx sessionctx.Context) []int {
is := sessiontxn.GetTxnManager(sctx).GetTxnInfoSchema()
tbl, ok := is.TableByID(p.TblInfo.ID)
intest.Assert(ok)
pTbl, ok := tbl.(table.PartitionedTable)
intest.Assert(ok)
intest.Assert(pTbl != nil)
r := make([]types.Datum, len(pTbl.Cols()))
rows := p.IndexValues
idxs := make([]int, 0, len(rows))
for i := range rows {
for j := range rows[i] {
rows[i][j].Copy(&r[p.IndexInfo.Columns[j].Offset])
}
pIdx, err := pTbl.GetPartitionIdxByRow(sctx.GetExprCtx().GetEvalCtx(), r)
if err != nil {
// Skip on any error, like:
// No matching partition, overflow etc.
idxs = append(idxs, -1)
continue
}
idxs = append(idxs, pIdx)
}
return idxs
}
// PrunePartitionsAndValues will check which partition to use
// returns:
// slice of non-duplicated handles (or nil if IndexValues is used)
// true if no matching partition (TableDual plan can be used)
func (p *BatchPointGetPlan) PrunePartitionsAndValues(sctx sessionctx.Context) ([]kv.Handle, bool) {
pi := p.TblInfo.GetPartitionInfo()
if p.IndexInfo != nil && p.IndexInfo.Global {
// Reading from a global index, i.e. base table ID
// Skip pruning partitions here
pi = nil
}
// reset the PartitionIDs
if pi != nil && !p.SinglePartition {
p.PartitionIdxs = p.PartitionIdxs[:0]
}
if p.IndexInfo != nil && !(p.TblInfo.IsCommonHandle && p.IndexInfo.Primary) {
filteredVals := p.IndexValues[:0]
for _, idxVals := range p.IndexValues {
// For all x, 'x IN (null)' evaluate to null, so the query get no result.
if !types.DatumsContainNull(idxVals) {
filteredVals = append(filteredVals, idxVals)
}
}
p.IndexValues = filteredVals
if pi != nil {
partIdxs := p.getPartitionIdxs(sctx)
partitionsFound := 0
for i, idx := range partIdxs {
if idx < 0 ||
(p.SinglePartition &&
idx != p.PartitionIdxs[0]) ||
!isInExplicitPartitions(pi, idx, p.PartitionNames) {
// Index value does not match any partitions,
// remove it from the plan
partIdxs[i] = -1
} else {
partitionsFound++
}
}
if partitionsFound == 0 {
return nil, true
}
skipped := 0
for i, idx := range partIdxs {
if idx < 0 {
curr := i - skipped
next := curr + 1
p.IndexValues = append(p.IndexValues[:curr], p.IndexValues[next:]...)
skipped++
} else if !p.SinglePartition {
p.PartitionIdxs = append(p.PartitionIdxs, idx)
}
}
intest.Assert(p.SinglePartition || partitionsFound == len(p.PartitionIdxs))
intest.Assert(partitionsFound == len(p.IndexValues))
}
return nil, false
}
handles := make([]kv.Handle, 0, len(p.Handles))
dedup := kv.NewHandleMap()
if p.IndexInfo == nil {
for _, handle := range p.Handles {
if _, found := dedup.Get(handle); found {
continue
}
dedup.Set(handle, true)
handles = append(handles, handle)
}
if pi != nil {
is := sessiontxn.GetTxnManager(sctx).GetTxnInfoSchema()
tbl, ok := is.TableByID(p.TblInfo.ID)
intest.Assert(ok)
pTbl, ok := tbl.(table.PartitionedTable)
intest.Assert(ok)
intest.Assert(pTbl != nil)
r := make([]types.Datum, p.HandleColOffset+1)
partIdxs := make([]int, 0, len(handles))
partitionsFound := 0
for _, handle := range handles {
var d types.Datum
if mysql.HasUnsignedFlag(p.TblInfo.Columns[p.HandleColOffset].GetFlag()) {
d = types.NewUintDatum(uint64(handle.IntValue()))
} else {
d = types.NewIntDatum(handle.IntValue())
}
d.Copy(&r[p.HandleColOffset])
pIdx, err := pTbl.GetPartitionIdxByRow(sctx.GetExprCtx().GetEvalCtx(), r)
if err != nil ||
!isInExplicitPartitions(pi, pIdx, p.PartitionNames) ||
(p.SinglePartition &&
p.PartitionIdxs[0] != pIdx) {
{
pIdx = -1
}
} else {
partitionsFound++
}
partIdxs = append(partIdxs, pIdx)
}
if partitionsFound == 0 {
return nil, true
}
skipped := 0
for i, idx := range partIdxs {
if idx < 0 {
curr := i - skipped
next := curr + 1
handles = append(handles[:curr], handles[next:]...)
skipped++
} else if !p.SinglePartition {
p.PartitionIdxs = append(p.PartitionIdxs, idx)
}
}
intest.Assert(p.SinglePartition || partitionsFound == len(p.PartitionIdxs))
intest.Assert(p.SinglePartition || partitionsFound == len(handles))
}
p.Handles = handles
} else {
usedValues := make([]bool, len(p.IndexValues))
for i, value := range p.IndexValues {
if types.DatumsContainNull(value) {
continue
}
handleBytes, err := EncodeUniqueIndexValuesForKey(sctx, p.TblInfo, p.IndexInfo, value)
if err != nil {
if kv.ErrNotExist.Equal(err) {
continue
}
intest.Assert(false)
continue
}
handle, err := kv.NewCommonHandle(handleBytes)
if err != nil {
intest.Assert(false)
continue
}
if _, found := dedup.Get(handle); found {
continue
}
dedup.Set(handle, true)
handles = append(handles, handle)
usedValues[i] = true
}
skipped := 0
for i, use := range usedValues {
if !use {
curr := i - skipped
p.IndexValues = append(p.IndexValues[:curr], p.IndexValues[curr+1:]...)
skipped++
}
}
if pi != nil {
partIdxs := p.getPartitionIdxs(sctx)
skipped = 0
partitionsFound := 0
for i, idx := range partIdxs {
if partIdxs[i] < 0 ||
(p.SinglePartition &&
partIdxs[i] != p.PartitionIdxs[0]) ||
!isInExplicitPartitions(pi, idx, p.PartitionNames) {
curr := i - skipped
handles = append(handles[:curr], handles[curr+1:]...)
p.IndexValues = append(p.IndexValues[:curr], p.IndexValues[curr+1:]...)
skipped++
continue
} else if !p.SinglePartition {
p.PartitionIdxs = append(p.PartitionIdxs, idx)
}
partitionsFound++
}
if partitionsFound == 0 {
return nil, true
}
intest.Assert(p.SinglePartition || partitionsFound == len(p.PartitionIdxs))
}
}
return handles, false
}
// PointPlanKey is used to get point plan that is pre-built for multi-statement query.
const PointPlanKey = stringutil.StringerStr("pointPlanKey")
// PointPlanVal is used to store point plan that is pre-built for multi-statement query.
// Save the plan in a struct so even if the point plan is nil, we don't need to try again.
type PointPlanVal struct {
Plan base.Plan
}
// TryFastPlan tries to use the PointGetPlan for the query.
func TryFastPlan(ctx base.PlanContext, node ast.Node) (p base.Plan) {
if checkStableResultMode(ctx) {
// the rule of stabilizing results has not taken effect yet, so cannot generate a plan here in this mode
return nil
}
ctx.GetSessionVars().PlanID.Store(0)
ctx.GetSessionVars().PlanColumnID.Store(0)
switch x := node.(type) {
case *ast.SelectStmt:
if x.SelectIntoOpt != nil {
return nil
}
defer func() {
vars := ctx.GetSessionVars()
if vars.SelectLimit != math2.MaxUint64 && p != nil {
ctx.GetSessionVars().StmtCtx.AppendWarning(errors.NewNoStackError("sql_select_limit is set, so point get plan is not activated"))
p = nil
}
if vars.StmtCtx.EnableOptimizeTrace && p != nil {
if vars.StmtCtx.OptimizeTracer == nil {
vars.StmtCtx.OptimizeTracer = &tracing.OptimizeTracer{}
}
vars.StmtCtx.OptimizeTracer.SetFastPlan(p.BuildPlanTrace())
}
}()
// Try to convert the `SELECT a, b, c FROM t WHERE (a, b, c) in ((1, 2, 4), (1, 3, 5))` to
// `PhysicalUnionAll` which children are `PointGet` if exists an unique key (a, b, c) in table `t`
if fp := tryWhereIn2BatchPointGet(ctx, x); fp != nil {
if checkFastPlanPrivilege(ctx, fp.dbName, fp.TblInfo.Name.L, mysql.SelectPriv) != nil {
return
}
if tidbutil.IsMemDB(fp.dbName) {
return nil
}
fp.Lock, fp.LockWaitTime = getLockWaitTime(ctx, x.LockInfo)
p = fp
return
}
if fp := tryPointGetPlan(ctx, x, isForUpdateReadSelectLock(x.LockInfo)); fp != nil {
if checkFastPlanPrivilege(ctx, fp.dbName, fp.TblInfo.Name.L, mysql.SelectPriv) != nil {
return nil
}
if tidbutil.IsMemDB(fp.dbName) {
return nil
}
if fp.IsTableDual {
tableDual := PhysicalTableDual{}
tableDual.names = fp.outputNames
tableDual.SetSchema(fp.Schema())
p = tableDual.Init(ctx, &property.StatsInfo{}, 0)
return
}
fp.Lock, fp.LockWaitTime = getLockWaitTime(ctx, x.LockInfo)
p = fp
return
}
case *ast.UpdateStmt:
return tryUpdatePointPlan(ctx, x)
case *ast.DeleteStmt:
return tryDeletePointPlan(ctx, x)
}
return nil
}
// IsSelectForUpdateLockType checks if the select lock type is for update type.
func IsSelectForUpdateLockType(lockType ast.SelectLockType) bool {
if lockType == ast.SelectLockForUpdate ||
lockType == ast.SelectLockForShare ||
lockType == ast.SelectLockForUpdateNoWait ||
lockType == ast.SelectLockForUpdateWaitN {
return true
}
return false
}
func getLockWaitTime(ctx base.PlanContext, lockInfo *ast.SelectLockInfo) (lock bool, waitTime int64) {
if lockInfo != nil {
if IsSelectForUpdateLockType(lockInfo.LockType) {
// 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
sessVars := ctx.GetSessionVars()
if !sessVars.IsAutocommit() || sessVars.InTxn() || (config.GetGlobalConfig().
PessimisticTxn.PessimisticAutoCommit.Load() && !sessVars.BulkDMLEnabled) {
lock = true
waitTime = sessVars.LockWaitTimeout
if lockInfo.LockType == ast.SelectLockForUpdateWaitN {
waitTime = int64(lockInfo.WaitSec * 1000)
} else if lockInfo.LockType == ast.SelectLockForUpdateNoWait {
waitTime = tikvstore.LockNoWait
}
}
}
}
return
}
func newBatchPointGetPlan(
ctx base.PlanContext, patternInExpr *ast.PatternInExpr,
handleCol *model.ColumnInfo, tbl *model.TableInfo, schema *expression.Schema,
names []*types.FieldName, whereColNames []string, indexHints []*ast.IndexHint,
) *BatchPointGetPlan {
stmtCtx := ctx.GetSessionVars().StmtCtx
statsInfo := &property.StatsInfo{RowCount: float64(len(patternInExpr.List))}
if tbl.GetPartitionInfo() != nil {
// TODO: remove this limitation
// Only keeping it for now to limit impact of
// enable plan cache for partitioned tables PR.
is := ctx.GetInfoSchema().(infoschema.InfoSchema)
table, ok := is.TableByID(tbl.ID)
if !ok {
return nil
}
partTable, ok := table.(partitionTable)
if !ok {
return nil
}
// PartitionExpr don't need columns and names for hash partition.
partExpr := partTable.PartitionExpr()
if partExpr == nil || partExpr.Expr == nil {
return nil
}
if _, ok := partExpr.Expr.(*expression.Column); !ok {
return nil
}
}
if handleCol != nil {
// condition key of where is primary key
var handles = make([]kv.Handle, len(patternInExpr.List))
var handleParams = make([]*expression.Constant, len(patternInExpr.List))
for i, item := range patternInExpr.List {