forked from ozturkosu/cms_topn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cms_topn.c
1235 lines (1061 loc) · 37.1 KB
/
cms_topn.c
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
/*-------------------------------------------------------------------------
*
* cms_topn.c
*
* This file contains the function definitions to perform top-n, point and
* union queries by using the count-min sketch structure.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "fmgr.h"
#include <math.h>
#include <limits.h>
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "MurmurHash3.h"
#include "utils/array.h"
#include "utils/bytea.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/typcache.h"
#define DEFAULT_ERROR_BOUND 0.001
#define DEFAULT_CONFIDENCE_INTERVAL 0.99
#define MURMUR_SEED 304837963
#define MAX_FREQUENCY ULONG_MAX
#define DEFAULT_TOPN_ITEM_SIZE 16
#define TOPN_ARRAY_OVERHEAD ARR_OVERHEAD_NONULLS(1)
/*
* Frequency can be set to different data types to specify upper limit of counter
* and required space for each counter. If we change type of Frequency, we also
* need to update MAX_FREQUENCY above. Such as if Frequency is defined as uint32,
* then MAX_FREQUENCY has to be UINT_MAX.
*/
typedef uint64 Frequency;
/*
* CmsTopn is the main struct for the count-min sketch top-n implementation and
* it has two variable length fields. First one is an array for keeping the sketch
* which is pointed by "sketch" of the struct and second one is an ArrayType for
* keeping the most frequent n items. It is not possible to lay out two variable
* width fields consecutively in memory. So we are using pointer arithmetic to
* reach and handle ArrayType for the most frequent n items.
*/
typedef struct CmsTopn
{
char length[4];
uint32 sketchDepth;
uint32 sketchWidth;
uint32 topnItemCount;
uint32 topnItemSize;
Frequency minFrequencyOfTopnItems;
Frequency sketch[1];
} CmsTopn;
/*
* FrequentTopnItem is the struct to keep frequent items and their frequencies
* together.
* It is useful to sort the top-n items before returning in topn() function.
*/
typedef struct FrequentTopnItem
{
Datum topnItem;
Frequency topnItemFrequency;
} FrequentTopnItem;
/* local functions forward declarations */
static CmsTopn * CreateCmsTopn(int32 topnItemCount, float8 errorBound,
float8 confidenceInterval);
static CmsTopn * UpdateCmsTopn(CmsTopn *currentCmsTopn, Datum newItem,
TypeCacheEntry *newItemTypeCacheEntry);
static ArrayType * TopnArray(CmsTopn *cmsTopn);
static Frequency UpdateSketchInPlace(CmsTopn *cmsTopn, Datum newItem,
TypeCacheEntry *newItemTypeCacheEntry);
static void ConvertDatumToBytes(Datum datum, TypeCacheEntry *datumTypeCacheEntry,
StringInfo datumString);
static Frequency CmsTopnEstimateHashedItemFrequency(CmsTopn *cmsTopn,
uint64 *hashValueArray);
static ArrayType * UpdateTopnArray(CmsTopn *cmsTopn, Datum candidateItem,
TypeCacheEntry *itemTypeCacheEntry,
Frequency itemFrequency, bool *topnArrayUpdated);
static Frequency CmsTopnEstimateItemFrequency(CmsTopn *cmsTopn, Datum item,
TypeCacheEntry *itemTypeCacheEntry);
static CmsTopn * FormCmsTopn(CmsTopn *cmsTopn, ArrayType *newTopnArray);
static CmsTopn * CmsTopnUnion(CmsTopn *firstCmsTopn, CmsTopn *secondCmsTopn,
TypeCacheEntry *itemTypeCacheEntry);
void SortTopnItems(FrequentTopnItem *topnItemArray, int topnItemCount);
/* declarations for dynamic loading */
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(cms_topn_in);
PG_FUNCTION_INFO_V1(cms_topn_out);
PG_FUNCTION_INFO_V1(cms_topn_recv);
PG_FUNCTION_INFO_V1(cms_topn_send);
PG_FUNCTION_INFO_V1(cms_topn);
PG_FUNCTION_INFO_V1(cms_topn_add);
PG_FUNCTION_INFO_V1(cms_topn_add_agg);
PG_FUNCTION_INFO_V1(cms_topn_add_agg_with_parameters);
PG_FUNCTION_INFO_V1(cms_topn_union);
PG_FUNCTION_INFO_V1(cms_topn_union_agg);
PG_FUNCTION_INFO_V1(cms_topn_frequency);
PG_FUNCTION_INFO_V1(cms_topn_info);
PG_FUNCTION_INFO_V1(topn);
/*
* cms_topn_in creates cms_topn from printable representation.
*/
Datum
cms_topn_in(PG_FUNCTION_ARGS)
{
Datum datum = DirectFunctionCall1(byteain, PG_GETARG_DATUM(0));
return datum;
}
/*
* cms_topn_out converts cms_topn to printable representation.
*/
Datum
cms_topn_out(PG_FUNCTION_ARGS)
{
Datum datum = DirectFunctionCall1(byteaout, PG_GETARG_DATUM(0));
PG_RETURN_CSTRING(datum);
}
/*
* cms_topn_recv creates cms_topn from external binary format.
*/
Datum
cms_topn_recv(PG_FUNCTION_ARGS)
{
Datum datum = DirectFunctionCall1(bytearecv, PG_GETARG_DATUM(0));
return datum;
}
/*
* cms_topn_send converts cms_topn to external binary format.
*/
Datum
cms_topn_send(PG_FUNCTION_ARGS)
{
Datum datum = DirectFunctionCall1(byteasend, PG_GETARG_DATUM(0));
return datum;
}
/*
* cms_topn is a user-facing UDF which creates new cms_topn with given parameters.
* The first parameter is for the number of top items which will be kept, the others
* are for error bound(e) and confidence interval(p) respectively. Given e and p,
* estimated frequency can be at most (e*||a||) more than real frequency with the
* probability p while ||a|| is the sum of frequencies of all items according to
* this paper: http://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf.
*/
Datum
cms_topn(PG_FUNCTION_ARGS)
{
int32 topnItemCount = PG_GETARG_UINT32(0);
float8 errorBound = PG_GETARG_FLOAT8(1);
float8 confidenceInterval = PG_GETARG_FLOAT8(2);
CmsTopn *cmsTopn = CreateCmsTopn(topnItemCount, errorBound, confidenceInterval);
PG_RETURN_POINTER(cmsTopn);
}
/*
* CmsTopnCreate creates CmsTopn structure with given parameters. The first parameter
* is for the number of frequent items, other two specifies error bound and confidence
* interval for this error bound. Size of the sketch is determined with the given
* error bound and confidence interval according to formula in this paper:
* http://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf.
*
* Note that here we also allocate initial memory for the ArrayType which keeps
* the frequent items. This allocation includes ArrayType overhead for one dimensional
* array and additional memory according to number of top-n items and default size
* for an individual item.
*/
static CmsTopn *
CreateCmsTopn(int32 topnItemCount, float8 errorBound, float8 confidenceInterval)
{
CmsTopn *cmsTopn = NULL;
uint32 sketchWidth = 0;
uint32 sketchDepth = 0;
Size staticStructSize = 0;
Size sketchSize = 0;
Size topnItemsReservedSize = 0;
Size topnArrayReservedSize = 0;
Size totalCmsTopnSize = 0;
if (topnItemCount <= 0)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid parameters for cms_topn"),
errhint("Number of top items has to be positive")));
}
else if (errorBound <= 0 || errorBound >= 1)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid parameters for cms_topn"),
errhint("Error bound has to be between 0 and 1")));
}
else if (confidenceInterval <= 0 || confidenceInterval >= 1)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid parameters for cms_topn"),
errhint("Confidence interval has to be between 0 and 1")));
}
sketchWidth = (uint32) ceil(exp(1) / errorBound);
sketchDepth = (uint32) ceil(log(1 / (1 - confidenceInterval)));
sketchSize = sizeof(Frequency) * sketchDepth * sketchWidth;
staticStructSize = sizeof(CmsTopn);
topnItemsReservedSize = topnItemCount * DEFAULT_TOPN_ITEM_SIZE;
topnArrayReservedSize = TOPN_ARRAY_OVERHEAD + topnItemsReservedSize;
totalCmsTopnSize = staticStructSize + sketchSize + topnArrayReservedSize;
cmsTopn = palloc0(totalCmsTopnSize);
cmsTopn->sketchDepth = sketchDepth;
cmsTopn->sketchWidth = sketchWidth;
cmsTopn->topnItemCount = topnItemCount;
cmsTopn->topnItemSize = DEFAULT_TOPN_ITEM_SIZE;
cmsTopn->minFrequencyOfTopnItems = 0;
SET_VARSIZE(cmsTopn, totalCmsTopnSize);
return cmsTopn;
}
/*
* cms_topn_add is a user-facing UDF which inserts new item to the given CmsTopn.
* The first parameter is for the CmsTopn to add the new item and second is for
* the new item. This function returns updated CmsTopn.
*/
Datum
cms_topn_add(PG_FUNCTION_ARGS)
{
CmsTopn *currentCmsTopn = NULL;
CmsTopn *updatedCmsTopn = NULL;
Datum newItem = 0;
TypeCacheEntry *newItemTypeCacheEntry = NULL;
Oid newItemType = InvalidOid;
/* check whether cms_topn is null */
if (PG_ARGISNULL(0))
{
PG_RETURN_NULL();
}
else
{
currentCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(0);
}
/* if new item is null, then return current CmsTopn */
if (PG_ARGISNULL(1))
{
PG_RETURN_POINTER(currentCmsTopn);
}
/* get item type and check if it is valid */
newItemType = get_fn_expr_argtype(fcinfo->flinfo, 1);
if (newItemType == InvalidOid)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not determine input data type")));
}
newItem = PG_GETARG_DATUM(1);
newItemTypeCacheEntry = lookup_type_cache(newItemType, 0);
updatedCmsTopn = UpdateCmsTopn(currentCmsTopn, newItem, newItemTypeCacheEntry);
PG_RETURN_POINTER(updatedCmsTopn);
}
/*
* UpdateCmsTopn is a helper function to add new item to CmsTopn structure. It
* adds the item to the sketch, calculates its frequency, and updates the top-n
* array. Finally it forms new CmsTopn from updated sketch and updated top-n array.
*/
static CmsTopn *
UpdateCmsTopn(CmsTopn *currentCmsTopn, Datum newItem,
TypeCacheEntry *newItemTypeCacheEntry)
{
CmsTopn *updatedCmsTopn = NULL;
ArrayType *currentTopnArray = NULL;
ArrayType *updatedTopnArray = NULL;
Datum detoastedItem = 0;
Oid newItemType = newItemTypeCacheEntry->type_id;
Oid currentItemType = InvalidOid;
Frequency newItemFrequency = 0;
bool topnArrayUpdated = false;
Size currentTopnArrayLength = 0;
currentTopnArray = TopnArray(currentCmsTopn);
currentTopnArrayLength = ARR_DIMS(currentTopnArray)[0];
currentItemType = ARR_ELEMTYPE(currentTopnArray);
if (currentTopnArrayLength != 0 && currentItemType != newItemType)
{
ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("not proper type for this cms_topn")));
}
/* if datum is toasted, detoast it */
if (newItemTypeCacheEntry->typlen == -1)
{
detoastedItem = PointerGetDatum(PG_DETOAST_DATUM(newItem));
}
else
{
detoastedItem = newItem;
}
newItemFrequency = UpdateSketchInPlace(currentCmsTopn, detoastedItem,
newItemTypeCacheEntry);
updatedTopnArray = UpdateTopnArray(currentCmsTopn, detoastedItem,
newItemTypeCacheEntry, newItemFrequency,
&topnArrayUpdated);
/* we only form a new CmsTopn only if top-n array is updated */
if (topnArrayUpdated)
{
updatedCmsTopn = FormCmsTopn(currentCmsTopn, updatedTopnArray);
}
else
{
updatedCmsTopn = currentCmsTopn;
}
return updatedCmsTopn;
}
/*
* TopnArray returns pointer for the ArrayType which is kept in CmsTopn structure
* by calculating its place with pointer arithmetic.
*/
static ArrayType *
TopnArray(CmsTopn *cmsTopn)
{
Size staticSize = sizeof(CmsTopn);
Size sketchSize = sizeof(Frequency) * cmsTopn->sketchDepth * cmsTopn->sketchWidth;
Size sizeWithoutTopnArray = staticSize + sketchSize;
ArrayType *topnArray = (ArrayType *) (((char *) cmsTopn) + sizeWithoutTopnArray);
return topnArray;
}
/*
* UpdateSketchInPlace updates sketch inside CmsTopn in-place with given item
* and returns new estimated frequency for the given item.
*/
static Frequency
UpdateSketchInPlace(CmsTopn *cmsTopn, Datum newItem,
TypeCacheEntry *newItemTypeCacheEntry)
{
uint32 hashIndex = 0;
uint64 hashValueArray[2] = {0, 0};
StringInfo newItemString = makeStringInfo();
Frequency newFrequency = 0;
Frequency minFrequency = MAX_FREQUENCY;
/* get hashed values for the given item */
ConvertDatumToBytes(newItem, newItemTypeCacheEntry, newItemString);
MurmurHash3_x64_128(newItemString->data, newItemString->len, MURMUR_SEED,
&hashValueArray);
/*
* Estimate frequency of the given item from hashed values and calculate new
* frequency for this item.
*/
minFrequency = CmsTopnEstimateHashedItemFrequency(cmsTopn, hashValueArray);
newFrequency = minFrequency + 1;
/*
* We can create an independent hash function for each index by using two hash
* values from the Murmur Hash function. This is a standard technique from the
* hashing literature for the additional hash functions of the form
* g(x) = h1(x) + i * h2(x) and does not hurt the independence between hash
* function. For more information you can check this paper:
* http://www.eecs.harvard.edu/~kirsch/pubs/bbbf/esa06.pdf
*/
for (hashIndex = 0; hashIndex < cmsTopn->sketchDepth; hashIndex++)
{
uint64 hashValue = hashValueArray[0] + (hashIndex * hashValueArray[1]);
uint32 widthIndex = hashValue % cmsTopn->sketchWidth;
uint32 depthOffset = hashIndex * cmsTopn->sketchWidth;
uint32 counterIndex = depthOffset + widthIndex;
/*
* Selective update to decrease effect of collisions. We only update
* counters less than new frequency because other counters are bigger
* due to collisions.
*/
Frequency counterFrequency = cmsTopn->sketch[counterIndex];
if (newFrequency > counterFrequency)
{
cmsTopn->sketch[counterIndex] = newFrequency;
}
}
return newFrequency;
}
/*
* ConvertDatumToBytes converts datum to byte array and saves it in the given
* datum string.
*/
static void
ConvertDatumToBytes(Datum datum, TypeCacheEntry *datumTypeCacheEntry,
StringInfo datumString)
{
int16 datumTypeLength = datumTypeCacheEntry->typlen;
bool datumTypeByValue = datumTypeCacheEntry->typbyval;
Size datumSize = 0;
if (datumTypeLength == -1)
{
datumSize = VARSIZE_ANY_EXHDR(DatumGetPointer(datum));
}
else
{
datumSize = datumGetSize(datum, datumTypeByValue, datumTypeLength);
}
if (datumTypeByValue)
{
appendBinaryStringInfo(datumString, (char *) &datum, datumSize);
}
else
{
appendBinaryStringInfo(datumString, VARDATA_ANY(datum), datumSize);
}
}
/*
* CmsTopnEstimateHashedItemFrequency is a helper function to get frequency
* estimate of an item from it's hashed values.
*/
static Frequency
CmsTopnEstimateHashedItemFrequency(CmsTopn *cmsTopn, uint64 *hashValueArray)
{
uint32 hashIndex = 0;
Frequency minFrequency = MAX_FREQUENCY;
for (hashIndex = 0; hashIndex < cmsTopn->sketchDepth; hashIndex++)
{
uint64 hashValue = hashValueArray[0] + (hashIndex * hashValueArray[1]);
uint32 widthIndex = hashValue % cmsTopn->sketchWidth;
uint32 depthOffset = hashIndex * cmsTopn->sketchWidth;
uint32 counterIndex = depthOffset + widthIndex;
Frequency counterFrequency = cmsTopn->sketch[counterIndex];
if (counterFrequency < minFrequency)
{
minFrequency = counterFrequency;
}
}
return minFrequency;
}
/*
* UpdateTopnArray is a helper function for the unions and inserts. It takes
* given item and its frequency. If the item is not in the top-n array, it tries
* to insert new item. If there is place in the top-n array, it insert directly.
* Otherwise, it compares its frequency with the minimum of current items in the
* array and updates top-n array if new frequency is bigger.
*/
static ArrayType *
UpdateTopnArray(CmsTopn *cmsTopn, Datum candidateItem, TypeCacheEntry *itemTypeCacheEntry,
Frequency itemFrequency, bool *topnArrayUpdated)
{
ArrayType *currentTopnArray = TopnArray(cmsTopn);
ArrayType *updatedTopnArray = NULL;
int16 itemTypeLength = itemTypeCacheEntry->typlen;
bool itemTypeByValue = itemTypeCacheEntry->typbyval;
char itemTypeAlignment = itemTypeCacheEntry->typalign;
Frequency minOfNewTopnItems = MAX_FREQUENCY;
bool candidateAlreadyInArray = false;
int candidateIndex = -1;
int currentArrayLength = ARR_DIMS(currentTopnArray)[0];
if (currentArrayLength == 0)
{
Oid itemType = itemTypeCacheEntry->type_id;
if (itemTypeCacheEntry->typtype == TYPTYPE_COMPOSITE)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("composite types are not supported")));
}
currentTopnArray = construct_empty_array(itemType);
}
/*
* If item frequency is smaller than min frequency of old top-n items,
* it cannot be in the top-n items and we insert it only if there is place.
* Otherwise, we need to check new minimum and whether it is in the top-n.
*/
if (itemFrequency <= cmsTopn->minFrequencyOfTopnItems)
{
if (currentArrayLength < cmsTopn->topnItemCount)
{
candidateIndex = currentArrayLength + 1;
minOfNewTopnItems = itemFrequency;
}
}
else
{
ArrayIterator iterator = array_create_iterator(currentTopnArray, 0);
Datum topnItem = 0;
int topnItemIndex = 1;
int minItemIndex = 1;
bool hasMoreItem = false;
bool isNull = false;
/*
* Find the top-n item with minimum frequency to replace it with candidate
* item.
*/
hasMoreItem = array_iterate(iterator, &topnItem, &isNull);
while (hasMoreItem)
{
Frequency topnItemFrequency = 0;
/* check if we already have this item in top-n array */
candidateAlreadyInArray = datumIsEqual(topnItem, candidateItem,
itemTypeByValue, itemTypeLength);
if (candidateAlreadyInArray)
{
minItemIndex = -1;
break;
}
/* keep track of minumum frequency item in the top-n array */
topnItemFrequency = CmsTopnEstimateItemFrequency(cmsTopn, topnItem,
itemTypeCacheEntry);
if (topnItemFrequency < minOfNewTopnItems)
{
minOfNewTopnItems = topnItemFrequency;
minItemIndex = topnItemIndex;
}
hasMoreItem = array_iterate(iterator, &topnItem, &isNull);
topnItemIndex++;
}
/* if new item is not in the top-n and there is place, insert the item */
if (!candidateAlreadyInArray && currentArrayLength < cmsTopn->topnItemCount)
{
minItemIndex = currentArrayLength + 1;
minOfNewTopnItems = Min(minOfNewTopnItems, itemFrequency);
}
candidateIndex = minItemIndex;
}
/*
* If it is not in the top-n structure and its frequency bigger than minimum
* put into top-n instead of the item which has minimum frequency. If it is
* in top-n or not frequent items, do not change anything.
*/
if (!candidateAlreadyInArray && minOfNewTopnItems <= itemFrequency)
{
updatedTopnArray = array_set(currentTopnArray, 1, &candidateIndex,
candidateItem, false, -1, itemTypeLength,
itemTypeByValue, itemTypeAlignment);
cmsTopn->minFrequencyOfTopnItems = minOfNewTopnItems;
*topnArrayUpdated = true;
}
else
{
updatedTopnArray = currentTopnArray;
*topnArrayUpdated = false;
}
return updatedTopnArray;
}
/*
* CmsTopnEstimateItemFrequency calculates estimated frequency for the given
* item and returns it.
*/
static Frequency
CmsTopnEstimateItemFrequency(CmsTopn *cmsTopn, Datum item,
TypeCacheEntry *itemTypeCacheEntry)
{
uint64 hashValueArray[2] = {0, 0};
StringInfo itemString = makeStringInfo();
Frequency frequency = 0;
/* if datum is toasted, detoast it */
if (itemTypeCacheEntry->typlen == -1)
{
Datum detoastedItem = PointerGetDatum(PG_DETOAST_DATUM(item));
ConvertDatumToBytes(detoastedItem, itemTypeCacheEntry, itemString);
}
else
{
ConvertDatumToBytes(item, itemTypeCacheEntry, itemString);
}
/*
* Calculate hash values for the given item and then get frequency estimate
* with these hashed values.
*/
MurmurHash3_x64_128(itemString->data, itemString->len, MURMUR_SEED, &hashValueArray);
frequency = CmsTopnEstimateHashedItemFrequency(cmsTopn, hashValueArray);
return frequency;
}
/*
* FormCmsTopn copies current count-min sketch and new top-n array into a new
* CmsTopn. This function is called only when there is an update in top-n and it
* only copies ArrayType part if allocated memory is enough for new ArrayType.
* Otherwise, it allocates new memory and copies all CmsTopn.
*/
static CmsTopn *
FormCmsTopn(CmsTopn *cmsTopn, ArrayType *newTopnArray)
{
Size staticSize = sizeof(CmsTopn);
Size sketchSize = cmsTopn->sketchDepth * cmsTopn->sketchWidth * sizeof(Frequency);
Size sizeWithoutTopnArray = staticSize + sketchSize;
Size topnArrayReservedSize = VARSIZE(cmsTopn) - sizeWithoutTopnArray;
Size newTopnArraySize = ARR_SIZE(newTopnArray);
Size newCmsTopnSize = 0;
char *newCmsTopn = NULL;
char *topnArrayOffset = NULL;
/*
* Check whether we have enough memory for new top-n array. If not, we need
* to allocate more memory and copy CmsTopn and new top-n array.
*/
if (newTopnArraySize > topnArrayReservedSize)
{
Size newItemsReservedSize = 0;
Size newTopnArrayReservedSize = 0;
uint32 topnItemCount = cmsTopn->topnItemCount;
/*
* Calculate average top-n item size in the new top-n array and use
* two times of it for each top-n item while allocating new memory.
*/
Size averageTopnItemSize = (Size) (newTopnArraySize / topnItemCount);
Size topnItemSize = averageTopnItemSize * 2;
cmsTopn->topnItemSize = topnItemSize;
newItemsReservedSize = topnItemCount * topnItemSize;
newTopnArrayReservedSize = TOPN_ARRAY_OVERHEAD + newItemsReservedSize;
newCmsTopnSize = sizeWithoutTopnArray + newTopnArrayReservedSize;
newCmsTopn = palloc0(newCmsTopnSize);
/* first copy until to top-n array */
memcpy(newCmsTopn, (char *)cmsTopn, sizeWithoutTopnArray);
/* set size of new CmsTopn */
SET_VARSIZE(newCmsTopn, newCmsTopnSize);
}
else
{
newCmsTopn = (char *)cmsTopn;
}
/* finally copy new top-n array */
topnArrayOffset = ((char *) newCmsTopn) + sizeWithoutTopnArray;
memcpy(topnArrayOffset, newTopnArray, ARR_SIZE(newTopnArray));
return (CmsTopn *) newCmsTopn;
}
/*
* cms_topn_add_agg is aggregate function to add items in a cms_topn. It uses
* default values for error bound, confidence interval and given top-n item
* count to create initial cms_topn. The first parameter for the CmsTopn which
* is updated during the aggregation, the second one is for the items to add and
* third one specifies number of items to be kept in top-n array.
*/
Datum
cms_topn_add_agg(PG_FUNCTION_ARGS)
{
CmsTopn *currentCmsTopn = NULL;
CmsTopn *updatedCmsTopn = NULL;
uint32 topnItemCount = PG_GETARG_UINT32(2);
float8 errorBound = DEFAULT_ERROR_BOUND;
float8 confidenceInterval = DEFAULT_CONFIDENCE_INTERVAL;
Datum newItem = 0;
TypeCacheEntry *newItemTypeCacheEntry = NULL;
Oid newItemType = InvalidOid;
if (!AggCheckCallContext(fcinfo, NULL))
{
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION),
errmsg("cms_topn_add_agg called in non-aggregate context")));
}
/* check whether cms_topn is null and create if it is */
if (PG_ARGISNULL(0))
{
currentCmsTopn = CreateCmsTopn(topnItemCount, errorBound, confidenceInterval);
}
else
{
currentCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(0);
}
/* if new item is null, return current CmsTopn */
if (PG_ARGISNULL(1))
{
PG_RETURN_POINTER(currentCmsTopn);
}
/*
* Keep type cache entry between subsequent calls in order to get rid of
* cache lookup overhead.
*/
newItem = PG_GETARG_DATUM(1);
if (fcinfo->flinfo->fn_extra == NULL)
{
newItemType = get_fn_expr_argtype(fcinfo->flinfo, 1);
newItemTypeCacheEntry = lookup_type_cache(newItemType, 0);
fcinfo->flinfo->fn_extra = newItemTypeCacheEntry;
}
else
{
newItemTypeCacheEntry = fcinfo->flinfo->fn_extra;
}
updatedCmsTopn = UpdateCmsTopn(currentCmsTopn, newItem, newItemTypeCacheEntry);
PG_RETURN_POINTER(updatedCmsTopn);
}
/*
* cms_topn_add_agg_with_parameters is a aggregate function to add items. It
* allows to specify parameters of created CmsTopn structure. In addition to
* cms_topn_add_agg function, it takes error bound and confidence interval
* parameters as the forth and fifth parameters.
*/
Datum
cms_topn_add_agg_with_parameters(PG_FUNCTION_ARGS)
{
CmsTopn *currentCmsTopn = NULL;
CmsTopn *updatedCmsTopn = NULL;
uint32 topnItemCount = PG_GETARG_UINT32(2);
float8 errorBound = PG_GETARG_FLOAT8(3);
float8 confidenceInterval = PG_GETARG_FLOAT8(4);
Datum newItem = 0;
TypeCacheEntry *newItemTypeCacheEntry = NULL;
Oid newItemType = InvalidOid;
if (!AggCheckCallContext(fcinfo, NULL))
{
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION),
errmsg("cms_topn_add_agg_with_parameters called in "
"non-aggregate context")));
}
/* check whether cms_topn is null and create if it is */
if (PG_ARGISNULL(0))
{
currentCmsTopn = CreateCmsTopn(topnItemCount, errorBound, confidenceInterval);
}
else
{
currentCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(0);
}
/* if new item is null, return current CmsTopn */
if (PG_ARGISNULL(1))
{
PG_RETURN_POINTER(currentCmsTopn);
}
/*
* Keep type cache entry between subsequent calls in order to get rid of
* cache lookup overhead.
*/
newItem = PG_GETARG_DATUM(1);
if (fcinfo->flinfo->fn_extra == NULL)
{
newItemType = get_fn_expr_argtype(fcinfo->flinfo, 1);
newItemTypeCacheEntry = lookup_type_cache(newItemType, 0);
fcinfo->flinfo->fn_extra = newItemTypeCacheEntry;
}
else
{
newItemTypeCacheEntry = fcinfo->flinfo->fn_extra;
}
updatedCmsTopn = UpdateCmsTopn(currentCmsTopn, newItem, newItemTypeCacheEntry);
PG_RETURN_POINTER(updatedCmsTopn);
}
/*
* cms_topn_union is a user-facing UDF which takes two cms_topn and returns
* their union.
*/
Datum
cms_topn_union(PG_FUNCTION_ARGS)
{
CmsTopn *firstCmsTopn = NULL;
CmsTopn *secondCmsTopn = NULL;
CmsTopn *newCmsTopn = NULL;
ArrayType *firstTopnArray = NULL;
Size firstTopnArrayLength = 0;
TypeCacheEntry *itemTypeCacheEntry = NULL;
/*
* If both cms_topn is null, it returns null. If one of the cms_topn's is
* null, it returns other cms_topn.
*/
if (PG_ARGISNULL(0) && PG_ARGISNULL(1))
{
PG_RETURN_NULL();
}
else if (PG_ARGISNULL(0))
{
secondCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(1);
PG_RETURN_POINTER(secondCmsTopn);
}
else if (PG_ARGISNULL(1))
{
firstCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(0);
PG_RETURN_POINTER(firstCmsTopn);
}
firstCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(0);
secondCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(1);
firstTopnArray = TopnArray(firstCmsTopn);
firstTopnArrayLength = ARR_DIMS(firstTopnArray)[0];
if (firstTopnArrayLength != 0)
{
Oid itemType = firstTopnArray->elemtype;
itemTypeCacheEntry = lookup_type_cache(itemType, 0);
}
newCmsTopn = CmsTopnUnion(firstCmsTopn, secondCmsTopn, itemTypeCacheEntry);
PG_RETURN_POINTER(newCmsTopn);
}
/*
* CmsTopnUnion is a helper function for union operations. It first sums up two
* sketchs and iterates through the top-n array of the second cms_topn to update
* the top-n of union.
*/
static CmsTopn *
CmsTopnUnion(CmsTopn *firstCmsTopn, CmsTopn *secondCmsTopn,
TypeCacheEntry *itemTypeCacheEntry)
{
ArrayType *firstTopnArray = TopnArray(firstCmsTopn);
ArrayType *secondTopnArray = TopnArray(secondCmsTopn);
ArrayType *newTopnArray = NULL;
Size firstTopnArrayLength = ARR_DIMS(firstTopnArray)[0];
Size secondTopnArrayLength = ARR_DIMS(secondTopnArray)[0];
Size sketchSize = 0;
CmsTopn *newCmsTopn = NULL;
uint32 topnItemIndex = 0;
Datum topnItem = 0;
ArrayIterator secondTopnArrayIterator = NULL;
bool isNull = false;
bool hasMoreItem = false;
if (firstCmsTopn->sketchDepth != secondCmsTopn->sketchDepth ||
firstCmsTopn->sketchWidth != secondCmsTopn->sketchWidth ||
firstCmsTopn->topnItemCount != secondCmsTopn->topnItemCount)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot merge cms_topns with different parameters")));
}
if (firstTopnArrayLength == 0)
{
newCmsTopn = secondCmsTopn;
}
else if (secondTopnArrayLength == 0)
{
newCmsTopn = firstCmsTopn;
}
else if (ARR_ELEMTYPE(firstTopnArray) != ARR_ELEMTYPE(secondTopnArray))
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot merge cms_topns of different types")));
}
else
{
/* for performance reasons we use first cms_topn to merge two cms_topn's */
newCmsTopn = firstCmsTopn;
newTopnArray = firstTopnArray;
sketchSize = newCmsTopn->sketchDepth * newCmsTopn->sketchWidth;
for (topnItemIndex = 0; topnItemIndex < sketchSize; topnItemIndex++)
{
newCmsTopn->sketch[topnItemIndex] += secondCmsTopn->sketch[topnItemIndex];
}
secondTopnArrayIterator = array_create_iterator(secondTopnArray, 0);
/*
* One by one we add top-n items in second top-n array to top-n array of
* first(new) top-n array. As a result only top-n elements of two item
* list are kept.
*/
hasMoreItem = array_iterate(secondTopnArrayIterator, &topnItem, &isNull);
while (hasMoreItem)
{
Frequency newItemFrequency = 0;
bool topnArrayUpdated = false;
newItemFrequency = CmsTopnEstimateItemFrequency(newCmsTopn, topnItem,
itemTypeCacheEntry);
newTopnArray = UpdateTopnArray(newCmsTopn, topnItem, itemTypeCacheEntry,
newItemFrequency, &topnArrayUpdated);
if (topnArrayUpdated)
{
newCmsTopn = FormCmsTopn(newCmsTopn, newTopnArray);
}
hasMoreItem = array_iterate(secondTopnArrayIterator, &topnItem, &isNull);
}
}
return newCmsTopn;
}
/*
* cms_topn_union_agg is aggregate function to create union of cms_topns.
*/
Datum
cms_topn_union_agg(PG_FUNCTION_ARGS)
{
CmsTopn *firstCmsTopn = NULL;
CmsTopn *secondCmsTopn = NULL;
CmsTopn *newCmsTopn = NULL;
ArrayType *firstTopnArray = NULL;
Size firstTopnArrayLength = 0;
TypeCacheEntry *itemTypeCacheEntry = NULL;
if (!AggCheckCallContext(fcinfo, NULL))
{
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION),
errmsg("cmsketch_merge_agg_trans called in non-aggregate "
"context")));
}
/*
* If both cms_topn is null, it returns null. If one of the cms_topn's is
* null, it returns other cms_topn.
*/
if (PG_ARGISNULL(0) && PG_ARGISNULL(1))
{
PG_RETURN_NULL();
}
else if (PG_ARGISNULL(0))
{
secondCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(1);
PG_RETURN_POINTER(secondCmsTopn);
}
else if (PG_ARGISNULL(1))
{
firstCmsTopn = (CmsTopn *) PG_GETARG_VARLENA_P(0);
PG_RETURN_POINTER(firstCmsTopn);
}