PostgreSQL Source Code git master
Loading...
Searching...
No Matches
mvdistinct.c File Reference
#include "postgres.h"
#include <math.h>
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_statistic_ext_data.h"
#include "statistics/extended_stats_internal.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "varatt.h"
Include dependency graph for mvdistinct.c:

Go to the source code of this file.

Data Structures

struct  CombinationGenerator
 

Macros

#define SizeOfHeader   (3 * sizeof(uint32))
 
#define SizeOfItem(natts)    (sizeof(double) + sizeof(int) + (natts) * sizeof(AttrNumber))
 
#define MinSizeOfItem   SizeOfItem(2)
 
#define MinSizeOfItems(nitems)    (SizeOfHeader + (nitems) * MinSizeOfItem)
 

Typedefs

typedef struct CombinationGenerator CombinationGenerator
 

Functions

static double ndistinct_for_combination (double totalrows, StatsBuildData *data, int k, int *combination)
 
static double estimate_ndistinct (double totalrows, int numrows, int d, int f1)
 
static int n_choose_k (int n, int k)
 
static int num_combinations (int n)
 
static CombinationGeneratorgenerator_init (int n, int k)
 
static void generator_free (CombinationGenerator *state)
 
static intgenerator_next (CombinationGenerator *state)
 
static void generate_combinations (CombinationGenerator *state)
 
MVNDistinctstatext_ndistinct_build (double totalrows, StatsBuildData *data)
 
MVNDistinctstatext_ndistinct_load (Oid mvoid, bool inh)
 
byteastatext_ndistinct_serialize (MVNDistinct *ndistinct)
 
MVNDistinctstatext_ndistinct_deserialize (bytea *data)
 
void statext_ndistinct_free (MVNDistinct *ndistinct)
 
bool statext_ndistinct_validate (const MVNDistinct *ndistinct, const int2vector *stxkeys, int numexprs, int elevel)
 
static void generate_combinations_recurse (CombinationGenerator *state, int index, int start, int *current)
 

Macro Definition Documentation

◆ MinSizeOfItem

#define MinSizeOfItem   SizeOfItem(2)

Definition at line 49 of file mvdistinct.c.

◆ MinSizeOfItems

#define MinSizeOfItems (   nitems)     (SizeOfHeader + (nitems) * MinSizeOfItem)

Definition at line 52 of file mvdistinct.c.

