/
stats.go
1526 lines (1444 loc) · 55.5 KB
/
stats.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 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"context"
"fmt"
"math"
"strings"
"github.com/pingcap/errors"
"github.com/wuhuizuo/tidb6/expression"
"github.com/wuhuizuo/tidb6/kv"
"github.com/wuhuizuo/tidb6/parser/ast"
"github.com/wuhuizuo/tidb6/parser/model"
"github.com/wuhuizuo/tidb6/parser/mysql"
"github.com/wuhuizuo/tidb6/planner/property"
"github.com/wuhuizuo/tidb6/planner/util"
"github.com/wuhuizuo/tidb6/sessionctx"
"github.com/wuhuizuo/tidb6/statistics"
"github.com/wuhuizuo/tidb6/types"
"github.com/wuhuizuo/tidb6/util/logutil"
"github.com/wuhuizuo/tidb6/util/mathutil"
"github.com/wuhuizuo/tidb6/util/ranger"
"go.uber.org/zap"
"golang.org/x/exp/slices"
)
func (p *basePhysicalPlan) StatsCount() float64 {
return p.stats.RowCount
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *LogicalTableDual) DeriveStats(_ []*property.StatsInfo, selfSchema *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if p.stats != nil {
return p.stats, nil
}
profile := &property.StatsInfo{
RowCount: float64(p.RowCount),
ColNDVs: make(map[int64]float64, selfSchema.Len()),
}
for _, col := range selfSchema.Columns {
profile.ColNDVs[col.UniqueID] = float64(p.RowCount)
}
p.stats = profile
return p.stats, nil
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *LogicalMemTable) DeriveStats(_ []*property.StatsInfo, selfSchema *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if p.stats != nil {
return p.stats, nil
}
statsTable := statistics.PseudoTable(p.TableInfo)
stats := &property.StatsInfo{
RowCount: float64(statsTable.Count),
ColNDVs: make(map[int64]float64, len(p.TableInfo.Columns)),
HistColl: statsTable.GenerateHistCollFromColumnInfo(p.TableInfo.Columns, p.schema.Columns),
StatsVersion: statistics.PseudoVersion,
}
for _, col := range selfSchema.Columns {
stats.ColNDVs[col.UniqueID] = float64(statsTable.Count)
}
p.stats = stats
return p.stats, nil
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *LogicalShow) DeriveStats(_ []*property.StatsInfo, selfSchema *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if p.stats != nil {
return p.stats, nil
}
// A fake count, just to avoid panic now.
p.stats = getFakeStats(selfSchema)
return p.stats, nil
}
func getFakeStats(schema *expression.Schema) *property.StatsInfo {
profile := &property.StatsInfo{
RowCount: 1,
ColNDVs: make(map[int64]float64, schema.Len()),
}
for _, col := range schema.Columns {
profile.ColNDVs[col.UniqueID] = 1
}
return profile
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *LogicalShowDDLJobs) DeriveStats(_ []*property.StatsInfo, selfSchema *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if p.stats != nil {
return p.stats, nil
}
// A fake count, just to avoid panic now.
p.stats = getFakeStats(selfSchema)
return p.stats, nil
}
// RecursiveDeriveStats4Test is a exporter just for test.
func RecursiveDeriveStats4Test(p LogicalPlan) (*property.StatsInfo, error) {
return p.recursiveDeriveStats(nil)
}
// GetStats4Test is a exporter just for test.
func GetStats4Test(p LogicalPlan) *property.StatsInfo {
return p.statsInfo()
}
func (p *baseLogicalPlan) recursiveDeriveStats(colGroups [][]*expression.Column) (*property.StatsInfo, error) {
childStats := make([]*property.StatsInfo, len(p.children))
childSchema := make([]*expression.Schema, len(p.children))
cumColGroups := p.self.ExtractColGroups(colGroups)
for i, child := range p.children {
childProfile, err := child.recursiveDeriveStats(cumColGroups)
if err != nil {
return nil, err
}
childStats[i] = childProfile
childSchema[i] = child.Schema()
}
return p.self.DeriveStats(childStats, p.self.Schema(), childSchema, colGroups)
}
// ExtractColGroups implements LogicalPlan ExtractColGroups interface.
func (p *baseLogicalPlan) ExtractColGroups(_ [][]*expression.Column) [][]*expression.Column {
return nil
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *baseLogicalPlan) DeriveStats(childStats []*property.StatsInfo, selfSchema *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if len(childStats) == 1 {
p.stats = childStats[0]
return p.stats, nil
}
if len(childStats) > 1 {
err := ErrInternal.GenWithStack("LogicalPlans with more than one child should implement their own DeriveStats().")
return nil, err
}
if p.stats != nil {
return p.stats, nil
}
profile := &property.StatsInfo{
RowCount: float64(1),
ColNDVs: make(map[int64]float64, selfSchema.Len()),
}
for _, col := range selfSchema.Columns {
profile.ColNDVs[col.UniqueID] = 1
}
p.stats = profile
return profile, nil
}
// getTotalRowCount returns the total row count, which is obtained when collecting colHist.
func getTotalRowCount(statsTbl *statistics.Table, colHist *statistics.Column) int64 {
if colHist.IsFullLoad() {
return int64(colHist.TotalRowCount())
}
// If colHist is not fully loaded, we may still get its total row count from other index/column stats.
for _, idx := range statsTbl.Indices {
if idx.IsFullLoad() && idx.LastUpdateVersion == colHist.LastUpdateVersion {
return int64(idx.TotalRowCount())
}
}
for _, col := range statsTbl.Columns {
if col.IsFullLoad() && col.LastUpdateVersion == colHist.LastUpdateVersion {
return int64(col.TotalRowCount())
}
}
return 0
}
// getColumnNDV computes estimated NDV of specified column using the original
// histogram of `DataSource` which is retrieved from storage(not the derived one).
func (ds *DataSource) getColumnNDV(colID int64) (ndv float64) {
hist, ok := ds.statisticTable.Columns[colID]
if ok && hist.IsStatsInitialized() {
ndv = float64(hist.Histogram.NDV)
// TODO: a better way to get the total row count derived from the last analyze.
analyzeCount := getTotalRowCount(ds.statisticTable, hist)
if analyzeCount > 0 {
factor := float64(ds.statisticTable.Count) / float64(analyzeCount)
ndv *= factor
}
} else {
ndv = float64(ds.statisticTable.Count) * distinctFactor
}
return ndv
}
func (ds *DataSource) getGroupNDVs(colGroups [][]*expression.Column) []property.GroupNDV {
if colGroups == nil {
return nil
}
tbl := ds.tableStats.HistColl
ndvs := make([]property.GroupNDV, 0, len(colGroups))
for idxID, idx := range tbl.Indices {
colsLen := len(tbl.Idx2ColumnIDs[idxID])
// tbl.Idx2ColumnIDs may only contain the prefix of index columns.
// But it may exceeds the total index since the index would contain the handle column if it's not a unique index.
// We append the handle at fillIndexPath.
if colsLen < len(idx.Info.Columns) {
continue
} else if colsLen > len(idx.Info.Columns) {
colsLen--
}
idxCols := make([]int64, colsLen)
copy(idxCols, tbl.Idx2ColumnIDs[idxID])
slices.Sort(idxCols)
for _, g := range colGroups {
// We only want those exact matches.
if len(g) != colsLen {
continue
}
match := true
for i, col := range g {
// Both slices are sorted according to UniqueID.
if col.UniqueID != idxCols[i] {
match = false
break
}
}
if match {
ndv := property.GroupNDV{
Cols: idxCols,
NDV: float64(idx.NDV),
}
ndvs = append(ndvs, ndv)
break
}
}
}
return ndvs
}
func (ds *DataSource) initStats(colGroups [][]*expression.Column) {
if ds.tableStats != nil {
// Reload GroupNDVs since colGroups may have changed.
ds.tableStats.GroupNDVs = ds.getGroupNDVs(colGroups)
return
}
if ds.statisticTable == nil {
ds.statisticTable = getStatsTable(ds.ctx, ds.tableInfo, ds.physicalTableID)
}
tableStats := &property.StatsInfo{
RowCount: float64(ds.statisticTable.Count),
ColNDVs: make(map[int64]float64, ds.schema.Len()),
HistColl: ds.statisticTable.GenerateHistCollFromColumnInfo(ds.Columns, ds.schema.Columns),
StatsVersion: ds.statisticTable.Version,
}
if ds.statisticTable.Pseudo {
tableStats.StatsVersion = statistics.PseudoVersion
}
for _, col := range ds.schema.Columns {
tableStats.ColNDVs[col.UniqueID] = ds.getColumnNDV(col.ID)
}
ds.tableStats = tableStats
ds.tableStats.GroupNDVs = ds.getGroupNDVs(colGroups)
ds.TblColHists = ds.statisticTable.ID2UniqueID(ds.TblCols)
}
func (ds *DataSource) deriveStatsByFilter(conds expression.CNFExprs, filledPaths []*util.AccessPath) *property.StatsInfo {
selectivity, nodes, err := ds.tableStats.HistColl.Selectivity(ds.ctx, conds, filledPaths)
if err != nil {
logutil.BgLogger().Debug("something wrong happened, use the default selectivity", zap.Error(err))
selectivity = SelectionFactor
}
stats := ds.tableStats.Scale(selectivity)
if ds.ctx.GetSessionVars().OptimizerSelectivityLevel >= 1 {
stats.HistColl = stats.HistColl.NewHistCollBySelectivity(ds.ctx, nodes)
}
return stats
}
// We bind logic of derivePathStats and tryHeuristics together. When some path matches the heuristic rule, we don't need
// to derive stats of subsequent paths. In this way we can save unnecessary computation of derivePathStats.
func (ds *DataSource) derivePathStatsAndTryHeuristics() error {
uniqueIdxsWithDoubleScan := make([]*util.AccessPath, 0, len(ds.possibleAccessPaths))
singleScanIdxs := make([]*util.AccessPath, 0, len(ds.possibleAccessPaths))
var (
selected, uniqueBest, refinedBest *util.AccessPath
isRefinedPath bool
)
for _, path := range ds.possibleAccessPaths {
if path.IsTablePath() {
err := ds.deriveTablePathStats(path, ds.pushedDownConds, false)
if err != nil {
return err
}
path.IsSingleScan = true
} else {
ds.deriveIndexPathStats(path, ds.pushedDownConds, false)
path.IsSingleScan = ds.isSingleScan(path.FullIdxCols, path.FullIdxColLens)
}
// Try some heuristic rules to select access path.
if len(path.Ranges) == 0 {
selected = path
break
}
if path.OnlyPointRange(ds.SCtx()) {
if path.IsTablePath() || path.Index.Unique {
if path.IsSingleScan {
selected = path
break
}
uniqueIdxsWithDoubleScan = append(uniqueIdxsWithDoubleScan, path)
}
} else if path.IsSingleScan {
singleScanIdxs = append(singleScanIdxs, path)
}
}
if selected == nil && len(uniqueIdxsWithDoubleScan) > 0 {
uniqueIdxAccessCols := make([]util.Col2Len, 0, len(uniqueIdxsWithDoubleScan))
for _, uniqueIdx := range uniqueIdxsWithDoubleScan {
uniqueIdxAccessCols = append(uniqueIdxAccessCols, uniqueIdx.GetCol2LenFromAccessConds())
// Find the unique index with the minimal number of ranges as `uniqueBest`.
if uniqueBest == nil || len(uniqueIdx.Ranges) < len(uniqueBest.Ranges) {
uniqueBest = uniqueIdx
}
}
// `uniqueBest` may not always be the best.
// ```
// create table t(a int, b int, c int, unique index idx_b(b), index idx_b_c(b, c));
// select b, c from t where b = 5 and c > 10;
// ```
// In the case, `uniqueBest` is `idx_b`. However, `idx_b_c` is better than `idx_b`.
// Hence, for each index in `singleScanIdxs`, we check whether it is better than some index in `uniqueIdxsWithDoubleScan`.
// If yes, the index is a refined one. We find the refined index with the minimal number of ranges as `refineBest`.
for _, singleScanIdx := range singleScanIdxs {
col2Len := singleScanIdx.GetCol2LenFromAccessConds()
for _, uniqueIdxCol2Len := range uniqueIdxAccessCols {
accessResult, comparable1 := util.CompareCol2Len(col2Len, uniqueIdxCol2Len)
if comparable1 && accessResult == 1 {
if refinedBest == nil || len(singleScanIdx.Ranges) < len(refinedBest.Ranges) {
refinedBest = singleScanIdx
}
}
}
}
// `refineBest` may not always be better than `uniqueBest`.
// ```
// create table t(a int, b int, c int, d int, unique index idx_a(a), unique index idx_b_c(b, c), unique index idx_b_c_a_d(b, c, a, d));
// select a, b, c from t where a = 1 and b = 2 and c in (1, 2, 3, 4, 5);
// ```
// In the case, `refinedBest` is `idx_b_c_a_d` and `uniqueBest` is `a`. `idx_b_c_a_d` needs to access five points while `idx_a`
// only needs one point access and one table access.
// Hence we should compare `len(refinedBest.Ranges)` and `2*len(uniqueBest.Ranges)` to select the better one.
if refinedBest != nil && (uniqueBest == nil || len(refinedBest.Ranges) < 2*len(uniqueBest.Ranges)) {
selected = refinedBest
isRefinedPath = true
} else {
selected = uniqueBest
}
}
// heuristic rule pruning other path should consider hint prefer.
// If no hints and some path matches a heuristic rule, just remove other possible paths.
if selected != nil {
// if user wanna tiFlash read, while current heuristic choose a TiKV path. so we shouldn't prune other paths.
keep := ds.preferStoreType&preferTiFlash != 0 && selected.StoreType != kv.TiFlash
if keep {
return nil
}
ds.possibleAccessPaths[0] = selected
ds.possibleAccessPaths = ds.possibleAccessPaths[:1]
if ds.ctx.GetSessionVars().StmtCtx.InVerboseExplain {
var tableName string
if ds.TableAsName.O == "" {
tableName = ds.tableInfo.Name.O
} else {
tableName = ds.TableAsName.O
}
if selected.IsTablePath() {
// TODO: primary key / handle / real name?
ds.ctx.GetSessionVars().StmtCtx.AppendNote(fmt.Errorf("handle of %s is selected since the path only has point ranges", tableName))
} else {
var sb strings.Builder
if selected.Index.Unique {
sb.WriteString("unique ")
}
sb.WriteString(fmt.Sprintf("index %s of %s is selected since the path", selected.Index.Name.O, tableName))
if isRefinedPath {
sb.WriteString(" only fetches limited number of rows")
} else {
sb.WriteString(" only has point ranges")
}
if selected.IsSingleScan {
sb.WriteString(" with single scan")
} else {
sb.WriteString(" with double scan")
}
ds.ctx.GetSessionVars().StmtCtx.AppendNote(errors.New(sb.String()))
}
}
}
return nil
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (ds *DataSource) DeriveStats(_ []*property.StatsInfo, _ *expression.Schema, _ []*expression.Schema, colGroups [][]*expression.Column) (*property.StatsInfo, error) {
if ds.stats != nil && len(colGroups) == 0 {
return ds.stats, nil
}
ds.initStats(colGroups)
if ds.stats != nil {
// Just reload the GroupNDVs.
selectivity := ds.stats.RowCount / ds.tableStats.RowCount
ds.stats = ds.tableStats.Scale(selectivity)
return ds.stats, nil
}
// PushDownNot here can convert query 'not (a != 1)' to 'a = 1'.
for i, expr := range ds.pushedDownConds {
ds.pushedDownConds[i] = expression.PushDownNot(ds.ctx, expr)
}
for _, path := range ds.possibleAccessPaths {
if path.IsTablePath() {
continue
}
err := ds.fillIndexPath(path, ds.pushedDownConds)
if err != nil {
return nil, err
}
}
// TODO: Can we move ds.deriveStatsByFilter after pruning by heuristics? In this way some computation can be avoided
// when ds.possibleAccessPaths are pruned.
ds.stats = ds.deriveStatsByFilter(ds.pushedDownConds, ds.possibleAccessPaths)
err := ds.derivePathStatsAndTryHeuristics()
if err != nil {
return nil, err
}
// Consider the IndexMergePath. Now, we just generate `IndexMergePath` in DNF case.
// Use allConds instread of pushedDownConds,
// because we want to use IndexMerge even if some expr cannot be pushed to TiKV.
// We will create new Selection for exprs that cannot be pushed in convertToIndexMergeScan.
indexMergeConds := make([]expression.Expression, 0, len(ds.allConds))
for _, expr := range ds.allConds {
indexMergeConds = append(indexMergeConds, expression.PushDownNot(ds.ctx, expr))
}
stmtCtx := ds.ctx.GetSessionVars().StmtCtx
isPossibleIdxMerge := len(indexMergeConds) > 0 && len(ds.possibleAccessPaths) > 1
sessionAndStmtPermission := (ds.ctx.GetSessionVars().GetEnableIndexMerge() || len(ds.indexMergeHints) > 0) && !stmtCtx.NoIndexMergeHint
// We current do not consider `IndexMergePath`:
// 1. If there is an index path.
// 2. TODO: If there exists exprs that cannot be pushed down. This is to avoid wrongly estRow of Selection added by rule_predicate_push_down.
needConsiderIndexMerge := true
if len(ds.indexMergeHints) == 0 {
for i := 1; i < len(ds.possibleAccessPaths); i++ {
if len(ds.possibleAccessPaths[i].AccessConds) != 0 {
needConsiderIndexMerge = false
break
}
}
if needConsiderIndexMerge {
// PushDownExprs() will append extra warnings, which is annoying. So we reset warnings here.
warnings := stmtCtx.GetWarnings()
_, remaining := expression.PushDownExprs(stmtCtx, indexMergeConds, ds.ctx.GetClient(), kv.UnSpecified)
stmtCtx.SetWarnings(warnings)
if len(remaining) != 0 {
needConsiderIndexMerge = false
}
}
}
if isPossibleIdxMerge && sessionAndStmtPermission && needConsiderIndexMerge && ds.tableInfo.TempTableType != model.TempTableLocal {
err := ds.generateAndPruneIndexMergePath(indexMergeConds, ds.indexMergeHints != nil)
if err != nil {
return nil, err
}
} else if len(ds.indexMergeHints) > 0 {
ds.indexMergeHints = nil
var msg string
if !isPossibleIdxMerge {
msg = "No available filter or available index."
} else if !sessionAndStmtPermission {
msg = "Got no_index_merge hint or tidb_enable_index_merge is off."
} else if ds.tableInfo.TempTableType == model.TempTableLocal {
msg = "Cannot use IndexMerge on temporary table."
}
msg = fmt.Sprintf("IndexMerge is inapplicable or disabled. %s", msg)
stmtCtx.AppendWarning(errors.Errorf(msg))
logutil.BgLogger().Debug(msg)
}
return ds.stats, nil
}
func (ds *DataSource) generateAndPruneIndexMergePath(indexMergeConds []expression.Expression, needPrune bool) error {
regularPathCount := len(ds.possibleAccessPaths)
// 1. Generate possible IndexMerge paths for `OR`.
err := ds.generateIndexMergeOrPaths(indexMergeConds)
if err != nil {
return err
}
// 2. Generate possible IndexMerge paths for `AND`.
indexMergeAndPath := ds.generateIndexMergeAndPaths(regularPathCount)
if indexMergeAndPath != nil {
ds.possibleAccessPaths = append(ds.possibleAccessPaths, indexMergeAndPath)
}
// 3. If needed, append a warning if no IndexMerge is generated.
// If without hints, it means that `enableIndexMerge` is true
if len(ds.indexMergeHints) == 0 {
return nil
}
// With hints and without generated IndexMerge paths
if regularPathCount == len(ds.possibleAccessPaths) {
ds.indexMergeHints = nil
ds.ctx.GetSessionVars().StmtCtx.AppendWarning(errors.Errorf("IndexMerge is inapplicable"))
return nil
}
// 4. If needPrune is true, prune non-IndexMerge paths.
// Do not need to consider the regular paths in find_best_task().
// So we can use index merge's row count as DataSource's row count.
if needPrune {
ds.possibleAccessPaths = ds.possibleAccessPaths[regularPathCount:]
minRowCount := ds.possibleAccessPaths[0].CountAfterAccess
for _, path := range ds.possibleAccessPaths {
if minRowCount < path.CountAfterAccess {
minRowCount = path.CountAfterAccess
}
}
if ds.stats.RowCount > minRowCount {
ds.stats = ds.tableStats.ScaleByExpectCnt(minRowCount)
}
}
return nil
}
// DeriveStats implements LogicalPlan DeriveStats interface.
func (ts *LogicalTableScan) DeriveStats(_ []*property.StatsInfo, _ *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (_ *property.StatsInfo, err error) {
ts.Source.initStats(nil)
// PushDownNot here can convert query 'not (a != 1)' to 'a = 1'.
for i, expr := range ts.AccessConds {
// TODO The expressions may be shared by TableScan and several IndexScans, there would be redundant
// `PushDownNot` function call in multiple `DeriveStats` then.
ts.AccessConds[i] = expression.PushDownNot(ts.ctx, expr)
}
ts.stats = ts.Source.deriveStatsByFilter(ts.AccessConds, nil)
// ts.Handle could be nil if PK is Handle, and PK column has been pruned.
// TODO: support clustered index.
if ts.HandleCols != nil {
// TODO: restrict mem usage of table ranges.
ts.Ranges, _, _, err = ranger.BuildTableRange(ts.AccessConds, ts.ctx, ts.HandleCols.GetCol(0).RetType, 0)
} else {
isUnsigned := false
if ts.Source.tableInfo.PKIsHandle {
if pkColInfo := ts.Source.tableInfo.GetPkColInfo(); pkColInfo != nil {
isUnsigned = mysql.HasUnsignedFlag(pkColInfo.GetFlag())
}
}
ts.Ranges = ranger.FullIntRange(isUnsigned)
}
if err != nil {
return nil, err
}
return ts.stats, nil
}
// DeriveStats implements LogicalPlan DeriveStats interface.
func (is *LogicalIndexScan) DeriveStats(_ []*property.StatsInfo, selfSchema *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
is.Source.initStats(nil)
for i, expr := range is.AccessConds {
is.AccessConds[i] = expression.PushDownNot(is.ctx, expr)
}
is.stats = is.Source.deriveStatsByFilter(is.AccessConds, nil)
if len(is.AccessConds) == 0 {
is.Ranges = ranger.FullRange()
}
is.IdxCols, is.IdxColLens = expression.IndexInfo2PrefixCols(is.Columns, selfSchema.Columns, is.Index)
is.FullIdxCols, is.FullIdxColLens = expression.IndexInfo2Cols(is.Columns, selfSchema.Columns, is.Index)
if !is.Index.Unique && !is.Index.Primary && len(is.Index.Columns) == len(is.IdxCols) {
handleCol := is.getPKIsHandleCol(selfSchema)
if handleCol != nil && !mysql.HasUnsignedFlag(handleCol.RetType.GetFlag()) {
is.IdxCols = append(is.IdxCols, handleCol)
is.IdxColLens = append(is.IdxColLens, types.UnspecifiedLength)
}
}
return is.stats, nil
}
// getIndexMergeOrPath generates all possible IndexMergeOrPaths.
func (ds *DataSource) generateIndexMergeOrPaths(filters []expression.Expression) error {
usedIndexCount := len(ds.possibleAccessPaths)
for i, cond := range filters {
sf, ok := cond.(*expression.ScalarFunction)
if !ok || sf.FuncName.L != ast.LogicOr {
continue
}
// shouldKeepCurrentFilter means the partial paths can't cover the current filter completely, so we must add
// the current filter into a Selection after partial paths.
shouldKeepCurrentFilter := false
var partialPaths = make([]*util.AccessPath, 0, usedIndexCount)
dnfItems := expression.FlattenDNFConditions(sf)
for _, item := range dnfItems {
cnfItems := expression.SplitCNFItems(item)
pushedDownCNFItems := make([]expression.Expression, 0, len(cnfItems))
for _, cnfItem := range cnfItems {
if expression.CanExprsPushDown(ds.ctx.GetSessionVars().StmtCtx,
[]expression.Expression{cnfItem},
ds.ctx.GetClient(),
kv.TiKV,
) {
pushedDownCNFItems = append(pushedDownCNFItems, cnfItem)
} else {
shouldKeepCurrentFilter = true
}
}
itemPaths := ds.accessPathsForConds(pushedDownCNFItems, usedIndexCount)
if len(itemPaths) == 0 {
partialPaths = nil
break
}
partialPath, err := ds.buildIndexMergePartialPath(itemPaths)
if err != nil {
return err
}
if partialPath == nil {
partialPaths = nil
break
}
partialPaths = append(partialPaths, partialPath)
}
// If all of the partialPaths use the same index, we will not use the indexMerge.
singlePath := true
for i := len(partialPaths) - 1; i >= 1; i-- {
if partialPaths[i].Index != partialPaths[i-1].Index {
singlePath = false
break
}
}
if singlePath {
continue
}
if len(partialPaths) > 1 {
possiblePath := ds.buildIndexMergeOrPath(filters, partialPaths, i, shouldKeepCurrentFilter)
if possiblePath == nil {
return nil
}
accessConds := make([]expression.Expression, 0, len(partialPaths))
for _, p := range partialPaths {
indexCondsForP := p.AccessConds[:]
indexCondsForP = append(indexCondsForP, p.IndexFilters...)
if len(indexCondsForP) > 0 {
accessConds = append(accessConds, expression.ComposeCNFCondition(ds.ctx, indexCondsForP...))
}
}
accessDNF := expression.ComposeDNFCondition(ds.ctx, accessConds...)
sel, _, err := ds.tableStats.HistColl.Selectivity(ds.ctx, []expression.Expression{accessDNF}, nil)
if err != nil {
logutil.BgLogger().Debug("something wrong happened, use the default selectivity", zap.Error(err))
sel = SelectionFactor
}
possiblePath.CountAfterAccess = sel * ds.tableStats.RowCount
ds.possibleAccessPaths = append(ds.possibleAccessPaths, possiblePath)
}
}
return nil
}
// isInIndexMergeHints returns true if the input index name is not excluded by the IndexMerge hints, which means either
// (1) there's no IndexMerge hint, (2) there's IndexMerge hint but no specified index names, or (3) the input index
// name is specified in the IndexMerge hints.
func (ds *DataSource) isInIndexMergeHints(name string) bool {
if len(ds.indexMergeHints) == 0 {
return true
}
for _, hint := range ds.indexMergeHints {
if hint.indexHint == nil || len(hint.indexHint.IndexNames) == 0 {
return true
}
for _, hintName := range hint.indexHint.IndexNames {
if strings.EqualFold(strings.ToLower(name), strings.ToLower(hintName.String())) {
return true
}
}
}
return false
}
// indexMergeHintsHasSpecifiedIdx returns true if there's IndexMerge hint, and it has specified index names.
func (ds *DataSource) indexMergeHintsHasSpecifiedIdx() bool {
for _, hint := range ds.indexMergeHints {
if hint.indexHint == nil || len(hint.indexHint.IndexNames) == 0 {
continue
}
if len(hint.indexHint.IndexNames) > 0 {
return true
}
}
return false
}
// indexMergeHintsHasSpecifiedIdx return true if the input index name is specified in the IndexMerge hint.
func (ds *DataSource) isSpecifiedInIndexMergeHints(name string) bool {
for _, hint := range ds.indexMergeHints {
if hint.indexHint == nil || len(hint.indexHint.IndexNames) == 0 {
continue
}
for _, hintName := range hint.indexHint.IndexNames {
if strings.EqualFold(strings.ToLower(name), strings.ToLower(hintName.String())) {
return true
}
}
}
return false
}
// accessPathsForConds generates all possible index paths for conditions.
func (ds *DataSource) accessPathsForConds(conditions []expression.Expression, usedIndexCount int) []*util.AccessPath {
var results = make([]*util.AccessPath, 0, usedIndexCount)
for i := 0; i < usedIndexCount; i++ {
path := &util.AccessPath{}
if ds.possibleAccessPaths[i].IsTablePath() {
if !ds.isInIndexMergeHints("primary") {
continue
}
if ds.tableInfo.IsCommonHandle {
path.IsCommonHandlePath = true
path.Index = ds.possibleAccessPaths[i].Index
} else {
path.IsIntHandlePath = true
}
err := ds.deriveTablePathStats(path, conditions, true)
if err != nil {
logutil.BgLogger().Debug("can not derive statistics of a path", zap.Error(err))
continue
}
var unsignedIntHandle bool
if path.IsIntHandlePath && ds.tableInfo.PKIsHandle {
if pkColInfo := ds.tableInfo.GetPkColInfo(); pkColInfo != nil {
unsignedIntHandle = mysql.HasUnsignedFlag(pkColInfo.GetFlag())
}
}
// If the path contains a full range, ignore it.
if ranger.HasFullRange(path.Ranges, unsignedIntHandle) {
continue
}
// If we have point or empty range, just remove other possible paths.
if len(path.Ranges) == 0 || path.OnlyPointRange(ds.SCtx()) {
if len(results) == 0 {
results = append(results, path)
} else {
results[0] = path
results = results[:1]
}
break
}
} else {
path.Index = ds.possibleAccessPaths[i].Index
if !ds.isInIndexMergeHints(path.Index.Name.L) {
continue
}
err := ds.fillIndexPath(path, conditions)
if err != nil {
logutil.BgLogger().Debug("can not derive statistics of a path", zap.Error(err))
continue
}
ds.deriveIndexPathStats(path, conditions, true)
// If the path contains a full range, ignore it.
if ranger.HasFullRange(path.Ranges, false) {
continue
}
// If we have empty range, or point range on unique index, just remove other possible paths.
if len(path.Ranges) == 0 || (path.OnlyPointRange(ds.SCtx()) && path.Index.Unique) {
if len(results) == 0 {
results = append(results, path)
} else {
results[0] = path
results = results[:1]
}
break
}
}
results = append(results, path)
}
return results
}
// buildIndexMergePartialPath chooses the best index path from all possible paths.
// Now we choose the index with minimal estimate row count.
func (ds *DataSource) buildIndexMergePartialPath(indexAccessPaths []*util.AccessPath) (*util.AccessPath, error) {
if len(indexAccessPaths) == 1 {
return indexAccessPaths[0], nil
}
minEstRowIndex := 0
minEstRow := math.MaxFloat64
for i := 0; i < len(indexAccessPaths); i++ {
rc := indexAccessPaths[i].CountAfterAccess
if len(indexAccessPaths[i].IndexFilters) > 0 {
rc = indexAccessPaths[i].CountAfterIndex
}
if rc < minEstRow {
minEstRowIndex = i
minEstRow = rc
}
}
return indexAccessPaths[minEstRowIndex], nil
}
// buildIndexMergeOrPath generates one possible IndexMergePath.
func (ds *DataSource) buildIndexMergeOrPath(
filters []expression.Expression,
partialPaths []*util.AccessPath,
current int,
shouldKeepCurrentFilter bool,
) *util.AccessPath {
indexMergePath := &util.AccessPath{PartialIndexPaths: partialPaths}
indexMergePath.TableFilters = append(indexMergePath.TableFilters, filters[:current]...)
indexMergePath.TableFilters = append(indexMergePath.TableFilters, filters[current+1:]...)
for _, path := range partialPaths {
// If any partial path contains table filters, we need to keep the whole DNF filter in the Selection.
if len(path.TableFilters) > 0 {
shouldKeepCurrentFilter = true
}
// If any partial path's index filter cannot be pushed to TiKV, we should keep the whole DNF filter.
if len(path.IndexFilters) != 0 && !expression.CanExprsPushDown(ds.ctx.GetSessionVars().StmtCtx, path.IndexFilters, ds.ctx.GetClient(), kv.TiKV) {
shouldKeepCurrentFilter = true
// Clear IndexFilter, the whole filter will be put in indexMergePath.TableFilters.
path.IndexFilters = nil
}
if len(path.TableFilters) != 0 && !expression.CanExprsPushDown(ds.ctx.GetSessionVars().StmtCtx, path.TableFilters, ds.ctx.GetClient(), kv.TiKV) {
shouldKeepCurrentFilter = true
path.TableFilters = nil
}
}
// Keep this filter as a part of table filters for safety if it has any parameter.
if expression.MaybeOverOptimized4PlanCache(ds.ctx, filters[current:current+1]) {
shouldKeepCurrentFilter = true
}
if shouldKeepCurrentFilter {
indexMergePath.TableFilters = append(indexMergePath.TableFilters, filters[current])
}
return indexMergePath
}
// generateIndexMergeAndPaths generates IndexMerge paths for `AND` (a.k.a. intersection type IndexMerge)
func (ds *DataSource) generateIndexMergeAndPaths(normalPathCnt int) *util.AccessPath {
// For now, we only consider intersection type IndexMerge when the index names are specified in the hints.
if !ds.indexMergeHintsHasSpecifiedIdx() {
return nil
}
// 1. Collect partial paths from normal paths.
var partialPaths []*util.AccessPath
for i := 0; i < normalPathCnt; i++ {
originalPath := ds.possibleAccessPaths[i]
// No need to consider table path as a partial path.
if ds.possibleAccessPaths[i].IsTablePath() {
continue
}
if !ds.isSpecifiedInIndexMergeHints(originalPath.Index.Name.L) {
continue
}
// If the path contains a full range, ignore it.
if ranger.HasFullRange(originalPath.Ranges, false) {
continue
}
newPath := originalPath.Clone()
partialPaths = append(partialPaths, newPath)
}
if len(partialPaths) < 2 {
return nil
}
// 2. Collect filters that can't be covered by the partial paths and deduplicate them.
finalFilters := make([]expression.Expression, 0)
partialFilters := make([]expression.Expression, 0, len(partialPaths))
hashCodeSet := make(map[string]struct{})
for _, path := range partialPaths {
// Classify filters into coveredConds and notCoveredConds.
coveredConds := make([]expression.Expression, 0, len(path.AccessConds)+len(path.IndexFilters))
notCoveredConds := make([]expression.Expression, 0, len(path.IndexFilters)+len(path.TableFilters))
// AccessConds can be covered by partial path.
coveredConds = append(coveredConds, path.AccessConds...)
for i, cond := range path.IndexFilters {
// IndexFilters can be covered by partial path if it can be pushed down to TiKV.
if !expression.CanExprsPushDown(ds.ctx.GetSessionVars().StmtCtx, []expression.Expression{cond}, ds.ctx.GetClient(), kv.TiKV) {
path.IndexFilters = append(path.IndexFilters[:i], path.IndexFilters[i+1:]...)
notCoveredConds = append(notCoveredConds, cond)
} else {
coveredConds = append(coveredConds, cond)
}
}
// TableFilters can't be covered by partial path.
notCoveredConds = append(notCoveredConds, path.TableFilters...)
// Record covered filters in hashCodeSet.
// Note that we only record filters that not appear in the notCoveredConds. It's possible that a filter appear
// in both coveredConds and notCoveredConds (e.g. because of prefix index). So we need this extra check to
// avoid wrong deduplication.
notCoveredHashCodeSet := make(map[string]struct{})
for _, cond := range notCoveredConds {
hashCode := string(cond.HashCode(ds.ctx.GetSessionVars().StmtCtx))
notCoveredHashCodeSet[hashCode] = struct{}{}
}
for _, cond := range coveredConds {
hashCode := string(cond.HashCode(ds.ctx.GetSessionVars().StmtCtx))
if _, ok := notCoveredHashCodeSet[hashCode]; !ok {
hashCodeSet[hashCode] = struct{}{}
}
}
finalFilters = append(finalFilters, notCoveredConds...)
partialFilters = append(partialFilters, coveredConds...)
}
// Remove covered filters from finalFilters and deduplicate finalFilters.
dedupedFinalFilters := make([]expression.Expression, 0, len(finalFilters))
for _, cond := range finalFilters {
hashCode := string(cond.HashCode(ds.ctx.GetSessionVars().StmtCtx))
if _, ok := hashCodeSet[hashCode]; !ok {
dedupedFinalFilters = append(dedupedFinalFilters, cond)
hashCodeSet[hashCode] = struct{}{}
}
}
// Keep these partial filters as a part of table filters for safety if there is any parameter.
if expression.MaybeOverOptimized4PlanCache(ds.ctx, partialFilters) {
dedupedFinalFilters = append(dedupedFinalFilters, partialFilters...)
}
// 3. Estimate the row count after partial paths.
sel, _, err := ds.tableStats.HistColl.Selectivity(ds.ctx, partialFilters, nil)
if err != nil {
logutil.BgLogger().Debug("something wrong happened, use the default selectivity", zap.Error(err))
sel = SelectionFactor
}
indexMergePath := &util.AccessPath{
PartialIndexPaths: partialPaths,
IndexMergeIsIntersection: true,
TableFilters: dedupedFinalFilters,
CountAfterAccess: sel * ds.tableStats.RowCount,
}
return indexMergePath
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *LogicalSelection) DeriveStats(childStats []*property.StatsInfo, _ *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if p.stats != nil {
return p.stats, nil
}
p.stats = childStats[0].Scale(SelectionFactor)
p.stats.GroupNDVs = nil
return p.stats, nil
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *LogicalUnionAll) DeriveStats(childStats []*property.StatsInfo, selfSchema *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if p.stats != nil {
return p.stats, nil
}
p.stats = &property.StatsInfo{
ColNDVs: make(map[int64]float64, selfSchema.Len()),
}
for _, childProfile := range childStats {
p.stats.RowCount += childProfile.RowCount
for _, col := range selfSchema.Columns {
p.stats.ColNDVs[col.UniqueID] += childProfile.ColNDVs[col.UniqueID]
}
}
return p.stats, nil
}
func deriveLimitStats(childProfile *property.StatsInfo, limitCount float64) *property.StatsInfo {
stats := &property.StatsInfo{
RowCount: math.Min(limitCount, childProfile.RowCount),
ColNDVs: make(map[int64]float64, len(childProfile.ColNDVs)),
}
for id, c := range childProfile.ColNDVs {
stats.ColNDVs[id] = math.Min(c, stats.RowCount)
}
return stats
}
// DeriveStats implement LogicalPlan DeriveStats interface.
func (p *LogicalLimit) DeriveStats(childStats []*property.StatsInfo, _ *expression.Schema, _ []*expression.Schema, _ [][]*expression.Column) (*property.StatsInfo, error) {
if p.stats != nil {
return p.stats, nil
}
p.stats = deriveLimitStats(childStats[0], float64(p.Count))