forked from pingcap/tidb
/
point_get_plan.go
1206 lines (1129 loc) · 34.9 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"bytes"
"fmt"
"github.com/pingcap/errors"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/opcode"
"github.com/pingcap/parser/terror"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/planner/property"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/types/parser_driver"
"github.com/pingcap/tidb/util/math"
"github.com/pingcap/tidb/util/plancodec"
"github.com/pingcap/tipb/go-tipb"
)
// 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 int64
HandleParam *driver.ParamMarkerExpr
IndexValues []types.Datum
IndexValueParams []*driver.ParamMarkerExpr
expr expression.Expression
ctx sessionctx.Context
UnsignedHandle bool
IsTableDual bool
Lock bool
outputNames []*types.FieldName
LockWaitTime int64
partitionColumnPos int
Columns []*model.ColumnInfo
}
type nameValuePair struct {
colName string
value types.Datum
param *driver.ParamMarkerExpr
}
// Init initializes PointGetPlan.
func (p PointGetPlan) Init(ctx sessionctx.Context, stats *property.StatsInfo, offset int, props ...*property.PhysicalProperty) *PointGetPlan {
p.basePlan = newBasePlan(ctx, plancodec.TypePointGet, offset)
p.stats = stats
p.Columns = ExpandVirtualColumn(p.Columns, p.schema, p.TblInfo.Columns)
return &p
}
// Schema implements the Plan interface.
func (p *PointGetPlan) Schema() *expression.Schema {
return p.schema
}
// 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 (p *PointGetPlan) attach2Task(...task) task {
return nil
}
// ToPB converts physical plan to tipb executor.
func (p *PointGetPlan) ToPB(ctx sessionctx.Context) (*tipb.Executor, error) {
return nil, nil
}
// ExplainInfo implements Plan interface.
func (p *PointGetPlan) ExplainInfo() string {
accessObject, operatorInfo := p.AccessObject(), 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(), p.OperatorInfo(true)
if len(operatorInfo) == 0 {
return accessObject
}
return accessObject + ", " + operatorInfo
}
// AccessObject implements dataAccesser interface.
func (p *PointGetPlan) AccessObject() string {
buffer := bytes.NewBufferString("")
tblName := p.TblInfo.Name.O
fmt.Fprintf(buffer, "table:%s", tblName)
if p.PartitionInfo != nil {
fmt.Fprintf(buffer, ", partition:%s", p.PartitionInfo.Name.L)
}
if p.IndexInfo != nil {
buffer.WriteString(", index:" + p.IndexInfo.Name.O + "(")
for i, idxCol := range p.IndexInfo.Columns {
buffer.WriteString(idxCol.Name.O)
if i+1 < len(p.IndexInfo.Columns) {
buffer.WriteString(", ")
}
}
buffer.WriteString(")")
}
return buffer.String()
}
// OperatorInfo implements dataAccesser interface.
func (p *PointGetPlan) OperatorInfo(normalized bool) string {
buffer := bytes.NewBufferString("")
if p.IndexInfo == nil {
if normalized {
fmt.Fprintf(buffer, "handle:?, ")
} else {
if p.UnsignedHandle {
fmt.Fprintf(buffer, "handle:%d, ", uint64(p.Handle))
} else {
fmt.Fprintf(buffer, "handle:%d, ", p.Handle)
}
}
}
if p.Lock {
fmt.Fprintf(buffer, "lock, ")
}
if buffer.Len() >= 2 {
buffer.Truncate(buffer.Len() - 2)
}
return buffer.String()
}
// GetChildReqProps gets the required property by child index.
func (p *PointGetPlan) GetChildReqProps(idx int) *property.PhysicalProperty {
return nil
}
// StatsCount will return the the RowCount of property.StatsInfo for this plan.
func (p *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 (p *PointGetPlan) Children() []PhysicalPlan {
return nil
}
// SetChildren sets the children for the plan.
func (p *PointGetPlan) SetChildren(...PhysicalPlan) {}
// SetChild sets a specific child for the plan.
func (p *PointGetPlan) SetChild(i int, child 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
}
// GetCost returns cost of the PointGetPlan.
func (p *PointGetPlan) GetCost(cols []*expression.Column) float64 {
sessVars := p.ctx.GetSessionVars()
var rowSize float64
cost := 0.0
if p.IndexInfo == nil {
rowSize = p.stats.HistColl.GetTableAvgRowSize(p.ctx, cols, kv.TiKV, true)
} else {
rowSize = p.stats.HistColl.GetIndexAvgRowSize(p.ctx, cols, p.IndexInfo.Unique)
}
cost += rowSize * sessVars.NetworkFactor
cost += sessVars.SeekFactor
cost /= float64(sessVars.DistSQLScanConcurrency)
return cost
}
// 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
Handles []int64
HandleParams []*driver.ParamMarkerExpr
IndexValues [][]types.Datum
IndexValueParams [][]*driver.ParamMarkerExpr
PartitionColPos int
KeepOrder bool
Desc bool
Lock bool
LockWaitTime int64
Columns []*model.ColumnInfo
}
// 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 (p *BatchPointGetPlan) attach2Task(...task) task {
return nil
}
// ToPB converts physical plan to tipb executor.
func (p *BatchPointGetPlan) ToPB(ctx sessionctx.Context) (*tipb.Executor, error) {
return nil, nil
}
// ExplainInfo implements Plan interface.
func (p *BatchPointGetPlan) ExplainInfo() string {
return p.AccessObject() + ", " + p.OperatorInfo(false)
}
// ExplainNormalizedInfo implements Plan interface.
func (p *BatchPointGetPlan) ExplainNormalizedInfo() string {
return p.AccessObject() + ", " + p.OperatorInfo(true)
}
// AccessObject implements physicalScan interface.
func (p *BatchPointGetPlan) AccessObject() string {
buffer := bytes.NewBufferString("")
tblName := p.TblInfo.Name.O
fmt.Fprintf(buffer, "table:%s", tblName)
if p.IndexInfo != nil {
buffer.WriteString(", index:" + p.IndexInfo.Name.O + "(")
for i, idxCol := range p.IndexInfo.Columns {
buffer.WriteString(idxCol.Name.O)
if i+1 < len(p.IndexInfo.Columns) {
buffer.WriteString(", ")
}
}
buffer.WriteString(")")
}
return buffer.String()
}
// OperatorInfo implements dataAccesser interface.
func (p *BatchPointGetPlan) OperatorInfo(normalized bool) string {
buffer := bytes.NewBufferString("")
if p.IndexInfo == nil {
if normalized {
fmt.Fprintf(buffer, "handle:?, ")
} else {
fmt.Fprintf(buffer, "handle:%v, ", p.Handles)
}
}
fmt.Fprintf(buffer, "keep order:%v, ", p.KeepOrder)
fmt.Fprintf(buffer, "desc:%v, ", p.Desc)
if p.Lock {
fmt.Fprintf(buffer, "lock, ")
}
if buffer.Len() >= 2 {
buffer.Truncate(buffer.Len() - 2)
}
return buffer.String()
}
// GetChildReqProps gets the required property by child index.
func (p *BatchPointGetPlan) GetChildReqProps(idx 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 (p *BatchPointGetPlan) Children() []PhysicalPlan {
return nil
}
// SetChildren sets the children for the plan.
func (p *BatchPointGetPlan) SetChildren(...PhysicalPlan) {}
// SetChild sets a specific child for the plan.
func (p *BatchPointGetPlan) SetChild(i int, child 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
}
// GetCost returns cost of the PointGetPlan.
func (p *BatchPointGetPlan) GetCost(cols []*expression.Column) float64 {
sessVars := p.ctx.GetSessionVars()
var rowSize, rowCount float64
cost := 0.0
if p.IndexInfo == nil {
rowCount = float64(len(p.Handles))
rowSize = p.stats.HistColl.GetTableAvgRowSize(p.ctx, cols, kv.TiKV, true)
} else {
rowCount = float64(len(p.IndexValues))
rowSize = p.stats.HistColl.GetIndexAvgRowSize(p.ctx, cols, p.IndexInfo.Unique)
}
cost += rowCount * rowSize * sessVars.NetworkFactor
cost += rowCount * sessVars.SeekFactor
cost /= float64(sessVars.DistSQLScanConcurrency)
return cost
}
// TryFastPlan tries to use the PointGetPlan for the query.
func TryFastPlan(ctx sessionctx.Context, node ast.Node) Plan {
ctx.GetSessionVars().PlanID = 0
ctx.GetSessionVars().PlanColumnID = 0
switch x := node.(type) {
case *ast.SelectStmt:
// 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 nil
}
fp.Lock, fp.LockWaitTime = getLockWaitTime(ctx, x.LockTp)
return fp
}
if fp := tryPointGetPlan(ctx, x); fp != nil {
if checkFastPlanPrivilege(ctx, fp.dbName, fp.TblInfo.Name.L, mysql.SelectPriv) != nil {
return nil
}
if fp.IsTableDual {
tableDual := PhysicalTableDual{}
tableDual.names = fp.outputNames
tableDual.SetSchema(fp.Schema())
return tableDual.Init(ctx, &property.StatsInfo{}, 0)
}
fp.Lock, fp.LockWaitTime = getLockWaitTime(ctx, x.LockTp)
return fp
}
case *ast.UpdateStmt:
return tryUpdatePointPlan(ctx, x)
case *ast.DeleteStmt:
return tryDeletePointPlan(ctx, x)
}
return nil
}
func getLockWaitTime(ctx sessionctx.Context, lockTp ast.SelectLockType) (lock bool, waitTime int64) {
if lockTp == ast.SelectLockForUpdate || lockTp == ast.SelectLockForUpdateNoWait {
// 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 lockTp == ast.SelectLockForUpdateNoWait {
waitTime = kv.LockNoWait
}
}
}
return
}
func newBatchPointGetPlan(
ctx sessionctx.Context, patternInExpr *ast.PatternInExpr,
handleCol *model.ColumnInfo, tbl *model.TableInfo, schema *expression.Schema,
names []*types.FieldName, whereColNames []string,
) *BatchPointGetPlan {
statsInfo := &property.StatsInfo{RowCount: float64(len(patternInExpr.List))}
partitionColName := getHashPartitionColumnName(ctx, tbl)
if tbl.GetPartitionInfo() != nil && partitionColName == nil {
return nil
}
if handleCol != nil {
var handles = make([]int64, len(patternInExpr.List))
var handleParams = make([]*driver.ParamMarkerExpr, 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 param *driver.ParamMarkerExpr
switch x := item.(type) {
case *driver.ValueExpr:
d = x.Datum
case *driver.ParamMarkerExpr:
d = x.Datum
param = x
default:
return nil
}
if d.IsNull() {
return nil
}
intDatum, err := d.ConvertTo(ctx.GetSessionVars().StmtCtx, &handleCol.FieldType)
if err != nil {
return nil
}
// The converted result must be same as original datum
cmp, err := intDatum.CompareDatum(ctx.GetSessionVars().StmtCtx, &d)
if err != nil || cmp != 0 {
return nil
}
handles[i] = intDatum.GetInt64()
handleParams[i] = param
}
return BatchPointGetPlan{
TblInfo: tbl,
Handles: handles,
HandleParams: handleParams,
}.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))
for _, idxInfo := range tbl.Indices {
if !idxInfo.Unique || idxInfo.State != model.StatePublic {
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
}
indexValues := make([][]types.Datum, len(patternInExpr.List))
indexValueParams := make([][]*driver.ParamMarkerExpr, 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 values []types.Datum
var valuesParams []*driver.ParamMarkerExpr
switch x := item.(type) {
case *ast.RowExpr:
// The `len(values) == len(valuesParams)` should be satisfied in this mode
values = make([]types.Datum, len(x.Values))
valuesParams = make([]*driver.ParamMarkerExpr, len(x.Values))
for index, inner := range x.Values {
permIndex := permutations[index]
switch innerX := inner.(type) {
case *driver.ValueExpr:
values[permIndex] = innerX.Datum
case *driver.ParamMarkerExpr:
values[permIndex] = innerX.Datum
valuesParams[permIndex] = innerX
default:
return nil
}
}
case *driver.ValueExpr:
values = []types.Datum{x.Datum}
case *driver.ParamMarkerExpr:
values = []types.Datum{x.Datum}
valuesParams = []*driver.ParamMarkerExpr{x}
default:
return nil
}
indexValues[i] = values
indexValueParams[i] = valuesParams
}
return BatchPointGetPlan{
TblInfo: tbl,
IndexInfo: matchIdxInfo,
IndexValues: indexValues,
IndexValueParams: indexValueParams,
PartitionColPos: getPartitionColumnPos(matchIdxInfo, partitionColName),
}.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 ||
len(selStmt.WindowSpecs) > 0 {
return nil
}
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
}
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.Flag) && 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)
if p == nil {
return nil
}
p.dbName = tblName.Schema.L
if p.dbName == "" {
p.dbName = ctx.GetSessionVars().CurrentDB
}
return p
}
// tryPointGetPlan determine if the SelectStmt can use a PointGetPlan.
// Returns nil if not applicable.
// To use the PointGetPlan the following rules must be satisfied:
// 1. For the limit clause, the count should at least 1 and the offset is 0.
// 2. It must be a single table select.
// 3. All the columns must be public and generated.
// 4. The condition is an access path that the range is a unique key.
func tryPointGetPlan(ctx sessionctx.Context, selStmt *ast.SelectStmt) *PointGetPlan {
if selStmt.Having != nil {
return nil
} else if selStmt.Limit != nil {
count, offset, err := extractLimitCountOffset(ctx, selStmt.Limit)
if err != nil || count == 0 || offset > 0 {
return nil
}
}
tblName, tblAlias := getSingleTableNameAndAlias(selStmt.From)
if tblName == nil {
return nil
}
tbl := tblName.TableInfo
if tbl == nil {
return nil
}
pi := tbl.GetPartitionInfo()
for _, col := range tbl.Columns {
// Do not handle generated columns.
if col.IsGenerated() {
return nil
}
// Only handle tables that all columns are public.
if col.State != model.StatePublic {
return nil
}
}
pairs := make([]nameValuePair, 0, 4)
pairs = getNameValuePairs(pairs, tblAlias, selStmt.Where)
if pairs == nil {
return nil
}
var partitionInfo *model.PartitionDefinition
var pos int
if pi != nil {
if pi.Type != model.PartitionTypeHash {
return nil
}
partitionInfo, pos = getPartitionInfo(ctx, tbl, pairs)
if partitionInfo == nil {
return nil
}
}
handlePair, fieldType := findPKHandle(tbl, pairs)
if handlePair.value.Kind() != types.KindNull && len(pairs) == 1 {
schema, names := buildSchemaFromFields(tblName.Schema, tbl, tblAlias, selStmt.Fields.Fields)
if schema == nil {
return nil
}
dbName := tblName.Schema.L
if dbName == "" {
dbName = ctx.GetSessionVars().CurrentDB
}
p := newPointGetPlan(ctx, dbName, schema, tbl, names)
intDatum, err := handlePair.value.ConvertTo(ctx.GetSessionVars().StmtCtx, fieldType)
if err != nil {
if terror.ErrorEqual(types.ErrOverflow, err) {
p.IsTableDual = true
return p
}
// some scenarios cast to int with error, but we may use this value in point get
if !terror.ErrorEqual(types.ErrTruncatedWrongVal, err) {
return nil
}
}
cmp, err := intDatum.CompareDatum(ctx.GetSessionVars().StmtCtx, &handlePair.value)
if err != nil {
return nil
} else if cmp != 0 {
p.IsTableDual = true
return p
}
p.Handle = intDatum.GetInt64()
p.UnsignedHandle = mysql.HasUnsignedFlag(fieldType.Flag)
p.HandleParam = handlePair.param
p.PartitionInfo = partitionInfo
return p
}
for _, idxInfo := range tbl.Indices {
if !idxInfo.Unique {
continue
}
if idxInfo.State != model.StatePublic {
continue
}
idxValues, idxValueParams := getIndexValues(idxInfo, pairs)
if idxValues == nil {
continue
}
schema, names := buildSchemaFromFields(tblName.Schema, tbl, tblAlias, selStmt.Fields.Fields)
if schema == nil {
return nil
}
dbName := tblName.Schema.L
if dbName == "" {
dbName = ctx.GetSessionVars().CurrentDB
}
p := newPointGetPlan(ctx, dbName, schema, tbl, names)
p.IndexInfo = idxInfo
p.IndexValues = idxValues
p.IndexValueParams = idxValueParams
p.PartitionInfo = partitionInfo
if p.PartitionInfo != nil {
p.partitionColumnPos = findPartitionIdx(idxInfo, pos, pairs)
}
return p
}
return nil
}
func newPointGetPlan(ctx sessionctx.Context, dbName string, schema *expression.Schema, tbl *model.TableInfo, names []*types.FieldName) *PointGetPlan {
p := &PointGetPlan{
basePlan: newBasePlan(ctx, plancodec.TypePointGet, 0),
dbName: dbName,
schema: schema,
TblInfo: tbl,
outputNames: names,
LockWaitTime: ctx.GetSessionVars().LockWaitTimeout,
}
ctx.GetSessionVars().StmtCtx.Tables = []stmtctx.TableEntry{{DB: dbName, Table: tbl.Name.L}}
return p
}
func checkFastPlanPrivilege(ctx sessionctx.Context, dbName, tableName string, checkTypes ...mysql.PrivilegeType) error {
pm := privilege.GetPrivilegeManager(ctx)
if pm == nil {
return nil
}
for _, checkType := range checkTypes {
if !pm.RequestVerification(ctx.GetSessionVars().ActiveRoles, dbName, tableName, "", checkType) {
return errors.New("privilege check fail")
}
}
return nil
}
func buildSchemaFromFields(
dbName model.CIStr,
tbl *model.TableInfo,
tblName model.CIStr,
fields []*ast.SelectField,
) (
*expression.Schema,
[]*types.FieldName,
) {
columns := make([]*expression.Column, 0, len(tbl.Columns)+1)
names := make([]*types.FieldName, 0, len(tbl.Columns)+1)
if len(fields) > 0 {
for _, field := range fields {
if field.WildCard != nil {
if field.WildCard.Table.L != "" && field.WildCard.Table.L != tblName.L {
return nil, nil
}
for _, col := range tbl.Columns {
names = append(names, &types.FieldName{
DBName: dbName,
OrigTblName: tbl.Name,
TblName: tblName,
ColName: col.Name,
})
columns = append(columns, colInfoToColumn(col, len(columns)))
}
continue
}
colNameExpr, ok := field.Expr.(*ast.ColumnNameExpr)
if !ok {
return nil, nil
}
if colNameExpr.Name.Table.L != "" && colNameExpr.Name.Table.L != tblName.L {
return nil, nil
}
col := findCol(tbl, colNameExpr.Name)
if col == nil {
return nil, nil
}
asName := col.Name
if field.AsName.L != "" {
asName = field.AsName
}
names = append(names, &types.FieldName{
DBName: dbName,
OrigTblName: tbl.Name,
TblName: tblName,
ColName: asName,
})
columns = append(columns, colInfoToColumn(col, len(columns)))
}
return expression.NewSchema(columns...), names
}
// fields len is 0 for update and delete.
for _, col := range tbl.Columns {
names = append(names, &types.FieldName{
DBName: dbName,
OrigTblName: tbl.Name,
TblName: tblName,
ColName: col.Name,
})
column := colInfoToColumn(col, len(columns))
columns = append(columns, column)
}
schema := expression.NewSchema(columns...)
return schema, names
}
// getSingleTableNameAndAlias return the ast node of queried table name and the alias string.
// `tblName` is `nil` if there are multiple tables in the query.
// `tblAlias` will be the real table name if there is no table alias in the query.
func getSingleTableNameAndAlias(tableRefs *ast.TableRefsClause) (tblName *ast.TableName, tblAlias model.CIStr) {
if tableRefs == nil || tableRefs.TableRefs == nil || tableRefs.TableRefs.Right != nil {
return nil, tblAlias
}
tblSrc, ok := tableRefs.TableRefs.Left.(*ast.TableSource)
if !ok {
return nil, tblAlias
}
tblName, ok = tblSrc.Source.(*ast.TableName)
if !ok {
return nil, tblAlias
}
tblAlias = tblSrc.AsName
if tblSrc.AsName.L == "" {
tblAlias = tblName.Name
}
return tblName, tblAlias
}
// getNameValuePairs extracts `column = constant/paramMarker` conditions from expr as name value pairs.
func getNameValuePairs(nvPairs []nameValuePair, tblName model.CIStr, expr ast.ExprNode) []nameValuePair {
binOp, ok := expr.(*ast.BinaryOperationExpr)
if !ok {
return nil
}
if binOp.Op == opcode.LogicAnd {
nvPairs = getNameValuePairs(nvPairs, tblName, binOp.L)
if nvPairs == nil {
return nil
}
nvPairs = getNameValuePairs(nvPairs, tblName, binOp.R)
if nvPairs == nil {
return nil
}
return nvPairs
} else if binOp.Op == opcode.EQ {
var d types.Datum
var colName *ast.ColumnNameExpr
var param *driver.ParamMarkerExpr
var ok bool
if colName, ok = binOp.L.(*ast.ColumnNameExpr); ok {
switch x := binOp.R.(type) {
case *driver.ValueExpr:
d = x.Datum
case *driver.ParamMarkerExpr:
d = x.Datum
param = x
}
} else if colName, ok = binOp.R.(*ast.ColumnNameExpr); ok {
switch x := binOp.L.(type) {
case *driver.ValueExpr:
d = x.Datum
case *driver.ParamMarkerExpr:
d = x.Datum
param = x
}
} else {
return nil
}
if d.IsNull() {
return nil
}
if colName.Name.Table.L != "" && colName.Name.Table.L != tblName.L {
return nil
}
return append(nvPairs, nameValuePair{colName: colName.Name.Name.L, value: d, param: param})
}
return nil
}
func findPKHandle(tblInfo *model.TableInfo, pairs []nameValuePair) (handlePair nameValuePair, fieldType *types.FieldType) {
if !tblInfo.PKIsHandle {
rowIDIdx := findInPairs("_tidb_rowid", pairs)
if rowIDIdx != -1 {
return pairs[rowIDIdx], types.NewFieldType(mysql.TypeLonglong)
}
return handlePair, nil
}
for _, col := range tblInfo.Columns {
if mysql.HasPriKeyFlag(col.Flag) {
i := findInPairs(col.Name.L, pairs)
if i == -1 {
return handlePair, nil
}
return pairs[i], &col.FieldType
}
}
return handlePair, nil
}
func getIndexValues(idxInfo *model.IndexInfo, pairs []nameValuePair) ([]types.Datum, []*driver.ParamMarkerExpr) {
idxValues := make([]types.Datum, 0, 4)
idxValueParams := make([]*driver.ParamMarkerExpr, 0, 4)
if len(idxInfo.Columns) != len(pairs) {
return nil, nil
}
if idxInfo.HasPrefixIndex() {
return nil, nil
}
for _, idxCol := range idxInfo.Columns {
i := findInPairs(idxCol.Name.L, pairs)
if i == -1 {
return nil, nil
}
idxValues = append(idxValues, pairs[i].value)
idxValueParams = append(idxValueParams, pairs[i].param)
}
if len(idxValues) > 0 {
return idxValues, idxValueParams
}
return nil, nil
}
func findInPairs(colName string, pairs []nameValuePair) int {
for i, pair := range pairs {
if pair.colName == colName {
return i
}
}
return -1
}
func tryUpdatePointPlan(ctx sessionctx.Context, updateStmt *ast.UpdateStmt) Plan {
selStmt := &ast.SelectStmt{
Fields: &ast.FieldList{},
From: updateStmt.TableRefs,
Where: updateStmt.Where,
OrderBy: updateStmt.Order,
Limit: updateStmt.Limit,
}
pointGet := tryPointGetPlan(ctx, selStmt)
if pointGet != nil {
if pointGet.IsTableDual {
return PhysicalTableDual{
names: pointGet.outputNames,
}.Init(ctx, &property.StatsInfo{}, 0)
}
if ctx.GetSessionVars().TxnCtx.IsPessimistic {
pointGet.Lock, pointGet.LockWaitTime = getLockWaitTime(ctx, ast.SelectLockForUpdate)
}
return buildPointUpdatePlan(ctx, pointGet, pointGet.dbName, pointGet.TblInfo, updateStmt)
}
batchPointGet := tryWhereIn2BatchPointGet(ctx, selStmt)
if batchPointGet != nil {
if ctx.GetSessionVars().TxnCtx.IsPessimistic {
batchPointGet.Lock, batchPointGet.LockWaitTime = getLockWaitTime(ctx, ast.SelectLockForUpdate)
}
return buildPointUpdatePlan(ctx, batchPointGet, batchPointGet.dbName, batchPointGet.TblInfo, updateStmt)
}
return nil
}
func buildPointUpdatePlan(ctx sessionctx.Context, pointPlan PhysicalPlan, dbName string, tbl *model.TableInfo, updateStmt *ast.UpdateStmt) Plan {
if checkFastPlanPrivilege(ctx, dbName, tbl.Name.L, mysql.SelectPriv, mysql.UpdatePriv) != nil {