/
aggregate_functions.cpp
3025 lines (2657 loc) · 127 KB
/
aggregate_functions.cpp
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
// This file is copied from
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/exprs/aggregate-functions.cpp
// and modified by Doris
// include aggregate_functions.h first to make sure that all need includes is written in header files
#include "exprs/aggregate_functions.h"
#include <math.h>
#include <sstream>
#include <unordered_set>
#include "common/logging.h"
#include "exprs/anyval_util.h"
#include "exprs/hybrid_set.h"
#include "runtime/datetime_value.h"
#include "runtime/decimalv2_value.h"
#include "runtime/runtime_state.h"
#include "runtime/string_value.h"
#include "util/counts.h"
#include "util/debug_util.h"
#include "util/tdigest.h"
// TODO: this file should be cross compiled and then all of the builtin
// aggregate functions will have a codegen enabled path. Then we can remove
// the custom code in aggregation node.
namespace doris {
using doris_udf::FunctionContext;
using doris_udf::BooleanVal;
using doris_udf::TinyIntVal;
using doris_udf::SmallIntVal;
using doris_udf::IntVal;
using doris_udf::BigIntVal;
using doris_udf::LargeIntVal;
using doris_udf::FloatVal;
using doris_udf::DoubleVal;
using doris_udf::DecimalV2Val;
using doris_udf::DateTimeVal;
using doris_udf::StringVal;
using doris_udf::AnyVal;
// Delimiter to use if the separator is nullptr.
static const StringVal DEFAULT_STRING_CONCAT_DELIM((uint8_t*)", ", 2);
void AggregateFunctions::init_null(FunctionContext*, AnyVal* dst) {
dst->is_null = true;
}
template <typename T>
void AggregateFunctions::init_zero_not_null(FunctionContext*, T* dst) {
dst->is_null = false;
dst->val = 0;
}
template <>
void AggregateFunctions::init_zero_not_null(FunctionContext*, DecimalV2Val* dst) {
dst->is_null = false;
dst->set_to_zero();
}
template <typename T>
void AggregateFunctions::init_zero(FunctionContext*, T* dst) {
dst->is_null = false;
dst->val = 0;
}
template <>
void AggregateFunctions::init_zero(FunctionContext*, DecimalV2Val* dst) {
dst->is_null = false;
dst->set_to_zero();
}
template <typename T>
void AggregateFunctions::init_zero_null(FunctionContext*, T* dst) {
dst->is_null = true;
dst->val = 0;
}
template <>
void AggregateFunctions::init_zero_null(FunctionContext*, DecimalV2Val* dst) {
dst->is_null = true;
dst->set_to_zero();
}
template <typename SRC_VAL, typename DST_VAL>
void AggregateFunctions::sum_remove(FunctionContext* ctx, const SRC_VAL& src, DST_VAL* dst) {
// Do not count null values towards the number of removes
if (src.is_null) {
ctx->impl()->increment_num_removes(-1);
}
if (ctx->impl()->num_removes() >= ctx->impl()->num_updates()) {
*dst = DST_VAL::null();
return;
}
if (src.is_null) {
return;
}
if (dst->is_null) {
init_zero_not_null<DST_VAL>(ctx, dst);
}
dst->val -= src.val;
}
template <>
void AggregateFunctions::sum_remove(FunctionContext* ctx, const DecimalV2Val& src,
DecimalV2Val* dst) {
if (ctx->impl()->num_removes() >= ctx->impl()->num_updates()) {
*dst = DecimalV2Val::null();
return;
}
if (src.is_null) {
return;
}
if (dst->is_null) {
init_zero_not_null<DecimalV2Val>(ctx, dst);
}
DecimalV2Value new_src = DecimalV2Value::from_decimal_val(src);
DecimalV2Value new_dst = DecimalV2Value::from_decimal_val(*dst);
new_dst = new_dst - new_src;
new_dst.to_decimal_val(dst);
}
StringVal AggregateFunctions::string_val_get_value(FunctionContext* ctx, const StringVal& src) {
if (src.is_null) {
return src;
}
StringVal result(ctx, src.len);
memcpy(result.ptr, src.ptr, src.len);
return result;
}
StringVal AggregateFunctions::string_val_serialize_or_finalize(FunctionContext* ctx,
const StringVal& src) {
StringVal result = string_val_get_value(ctx, src);
if (!src.is_null) {
ctx->free(src.ptr);
}
return result;
}
void AggregateFunctions::count_update(FunctionContext*, const AnyVal& src, BigIntVal* dst) {
DCHECK(!dst->is_null);
if (!src.is_null) {
++dst->val;
}
}
void AggregateFunctions::count_merge(FunctionContext*, const BigIntVal& src, BigIntVal* dst) {
DCHECK(!dst->is_null);
DCHECK(!src.is_null);
dst->val += src.val;
}
void AggregateFunctions::count_remove(FunctionContext*, const AnyVal& src, BigIntVal* dst) {
DCHECK(!dst->is_null);
if (!src.is_null) {
--dst->val;
DCHECK_GE(dst->val, 0);
}
}
struct PercentileState {
Counts counts;
double quantile = -1.0;
};
void AggregateFunctions::percentile_init(FunctionContext* ctx, StringVal* dst) {
dst->is_null = false;
dst->len = sizeof(PercentileState);
dst->ptr = (uint8_t*)new PercentileState();
}
template <typename T>
void AggregateFunctions::percentile_update(FunctionContext* ctx, const T& src,
const DoubleVal& quantile, StringVal* dst) {
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(PercentileState), dst->len);
PercentileState* percentile = reinterpret_cast<PercentileState*>(dst->ptr);
percentile->counts.increment(src.val, 1);
percentile->quantile = quantile.val;
}
void AggregateFunctions::percentile_merge(FunctionContext* ctx, const StringVal& src,
StringVal* dst) {
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(PercentileState), dst->len);
double quantile;
memcpy(&quantile, src.ptr, sizeof(double));
PercentileState* src_percentile = new PercentileState();
src_percentile->quantile = quantile;
src_percentile->counts.unserialize(src.ptr + sizeof(double));
PercentileState* dst_percentile = reinterpret_cast<PercentileState*>(dst->ptr);
dst_percentile->counts.merge(&src_percentile->counts);
if (dst_percentile->quantile == -1.0) {
dst_percentile->quantile = quantile;
}
delete src_percentile;
}
StringVal AggregateFunctions::percentile_serialize(FunctionContext* ctx, const StringVal& src) {
DCHECK(!src.is_null);
PercentileState* percentile = reinterpret_cast<PercentileState*>(src.ptr);
uint32_t serialize_size = percentile->counts.serialized_size();
StringVal result(ctx, sizeof(double) + serialize_size);
memcpy(result.ptr, &percentile->quantile, sizeof(double));
percentile->counts.serialize(result.ptr + sizeof(double));
delete percentile;
return result;
}
DoubleVal AggregateFunctions::percentile_finalize(FunctionContext* ctx, const StringVal& src) {
PercentileState* percentile = reinterpret_cast<PercentileState*>(src.ptr);
double quantile = percentile->quantile;
auto result = percentile->counts.terminate(quantile);
delete percentile;
return result;
}
struct PercentileApproxState {
public:
PercentileApproxState() : digest(new TDigest()) {}
PercentileApproxState(double compression) : digest(new TDigest(compression)) {}
~PercentileApproxState() { delete digest; }
static constexpr double INIT_QUANTILE = -1.0;
TDigest* digest = nullptr;
double targetQuantile = INIT_QUANTILE;
};
void AggregateFunctions::percentile_approx_init(FunctionContext* ctx, StringVal* dst) {
dst->is_null = false;
dst->len = sizeof(PercentileApproxState);
const AnyVal* digest_compression = ctx->get_constant_arg(2);
if (digest_compression != nullptr) {
double compression = reinterpret_cast<const DoubleVal*>(digest_compression)->val;
if (compression >= 2048 && compression <= 10000) {
dst->ptr = (uint8_t*)new PercentileApproxState(compression);
return;
}
}
dst->ptr = (uint8_t*)new PercentileApproxState();
};
template <typename T>
void AggregateFunctions::percentile_approx_update(FunctionContext* ctx, const T& src,
const DoubleVal& quantile, StringVal* dst) {
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(PercentileApproxState), dst->len);
PercentileApproxState* percentile = reinterpret_cast<PercentileApproxState*>(dst->ptr);
percentile->digest->add(src.val);
percentile->targetQuantile = quantile.val;
}
template <typename T>
void AggregateFunctions::percentile_approx_update(FunctionContext* ctx, const T& src,
const DoubleVal& quantile,
const DoubleVal& digest_compression,
StringVal* dst) {
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(PercentileApproxState), dst->len);
PercentileApproxState* percentile = reinterpret_cast<PercentileApproxState*>(dst->ptr);
percentile->digest->add(src.val);
percentile->targetQuantile = quantile.val;
}
StringVal AggregateFunctions::percentile_approx_serialize(FunctionContext* ctx,
const StringVal& src) {
DCHECK(!src.is_null);
PercentileApproxState* percentile = reinterpret_cast<PercentileApproxState*>(src.ptr);
uint32_t serialized_size = percentile->digest->serialized_size();
StringVal result(ctx, sizeof(double) + serialized_size);
memcpy(result.ptr, &percentile->targetQuantile, sizeof(double));
percentile->digest->serialize(result.ptr + sizeof(double));
delete percentile;
return result;
}
void AggregateFunctions::percentile_approx_merge(FunctionContext* ctx, const StringVal& src,
StringVal* dst) {
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(PercentileApproxState), dst->len);
double quantile;
memcpy(&quantile, src.ptr, sizeof(double));
PercentileApproxState* src_percentile = new PercentileApproxState();
src_percentile->targetQuantile = quantile;
src_percentile->digest->unserialize(src.ptr + sizeof(double));
PercentileApproxState* dst_percentile = reinterpret_cast<PercentileApproxState*>(dst->ptr);
dst_percentile->digest->merge(src_percentile->digest);
// dst_percentile->targetQuantile only need set once from child result
// for example:
// child result targetQuantile is (0.5, -1), we should set 0.5 once to make sure correct result
if (dst_percentile->targetQuantile == PercentileApproxState::INIT_QUANTILE) {
dst_percentile->targetQuantile = quantile;
}
delete src_percentile;
}
DoubleVal AggregateFunctions::percentile_approx_finalize(FunctionContext* ctx,
const StringVal& src) {
PercentileApproxState* percentile = reinterpret_cast<PercentileApproxState*>(src.ptr);
double quantile = percentile->targetQuantile;
double result = percentile->digest->quantile(quantile);
delete percentile;
if (isnan(result)) {
return DoubleVal(result).null();
} else {
return DoubleVal(result);
}
}
struct AvgState {
double sum = 0;
int64_t count = 0;
};
struct DecimalV2AvgState {
DecimalV2Val sum;
int64_t count = 0;
};
void AggregateFunctions::avg_init(FunctionContext* ctx, StringVal* dst) {
dst->is_null = false;
dst->len = sizeof(AvgState);
dst->ptr = ctx->allocate(dst->len);
new (dst->ptr) AvgState;
}
void AggregateFunctions::decimalv2_avg_init(FunctionContext* ctx, StringVal* dst) {
dst->is_null = false;
dst->len = sizeof(DecimalV2AvgState);
// The memory for int128 need to be aligned by 16.
// So the constructor has been used instead of allocating memory.
// Also, it will be release in finalize.
dst->ptr = (uint8_t*)new DecimalV2AvgState;
}
template <typename T>
void AggregateFunctions::avg_update(FunctionContext* ctx, const T& src, StringVal* dst) {
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(AvgState), dst->len);
AvgState* avg = reinterpret_cast<AvgState*>(dst->ptr);
avg->sum += src.val;
++avg->count;
}
void AggregateFunctions::decimalv2_avg_update(FunctionContext* ctx, const DecimalV2Val& src,
StringVal* dst) {
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(DecimalV2AvgState), dst->len);
DecimalV2AvgState* avg = reinterpret_cast<DecimalV2AvgState*>(dst->ptr);
DecimalV2Value v1 = DecimalV2Value::from_decimal_val(avg->sum);
DecimalV2Value v2 = DecimalV2Value::from_decimal_val(src);
DecimalV2Value v = v1 + v2;
v.to_decimal_val(&avg->sum);
++avg->count;
}
StringVal AggregateFunctions::decimalv2_avg_serialize(FunctionContext* ctx, const StringVal& src) {
DCHECK(!src.is_null);
StringVal result(ctx, src.len);
memcpy(result.ptr, src.ptr, src.len);
delete (DecimalV2AvgState*)src.ptr;
return result;
}
template <typename T>
void AggregateFunctions::avg_remove(FunctionContext* ctx, const T& src, StringVal* dst) {
// Remove doesn't need to explicitly check the number of calls to Update() or Remove()
// because Finalize() returns nullptr if count is 0.
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(AvgState), dst->len);
AvgState* avg = reinterpret_cast<AvgState*>(dst->ptr);
avg->sum -= src.val;
--avg->count;
DCHECK_GE(avg->count, 0);
}
void AggregateFunctions::decimalv2_avg_remove(doris_udf::FunctionContext* ctx,
const DecimalV2Val& src, StringVal* dst) {
// Remove doesn't need to explicitly check the number of calls to Update() or Remove()
// because Finalize() returns nullptr if count is 0.
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(DecimalV2AvgState), dst->len);
DecimalV2AvgState* avg = reinterpret_cast<DecimalV2AvgState*>(dst->ptr);
DecimalV2Value v1 = DecimalV2Value::from_decimal_val(avg->sum);
DecimalV2Value v2 = DecimalV2Value::from_decimal_val(src);
DecimalV2Value v = v1 - v2;
v.to_decimal_val(&avg->sum);
--avg->count;
DCHECK_GE(avg->count, 0);
}
void AggregateFunctions::avg_merge(FunctionContext* ctx, const StringVal& src, StringVal* dst) {
const AvgState* src_struct = reinterpret_cast<const AvgState*>(src.ptr);
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(AvgState), dst->len);
AvgState* dst_struct = reinterpret_cast<AvgState*>(dst->ptr);
dst_struct->sum += src_struct->sum;
dst_struct->count += src_struct->count;
}
void AggregateFunctions::decimalv2_avg_merge(FunctionContext* ctx, const StringVal& src,
StringVal* dst) {
DecimalV2AvgState src_struct;
memcpy(&src_struct, src.ptr, sizeof(DecimalV2AvgState));
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(DecimalV2AvgState), dst->len);
DecimalV2AvgState* dst_struct = reinterpret_cast<DecimalV2AvgState*>(dst->ptr);
DecimalV2Value v1 = DecimalV2Value::from_decimal_val(dst_struct->sum);
DecimalV2Value v2 = DecimalV2Value::from_decimal_val(src_struct.sum);
DecimalV2Value v = v1 + v2;
v.to_decimal_val(&dst_struct->sum);
dst_struct->count += src_struct.count;
}
DoubleVal AggregateFunctions::avg_get_value(FunctionContext* ctx, const StringVal& src) {
AvgState* val_struct = reinterpret_cast<AvgState*>(src.ptr);
if (val_struct->count == 0) {
return DoubleVal::null();
}
return DoubleVal(val_struct->sum / val_struct->count);
}
DecimalV2Val AggregateFunctions::decimalv2_avg_get_value(FunctionContext* ctx,
const StringVal& src) {
DecimalV2AvgState* val_struct = reinterpret_cast<DecimalV2AvgState*>(src.ptr);
if (val_struct->count == 0) {
return DecimalV2Val::null();
}
DecimalV2Value v1 = DecimalV2Value::from_decimal_val(val_struct->sum);
DecimalV2Value v = v1 / DecimalV2Value(val_struct->count, 0);
DecimalV2Val res;
v.to_decimal_val(&res);
return res;
}
DoubleVal AggregateFunctions::avg_finalize(FunctionContext* ctx, const StringVal& src) {
if (src.is_null) {
return DoubleVal::null();
}
DoubleVal result = avg_get_value(ctx, src);
ctx->free(src.ptr);
return result;
}
DecimalV2Val AggregateFunctions::decimalv2_avg_finalize(FunctionContext* ctx,
const StringVal& src) {
DecimalV2Val result = decimalv2_avg_get_value(ctx, src);
delete (DecimalV2AvgState*)src.ptr;
return result;
}
void AggregateFunctions::timestamp_avg_update(FunctionContext* ctx, const DateTimeVal& src,
StringVal* dst) {
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(AvgState), dst->len);
AvgState* avg = reinterpret_cast<AvgState*>(dst->ptr);
double val = DateTimeValue::from_datetime_val(src);
avg->sum += val;
++avg->count;
}
void AggregateFunctions::timestamp_avg_remove(FunctionContext* ctx, const DateTimeVal& src,
StringVal* dst) {
if (src.is_null) {
return;
}
DCHECK(dst->ptr != nullptr);
DCHECK_EQ(sizeof(AvgState), dst->len);
AvgState* avg = reinterpret_cast<AvgState*>(dst->ptr);
double val = DateTimeValue::from_datetime_val(src);
avg->sum -= val;
--avg->count;
DCHECK_GE(avg->count, 0);
}
DateTimeVal AggregateFunctions::timestamp_avg_get_value(FunctionContext* ctx,
const StringVal& src) {
AvgState* val_struct = reinterpret_cast<AvgState*>(src.ptr);
if (val_struct->count == 0) {
return DateTimeVal::null();
}
DateTimeValue tv(val_struct->sum / val_struct->count);
DateTimeVal result;
tv.to_datetime_val(&result);
return result;
}
DateTimeVal AggregateFunctions::timestamp_avg_finalize(FunctionContext* ctx, const StringVal& src) {
if (src.is_null) {
return DateTimeVal::null();
}
DateTimeVal result = timestamp_avg_get_value(ctx, src);
ctx->free(src.ptr);
return result;
}
void AggregateFunctions::count_star_update(FunctionContext*, BigIntVal* dst) {
DCHECK(!dst->is_null);
++dst->val;
}
void AggregateFunctions::count_star_remove(FunctionContext*, BigIntVal* dst) {
DCHECK(!dst->is_null);
--dst->val;
DCHECK_GE(dst->val, 0);
}
template <typename SRC_VAL, typename DST_VAL>
void AggregateFunctions::sum(FunctionContext* ctx, const SRC_VAL& src, DST_VAL* dst) {
if (src.is_null) {
return;
}
if (dst->is_null) {
init_zero_not_null<DST_VAL>(ctx, dst);
}
dst->val += src.val;
}
template <>
void AggregateFunctions::sum(FunctionContext* ctx, const DecimalV2Val& src, DecimalV2Val* dst) {
if (src.is_null) {
return;
}
if (dst->is_null) {
init_zero_not_null<DecimalV2Val>(ctx, dst);
}
DecimalV2Value new_src = DecimalV2Value::from_decimal_val(src);
DecimalV2Value new_dst = DecimalV2Value::from_decimal_val(*dst);
new_dst = new_dst + new_src;
new_dst.to_decimal_val(dst);
}
template <typename T>
void AggregateFunctions::min_init(FunctionContext* ctx, T* dst) {
auto val = AnyValUtil::max_val<T>(ctx);
// set to null when intermediate slot is nullable
val.is_null = true;
*dst = val;
}
template <typename T>
void AggregateFunctions::min(FunctionContext*, const T& src, T* dst) {
if (src.is_null) {
return;
}
if (dst->is_null || src.val < dst->val) {
*dst = src;
}
}
template <typename T>
void AggregateFunctions::max_init(FunctionContext* ctx, T* dst) {
auto val = AnyValUtil::min_val<T>(ctx);
// set to null when intermediate slot is nullable
val.is_null = true;
*dst = val;
}
template <typename T>
void AggregateFunctions::max(FunctionContext*, const T& src, T* dst) {
if (src.is_null) {
return;
}
if (dst->is_null || src.val > dst->val) {
*dst = src;
}
}
template <>
void AggregateFunctions::min(FunctionContext*, const DecimalV2Val& src, DecimalV2Val* dst) {
if (src.is_null) {
return;
}
if (dst->is_null) {
*dst = src;
} else {
DecimalV2Value new_src = DecimalV2Value::from_decimal_val(src);
DecimalV2Value new_dst = DecimalV2Value::from_decimal_val(*dst);
if (new_src < new_dst) {
*dst = src;
}
}
}
template <>
void AggregateFunctions::max(FunctionContext*, const DecimalV2Val& src, DecimalV2Val* dst) {
if (src.is_null) {
return;
}
if (dst->is_null) {
*dst = src;
} else {
DecimalV2Value new_src = DecimalV2Value::from_decimal_val(src);
DecimalV2Value new_dst = DecimalV2Value::from_decimal_val(*dst);
if (new_src > new_dst) {
*dst = src;
}
}
}
void AggregateFunctions::init_null_string(FunctionContext* c, StringVal* dst) {
dst->is_null = true;
dst->ptr = nullptr;
dst->len = 0;
}
template <>
void AggregateFunctions::min(FunctionContext* ctx, const StringVal& src, StringVal* dst) {
if (src.is_null) {
return;
}
if (dst->is_null || StringValue::from_string_val(src) < StringValue::from_string_val(*dst)) {
if (!dst->is_null) {
ctx->free(dst->ptr);
}
uint8_t* copy = ctx->allocate(src.len);
memcpy(copy, src.ptr, src.len);
*dst = StringVal(copy, src.len);
}
}
template <>
void AggregateFunctions::max(FunctionContext* ctx, const StringVal& src, StringVal* dst) {
if (src.is_null) {
return;
}
if (dst->is_null || StringValue::from_string_val(src) > StringValue::from_string_val(*dst)) {
if (!dst->is_null) {
ctx->free(dst->ptr);
}
uint8_t* copy = ctx->allocate(src.len);
memcpy(copy, src.ptr, src.len);
*dst = StringVal(copy, src.len);
}
}
template <>
void AggregateFunctions::min(FunctionContext*, const DateTimeVal& src, DateTimeVal* dst) {
if (src.is_null) {
return;
}
if (dst->is_null) {
*dst = src;
return;
}
DateTimeValue src_tv = DateTimeValue::from_datetime_val(src);
DateTimeValue dst_tv = DateTimeValue::from_datetime_val(*dst);
if (src_tv < dst_tv) {
*dst = src;
}
}
template <>
void AggregateFunctions::max(FunctionContext*, const DateTimeVal& src, DateTimeVal* dst) {
if (src.is_null) {
return;
}
if (dst->is_null) {
*dst = src;
return;
}
DateTimeValue src_tv = DateTimeValue::from_datetime_val(src);
DateTimeValue dst_tv = DateTimeValue::from_datetime_val(*dst);
if (src_tv > dst_tv) {
*dst = src;
}
}
void AggregateFunctions::string_concat(FunctionContext* ctx, const StringVal& src,
const StringVal& separator, StringVal* result) {
if (src.is_null || separator.is_null) {
return;
}
if (result->is_null) {
uint8_t* copy = ctx->allocate(src.len);
memcpy(copy, src.ptr, src.len);
*result = StringVal(copy, src.len);
return;
}
const StringVal* sep_ptr = separator.is_null ? &DEFAULT_STRING_CONCAT_DELIM : &separator;
int new_size = result->len + sep_ptr->len + src.len;
result->ptr = ctx->reallocate(result->ptr, new_size);
memcpy(result->ptr + result->len, sep_ptr->ptr, sep_ptr->len);
result->len += sep_ptr->len;
memcpy(result->ptr + result->len, src.ptr, src.len);
result->len += src.len;
}
// StringConcat intermediate state starts with the length of the first
// separator, followed by the accumulated string. The accumulated
// string starts with the separator of the first value that arrived in
// StringConcatUpdate().
using StringConcatHeader = int64_t;
// Delimiter to use if the separator is nullptr.
void AggregateFunctions::string_concat_update(FunctionContext* ctx, const StringVal& src,
StringVal* result) {
string_concat_update(ctx, src, DEFAULT_STRING_CONCAT_DELIM, result);
}
void AggregateFunctions::string_concat_update(FunctionContext* ctx, const StringVal& src,
const StringVal& separator, StringVal* result) {
if (src.is_null || separator.is_null) {
return;
}
const StringVal* sep = separator.is_null ? &DEFAULT_STRING_CONCAT_DELIM : &separator;
if (result->is_null || !result->ptr) {
// Header of the intermediate state holds the length of the first separator.
const auto header_len = sizeof(StringConcatHeader);
DCHECK(header_len == sizeof(sep->len));
*result = StringVal(ctx->allocate(header_len), header_len);
*reinterpret_cast<StringConcatHeader*>(result->ptr) = sep->len;
}
result->append(ctx, sep->ptr, sep->len, src.ptr, src.len);
}
void AggregateFunctions::string_concat_merge(FunctionContext* ctx, const StringVal& src,
StringVal* result) {
if (src.is_null) {
return;
}
const auto header_len = sizeof(StringConcatHeader);
if (result->is_null || !result->ptr) {
// Copy the header from the first intermediate value.
*result = StringVal(ctx->allocate(header_len), header_len);
if (result->is_null) {
return;
}
*reinterpret_cast<StringConcatHeader*>(result->ptr) =
*reinterpret_cast<StringConcatHeader*>(src.ptr);
}
// Append the string portion of the intermediate src to result (omit src's header).
result->append(ctx, src.ptr + header_len, src.len - header_len);
}
StringVal AggregateFunctions::string_concat_finalize(FunctionContext* ctx, const StringVal& src) {
if (src.is_null) {
return src;
}
const auto header_len = sizeof(StringConcatHeader);
DCHECK(src.len >= header_len);
int sep_len = *reinterpret_cast<StringConcatHeader*>(src.ptr);
DCHECK(src.len >= header_len + sep_len);
// Remove the header and the first separator.
StringVal result = StringVal::copy_from(ctx, src.ptr + header_len + sep_len,
src.len - header_len - sep_len);
ctx->free(src.ptr);
return result;
}
// Compute distinctpc and distinctpcsa using Flajolet and Martin's algorithm
// (Probabilistic Counting Algorithms for Data Base Applications)
// We have implemented two variants here: one with stochastic averaging (with PCSA
// postfix) and one without.
// There are 4 phases to compute the aggregate:
// 1. allocate a bitmap, stored in the aggregation tuple's output string slot
// 2. update the bitmap per row (UpdateDistinctEstimateSlot)
// 3. for distributed plan, merge the bitmaps from all the nodes
// (UpdateMergeEstimateSlot)
// 4. compute the estimate using the bitmaps when all the rows are processed
// (FinalizeEstimateSlot)
const static int NUM_PC_BITMAPS = 64; // number of bitmaps
const static int PC_BITMAP_LENGTH = 32; // the length of each bit map
const static float PC_THETA = 0.77351f; // the magic number to compute the final result
void AggregateFunctions::pc_init(FunctionContext* c, StringVal* dst) {
// Initialize the distinct estimate bit map - Probabilistic Counting Algorithms for Data
// Base Applications (Flajolet and Martin)
//
// The bitmap is a 64bit(1st index) x 32bit(2nd index) matrix.
// So, the string length of 256 byte is enough.
// The layout is:
// row 1: 8bit 8bit 8bit 8bit
// row 2: 8bit 8bit 8bit 8bit
// ... ..
// ... ..
// row 64: 8bit 8bit 8bit 8bit
//
// Using 32bit length, we can count up to 10^8. This will not be enough for Fact table
// primary key, but once we approach the limit, we could interpret the result as
// "every row is distinct".
//
// We use "string" type for DISTINCT_PC function so that we can use the string
// slot to hold the bitmaps.
dst->is_null = false;
int str_len = NUM_PC_BITMAPS * PC_BITMAP_LENGTH / 8;
dst->ptr = c->allocate(str_len);
dst->len = str_len;
memset(dst->ptr, 0, str_len);
}
static inline void set_distinct_estimate_bit(uint8_t* bitmap, uint32_t row_index,
uint32_t bit_index) {
// We need to convert Bitmap[alpha,index] into the index of the string.
// alpha tells which of the 32bit we've to jump to.
// index then lead us to the byte and bit.
uint32_t* int_bitmap = reinterpret_cast<uint32_t*>(bitmap);
int_bitmap[row_index] |= (1 << bit_index);
}
static inline bool get_distinct_estimate_bit(uint8_t* bitmap, uint32_t row_index,
uint32_t bit_index) {
uint32_t* int_bitmap = reinterpret_cast<uint32_t*>(bitmap);
return ((int_bitmap[row_index] & (1 << bit_index)) > 0);
}
template <typename T>
void AggregateFunctions::pc_update(FunctionContext* c, const T& input, StringVal* dst) {
if (input.is_null) {
return;
}
// Core of the algorithm. This is a direct translation of the code in the paper.
// Please see the paper for details. For simple averaging, we need to compute hash
// values NUM_PC_BITMAPS times using NUM_PC_BITMAPS different hash functions (by using a
// different seed).
for (int i = 0; i < NUM_PC_BITMAPS; ++i) {
uint32_t hash_value = AnyValUtil::hash(input, i);
int bit_index = __builtin_ctz(hash_value);
if (UNLIKELY(hash_value == 0)) {
bit_index = PC_BITMAP_LENGTH - 1;
}
// Set bitmap[i, bit_index] to 1
set_distinct_estimate_bit(dst->ptr, i, bit_index);
}
}
template <typename T>
void AggregateFunctions::pcsa_update(FunctionContext* c, const T& input, StringVal* dst) {
if (input.is_null) {
return;
}
// Core of the algorithm. This is a direct translation of the code in the paper.
// Please see the paper for details. Using stochastic averaging, we only need to
// the hash value once for each row.
uint32_t hash_value = AnyValUtil::hash(input, 0);
uint32_t row_index = hash_value % NUM_PC_BITMAPS;
// We want the zero-based position of the least significant 1-bit in binary
// representation of hash_value. __builtin_ctz does exactly this because it returns
// the number of trailing 0-bits in x (or undefined if x is zero).
int bit_index = __builtin_ctz(hash_value / NUM_PC_BITMAPS);
if (UNLIKELY(hash_value == 0)) {
bit_index = PC_BITMAP_LENGTH - 1;
}
// Set bitmap[row_index, bit_index] to 1
set_distinct_estimate_bit(dst->ptr, row_index, bit_index);
}
std::string distinct_estimate_bitmap_to_string(uint8_t* v) {
std::stringstream debugstr;
for (int i = 0; i < NUM_PC_BITMAPS; ++i) {
for (int j = 0; j < PC_BITMAP_LENGTH; ++j) {
// print bitmap[i][j]
debugstr << get_distinct_estimate_bit(v, i, j);
}
debugstr << "\n";
}
debugstr << "\n";
return debugstr.str();
}
void AggregateFunctions::pc_merge(FunctionContext* c, const StringVal& src, StringVal* dst) {
DCHECK(!src.is_null);
DCHECK(!dst->is_null);
DCHECK_EQ(src.len, NUM_PC_BITMAPS * PC_BITMAP_LENGTH / 8);
// Merge the bits
// I think _mm_or_ps can do it, but perf doesn't really matter here. We call this only
// once group per node.
for (int i = 0; i < NUM_PC_BITMAPS * PC_BITMAP_LENGTH / 8; ++i) {
*(dst->ptr + i) |= *(src.ptr + i);
}
VLOG_ROW << "UpdateMergeEstimateSlot Src Bit map:\n"
<< distinct_estimate_bitmap_to_string(src.ptr);
VLOG_ROW << "UpdateMergeEstimateSlot Dst Bit map:\n"
<< distinct_estimate_bitmap_to_string(dst->ptr);
}
double distinct_estimate_finalize(const StringVal& src) {
DCHECK(!src.is_null);
DCHECK_EQ(src.len, NUM_PC_BITMAPS * PC_BITMAP_LENGTH / 8);
VLOG_ROW << "FinalizeEstimateSlot Bit map:\n" << distinct_estimate_bitmap_to_string(src.ptr);
// We haven't processed any rows if none of the bits are set. Therefore, we have zero
// distinct rows. We're overwriting the result in the same string buffer we've
// allocated.
bool is_empty = true;
for (int i = 0; i < NUM_PC_BITMAPS * PC_BITMAP_LENGTH / 8; ++i) {
if (src.ptr[i] != 0) {
is_empty = false;
break;
}
}
if (is_empty) {
return 0;
}
// Convert the bitmap to a number, please see the paper for details
// In short, we count the average number of leading 1s (per row) in the bit map.
// The number is proportional to the log2(1/NUM_PC_BITMAPS of the actual number of
// distinct).