-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathaggregate_builtins.go
1146 lines (994 loc) · 31.7 KB
/
aggregate_builtins.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 2015 The Cockroach Authors.
//
// 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 parser
import (
"bytes"
"fmt"
"math"
"golang.org/x/net/context"
"github.com/cockroachdb/apd"
"github.com/cockroachdb/cockroach/pkg/sql/mon"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/util/duration"
)
func initAggregateBuiltins() {
// Add all aggregates to the Builtins map after a few sanity checks.
for k, v := range Aggregates {
for i, a := range v {
if !a.impure {
panic(fmt.Sprintf("aggregate functions should all be impure, found %v", a))
}
if a.class != AggregateClass {
panic(fmt.Sprintf("aggregate functions should be marked with the AggregateClass "+
"function class, found %v", a))
}
if a.AggregateFunc == nil {
panic(fmt.Sprintf("aggregate functions should have AggregateFunc constructors, "+
"found %v", a))
}
if a.WindowFunc == nil {
panic(fmt.Sprintf("aggregate functions should have WindowFunc constructors, "+
"found %v", a))
}
// The aggregate functions are considered "row dependent". This is
// because each aggregate function application receives the set of
// grouped rows as implicit parameter. It may have a different
// value in every group, so it cannot be considered constant in
// the context of a data source.
v[i].needsRepeatedEvaluation = true
}
Builtins[k] = v
}
}
// AggregateFunc accumulates the result of a function of a Datum.
type AggregateFunc interface {
// Add accumulates the passed datums into the AggregateFunc.
// Most implementations require one and only one firstArg argument.
// If an aggregate function requires more than one argument,
// all additional arguments (after firstArg) are passed in as a
// variadic collection, otherArgs.
// This interface (as opposed to `args ...Datum`) avoids unnecessary
// allocation of otherArgs in the majority of cases.
Add(_ context.Context, firstArg Datum, otherArgs ...Datum) error
// Result returns the current value of the accumulation. This value
// will be a deep copy of any AggregateFunc internal state, so that
// it will not be mutated by additional calls to Add.
Result() (Datum, error)
// Close closes out the AggregateFunc and allows it to release any memory it
// requested during aggregation, and must be called upon completion of the
// aggregation.
Close(context.Context)
}
// Aggregates are a special class of builtin functions that are wrapped
// at execution in a bucketing layer to combine (aggregate) the result
// of the function being run over many rows.
// See `aggregateFuncHolder` in the sql package.
// In particular they must not be simplified during normalization
// (and thus must be marked as impure), even when they are given a
// constant argument (e.g. SUM(1)). This is because aggregate
// functions must return NULL when they are no rows in the source
// table, so their evaluation must always be delayed until query
// execution.
// Exported for use in documentation.
var Aggregates = map[string][]Builtin{
"array_agg": {
makeAggBuiltinWithReturnType(
[]Type{TypeAny},
func(args []TypedExpr) Type {
if len(args) == 0 {
return unknownReturnType
}
return TArray{args[0].ResolvedType()}
},
newArrayAggregate,
"Aggregates the selected values into an array.",
),
},
"avg": {
makeAggBuiltin([]Type{TypeInt}, TypeDecimal, newIntAvgAggregate,
"Calculates the average of the selected values."),
makeAggBuiltin([]Type{TypeFloat}, TypeFloat, newFloatAvgAggregate,
"Calculates the average of the selected values."),
makeAggBuiltin([]Type{TypeDecimal}, TypeDecimal, newDecimalAvgAggregate,
"Calculates the average of the selected values."),
},
"bool_and": {
makeAggBuiltin([]Type{TypeBool}, TypeBool, newBoolAndAggregate,
"Calculates the boolean value of `AND`ing all selected values."),
},
"bool_or": {
makeAggBuiltin([]Type{TypeBool}, TypeBool, newBoolOrAggregate,
"Calculates the boolean value of `OR`ing all selected values."),
},
"concat_agg": {
// TODO(knz): When CockroachDB supports STRING_AGG, CONCAT_AGG(X)
// should be substituted to STRING_AGG(X, '') and executed as
// such (no need for a separate implementation).
makeAggBuiltin([]Type{TypeString}, TypeString, newStringConcatAggregate,
"Concatenates all selected values."),
makeAggBuiltin([]Type{TypeBytes}, TypeBytes, newBytesConcatAggregate,
"Concatenates all selected values."),
// TODO(eisen): support collated strings when the type system properly
// supports parametric types.
},
"count": {
makeAggBuiltin([]Type{TypeAny}, TypeInt, newCountAggregate,
"Calculates the number of selected elements."),
},
"count_rows": {
{
impure: true,
class: AggregateClass,
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeInt),
AggregateFunc: newCountRowsAggregate,
WindowFunc: func(params []Type, evalCtx *EvalContext) WindowFunc {
return newAggregateWindow(newCountRowsAggregate(params, evalCtx))
},
Info: "Calculates the number of rows.",
},
},
"max": collectBuiltins(func(t Type) Builtin {
return makeAggBuiltin([]Type{t}, t, newMaxAggregate,
"Identifies the maximum selected value.")
}, TypesAnyNonArray...),
"min": collectBuiltins(func(t Type) Builtin {
return makeAggBuiltin([]Type{t}, t, newMinAggregate,
"Identifies the minimum selected value.")
}, TypesAnyNonArray...),
"sum_int": {
makeAggBuiltin([]Type{TypeInt}, TypeInt, newSmallIntSumAggregate,
"Calculates the sum of the selected values."),
},
"sum": {
makeAggBuiltin([]Type{TypeInt}, TypeDecimal, newIntSumAggregate,
"Calculates the sum of the selected values."),
makeAggBuiltin([]Type{TypeFloat}, TypeFloat, newFloatSumAggregate,
"Calculates the sum of the selected values."),
makeAggBuiltin([]Type{TypeDecimal}, TypeDecimal, newDecimalSumAggregate,
"Calculates the sum of the selected values."),
makeAggBuiltin([]Type{TypeInterval}, TypeInterval, newIntervalSumAggregate,
"Calculates the sum of the selected values."),
},
"variance": {
makeAggBuiltin([]Type{TypeInt}, TypeDecimal, newIntVarianceAggregate,
"Calculates the variance of the selected values."),
makeAggBuiltin([]Type{TypeDecimal}, TypeDecimal, newDecimalVarianceAggregate,
"Calculates the variance of the selected values."),
makeAggBuiltin([]Type{TypeFloat}, TypeFloat, newFloatVarianceAggregate,
"Calculates the variance of the selected values."),
},
"stddev": {
makeAggBuiltin([]Type{TypeInt}, TypeDecimal, newIntStdDevAggregate,
"Calculates the standard deviation of the selected values."),
makeAggBuiltin([]Type{TypeDecimal}, TypeDecimal, newDecimalStdDevAggregate,
"Calculates the standard deviation of the selected values."),
makeAggBuiltin([]Type{TypeFloat}, TypeFloat, newFloatStdDevAggregate,
"Calculates the standard deviation of the selected values."),
},
"xor_agg": {
makeAggBuiltin([]Type{TypeBytes}, TypeBytes, newBytesXorAggregate,
"Calculates the bitwise XOR of the selected values."),
makeAggBuiltin([]Type{TypeInt}, TypeInt, newIntXorAggregate,
"Calculates the bitwise XOR of the selected values."),
},
}
func makeAggBuiltin(
in []Type, ret Type, f func([]Type, *EvalContext) AggregateFunc, info string,
) Builtin {
return makeAggBuiltinWithReturnType(in, fixedReturnType(ret), f, info)
}
func makeAggBuiltinWithReturnType(
in []Type, retType returnTyper, f func([]Type, *EvalContext) AggregateFunc, info string,
) Builtin {
argTypes := make(ArgTypes, len(in))
for i, typ := range in {
argTypes[i].Name = fmt.Sprintf("arg%d", i)
argTypes[i].Typ = typ
}
return Builtin{
// See the comment about aggregate functions in the definitions
// of the Builtins array above.
impure: true,
class: AggregateClass,
Types: argTypes,
ReturnType: retType,
AggregateFunc: f,
WindowFunc: func(params []Type, evalCtx *EvalContext) WindowFunc {
return newAggregateWindow(f(params, evalCtx))
},
Info: info,
}
}
var _ AggregateFunc = &arrayAggregate{}
var _ AggregateFunc = &avgAggregate{}
var _ AggregateFunc = &countAggregate{}
var _ AggregateFunc = &MaxAggregate{}
var _ AggregateFunc = &MinAggregate{}
var _ AggregateFunc = &intSumAggregate{}
var _ AggregateFunc = &decimalSumAggregate{}
var _ AggregateFunc = &floatSumAggregate{}
var _ AggregateFunc = &stdDevAggregate{}
var _ AggregateFunc = &intVarianceAggregate{}
var _ AggregateFunc = &floatVarianceAggregate{}
var _ AggregateFunc = &decimalVarianceAggregate{}
var _ AggregateFunc = &identAggregate{}
var _ AggregateFunc = &concatAggregate{}
var _ AggregateFunc = &bytesXorAggregate{}
var _ AggregateFunc = &intXorAggregate{}
// In order to render the unaggregated (i.e. grouped) fields, during aggregation,
// the values for those fields have to be stored for each bucket.
// The `identAggregate` provides an "aggregate" function that actually
// just returns the last value passed to `add`, unchanged. For accumulating
// and rendering though it behaves like the other aggregate functions,
// allowing both those steps to avoid special-casing grouped vs aggregated fields.
type identAggregate struct {
val Datum
}
// NewIdentAggregate returns an identAggregate (see comment on struct).
func NewIdentAggregate(*EvalContext) AggregateFunc {
return &identAggregate{}
}
// Add sets the value to the passed datum.
func (a *identAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
// If we see at least one non-NULL value, ignore any NULLs.
// This is used in distributed multi-stage aggregations, where a local stage
// with multiple (parallel) instances feeds into a final stage. If some of the
// instances see no rows, they emit a NULL; the final IDENT aggregator needs
// to ignore these.
// TODO(radu): this - along with other hacks like special-handling of the nil
// result in (*aggregateGroupHolder).Eval - illustrates why IDENT as an
// aggregator is not a sound. We should remove this concept and handle GROUP
// BY columns separately in the groupNode and the aggregator processor
// (#12525).
if a.val == nil || datum != DNull {
a.val = datum
}
return nil
}
// Result returns the value most recently passed to Add.
func (a *identAggregate) Result() (Datum, error) {
// It is significant that identAggregate returns nil, and not DNull,
// if no result was known via Add(). See
// sql.(*aggregateFuncHolder).Eval() for details.
return a.val, nil
}
// Close is no-op in aggregates using constant space.
func (a *identAggregate) Close(context.Context) {}
type arrayAggregate struct {
arr *DArray
acc mon.BoundAccount
}
func newArrayAggregate(params []Type, evalCtx *EvalContext) AggregateFunc {
return &arrayAggregate{
arr: NewDArray(params[0]),
acc: evalCtx.Mon.MakeBoundAccount(),
}
}
// Add accumulates the passed datum into the array.
func (a *arrayAggregate) Add(ctx context.Context, datum Datum, _ ...Datum) error {
if err := a.acc.Grow(ctx, int64(datum.Size())); err != nil {
return err
}
if err := a.arr.Append(datum); err != nil {
return err
}
return nil
}
// Result returns an array of all datums passed to Add.
func (a *arrayAggregate) Result() (Datum, error) {
if len(a.arr.Array) > 0 {
return a.arr, nil
}
return DNull, nil
}
// Close allows the aggregate to release the memory it requested during
// operation.
func (a *arrayAggregate) Close(ctx context.Context) {
a.acc.Close(ctx)
}
type avgAggregate struct {
agg AggregateFunc
count int
}
func newIntAvgAggregate(params []Type, evalCtx *EvalContext) AggregateFunc {
return &avgAggregate{agg: newIntSumAggregate(params, evalCtx)}
}
func newFloatAvgAggregate(params []Type, evalCtx *EvalContext) AggregateFunc {
return &avgAggregate{agg: newFloatSumAggregate(params, evalCtx)}
}
func newDecimalAvgAggregate(params []Type, evalCtx *EvalContext) AggregateFunc {
return &avgAggregate{agg: newDecimalSumAggregate(params, evalCtx)}
}
// Add accumulates the passed datum into the average.
func (a *avgAggregate) Add(ctx context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
if err := a.agg.Add(ctx, datum); err != nil {
return err
}
a.count++
return nil
}
// Result returns the average of all datums passed to Add.
func (a *avgAggregate) Result() (Datum, error) {
sum, err := a.agg.Result()
if err != nil {
return nil, err
}
if sum == DNull {
return sum, nil
}
switch t := sum.(type) {
case *DFloat:
return NewDFloat(*t / DFloat(a.count)), nil
case *DDecimal:
count := apd.New(int64(a.count), 0)
_, err := DecimalCtx.Quo(&t.Decimal, &t.Decimal, count)
return t, err
default:
return nil, pgerror.NewErrorf(pgerror.CodeInternalError, "unexpected SUM result type: %s", t)
}
}
// Close is part of the AggregateFunc interface.
func (a *avgAggregate) Close(context.Context) {}
type concatAggregate struct {
forBytes bool
sawNonNull bool
result bytes.Buffer
acc mon.BoundAccount
}
func newBytesConcatAggregate(_ []Type, evalCtx *EvalContext) AggregateFunc {
return &concatAggregate{
forBytes: true,
acc: evalCtx.Mon.MakeBoundAccount(),
}
}
func newStringConcatAggregate(_ []Type, evalCtx *EvalContext) AggregateFunc {
return &concatAggregate{acc: evalCtx.Mon.MakeBoundAccount()}
}
func (a *concatAggregate) Add(ctx context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
a.sawNonNull = true
var arg string
if a.forBytes {
arg = string(*datum.(*DBytes))
} else {
arg = string(MustBeDString(datum))
}
if err := a.acc.Grow(ctx, int64(datum.Size())); err != nil {
return err
}
a.result.WriteString(arg)
return nil
}
func (a *concatAggregate) Result() (Datum, error) {
if !a.sawNonNull {
return DNull, nil
}
if a.forBytes {
res := DBytes(a.result.String())
return &res, nil
}
res := DString(a.result.String())
return &res, nil
}
// Close allows the aggregate to release the memory it requested during
// operation.
func (a *concatAggregate) Close(ctx context.Context) {
a.acc.Close(ctx)
}
type boolAndAggregate struct {
sawNonNull bool
result bool
}
func newBoolAndAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &boolAndAggregate{}
}
func (a *boolAndAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
if !a.sawNonNull {
a.sawNonNull = true
a.result = true
}
a.result = a.result && bool(*datum.(*DBool))
return nil
}
func (a *boolAndAggregate) Result() (Datum, error) {
if !a.sawNonNull {
return DNull, nil
}
return MakeDBool(DBool(a.result)), nil
}
// Close is part of the AggregateFunc interface.
func (a *boolAndAggregate) Close(context.Context) {}
type boolOrAggregate struct {
sawNonNull bool
result bool
}
func newBoolOrAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &boolOrAggregate{}
}
func (a *boolOrAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
a.sawNonNull = true
a.result = a.result || bool(*datum.(*DBool))
return nil
}
func (a *boolOrAggregate) Result() (Datum, error) {
if !a.sawNonNull {
return DNull, nil
}
return MakeDBool(DBool(a.result)), nil
}
// Close is part of the AggregateFunc interface.
func (a *boolOrAggregate) Close(context.Context) {}
type countAggregate struct {
count int
}
func newCountAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &countAggregate{}
}
func (a *countAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
a.count++
return nil
}
func (a *countAggregate) Result() (Datum, error) {
return NewDInt(DInt(a.count)), nil
}
// Close is part of the AggregateFunc interface.
func (a *countAggregate) Close(context.Context) {}
type countRowsAggregate struct {
count int
}
func newCountRowsAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &countRowsAggregate{}
}
func (a *countRowsAggregate) Add(_ context.Context, _ Datum, _ ...Datum) error {
a.count++
return nil
}
func (a *countRowsAggregate) Result() (Datum, error) {
return NewDInt(DInt(a.count)), nil
}
// Close is part of the AggregateFunc interface.
func (a *countRowsAggregate) Close(context.Context) {}
// MaxAggregate keeps track of the largest value passed to Add.
type MaxAggregate struct {
max Datum
evalCtx *EvalContext
}
func newMaxAggregate(_ []Type, evalCtx *EvalContext) AggregateFunc {
return &MaxAggregate{evalCtx: evalCtx}
}
// Add sets the max to the larger of the current max or the passed datum.
func (a *MaxAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
if a.max == nil {
a.max = datum
return nil
}
c := a.max.Compare(a.evalCtx, datum)
if c < 0 {
a.max = datum
}
return nil
}
// Result returns the largest value passed to Add.
func (a *MaxAggregate) Result() (Datum, error) {
if a.max == nil {
return DNull, nil
}
return a.max, nil
}
// Close is part of the AggregateFunc interface.
func (a *MaxAggregate) Close(context.Context) {}
// MinAggregate keeps track of the smallest value passed to Add.
type MinAggregate struct {
min Datum
evalCtx *EvalContext
}
func newMinAggregate(_ []Type, evalCtx *EvalContext) AggregateFunc {
return &MinAggregate{evalCtx: evalCtx}
}
// Add sets the min to the smaller of the current min or the passed datum.
func (a *MinAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
if a.min == nil {
a.min = datum
return nil
}
c := a.min.Compare(a.evalCtx, datum)
if c > 0 {
a.min = datum
}
return nil
}
// Result returns the smallest value passed to Add.
func (a *MinAggregate) Result() (Datum, error) {
if a.min == nil {
return DNull, nil
}
return a.min, nil
}
// Close is part of the AggregateFunc interface.
func (a *MinAggregate) Close(context.Context) {}
type smallIntSumAggregate struct {
sum int64
seenNonNull bool
}
func newSmallIntSumAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &smallIntSumAggregate{}
}
// Add adds the value of the passed datum to the sum.
func (a *smallIntSumAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
a.sum += int64(MustBeDInt(datum))
a.seenNonNull = true
return nil
}
// Result returns the sum.
func (a *smallIntSumAggregate) Result() (Datum, error) {
if !a.seenNonNull {
return DNull, nil
}
return NewDInt(DInt(a.sum)), nil
}
// Close is part of the AggregateFunc interface.
func (a *smallIntSumAggregate) Close(context.Context) {}
type intSumAggregate struct {
// Either the `intSum` and `decSum` fields contains the
// result. Which one is used is determined by the `large` field
// below.
intSum int64
decSum DDecimal
tmpDec apd.Decimal
large bool
seenNonNull bool
}
func newIntSumAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &intSumAggregate{}
}
// Add adds the value of the passed datum to the sum.
func (a *intSumAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
t := int64(MustBeDInt(datum))
if t != 0 {
// The sum can be computed using a single int64 as long as the
// result of the addition does not overflow. However since Go
// does not provide checked addition, we have to check for the
// overflow explicitly.
if !a.large {
r, ok := addWithOverflow(a.intSum, t)
if ok {
a.intSum = r
} else {
// And overflow was detected; go to large integers, but keep the
// sum computed so far.
a.large = true
a.decSum.SetCoefficient(a.intSum)
}
}
if a.large {
a.tmpDec.SetCoefficient(t)
_, err := ExactCtx.Add(&a.decSum.Decimal, &a.decSum.Decimal, &a.tmpDec)
if err != nil {
return err
}
}
}
a.seenNonNull = true
return nil
}
// Result returns the sum.
func (a *intSumAggregate) Result() (Datum, error) {
if !a.seenNonNull {
return DNull, nil
}
dd := &DDecimal{}
if a.large {
dd.Set(&a.decSum.Decimal)
} else {
dd.SetCoefficient(a.intSum)
}
return dd, nil
}
// Close is part of the AggregateFunc interface.
func (a *intSumAggregate) Close(context.Context) {}
type decimalSumAggregate struct {
sum apd.Decimal
sawNonNull bool
}
func newDecimalSumAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &decimalSumAggregate{}
}
// Add adds the value of the passed datum to the sum.
func (a *decimalSumAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
t := datum.(*DDecimal)
_, err := ExactCtx.Add(&a.sum, &a.sum, &t.Decimal)
if err != nil {
return err
}
a.sawNonNull = true
return nil
}
// Result returns the sum.
func (a *decimalSumAggregate) Result() (Datum, error) {
if !a.sawNonNull {
return DNull, nil
}
dd := &DDecimal{}
dd.Set(&a.sum)
return dd, nil
}
// Close is part of the AggregateFunc interface.
func (a *decimalSumAggregate) Close(context.Context) {}
type floatSumAggregate struct {
sum float64
sawNonNull bool
}
func newFloatSumAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &floatSumAggregate{}
}
// Add adds the value of the passed datum to the sum.
func (a *floatSumAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
t := datum.(*DFloat)
a.sum += float64(*t)
a.sawNonNull = true
return nil
}
// Result returns the sum.
func (a *floatSumAggregate) Result() (Datum, error) {
if !a.sawNonNull {
return DNull, nil
}
return NewDFloat(DFloat(a.sum)), nil
}
// Close is part of the AggregateFunc interface.
func (a *floatSumAggregate) Close(context.Context) {}
type intervalSumAggregate struct {
sum duration.Duration
sawNonNull bool
}
func newIntervalSumAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &intervalSumAggregate{}
}
// Add adds the value of the passed datum to the sum.
func (a *intervalSumAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
t := datum.(*DInterval).Duration
a.sum = a.sum.Add(t)
a.sawNonNull = true
return nil
}
// Result returns the sum.
func (a *intervalSumAggregate) Result() (Datum, error) {
if !a.sawNonNull {
return DNull, nil
}
return &DInterval{Duration: a.sum}, nil
}
// Close is part of the AggregateFunc interface.
func (a *intervalSumAggregate) Close(context.Context) {}
type intVarianceAggregate struct {
agg *decimalVarianceAggregate
// Used for passing int64s as *apd.Decimal values.
tmpDec DDecimal
}
func newIntVarianceAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &intVarianceAggregate{
agg: newDecimalVariance(),
}
}
func (a *intVarianceAggregate) Add(ctx context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
a.tmpDec.SetCoefficient(int64(MustBeDInt(datum)))
return a.agg.Add(ctx, &a.tmpDec)
}
func (a *intVarianceAggregate) Result() (Datum, error) {
return a.agg.Result()
}
// Close is part of the AggregateFunc interface.
func (a *intVarianceAggregate) Close(context.Context) {}
type floatVarianceAggregate struct {
count int
mean float64
sqrDiff float64
}
func newFloatVarianceAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return &floatVarianceAggregate{}
}
func (a *floatVarianceAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
f := float64(*datum.(*DFloat))
// Uses the Knuth/Welford method for accurately computing variance online in a
// single pass. See http://www.johndcook.com/blog/standard_deviation/ and
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm.
a.count++
delta := f - a.mean
a.mean += delta / float64(a.count)
a.sqrDiff += delta * (f - a.mean)
return nil
}
func (a *floatVarianceAggregate) Result() (Datum, error) {
if a.count < 2 {
return DNull, nil
}
return NewDFloat(DFloat(a.sqrDiff / (float64(a.count) - 1))), nil
}
// Close is part of the AggregateFunc interface.
func (a *floatVarianceAggregate) Close(context.Context) {}
type decimalVarianceAggregate struct {
// Variables used across iterations.
ed *apd.ErrDecimal
count apd.Decimal
mean apd.Decimal
sqrDiff apd.Decimal
// Variables used as scratch space within iterations.
delta apd.Decimal
tmp apd.Decimal
}
func newDecimalVariance() *decimalVarianceAggregate {
// Use extra internal precision during variance and stddev to protect against
// order changes that can happen in dist SQL. The additional 3 here should
// allow for correctness up to 1000 more worst case inputs than non-worst
// case inputs. See #13689 for more analysis and other algorithms.
c := DecimalCtx.WithPrecision(DecimalCtx.Precision + 3)
ed := apd.MakeErrDecimal(c)
return &decimalVarianceAggregate{
ed: &ed,
}
}
func newDecimalVarianceAggregate(_ []Type, _ *EvalContext) AggregateFunc {
return newDecimalVariance()
}
// Read-only constants used for compuation.
var (
decimalOne = apd.New(1, 0)
decimalTwo = apd.New(2, 0)
)
func (a *decimalVarianceAggregate) Add(_ context.Context, datum Datum, _ ...Datum) error {
if datum == DNull {
return nil
}
d := &datum.(*DDecimal).Decimal
// Uses the Knuth/Welford method for accurately computing variance online in a
// single pass. See http://www.johndcook.com/blog/standard_deviation/ and
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm.
a.ed.Add(&a.count, &a.count, decimalOne)
a.ed.Sub(&a.delta, d, &a.mean)
a.ed.Quo(&a.tmp, &a.delta, &a.count)
a.ed.Add(&a.mean, &a.mean, &a.tmp)
a.ed.Sub(&a.tmp, d, &a.mean)
a.ed.Add(&a.sqrDiff, &a.sqrDiff, a.ed.Mul(&a.delta, &a.delta, &a.tmp))
return a.ed.Err()
}
func (a *decimalVarianceAggregate) Result() (Datum, error) {
if a.count.Cmp(decimalTwo) < 0 {
return DNull, nil
}
a.ed.Sub(&a.tmp, &a.count, decimalOne)
dd := &DDecimal{}
a.ed.Ctx = DecimalCtx
a.ed.Quo(&dd.Decimal, &a.sqrDiff, &a.tmp)
if err := a.ed.Err(); err != nil {
return nil, err
}
// Remove trailing zeros. Depending on the order in which the input
// is processed, some number of trailing zeros could be added to the
// output. Remove them so that the results are the same regardless of order.
dd.Decimal.Reduce(&dd.Decimal)
return dd, nil
}
// Close is part of the AggregateFunc interface.
func (a *decimalVarianceAggregate) Close(context.Context) {}
type stdDevAggregate struct {
agg AggregateFunc
}
func newIntStdDevAggregate(params []Type, evalCtx *EvalContext) AggregateFunc {
return &stdDevAggregate{agg: newIntVarianceAggregate(params, evalCtx)}
}
func newFloatStdDevAggregate(params []Type, evalCtx *EvalContext) AggregateFunc {
return &stdDevAggregate{agg: newFloatVarianceAggregate(params, evalCtx)}
}
func newDecimalStdDevAggregate(params []Type, evalCtx *EvalContext) AggregateFunc {
return &stdDevAggregate{agg: newDecimalVarianceAggregate(params, evalCtx)}
}
// Add implements the AggregateFunc interface.
func (a *stdDevAggregate) Add(ctx context.Context, datum Datum, _ ...Datum) error {
return a.agg.Add(ctx, datum)
}
// Result computes the square root of the variance.
func (a *stdDevAggregate) Result() (Datum, error) {
variance, err := a.agg.Result()
if err != nil {
return nil, err
}
if variance == DNull {
return variance, nil
}
switch t := variance.(type) {
case *DFloat:
return NewDFloat(DFloat(math.Sqrt(float64(*t)))), nil
case *DDecimal:
_, err := DecimalCtx.Sqrt(&t.Decimal, &t.Decimal)
return t, err
}
return nil, pgerror.NewErrorf(pgerror.CodeInternalError, "unexpected variance result type: %s", variance.ResolvedType())
}
// Close is part of the AggregateFunc interface.
func (a *stdDevAggregate) Close(context.Context) {}
var _ Visitor = &IsAggregateVisitor{}
type bytesXorAggregate struct {
sum []byte
sawNonNull bool
}