forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtable.go
1626 lines (1526 loc) · 51.6 KB
/
table.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 statistics
import (
"fmt"
"math"
"strings"
"sync"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/planner/util/debugtrace"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/mathutil"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/tracing"
"go.uber.org/atomic"
"go.uber.org/zap"
"golang.org/x/exp/slices"
)
const (
pseudoEqualRate = 1000
pseudoLessRate = 3
pseudoBetweenRate = 40
pseudoColSize = 8.0
outOfRangeBetweenRate = 100
)
const (
// PseudoVersion means the pseudo statistics version is 0.
PseudoVersion uint64 = 0
// PseudoRowCount export for other pkg to use.
// When we haven't analyzed a table, we use pseudo statistics to estimate costs.
// It has row count 10000, equal condition selects 1/1000 of total rows, less condition selects 1/3 of total rows,
// between condition selects 1/40 of total rows.
PseudoRowCount = 10000
)
// Table represents statistics for a table.
type Table struct {
ExtendedStats *ExtendedStatsColl
Name string
HistColl
Version uint64
// TblInfoUpdateTS is the UpdateTS of the TableInfo used when filling this struct.
// It is the schema version of the corresponding table. It is used to skip redundant
// loading of stats, i.e, if the cached stats is already update-to-date with mysql.stats_xxx tables,
// and the schema of the table does not change, we don't need to load the stats for this
// table again.
TblInfoUpdateTS uint64
}
// ExtendedStatsItem is the cached item of a mysql.stats_extended record.
type ExtendedStatsItem struct {
StringVals string
ColIDs []int64
ScalarVals float64
Tp uint8
}
// ExtendedStatsColl is a collection of cached items for mysql.stats_extended records.
type ExtendedStatsColl struct {
Stats map[string]*ExtendedStatsItem
LastUpdateVersion uint64
}
// NewExtendedStatsColl allocate an ExtendedStatsColl struct.
func NewExtendedStatsColl() *ExtendedStatsColl {
return &ExtendedStatsColl{Stats: make(map[string]*ExtendedStatsItem)}
}
const (
// ExtendedStatsInited is the status for extended stats which are just registered but have not been analyzed yet.
ExtendedStatsInited uint8 = iota
// ExtendedStatsAnalyzed is the status for extended stats which have been collected in analyze.
ExtendedStatsAnalyzed
// ExtendedStatsDeleted is the status for extended stats which were dropped. These "deleted" records would be removed from storage by GCStats().
ExtendedStatsDeleted
)
// HistColl is a collection of histogram. It collects enough information for plan to calculate the selectivity.
type HistColl struct {
Columns map[int64]*Column
Indices map[int64]*Index
// Idx2ColumnIDs maps the index id to its column ids. It's used to calculate the selectivity in planner.
Idx2ColumnIDs map[int64][]int64
// ColID2IdxIDs maps the column id to a list index ids whose first column is it. It's used to calculate the selectivity in planner.
ColID2IdxIDs map[int64][]int64
PhysicalID int64
// TODO: add AnalyzeCount here
RealtimeCount int64 // RealtimeCount is the current table row count, maintained by applying stats delta based on AnalyzeCount.
ModifyCount int64 // Total modify count in a table.
// HavePhysicalID is true means this HistColl is from single table and have its ID's information.
// The physical id is used when try to load column stats from storage.
HavePhysicalID bool
Pseudo bool
}
// TableMemoryUsage records tbl memory usage
type TableMemoryUsage struct {
ColumnsMemUsage map[int64]CacheItemMemoryUsage
IndicesMemUsage map[int64]CacheItemMemoryUsage
TableID int64
TotalMemUsage int64
}
// TotalIdxTrackingMemUsage returns total indices' tracking memory usage
func (t *TableMemoryUsage) TotalIdxTrackingMemUsage() (sum int64) {
for _, idx := range t.IndicesMemUsage {
sum += idx.TrackingMemUsage()
}
return sum
}
// TotalColTrackingMemUsage returns total columns' tracking memory usage
func (t *TableMemoryUsage) TotalColTrackingMemUsage() (sum int64) {
for _, col := range t.ColumnsMemUsage {
sum += col.TrackingMemUsage()
}
return sum
}
// TotalTrackingMemUsage return total tracking memory usage
func (t *TableMemoryUsage) TotalTrackingMemUsage() int64 {
return t.TotalIdxTrackingMemUsage() + t.TotalColTrackingMemUsage()
}
// TableCacheItem indicates the unit item stored in statsCache, eg: Column/Index
type TableCacheItem interface {
ItemID() int64
MemoryUsage() CacheItemMemoryUsage
IsAllEvicted() bool
dropCMS()
dropTopN()
dropHist()
isStatsInitialized() bool
getEvictedStatus() int
statsVer() int64
isCMSExist() bool
}
// DropEvicted drop stats for table column/index
func DropEvicted(item TableCacheItem) {
if !item.isStatsInitialized() {
return
}
switch item.getEvictedStatus() {
case allLoaded:
if item.isCMSExist() && item.statsVer() < Version2 {
item.dropCMS()
return
}
// For stats version2, there is no cms thus we directly drop topn
item.dropTopN()
return
case onlyCmsEvicted:
item.dropTopN()
return
case onlyHistRemained:
item.dropHist()
return
default:
return
}
}
// CacheItemMemoryUsage indicates the memory usage of TableCacheItem
type CacheItemMemoryUsage interface {
ItemID() int64
TotalMemoryUsage() int64
TrackingMemUsage() int64
HistMemUsage() int64
TopnMemUsage() int64
CMSMemUsage() int64
}
// ColumnMemUsage records column memory usage
type ColumnMemUsage struct {
ColumnID int64
HistogramMemUsage int64
CMSketchMemUsage int64
FMSketchMemUsage int64
TopNMemUsage int64
TotalMemUsage int64
}
// TotalMemoryUsage implements CacheItemMemoryUsage
func (c *ColumnMemUsage) TotalMemoryUsage() int64 {
return c.TotalMemUsage
}
// ItemID implements CacheItemMemoryUsage
func (c *ColumnMemUsage) ItemID() int64 {
return c.ColumnID
}
// TrackingMemUsage implements CacheItemMemoryUsage
func (c *ColumnMemUsage) TrackingMemUsage() int64 {
return c.CMSketchMemUsage + c.TopNMemUsage + c.HistogramMemUsage
}
// HistMemUsage implements CacheItemMemoryUsage
func (c *ColumnMemUsage) HistMemUsage() int64 {
return c.HistogramMemUsage
}
// TopnMemUsage implements CacheItemMemoryUsage
func (c *ColumnMemUsage) TopnMemUsage() int64 {
return c.TopNMemUsage
}
// CMSMemUsage implements CacheItemMemoryUsage
func (c *ColumnMemUsage) CMSMemUsage() int64 {
return c.CMSketchMemUsage
}
// IndexMemUsage records index memory usage
type IndexMemUsage struct {
IndexID int64
HistogramMemUsage int64
CMSketchMemUsage int64
TopNMemUsage int64
TotalMemUsage int64
}
// TotalMemoryUsage implements CacheItemMemoryUsage
func (c *IndexMemUsage) TotalMemoryUsage() int64 {
return c.TotalMemUsage
}
// ItemID implements CacheItemMemoryUsage
func (c *IndexMemUsage) ItemID() int64 {
return c.IndexID
}
// TrackingMemUsage implements CacheItemMemoryUsage
func (c *IndexMemUsage) TrackingMemUsage() int64 {
return c.CMSketchMemUsage + c.TopNMemUsage + c.HistogramMemUsage
}
// HistMemUsage implements CacheItemMemoryUsage
func (c *IndexMemUsage) HistMemUsage() int64 {
return c.HistogramMemUsage
}
// TopnMemUsage implements CacheItemMemoryUsage
func (c *IndexMemUsage) TopnMemUsage() int64 {
return c.TopNMemUsage
}
// CMSMemUsage implements CacheItemMemoryUsage
func (c *IndexMemUsage) CMSMemUsage() int64 {
return c.CMSketchMemUsage
}
// MemoryUsage returns the total memory usage of this Table.
// it will only calc the size of Columns and Indices stats data of table.
// We ignore the size of other metadata in Table
func (t *Table) MemoryUsage() *TableMemoryUsage {
tMemUsage := &TableMemoryUsage{
TableID: t.PhysicalID,
ColumnsMemUsage: make(map[int64]CacheItemMemoryUsage),
IndicesMemUsage: make(map[int64]CacheItemMemoryUsage),
}
for _, col := range t.Columns {
if col != nil {
colMemUsage := col.MemoryUsage()
tMemUsage.ColumnsMemUsage[colMemUsage.ItemID()] = colMemUsage
tMemUsage.TotalMemUsage += colMemUsage.TotalMemoryUsage()
}
}
for _, index := range t.Indices {
if index != nil {
idxMemUsage := index.MemoryUsage()
tMemUsage.IndicesMemUsage[idxMemUsage.ItemID()] = idxMemUsage
tMemUsage.TotalMemUsage += idxMemUsage.TotalMemoryUsage()
}
}
return tMemUsage
}
// Copy copies the current table.
func (t *Table) Copy() *Table {
newHistColl := HistColl{
PhysicalID: t.PhysicalID,
HavePhysicalID: t.HavePhysicalID,
RealtimeCount: t.RealtimeCount,
Columns: make(map[int64]*Column, len(t.Columns)),
Indices: make(map[int64]*Index, len(t.Indices)),
Pseudo: t.Pseudo,
ModifyCount: t.ModifyCount,
}
for id, col := range t.Columns {
newHistColl.Columns[id] = col
}
for id, idx := range t.Indices {
newHistColl.Indices[id] = idx
}
nt := &Table{
HistColl: newHistColl,
Version: t.Version,
Name: t.Name,
TblInfoUpdateTS: t.TblInfoUpdateTS,
}
if t.ExtendedStats != nil {
newExtStatsColl := &ExtendedStatsColl{
Stats: make(map[string]*ExtendedStatsItem),
LastUpdateVersion: t.ExtendedStats.LastUpdateVersion,
}
for name, item := range t.ExtendedStats.Stats {
newExtStatsColl.Stats[name] = item
}
nt.ExtendedStats = newExtStatsColl
}
return nt
}
// String implements Stringer interface.
func (t *Table) String() string {
strs := make([]string, 0, len(t.Columns)+1)
strs = append(strs, fmt.Sprintf("Table:%d RealtimeCount:%d", t.PhysicalID, t.RealtimeCount))
cols := make([]*Column, 0, len(t.Columns))
for _, col := range t.Columns {
cols = append(cols, col)
}
slices.SortFunc(cols, func(i, j *Column) bool { return i.ID < j.ID })
for _, col := range cols {
strs = append(strs, col.String())
}
idxs := make([]*Index, 0, len(t.Indices))
for _, idx := range t.Indices {
idxs = append(idxs, idx)
}
slices.SortFunc(idxs, func(i, j *Index) bool { return i.ID < j.ID })
for _, idx := range idxs {
strs = append(strs, idx.String())
}
// TODO: concat content of ExtendedStatsColl
return strings.Join(strs, "\n")
}
// IndexStartWithColumn finds the first index whose first column is the given column.
func (t *Table) IndexStartWithColumn(colName string) *Index {
for _, index := range t.Indices {
if index.Info.Columns[0].Name.L == colName {
return index
}
}
return nil
}
// ColumnByName finds the statistics.Column for the given column.
func (t *Table) ColumnByName(colName string) *Column {
for _, c := range t.Columns {
if c.Info.Name.L == colName {
return c
}
}
return nil
}
// GetStatsInfo returns their statistics according to the ID of the column or index, including histogram, CMSketch, TopN and FMSketch.
func (t *Table) GetStatsInfo(id int64, isIndex bool) (*Histogram, *CMSketch, *TopN, *FMSketch, bool) {
if isIndex {
if idxStatsInfo, ok := t.Indices[id]; ok {
return idxStatsInfo.Histogram.Copy(),
idxStatsInfo.CMSketch.Copy(), idxStatsInfo.TopN.Copy(), idxStatsInfo.FMSketch.Copy(), true
}
// newly added index which is not analyzed yet
return nil, nil, nil, nil, false
}
if colStatsInfo, ok := t.Columns[id]; ok {
return colStatsInfo.Histogram.Copy(), colStatsInfo.CMSketch.Copy(),
colStatsInfo.TopN.Copy(), colStatsInfo.FMSketch.Copy(), true
}
// newly added column which is not analyzed yet
return nil, nil, nil, nil, false
}
// GetColRowCount tries to get the row count of the a column if possible.
// This method is useful because this row count doesn't consider the modify count.
func (t *Table) GetColRowCount() float64 {
ids := make([]int64, 0, len(t.Columns))
for id := range t.Columns {
ids = append(ids, id)
}
slices.Sort(ids)
for _, id := range ids {
col := t.Columns[id]
if col != nil && col.IsFullLoad() {
return col.TotalRowCount()
}
}
return -1
}
// GetStatsHealthy calculates stats healthy if the table stats is not pseudo.
// If the table stats is pseudo, it returns 0, false, otherwise it returns stats healthy, true.
func (t *Table) GetStatsHealthy() (int64, bool) {
if t == nil || t.Pseudo {
return 0, false
}
var healthy int64
count := float64(t.RealtimeCount)
if histCount := t.GetColRowCount(); histCount > 0 {
count = histCount
}
if float64(t.ModifyCount) < count {
healthy = int64((1.0 - float64(t.ModifyCount)/count) * 100.0)
} else if t.ModifyCount == 0 {
healthy = 100
}
return healthy, true
}
type neededStatsMap struct {
items map[model.TableItemID]struct{}
m sync.RWMutex
}
func (n *neededStatsMap) AllItems() []model.TableItemID {
n.m.RLock()
keys := make([]model.TableItemID, 0, len(n.items))
for key := range n.items {
keys = append(keys, key)
}
n.m.RUnlock()
return keys
}
func (n *neededStatsMap) insert(col model.TableItemID) {
n.m.Lock()
n.items[col] = struct{}{}
n.m.Unlock()
}
func (n *neededStatsMap) Delete(col model.TableItemID) {
n.m.Lock()
delete(n.items, col)
n.m.Unlock()
}
func (n *neededStatsMap) Length() int {
n.m.RLock()
defer n.m.RUnlock()
return len(n.items)
}
// RatioOfPseudoEstimate means if modifyCount / statsTblCount is greater than this ratio, we think the stats is invalid
// and use pseudo estimation.
var RatioOfPseudoEstimate = atomic.NewFloat64(0.7)
// IsInitialized returns true if any column/index stats of the table is initialized.
func (t *Table) IsInitialized() bool {
for _, col := range t.Columns {
if col != nil && col.IsStatsInitialized() {
return true
}
}
for _, idx := range t.Indices {
if idx != nil && idx.IsStatsInitialized() {
return true
}
}
return false
}
// IsOutdated returns true if the table stats is outdated.
func (t *Table) IsOutdated() bool {
rowcount := t.GetColRowCount()
if rowcount < 0 {
rowcount = float64(t.RealtimeCount)
}
if rowcount > 0 && float64(t.ModifyCount)/rowcount > RatioOfPseudoEstimate.Load() {
return true
}
return false
}
// ColumnGreaterRowCount estimates the row count where the column greater than value.
func (t *Table) ColumnGreaterRowCount(sctx sessionctx.Context, value types.Datum, colID int64) float64 {
c, ok := t.Columns[colID]
if !ok || c.IsInvalid(sctx, t.Pseudo) {
return float64(t.RealtimeCount) / pseudoLessRate
}
return c.greaterRowCount(value) * c.GetIncreaseFactor(t.RealtimeCount)
}
// ColumnLessRowCount estimates the row count where the column less than value. Note that null values are not counted.
func (t *Table) ColumnLessRowCount(sctx sessionctx.Context, value types.Datum, colID int64) float64 {
c, ok := t.Columns[colID]
if !ok || c.IsInvalid(sctx, t.Pseudo) {
return float64(t.RealtimeCount) / pseudoLessRate
}
return c.lessRowCount(sctx, value) * c.GetIncreaseFactor(t.RealtimeCount)
}
// ColumnBetweenRowCount estimates the row count where column greater or equal to a and less than b.
func (t *Table) ColumnBetweenRowCount(sctx sessionctx.Context, a, b types.Datum, colID int64) (float64, error) {
sc := sctx.GetSessionVars().StmtCtx
c, ok := t.Columns[colID]
if !ok || c.IsInvalid(sctx, t.Pseudo) {
return float64(t.RealtimeCount) / pseudoBetweenRate, nil
}
aEncoded, err := codec.EncodeKey(sc, nil, a)
if err != nil {
return 0, err
}
bEncoded, err := codec.EncodeKey(sc, nil, b)
if err != nil {
return 0, err
}
count := c.BetweenRowCount(sctx, a, b, aEncoded, bEncoded)
if a.IsNull() {
count += float64(c.NullCount)
}
return count * c.GetIncreaseFactor(t.RealtimeCount), nil
}
// ColumnEqualRowCount estimates the row count where the column equals to value.
func (t *Table) ColumnEqualRowCount(sctx sessionctx.Context, value types.Datum, colID int64) (float64, error) {
c, ok := t.Columns[colID]
if !ok || c.IsInvalid(sctx, t.Pseudo) {
return float64(t.RealtimeCount) / pseudoEqualRate, nil
}
encodedVal, err := codec.EncodeKey(sctx.GetSessionVars().StmtCtx, nil, value)
if err != nil {
return 0, err
}
result, err := c.equalRowCount(sctx, value, encodedVal, t.ModifyCount)
result *= c.GetIncreaseFactor(t.RealtimeCount)
return result, errors.Trace(err)
}
// GetRowCountByIntColumnRanges estimates the row count by a slice of IntColumnRange.
func (coll *HistColl) GetRowCountByIntColumnRanges(sctx sessionctx.Context, colID int64, intRanges []*ranger.Range) (result float64, err error) {
var name string
if sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {
debugtrace.EnterContextCommon(sctx)
debugTraceGetRowCountInput(sctx, colID, intRanges)
defer func() {
debugtrace.RecordAnyValuesWithNames(sctx, "Name", name, "Result", result)
debugtrace.LeaveContextCommon(sctx)
}()
}
sc := sctx.GetSessionVars().StmtCtx
c, ok := coll.Columns[colID]
recordUsedItemStatsStatus(sctx, c, coll.PhysicalID, colID)
if c != nil && c.Info != nil {
name = c.Info.Name.O
}
if !ok || c.IsInvalid(sctx, coll.Pseudo) {
if len(intRanges) == 0 {
return 0, nil
}
if intRanges[0].LowVal[0].Kind() == types.KindInt64 {
result = getPseudoRowCountBySignedIntRanges(intRanges, float64(coll.RealtimeCount))
} else {
result = getPseudoRowCountByUnsignedIntRanges(intRanges, float64(coll.RealtimeCount))
}
if sc.EnableOptimizerCETrace && ok {
CETraceRange(sctx, coll.PhysicalID, []string{c.Info.Name.O}, intRanges, "Column Stats-Pseudo", uint64(result))
}
return result, nil
}
if sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {
debugtrace.RecordAnyValuesWithNames(sctx,
"Histogram NotNull Count", c.Histogram.notNullCount(),
"TopN total count", c.TopN.TotalCount(),
"Increase Factor", c.GetIncreaseFactor(coll.RealtimeCount),
)
}
result, err = c.GetColumnRowCount(sctx, intRanges, coll.RealtimeCount, coll.ModifyCount, true)
if sc.EnableOptimizerCETrace {
CETraceRange(sctx, coll.PhysicalID, []string{c.Info.Name.O}, intRanges, "Column Stats", uint64(result))
}
return result, errors.Trace(err)
}
// GetRowCountByColumnRanges estimates the row count by a slice of Range.
func (coll *HistColl) GetRowCountByColumnRanges(sctx sessionctx.Context, colID int64, colRanges []*ranger.Range) (result float64, err error) {
var name string
if sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {
debugtrace.EnterContextCommon(sctx)
debugTraceGetRowCountInput(sctx, colID, colRanges)
defer func() {
debugtrace.RecordAnyValuesWithNames(sctx, "Name", name, "Result", result)
debugtrace.LeaveContextCommon(sctx)
}()
}
sc := sctx.GetSessionVars().StmtCtx
c, ok := coll.Columns[colID]
recordUsedItemStatsStatus(sctx, c, coll.PhysicalID, colID)
if c != nil && c.Info != nil {
name = c.Info.Name.O
}
if !ok || c.IsInvalid(sctx, coll.Pseudo) {
result, err = GetPseudoRowCountByColumnRanges(sc, float64(coll.RealtimeCount), colRanges, 0)
if err == nil && sc.EnableOptimizerCETrace && ok {
CETraceRange(sctx, coll.PhysicalID, []string{c.Info.Name.O}, colRanges, "Column Stats-Pseudo", uint64(result))
}
return result, err
}
if sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {
debugtrace.RecordAnyValuesWithNames(sctx,
"Histogram NotNull Count", c.Histogram.notNullCount(),
"TopN total count", c.TopN.TotalCount(),
"Increase Factor", c.GetIncreaseFactor(coll.RealtimeCount),
)
}
result, err = c.GetColumnRowCount(sctx, colRanges, coll.RealtimeCount, coll.ModifyCount, false)
if sc.EnableOptimizerCETrace {
CETraceRange(sctx, coll.PhysicalID, []string{c.Info.Name.O}, colRanges, "Column Stats", uint64(result))
}
return result, errors.Trace(err)
}
// GetRowCountByIndexRanges estimates the row count by a slice of Range.
func (coll *HistColl) GetRowCountByIndexRanges(sctx sessionctx.Context, idxID int64, indexRanges []*ranger.Range) (result float64, err error) {
var name string
if sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {
debugtrace.EnterContextCommon(sctx)
debugTraceGetRowCountInput(sctx, idxID, indexRanges)
defer func() {
debugtrace.RecordAnyValuesWithNames(sctx, "Name", name, "Result", result)
debugtrace.LeaveContextCommon(sctx)
}()
}
sc := sctx.GetSessionVars().StmtCtx
idx, ok := coll.Indices[idxID]
colNames := make([]string, 0, 8)
if ok {
if idx.Info != nil {
name = idx.Info.Name.O
for _, col := range idx.Info.Columns {
colNames = append(colNames, col.Name.O)
}
}
}
recordUsedItemStatsStatus(sctx, idx, coll.PhysicalID, idxID)
if !ok || idx.IsInvalid(sctx, coll.Pseudo) {
colsLen := -1
if idx != nil && idx.Info.Unique {
colsLen = len(idx.Info.Columns)
}
result, err = getPseudoRowCountByIndexRanges(sc, indexRanges, float64(coll.RealtimeCount), colsLen)
if err == nil && sc.EnableOptimizerCETrace && ok {
CETraceRange(sctx, coll.PhysicalID, colNames, indexRanges, "Index Stats-Pseudo", uint64(result))
}
return result, err
}
if sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {
debugtrace.RecordAnyValuesWithNames(sctx,
"Histogram NotNull Count", idx.Histogram.notNullCount(),
"TopN total count", idx.TopN.TotalCount(),
"Increase Factor", idx.GetIncreaseFactor(coll.RealtimeCount),
)
}
if idx.CMSketch != nil && idx.StatsVer == Version1 {
result, err = coll.getIndexRowCount(sctx, idxID, indexRanges)
} else {
result, err = idx.GetRowCount(sctx, coll, indexRanges, coll.RealtimeCount, coll.ModifyCount)
}
if sc.EnableOptimizerCETrace {
CETraceRange(sctx, coll.PhysicalID, colNames, indexRanges, "Index Stats", uint64(result))
}
return result, errors.Trace(err)
}
// CETraceRange appends a list of ranges and related information into CE trace
func CETraceRange(sctx sessionctx.Context, tableID int64, colNames []string, ranges []*ranger.Range, tp string, rowCount uint64) {
sc := sctx.GetSessionVars().StmtCtx
allPoint := true
for _, ran := range ranges {
if !ran.IsPointNullable(sctx) {
allPoint = false
break
}
}
if allPoint {
tp = tp + "-Point"
} else {
tp = tp + "-Range"
}
expr, err := ranger.RangesToString(sc, ranges, colNames)
if err != nil {
logutil.BgLogger().Debug("Failed to trace CE of ranges", zap.String("category", "OptimizerTrace"), zap.Error(err))
}
// We don't need to record meaningless expressions.
if expr == "" || expr == "true" || expr == "false" {
return
}
ceRecord := tracing.CETraceRecord{
TableID: tableID,
Type: tp,
Expr: expr,
RowCount: rowCount,
}
sc.OptimizerCETrace = append(sc.OptimizerCETrace, &ceRecord)
}
func (coll *HistColl) findAvailableStatsForCol(sctx sessionctx.Context, uniqueID int64) (isIndex bool, idx int64) {
// try to find available stats in column stats
if colStats, ok := coll.Columns[uniqueID]; ok && colStats != nil && !colStats.IsInvalid(sctx, coll.Pseudo) && colStats.IsFullLoad() {
return false, uniqueID
}
// try to find available stats in single column index stats (except for prefix index)
for idxStatsIdx, cols := range coll.Idx2ColumnIDs {
if len(cols) == 1 && cols[0] == uniqueID {
idxStats, ok := coll.Indices[idxStatsIdx]
if ok &&
idxStats.Info.Columns[0].Length == types.UnspecifiedLength &&
!idxStats.IsInvalid(sctx, coll.Pseudo) &&
idxStats.IsFullLoad() {
return true, idxStatsIdx
}
}
}
return false, -1
}
// GetSelectivityByFilter try to estimate selectivity of expressions by evaluate the expressions using TopN, Histogram buckets boundaries and NULL.
// Currently, this method can only handle expressions involving a single column.
func (coll *HistColl) GetSelectivityByFilter(sctx sessionctx.Context, filters []expression.Expression) (ok bool, selectivity float64, err error) {
// 1. Make sure the expressions
// (1) are safe to be evaluated here,
// (2) involve only one column,
// (3) and this column is not a "new collation" string column so that we're able to restore values from the stats.
for _, filter := range filters {
if expression.IsMutableEffectsExpr(filter) {
return false, 0, nil
}
}
if expression.ContainCorrelatedColumn(filters) {
return false, 0, nil
}
cols := expression.ExtractColumnsFromExpressions(nil, filters, nil)
if len(cols) != 1 {
return false, 0, nil
}
col := cols[0]
tp := col.RetType
if types.IsString(tp.GetType()) && collate.NewCollationEnabled() && !collate.IsBinCollation(tp.GetCollate()) {
return false, 0, nil
}
// 2. Get the available stats, make sure it's a ver2 stats and get the needed data structure from it.
isIndex, i := coll.findAvailableStatsForCol(sctx, col.UniqueID)
if i < 0 {
return false, 0, nil
}
var statsVer, nullCnt int64
var histTotalCnt, totalCnt float64
var topnTotalCnt uint64
var hist *Histogram
var topn *TopN
if isIndex {
stats := coll.Indices[i]
statsVer = stats.StatsVer
hist = &stats.Histogram
nullCnt = hist.NullCount
topn = stats.TopN
} else {
stats := coll.Columns[i]
statsVer = stats.StatsVer
hist = &stats.Histogram
nullCnt = hist.NullCount
topn = stats.TopN
}
// Only in stats ver2, we can assume that: TopN + Histogram + NULL == All data
if statsVer != Version2 {
return false, 0, nil
}
topnTotalCnt = topn.TotalCount()
histTotalCnt = hist.notNullCount()
totalCnt = float64(topnTotalCnt) + histTotalCnt + float64(nullCnt)
var topNSel, histSel, nullSel float64
// Prepare for evaluation.
// For execution, we use Column.Index instead of Column.UniqueID to locate a column.
// We have only one column here, so we set it to 0.
originalIndex := col.Index
col.Index = 0
defer func() {
// Restore the original Index to avoid unexpected situation.
col.Index = originalIndex
}()
topNLen := 0
histBucketsLen := hist.Len()
if topn != nil {
topNLen = len(topn.TopN)
}
c := chunk.NewChunkWithCapacity([]*types.FieldType{tp}, mathutil.Max(1, topNLen))
selected := make([]bool, 0, mathutil.Max(histBucketsLen, topNLen))
// 3. Calculate the TopN part selectivity.
// This stage is considered as the core functionality of this method, errors in this stage would make this entire method fail.
var topNSelectedCnt uint64
if topn != nil {
for _, item := range topn.TopN {
_, val, err := codec.DecodeOne(item.Encoded)
if err != nil {
return false, 0, err
}
c.AppendDatum(0, &val)
}
selected, err = expression.VectorizedFilter(sctx, filters, chunk.NewIterator4Chunk(c), selected)
if err != nil {
return false, 0, err
}
for i, isTrue := range selected {
if isTrue {
topNSelectedCnt += topn.TopN[i].Count
}
}
}
topNSel = float64(topNSelectedCnt) / totalCnt
// 4. Calculate the Histogram part selectivity.
// The buckets upper bounds and the Bucket.Repeat are used like the TopN above.
// The buckets lower bounds are used as random samples and are regarded equally.
if hist != nil && histTotalCnt > 0 {
selected = selected[:0]
selected, err = expression.VectorizedFilter(sctx, filters, chunk.NewIterator4Chunk(hist.Bounds), selected)
if err != nil {
return false, 0, err
}
var bucketRepeatTotalCnt, bucketRepeatSelectedCnt, lowerBoundMatchCnt int64
for i := range hist.Buckets {
bucketRepeatTotalCnt += hist.Buckets[i].Repeat
if len(selected) < 2*i {
// This should not happen, but we add this check for safety.
break
}
if selected[2*i] {
lowerBoundMatchCnt++
}
if selected[2*i+1] {
bucketRepeatSelectedCnt += hist.Buckets[i].Repeat
}
}
var lowerBoundsRatio, upperBoundsRatio, lowerBoundsSel, upperBoundsSel float64
upperBoundsRatio = mathutil.Min(float64(bucketRepeatTotalCnt)/histTotalCnt, 1)
lowerBoundsRatio = 1 - upperBoundsRatio
if bucketRepeatTotalCnt > 0 {
upperBoundsSel = float64(bucketRepeatSelectedCnt) / float64(bucketRepeatTotalCnt)
}
lowerBoundsSel = float64(lowerBoundMatchCnt) / float64(histBucketsLen)
histSel = lowerBoundsSel*lowerBoundsRatio + upperBoundsSel*upperBoundsRatio
histSel *= histTotalCnt / totalCnt
}
// 5. Calculate the NULL part selectivity.
// Errors in this staged would be returned, but would not make this entire method fail.
c.Reset()
c.AppendNull(0)
selected = selected[:0]
selected, err = expression.VectorizedFilter(sctx, filters, chunk.NewIterator4Chunk(c), selected)
if err != nil || len(selected) != 1 || !selected[0] {
nullSel = 0
} else {
nullSel = float64(nullCnt) / totalCnt
}
// 6. Get the final result.
res := topNSel + histSel + nullSel
return true, res, err
}
// PseudoAvgCountPerValue gets a pseudo average count if histogram not exists.
func (t *Table) PseudoAvgCountPerValue() float64 {
return float64(t.RealtimeCount) / pseudoEqualRate
}
// GetOrdinalOfRangeCond gets the ordinal of the position range condition,
// if not exist, it returns the end position.
func GetOrdinalOfRangeCond(sc *stmtctx.StatementContext, ran *ranger.Range) int {
for i := range ran.LowVal {
a, b := ran.LowVal[i], ran.HighVal[i]
cmp, err := a.Compare(sc, &b, ran.Collators[0])
if err != nil {
return 0
}
if cmp != 0 {
return i
}
}
return len(ran.LowVal)
}
// ID2UniqueID generates a new HistColl whose `Columns` is built from UniqueID of given columns.
func (coll *HistColl) ID2UniqueID(columns []*expression.Column) *HistColl {
cols := make(map[int64]*Column)
for _, col := range columns {
colHist, ok := coll.Columns[col.ID]
if ok {
cols[col.UniqueID] = colHist
}
}
newColl := &HistColl{
PhysicalID: coll.PhysicalID,
HavePhysicalID: coll.HavePhysicalID,
Pseudo: coll.Pseudo,
RealtimeCount: coll.RealtimeCount,
ModifyCount: coll.ModifyCount,
Columns: cols,
}
return newColl
}
// GenerateHistCollFromColumnInfo generates a new HistColl whose ColID2IdxIDs and IdxID2ColIDs is built from the given parameter.
func (coll *HistColl) GenerateHistCollFromColumnInfo(tblInfo *model.TableInfo, columns []*expression.Column) *HistColl {
newColHistMap := make(map[int64]*Column)
colInfoID2UniqueID := make(map[int64]int64, len(columns))
idxID2idxInfo := make(map[int64]*model.IndexInfo)
for _, col := range columns {
colInfoID2UniqueID[col.ID] = col.UniqueID
}
for id, colHist := range coll.Columns {
uniqueID, ok := colInfoID2UniqueID[id]
// Collect the statistics by the given columns.
if ok {
newColHistMap[uniqueID] = colHist
}
}
for _, idxInfo := range tblInfo.Indices {
idxID2idxInfo[idxInfo.ID] = idxInfo
}
newIdxHistMap := make(map[int64]*Index)
idx2Columns := make(map[int64][]int64)
colID2IdxIDs := make(map[int64][]int64)
for id, idxHist := range coll.Indices {
idxInfo := idxID2idxInfo[id]
if idxInfo == nil {
continue
}
ids := make([]int64, 0, len(idxInfo.Columns))
for _, idxCol := range idxInfo.Columns {
uniqueID, ok := colInfoID2UniqueID[tblInfo.Columns[idxCol.Offset].ID]
if !ok {
break
}
ids = append(ids, uniqueID)
}
// If the length of the id list is 0, this index won't be used in this query.
if len(ids) == 0 {
continue
}
colID2IdxIDs[ids[0]] = append(colID2IdxIDs[ids[0]], idxHist.ID)
newIdxHistMap[idxHist.ID] = idxHist
idx2Columns[idxHist.ID] = ids
}
for _, idxIDs := range colID2IdxIDs {
slices.Sort(idxIDs)
}
newColl := &HistColl{
PhysicalID: coll.PhysicalID,
HavePhysicalID: coll.HavePhysicalID,
Pseudo: coll.Pseudo,
RealtimeCount: coll.RealtimeCount,
ModifyCount: coll.ModifyCount,
Columns: newColHistMap,
Indices: newIdxHistMap,
ColID2IdxIDs: colID2IdxIDs,
Idx2ColumnIDs: idx2Columns,
}
return newColl
}
// isSingleColIdxNullRange checks if a range is [NULL, NULL] on a single-column index.