/
stats.go
1224 lines (1130 loc) · 35.2 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 2022 Matrix Origin
//
// 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 plan
import (
"bytes"
"context"
"fmt"
"math"
"sort"
"strings"
"time"
"github.com/matrixorigin/matrixone/pkg/catalog"
"github.com/matrixorigin/matrixone/pkg/container/batch"
"github.com/matrixorigin/matrixone/pkg/container/types"
"github.com/matrixorigin/matrixone/pkg/objectio"
"github.com/matrixorigin/matrixone/pkg/pb/plan"
"github.com/matrixorigin/matrixone/pkg/sql/util"
v2 "github.com/matrixorigin/matrixone/pkg/util/metric/v2"
"github.com/matrixorigin/matrixone/pkg/vm/process"
)
const DefaultBlockMaxRows = 8192
const BlockNumForceOneCN = 200
const blockSelectivityThreshHold = 0.95
const blockNDVThreshHold = 100
const highNDVcolumnThreshHold = 0.95
// stats cache is small, no need to use LRU for now
type StatsCache struct {
cachePool map[uint64]*StatsInfoMap
}
func NewStatsCache() *StatsCache {
return &StatsCache{
cachePool: make(map[uint64]*StatsInfoMap, 100),
}
}
type StatsInfoMap struct {
NdvMap map[string]float64
MinValMap map[string]float64
MaxValMap map[string]float64
DataTypeMap map[string]types.T
NullCntMap map[string]int64
ShuffleRangeMap map[string]*ShuffleRange
BlockNumber int
AccurateObjectNumber int
ApproxObjectNumber int //detect if block number changes , update stats info map
TableCnt float64
tableName string
}
func NewStatsInfoMap() *StatsInfoMap {
return &StatsInfoMap{
NdvMap: make(map[string]float64),
MinValMap: make(map[string]float64),
MaxValMap: make(map[string]float64),
DataTypeMap: make(map[string]types.T),
NullCntMap: make(map[string]int64),
ShuffleRangeMap: make(map[string]*ShuffleRange),
BlockNumber: 0,
ApproxObjectNumber: 0,
TableCnt: 0,
}
}
func (sc *StatsInfoMap) NeedUpdate(currentApproxObjNum int) bool {
if sc.ApproxObjectNumber == 0 || sc.AccurateObjectNumber == 0 {
return true
}
if math.Abs(float64(sc.ApproxObjectNumber-currentApproxObjNum)) >= 10 {
return true
}
if float64(currentApproxObjNum)/float64(sc.ApproxObjectNumber) > 1.05 || float64(currentApproxObjNum)/float64(sc.ApproxObjectNumber) < 0.95 {
return true
}
return false
}
func (sc *StatsCache) GetStatsInfoMap(tableID uint64, create bool) *StatsInfoMap {
if sc == nil {
return nil
}
if s, ok := (sc.cachePool)[tableID]; ok {
return s
} else if create {
s = NewStatsInfoMap()
(sc.cachePool)[tableID] = s
return s
} else {
return nil
}
}
type InfoFromZoneMap struct {
ColumnZMs []objectio.ZoneMap
DataTypes []types.Type
ColumnNDVs []float64
NullCnts []int64
ShuffleRanges []*ShuffleRange
BlockNumber int
AccurateObjectNumber int
ApproxObjectNumber int
TableCnt float64
}
func NewInfoFromZoneMap(lenCols int) *InfoFromZoneMap {
info := &InfoFromZoneMap{
ColumnZMs: make([]objectio.ZoneMap, lenCols),
DataTypes: make([]types.Type, lenCols),
ColumnNDVs: make([]float64, lenCols),
NullCnts: make([]int64, lenCols),
ShuffleRanges: make([]*ShuffleRange, lenCols),
}
return info
}
func UpdateStatsInfoMap(info *InfoFromZoneMap, tableDef *plan.TableDef, s *StatsInfoMap) {
start := time.Now()
defer func() {
v2.TxnStatementUpdateStatsInfoMapHistogram.Observe(time.Since(start).Seconds())
}()
s.ApproxObjectNumber = info.ApproxObjectNumber
s.AccurateObjectNumber = info.AccurateObjectNumber
s.BlockNumber = info.BlockNumber
s.TableCnt = info.TableCnt
s.tableName = tableDef.Name
//calc ndv with min,max,distinct value in zonemap, blocknumer and column type
//set info in statsInfoMap
for i, coldef := range tableDef.Cols[:len(tableDef.Cols)-1] {
colName := coldef.Name
s.NdvMap[colName] = info.ColumnNDVs[i]
s.DataTypeMap[colName] = info.DataTypes[i].Oid
s.NullCntMap[colName] = info.NullCnts[i]
if !info.ColumnZMs[i].IsInited() {
s.MinValMap[colName] = 0
s.MaxValMap[colName] = 0
continue
}
switch info.DataTypes[i].Oid {
case types.T_int8:
s.MinValMap[colName] = float64(types.DecodeInt8(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeInt8(info.ColumnZMs[i].GetMaxBuf()))
case types.T_int16:
s.MinValMap[colName] = float64(types.DecodeInt16(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeInt16(info.ColumnZMs[i].GetMaxBuf()))
case types.T_int32:
s.MinValMap[colName] = float64(types.DecodeInt32(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeInt32(info.ColumnZMs[i].GetMaxBuf()))
case types.T_int64:
s.MinValMap[colName] = float64(types.DecodeInt64(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeInt64(info.ColumnZMs[i].GetMaxBuf()))
case types.T_uint8:
s.MinValMap[colName] = float64(types.DecodeUint8(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeUint8(info.ColumnZMs[i].GetMaxBuf()))
case types.T_uint16:
s.MinValMap[colName] = float64(types.DecodeUint16(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeUint16(info.ColumnZMs[i].GetMaxBuf()))
case types.T_uint32:
s.MinValMap[colName] = float64(types.DecodeUint32(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeUint32(info.ColumnZMs[i].GetMaxBuf()))
case types.T_uint64:
s.MinValMap[colName] = float64(types.DecodeUint64(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeUint64(info.ColumnZMs[i].GetMaxBuf()))
case types.T_date:
s.MinValMap[colName] = float64(types.DecodeDate(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeDate(info.ColumnZMs[i].GetMaxBuf()))
case types.T_time:
s.MinValMap[colName] = float64(types.DecodeTime(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeTime(info.ColumnZMs[i].GetMaxBuf()))
case types.T_timestamp:
s.MinValMap[colName] = float64(types.DecodeTimestamp(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeTimestamp(info.ColumnZMs[i].GetMaxBuf()))
case types.T_datetime:
s.MinValMap[colName] = float64(types.DecodeDatetime(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(types.DecodeDatetime(info.ColumnZMs[i].GetMaxBuf()))
case types.T_char, types.T_varchar, types.T_text:
s.MinValMap[colName] = float64(ByteSliceToUint64(info.ColumnZMs[i].GetMinBuf()))
s.MaxValMap[colName] = float64(ByteSliceToUint64(info.ColumnZMs[i].GetMaxBuf()))
}
if info.ShuffleRanges[i] != nil {
if s.MinValMap[colName] != s.MaxValMap[colName] && s.TableCnt > HashMapSizeForShuffle && info.ColumnNDVs[i] >= ShuffleThreshHoldOfNDV && !util.JudgeIsCompositeClusterByColumn(colName) && colName != catalog.CPrimaryKeyColName {
info.ShuffleRanges[i].Eval(1024)
s.ShuffleRangeMap[colName] = info.ShuffleRanges[i]
}
info.ShuffleRanges[i] = nil
}
}
}
// cols in one table, return if ndv of multi column is high enough
func isHighNdvCols(cols []int32, tableDef *TableDef, builder *QueryBuilder) bool {
if tableDef == nil {
return false
}
// first to check if it is primary key.
if containsAllPKs(cols, tableDef) {
return true
}
s := getStatsInfoByTableID(tableDef.TblId, builder)
if s == nil {
return false
}
var totalNDV float64 = 1
for i := range cols {
totalNDV *= s.NdvMap[tableDef.Cols[cols[i]].Name]
}
return totalNDV > s.TableCnt*highNDVcolumnThreshHold
}
func getStatsInfoByTableID(tableID uint64, builder *QueryBuilder) *StatsInfoMap {
if builder == nil {
return nil
}
sc := builder.compCtx.GetStatsCache()
if sc == nil {
return nil
}
return sc.GetStatsInfoMap(tableID, false)
}
func getStatsInfoByCol(col *plan.ColRef, builder *QueryBuilder) *StatsInfoMap {
if builder == nil {
return nil
}
sc := builder.compCtx.GetStatsCache()
if sc == nil {
return nil
}
tableDef, ok := builder.tag2Table[col.RelPos]
if !ok {
return nil
}
//fix column name
if len(col.Name) == 0 {
col.Name = tableDef.Cols[col.ColPos].Name
}
return sc.GetStatsInfoMap(tableDef.TblId, false)
}
func getColNdv(col *plan.ColRef, builder *QueryBuilder) float64 {
s := getStatsInfoByCol(col, builder)
if s == nil {
return -1
}
return s.NdvMap[col.Name]
}
func getNullSelectivity(arg *plan.Expr, builder *QueryBuilder, isnull bool) float64 {
switch exprImpl := arg.Expr.(type) {
case *plan.Expr_Col:
col := exprImpl.Col
s := getStatsInfoByCol(col, builder)
if s == nil {
break
}
nullCnt := float64(s.NullCntMap[col.Name])
if isnull {
return nullCnt / s.TableCnt
} else {
return 1 - (nullCnt / s.TableCnt)
}
}
if isnull {
return 0.1
} else {
return 0.9
}
}
// this function is used to calculate the ndv of expressions,
// like year(l_orderdate), substring(phone_number), and assume col is the first argument
// if only the ndv of column is needed, please call getColNDV
// if this function fail, it will return -1
func getExprNdv(expr *plan.Expr, builder *QueryBuilder) float64 {
switch exprImpl := expr.Expr.(type) {
case *plan.Expr_F:
funcName := exprImpl.F.Func.ObjName
switch funcName {
case "year":
return getExprNdv(exprImpl.F.Args[0], builder) / 365
case "substring":
// no good way to calc ndv for substring
return math.Min(getExprNdv(exprImpl.F.Args[0], builder), 25)
default:
return getExprNdv(exprImpl.F.Args[0], builder)
}
case *plan.Expr_Col:
return getColNdv(exprImpl.Col, builder)
}
return -1
}
func estimateEqualitySelectivity(expr *plan.Expr, builder *QueryBuilder) float64 {
// only filter like func(col)=1 or col=? can estimate outcnt
// and only 1 colRef is allowd in the filter. otherwise, no good method to calculate
col := extractColRefInFilter(expr)
if col == nil {
return 0.01
}
ndv := getExprNdv(expr, builder)
if ndv > 0 {
return 1 / ndv
}
return 0.01
}
func calcSelectivityByMinMax(funcName string, min, max float64, typ types.T, vals []*plan.Literal) (ret float64) {
switch funcName {
case ">", ">=":
if val, ok := getFloat64Value(typ, vals[0]); ok {
ret = (max - val + 1) / (max - min)
}
case "<", "<=":
if val, ok := getFloat64Value(typ, vals[0]); ok {
ret = (val - min + 1) / (max - min)
}
case "between":
if lb, ok := getFloat64Value(typ, vals[0]); ok {
if ub, ok := getFloat64Value(typ, vals[1]); ok {
ret = (ub - lb + 1) / (max - min)
}
}
default:
ret = 0.3
}
if ret < 0 {
ret = 0
}
if ret > 1 {
ret = 1
}
return ret
}
func getFloat64Value(typ types.T, lit *plan.Literal) (float64, bool) {
switch typ {
case types.T_float32:
if val, valOk := lit.Value.(*plan.Literal_Fval); valOk {
return float64(val.Fval), true
}
case types.T_float64:
if val, valOk := lit.Value.(*plan.Literal_Dval); valOk {
return val.Dval, true
}
case types.T_int8:
if val, valOk := lit.Value.(*plan.Literal_I8Val); valOk {
return float64(val.I8Val), true
}
case types.T_int16:
if val, valOk := lit.Value.(*plan.Literal_I16Val); valOk {
return float64(val.I16Val), true
}
case types.T_int32:
if val, valOk := lit.Value.(*plan.Literal_I32Val); valOk {
return float64(val.I32Val), true
}
case types.T_int64:
if val, valOk := lit.Value.(*plan.Literal_I64Val); valOk {
return float64(val.I64Val), true
}
case types.T_uint8:
if val, valOk := lit.Value.(*plan.Literal_U8Val); valOk {
return float64(val.U8Val), true
}
case types.T_uint16:
if val, valOk := lit.Value.(*plan.Literal_U16Val); valOk {
return float64(val.U16Val), true
}
case types.T_uint32:
if val, valOk := lit.Value.(*plan.Literal_U32Val); valOk {
return float64(val.U32Val), true
}
case types.T_uint64:
if val, valOk := lit.Value.(*plan.Literal_U64Val); valOk {
return float64(val.U64Val), true
}
case types.T_date:
if val, valOk := lit.Value.(*plan.Literal_Dateval); valOk {
return float64(val.Dateval), true
}
case types.T_datetime:
if val, valOk := lit.Value.(*plan.Literal_Datetimeval); valOk {
return float64(val.Datetimeval), true
}
}
return 0, false
}
func estimateNonEqualitySelectivity(expr *plan.Expr, funcName string, builder *QueryBuilder) float64 {
// only filter like func(col)>1 , or (col=1) or (col=2) can estimate outcnt
// and only 1 colRef is allowd in the filter. otherwise, no good method to calculate
col := extractColRefInFilter(expr)
if col == nil {
return 0.1
}
s := getStatsInfoByCol(col, builder)
if s == nil {
return 0.1
}
//check strict filter, otherwise can not estimate outcnt by min/max val
col, litType, literals, colFnName := extractColRefAndLiteralsInFilter(expr)
if col != nil && len(literals) > 0 {
typ := s.DataTypeMap[col.Name]
if !(typ.IsInteger() || typ.IsDateRelate()) {
return 0.1
}
switch colFnName {
case "":
return calcSelectivityByMinMax(funcName, s.MinValMap[col.Name], s.MaxValMap[col.Name], typ, literals)
case "year":
switch typ {
case types.T_date:
minVal := types.Date(s.MinValMap[col.Name])
maxVal := types.Date(s.MaxValMap[col.Name])
return calcSelectivityByMinMax(funcName, float64(minVal.Year()), float64(maxVal.Year()), litType, literals)
case types.T_datetime:
// TODO
}
}
}
return 0.1
}
func estimateExprSelectivity(expr *plan.Expr, builder *QueryBuilder) float64 {
if expr == nil {
return 1
}
switch exprImpl := expr.Expr.(type) {
case *plan.Expr_F:
funcName := exprImpl.F.Func.ObjName
switch funcName {
case "=":
return estimateEqualitySelectivity(expr, builder)
case "!=", "<>":
return 0.9
case ">", "<", ">=", "<=", "between":
return estimateNonEqualitySelectivity(expr, funcName, builder)
case "and":
sel1 := estimateExprSelectivity(exprImpl.F.Args[0], builder)
sel2 := estimateExprSelectivity(exprImpl.F.Args[1], builder)
if canMergeToBetweenAnd(exprImpl.F.Args[0], exprImpl.F.Args[1]) && (sel1+sel2) > 1 {
return sel1 + sel2 - 1
} else {
return andSelectivity(sel1, sel2)
}
case "or":
sel1 := estimateExprSelectivity(exprImpl.F.Args[0], builder)
sel2 := estimateExprSelectivity(exprImpl.F.Args[1], builder)
return orSelectivity(sel1, sel2)
case "not":
return 1 - estimateExprSelectivity(exprImpl.F.Args[0], builder)
case "like":
return 0.2
case "prefix_eq":
ndv := getExprNdv(expr, builder)
if ndv > 10 {
return 10 / ndv
}
return 0.5
case "in":
card := float64(exprImpl.F.Args[1].Expr.(*plan.Expr_Vec).Vec.Len)
ndv := getExprNdv(expr, builder)
if ndv > card {
return card / ndv
}
return 1
case "prefix_in":
card := float64(exprImpl.F.Args[1].Expr.(*plan.Expr_Vec).Vec.Len)
ndv := getExprNdv(expr, builder)
if ndv > 10*card {
return 10 * card / ndv
}
return 0.5
case "prefix_between":
return 0.1
case "isnull", "is_null":
return getNullSelectivity(exprImpl.F.Args[0], builder, true)
case "isnotnull", "is_not_null":
return getNullSelectivity(exprImpl.F.Args[0], builder, false)
default:
return 0.15
}
case *plan.Expr_Lit:
return 1
}
return 1
}
func estimateFilterWeight(expr *plan.Expr, w float64) float64 {
switch expr.Typ.Id {
case int32(types.T_decimal64):
w += 64
case int32(types.T_decimal128):
w += 128
case int32(types.T_float32), int32(types.T_float64):
w += 8
case int32(types.T_char), int32(types.T_varchar), int32(types.T_text), int32(types.T_json):
w += 4
}
switch exprImpl := expr.Expr.(type) {
case *plan.Expr_F:
funcImpl := exprImpl.F
switch funcImpl.Func.GetObjName() {
case "like":
w += 10
case "cast":
w += 3
case "in":
w += 2
case "<>", "!=":
w += 1.2
case "<", "<=":
w += 1.1
default:
w += 1
}
for _, child := range exprImpl.F.Args {
w += estimateFilterWeight(child, 0)
}
}
return w
}
// harsh estimate of block selectivity, will improve it in the future
func estimateFilterBlockSelectivity(ctx context.Context, expr *plan.Expr, tableDef *plan.TableDef, builder *QueryBuilder) float64 {
if !ExprIsZonemappable(ctx, expr) {
return 1
}
if expr.Selectivity < 0.01 {
return expr.Selectivity * 90
}
col := extractColRefInFilter(expr)
if col != nil {
switch GetSortOrder(tableDef, col.Name) {
case 0:
return math.Min(expr.Selectivity*10, 0.5)
case 1:
return math.Min(expr.Selectivity*10, 0.7)
case 2:
return math.Min(expr.Selectivity*10, 0.9)
}
}
if getExprNdv(expr, builder) < blockNDVThreshHold {
return 1
}
// do not know selectivity for this expr, default 0.5
return 0.5
}
func rewriteFilterListByStats(ctx context.Context, nodeID int32, builder *QueryBuilder) {
node := builder.qry.Nodes[nodeID]
if len(node.Children) > 0 {
for _, child := range node.Children {
rewriteFilterListByStats(ctx, child, builder)
}
}
switch node.NodeType {
case plan.Node_TABLE_SCAN:
if node.ObjRef != nil && len(node.FilterList) >= 1 {
sort.Slice(node.FilterList, func(i, j int) bool {
cost1 := estimateFilterWeight(node.FilterList[i], 0) * estimateExprSelectivity(node.FilterList[i], builder)
cost2 := estimateFilterWeight(node.FilterList[j], 0) * estimateExprSelectivity(node.FilterList[j], builder)
return cost1 <= cost2
})
sort.Slice(node.BlockFilterList, func(i, j int) bool {
blockSel1 := node.BlockFilterList[i].Selectivity
blockSel2 := node.BlockFilterList[j].Selectivity
return blockSel1 <= blockSel2
})
}
}
}
func ReCalcNodeStats(nodeID int32, builder *QueryBuilder, recursive bool, leafNode bool, needResetHashMapStats bool) {
node := builder.qry.Nodes[nodeID]
if recursive {
if len(node.Children) > 0 {
for _, child := range node.Children {
ReCalcNodeStats(child, builder, recursive, leafNode, needResetHashMapStats)
}
}
}
var leftStats, rightStats, childStats *Stats
if len(node.Children) == 1 {
childStats = builder.qry.Nodes[node.Children[0]].Stats
} else if len(node.Children) == 2 {
leftStats = builder.qry.Nodes[node.Children[0]].Stats
rightStats = builder.qry.Nodes[node.Children[1]].Stats
}
if node.Stats == nil {
if node.NodeType != plan.Node_EXTERNAL_SCAN && node.NodeType != plan.Node_TABLE_SCAN {
node.Stats = DefaultStats()
}
}
switch node.NodeType {
case plan.Node_JOIN:
if needResetHashMapStats {
resetHashMapStats(node.Stats)
}
ndv := math.Min(leftStats.Outcnt, rightStats.Outcnt)
if ndv < 1 {
ndv = 1
}
//assume all join is not cross join
//will fix this in the future
//isCrossJoin := (len(node.OnList) == 0)
isCrossJoin := false
selectivity := math.Pow(rightStats.Selectivity, math.Pow(leftStats.Selectivity, 0.2))
selectivity_out := andSelectivity(leftStats.Selectivity, rightStats.Selectivity)
for _, pred := range node.OnList {
if pred.Ndv <= 0 {
pred.Ndv = getExprNdv(pred, builder)
}
}
switch node.JoinType {
case plan.Node_INNER:
outcnt := leftStats.Outcnt * rightStats.Outcnt / ndv
if !isCrossJoin {
outcnt *= selectivity
}
if outcnt < rightStats.Outcnt && leftStats.Selectivity > 0.95 {
outcnt = rightStats.Outcnt
}
node.Stats.Outcnt = outcnt
node.Stats.Cost = leftStats.Cost + rightStats.Cost
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
node.Stats.Selectivity = selectivity_out
case plan.Node_LEFT:
node.Stats.Outcnt = leftStats.Outcnt
node.Stats.Cost = leftStats.Cost + rightStats.Cost
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
node.Stats.Selectivity = selectivity_out
case plan.Node_RIGHT:
node.Stats.Outcnt = rightStats.Outcnt
node.Stats.Cost = leftStats.Cost + rightStats.Cost
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
node.Stats.Selectivity = selectivity_out
case plan.Node_OUTER:
node.Stats.Outcnt = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Cost = leftStats.Cost + rightStats.Cost
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
node.Stats.Selectivity = selectivity_out
case plan.Node_SEMI:
node.Stats.Outcnt = leftStats.Outcnt * selectivity
node.Stats.Cost = leftStats.Cost + rightStats.Cost
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
node.Stats.Selectivity = selectivity_out
case plan.Node_ANTI:
node.Stats.Outcnt = leftStats.Outcnt * (1 - rightStats.Selectivity) * 0.5
node.Stats.Cost = leftStats.Cost + rightStats.Cost
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
node.Stats.Selectivity = selectivity_out
case plan.Node_SINGLE, plan.Node_MARK:
node.Stats.Outcnt = leftStats.Outcnt
node.Stats.Cost = leftStats.Cost + rightStats.Cost
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
node.Stats.Selectivity = selectivity_out
}
case plan.Node_AGG:
if needResetHashMapStats {
resetHashMapStats(node.Stats)
}
if len(node.GroupBy) > 0 {
incnt := childStats.Outcnt
outcnt := 1.0
for _, groupby := range node.GroupBy {
ndv := getExprNdv(groupby, builder)
if ndv > 1 {
groupby.Ndv = ndv
outcnt *= ndv
}
}
if outcnt > incnt {
outcnt = math.Min(incnt, outcnt*math.Pow(childStats.Selectivity, 0.8))
}
node.Stats.Outcnt = outcnt
node.Stats.Cost = incnt + outcnt
node.Stats.HashmapStats.HashmapSize = outcnt
node.Stats.Selectivity = 1
if len(node.FilterList) > 0 {
node.Stats.Outcnt *= 0.0001
node.Stats.Selectivity *= 0.0001
}
} else {
node.Stats.Outcnt = 1
node.Stats.Cost = childStats.Cost
node.Stats.HashmapStats.HashmapSize = 1
node.Stats.Selectivity = 1
}
case plan.Node_UNION:
if needResetHashMapStats {
resetHashMapStats(node.Stats)
}
node.Stats.Outcnt = (leftStats.Outcnt + rightStats.Outcnt) * 0.7
node.Stats.Cost = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Selectivity = 1
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
case plan.Node_UNION_ALL:
node.Stats.Outcnt = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Cost = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Selectivity = 1
case plan.Node_INTERSECT:
if needResetHashMapStats {
resetHashMapStats(node.Stats)
}
node.Stats.Outcnt = math.Min(leftStats.Outcnt, rightStats.Outcnt) * 0.5
node.Stats.Cost = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Selectivity = 1
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
case plan.Node_INTERSECT_ALL:
if needResetHashMapStats {
resetHashMapStats(node.Stats)
}
node.Stats.Outcnt = math.Min(leftStats.Outcnt, rightStats.Outcnt) * 0.7
node.Stats.Cost = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Selectivity = 1
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
case plan.Node_MINUS:
if needResetHashMapStats {
resetHashMapStats(node.Stats)
}
minus := math.Max(leftStats.Outcnt, rightStats.Outcnt) - math.Min(leftStats.Outcnt, rightStats.Outcnt)
node.Stats.Outcnt = minus * 0.5
node.Stats.Cost = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Selectivity = 1
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
case plan.Node_MINUS_ALL:
if needResetHashMapStats {
resetHashMapStats(node.Stats)
}
minus := math.Max(leftStats.Outcnt, rightStats.Outcnt) - math.Min(leftStats.Outcnt, rightStats.Outcnt)
node.Stats.Outcnt = minus * 0.7
node.Stats.Cost = leftStats.Outcnt + rightStats.Outcnt
node.Stats.Selectivity = 1
node.Stats.HashmapStats.HashmapSize = rightStats.Outcnt
case plan.Node_VALUE_SCAN:
//do nothing and just return default stats, fix this in the future
/*
if node.RowsetData == nil {
node.Stats = DefaultStats()
} else {
colsData := node.RowsetData.Cols
rowCount := float64(len(colsData[0].Data))
blockNumber := rowCount/float64(options.DefaultBlockMaxRows) + 1
node.Stats = &plan.Stats{
TableCnt: (rowCount),
BlockNum: int32(blockNumber),
Outcnt: rowCount,
Cost: rowCount,
Selectivity: 1,
}
}
*/
case plan.Node_SINK_SCAN:
sourceNode := builder.qry.Steps[node.GetSourceStep()[0]]
node.Stats = builder.qry.Nodes[sourceNode].Stats
case plan.Node_RECURSIVE_SCAN:
sourceNode := builder.qry.Steps[node.GetSourceStep()[0]]
node.Stats = builder.qry.Nodes[sourceNode].Stats
case plan.Node_EXTERNAL_SCAN:
//calc for external scan is heavy, avoid recalc of this
if node.Stats == nil || node.Stats.TableCnt == 0 {
node.Stats = getExternalStats(node, builder)
}
case plan.Node_TABLE_SCAN:
//calc for scan is heavy. use leafNode to judge if scan need to recalculate
if node.ObjRef != nil && leafNode {
if len(node.BindingTags) > 0 {
builder.tag2Table[node.BindingTags[0]] = node.TableDef
}
newStats := calcScanStats(node, builder)
if needResetHashMapStats {
resetHashMapStats(newStats)
}
node.Stats = newStats
}
case plan.Node_FILTER:
//filters which can not push down to scan nodes. hard to estimate selectivity
node.Stats.Outcnt = childStats.Outcnt * 0.05
if node.Stats.Outcnt < 1 {
node.Stats.Outcnt = 1
}
node.Stats.Cost = childStats.Cost
node.Stats.Selectivity = 0.05
case plan.Node_FUNCTION_SCAN:
if !computeFunctionScan(node.TableDef.TblFunc.Name, node.TblFuncExprList, node.Stats) {
if len(node.Children) > 0 && childStats != nil {
node.Stats.Outcnt = childStats.Outcnt
node.Stats.Cost = childStats.Outcnt
node.Stats.Selectivity = childStats.Selectivity
}
}
default:
if len(node.Children) > 0 && childStats != nil {
node.Stats.Outcnt = childStats.Outcnt
node.Stats.Cost = childStats.Outcnt
node.Stats.Selectivity = childStats.Selectivity
}
}
// if there is a limit, outcnt is limit number
if node.Limit != nil {
if cExpr, ok := node.Limit.Expr.(*plan.Expr_Lit); ok {
if c, ok := cExpr.Lit.Value.(*plan.Literal_I64Val); ok {
node.Stats.Outcnt = float64(c.I64Val)
}
}
}
}
func computeFunctionScan(name string, exprs []*Expr, nodeStat *Stats) bool {
if name != "generate_series" {
return false
}
var cost float64
var canGetCost bool
if len(exprs) == 2 {
if exprs[0].Typ.Id != exprs[1].Typ.Id {
return false
}
cost, canGetCost = getCost(exprs[0], exprs[1], nil)
} else if len(exprs) == 3 {
if !(exprs[0].Typ.Id == exprs[1].Typ.Id && exprs[1].Typ.Id == exprs[2].Typ.Id) {
return false
}
cost, canGetCost = getCost(exprs[0], exprs[1], exprs[2])
} else {
return false
}
if !canGetCost {
return false
}
nodeStat.Outcnt = cost
nodeStat.TableCnt = cost
nodeStat.Cost = cost
nodeStat.Selectivity = 1
return true
}
func getCost(start *Expr, end *Expr, step *Expr) (float64, bool) {
var startNum, endNum, stepNum float64
var flag1, flag2, flag3 bool
getInt32Val := func(e *Expr) (float64, bool) {
if s, ok := e.Expr.(*plan.Expr_Lit); ok {
if v, ok := s.Lit.Value.(*plan.Literal_I32Val); ok && !s.Lit.Isnull {
return float64(v.I32Val), true
}
}
return 0, false
}
getInt64Val := func(e *Expr) (float64, bool) {
if s, ok := e.Expr.(*plan.Expr_Lit); ok {
if v, ok := s.Lit.Value.(*plan.Literal_I64Val); ok && !s.Lit.Isnull {
return float64(v.I64Val), true
}
}
return 0, false
}
switch start.Typ.Id {
case int32(types.T_int32):
startNum, flag1 = getInt32Val(start)
endNum, flag2 = getInt32Val(end)
flag3 = true
if step != nil {
stepNum, flag3 = getInt32Val(step)
}
if !(flag1 && flag2 && flag3) {
return 0, false
}
case int32(types.T_int64):
startNum, flag1 = getInt64Val(start)
endNum, flag2 = getInt64Val(end)
flag3 = true
if step != nil {
stepNum, flag3 = getInt64Val(step)
}
if !(flag1 && flag2 && flag3) {
return 0, false
}
}
if step == nil {
if startNum > endNum {
stepNum = -1
} else {
stepNum = 1
}
}
ret := (endNum - startNum) / stepNum
if ret < 0 {
return 0, false
}
return ret, true
}
func foldTableScanFilters(proc *process.Process, qry *Query, nodeId int32) error {
node := qry.Nodes[nodeId]
if node.NodeType == plan.Node_TABLE_SCAN && len(node.FilterList) > 0 {
for i, e := range node.FilterList {
foldedExpr, err := ConstantFold(batch.EmptyForConstFoldBatch, e, proc, false)
if err != nil {
return err
}
node.FilterList[i] = foldedExpr
}
}
for _, childId := range node.Children {
err := foldTableScanFilters(proc, qry, childId)
if err != nil {
return err
}
}
return nil
}
func recalcStatsByRuntimeFilter(node *plan.Node, runtimeFilterSel float64) {
if node.NodeType != plan.Node_TABLE_SCAN {
return
}
node.Stats.Cost *= runtimeFilterSel
node.Stats.Outcnt *= runtimeFilterSel
if node.Stats.Cost < 1 {
node.Stats.Cost = 1
}
node.Stats.BlockNum = int32(float64(node.Stats.BlockNum)*runtimeFilterSel) + 1
}
func calcScanStats(node *plan.Node, builder *QueryBuilder) *plan.Stats {
if !needStats(node.TableDef) {
return DefaultStats()
}
if shouldReturnMinimalStats(node) {
return DefaultMinimalStats()
}
if !builder.compCtx.Stats(node.ObjRef) {
return DefaultStats()
}
//get statsInfoMap from statscache
s := getStatsInfoByTableID(node.TableDef.TblId, builder)
if s == nil {
return DefaultStats()
}
stats := new(plan.Stats)
stats.TableCnt = s.TableCnt
var blockSel float64 = 1
var blockExprList []*plan.Expr
for i := range node.FilterList {
node.FilterList[i].Selectivity = estimateExprSelectivity(node.FilterList[i], builder)
currentBlockSel := estimateFilterBlockSelectivity(builder.GetContext(), node.FilterList[i], node.TableDef, builder)