-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
point_get_plan.go
1941 lines (1803 loc) · 57.8 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"
"sort"
"strconv"
"strings"
"unsafe"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/charset"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/opcode"
"github.com/pingcap/tidb/parser/terror"
ptypes "github.com/pingcap/tidb/parser/types"
"github.com/pingcap/tidb/planner/property"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessiontxn"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/types"
driver "github.com/pingcap/tidb/types/parser_driver"
tidbutil "github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/execdetails"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/mathutil"
"github.com/pingcap/tidb/util/plancodec"
"github.com/pingcap/tidb/util/size"
"github.com/pingcap/tidb/util/stringutil"
"github.com/pingcap/tidb/util/tracing"
"github.com/pingcap/tipb/go-tipb"
tikvstore "github.com/tikv/client-go/v2/kv"
"go.uber.org/zap"
)
// 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 avoid the optimization and coprocessor cost.
type PointGetPlan struct {
basePlan
dbName string
schema *expression.Schema
TblInfo *model.TableInfo
IndexInfo *model.IndexInfo
PartitionInfo *model.PartitionDefinition
Handle kv.Handle
HandleConstant *expression.Constant
handleFieldType *types.FieldType
IndexValues []types.Datum
IndexConstants []*expression.Constant
ColsFieldType []*types.FieldType
IdxCols []*expression.Column
IdxColLens []int
AccessConditions []expression.Expression
ctx sessionctx.Context
UnsignedHandle bool
IsTableDual bool
Lock bool
outputNames []*types.FieldName
LockWaitTime int64
partitionColumnPos int
Columns []*model.ColumnInfo
cost float64
// required by cost model
planCostInit bool
planCost float64
planCostVer2 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 []PhysicalPlan
}
func (p *PointGetPlan) getEstRowCountForDisplay() float64 {
if p == nil {
return 0
}
return p.statsInfo().RowCount * getEstimatedProbeCntFromProbeParents(p.probeParents)
}
func (p *PointGetPlan) getActualProbeCnt(statsColl *execdetails.RuntimeStatsColl) int64 {
if p == nil {
return 1
}
return getActualProbeCntFromProbeParents(p.probeParents, statsColl)
}
func (p *PointGetPlan) setProbeParents(probeParents []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(...task) task {
return nil
}
// ToPB converts physical plan to tipb executor.
func (*PointGetPlan) ToPB(_ sessionctx.Context, _ kv.StoreType) (*tipb.Executor, error) {
return nil, nil
}
// Clone implements PhysicalPlan interface.
func (p *PointGetPlan) Clone() (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 the RowCount of property.StatsInfo for this plan.
func (*PointGetPlan) StatsCount() float64 {
return 1
}
// statsInfo will return the the RowCount of property.StatsInfo for this plan.
func (p *PointGetPlan) statsInfo() *property.StatsInfo {
if p.stats == nil {
p.stats = &property.StatsInfo{}
}
p.stats.RowCount = 1
return p.stats
}
// Children gets all the children.
func (*PointGetPlan) Children() []PhysicalPlan {
return nil
}
// SetChildren sets the children for the plan.
func (*PointGetPlan) SetChildren(...PhysicalPlan) {}
// SetChild sets a specific child for the plan.
func (*PointGetPlan) SetChild(_ int, _ 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
}
func (*PointGetPlan) appendChildCandidate(_ *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.basePlan.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.PartitionInfo != nil {
sum += p.PartitionInfo.MemoryUsage()
}
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
}
// 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 sessionctx.Context
dbName string
TblInfo *model.TableInfo
IndexInfo *model.IndexInfo
PartitionInfos []*model.PartitionDefinition
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
PartitionColPos int
PartitionExpr *tables.PartitionExpr
KeepOrder bool
Desc bool
Lock bool
LockWaitTime int64
Columns []*model.ColumnInfo
cost float64
// SinglePart indicates whether this BatchPointGetPlan is just for a single partition, instead of the whole partition table.
// If the BatchPointGetPlan is built in fast path, this value if false; if the plan is generated in physical optimization for a partition,
// this value would be true. This value would decide the behavior of BatchPointGetExec, i.e, whether to compute the table ID of the partition
// on the fly.
SinglePart bool
// PartTblID is the table ID for the specific table partition.
PartTblID int64
// required by cost model
planCostInit bool
planCost float64
planCostVer2 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 []PhysicalPlan
}
func (p *BatchPointGetPlan) getEstRowCountForDisplay() float64 {
if p == nil {
return 0
}
return p.statsInfo().RowCount * getEstimatedProbeCntFromProbeParents(p.probeParents)
}
func (p *BatchPointGetPlan) getActualProbeCnt(statsColl *execdetails.RuntimeStatsColl) int64 {
if p == nil {
return 1
}
return getActualProbeCntFromProbeParents(p.probeParents, statsColl)
}
func (p *BatchPointGetPlan) setProbeParents(probeParents []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() (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(...task) task {
return nil
}
// ToPB converts physical plan to tipb executor.
func (*BatchPointGetPlan) ToPB(_ sessionctx.Context, _ 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 the RowCount of property.StatsInfo for this plan.
func (p *BatchPointGetPlan) StatsCount() float64 {
return p.statsInfo().RowCount
}
// statsInfo will return the the RowCount of property.StatsInfo for this plan.
func (p *BatchPointGetPlan) statsInfo() *property.StatsInfo {
return p.stats
}
// Children gets all the children.
func (*BatchPointGetPlan) Children() []PhysicalPlan {
return nil
}
// SetChildren sets the children for the plan.
func (*BatchPointGetPlan) SetChildren(...PhysicalPlan) {}
// SetChild sets a specific child for the plan.
func (*BatchPointGetPlan) SetChild(_ int, _ 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
}
func (*BatchPointGetPlan) appendChildCandidate(_ *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))*size.SizeOfInt + int64(cap(p.Handles))*size.SizeOfInterface +
int64(cap(p.PartitionInfos)+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
}
// 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 Plan
}
// TryFastPlan tries to use the PointGetPlan for the query.
func TryFastPlan(ctx sessionctx.Context, node ast.Node) (p 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 = 0
ctx.GetSessionVars().PlanColumnID = 0
switch x := node.(type) {
case *ast.SelectStmt:
defer func() {
vars := ctx.GetSessionVars()
if vars.SelectLimit != math2.MaxUint64 && p != nil {
ctx.GetSessionVars().StmtCtx.AppendWarning(errors.New("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 sessionctx.Context, 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() {
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 sessionctx.Context, 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))}
var partitionExpr *tables.PartitionExpr
if tbl.GetPartitionInfo() != nil {
partitionExpr = getPartitionExpr(ctx, tbl)
if partitionExpr == nil {
return nil
}
if partitionExpr.Expr == nil {
return nil
}
if _, ok := partitionExpr.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))
var pos2PartitionDefinition = make(map[int]*model.PartitionDefinition)
partitionInfos := make([]*model.PartitionDefinition, 0, len(patternInExpr.List))
for i, item := range patternInExpr.List {
// SELECT * FROM t WHERE (key) in ((1), (2))
if p, ok := item.(*ast.ParenthesesExpr); ok {
item = p.Expr
}
var d types.Datum
var con *expression.Constant
switch x := item.(type) {
case *driver.ValueExpr:
d = x.Datum
case *driver.ParamMarkerExpr:
var err error
con, err = expression.ParamMarkerExpression(ctx, x, true)
if err != nil {
return nil
}
d, err = con.Eval(chunk.Row{})
if err != nil {
return nil
}
default:
return nil
}
if d.IsNull() {
return nil
}
intDatum := getPointGetValue(stmtCtx, handleCol, &d)
if intDatum == nil {
return nil
}
handles[i] = kv.IntHandle(intDatum.GetInt64())
handleParams[i] = con
pairs := []nameValuePair{{colName: handleCol.Name.L, colFieldType: item.GetType(), value: *intDatum, con: con}}
if tbl.GetPartitionInfo() != nil {
tmpPartitionDefinition, _, pos, isTableDual := getPartitionInfo(ctx, tbl, pairs)
if isTableDual {
return nil
}
if tmpPartitionDefinition != nil {
pos2PartitionDefinition[pos] = tmpPartitionDefinition
}
}
}
posArr := make([]int, len(pos2PartitionDefinition))
i := 0
for pos := range pos2PartitionDefinition {
posArr[i] = pos
i++
}
sort.Ints(posArr)
for _, pos := range posArr {
partitionInfos = append(partitionInfos, pos2PartitionDefinition[pos])
}
if len(partitionInfos) == 0 {
partitionInfos = nil
}
return BatchPointGetPlan{
TblInfo: tbl,
Handles: handles,
HandleParams: handleParams,
HandleType: &handleCol.FieldType,
PartitionExpr: partitionExpr,
PartitionInfos: partitionInfos,
}.Init(ctx, statsInfo, schema, names, 0)
}
// The columns in where clause should be covered by unique index
var matchIdxInfo *model.IndexInfo
permutations := make([]int, len(whereColNames))
colInfos := make([]*model.ColumnInfo, len(whereColNames))
for i, innerCol := range whereColNames {
for _, col := range tbl.Columns {
if col.Name.L == innerCol {
colInfos[i] = col
}
}
}
for _, idxInfo := range tbl.Indices {
if !idxInfo.Unique || idxInfo.State != model.StatePublic || idxInfo.Invisible ||
!indexIsAvailableByHints(idxInfo, indexHints) {
continue
}
if len(idxInfo.Columns) != len(whereColNames) || idxInfo.HasPrefixIndex() {
continue
}
// TODO: not sure is there any function to reuse
matched := true
for whereColIndex, innerCol := range whereColNames {
var found bool
for i, col := range idxInfo.Columns {
if innerCol == col.Name.L {
permutations[whereColIndex] = i
found = true
break
}
}
if !found {
matched = false
break
}
}
if matched {
matchIdxInfo = idxInfo
break
}
}
if matchIdxInfo == nil {
return nil
}
pos, err := getPartitionColumnPos(matchIdxInfo, partitionExpr, tbl)
if err != nil {
return nil
}
indexValues := make([][]types.Datum, len(patternInExpr.List))
indexValueParams := make([][]*expression.Constant, len(patternInExpr.List))
partitionInfos := make([]*model.PartitionDefinition, 0, len(patternInExpr.List))
var pos2PartitionDefinition = make(map[int]*model.PartitionDefinition)
var indexTypes []*types.FieldType
for i, item := range patternInExpr.List {
// SELECT * FROM t WHERE (key) in ((1), (2)) or SELECT * FROM t WHERE (key1, key2) in ((1, 1), (2, 2))
if p, ok := item.(*ast.ParenthesesExpr); ok {
item = p.Expr
}
var values []types.Datum
var valuesParams []*expression.Constant
var pairs []nameValuePair
switch x := item.(type) {
case *ast.RowExpr:
// The `len(values) == len(valuesParams)` should be satisfied in this mode
if len(x.Values) != len(whereColNames) {
return nil
}
values = make([]types.Datum, len(x.Values))
pairs = make([]nameValuePair, 0, len(x.Values))
valuesParams = make([]*expression.Constant, len(x.Values))
initTypes := false
if indexTypes == nil { // only init once
indexTypes = make([]*types.FieldType, len(x.Values))
initTypes = true
}
for index, inner := range x.Values {
// permutations is used to match column and value.
permIndex := permutations[index]
switch innerX := inner.(type) {
case *driver.ValueExpr:
dval := getPointGetValue(stmtCtx, colInfos[index], &innerX.Datum)
if dval == nil {
return nil
}
values[permIndex] = innerX.Datum
pairs = append(pairs, nameValuePair{colName: whereColNames[index], value: innerX.Datum})
case *driver.ParamMarkerExpr:
con, err := expression.ParamMarkerExpression(ctx, innerX, true)
if err != nil {
return nil
}
d, err := con.Eval(chunk.Row{})
if err != nil {
return nil
}
dval := getPointGetValue(stmtCtx, colInfos[index], &d)
if dval == nil {
return nil
}
values[permIndex] = innerX.Datum
valuesParams[permIndex] = con
if initTypes {
indexTypes[permIndex] = &colInfos[index].FieldType
}
pairs = append(pairs, nameValuePair{colName: whereColNames[index], value: innerX.Datum})
default:
return nil
}
}
case *driver.ValueExpr:
// if any item is `ValueExpr` type, `Expr` should contain only one column,
// otherwise column count doesn't match and no plan can be built.
if len(whereColNames) != 1 {
return nil
}
dval := getPointGetValue(stmtCtx, colInfos[0], &x.Datum)
if dval == nil {
return nil
}
values = []types.Datum{*dval}
valuesParams = []*expression.Constant{nil}
pairs = append(pairs, nameValuePair{colName: whereColNames[0], value: *dval})
case *driver.ParamMarkerExpr:
if len(whereColNames) != 1 {
return nil
}
con, err := expression.ParamMarkerExpression(ctx, x, true)
if err != nil {
return nil
}
d, err := con.Eval(chunk.Row{})
if err != nil {
return nil
}
dval := getPointGetValue(stmtCtx, colInfos[0], &d)
if dval == nil {
return nil
}
values = []types.Datum{*dval}
valuesParams = []*expression.Constant{con}
if indexTypes == nil { // only init once
indexTypes = []*types.FieldType{&colInfos[0].FieldType}
}
pairs = append(pairs, nameValuePair{colName: whereColNames[0], value: *dval})
default:
return nil
}
indexValues[i] = values
indexValueParams[i] = valuesParams
if tbl.GetPartitionInfo() != nil {
tmpPartitionDefinition, _, pos, isTableDual := getPartitionInfo(ctx, tbl, pairs)
if isTableDual {
return nil
}
if tmpPartitionDefinition != nil {
pos2PartitionDefinition[pos] = tmpPartitionDefinition
}
}
}
posArr := make([]int, len(pos2PartitionDefinition))
i := 0
for pos := range pos2PartitionDefinition {
posArr[i] = pos
i++
}
sort.Ints(posArr)
for _, pos := range posArr {
partitionInfos = append(partitionInfos, pos2PartitionDefinition[pos])
}
if len(partitionInfos) == 0 {
partitionInfos = nil
}
return BatchPointGetPlan{
TblInfo: tbl,
IndexInfo: matchIdxInfo,
IndexValues: indexValues,
IndexValueParams: indexValueParams,
IndexColTypes: indexTypes,
PartitionColPos: pos,
PartitionExpr: partitionExpr,
PartitionInfos: partitionInfos,
}.Init(ctx, statsInfo, schema, names, 0)
}
func tryWhereIn2BatchPointGet(ctx sessionctx.Context, selStmt *ast.SelectStmt) *BatchPointGetPlan {
if selStmt.OrderBy != nil || selStmt.GroupBy != nil ||
selStmt.Limit != nil || selStmt.Having != nil || selStmt.Distinct ||
len(selStmt.WindowSpecs) > 0 {
return nil
}
// `expr1 in (1, 2) and expr2 in (1, 2)` isn't PatternInExpr, so it can't use tryWhereIn2BatchPointGet.
// (expr1, expr2) in ((1, 1), (2, 2)) can hit it.
in, ok := selStmt.Where.(*ast.PatternInExpr)
if !ok || in.Not || len(in.List) < 1 {
return nil
}
tblName, tblAlias := getSingleTableNameAndAlias(selStmt.From)
if tblName == nil {
return nil
}
tbl := tblName.TableInfo
if tbl == nil {
return nil
}
// Skip the optimization with partition selection.
if len(tblName.PartitionNames) > 0 {
return nil
}
for _, col := range tbl.Columns {
if col.IsGenerated() || col.State != model.StatePublic {
return nil
}
}
schema, names := buildSchemaFromFields(tblName.Schema, tbl, tblAlias, selStmt.Fields.Fields)
if schema == nil {
return nil
}
var (
handleCol *model.ColumnInfo
whereColNames []string
)
// SELECT * FROM t WHERE (key) in ((1), (2))
colExpr := in.Expr
if p, ok := colExpr.(*ast.ParenthesesExpr); ok {
colExpr = p.Expr
}
switch colName := colExpr.(type) {
case *ast.ColumnNameExpr:
if name := colName.Name.Table.L; name != "" && name != tblAlias.L {
return nil
}
// Try use handle
if tbl.PKIsHandle {
for _, col := range tbl.Columns {
if mysql.HasPriKeyFlag(col.GetFlag()) && col.Name.L == colName.Name.Name.L {
handleCol = col
whereColNames = append(whereColNames, col.Name.L)
break
}
}
}
if handleCol == nil {
// Downgrade to use unique index
whereColNames = append(whereColNames, colName.Name.Name.L)
}
case *ast.RowExpr:
for _, col := range colName.Values {
c, ok := col.(*ast.ColumnNameExpr)
if !ok {
return nil
}
if name := c.Name.Table.L; name != "" && name != tblAlias.L {
return nil
}
whereColNames = append(whereColNames, c.Name.Name.L)
}
default:
return nil
}
p := newBatchPointGetPlan(ctx, in, handleCol, tbl, schema, names, whereColNames, tblName.IndexHints)
if p == nil {
return nil
}
p.dbName = tblName.Schema.L
if p.dbName == "" {
p.dbName = ctx.GetSessionVars().CurrentDB
}
return p