-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathanalyzeutils.c
More file actions
1382 lines (1183 loc) · 38.4 KB
/
analyzeutils.c
File metadata and controls
1382 lines (1183 loc) · 38.4 KB
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
/*-------------------------------------------------------------------------
*
* analyzeutils.c
*
* Provides utils functions for analyze.c
*
* Copyright (c) 2015, VMware, Inc. or its affiliates.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "catalog/indexing.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_statistic.h"
#include "cdb/cdbhash.h"
#include "commands/analyzeutils.h"
#include "commands/vacuum.h"
#include "lib/binaryheap.h"
#include "miscadmin.h"
#include "parser/parse_oper.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/hsearch.h"
typedef struct MCVFreqEntry
{
MCVFreqPair *entry;
} MCVFreqEntry;
typedef struct PartDatum
{
int partId; /* id of the partition histogram where the
* datum is from */
Datum datum;
} PartDatum;
static Datum *buildMCVArrayForStatsEntry(MCVFreqPair **mcvpairArray, int *nEntries, float4 ndistinct, float4 nrows);
static float4 *buildFreqArrayForStatsEntry(MCVFreqPair **mcvpairArray, int nEntries, float4 reltuples);
static int datumHashTableMatch(const void *keyPtr1, const void *keyPtr2, Size keysize);
static uint32 datumHashTableHash(const void *keyPtr, Size keysize);
static HTAB *createDatumHashTable(unsigned int nEntries);
static MCVFreqPair *MCVFreqPairCopy(MCVFreqPair *mcvFreqPair);
static bool containsDatum(HTAB *datumHash, MCVFreqPair *mcvFreqPair);
static void addLeafPartitionMCVsToHashTable(HTAB *datumHash, HeapTuple heaptupleStats,
float4 partReltuples, TypInfo *typInfo, int *idx
);
static void addMCVToHashTable(HTAB *datumHash, MCVFreqPair *mcvFreqPair);
static int mcvpair_cmp(const void *a, const void *b);
static void initTypInfo(TypInfo *typInfo, Oid relationOid, AttrNumber attnum);
static int DatumHeapComparator(Datum lhs, Datum rhs, void *context);
static void advanceCursor(int pid, int *cursors, AttStatsSlot * *histSlots);
static Datum getMinBound(AttStatsSlot * *histSlots, int *cursors, int nParts,
Oid ltFuncOid, Oid collid);
static Datum getMaxBound(AttStatsSlot * *histSlots, int nParts, Oid ltFuncOid, Oid
collid);
static void
getHistogramHeapTuple(AttStatsSlot * *histSlots, HeapTuple *heaptupleStats, int *numNotNullParts, int nParts);
static void initDatumHeap(binaryheap *hp, AttStatsSlot * *histSlots, int *cursors, int nParts);
static float4 getBucketSizes(const HeapTuple *heaptupleStats, const float4 *relTuples, int nParts,
MCVFreqPair **mcvPairRemaining, int rem_mcv,
float4 *eachBucket);
float4
get_rel_reltuples(Oid relid)
{
float4 relTuples = 0.0;
HeapTuple tp;
tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (HeapTupleIsValid(tp))
{
Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
relTuples = reltup->reltuples;
ReleaseSysCache(tp);
}
return relTuples;
}
int32
get_rel_relpages(Oid relid)
{
int32 relPages = 0.0;
HeapTuple tp;
tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (HeapTupleIsValid(tp))
{
Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
relPages = reltup->relpages;
ReleaseSysCache(tp);
}
return relPages;
}
/*
* Given column stats of an attribute, build an MCVFreqPair and add it to the hash table.
* If the MCV to be added already exist in the hash table, we increment its count value.
* Input:
* - datumHash: hash table
* - partOid: Oid of current partition
* - partReltuples: Number of tuples in that partition
* - typInfo: type information
* Output:
* - partReltuples: the number of tuples in this partition
*/
static void
addLeafPartitionMCVsToHashTable (HTAB *datumHash, HeapTuple heaptupleStats,
float4 partReltuples, TypInfo * typInfo,
int *idx)
{
AttStatsSlot mcvSlot;
int position = *idx;
(void) get_attstatsslot(&mcvSlot, heaptupleStats, STATISTIC_KIND_MCV,
InvalidOid, ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
Assert(mcvSlot.nvalues == mcvSlot.nnumbers);
for (int i = 0; i < mcvSlot.nvalues; i++)
{
Datum mcv = mcvSlot.values[i];
float4 count = partReltuples * mcvSlot.numbers[i];
MCVFreqPair *mcvFreqPair = (MCVFreqPair *) palloc(sizeof(MCVFreqPair));
mcvFreqPair->mcv = mcv;
mcvFreqPair->count = count;
mcvFreqPair->position = position++;
mcvFreqPair->typinfo = typInfo;
addMCVToHashTable(datumHash, mcvFreqPair);
pfree(mcvFreqPair);
}
*idx = position;
free_attstatsslot(&mcvSlot);
}
/*
* Main function for aggregating leaf partition MCV/Freq to compute
* root or interior partition MCV/Freq
*
* Input:
* - relationOid: Oid of root or interior partition
* - attnum: column number
* - numPartitions: # of elements in heaptupleStats and relTuples arrays
* - heaptupleStats: pg_statistics tuples for each partition
* - relTuples: number of tuples in each partition (pg_class.reltuples)
* - nEntries: target number of MCVs/Freqs to be collected, the real number of
* MCVs/Freqs returned may be less
*
* Output:
* - result: two dimensional arrays of MCVs and Freqs
*/
MCVFreqPair **
aggregate_leaf_partition_MCVs(Oid relationOid,
AttrNumber attnum,
int numPartitions,
HeapTuple *heaptupleStats,
float4 *relTuples,
unsigned int nEntries,
double ndistinct,
int *num_mcv,
int *rem_mcv,
void **result)
{
TypInfo *typInfo = (TypInfo *) palloc(sizeof(TypInfo));
initTypInfo(typInfo, relationOid, attnum);
/* Hash table for storing combined MCVs */
HTAB *datumHash = createDatumHashTable(nEntries);
float4 sumReltuples = 0;
int orderIdx = 0;
for (int i = 0; i < numPartitions; i++)
{
if (!HeapTupleIsValid(heaptupleStats[i]))
continue;
addLeafPartitionMCVsToHashTable(datumHash, heaptupleStats[i], relTuples[i],
typInfo, &orderIdx);
sumReltuples += relTuples[i];
}
*rem_mcv = hash_get_num_entries(datumHash);
if (0 == *rem_mcv)
{
/* in the unlikely event of an empty hash table, return early */
*result = NULL;
result++;
*result = NULL;
hash_destroy(datumHash);
return NULL;
}
int i = 0;
HASH_SEQ_STATUS hash_seq;
MCVFreqEntry *mcvfreq;
MCVFreqPair **mcvpairArray = palloc((*rem_mcv) * sizeof(MCVFreqPair *));
/* put MCVFreqPairs in an array in order to sort */
hash_seq_init(&hash_seq, datumHash);
while ((mcvfreq = hash_seq_search(&hash_seq)) != NULL)
{
mcvpairArray[i++] = mcvfreq->entry;
}
/* sort MCVFreqPairs in descending order of frequency */
qsort(mcvpairArray, i, sizeof(MCVFreqPair *), mcvpair_cmp);
/* prepare returning MCV and Freq arrays */
*num_mcv = Min(i, nEntries);
*result = (void *) buildMCVArrayForStatsEntry(mcvpairArray, num_mcv,
ndistinct, sumReltuples);
if (*result == NULL)
{
hash_destroy(datumHash);
*num_mcv = 0;
return mcvpairArray;
}
result++; /* now switch to frequency array (result[1]) */
*result = (void *) buildFreqArrayForStatsEntry(mcvpairArray, *num_mcv,
sumReltuples);
hash_destroy(datumHash);
pfree(typInfo);
*rem_mcv -= *num_mcv;
return mcvpairArray;
}
/*
* Return an array of MCVs from the resultant MCVFreqPair array
* Input:
* - mcvpairArray: contains MCVs and corresponding counts in desc order
* - nEntries: number of MCVs to be returned
* - typoid: type oid of the MCV datum
* - nrows: number of tuples from all partitions
*/
static Datum *
buildMCVArrayForStatsEntry(MCVFreqPair **mcvpairArray,
int *nEntries,
float4 ndistinct,
float4 nrows)
{
Assert(mcvpairArray);
Assert(*nEntries > 0);
Datum *out = palloc(sizeof(Datum) * (*nEntries));
double mincount = -1.0;
if (*nEntries == (int) ndistinct && ndistinct > 0)
{
/* Track list includes all values seen, and all will fit */
}
else
{
double avgcount,
maxmincount;
/* estimate # of occurrences in sample of a typical value */
avgcount = (double) nrows / ndistinct;
/* set minimum threshold count to store a value */
mincount = avgcount * 0.80;
if (mincount < 2)
mincount = 2;
/* don't let threshold exceed 1/K, however */
maxmincount = (double) nrows / (double) *nEntries;
if (mincount > maxmincount)
mincount = maxmincount;
}
for (int i = 0; i < *nEntries; i++)
{
if ((mcvpairArray[i])->count < mincount)
{
if (i == 0)
{
pfree(out);
return NULL;
}
else
{
*nEntries = i;
break;
}
}
Datum mcv = (mcvpairArray[i])->mcv;
out[i] = mcv;
}
return out;
}
/*
* Return an array of frequencies from the resultant MCVFreqPair array
* Input:
* - mcvpairArray: contains MCVs and corresponding counts in desc order
* - nEntries: number of frequencies to be returned
* - reltuples: number of tuples of the root or interior partition (all leaf partitions combined)
*/
static float4 *
buildFreqArrayForStatsEntry(MCVFreqPair **mcvpairArray,
int nEntries,
float4 reltuples)
{
Assert(mcvpairArray);
Assert(nEntries > 0);
Assert(reltuples > 0); /* otherwise ANALYZE will not collect stats */
float4 *out = (float *) palloc(sizeof(float4) * nEntries);
for (int i = 0; i < nEntries; i++)
{
float4 freq = mcvpairArray[i]->count / reltuples;
out[i] = freq;
}
return out;
}
/*
* Comparison function to sort an array of MCVFreqPairs in desc order
*/
static int
mcvpair_cmp(const void *a, const void *b)
{
Assert(a);
Assert(b);
MCVFreqPair *mcvFreqPair1 = *(MCVFreqPair **) a;
MCVFreqPair *mcvFreqPair2 = *(MCVFreqPair **) b;
if (mcvFreqPair1->count > mcvFreqPair2->count)
return -1;
if (mcvFreqPair1->count < mcvFreqPair2->count)
return 1;
return mcvFreqPair1->position - mcvFreqPair2->position;
}
/**
* Add an MCVFreqPair to the hash table, if the same datum already exists
* in the hash table, update its count
* Input:
* datumHash - hash table
* mcvFreqPair - MCVFreqPair to be added
* typbyval - whether the datum inside is passed by value
* typlen - pg_type.typlen of the datum type
*/
static void
addMCVToHashTable(HTAB *datumHash, MCVFreqPair *mcvFreqPair)
{
Assert(datumHash);
Assert(mcvFreqPair);
MCVFreqEntry *mcvfreq;
bool found = false; /* required by hash_search */
if (!containsDatum(datumHash, mcvFreqPair))
{
/* create a deep copy of MCVFreqPair and put it in the hash table */
MCVFreqPair *key = MCVFreqPairCopy(mcvFreqPair);
mcvfreq = hash_search(datumHash, &key, HASH_ENTER, &found);
mcvfreq->entry = key;
}
else
{
mcvfreq = hash_search(datumHash, &mcvFreqPair, HASH_FIND, &found);
Assert(mcvfreq);
mcvfreq->entry->count += mcvFreqPair->count;
}
return;
}
/**
* Copy function for MCVFreqPair
* Input:
* mcvFreqPair - input MCVFreqPair
* typbyval - whether the datum inside is passed by value
* typlen - pg_type.typlen of the datum type
* Output:
* result - a deep copy of input MCVFreqPair
*/
static MCVFreqPair *
MCVFreqPairCopy(MCVFreqPair *mcvFreqPair)
{
MCVFreqPair *result = (MCVFreqPair *) palloc(sizeof(MCVFreqPair));
result->count = mcvFreqPair->count;
result->position = mcvFreqPair->position;
result->typinfo = mcvFreqPair->typinfo;
result->mcv = datumCopy(mcvFreqPair->mcv,
mcvFreqPair->typinfo->typbyval,
mcvFreqPair->typinfo->typlen);
return result;
}
/**
* Test whether an MCVFreqPair is in the hash table
* Input:
* datumHash - hash table
* mcvFreqPair - pointer to an MCVFreqPair
* Output:
* found - whether the MCVFreqPair is found
*/
static bool
containsDatum(HTAB *datumHash, MCVFreqPair *mcvFreqPair)
{
bool found = false;
if (datumHash != NULL)
hash_search(datumHash, &mcvFreqPair, HASH_FIND, &found);
return found;
}
/**
* Create a hash table with both hash key and hash entry as a pointer
* to a MCVFreqPair struct
* Input:
* nEntries - estimated number of elements in the hash table, the size
* of the hash table can grow dynamically
* Output:
* a pointer to the created hash table
*/
static HTAB *
createDatumHashTable(unsigned int nEntries)
{
HASHCTL hash_ctl;
MemSet(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(MCVFreqPair *);
hash_ctl.entrysize = sizeof(MCVFreqEntry);
hash_ctl.hash = datumHashTableHash;
hash_ctl.match = datumHashTableMatch;
hash_ctl.hcxt = CurrentMemoryContext; /* VacAttrStats->anl_context */
return hash_create("DatumHashTable", nEntries, &hash_ctl,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
}
/**
* Hash function for MCVFreqPair struct pointer.
* Input:
* keyPtr - pointer to hash key
* keysize - not used, hash function must have this signature
* Output:
* result - hash value as an unsigned integer
*/
static uint32
datumHashTableHash(const void *keyPtr, Size keysize)
{
uint32 result;
MCVFreqPair *mcvFreqPair = *((MCVFreqPair **)keyPtr);
FmgrInfo *hashfunc = &mcvFreqPair->typinfo->hashfunc;
Oid collid = mcvFreqPair->typinfo->collid;
result = DatumGetUInt32(FunctionCall1Coll(hashfunc, collid, mcvFreqPair->mcv));
return result;
}
/**
* Match function for MCVFreqPair struct pointer.
* Input:
* keyPtr1, keyPtr2 - pointers to two hash keys
* keysize - not used, hash function must have this signature
* Output:
* 0 if two hash keys match, 1 otherwise
*/
static int
datumHashTableMatch(const void *keyPtr1, const void *keyPtr2, Size keysize)
{
Assert(keyPtr1);
Assert(keyPtr2);
MCVFreqPair *left = *((MCVFreqPair **) keyPtr1);
MCVFreqPair *right = *((MCVFreqPair **) keyPtr2);
Assert(left->typinfo->typOid == right->typinfo->typOid);
return OidFunctionCall2Coll(left->typinfo->eqFuncOp,
left->typinfo->collid,
left->mcv, right->mcv) ? 0 : 1;
}
/*
* Initialize type information
* Input:
* relationOid - oid of the relation
* attnum - attribute numbe
* Output:
* members of typInfo are initialized
*/
static void
initTypInfo(TypInfo *typInfo, Oid relationOid, AttrNumber attnum)
{
Oid ltOpr;
Oid eqOpr;
Oid hashFunc;
Oid typoid;
int32 typmod;
Oid collid;
get_atttypetypmodcoll(relationOid, attnum, &typoid, &typmod, &collid);
typInfo->typOid = typoid;
typInfo->collid = collid;
get_typlenbyval(typoid, &typInfo->typlen, &typInfo->typbyval);
get_sort_group_operators(typoid, false, true, false, <Opr, &eqOpr, NULL, NULL);
typInfo->ltFuncOp = get_opcode(ltOpr);
typInfo->eqFuncOp = get_opcode(eqOpr);
if (!get_op_hash_functions(eqOpr, &hashFunc, NULL))
elog(ERROR, "could not find hash function for hash operator %u", eqOpr);
fmgr_info(hashFunc, &typInfo->hashfunc);
}
/*
* Comparator function of heap element PartDatum
* Input:
* lhs, rhs - pointers to heap elements
* context - pointer to comparison context
* Output:
* -1 if lhs < rhs
* 0 if lhs == rhs
* 1 if lhs > rhs
*/
static int
DatumHeapComparator(Datum lhs, Datum rhs, void *context)
{
Datum d1 = ((PartDatum *) DatumGetPointer(lhs))->datum;
Datum d2 = ((PartDatum *) DatumGetPointer(rhs))->datum;
TypInfo *typInfo = (TypInfo *) context;
if (OidFunctionCall2Coll(typInfo->ltFuncOp,
typInfo->collid,
d1, d2))
{
return 1;
}
if (OidFunctionCall2Coll(typInfo->eqFuncOp,
typInfo->collid,
d1, d2))
{
return 0;
}
return -1;
}
/* Advance the cursor of a partition by 1, set to -1 if the end is reached
* Input:
* pid - partition id
* cursors - cursor vector
* nBounds - array of the number of bounds
* */
static void
advanceCursor(int pid, int *cursors, AttStatsSlot * *histSlots)
{
cursors[pid]++;
if (cursors[pid] >= histSlots[pid]->nvalues)
{
cursors[pid] = -1;
}
}
/*
* Get the minimum bound of all partition bounds. Only need to iterate over
* the first bound of each partition since the bounds in a histogram are ordered.
*/
static Datum
getMinBound(AttStatsSlot * *histSlots, int *cursors, int nParts, Oid ltFuncOid, Oid collid)
{
Assert(histSlots);
Assert(histSlots[0]);
Assert(cursors);
Assert(nParts > 0);
Datum minDatum = histSlots[0]->values[0];
for (int pid = 0; pid < nParts; pid++)
{
if (OidFunctionCall2Coll(ltFuncOid, collid,
histSlots[pid]->values[0], minDatum))
{
minDatum = histSlots[pid]->values[0];
}
advanceCursor(pid, cursors, histSlots);
}
return minDatum;
}
/*
* Get the maximum bound of all partition bounds. Only need to iterate over
* the last bound of each partition since the bounds in a histogram are ordered.
*/
static Datum
getMaxBound(AttStatsSlot * *histSlots, int nParts, Oid ltFuncOid, Oid collid)
{
Assert(histSlots);
Assert(histSlots[0]);
Assert(nParts > 0);
Datum maxDatum = histSlots[0]->values[histSlots[0]->nvalues - 1];
for (int pid = 0; pid < nParts; pid++)
{
if (OidFunctionCall2Coll(ltFuncOid, collid,
maxDatum, histSlots[pid]->values[histSlots[pid]->nvalues - 1]))
{
maxDatum = histSlots[pid]->values[histSlots[pid]->nvalues - 1];
}
}
return maxDatum;
}
/*
* Preparing the output array of histogram bounds, removing any duplicates
* Input:
* ldatum - list of pointers to the aggregated bounds, may contain duplicates
* typInfo - type information
* Output:
* an array containing the aggregated histogram bounds
*/
static Datum *
buildHistogramEntryForStats(List *ldatum, TypInfo *typInfo, int *num_hist)
{
Assert(ldatum);
Assert(typInfo);
Datum *histArray = (Datum *) palloc(sizeof(Datum) * list_length(ldatum));
ListCell *lc;
Datum *prevDatum = (Datum *) linitial(ldatum);
int idx = 0;
*num_hist = 0;
foreach_with_count(lc, ldatum, idx)
{
Datum *pdatum = (Datum *) lfirst(lc);
/* remove duplicate datum in the list, starting from the second datum */
if (OidFunctionCall2Coll(typInfo->eqFuncOp, typInfo->collid,
*pdatum, *prevDatum) && idx > 0)
{
continue;
}
histArray[*num_hist] = *pdatum;
*num_hist = *num_hist + 1;
*prevDatum = *pdatum;
}
return histArray;
}
/*
* Obtain all histogram bounds from every partition and store them in a 2D array (histData)
* Input:
* lRelOids - list of part Oids
* typInfo - type info
* attnum - attribute number
* Output:
* histData - 2D array of all histogram bounds from every partition
* nBounds - array of the number of histogram bounds (from each partition)
* partsReltuples - array of the number of tuples (from each partition)
* sumReltuples - sum of number of tuples in all partitions
*/
static void
getHistogramHeapTuple(AttStatsSlot * *histSlots, HeapTuple *heaptupleStats,
int *numNotNullParts, int nParts)
{
int pid = 0;
for (int i = 0; i < nParts; i++)
{
if (!HeapTupleIsValid(heaptupleStats[i]))
{
continue;
}
histSlots[pid] = (AttStatsSlot *) palloc(sizeof(AttStatsSlot));
(void) get_attstatsslot(histSlots[pid], heaptupleStats[i], STATISTIC_KIND_HISTOGRAM, InvalidOid, ATTSTATSSLOT_VALUES);
if (histSlots[pid]->nvalues > 0)
{
pid++;
}
}
*numNotNullParts = pid;
}
/*
* Obtain all histogram bounds from every partition and store them in a 2D array (histData)
* Input:
* lRelOids - list of part Oids
* typInfo - type info
* attnum - attribute number
* Output:
* histData - 2D array of all histogram bounds from every partition
* nBounds - array of the number of histogram bounds (from each partition)
* partsReltuples - array of the number of tuples (from each partition)
* sumReltuples - sum of number of tuples in all partitions
*/
static void
getHistogramMCVTuple(AttStatsSlot * *histSlots, MCVFreqPair **mcvRemaining,
int start_idx, int rem_mcv)
{
for (int i = 0; i < rem_mcv; i++)
{
histSlots[start_idx + i] = (AttStatsSlot *) palloc(sizeof(AttStatsSlot));
histSlots[start_idx + i]->nvalues = 2;
histSlots[start_idx + i]->values = (Datum *) palloc(sizeof(Datum) * 2);
histSlots[start_idx + i]->values[0] = mcvRemaining[i]->mcv;
histSlots[start_idx + i]->values[1] = mcvRemaining[i]->mcv;
}
}
static bool
getNdvBySegHeapTuple(AttStatsSlot * *ndvbsSlots, HeapTuple *heaptupleStats, float4 *relTuples, int nParts)
{
bool valid = true;
for (int i = 0; i < nParts; i++)
{
if (!HeapTupleIsValid(heaptupleStats[i]))
{
continue;
}
ndvbsSlots[i] = (AttStatsSlot *) palloc(sizeof(AttStatsSlot));
(void) get_attstatsslot(ndvbsSlots[i], heaptupleStats[i],
STATISTIC_KIND_NDV_BY_SEGMENTS, InvalidOid, ATTSTATSSLOT_VALUES);
if (ndvbsSlots[i]->valuetype != FLOAT8OID)
{
/*
* NDV_BY_SEGMENTS slot not found or has unexpected type.
* Non-empty partitions must have valid NDV_BY_SEGMENTS;
* empty partitions (relTuples == 0) can be skipped.
*/
if (relTuples[i] > 0)
{
valid = false;
break;
}
free_attstatsslot(ndvbsSlots[i]);
pfree(ndvbsSlots[i]);
ndvbsSlots[i] = NULL;
continue;
}
Assert(ndvbsSlots[i]->valuetype == FLOAT8OID);
if (ndvbsSlots[i]->nvalues != 1)
{
valid = false;
break;
}
/* Non-empty partition with zero NDV is suspicious */
if (relTuples[i] > 0 && DatumGetFloat8(ndvbsSlots[i]->values[0]) == 0)
{
valid = false;
break;
}
}
return valid;
}
/*
* Initialize heap by inserting the second histogram bound from each partition histogram.
* Input:
* hp - heap
* histData - all histogram bounds from each part
* cursors - cursor vector
* nParts - number of partitions
*/
static void
initDatumHeap(binaryheap *hp, AttStatsSlot * *histSlots, int *cursors, int nParts)
{
PartDatum *pds = (PartDatum *) palloc(nParts * sizeof(PartDatum));
for (int pid = 0; pid < nParts; pid++)
{
/* do nothing if part histogram only has one element */
if (cursors[pid] > 0)
{
pds[pid].partId = pid;
pds[pid].datum = histSlots[pid]->values[cursors[pid]];
binaryheap_add_unordered(hp, PointerGetDatum(&pds[pid]));
}
}
binaryheap_build(hp);
}
/*
* Main function for aggregating leaf partition histogram to compute
* root or interior partition histogram
* Input:
* - relationOid: Oid of root or interior partition
* - attnum: column number
* - nParts: # of elements in heaptupleStats and relTuples arrays
* - heaptupleStats: pg_statistics tuples for each partition
* - nEntries: target number of histogram bounds to be collected, the real number of
* histogram bounds returned may be less
* Output:
* - result: an array of aggregated histogram bounds
* Algorithm:
*
* We use the following example to explain how the aggregating algorithm works.
Suppose a parent table 'lineitem' has 3 partitions 'lineitem_prt_1', 'lineitem_prt_2',
'lineitem_prt_3'. The histograms of the column of interest of the parts are:
hist(prt_1): {0,19,38,59}
hist(prt_2): {2,18,40,62}
hist(prt_3): {1,22,39,61}
Note the histograms are equi-depth, which implies each bucket should contain the same number of tuples.
The number of tuples in each part is:
nTuples(prt_1) = 300
nTuples(prt_2) = 270
nTuples(prt_3) = 330
Some notation:
hist(agg): the aggregated histogram
hist(parts): the histograms of the partitions, i.e., {hist(prt_1), hist(prt_2), hist(prt_3)}
nEntries: the target number of histogram buckets in hist(agg). Usually this is the same as in the partitions. In this example, nEntries = 3.
nParts: the number of partitions. nParts = 3 in this example.
Since we know the target number of tuples in each bucket of hist(agg), the basic idea is to fill the buckets of hist(agg) using the buckets in hist(parts). And once a bucket in hist(agg) is filled up, we look at which bucket from hist(parts) is the current bucket, and use its bound as the bucket bound in hist(agg).
Continue with our example we have,
bucketSize(prt_1) = 300/3 = 100
bucketSize(prt_2) = 270/3 = 90
bucketSize(prt_3) = 330/3 = 110
bucketSize(agg) = (300+270+330)/3 = 300
Now, to begin with, we find the minimum of the first boundary point across hist(parts) and use it as the first boundary of hist(agg), i.e.,
hist(agg) = {min({0,2,1})} = {0}
We need to maintain a priority queue in order to decide on the next bucket from hist(parts) to work with.
Each element in the queue is a (Datum, partID) pair, where Datum is a boundary from hist(parts) and partID is the ID of the part the Datum comes from.
Each time we dequeue(), we get the minimum datum in the queue as the next datum we will work on.
The priority queue contains up to nParts entries. In our example, we first enqueue
the second boundary across hist(parts), i.e., 19, 18, 22, along with their part ID.
Continue with filling the bucket of hist(agg), we dequeue '18' from the queue and fill in
the first bucket (having 90 tuples). Since bucketSize(agg) = 300, we need more buckets
from hist(parts) to fill it. At the same time, we dequeue 18 and enqueue the next bound (which is 40).
The first bucket of hist(agg) will be filled up by '22' (90+100+110 >= 300), at this time we put '22' as the next boundary value in hist(agg), i.e.
hist(agg) = {0,22}
Continue with the iteration, we will finally fill all the buckets
hist(agg) = {0,22,40,62}
*
*/
int
aggregate_leaf_partition_histograms(Oid relationOid,
AttrNumber attnum,
int nParts,
HeapTuple *heaptupleStats,
float4 *relTuples,
unsigned int nEntries,
MCVFreqPair **mcvpairArray,
int rem_mcv,
void **result)
{
AssertImply(rem_mcv != 0, mcvpairArray != NULL);
Assert(nParts > 0);
/* get type information */
TypInfo typInfo;
initTypInfo(&typInfo, relationOid, attnum);
AttStatsSlot **histSlots = (AttStatsSlot * *) palloc0((nParts + rem_mcv) * sizeof(AttStatsSlot *));
float4 sumReltuples = 0;
int numNotNullParts = 0;
/* populate histData, nBounds, partsReltuples and sumReltuples */
float4 *eachBucket = palloc0((nParts + rem_mcv) * sizeof(float4)); /* the number of data
* points in each bucket
* for each histogram */
getHistogramHeapTuple(histSlots, heaptupleStats, &numNotNullParts, nParts);
if (0 == numNotNullParts + rem_mcv)
{
/* if all the parts histograms are empty, we return nothing */
result = NULL;
return 0;
}
getHistogramMCVTuple(histSlots, mcvpairArray, numNotNullParts, rem_mcv);
sumReltuples = getBucketSizes(heaptupleStats, relTuples, nParts, mcvpairArray, rem_mcv, eachBucket);
/* reset nParts to the number of non-null parts */
nParts = numNotNullParts + rem_mcv;
/* now define the state variables needed for the aggregation loop */
float4 bucketSize = sumReltuples / nEntries; /* target bucket size in
* the aggregated
* histogram */
float4 nTuplesToFill = bucketSize; /* remaining number of tuples to
* fill in the current bucket of
* the aggregated histogram, reset
* to bucketSize when a new bucket
* is added */
int *cursors = palloc0(nParts * sizeof(int)); /* the index of current
* bucket for each
* histogram, set to -1
* after the histogram
* has been traversed */
float4 *remainingSize = palloc0(nParts * sizeof(float4)); /* remaining number of
* tuples in the current
* bucket of a part */
/* initialize eachBucket[] and remainingSize[] */
for (int i = 0; i < nParts; i++)
{
if (1 < histSlots[i]->nvalues)
{
remainingSize[i] = eachBucket[i];
}
}
/* we maintain a priority queue (min heap) of PartDatum */
binaryheap *dhp = binaryheap_allocate(nParts,
DatumHeapComparator,
&typInfo);
List *ldatum = NIL; /* list of pointers to the selected bounds */
/*
* the first bound in the aggregated histogram will be the minimum of the
* first bounds of all parts
*/
Datum minBound = getMinBound(histSlots, cursors, nParts,
typInfo.ltFuncOp, typInfo.collid);
ldatum = lappend(ldatum, &minBound);
/*
* continue filling the aggregated histogram, starting from the second
* bound
*/
initDatumHeap(dhp, histSlots, cursors, nParts);
/*
* loop continues when DatumHeap is not empty yet and the number of
* histogram boundaries has not reached nEntries
*/
while (!binaryheap_empty(dhp) && list_length(ldatum) < nEntries)
{
PartDatum *pd = (PartDatum *) DatumGetPointer(binaryheap_first(dhp));
int pid = pd->partId;
if (remainingSize[pid] < nTuplesToFill)
{
nTuplesToFill -= remainingSize[pid];
advanceCursor(pid, cursors, histSlots);
remainingSize[pid] = eachBucket[pid];
if (cursors[pid] > 0)
{
pd->datum = histSlots[pid]->values[cursors[pid]];
binaryheap_replace_first(dhp, PointerGetDatum(pd));
}
else
(void) binaryheap_remove_first(dhp);