LCOV - differential code coverage report
Current view: top level - src/backend/statistics - mvdistinct.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 94.9 % 215 204 11 6 198 6
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 15 15 5 10
Baseline: lcov-20260827-baseline Branches: 62.7 % 126 79 47 10 69
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 33 33 5 28
(360..) days: 93.9 % 181 170 11 170
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 100.0 % 13 13 3 10
Branch coverage date bins:
(30,360] days: 88.5 % 26 23 3 10 13
(360..) days: 56.0 % 100 56 44 56

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * mvdistinct.c
                                  4                 :                :  *    POSTGRES multivariate ndistinct coefficients
                                  5                 :                :  *
                                  6                 :                :  * Estimating number of groups in a combination of columns (e.g. for GROUP BY)
                                  7                 :                :  * is tricky, and the estimation error is often significant.
                                  8                 :                : 
                                  9                 :                :  * The multivariate ndistinct coefficients address this by storing ndistinct
                                 10                 :                :  * estimates for combinations of the user-specified columns.  So for example
                                 11                 :                :  * given a statistics object on three columns (a,b,c), this module estimates
                                 12                 :                :  * and stores n-distinct for (a,b), (a,c), (b,c) and (a,b,c).  The per-column
                                 13                 :                :  * estimates are already available in pg_statistic.
                                 14                 :                :  *
                                 15                 :                :  *
                                 16                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                 17                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 18                 :                :  *
                                 19                 :                :  * IDENTIFICATION
                                 20                 :                :  *    src/backend/statistics/mvdistinct.c
                                 21                 :                :  *
                                 22                 :                :  *-------------------------------------------------------------------------
                                 23                 :                :  */
                                 24                 :                : #include "postgres.h"
                                 25                 :                : 
                                 26                 :                : #include <math.h>
                                 27                 :                : 
                                 28                 :                : #include "catalog/pg_statistic_ext.h"
                                 29                 :                : #include "catalog/pg_statistic_ext_data.h"
                                 30                 :                : #include "statistics/extended_stats_internal.h"
                                 31                 :                : #include "utils/syscache.h"
                                 32                 :                : #include "utils/typcache.h"
                                 33                 :                : #include "varatt.h"
                                 34                 :                : 
                                 35                 :                : static double ndistinct_for_combination(double totalrows, StatsBuildData *data,
                                 36                 :                :                                         int k, int *combination);
                                 37                 :                : static double estimate_ndistinct(double totalrows, int numrows, int d, int f1);
                                 38                 :                : static int  n_choose_k(int n, int k);
                                 39                 :                : static int  num_combinations(int n);
                                 40                 :                : 
                                 41                 :                : /* size of the struct header fields (magic, type, nitems) */
                                 42                 :                : #define SizeOfHeader        (3 * sizeof(uint32))
                                 43                 :                : 
                                 44                 :                : /* size of a serialized ndistinct item (coefficient, natts, atts) */
                                 45                 :                : #define SizeOfItem(natts) \
                                 46                 :                :     (sizeof(double) + sizeof(int) + (natts) * sizeof(AttrNumber))
                                 47                 :                : 
                                 48                 :                : /* minimal size of a ndistinct item (with two attributes) */
                                 49                 :                : #define MinSizeOfItem   SizeOfItem(2)
                                 50                 :                : 
                                 51                 :                : /* minimal size of mvndistinct, when all items are minimal */
                                 52                 :                : #define MinSizeOfItems(nitems)  \
                                 53                 :                :     (SizeOfHeader + (nitems) * MinSizeOfItem)
                                 54                 :                : 
                                 55                 :                : /* Combination generator API */
                                 56                 :                : 
                                 57                 :                : /* internal state for generator of k-combinations of n elements */
                                 58                 :                : typedef struct CombinationGenerator
                                 59                 :                : {
                                 60                 :                :     int         k;              /* size of the combination */
                                 61                 :                :     int         n;              /* total number of elements */
                                 62                 :                :     int         current;        /* index of the next combination to return */
                                 63                 :                :     int         ncombinations;  /* number of combinations (size of array) */
                                 64                 :                :     int        *combinations;   /* array of pre-built combinations */
                                 65                 :                : } CombinationGenerator;
                                 66                 :                : 
                                 67                 :                : static CombinationGenerator *generator_init(int n, int k);
                                 68                 :                : static void generator_free(CombinationGenerator *state);
                                 69                 :                : static int *generator_next(CombinationGenerator *state);
                                 70                 :                : static void generate_combinations(CombinationGenerator *state);
                                 71                 :                : 
                                 72                 :                : 
                                 73                 :                : /*
                                 74                 :                :  * statext_ndistinct_build
                                 75                 :                :  *      Compute ndistinct coefficient for the combination of attributes.
                                 76                 :                :  *
                                 77                 :                :  * This computes the ndistinct estimate using the same estimator used
                                 78                 :                :  * in analyze.c and then computes the coefficient.
                                 79                 :                :  *
                                 80                 :                :  * To handle expressions easily, we treat them as system attributes with
                                 81                 :                :  * negative attnums, and offset everything by number of expressions to
                                 82                 :                :  * allow using Bitmapsets.
                                 83                 :                :  */
                                 84                 :                : MVNDistinct *
 1980 tomas.vondra@postgre       85                 :CBC         187 : statext_ndistinct_build(double totalrows, StatsBuildData *data)
                                 86                 :                : {
                                 87                 :                :     MVNDistinct *result;
                                 88                 :                :     int         k;
                                 89                 :                :     uint32      itemcnt;
                                 90                 :            187 :     int         numattrs = data->nattnums;
 3443 alvherre@alvh.no-ip.       91                 :            187 :     int         numcombs = num_combinations(numattrs);
                                 92                 :                : 
                                 93                 :            187 :     result = palloc(offsetof(MVNDistinct, items) +
                                 94                 :            187 :                     numcombs * sizeof(MVNDistinctItem));
                                 95                 :            187 :     result->magic = STATS_NDISTINCT_MAGIC;
                                 96                 :            187 :     result->type = STATS_NDISTINCT_TYPE_BASIC;
                                 97                 :            187 :     result->nitems = numcombs;
                                 98                 :                : 
                                 99                 :            187 :     itemcnt = 0;
                                100         [ +  + ]:            458 :     for (k = 2; k <= numattrs; k++)
                                101                 :                :     {
                                102                 :                :         int        *combination;
                                103                 :                :         CombinationGenerator *generator;
                                104                 :                : 
                                105                 :                :         /* generate combinations of K out of N elements */
                                106                 :            271 :         generator = generator_init(numattrs, k);
                                107                 :                : 
                                108         [ +  + ]:            806 :         while ((combination = generator_next(generator)))
                                109                 :                :         {
                                110                 :            535 :             MVNDistinctItem *item = &result->items[itemcnt];
                                111                 :                :             int         j;
                                112                 :                : 
  259 michael@paquier.xyz       113                 :            535 :             item->attributes = palloc_array(AttrNumber, k);
 1980 tomas.vondra@postgre      114                 :            535 :             item->nattributes = k;
                                115                 :                : 
                                116                 :                :             /* translate the indexes to attnums */
 3443 alvherre@alvh.no-ip.      117         [ +  + ]:           1785 :             for (j = 0; j < k; j++)
                                118                 :                :             {
 1980 tomas.vondra@postgre      119                 :           1250 :                 item->attributes[j] = data->attnums[combination[j]];
                                120                 :                : 
                                121         [ -  + ]:           1250 :                 Assert(AttributeNumberIsValid(item->attributes[j]));
                                122                 :                :             }
                                123                 :                : 
 3443 alvherre@alvh.no-ip.      124                 :            535 :             item->ndistinct =
 1980 tomas.vondra@postgre      125                 :            535 :                 ndistinct_for_combination(totalrows, data, k, combination);
                                126                 :                : 
 3443 alvherre@alvh.no-ip.      127                 :            535 :             itemcnt++;
                                128         [ -  + ]:            535 :             Assert(itemcnt <= result->nitems);
                                129                 :                :         }
                                130                 :                : 
                                131                 :            271 :         generator_free(generator);
                                132                 :                :     }
                                133                 :                : 
                                134                 :                :     /* must consume exactly the whole output array */
                                135         [ -  + ]:            187 :     Assert(itemcnt == result->nitems);
                                136                 :                : 
                                137                 :            187 :     return result;
                                138                 :                : }
                                139                 :                : 
                                140                 :                : /*
                                141                 :                :  * statext_ndistinct_load
                                142                 :                :  *      Load the ndistinct value for the indicated pg_statistic_ext tuple
                                143                 :                :  */
                                144                 :                : MVNDistinct *
 1684 tomas.vondra@postgre      145                 :            355 : statext_ndistinct_load(Oid mvoid, bool inh)
                                146                 :                : {
                                147                 :                :     MVNDistinct *result;
                                148                 :                :     bool        isnull;
                                149                 :                :     Datum       ndist;
                                150                 :                :     HeapTuple   htup;
                                151                 :                : 
                                152                 :            355 :     htup = SearchSysCache2(STATEXTDATASTXOID,
                                153                 :                :                            ObjectIdGetDatum(mvoid), BoolGetDatum(inh));
 3039 tgl@sss.pgh.pa.us         154         [ -  + ]:            355 :     if (!HeapTupleIsValid(htup))
 3392 tgl@sss.pgh.pa.us         155         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for statistics object %u", mvoid);
                                156                 :                : 
 2632 tomas.vondra@postgre      157                 :CBC         355 :     ndist = SysCacheGetAttr(STATEXTDATASTXOID, htup,
                                158                 :                :                             Anum_pg_statistic_ext_data_stxdndistinct, &isnull);
 3443 alvherre@alvh.no-ip.      159         [ -  + ]:            355 :     if (isnull)
 3443 alvherre@alvh.no-ip.      160         [ #  # ]:UBC           0 :         elog(ERROR,
                                161                 :                :              "requested statistics kind \"%c\" is not yet built for statistics object %u",
                                162                 :                :              STATS_EXT_NDISTINCT, mvoid);
                                163                 :                : 
 3039 tgl@sss.pgh.pa.us         164                 :CBC         355 :     result = statext_ndistinct_deserialize(DatumGetByteaPP(ndist));
                                165                 :                : 
 3443 alvherre@alvh.no-ip.      166                 :            355 :     ReleaseSysCache(htup);
                                167                 :                : 
 3039 tgl@sss.pgh.pa.us         168                 :            355 :     return result;
                                169                 :                : }
                                170                 :                : 
                                171                 :                : /*
                                172                 :                :  * statext_ndistinct_serialize
                                173                 :                :  *      serialize ndistinct to the on-disk bytea format
                                174                 :                :  */
                                175                 :                : bytea *
 3443 alvherre@alvh.no-ip.      176                 :            227 : statext_ndistinct_serialize(MVNDistinct *ndistinct)
                                177                 :                : {
                                178                 :                :     bytea      *output;
                                179                 :                :     char       *tmp;
                                180                 :                :     Size        len;
                                181                 :                : 
                                182         [ -  + ]:            227 :     Assert(ndistinct->magic == STATS_NDISTINCT_MAGIC);
                                183         [ -  + ]:            227 :     Assert(ndistinct->type == STATS_NDISTINCT_TYPE_BASIC);
                                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                 :                :      */
 2685 tomas.vondra@postgre      189                 :            227 :     len = VARHDRSZ + SizeOfHeader;
                                190                 :                : 
                                191                 :                :     /* and also include space for the actual attribute numbers */
   47 peter@eisentraut.org      192         [ +  + ]:GNC         826 :     for (uint32 i = 0; i < ndistinct->nitems; i++)
                                193                 :                :     {
                                194                 :                :         int         nmembers;
                                195                 :                : 
 1980 tomas.vondra@postgre      196                 :CBC         599 :         nmembers = ndistinct->items[i].nattributes;
 3443 alvherre@alvh.no-ip.      197         [ -  + ]:            599 :         Assert(nmembers >= 2);
                                198                 :                : 
 2685 tomas.vondra@postgre      199                 :            599 :         len += SizeOfItem(nmembers);
                                200                 :                :     }
                                201                 :                : 
 3443 alvherre@alvh.no-ip.      202                 :            227 :     output = (bytea *) palloc(len);
                                203                 :            227 :     SET_VARSIZE(output, len);
                                204                 :                : 
                                205                 :            227 :     tmp = VARDATA(output);
                                206                 :                : 
                                207                 :                :     /* Store the base struct values (magic, type, nitems) */
 3440                           208                 :            227 :     memcpy(tmp, &ndistinct->magic, sizeof(uint32));
                                209                 :            227 :     tmp += sizeof(uint32);
                                210                 :            227 :     memcpy(tmp, &ndistinct->type, sizeof(uint32));
                                211                 :            227 :     tmp += sizeof(uint32);
                                212                 :            227 :     memcpy(tmp, &ndistinct->nitems, sizeof(uint32));
                                213                 :            227 :     tmp += sizeof(uint32);
                                214                 :                : 
                                215                 :                :     /*
                                216                 :                :      * store number of attributes and attribute numbers for each entry
                                217                 :                :      */
   47 peter@eisentraut.org      218         [ +  + ]:GNC         826 :     for (uint32 i = 0; i < ndistinct->nitems; i++)
                                219                 :                :     {
 3443 alvherre@alvh.no-ip.      220                 :CBC         599 :         MVNDistinctItem item = ndistinct->items[i];
 1980 tomas.vondra@postgre      221                 :            599 :         int         nmembers = item.nattributes;
                                222                 :                : 
 3443 alvherre@alvh.no-ip.      223                 :            599 :         memcpy(tmp, &item.ndistinct, sizeof(double));
                                224                 :            599 :         tmp += sizeof(double);
                                225                 :            599 :         memcpy(tmp, &nmembers, sizeof(int));
                                226                 :            599 :         tmp += sizeof(int);
                                227                 :                : 
 1980 tomas.vondra@postgre      228                 :            599 :         memcpy(tmp, item.attributes, sizeof(AttrNumber) * nmembers);
                                229                 :            599 :         tmp += nmembers * sizeof(AttrNumber);
                                230                 :                : 
                                231                 :                :         /* protect against overflows */
 3443 alvherre@alvh.no-ip.      232         [ -  + ]:            599 :         Assert(tmp <= ((char *) output + len));
                                233                 :                :     }
                                234                 :                : 
                                235                 :                :     /* check we used exactly the expected space */
 2685 tomas.vondra@postgre      236         [ -  + ]:            227 :     Assert(tmp == ((char *) output + len));
                                237                 :                : 
 3443 alvherre@alvh.no-ip.      238                 :            227 :     return output;
                                239                 :                : }
                                240                 :                : 
                                241                 :                : /*
                                242                 :                :  * statext_ndistinct_deserialize
                                243                 :                :  *      Read an on-disk bytea format MVNDistinct to in-memory format
                                244                 :                :  */
                                245                 :                : MVNDistinct *
                                246                 :            463 : statext_ndistinct_deserialize(bytea *data)
                                247                 :                : {
                                248                 :                :     Size        minimum_size;
                                249                 :                :     MVNDistinct ndist;
                                250                 :                :     MVNDistinct *ndistinct;
                                251                 :                :     char       *tmp;
                                252                 :                : 
                                253         [ -  + ]:            463 :     if (data == NULL)
 3443 alvherre@alvh.no-ip.      254                 :UBC           0 :         return NULL;
                                255                 :                : 
                                256                 :                :     /* we expect at least the basic fields of MVNDistinct struct */
 2685 tomas.vondra@postgre      257         [ -  + ]:CBC         463 :     if (VARSIZE_ANY_EXHDR(data) < SizeOfHeader)
 1280 peter@eisentraut.org      258         [ #  # ]:UBC           0 :         elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
                                259                 :                :              VARSIZE_ANY_EXHDR(data), SizeOfHeader);
                                260                 :                : 
                                261                 :                :     /* initialize pointer to the data part (skip the varlena header) */
 3443 alvherre@alvh.no-ip.      262                 :CBC         463 :     tmp = VARDATA_ANY(data);
                                263                 :                : 
                                264                 :                :     /* read the header fields and perform basic sanity checks */
 3440                           265                 :            463 :     memcpy(&ndist.magic, tmp, sizeof(uint32));
                                266                 :            463 :     tmp += sizeof(uint32);
                                267                 :            463 :     memcpy(&ndist.type, tmp, sizeof(uint32));
                                268                 :            463 :     tmp += sizeof(uint32);
                                269                 :            463 :     memcpy(&ndist.nitems, tmp, sizeof(uint32));
                                270                 :            463 :     tmp += sizeof(uint32);
                                271                 :                : 
                                272         [ -  + ]:            463 :     if (ndist.magic != STATS_NDISTINCT_MAGIC)
 2646 tomas.vondra@postgre      273         [ #  # ]:UBC           0 :         elog(ERROR, "invalid ndistinct magic %08x (expected %08x)",
                                274                 :                :              ndist.magic, STATS_NDISTINCT_MAGIC);
 3440 alvherre@alvh.no-ip.      275         [ -  + ]:CBC         463 :     if (ndist.type != STATS_NDISTINCT_TYPE_BASIC)
 2646 tomas.vondra@postgre      276         [ #  # ]:UBC           0 :         elog(ERROR, "invalid ndistinct type %d (expected %d)",
                                277                 :                :              ndist.type, STATS_NDISTINCT_TYPE_BASIC);
 3440 alvherre@alvh.no-ip.      278         [ -  + ]:CBC         463 :     if (ndist.nitems == 0)
 2646 tomas.vondra@postgre      279         [ #  # ]:UBC           0 :         elog(ERROR, "invalid zero-length item array in MVNDistinct");
                                280                 :                : 
                                281                 :                :     /* what minimum bytea size do we expect for those parameters */
 2685 tomas.vondra@postgre      282                 :CBC         463 :     minimum_size = MinSizeOfItems(ndist.nitems);
 3440 alvherre@alvh.no-ip.      283         [ -  + ]:            463 :     if (VARSIZE_ANY_EXHDR(data) < minimum_size)
 1280 peter@eisentraut.org      284         [ #  # ]:UBC           0 :         elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
                                285                 :                :              VARSIZE_ANY_EXHDR(data), minimum_size);
                                286                 :                : 
                                287                 :                :     /*
                                288                 :                :      * Allocate space for the ndistinct items (no space for each item's
                                289                 :                :      * attnos: those live in bitmapsets allocated separately)
                                290                 :                :      */
 2685 tomas.vondra@postgre      291                 :CBC         463 :     ndistinct = palloc0(MAXALIGN(offsetof(MVNDistinct, items)) +
 3440 alvherre@alvh.no-ip.      292                 :            463 :                         (ndist.nitems * sizeof(MVNDistinctItem)));
                                293                 :            463 :     ndistinct->magic = ndist.magic;
                                294                 :            463 :     ndistinct->type = ndist.type;
                                295                 :            463 :     ndistinct->nitems = ndist.nitems;
                                296                 :                : 
   47 peter@eisentraut.org      297         [ +  + ]:GNC        2262 :     for (uint32 i = 0; i < ndistinct->nitems; i++)
                                298                 :                :     {
 3443 alvherre@alvh.no-ip.      299                 :CBC        1799 :         MVNDistinctItem *item = &ndistinct->items[i];
                                300                 :                : 
                                301                 :                :         /* ndistinct value */
                                302                 :           1799 :         memcpy(&item->ndistinct, tmp, sizeof(double));
                                303                 :           1799 :         tmp += sizeof(double);
                                304                 :                : 
                                305                 :                :         /* number of attributes */
 1980 tomas.vondra@postgre      306                 :           1799 :         memcpy(&item->nattributes, tmp, sizeof(int));
 3443 alvherre@alvh.no-ip.      307                 :           1799 :         tmp += sizeof(int);
 1980 tomas.vondra@postgre      308   [ +  -  -  + ]:           1799 :         Assert((item->nattributes >= 2) && (item->nattributes <= STATS_MAX_DIMENSIONS));
                                309                 :                : 
   10 michael@paquier.xyz       310                 :GNC        1799 :         item->attributes = palloc_array(AttrNumber, item->nattributes);
                                311                 :                : 
 1980 tomas.vondra@postgre      312                 :CBC        1799 :         memcpy(item->attributes, tmp, sizeof(AttrNumber) * item->nattributes);
                                313                 :           1799 :         tmp += sizeof(AttrNumber) * item->nattributes;
                                314                 :                : 
                                315                 :                :         /* still within the bytea */
 3443 alvherre@alvh.no-ip.      316         [ -  + ]:           1799 :         Assert(tmp <= ((char *) data + VARSIZE_ANY(data)));
                                317                 :                :     }
                                318                 :                : 
                                319                 :                :     /* we should have consumed the whole bytea exactly */
                                320         [ -  + ]:            463 :     Assert(tmp == ((char *) data + VARSIZE_ANY(data)));
                                321                 :                : 
                                322                 :            463 :     return ndistinct;
                                323                 :                : }
                                324                 :                : 
                                325                 :                : /*
                                326                 :                :  * Free allocations of a MVNDistinct.
                                327                 :                :  */
                                328                 :                : void
  224 michael@paquier.xyz       329                 :             32 : statext_ndistinct_free(MVNDistinct *ndistinct)
                                330                 :                : {
   47 peter@eisentraut.org      331         [ +  + ]:GNC         128 :     for (uint32 i = 0; i < ndistinct->nitems; i++)
  224 michael@paquier.xyz       332                 :CBC          96 :         pfree(ndistinct->items[i].attributes);
                                333                 :             32 :     pfree(ndistinct);
                                334                 :             32 : }
                                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                 :                :  */
                                348                 :                : bool
                                349                 :             32 : statext_ndistinct_validate(const MVNDistinct *ndistinct,
                                350                 :                :                            const int2vector *stxkeys,
                                351                 :                :                            int numexprs, int elevel)
                                352                 :                : {
                                353                 :             32 :     int         attnum_expr_lowbound = 0 - numexprs;
                                354                 :                : 
                                355                 :                :     /* Scan through each MVNDistinct entry */
   47 peter@eisentraut.org      356         [ +  + ]:GNC         120 :     for (uint32 i = 0; i < ndistinct->nitems; i++)
                                357                 :                :     {
  224 michael@paquier.xyz       358                 :CBC          96 :         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         [ +  + ]:            304 :         for (int j = 0; j < item.nattributes; j++)
                                365                 :                :         {
                                366                 :            216 :             AttrNumber  attnum = item.attributes[j];
                                367                 :            216 :             bool        ok = false;
                                368                 :                : 
                                369         [ +  + ]:            216 :             if (attnum > 0)
                                370                 :                :             {
                                371                 :                :                 /* attribute number in stxkeys */
                                372         [ +  + ]:            196 :                 for (int k = 0; k < stxkeys->dim1; k++)
                                373                 :                :                 {
                                374         [ +  + ]:            188 :                     if (attnum == stxkeys->values[k])
                                375                 :                :                     {
                                376                 :            120 :                         ok = true;
                                377                 :            120 :                         break;
                                378                 :                :                     }
                                379                 :                :                 }
                                380                 :                :             }
                                381   [ +  -  +  - ]:             88 :             else if ((attnum < 0) && (attnum >= attnum_expr_lowbound))
                                382                 :                :             {
                                383                 :                :                 /* attribute number for an expression */
                                384                 :             88 :                 ok = true;
                                385                 :                :             }
                                386                 :                : 
                                387         [ +  + ]:            216 :             if (!ok)
                                388                 :                :             {
                                389         [ +  - ]:              8 :                 ereport(elevel,
                                390                 :                :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                                391                 :                :                          errmsg("could not validate \"%s\" object: invalid attribute number %d found",
                                392                 :                :                                 "pg_ndistinct", attnum)));
                                393                 :              8 :                 return false;
                                394                 :                :             }
                                395                 :                :         }
                                396                 :                :     }
                                397                 :                : 
                                398                 :             24 :     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                 :                :  */
                                412                 :                : static double
 1980 tomas.vondra@postgre      413                 :            535 : ndistinct_for_combination(double totalrows, StatsBuildData *data,
                                414                 :                :                           int k, int *combination)
                                415                 :                : {
                                416                 :                :     int         i,
                                417                 :                :                 j;
                                418                 :                :     int         f1,
                                419                 :                :                 cnt,
                                420                 :                :                 d;
                                421                 :                :     bool       *isnull;
                                422                 :                :     Datum      *values;
                                423                 :                :     SortItem   *items;
                                424                 :                :     MultiSortSupport mss;
                                425                 :            535 :     int         numrows = data->numrows;
                                426                 :                : 
 3443 alvherre@alvh.no-ip.      427                 :            535 :     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                 :                :      */
  259 michael@paquier.xyz       435                 :            535 :     items = palloc_array(SortItem, numrows);
                                436                 :            535 :     values = palloc0_array(Datum, numrows * k);
                                437                 :            535 :     isnull = palloc0_array(bool, numrows * k);
                                438                 :                : 
 3443 alvherre@alvh.no-ip.      439         [ +  + ]:         643862 :     for (i = 0; i < numrows; i++)
                                440                 :                :     {
                                441                 :         643327 :         items[i].values = &values[i * k];
                                442                 :         643327 :         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         [ +  + ]:           1785 :     for (i = 0; i < k; i++)
                                453                 :                :     {
                                454                 :                :         Oid         typid;
                                455                 :                :         TypeCacheEntry *type;
 1980 tomas.vondra@postgre      456                 :           1250 :         Oid         collid = InvalidOid;
                                457                 :           1250 :         VacAttrStats *colstat = data->stats[combination[i]];
                                458                 :                : 
                                459                 :           1250 :         typid = colstat->attrtypid;
                                460                 :           1250 :         collid = colstat->attrcollid;
                                461                 :                : 
                                462                 :           1250 :         type = lookup_type_cache(typid, TYPECACHE_LT_OPR);
 3389 bruce@momjian.us          463         [ -  + ]:           1250 :         if (type->lt_opr == InvalidOid) /* shouldn't happen */
 3443 alvherre@alvh.no-ip.      464         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for ordering operator for type %u",
                                465                 :                :                  typid);
                                466                 :                : 
                                467                 :                :         /* prepare the sort function for this dimension */
 1980 tomas.vondra@postgre      468                 :CBC        1250 :         multi_sort_add_dimension(mss, i, type->lt_opr, collid);
                                469                 :                : 
                                470                 :                :         /* accumulate all the data for this dimension into the arrays */
 3443 alvherre@alvh.no-ip.      471         [ +  + ]:        1488104 :         for (j = 0; j < numrows; j++)
                                472                 :                :         {
 1980 tomas.vondra@postgre      473                 :        1486854 :             items[j].values[i] = data->values[combination[i]][j];
                                474                 :        1486854 :             items[j].isnull[i] = data->nulls[combination[i]][j];
                                475                 :                :         }
                                476                 :                :     }
                                477                 :                : 
                                478                 :                :     /* We can sort the array now ... */
 1297 peter@eisentraut.org      479                 :            535 :     qsort_interruptible(items, numrows, sizeof(SortItem),
                                480                 :                :                         multi_sort_compare, mss);
                                481                 :                : 
                                482                 :                :     /* ... and count the number of distinct combinations */
                                483                 :                : 
 3443 alvherre@alvh.no-ip.      484                 :            535 :     f1 = 0;
                                485                 :            535 :     cnt = 1;
                                486                 :            535 :     d = 1;
                                487         [ +  + ]:         643327 :     for (i = 1; i < numrows; i++)
                                488                 :                :     {
                                489         [ +  + ]:         642792 :         if (multi_sort_compare(&items[i], &items[i - 1], mss) != 0)
                                490                 :                :         {
                                491         [ +  + ]:         190509 :             if (cnt == 1)
                                492                 :          98182 :                 f1 += 1;
                                493                 :                : 
                                494                 :         190509 :             d++;
                                495                 :         190509 :             cnt = 0;
                                496                 :                :         }
                                497                 :                : 
                                498                 :         642792 :         cnt += 1;
                                499                 :                :     }
                                500                 :                : 
                                501         [ +  + ]:            535 :     if (cnt == 1)
                                502                 :            227 :         f1 += 1;
                                503                 :                : 
                                504                 :            535 :     return estimate_ndistinct(totalrows, numrows, d, f1);
                                505                 :                : }
                                506                 :                : 
                                507                 :                : /* The Duj1 estimator (already used in analyze.c). */
                                508                 :                : static double
                                509                 :            535 : estimate_ndistinct(double totalrows, int numrows, int d, int f1)
                                510                 :                : {
                                511                 :                :     double      numer,
                                512                 :                :                 denom,
                                513                 :                :                 ndistinct;
                                514                 :                : 
 3354 tgl@sss.pgh.pa.us         515                 :            535 :     numer = (double) numrows * (double) d;
                                516                 :                : 
 3443 alvherre@alvh.no-ip.      517                 :            535 :     denom = (double) (numrows - f1) +
 3354 tgl@sss.pgh.pa.us         518                 :            535 :         (double) f1 * (double) numrows / totalrows;
                                519                 :                : 
 3443 alvherre@alvh.no-ip.      520                 :            535 :     ndistinct = numer / denom;
                                521                 :                : 
                                522                 :                :     /* Clamp to sane range in case of roundoff error */
                                523         [ -  + ]:            535 :     if (ndistinct < (double) d)
 3443 alvherre@alvh.no-ip.      524                 :UBC           0 :         ndistinct = (double) d;
                                525                 :                : 
 3443 alvherre@alvh.no-ip.      526         [ -  + ]:CBC         535 :     if (ndistinct > totalrows)
 3443 alvherre@alvh.no-ip.      527                 :UBC           0 :         ndistinct = totalrows;
                                528                 :                : 
 3443 alvherre@alvh.no-ip.      529                 :CBC         535 :     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                 :                :  */
                                537                 :                : static int
                                538                 :            271 : n_choose_k(int n, int k)
                                539                 :                : {
                                540                 :                :     int         d,
                                541                 :                :                 r;
                                542                 :                : 
                                543   [ +  -  -  + ]:            271 :     Assert((k > 0) && (n >= k));
                                544                 :                : 
                                545                 :                :     /* use symmetry of the binomial coefficients */
                                546                 :            271 :     k = Min(k, n - k);
                                547                 :                : 
                                548                 :            271 :     r = 1;
                                549         [ +  + ]:            379 :     for (d = 1; d <= k; ++d)
                                550                 :                :     {
                                551                 :            108 :         r *= n--;
                                552                 :            108 :         r /= d;
                                553                 :                :     }
                                554                 :                : 
                                555                 :            271 :     return r;
                                556                 :                : }
                                557                 :                : 
                                558                 :                : /*
                                559                 :                :  * num_combinations
                                560                 :                :  *      number of combinations, excluding single-value combinations
                                561                 :                :  */
                                562                 :                : static int
                                563                 :            187 : num_combinations(int n)
                                564                 :                : {
 2332 drowley@postgresql.o      565                 :            187 :     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                 :                :  */
                                576                 :                : static CombinationGenerator *
 3443 alvherre@alvh.no-ip.      577                 :            271 : generator_init(int n, int k)
                                578                 :                : {
                                579                 :                :     CombinationGenerator *state;
                                580                 :                : 
                                581   [ +  -  -  + ]:            271 :     Assert((n >= k) && (k > 0));
                                582                 :                : 
                                583                 :                :     /* allocate the generator state as a single chunk of memory */
  259 michael@paquier.xyz       584                 :            271 :     state = palloc_object(CombinationGenerator);
                                585                 :                : 
 3443 alvherre@alvh.no-ip.      586                 :            271 :     state->ncombinations = n_choose_k(n, k);
                                587                 :                : 
                                588                 :                :     /* pre-allocate space for all combinations */
  259 michael@paquier.xyz       589                 :            271 :     state->combinations = palloc_array(int, k * state->ncombinations);
                                590                 :                : 
 3443 alvherre@alvh.no-ip.      591                 :            271 :     state->current = 0;
                                592                 :            271 :     state->k = k;
                                593                 :            271 :     state->n = n;
                                594                 :                : 
                                595                 :                :     /* now actually pre-generate all the combinations of K elements */
                                596                 :            271 :     generate_combinations(state);
                                597                 :                : 
                                598                 :                :     /* make sure we got the expected number of combinations */
                                599         [ -  + ]:            271 :     Assert(state->current == state->ncombinations);
                                600                 :                : 
                                601                 :                :     /* reset the number, so we start with the first one */
                                602                 :            271 :     state->current = 0;
                                603                 :                : 
                                604                 :            271 :     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                 :                :  */
                                614                 :                : static int *
                                615                 :            806 : generator_next(CombinationGenerator *state)
                                616                 :                : {
                                617         [ +  + ]:            806 :     if (state->current == state->ncombinations)
                                618                 :            271 :         return NULL;
                                619                 :                : 
                                620                 :            535 :     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                 :                :  */
                                629                 :                : static void
                                630                 :            271 : generator_free(CombinationGenerator *state)
                                631                 :                : {
                                632                 :            271 :     pfree(state->combinations);
                                633                 :            271 :     pfree(state);
                                634                 :            271 : }
                                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                 :                :  */
                                644                 :                : static void
                                645                 :           2056 : generate_combinations_recurse(CombinationGenerator *state,
                                646                 :                :                               int index, int start, int *current)
                                647                 :                : {
                                648                 :                :     /* If we haven't filled all the elements, simply recurse. */
                                649         [ +  + ]:           2056 :     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         [ +  + ]:           3306 :         for (i = start; i < state->n; i++)
                                659                 :                :         {
                                660                 :           1785 :             current[index] = i;
                                661                 :           1785 :             generate_combinations_recurse(state, (index + 1), (i + 1), current);
                                662                 :                :         }
                                663                 :                : 
                                664                 :           1521 :         return;
                                665                 :                :     }
                                666                 :                :     else
                                667                 :                :     {
                                668                 :                :         /* we got a valid combination, add it to the array */
                                669                 :            535 :         memcpy(&state->combinations[(state->k * state->current)],
                                670                 :            535 :                current, state->k * sizeof(int));
                                671                 :            535 :         state->current++;
                                672                 :                :     }
                                673                 :                : }
                                674                 :                : 
                                675                 :                : /*
                                676                 :                :  * generate_combinations
                                677                 :                :  *      generate all k-combinations of N elements
                                678                 :                :  */
                                679                 :                : static void
                                680                 :            271 : generate_combinations(CombinationGenerator *state)
                                681                 :                : {
  259 michael@paquier.xyz       682                 :            271 :     int        *current = palloc0_array(int, state->k);
                                683                 :                : 
 3443 alvherre@alvh.no-ip.      684                 :            271 :     generate_combinations_recurse(state, 0, 0, current);
                                685                 :                : 
                                686                 :            271 :     pfree(current);
                                687                 :            271 : }
        

Generated by: LCOV version 2.0-1