58{
59 int k; /* size of the combination */
60 int n; /* total number of elements */
61 int current; /* index of the next combination to return */
62 int ncombinations; /* number of combinations (size of array) */
63 int *combinations; /* array of pre-built combinations */
65
66static CombinationGenerator *generator_init(int n, int k);
70
71
72/*
73 * statext_ndistinct_build
74 * Compute ndistinct coefficient for the combination of attributes.
75 *
76 * This computes the ndistinct estimate using the same estimator used
77 * in analyze.c and then computes the coefficient.
78 *
79 * To handle expressions easily, we treat them as system attributes with
80 * negative attnums, and offset everything by number of expressions to
81 * allow using Bitmapsets.
82 */
85{
87 int k;
89 int numattrs = data->nattnums;
91
93 numcombs * sizeof(MVNDistinctItem));
96 result->nitems = numcombs;
97
98 itemcnt = 0;
99 for (k = 2; k <= numattrs; k++)
100 {
101 int *combination;
103
104 /* generate combinations of K out of N elements */
106
108 {
109 MVNDistinctItem *item = &result->items[itemcnt];
110 int j;
111
113 item->nattributes = k;
114
115 /* translate the indexes to attnums */
116 for (j = 0; j < k; j++)
117 {
118 item->attributes[j] = data->attnums[combination[j]];
119
121 }
122
123 item->ndistinct =
125
126 itemcnt++;
128 }
129
131 }
132
133 /* must consume exactly the whole output array */
134 Assert(itemcnt == result->nitems);
135
136 return result;
137}
138
139/*
140 * statext_ndistinct_load
141 * Load the ndistinct value for the indicated pg_statistic_ext tuple
142 */
145{
147 bool isnull;
148 Datum ndist;
149 HeapTuple htup;
150
153 if (!HeapTupleIsValid(htup))
154 elog(ERROR, "cache lookup failed for statistics object %u", mvoid);
155
158 if (isnull)
159 elog(ERROR,
160 "requested statistics kind \"%c\" is not yet built for statistics object %u",
162
164
165 ReleaseSysCache(htup);
166
167 return result;
168}
169
170/*
171 * statext_ndistinct_serialize
172 * serialize ndistinct to the on-disk bytea format
173 */
174bytea *
176{
177 bytea *output;
178 char *tmp;
179 Size len;
180
181 Assert(ndistinct->magic == STATS_NDISTINCT_MAGIC);
183
184 /*
185 * Base size is size of scalar fields in the struct, plus one base struct
186 * for each item, including number of items for each.
187 */
189
190 /* and also include space for the actual attribute numbers */
191 for (uint32 i = 0; i < ndistinct->nitems; i++)
192 {
193 int nmembers;
194
195 nmembers = ndistinct->items[i].nattributes;
196 Assert(nmembers >= 2);
197
198 len += SizeOfItem(nmembers);
199 }
200
201 output = (bytea *) palloc(len);
203
204 tmp = VARDATA(output);
205
206 /* Store the base struct values (magic, type, nitems) */
207 memcpy(tmp, &ndistinct->magic, sizeof(uint32));
208 tmp += sizeof(uint32);
209 memcpy(tmp, &ndistinct->type, sizeof(uint32));
210 tmp += sizeof(uint32);
211 memcpy(tmp, &ndistinct->nitems, sizeof(uint32));
212 tmp += sizeof(uint32);
213
214 /*
215 * store number of attributes and attribute numbers for each entry
216 */
217 for (uint32 i = 0; i < ndistinct->nitems; i++)
218 {
219 MVNDistinctItem item = ndistinct->items[i];
220 int nmembers = item.nattributes;
221
222 memcpy(tmp, &item.ndistinct, sizeof(double));
223 tmp += sizeof(double);
224 memcpy(tmp, &nmembers, sizeof(int));
225 tmp += sizeof(int);
226
227 memcpy(tmp, item.attributes, sizeof(AttrNumber) * nmembers);
228 tmp += nmembers * sizeof(AttrNumber);
229
230 /* protect against overflows */
231 Assert(tmp <= ((char *) output + len));
232 }
233
234 /* check we used exactly the expected space */
235 Assert(tmp == ((char *) output + len));
236
237 return output;
238}
239
240/*
241 * statext_ndistinct_deserialize
242 * Read an on-disk bytea format MVNDistinct to in-memory format
243 */
246{
249 MVNDistinct *ndistinct;
250 char *tmp;
251
252 if (data == NULL)
253 return NULL;
254
255 /* we expect at least the basic fields of MVNDistinct struct */
257 elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
259
260 /* initialize pointer to the data part (skip the varlena header) */
261 tmp = VARDATA_ANY(data);
262
263 /* read the header fields and perform basic sanity checks */
264 memcpy(&ndist.magic, tmp, sizeof(uint32));
265 tmp += sizeof(uint32);
266 memcpy(&ndist.type, tmp, sizeof(uint32));
267 tmp += sizeof(uint32);
268 memcpy(&ndist.nitems, tmp, sizeof(uint32));
269 tmp += sizeof(uint32);
270
271 if (ndist.magic != STATS_NDISTINCT_MAGIC)
272 elog(ERROR, "invalid ndistinct magic %08x (expected %08x)",
275 elog(ERROR, "invalid ndistinct type %d (expected %d)",
277 if (ndist.nitems == 0)
278 elog(ERROR, "invalid zero-length item array in MVNDistinct");
279
280 /* what minimum bytea size do we expect for those parameters */
283 elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
285
286 /*
287 * Allocate space for the ndistinct items (no space for each item's
288 * attnos: those live in bitmapsets allocated separately)
289 */
290 ndistinct = palloc0(MAXALIGN(offsetof(MVNDistinct, items)) +
291 (ndist.nitems * sizeof(MVNDistinctItem)));
292 ndistinct->magic = ndist.magic;
293 ndistinct->type = ndist.type;
294 ndistinct->nitems = ndist.nitems;
295
296 for (uint32 i = 0; i < ndistinct->nitems; i++)
297 {
298 MVNDistinctItem *item = &ndistinct->items[i];
299
300 /* ndistinct value */
301 memcpy(&item->ndistinct, tmp, sizeof(double));
302 tmp += sizeof(double);
303
304 /* number of attributes */
305 memcpy(&item->nattributes, tmp, sizeof(int));
306 tmp += sizeof(int);
307 Assert((item->nattributes >= 2) && (item->nattributes <= STATS_MAX_DIMENSIONS));
308
309 item->attributes
310 = (AttrNumber *) palloc(item->nattributes * sizeof(AttrNumber));
311
312 memcpy(item->attributes, tmp, sizeof(AttrNumber) * item->nattributes);
313 tmp += sizeof(AttrNumber) * item->nattributes;
314
315 /* still within the bytea */
316 Assert(tmp <= ((char *) data + VARSIZE_ANY(data)));
317 }
318
319 /* we should have consumed the whole bytea exactly */
320 Assert(tmp == ((char *) data + VARSIZE_ANY(data)));
321
322 return ndistinct;
323}
324
325/*
326 * Free allocations of a MVNDistinct.
327 */
328void
330{
331 for (uint32 i = 0; i < ndistinct->nitems; i++)
332 pfree(ndistinct->items[i].attributes);
333 pfree(ndistinct);
334}
335
336/*
337 * Validate a set of MVNDistincts against the extended statistics object
338 * definition.
339 *
340 * Every MVNDistinctItem must be checked to ensure that the attnums in the
341 * attributes list correspond to attnums/expressions defined by the extended
342 * statistics object.
343 *
344 * Positive attnums are attributes which must be found in the stxkeys,
345 * while negative attnums correspond to an expression number, no attribute
346 * number can be below (0 - numexprs).
347 */
348bool
350 const int2vector *stxkeys,
351 int numexprs, int elevel)
352{
354
355 /* Scan through each MVNDistinct entry */
356 for (uint32 i = 0; i < ndistinct->nitems; i++)
357 {
358 MVNDistinctItem item = ndistinct->items[i];
359
360 /*
361 * Cross-check each attribute in a MVNDistinct entry with the extended
362 * stats object definition.
363 */
364 for (int j = 0; j < item.nattributes; j++)
365 {
367 bool ok = false;
368
369 if (attnum > 0)
370 {
371 /* attribute number in stxkeys */
372 for (int k = 0; k < stxkeys->dim1; k++)
373 {
374 if (attnum == stxkeys->values[k])
375 {
376 ok = true;
377 break;
378 }
379 }
380 }
381 else if ((attnum < 0) && (attnum >= attnum_expr_lowbound))
382 {
383 /* attribute number for an expression */
384 ok = true;
385 }
386
387 if (!ok)
388 {
389 ereport(elevel,
391 errmsg("could not validate \"%s\" object: invalid attribute number %d found",
392 "pg_ndistinct", attnum)));
393 return false;
394 }
395 }
396 }
397
398 return true;
399}
400
401/*
402 * ndistinct_for_combination
403 * Estimates number of distinct values in a combination of columns.
404 *
405 * This uses the same ndistinct estimator as compute_scalar_stats() in
406 * ANALYZE, i.e.,
407 * n*d / (n - f1 + f1*n/N)
408 *
409 * except that instead of values in a single column we are dealing with
410 * combination of multiple columns.
411 */
412static double
414 int k, int *combination)
415{
416 int i,
417 j;
418 int f1,
419 cnt,
420 d;
421 bool *isnull;
422 Datum *values;
425 int numrows = data->numrows;
426
427 mss = multi_sort_init(k);
428
429 /*
430 * In order to determine the number of distinct elements, create separate
431 * values[]/isnull[] arrays with all the data we have, then sort them
432 * using the specified column combination as dimensions. We could try to
433 * sort in place, but it'd probably be more complex and bug-prone.
434 */
435 items = palloc_array(SortItem, numrows);
436 values = palloc0_array(Datum, numrows * k);
437 isnull = palloc0_array(bool, numrows * k);
438
439 for (i = 0; i < numrows; i++)
440 {
441 items[i].values = &values[i * k];
442 items[i].isnull = &isnull[i * k];
443 }
444
445 /*
446 * For each dimension, set up sort-support and fill in the values from the
447 * sample data.
448 *
449 * We use the column data types' default sort operators and collations;
450 * perhaps at some point it'd be worth using column-specific collations?
451 */
452 for (i = 0; i < k; i++)
453 {
454 Oid typid;
458
459 typid = colstat->attrtypid;
460 collid = colstat->attrcollid;
461
463 if (type->lt_opr == InvalidOid) /* shouldn't happen */
464 elog(ERROR, "cache lookup failed for ordering operator for type %u",
465 typid);
466
467 /* prepare the sort function for this dimension */
469
470 /* accumulate all the data for this dimension into the arrays */
471 for (j = 0; j < numrows; j++)
472 {
473 items[j].values[i] = data->values[combination[i]][j];
474 items[j].isnull[i] = data->nulls[combination[i]][j];
475 }
476 }
477
478 /* We can sort the array now ... */
479 qsort_interruptible(items, numrows, sizeof(SortItem),
481
482 /* ... and count the number of distinct combinations */
483
484 f1 = 0;
485 cnt = 1;
486 d = 1;
487 for (i = 1; i < numrows; i++)
488 {
489 if (multi_sort_compare(&items[i], &items[i - 1], mss) != 0)
490 {
491 if (cnt == 1)
492 f1 += 1;
493
494 d++;
495 cnt = 0;
496 }
497
498 cnt += 1;
499 }
500
501 if (cnt == 1)
502 f1 += 1;
503
504 return estimate_ndistinct(totalrows, numrows, d, f1);
505}
506
507/* The Duj1 estimator (already used in analyze.c). */
508static double
509estimate_ndistinct(double totalrows, int numrows, int d, int f1)
510{
511 double numer,
512 denom,
513 ndistinct;
514
515 numer = (double) numrows * (double) d;
516
517 denom = (double) (numrows - f1) +
518 (double) f1 * (double) numrows / totalrows;
519
520 ndistinct = numer / denom;
521
522 /* Clamp to sane range in case of roundoff error */
523 if (ndistinct < (double) d)
524 ndistinct = (double) d;
525
526 if (ndistinct > totalrows)
527 ndistinct = totalrows;
528
529 return floor(ndistinct + 0.5);
530}
531
532/*
533 * n_choose_k
534 * computes binomial coefficients using an algorithm that is both
535 * efficient and prevents overflows
536 */
537static int
538n_choose_k(int n, int k)
539{
540 int d,
541 r;
542
543 Assert((k > 0) && (n >= k));
544
545 /* use symmetry of the binomial coefficients */
546 k = Min(k, n - k);
547
548 r = 1;
549 for (d = 1; d <= k; ++d)
550 {
551 r *= n--;
552 r /= d;
553 }
554
555 return r;
556}
557
558/*
559 * num_combinations
560 * number of combinations, excluding single-value combinations
561 */
562static int
563num_combinations(int n)
564{
565 return (1 << n) - (n + 1);
566}
567
568/*
569 * generator_init
570 * initialize the generator of combinations
571 *
572 * The generator produces combinations of K elements in the interval (0..N).
573 * We prebuild all the combinations in this method, which is simpler than
574 * generating them on the fly.
575 */
577generator_init(int n, int k)
578{
580
581 Assert((n >= k) && (k > 0));
582
583 /* allocate the generator state as a single chunk of memory */
585
586 state->ncombinations = n_choose_k(n, k);
587
588 /* pre-allocate space for all combinations */
589 state->combinations = palloc_array(int, k * state->ncombinations);
590
591 state->current = 0;
592 state->k = k;
593 state->n = n;
594
595 /* now actually pre-generate all the combinations of K elements */
597
598 /* make sure we got the expected number of combinations */
599 Assert(state->current == state->ncombinations);
600
601 /* reset the number, so we start with the first one */
602 state->current = 0;
603
604 return state;
605}
606
607/*
608 * generator_next
609 * returns the next combination from the prebuilt list
610 *
611 * Returns a combination of K array indexes (0 .. N), as specified to
612 * generator_init), or NULL when there are no more combination.
613 */
614static int *
616{
617 if (state->current == state->ncombinations)
618 return NULL;
619
620 return &state->combinations[state->k * state->current++];
621}
622
623/*
624 * generator_free
625 * free the internal state of the generator
626 *
627 * Releases the generator internal state (pre-built combinations).
628 */
629static void
631{
632 pfree(state->combinations);
633 pfree(state);
634}
635
636/*
637 * generate_combinations_recurse
638 * given a prefix, generate all possible combinations
639 *
640 * Given a prefix (first few elements of the combination), generate following
641 * elements recursively. We generate the combinations in lexicographic order,
642 * which eliminates permutations of the same combination.
643 */
644static void
646 int index, int start, int *current)
647{
648 /* If we haven't filled all the elements, simply recurse. */
649 if (index < state->k)
650 {
651 int i;
652
653 /*
654 * The values have to be in ascending order, so make sure we start
655 * with the value passed by parameter.
656 */
657
658 for (i = start; i < state->n; i++)
659 {
660 current[index] = i;
661 generate_combinations_recurse(state, (index + 1), (i + 1), current);
662 }
663
664 return;
665 }
666 else
667 {
668 /* we got a valid combination, add it to the array */
669 memcpy(&state->combinations[(state->k * state->current)],
670 current, state->k * sizeof(int));
671 state->current++;
672 }
673}
674
675/*
676 * generate_combinations
677 * generate all k-combinations of N elements
678 */
679static void
681{
682 int *current = palloc0_array(int, state->k);
683
684 generate_combinations_recurse(state, 0, 0, current);
685
686 pfree(current);
687}
int16 AttrNumber
Definition attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition attnum.h:34
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define Min(x, y)
Definition c.h:1131
#define MAXALIGN(LEN)
Definition c.h:955
#define VARHDRSZ
Definition c.h:840
#define Assert(condition)
Definition c.h:1002
uint32_t uint32
Definition c.h:683
size_t Size
Definition c.h:748
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
Oid collid
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
int multi_sort_compare(const void *a, const void *b, void *arg)
MultiSortSupport multi_sort_init(int ndims)
void multi_sort_add_dimension(MultiSortSupport mss, int sortdim, Oid oper, Oid collation)
#define palloc_object(type)
Definition fe_memutils.h:89
#define palloc_array(type, count)
Definition fe_memutils.h:91
#define palloc0_array(type, count)
Definition fe_memutils.h:92
#define DatumGetByteaPP(X)
Definition fmgr.h:292
return str start
#define HeapTupleIsValid(tuple)
Definition htup.h:78
#define nitems(x)
Definition indent.h:31
FILE * output
int j
Definition isn.c:78
int i
Definition isn.c:77
void pfree(void *pointer)
Definition mcxt.c:1619
void * palloc0(Size size)
Definition mcxt.c:1420
void * palloc(Size size)
Definition mcxt.c:1390
static int n_choose_k(int n, int k)
Definition mvdistinct.c:539
#define SizeOfHeader
Definition mvdistinct.c:42
void statext_ndistinct_free(MVNDistinct *ndistinct)
Definition mvdistinct.c:330
static double estimate_ndistinct(double totalrows, int numrows, int d, int f1)
Definition mvdistinct.c:510
static void generate_combinations_recurse(CombinationGenerator *state, int index, int start, int *current)
Definition mvdistinct.c:646
MVNDistinct * statext_ndistinct_deserialize(bytea *data)
Definition mvdistinct.c:246
static double ndistinct_for_combination(double totalrows, StatsBuildData *data, int k, int *combination)
Definition mvdistinct.c:414
bytea * statext_ndistinct_serialize(MVNDistinct *ndistinct)
Definition mvdistinct.c:176
static void generate_combinations(CombinationGenerator *state)
Definition mvdistinct.c:681
MVNDistinct * statext_ndistinct_load(Oid mvoid, bool inh)
Definition mvdistinct.c:145
static int num_combinations(int n)
Definition mvdistinct.c:564
MVNDistinct * statext_ndistinct_build(double totalrows, StatsBuildData *data)
Definition mvdistinct.c:85
#define SizeOfItem(natts)
Definition mvdistinct.c:45
static void generator_free(CombinationGenerator *state)
Definition mvdistinct.c:631
static CombinationGenerator * generator_init(int n, int k)
Definition mvdistinct.c:578
#define MinSizeOfItems(nitems)
Definition mvdistinct.c:52
bool statext_ndistinct_validate(const MVNDistinct *ndistinct, const int2vector *stxkeys, int numexprs, int elevel)
Definition mvdistinct.c:350
static int * generator_next(CombinationGenerator *state)
Definition mvdistinct.c:616
static char * errmsg
int16 attnum
const void size_t len
const void * data
void qsort_interruptible(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
unsigned int Oid
static int fb(int x)
int f1[ARRAY_SIZE]
#define STATS_NDISTINCT_MAGIC
Definition statistics.h:22
#define STATS_NDISTINCT_TYPE_BASIC
Definition statistics.h:23
#define STATS_MAX_DIMENSIONS
Definition statistics.h:19
AttrNumber * attributes
Definition statistics.h:30
uint32 nitems
Definition statistics.h:38
uint32 type
Definition statistics.h:37
uint32 magic
Definition statistics.h:36
MVNDistinctItem items[FLEXIBLE_ARRAY_MEMBER]
Definition statistics.h:39
Oid attrtypid
Definition vacuum.h:125
Definition type.h:97
Definition c.h:835
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache2(SysCacheIdentifier cacheId, Datum key1, Datum key2)
Definition syscache.c:231
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
static ItemArray items
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition typcache.c:389
#define TYPECACHE_LT_OPR
Definition typcache.h:139
static Size VARSIZE_ANY(const void *PTR)
Definition varatt.h:460
static Size VARSIZE_ANY_EXHDR(const void *PTR)
Definition varatt.h:472
static char * VARDATA(const void *PTR)
Definition varatt.h:305
static char * VARDATA_ANY(const void *PTR)
Definition varatt.h:486
static void SET_VARSIZE(void *PTR, Size len)
Definition varatt.h:432
const char * type

◆ SizeOfHeader

#define SizeOfHeader   (3 * sizeof(uint32))

Definition at line 42 of file mvdistinct.c.

◆ SizeOfItem

#define SizeOfItem (   natts)     (sizeof(double) + sizeof(int) + (natts) * sizeof(AttrNumber))

Definition at line 45 of file mvdistinct.c.

Typedef Documentation

◆ CombinationGenerator

Function Documentation

◆ estimate_ndistinct()

static double estimate_ndistinct ( double  totalrows,
int  numrows,
int  d,
int  f1 
)
static

Definition at line 510 of file mvdistinct.c.

511{
512 double numer,
513 denom,
514 ndistinct;
515
516 numer = (double) numrows * (double) d;
517
518 denom = (double) (numrows - f1) +
519 (double) f1 * (double) numrows / totalrows;
520
521 ndistinct = numer / denom;
522
523 /* Clamp to sane range in case of roundoff error */
524 if (ndistinct < (double) d)
525 ndistinct = (double) d;
526
527 if (ndistinct > totalrows)
528 ndistinct = totalrows;
529
530 return floor(ndistinct + 0.5);
531}

References f1, and fb().

Referenced by ndistinct_for_combination().

◆ generate_combinations()

static void generate_combinations ( CombinationGenerator state)
static

Definition at line 681 of file mvdistinct.c.

682{
683 int *current = palloc0_array(int, state->k);
684
685 generate_combinations_recurse(state, 0, 0, current);
686
687 pfree(current);
688}

References generate_combinations_recurse(), palloc0_array, and pfree().

Referenced by generator_init().

◆ generate_combinations_recurse()

static void generate_combinations_recurse ( CombinationGenerator state,
int  index,
int  start,
int current 
)
static

Definition at line 646 of file mvdistinct.c.

648{
649 /* If we haven't filled all the elements, simply recurse. */
650 if (index < state->k)
651 {
652 int i;
653
654 /*
655 * The values have to be in ascending order, so make sure we start
656 * with the value passed by parameter.
657 */
658
659 for (i = start; i < state->n; i++)
660 {
661 current[index] = i;
662 generate_combinations_recurse(state, (index + 1), (i + 1), current);
663 }
664
665 return;
666 }
667 else
668 {
669 /* we got a valid combination, add it to the array */
670 memcpy(&state->combinations[(state->k * state->current)],
671 current, state->k * sizeof(int));
672 state->current++;
673 }
674}

References fb(), generate_combinations_recurse(), i, memcpy(), and start.

Referenced by generate_combinations(), and generate_combinations_recurse().

◆ generator_free()

static void generator_free ( CombinationGenerator state)
static

Definition at line 631 of file mvdistinct.c.

632{
633 pfree(state->combinations);
634 pfree(state);
635}

References pfree().

Referenced by statext_ndistinct_build().

◆ generator_init()

static CombinationGenerator * generator_init ( int  n,
int  k 
)
static

Definition at line 578 of file mvdistinct.c.

579{
581
582 Assert((n >= k) && (k > 0));
583
584 /* allocate the generator state as a single chunk of memory */
586
587 state->ncombinations = n_choose_k(n, k);
588
589 /* pre-allocate space for all combinations */
590 state->combinations = palloc_array(int, k * state->ncombinations);
591
592 state->current = 0;
593 state->k = k;
594 state->n = n;
595
596 /* now actually pre-generate all the combinations of K elements */
598
599 /* make sure we got the expected number of combinations */
600 Assert(state->current == state->ncombinations);
601
602 /* reset the number, so we start with the first one */
603 state->current = 0;
604
605 return state;
606}

References Assert, generate_combinations(), n_choose_k(), palloc_array, and palloc_object.

Referenced by statext_ndistinct_build().

◆ generator_next()

static int * generator_next ( CombinationGenerator state)
static

Definition at line 616 of file mvdistinct.c.

617{
618 if (state->current == state->ncombinations)
619 return NULL;
620
621 return &state->combinations[state->k * state->current++];
622}

References fb().

Referenced by statext_ndistinct_build().

◆ n_choose_k()

static int n_choose_k ( int  n,
int  k 
)
static

Definition at line 539 of file mvdistinct.c.

540{
541 int d,
542 r;
543
544 Assert((k > 0) && (n >= k));
545
546 /* use symmetry of the binomial coefficients */
547 k = Min(k, n - k);
548
549 r = 1;
550 for (d = 1; d <= k; ++d)
551 {
552 r *= n--;
553 r /= d;
554 }
555
556 return r;
557}

References Assert, and Min.

Referenced by generator_init().

◆ ndistinct_for_combination()

static double ndistinct_for_combination ( double  totalrows,
StatsBuildData data,
int  k,
int combination 
)
static

Definition at line 414 of file mvdistinct.c.

416{
417 int i,
418 j;
419 int f1,
420 cnt,
421 d;
422 bool *isnull;
423 Datum *values;
426 int numrows = data->numrows;
427
428 mss = multi_sort_init(k);
429
430 /*
431 * In order to determine the number of distinct elements, create separate
432 * values[]/isnull[] arrays with all the data we have, then sort them
433 * using the specified column combination as dimensions. We could try to
434 * sort in place, but it'd probably be more complex and bug-prone.
435 */
436 items = palloc_array(SortItem, numrows);
437 values = palloc0_array(Datum, numrows * k);
438 isnull = palloc0_array(bool, numrows * k);
439
440 for (i = 0; i < numrows; i++)
441 {
442 items[i].values = &values[i * k];
443 items[i].isnull = &isnull[i * k];
444 }
445
446 /*
447 * For each dimension, set up sort-support and fill in the values from the
448 * sample data.
449 *
450 * We use the column data types' default sort operators and collations;
451 * perhaps at some point it'd be worth using column-specific collations?
452 */
453 for (i = 0; i < k; i++)
454 {
455 Oid typid;
459
460 typid = colstat->attrtypid;
461 collid = colstat->attrcollid;
462
464 if (type->lt_opr == InvalidOid) /* shouldn't happen */
465 elog(ERROR, "cache lookup failed for ordering operator for type %u",
466 typid);
467
468 /* prepare the sort function for this dimension */
470
471 /* accumulate all the data for this dimension into the arrays */
472 for (j = 0; j < numrows; j++)
473 {
474 items[j].values[i] = data->values[combination[i]][j];
475 items[j].isnull[i] = data->nulls[combination[i]][j];
476 }
477 }
478
479 /* We can sort the array now ... */
480 qsort_interruptible(items, numrows, sizeof(SortItem),
482
483 /* ... and count the number of distinct combinations */
484
485 f1 = 0;
486 cnt = 1;
487 d = 1;
488 for (i = 1; i < numrows; i++)
489 {
490 if (multi_sort_compare(&items[i], &items[i - 1], mss) != 0)
491 {
492 if (cnt == 1)
493 f1 += 1;
494
495 d++;
496 cnt = 0;
497 }
498
499 cnt += 1;
500 }
501
502 if (cnt == 1)
503 f1 += 1;
504
505 return estimate_ndistinct(totalrows, numrows, d, f1);
506}

References VacAttrStats::attrtypid, collid, data, elog, ERROR, estimate_ndistinct(), f1, fb(), i, InvalidOid, items, j, lookup_type_cache(), multi_sort_add_dimension(), multi_sort_compare(), multi_sort_init(), palloc0_array, palloc_array, qsort_interruptible(), type, TYPECACHE_LT_OPR, and values.

Referenced by statext_ndistinct_build().

◆ num_combinations()

static int num_combinations ( int  n)
static

Definition at line 564 of file mvdistinct.c.

565{
566 return (1 << n) - (n + 1);
567}

Referenced by statext_ndistinct_build().

◆ statext_ndistinct_build()

MVNDistinct * statext_ndistinct_build ( double  totalrows,
StatsBuildData data 
)

Definition at line 85 of file mvdistinct.c.

86{
88 int k;
90 int numattrs = data->nattnums;
92
94 numcombs * sizeof(MVNDistinctItem));
97 result->nitems = numcombs;
98
99 itemcnt = 0;
100 for (k = 2; k <= numattrs; k++)
101 {
102 int *combination;
104
105 /* generate combinations of K out of N elements */
107
109 {
110 MVNDistinctItem *item = &result->items[itemcnt];
111 int j;
112
114 item->nattributes = k;
115
116 /* translate the indexes to attnums */
117 for (j = 0; j < k; j++)
118 {
119 item->attributes[j] = data->attnums[combination[j]];
120
122 }
123
124 item->ndistinct =
126
127 itemcnt++;
129 }
130
132 }
133
134 /* must consume exactly the whole output array */
135 Assert(itemcnt == result->nitems);
136
137 return result;
138}

References Assert, AttributeNumberIsValid, MVNDistinctItem::attributes, data, fb(), generator_free(), generator_init(), generator_next(), items, j, MVNDistinctItem::nattributes, MVNDistinctItem::ndistinct, ndistinct_for_combination(), nitems, num_combinations(), palloc(), palloc_array, result, STATS_NDISTINCT_MAGIC, and STATS_NDISTINCT_TYPE_BASIC.

Referenced by BuildRelationExtStatistics().

◆ statext_ndistinct_deserialize()

MVNDistinct * statext_ndistinct_deserialize ( bytea data)

Definition at line 246 of file mvdistinct.c.

247{
250 MVNDistinct *ndistinct;
251 char *tmp;
252
253 if (data == NULL)
254 return NULL;
255
256 /* we expect at least the basic fields of MVNDistinct struct */
258 elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
260
261 /* initialize pointer to the data part (skip the varlena header) */
262 tmp = VARDATA_ANY(data);
263
264 /* read the header fields and perform basic sanity checks */
265 memcpy(&ndist.magic, tmp, sizeof(uint32));
266 tmp += sizeof(uint32);
267 memcpy(&ndist.type, tmp, sizeof(uint32));
268 tmp += sizeof(uint32);
269 memcpy(&ndist.nitems, tmp, sizeof(uint32));
270 tmp += sizeof(uint32);
271
272 if (ndist.magic != STATS_NDISTINCT_MAGIC)
273 elog(ERROR, "invalid ndistinct magic %08x (expected %08x)",
276 elog(ERROR, "invalid ndistinct type %d (expected %d)",
278 if (ndist.nitems == 0)
279 elog(ERROR, "invalid zero-length item array in MVNDistinct");
280
281 /* what minimum bytea size do we expect for those parameters */
284 elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
286
287 /*
288 * Allocate space for the ndistinct items (no space for each item's
289 * attnos: those live in bitmapsets allocated separately)
290 */
291 ndistinct = palloc0(MAXALIGN(offsetof(MVNDistinct, items)) +
292 (ndist.nitems * sizeof(MVNDistinctItem)));
293 ndistinct->magic = ndist.magic;
294 ndistinct->type = ndist.type;
295 ndistinct->nitems = ndist.nitems;
296
297 for (uint32 i = 0; i < ndistinct->nitems; i++)
298 {
299 MVNDistinctItem *item = &ndistinct->items[i];
300
301 /* ndistinct value */
302 memcpy(&item->ndistinct, tmp, sizeof(double));
303 tmp += sizeof(double);
304
305 /* number of attributes */
306 memcpy(&item->nattributes, tmp, sizeof(int));
307 tmp += sizeof(int);
308 Assert((item->nattributes >= 2) && (item->nattributes <= STATS_MAX_DIMENSIONS));
309
310 item->attributes
311 = (AttrNumber *) palloc(item->nattributes * sizeof(AttrNumber));
312
313 memcpy(item->attributes, tmp, sizeof(AttrNumber) * item->nattributes);
314 tmp += sizeof(AttrNumber) * item->nattributes;
315
316 /* still within the bytea */
317 Assert(tmp <= ((char *) data + VARSIZE_ANY(data)));
318 }
319
320 /* we should have consumed the whole bytea exactly */
321 Assert(tmp == ((char *) data + VARSIZE_ANY(data)));
322
323 return ndistinct;
324}

References Assert, MVNDistinctItem::attributes, data, elog, ERROR, fb(), i, MVNDistinct::items, items, MVNDistinct::magic, MAXALIGN, memcpy(), MinSizeOfItems, MVNDistinctItem::nattributes, MVNDistinctItem::ndistinct, MVNDistinct::nitems, palloc(), palloc0(), SizeOfHeader, STATS_MAX_DIMENSIONS, STATS_NDISTINCT_MAGIC, STATS_NDISTINCT_TYPE_BASIC, MVNDistinct::type, VARDATA_ANY(), VARSIZE_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by extended_statistics_update(), pg_ndistinct_out(), and statext_ndistinct_load().

◆ statext_ndistinct_free()

void statext_ndistinct_free ( MVNDistinct ndistinct)

Definition at line 330 of file mvdistinct.c.

331{
332 for (uint32 i = 0; i < ndistinct->nitems; i++)
333 pfree(ndistinct->items[i].attributes);
334 pfree(ndistinct);
335}

References MVNDistinctItem::attributes, i, MVNDistinct::items, MVNDistinct::nitems, and pfree().

Referenced by extended_statistics_update().

◆ statext_ndistinct_load()

MVNDistinct * statext_ndistinct_load ( Oid  mvoid,
bool  inh 
)

Definition at line 145 of file mvdistinct.c.

146{
148 bool isnull;
149 Datum ndist;
150 HeapTuple htup;
151
154 if (!HeapTupleIsValid(htup))
155 elog(ERROR, "cache lookup failed for statistics object %u", mvoid);
156
159 if (isnull)
160 elog(ERROR,
161 "requested statistics kind \"%c\" is not yet built for statistics object %u",
163
165
166 ReleaseSysCache(htup);
167
168 return result;
169}

References BoolGetDatum(), DatumGetByteaPP, elog, ERROR, fb(), HeapTupleIsValid, ObjectIdGetDatum(), ReleaseSysCache(), result, SearchSysCache2(), statext_ndistinct_deserialize(), and SysCacheGetAttr().

Referenced by estimate_multivariate_ndistinct().

◆ statext_ndistinct_serialize()

bytea * statext_ndistinct_serialize ( MVNDistinct ndistinct)

Definition at line 176 of file mvdistinct.c.

177{
178 bytea *output;
179 char *tmp;
180 Size len;
181
182 Assert(ndistinct->magic == STATS_NDISTINCT_MAGIC);
184
185 /*
186 * Base size is size of scalar fields in the struct, plus one base struct
187 * for each item, including number of items for each.
188 */
190
191 /* and also include space for the actual attribute numbers */
192 for (uint32 i = 0; i < ndistinct->nitems; i++)
193 {
194 int nmembers;
195
196 nmembers = ndistinct->items[i].nattributes;
197 Assert(nmembers >= 2);
198
199 len += SizeOfItem(nmembers);
200 }
201
202 output = (bytea *) palloc(len);
204
205 tmp = VARDATA(output);
206
207 /* Store the base struct values (magic, type, nitems) */
208 memcpy(tmp, &ndistinct->magic, sizeof(uint32));
209 tmp += sizeof(uint32);
210 memcpy(tmp, &ndistinct->type, sizeof(uint32));
211 tmp += sizeof(uint32);
212 memcpy(tmp, &ndistinct->nitems, sizeof(uint32));
213 tmp += sizeof(uint32);
214
215 /*
216 * store number of attributes and attribute numbers for each entry
217 */
218 for (uint32 i = 0; i < ndistinct->nitems; i++)
219 {
220 MVNDistinctItem item = ndistinct->items[i];
221 int nmembers = item.nattributes;
222
223 memcpy(tmp, &item.ndistinct, sizeof(double));
224 tmp += sizeof(double);
225 memcpy(tmp, &nmembers, sizeof(int));
226 tmp += sizeof(int);
227
228 memcpy(tmp, item.attributes, sizeof(AttrNumber) * nmembers);
229 tmp += nmembers * sizeof(AttrNumber);
230
231 /* protect against overflows */
232 Assert(tmp <= ((char *) output + len));
233 }
234
235 /* check we used exactly the expected space */
236 Assert(tmp == ((char *) output + len));
237
238 return output;
239}

References Assert, MVNDistinctItem::attributes, fb(), i, MVNDistinct::items, len, MVNDistinct::magic, memcpy(), MVNDistinctItem::nattributes, MVNDistinctItem::ndistinct, MVNDistinct::nitems, output, palloc(), SET_VARSIZE(), SizeOfHeader, SizeOfItem, STATS_NDISTINCT_MAGIC, STATS_NDISTINCT_TYPE_BASIC, MVNDistinct::type, VARDATA(), and VARHDRSZ.

Referenced by build_mvndistinct(), and statext_store().

◆ statext_ndistinct_validate()

bool statext_ndistinct_validate ( const MVNDistinct ndistinct,
const int2vector stxkeys,
int  numexprs,
int  elevel 
)

Definition at line 350 of file mvdistinct.c.

353{
355
356 /* Scan through each MVNDistinct entry */
357 for (uint32 i = 0; i < ndistinct->nitems; i++)
358 {
359 MVNDistinctItem item = ndistinct->items[i];
360
361 /*
362 * Cross-check each attribute in a MVNDistinct entry with the extended
363 * stats object definition.
364 */
365 for (int j = 0; j < item.nattributes; j++)
366 {
368 bool ok = false;
369
370 if (attnum > 0)
371 {
372 /* attribute number in stxkeys */
373 for (int k = 0; k < stxkeys->dim1; k++)
374 {
375 if (attnum == stxkeys->values[k])
376 {
377 ok = true;
378 break;
379 }
380 }
381 }
382 else if ((attnum < 0) && (attnum >= attnum_expr_lowbound))
383 {
384 /* attribute number for an expression */
385 ok = true;
386 }
387
388 if (!ok)
389 {
390 ereport(elevel,
392 errmsg("could not validate \"%s\" object: invalid attribute number %d found",
393 "pg_ndistinct", attnum)));
394 return false;
395 }
396 }
397 }
398
399 return true;
400}

References attnum, MVNDistinctItem::attributes, ereport, errcode(), errmsg, fb(), i, MVNDistinct::items, j, MVNDistinctItem::nattributes, and MVNDistinct::nitems.

Referenced by extended_statistics_update().