LCOV - code coverage report
Current view: top level - src/backend/statistics - dependencies.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 89.5 % 496 444
Test Date: 2026-07-23 04:15:41 Functions: 100.0 % 18 18
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 77.2 % 346 267

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * dependencies.c
       4                 :             :  *    POSTGRES functional dependencies
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  * IDENTIFICATION
      10                 :             :  *    src/backend/statistics/dependencies.c
      11                 :             :  *
      12                 :             :  *-------------------------------------------------------------------------
      13                 :             :  */
      14                 :             : #include "postgres.h"
      15                 :             : 
      16                 :             : #include "access/htup_details.h"
      17                 :             : #include "catalog/pg_statistic_ext.h"
      18                 :             : #include "catalog/pg_statistic_ext_data.h"
      19                 :             : #include "nodes/nodeFuncs.h"
      20                 :             : #include "optimizer/clauses.h"
      21                 :             : #include "optimizer/optimizer.h"
      22                 :             : #include "parser/parsetree.h"
      23                 :             : #include "statistics/extended_stats_internal.h"
      24                 :             : #include "utils/fmgroids.h"
      25                 :             : #include "utils/lsyscache.h"
      26                 :             : #include "utils/memutils.h"
      27                 :             : #include "utils/selfuncs.h"
      28                 :             : #include "utils/syscache.h"
      29                 :             : #include "utils/typcache.h"
      30                 :             : 
      31                 :             : /* size of the struct header fields (magic, type, ndeps) */
      32                 :             : #define SizeOfHeader        (3 * sizeof(uint32))
      33                 :             : 
      34                 :             : /* size of a serialized dependency (degree, natts, atts) */
      35                 :             : #define SizeOfItem(natts) \
      36                 :             :     (sizeof(double) + sizeof(AttrNumber) * (1 + (natts)))
      37                 :             : 
      38                 :             : /* minimal size of a dependency (with two attributes) */
      39                 :             : #define MinSizeOfItem   SizeOfItem(2)
      40                 :             : 
      41                 :             : /* minimal size of dependencies, when all deps are minimal */
      42                 :             : #define MinSizeOfItems(ndeps) \
      43                 :             :     (SizeOfHeader + (ndeps) * MinSizeOfItem)
      44                 :             : 
      45                 :             : /*
      46                 :             :  * Internal state for DependencyGenerator of dependencies. Dependencies are similar to
      47                 :             :  * k-permutations of n elements, except that the order does not matter for the
      48                 :             :  * first (k-1) elements. That is, (a,b=>c) and (b,a=>c) are equivalent.
      49                 :             :  */
      50                 :             : typedef struct DependencyGeneratorData
      51                 :             : {
      52                 :             :     int         k;              /* size of the dependency */
      53                 :             :     int         n;              /* number of possible attributes */
      54                 :             :     int         current;        /* next dependency to return (index) */
      55                 :             :     AttrNumber  ndependencies;  /* number of dependencies generated */
      56                 :             :     AttrNumber *dependencies;   /* array of pre-generated dependencies  */
      57                 :             : } DependencyGeneratorData;
      58                 :             : 
      59                 :             : typedef DependencyGeneratorData *DependencyGenerator;
      60                 :             : 
      61                 :             : static void generate_dependencies_recurse(DependencyGenerator state,
      62                 :             :                                           int index, AttrNumber start, AttrNumber *current);
      63                 :             : static void generate_dependencies(DependencyGenerator state);
      64                 :             : static DependencyGenerator DependencyGenerator_init(int n, int k);
      65                 :             : static void DependencyGenerator_free(DependencyGenerator state);
      66                 :             : static AttrNumber *DependencyGenerator_next(DependencyGenerator state);
      67                 :             : static double dependency_degree(StatsBuildData *data, int k, AttrNumber *dependency);
      68                 :             : static bool dependency_is_fully_matched(MVDependency *dependency,
      69                 :             :                                         Bitmapset *attnums);
      70                 :             : static bool dependency_is_compatible_clause(Node *clause, Index relid,
      71                 :             :                                             AttrNumber *attnum);
      72                 :             : static bool dependency_is_compatible_expression(Node *clause, Index relid,
      73                 :             :                                                 List *statlist, Node **expr);
      74                 :             : static MVDependency *find_strongest_dependency(MVDependencies **dependencies,
      75                 :             :                                                int ndependencies, Bitmapset *attnums);
      76                 :             : static Selectivity clauselist_apply_dependencies(PlannerInfo *root, List *clauses,
      77                 :             :                                                  int varRelid, JoinType jointype,
      78                 :             :                                                  SpecialJoinInfo *sjinfo,
      79                 :             :                                                  MVDependency **dependencies,
      80                 :             :                                                  int ndependencies,
      81                 :             :                                                  AttrNumber *list_attnums,
      82                 :             :                                                  Bitmapset **estimatedclauses);
      83                 :             : 
      84                 :             : static void
      85                 :         974 : generate_dependencies_recurse(DependencyGenerator state, int index,
      86                 :             :                               AttrNumber start, AttrNumber *current)
      87                 :             : {
      88                 :             :     /*
      89                 :             :      * The generator handles the first (k-1) elements differently from the
      90                 :             :      * last element.
      91                 :             :      */
      92         [ +  + ]:         974 :     if (index < (state->k - 1))
      93                 :             :     {
      94                 :             :         AttrNumber  i;
      95                 :             : 
      96                 :             :         /*
      97                 :             :          * The first (k-1) values have to be in ascending order, which we
      98                 :             :          * generate recursively.
      99                 :             :          */
     100                 :             : 
     101         [ +  + ]:        1194 :         for (i = start; i < state->n; i++)
     102                 :             :         {
     103                 :         768 :             current[index] = i;
     104                 :         768 :             generate_dependencies_recurse(state, (index + 1), (i + 1), current);
     105                 :             :         }
     106                 :             :     }
     107                 :             :     else
     108                 :             :     {
     109                 :             :         int         i;
     110                 :             : 
     111                 :             :         /*
     112                 :             :          * the last element is the implied value, which does not respect the
     113                 :             :          * ascending order. We just need to check that the value is not in the
     114                 :             :          * first (k-1) elements.
     115                 :             :          */
     116                 :             : 
     117         [ +  + ]:        2084 :         for (i = 0; i < state->n; i++)
     118                 :             :         {
     119                 :             :             int         j;
     120                 :        1536 :             bool        match = false;
     121                 :             : 
     122                 :        1536 :             current[index] = i;
     123                 :             : 
     124         [ +  + ]:        2824 :             for (j = 0; j < index; j++)
     125                 :             :             {
     126         [ +  + ]:        2056 :                 if (current[j] == i)
     127                 :             :                 {
     128                 :         768 :                     match = true;
     129                 :         768 :                     break;
     130                 :             :                 }
     131                 :             :             }
     132                 :             : 
     133                 :             :             /*
     134                 :             :              * If the value is not found in the first part of the dependency,
     135                 :             :              * we're done.
     136                 :             :              */
     137         [ +  + ]:        1536 :             if (!match)
     138                 :             :             {
     139                 :        1536 :                 state->dependencies = (AttrNumber *) repalloc(state->dependencies,
     140                 :         768 :                                                               state->k * (state->ndependencies + 1) * sizeof(AttrNumber));
     141                 :         768 :                 memcpy(&state->dependencies[(state->k * state->ndependencies)],
     142                 :         768 :                        current, state->k * sizeof(AttrNumber));
     143                 :         768 :                 state->ndependencies++;
     144                 :             :             }
     145                 :             :         }
     146                 :             :     }
     147                 :         974 : }
     148                 :             : 
     149                 :             : /* generate all dependencies (k-permutations of n elements) */
     150                 :             : static void
     151                 :         206 : generate_dependencies(DependencyGenerator state)
     152                 :             : {
     153                 :         206 :     AttrNumber *current = palloc0_array(AttrNumber, state->k);
     154                 :             : 
     155                 :         206 :     generate_dependencies_recurse(state, 0, 0, current);
     156                 :             : 
     157                 :         206 :     pfree(current);
     158                 :         206 : }
     159                 :             : 
     160                 :             : /*
     161                 :             :  * initialize the DependencyGenerator of variations, and prebuild the variations
     162                 :             :  *
     163                 :             :  * This pre-builds all the variations. We could also generate them in
     164                 :             :  * DependencyGenerator_next(), but this seems simpler.
     165                 :             :  */
     166                 :             : static DependencyGenerator
     167                 :         206 : DependencyGenerator_init(int n, int k)
     168                 :             : {
     169                 :             :     DependencyGenerator state;
     170                 :             : 
     171                 :             :     Assert((n >= k) && (k > 0));
     172                 :             : 
     173                 :             :     /* allocate the DependencyGenerator state */
     174                 :         206 :     state = palloc0_object(DependencyGeneratorData);
     175                 :         206 :     state->dependencies = palloc_array(AttrNumber, k);
     176                 :             : 
     177                 :         206 :     state->ndependencies = 0;
     178                 :         206 :     state->current = 0;
     179                 :         206 :     state->k = k;
     180                 :         206 :     state->n = n;
     181                 :             : 
     182                 :             :     /* now actually pre-generate all the variations */
     183                 :         206 :     generate_dependencies(state);
     184                 :             : 
     185                 :         206 :     return state;
     186                 :             : }
     187                 :             : 
     188                 :             : /* free the DependencyGenerator state */
     189                 :             : static void
     190                 :         206 : DependencyGenerator_free(DependencyGenerator state)
     191                 :             : {
     192                 :         206 :     pfree(state->dependencies);
     193                 :         206 :     pfree(state);
     194                 :         206 : }
     195                 :             : 
     196                 :             : /* generate next combination */
     197                 :             : static AttrNumber *
     198                 :         974 : DependencyGenerator_next(DependencyGenerator state)
     199                 :             : {
     200         [ +  + ]:         974 :     if (state->current == state->ndependencies)
     201                 :         206 :         return NULL;
     202                 :             : 
     203                 :         768 :     return &state->dependencies[state->k * state->current++];
     204                 :             : }
     205                 :             : 
     206                 :             : 
     207                 :             : /*
     208                 :             :  * validates functional dependency on the data
     209                 :             :  *
     210                 :             :  * An actual work horse of detecting functional dependencies. Given a variation
     211                 :             :  * of k attributes, it checks that the first (k-1) are sufficient to determine
     212                 :             :  * the last one.
     213                 :             :  */
     214                 :             : static double
     215                 :         768 : dependency_degree(StatsBuildData *data, int k, AttrNumber *dependency)
     216                 :             : {
     217                 :             :     int         i,
     218                 :             :                 nitems;
     219                 :             :     MultiSortSupport mss;
     220                 :             :     SortItem   *items;
     221                 :             :     AttrNumber *attnums_dep;
     222                 :             : 
     223                 :             :     /* counters valid within a group */
     224                 :         768 :     int         group_size = 0;
     225                 :         768 :     int         n_violations = 0;
     226                 :             : 
     227                 :             :     /* total number of rows supporting (consistent with) the dependency */
     228                 :         768 :     int         n_supporting_rows = 0;
     229                 :             : 
     230                 :             :     /* Make sure we have at least two input attributes. */
     231                 :             :     Assert(k >= 2);
     232                 :             : 
     233                 :             :     /* sort info for all attributes columns */
     234                 :         768 :     mss = multi_sort_init(k);
     235                 :             : 
     236                 :             :     /*
     237                 :             :      * Translate the array of indexes to regular attnums for the dependency
     238                 :             :      * (we will need this to identify the columns in StatsBuildData).
     239                 :             :      */
     240                 :         768 :     attnums_dep = palloc_array(AttrNumber, k);
     241         [ +  + ]:        2572 :     for (i = 0; i < k; i++)
     242                 :        1804 :         attnums_dep[i] = data->attnums[dependency[i]];
     243                 :             : 
     244                 :             :     /*
     245                 :             :      * Verify the dependency (a,b,...)->z, using a rather simple algorithm:
     246                 :             :      *
     247                 :             :      * (a) sort the data lexicographically
     248                 :             :      *
     249                 :             :      * (b) split the data into groups by first (k-1) columns
     250                 :             :      *
     251                 :             :      * (c) for each group count different values in the last column
     252                 :             :      *
     253                 :             :      * We use the column data types' default sort operators and collations;
     254                 :             :      * perhaps at some point it'd be worth using column-specific collations?
     255                 :             :      */
     256                 :             : 
     257                 :             :     /* prepare the sort function for the dimensions */
     258         [ +  + ]:        2572 :     for (i = 0; i < k; i++)
     259                 :             :     {
     260                 :        1804 :         VacAttrStats *colstat = data->stats[dependency[i]];
     261                 :             :         TypeCacheEntry *type;
     262                 :             : 
     263                 :        1804 :         type = lookup_type_cache(colstat->attrtypid, TYPECACHE_LT_OPR);
     264         [ -  + ]:        1804 :         if (type->lt_opr == InvalidOid) /* shouldn't happen */
     265         [ #  # ]:           0 :             elog(ERROR, "cache lookup failed for ordering operator for type %u",
     266                 :             :                  colstat->attrtypid);
     267                 :             : 
     268                 :             :         /* prepare the sort function for this dimension */
     269                 :        1804 :         multi_sort_add_dimension(mss, i, type->lt_opr, colstat->attrcollid);
     270                 :             :     }
     271                 :             : 
     272                 :             :     /*
     273                 :             :      * build an array of SortItem(s) sorted using the multi-sort support
     274                 :             :      *
     275                 :             :      * XXX This relies on all stats entries pointing to the same tuple
     276                 :             :      * descriptor.  For now that assumption holds, but it might change in the
     277                 :             :      * future for example if we support statistics on multiple tables.
     278                 :             :      */
     279                 :         768 :     items = build_sorted_items(data, &nitems, mss, k, attnums_dep);
     280                 :             : 
     281                 :             :     /*
     282                 :             :      * Walk through the sorted array, split it into rows according to the
     283                 :             :      * first (k-1) columns. If there's a single value in the last column, we
     284                 :             :      * count the group as 'supporting' the functional dependency. Otherwise we
     285                 :             :      * count it as contradicting.
     286                 :             :      */
     287                 :             : 
     288                 :             :     /* start with the first row forming a group */
     289                 :         768 :     group_size = 1;
     290                 :             : 
     291                 :             :     /* loop 1 beyond the end of the array so that we count the final group */
     292         [ +  + ]:     1006864 :     for (i = 1; i <= nitems; i++)
     293                 :             :     {
     294                 :             :         /*
     295                 :             :          * Check if the group ended, which may be either because we processed
     296                 :             :          * all the items (i==nitems), or because the i-th item is not equal to
     297                 :             :          * the preceding one.
     298                 :             :          */
     299   [ +  +  +  + ]:     2011424 :         if (i == nitems ||
     300                 :     1005328 :             multi_sort_compare_dims(0, k - 2, &items[i - 1], &items[i], mss) != 0)
     301                 :             :         {
     302                 :             :             /*
     303                 :             :              * If no violations were found in the group then track the rows of
     304                 :             :              * the group as supporting the functional dependency.
     305                 :             :              */
     306         [ +  + ]:       23512 :             if (n_violations == 0)
     307                 :       14936 :                 n_supporting_rows += group_size;
     308                 :             : 
     309                 :             :             /* Reset counters for the new group */
     310                 :       23512 :             n_violations = 0;
     311                 :       23512 :             group_size = 1;
     312                 :       23512 :             continue;
     313                 :             :         }
     314                 :             :         /* first columns match, but the last one does not (so contradicting) */
     315         [ +  + ]:      982584 :         else if (multi_sort_compare_dim(k - 1, &items[i - 1], &items[i], mss) != 0)
     316                 :       40644 :             n_violations++;
     317                 :             : 
     318                 :      982584 :         group_size++;
     319                 :             :     }
     320                 :             : 
     321                 :             :     /* Compute the 'degree of validity' as (supporting/total). */
     322                 :         768 :     return (n_supporting_rows * 1.0 / data->numrows);
     323                 :             : }
     324                 :             : 
     325                 :             : /*
     326                 :             :  * detects functional dependencies between groups of columns
     327                 :             :  *
     328                 :             :  * Generates all possible subsets of columns (variations) and computes
     329                 :             :  * the degree of validity for each one. For example when creating statistics
     330                 :             :  * on three columns (a,b,c) there are 9 possible dependencies
     331                 :             :  *
     332                 :             :  *     two columns            three columns
     333                 :             :  *     -----------            -------------
     334                 :             :  *     (a) -> b                (a,b) -> c
     335                 :             :  *     (a) -> c                (a,c) -> b
     336                 :             :  *     (b) -> a                (b,c) -> a
     337                 :             :  *     (b) -> c
     338                 :             :  *     (c) -> a
     339                 :             :  *     (c) -> b
     340                 :             :  */
     341                 :             : MVDependencies *
     342                 :         154 : statext_dependencies_build(StatsBuildData *data)
     343                 :             : {
     344                 :             :     int         i,
     345                 :             :                 k;
     346                 :             : 
     347                 :             :     /* result */
     348                 :         154 :     MVDependencies *dependencies = NULL;
     349                 :             :     MemoryContext cxt;
     350                 :             : 
     351                 :             :     Assert(data->nattnums >= 2);
     352                 :             : 
     353                 :             :     /* tracks memory allocated by dependency_degree calls */
     354                 :         154 :     cxt = AllocSetContextCreate(CurrentMemoryContext,
     355                 :             :                                 "dependency_degree cxt",
     356                 :             :                                 ALLOCSET_DEFAULT_SIZES);
     357                 :             : 
     358                 :             :     /*
     359                 :             :      * We'll try build functional dependencies starting from the smallest ones
     360                 :             :      * covering just 2 columns, to the largest ones, covering all columns
     361                 :             :      * included in the statistics object.  We start from the smallest ones
     362                 :             :      * because we want to be able to skip already implied ones.
     363                 :             :      */
     364         [ +  + ]:         360 :     for (k = 2; k <= data->nattnums; k++)
     365                 :             :     {
     366                 :             :         AttrNumber *dependency; /* array with k elements */
     367                 :             : 
     368                 :             :         /* prepare a DependencyGenerator of variation */
     369                 :         206 :         DependencyGenerator DependencyGenerator = DependencyGenerator_init(data->nattnums, k);
     370                 :             : 
     371                 :             :         /* generate all possible variations of k values (out of n) */
     372         [ +  + ]:         974 :         while ((dependency = DependencyGenerator_next(DependencyGenerator)))
     373                 :             :         {
     374                 :             :             double      degree;
     375                 :             :             MVDependency *d;
     376                 :             :             MemoryContext oldcxt;
     377                 :             : 
     378                 :             :             /* release memory used by dependency degree calculation */
     379                 :         768 :             oldcxt = MemoryContextSwitchTo(cxt);
     380                 :             : 
     381                 :             :             /* compute how valid the dependency seems */
     382                 :         768 :             degree = dependency_degree(data, k, dependency);
     383                 :             : 
     384                 :         768 :             MemoryContextSwitchTo(oldcxt);
     385                 :         768 :             MemoryContextReset(cxt);
     386                 :             : 
     387                 :             :             /*
     388                 :             :              * if the dependency seems entirely invalid, don't store it
     389                 :             :              */
     390         [ +  + ]:         768 :             if (degree == 0.0)
     391                 :         186 :                 continue;
     392                 :             : 
     393                 :         582 :             d = (MVDependency *) palloc0(offsetof(MVDependency, attributes)
     394                 :         582 :                                          + k * sizeof(AttrNumber));
     395                 :             : 
     396                 :             :             /* copy the dependency (and keep the indexes into stxkeys) */
     397                 :         582 :             d->degree = degree;
     398                 :         582 :             d->nattributes = k;
     399         [ +  + ]:        1966 :             for (i = 0; i < k; i++)
     400                 :        1384 :                 d->attributes[i] = data->attnums[dependency[i]];
     401                 :             : 
     402                 :             :             /* initialize the list of dependencies */
     403         [ +  + ]:         582 :             if (dependencies == NULL)
     404                 :             :             {
     405                 :         142 :                 dependencies = palloc0_object(MVDependencies);
     406                 :             : 
     407                 :         142 :                 dependencies->magic = STATS_DEPS_MAGIC;
     408                 :         142 :                 dependencies->type = STATS_DEPS_TYPE_BASIC;
     409                 :         142 :                 dependencies->ndeps = 0;
     410                 :             :             }
     411                 :             : 
     412                 :         582 :             dependencies->ndeps++;
     413                 :         582 :             dependencies = (MVDependencies *) repalloc(dependencies,
     414                 :             :                                                        offsetof(MVDependencies, deps)
     415                 :         582 :                                                        + dependencies->ndeps * sizeof(MVDependency *));
     416                 :             : 
     417                 :         582 :             dependencies->deps[dependencies->ndeps - 1] = d;
     418                 :             :         }
     419                 :             : 
     420                 :             :         /*
     421                 :             :          * we're done with variations of k elements, so free the
     422                 :             :          * DependencyGenerator
     423                 :             :          */
     424                 :         206 :         DependencyGenerator_free(DependencyGenerator);
     425                 :             :     }
     426                 :             : 
     427                 :         154 :     MemoryContextDelete(cxt);
     428                 :             : 
     429                 :         154 :     return dependencies;
     430                 :             : }
     431                 :             : 
     432                 :             : 
     433                 :             : /*
     434                 :             :  * Serialize list of dependencies into a bytea value.
     435                 :             :  */
     436                 :             : bytea *
     437                 :         195 : statext_dependencies_serialize(MVDependencies *dependencies)
     438                 :             : {
     439                 :             :     bytea      *output;
     440                 :             :     char       *tmp;
     441                 :             :     Size        len;
     442                 :             : 
     443                 :             :     /* we need to store ndeps, with a number of attributes for each one */
     444                 :         195 :     len = VARHDRSZ + SizeOfHeader;
     445                 :             : 
     446                 :             :     /* and also include space for the actual attribute numbers and degrees */
     447         [ +  + ]:         914 :     for (uint32 i = 0; i < dependencies->ndeps; i++)
     448                 :         719 :         len += SizeOfItem(dependencies->deps[i]->nattributes);
     449                 :             : 
     450                 :         195 :     output = (bytea *) palloc0(len);
     451                 :         195 :     SET_VARSIZE(output, len);
     452                 :             : 
     453                 :         195 :     tmp = VARDATA(output);
     454                 :             : 
     455                 :             :     /* Store the base struct values (magic, type, ndeps) */
     456                 :         195 :     memcpy(tmp, &dependencies->magic, sizeof(uint32));
     457                 :         195 :     tmp += sizeof(uint32);
     458                 :         195 :     memcpy(tmp, &dependencies->type, sizeof(uint32));
     459                 :         195 :     tmp += sizeof(uint32);
     460                 :         195 :     memcpy(tmp, &dependencies->ndeps, sizeof(uint32));
     461                 :         195 :     tmp += sizeof(uint32);
     462                 :             : 
     463                 :             :     /* store number of attributes and attribute numbers for each dependency */
     464         [ +  + ]:         914 :     for (uint32 i = 0; i < dependencies->ndeps; i++)
     465                 :             :     {
     466                 :         719 :         MVDependency *d = dependencies->deps[i];
     467                 :             : 
     468                 :         719 :         memcpy(tmp, &d->degree, sizeof(double));
     469                 :         719 :         tmp += sizeof(double);
     470                 :             : 
     471                 :         719 :         memcpy(tmp, &d->nattributes, sizeof(AttrNumber));
     472                 :         719 :         tmp += sizeof(AttrNumber);
     473                 :             : 
     474                 :         719 :         memcpy(tmp, d->attributes, sizeof(AttrNumber) * d->nattributes);
     475                 :         719 :         tmp += sizeof(AttrNumber) * d->nattributes;
     476                 :             : 
     477                 :             :         /* protect against overflow */
     478                 :             :         Assert(tmp <= ((char *) output + len));
     479                 :             :     }
     480                 :             : 
     481                 :             :     /* make sure we've produced exactly the right amount of data */
     482                 :             :     Assert(tmp == ((char *) output + len));
     483                 :             : 
     484                 :         195 :     return output;
     485                 :             : }
     486                 :             : 
     487                 :             : /*
     488                 :             :  * Reads serialized dependencies into MVDependencies structure.
     489                 :             :  */
     490                 :             : MVDependencies *
     491                 :        1452 : statext_dependencies_deserialize(bytea *data)
     492                 :             : {
     493                 :             :     Size        min_expected_size;
     494                 :             :     MVDependencies *dependencies;
     495                 :             :     char       *tmp;
     496                 :             : 
     497         [ -  + ]:        1452 :     if (data == NULL)
     498                 :           0 :         return NULL;
     499                 :             : 
     500         [ -  + ]:        1452 :     if (VARSIZE_ANY_EXHDR(data) < SizeOfHeader)
     501         [ #  # ]:           0 :         elog(ERROR, "invalid MVDependencies size %zu (expected at least %zu)",
     502                 :             :              VARSIZE_ANY_EXHDR(data), SizeOfHeader);
     503                 :             : 
     504                 :             :     /* read the MVDependencies header */
     505                 :        1452 :     dependencies = palloc0_object(MVDependencies);
     506                 :             : 
     507                 :             :     /* initialize pointer to the data part (skip the varlena header) */
     508                 :        1452 :     tmp = VARDATA_ANY(data);
     509                 :             : 
     510                 :             :     /* read the header fields and perform basic sanity checks */
     511                 :        1452 :     memcpy(&dependencies->magic, tmp, sizeof(uint32));
     512                 :        1452 :     tmp += sizeof(uint32);
     513                 :        1452 :     memcpy(&dependencies->type, tmp, sizeof(uint32));
     514                 :        1452 :     tmp += sizeof(uint32);
     515                 :        1452 :     memcpy(&dependencies->ndeps, tmp, sizeof(uint32));
     516                 :        1452 :     tmp += sizeof(uint32);
     517                 :             : 
     518         [ -  + ]:        1452 :     if (dependencies->magic != STATS_DEPS_MAGIC)
     519         [ #  # ]:           0 :         elog(ERROR, "invalid dependency magic %d (expected %d)",
     520                 :             :              dependencies->magic, STATS_DEPS_MAGIC);
     521                 :             : 
     522         [ -  + ]:        1452 :     if (dependencies->type != STATS_DEPS_TYPE_BASIC)
     523         [ #  # ]:           0 :         elog(ERROR, "invalid dependency type %d (expected %d)",
     524                 :             :              dependencies->type, STATS_DEPS_TYPE_BASIC);
     525                 :             : 
     526         [ -  + ]:        1452 :     if (dependencies->ndeps == 0)
     527         [ #  # ]:           0 :         elog(ERROR, "invalid zero-length item array in MVDependencies");
     528                 :             : 
     529                 :             :     /* what minimum bytea size do we expect for those parameters */
     530                 :        1452 :     min_expected_size = MinSizeOfItems(dependencies->ndeps);
     531                 :             : 
     532         [ -  + ]:        1452 :     if (VARSIZE_ANY_EXHDR(data) < min_expected_size)
     533         [ #  # ]:           0 :         elog(ERROR, "invalid dependencies size %zu (expected at least %zu)",
     534                 :             :              VARSIZE_ANY_EXHDR(data), min_expected_size);
     535                 :             : 
     536                 :             :     /* allocate space for the MCV items */
     537                 :        1452 :     dependencies = repalloc(dependencies, offsetof(MVDependencies, deps)
     538                 :        1452 :                             + (dependencies->ndeps * sizeof(MVDependency *)));
     539                 :             : 
     540         [ +  + ]:        8435 :     for (uint32 i = 0; i < dependencies->ndeps; i++)
     541                 :             :     {
     542                 :             :         double      degree;
     543                 :             :         AttrNumber  k;
     544                 :             :         MVDependency *d;
     545                 :             : 
     546                 :             :         /* degree of validity */
     547                 :        6983 :         memcpy(&degree, tmp, sizeof(double));
     548                 :        6983 :         tmp += sizeof(double);
     549                 :             : 
     550                 :             :         /* number of attributes */
     551                 :        6983 :         memcpy(&k, tmp, sizeof(AttrNumber));
     552                 :        6983 :         tmp += sizeof(AttrNumber);
     553                 :             : 
     554                 :             :         /* is the number of attributes valid? */
     555                 :             :         Assert((k >= 2) && (k <= STATS_MAX_DIMENSIONS));
     556                 :             : 
     557                 :             :         /* now that we know the number of attributes, allocate the dependency */
     558                 :        6983 :         d = (MVDependency *) palloc0(offsetof(MVDependency, attributes)
     559                 :        6983 :                                      + (k * sizeof(AttrNumber)));
     560                 :             : 
     561                 :        6983 :         d->degree = degree;
     562                 :        6983 :         d->nattributes = k;
     563                 :             : 
     564                 :             :         /* copy attribute numbers */
     565                 :        6983 :         memcpy(d->attributes, tmp, sizeof(AttrNumber) * d->nattributes);
     566                 :        6983 :         tmp += sizeof(AttrNumber) * d->nattributes;
     567                 :             : 
     568                 :        6983 :         dependencies->deps[i] = d;
     569                 :             : 
     570                 :             :         /* still within the bytea */
     571                 :             :         Assert(tmp <= ((char *) data + VARSIZE_ANY(data)));
     572                 :             :     }
     573                 :             : 
     574                 :             :     /* we should have consumed the whole bytea exactly */
     575                 :             :     Assert(tmp == ((char *) data + VARSIZE_ANY(data)));
     576                 :             : 
     577                 :        1452 :     return dependencies;
     578                 :             : }
     579                 :             : 
     580                 :             : /*
     581                 :             :  * Free allocations of a MVDependencies.
     582                 :             :  */
     583                 :             : void
     584                 :          29 : statext_dependencies_free(MVDependencies *dependencies)
     585                 :             : {
     586         [ +  + ]:         234 :     for (uint32 i = 0; i < dependencies->ndeps; i++)
     587                 :         205 :         pfree(dependencies->deps[i]);
     588                 :          29 :     pfree(dependencies);
     589                 :          29 : }
     590                 :             : 
     591                 :             : /*
     592                 :             :  * Validate a set of MVDependencies against the extended statistics object
     593                 :             :  * definition.
     594                 :             :  *
     595                 :             :  * Every MVDependencies must be checked to ensure that the attnums in the
     596                 :             :  * attributes list correspond to attnums/expressions defined by the
     597                 :             :  * extended statistics object.
     598                 :             :  *
     599                 :             :  * Positive attnums are attributes which must be found in the stxkeys, while
     600                 :             :  * negative attnums correspond to an expression number, no attribute number
     601                 :             :  * can be below (0 - numexprs).
     602                 :             :  */
     603                 :             : bool
     604                 :          29 : statext_dependencies_validate(const MVDependencies *dependencies,
     605                 :             :                               const int2vector *stxkeys,
     606                 :             :                               int numexprs, int elevel)
     607                 :             : {
     608                 :          29 :     int         attnum_expr_lowbound = 0 - numexprs;
     609                 :             : 
     610                 :             :     /* Scan through each dependency entry */
     611         [ +  + ]:         218 :     for (uint32 i = 0; i < dependencies->ndeps; i++)
     612                 :             :     {
     613                 :         197 :         const MVDependency *dep = dependencies->deps[i];
     614                 :             : 
     615                 :             :         /*
     616                 :             :          * Cross-check each attribute in a dependency entry with the extended
     617                 :             :          * stats object definition.
     618                 :             :          */
     619         [ +  + ]:         685 :         for (int j = 0; j < dep->nattributes; j++)
     620                 :             :         {
     621                 :         496 :             AttrNumber  attnum = dep->attributes[j];
     622                 :         496 :             bool        ok = false;
     623                 :             : 
     624         [ +  + ]:         496 :             if (attnum > 0)
     625                 :             :             {
     626                 :             :                 /* attribute number in stxkeys */
     627         [ +  + ]:         404 :                 for (int k = 0; k < stxkeys->dim1; k++)
     628                 :             :                 {
     629         [ +  + ]:         396 :                     if (attnum == stxkeys->values[k])
     630                 :             :                     {
     631                 :         256 :                         ok = true;
     632                 :         256 :                         break;
     633                 :             :                     }
     634                 :             :                 }
     635                 :             :             }
     636   [ +  -  +  - ]:         232 :             else if ((attnum < 0) && (attnum >= attnum_expr_lowbound))
     637                 :             :             {
     638                 :             :                 /* attribute number for an expression */
     639                 :         232 :                 ok = true;
     640                 :             :             }
     641                 :             : 
     642         [ +  + ]:         496 :             if (!ok)
     643                 :             :             {
     644         [ +  - ]:           8 :                 ereport(elevel,
     645                 :             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     646                 :             :                          errmsg("could not validate \"%s\" object: invalid attribute number %d found",
     647                 :             :                                 "pg_dependencies", attnum)));
     648                 :           8 :                 return false;
     649                 :             :             }
     650                 :             :         }
     651                 :             :     }
     652                 :             : 
     653                 :          21 :     return true;
     654                 :             : }
     655                 :             : 
     656                 :             : /*
     657                 :             :  * dependency_is_fully_matched
     658                 :             :  *      checks that a functional dependency is fully matched given clauses on
     659                 :             :  *      attributes (assuming the clauses are suitable equality clauses)
     660                 :             :  */
     661                 :             : static bool
     662                 :        5130 : dependency_is_fully_matched(MVDependency *dependency, Bitmapset *attnums)
     663                 :             : {
     664                 :             :     int         j;
     665                 :             : 
     666                 :             :     /*
     667                 :             :      * Check that the dependency actually is fully covered by clauses. We have
     668                 :             :      * to translate all attribute numbers, as those are referenced
     669                 :             :      */
     670         [ +  + ]:       13035 :     for (j = 0; j < dependency->nattributes; j++)
     671                 :             :     {
     672                 :       10465 :         int         attnum = dependency->attributes[j];
     673                 :             : 
     674         [ +  + ]:       10465 :         if (!bms_is_member(attnum, attnums))
     675                 :        2560 :             return false;
     676                 :             :     }
     677                 :             : 
     678                 :        2570 :     return true;
     679                 :             : }
     680                 :             : 
     681                 :             : /*
     682                 :             :  * statext_dependencies_load
     683                 :             :  *      Load the functional dependencies for the indicated pg_statistic_ext tuple
     684                 :             :  */
     685                 :             : MVDependencies *
     686                 :        1340 : statext_dependencies_load(Oid mvoid, bool inh)
     687                 :             : {
     688                 :             :     MVDependencies *result;
     689                 :             :     bool        isnull;
     690                 :             :     Datum       deps;
     691                 :             :     HeapTuple   htup;
     692                 :             : 
     693                 :        1340 :     htup = SearchSysCache2(STATEXTDATASTXOID,
     694                 :             :                            ObjectIdGetDatum(mvoid),
     695                 :             :                            BoolGetDatum(inh));
     696         [ -  + ]:        1340 :     if (!HeapTupleIsValid(htup))
     697         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for statistics object %u", mvoid);
     698                 :             : 
     699                 :        1340 :     deps = SysCacheGetAttr(STATEXTDATASTXOID, htup,
     700                 :             :                            Anum_pg_statistic_ext_data_stxddependencies, &isnull);
     701         [ -  + ]:        1340 :     if (isnull)
     702         [ #  # ]:           0 :         elog(ERROR,
     703                 :             :              "requested statistics kind \"%c\" is not yet built for statistics object %u",
     704                 :             :              STATS_EXT_DEPENDENCIES, mvoid);
     705                 :             : 
     706                 :        1340 :     result = statext_dependencies_deserialize(DatumGetByteaPP(deps));
     707                 :             : 
     708                 :        1340 :     ReleaseSysCache(htup);
     709                 :             : 
     710                 :        1340 :     return result;
     711                 :             : }
     712                 :             : 
     713                 :             : /*
     714                 :             :  * dependency_is_compatible_clause
     715                 :             :  *      Determines if the clause is compatible with functional dependencies
     716                 :             :  *
     717                 :             :  * Only clauses that have the form of equality to a pseudoconstant, or can be
     718                 :             :  * interpreted that way, are currently accepted.  Furthermore the variable
     719                 :             :  * part of the clause must be a simple Var belonging to the specified
     720                 :             :  * relation, whose attribute number we return in *attnum on success.
     721                 :             :  */
     722                 :             : static bool
     723                 :        3300 : dependency_is_compatible_clause(Node *clause, Index relid, AttrNumber *attnum)
     724                 :             : {
     725                 :             :     Var        *var;
     726                 :             :     Node       *clause_expr;
     727                 :             : 
     728         [ +  + ]:        3300 :     if (IsA(clause, RestrictInfo))
     729                 :             :     {
     730                 :        3200 :         RestrictInfo *rinfo = (RestrictInfo *) clause;
     731                 :             : 
     732                 :             :         /* Pseudoconstants are not interesting (they couldn't contain a Var) */
     733         [ +  + ]:        3200 :         if (rinfo->pseudoconstant)
     734                 :           5 :             return false;
     735                 :             : 
     736                 :             :         /* Clauses referencing multiple, or no, varnos are incompatible */
     737         [ -  + ]:        3195 :         if (bms_membership(rinfo->clause_relids) != BMS_SINGLETON)
     738                 :           0 :             return false;
     739                 :             : 
     740                 :        3195 :         clause = (Node *) rinfo->clause;
     741                 :             :     }
     742                 :             : 
     743         [ +  + ]:        3295 :     if (is_opclause(clause))
     744                 :             :     {
     745                 :             :         /* If it's an opclause, check for Var = Const or Const = Var. */
     746                 :        1205 :         OpExpr     *expr = (OpExpr *) clause;
     747                 :             : 
     748                 :             :         /* Only expressions with two arguments are candidates. */
     749         [ -  + ]:        1205 :         if (list_length(expr->args) != 2)
     750                 :           0 :             return false;
     751                 :             : 
     752                 :             :         /* Make sure non-selected argument is a pseudoconstant. */
     753         [ +  - ]:        1205 :         if (is_pseudo_constant_clause(lsecond(expr->args)))
     754                 :        1205 :             clause_expr = linitial(expr->args);
     755         [ #  # ]:           0 :         else if (is_pseudo_constant_clause(linitial(expr->args)))
     756                 :           0 :             clause_expr = lsecond(expr->args);
     757                 :             :         else
     758                 :           0 :             return false;
     759                 :             : 
     760                 :             :         /*
     761                 :             :          * If it's not an "=" operator, just ignore the clause, as it's not
     762                 :             :          * compatible with functional dependencies.
     763                 :             :          *
     764                 :             :          * This uses the function for estimating selectivity, not the operator
     765                 :             :          * directly (a bit awkward, but well ...).
     766                 :             :          *
     767                 :             :          * XXX this is pretty dubious; probably it'd be better to check btree
     768                 :             :          * or hash opclass membership, so as not to be fooled by custom
     769                 :             :          * selectivity functions, and to be more consistent with decisions
     770                 :             :          * elsewhere in the planner.
     771                 :             :          */
     772         [ +  + ]:        1205 :         if (get_oprrest(expr->opno) != F_EQSEL)
     773                 :          30 :             return false;
     774                 :             : 
     775                 :             :         /* OK to proceed with checking "var" */
     776                 :             :     }
     777         [ +  + ]:        2090 :     else if (IsA(clause, ScalarArrayOpExpr))
     778                 :             :     {
     779                 :             :         /* If it's a scalar array operator, check for Var IN Const. */
     780                 :        2030 :         ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
     781                 :             : 
     782                 :             :         /*
     783                 :             :          * Reject ALL() variant, we only care about ANY/IN.
     784                 :             :          *
     785                 :             :          * XXX Maybe we should check if all the values are the same, and allow
     786                 :             :          * ALL in that case? Doesn't seem very practical, though.
     787                 :             :          */
     788         [ +  + ]:        2030 :         if (!expr->useOr)
     789                 :          30 :             return false;
     790                 :             : 
     791                 :             :         /* Only expressions with two arguments are candidates. */
     792         [ -  + ]:        2000 :         if (list_length(expr->args) != 2)
     793                 :           0 :             return false;
     794                 :             : 
     795                 :             :         /*
     796                 :             :          * We know it's always (Var IN Const), so we assume the var is the
     797                 :             :          * first argument, and pseudoconstant is the second one.
     798                 :             :          */
     799         [ -  + ]:        2000 :         if (!is_pseudo_constant_clause(lsecond(expr->args)))
     800                 :           0 :             return false;
     801                 :             : 
     802                 :        2000 :         clause_expr = linitial(expr->args);
     803                 :             : 
     804                 :             :         /*
     805                 :             :          * If it's not an "=" operator, just ignore the clause, as it's not
     806                 :             :          * compatible with functional dependencies. The operator is identified
     807                 :             :          * simply by looking at which function it uses to estimate
     808                 :             :          * selectivity. That's a bit strange, but it's what other similar
     809                 :             :          * places do.
     810                 :             :          */
     811         [ +  + ]:        2000 :         if (get_oprrest(expr->opno) != F_EQSEL)
     812                 :         150 :             return false;
     813                 :             : 
     814                 :             :         /* OK to proceed with checking "var" */
     815                 :             :     }
     816         [ +  - ]:          60 :     else if (is_orclause(clause))
     817                 :             :     {
     818                 :          60 :         BoolExpr   *bool_expr = (BoolExpr *) clause;
     819                 :             :         ListCell   *lc;
     820                 :             : 
     821                 :             :         /* start with no attribute number */
     822                 :          60 :         *attnum = InvalidAttrNumber;
     823                 :             : 
     824   [ +  -  +  +  :         125 :         foreach(lc, bool_expr->args)
                   +  + ]
     825                 :             :         {
     826                 :             :             AttrNumber  clause_attnum;
     827                 :             : 
     828                 :             :             /*
     829                 :             :              * Had we found incompatible clause in the arguments, treat the
     830                 :             :              * whole clause as incompatible.
     831                 :             :              */
     832         [ +  + ]:         100 :             if (!dependency_is_compatible_clause((Node *) lfirst(lc),
     833                 :             :                                                  relid, &clause_attnum))
     834                 :          35 :                 return false;
     835                 :             : 
     836         [ +  + ]:          70 :             if (*attnum == InvalidAttrNumber)
     837                 :          30 :                 *attnum = clause_attnum;
     838                 :             : 
     839                 :             :             /* ensure all the variables are the same (same attnum) */
     840         [ +  + ]:          70 :             if (*attnum != clause_attnum)
     841                 :           5 :                 return false;
     842                 :             :         }
     843                 :             : 
     844                 :             :         /* the Var is already checked by the recursive call */
     845                 :          25 :         return true;
     846                 :             :     }
     847         [ #  # ]:           0 :     else if (is_notclause(clause))
     848                 :             :     {
     849                 :             :         /*
     850                 :             :          * "NOT x" can be interpreted as "x = false", so get the argument and
     851                 :             :          * proceed with seeing if it's a suitable Var.
     852                 :             :          */
     853                 :           0 :         clause_expr = (Node *) get_notclausearg(clause);
     854                 :             :     }
     855                 :             :     else
     856                 :             :     {
     857                 :             :         /*
     858                 :             :          * A boolean expression "x" can be interpreted as "x = true", so
     859                 :             :          * proceed with seeing if it's a suitable Var.
     860                 :             :          */
     861                 :           0 :         clause_expr = clause;
     862                 :             :     }
     863                 :             : 
     864                 :             :     /*
     865                 :             :      * We may ignore any RelabelType node above the operand.  (There won't be
     866                 :             :      * more than one, since eval_const_expressions has been applied already.)
     867                 :             :      */
     868         [ -  + ]:        3025 :     if (IsA(clause_expr, RelabelType))
     869                 :           0 :         clause_expr = (Node *) ((RelabelType *) clause_expr)->arg;
     870                 :             : 
     871                 :             :     /* We only support plain Vars for now */
     872         [ +  + ]:        3025 :     if (!IsA(clause_expr, Var))
     873                 :         240 :         return false;
     874                 :             : 
     875                 :             :     /* OK, we know we have a Var */
     876                 :        2785 :     var = (Var *) clause_expr;
     877                 :             : 
     878                 :             :     /* Ensure Var is from the correct relation */
     879         [ -  + ]:        2785 :     if (var->varno != relid)
     880                 :           0 :         return false;
     881                 :             : 
     882                 :             :     /* We also better ensure the Var is from the current level */
     883         [ -  + ]:        2785 :     if (var->varlevelsup != 0)
     884                 :           0 :         return false;
     885                 :             : 
     886                 :             :     /* Also ignore system attributes (we don't allow stats on those) */
     887         [ -  + ]:        2785 :     if (!AttrNumberIsForUserDefinedAttr(var->varattno))
     888                 :           0 :         return false;
     889                 :             : 
     890                 :        2785 :     *attnum = var->varattno;
     891                 :        2785 :     return true;
     892                 :             : }
     893                 :             : 
     894                 :             : /*
     895                 :             :  * find_strongest_dependency
     896                 :             :  *      find the strongest dependency on the attributes
     897                 :             :  *
     898                 :             :  * When applying functional dependencies, we start with the strongest
     899                 :             :  * dependencies. That is, we select the dependency that:
     900                 :             :  *
     901                 :             :  * (a) has all attributes covered by equality clauses
     902                 :             :  *
     903                 :             :  * (b) has the most attributes
     904                 :             :  *
     905                 :             :  * (c) has the highest degree of validity
     906                 :             :  *
     907                 :             :  * This guarantees that we eliminate the most redundant conditions first
     908                 :             :  * (see the comment in dependencies_clauselist_selectivity).
     909                 :             :  */
     910                 :             : static MVDependency *
     911                 :        2905 : find_strongest_dependency(MVDependencies **dependencies, int ndependencies,
     912                 :             :                           Bitmapset *attnums)
     913                 :             : {
     914                 :        2905 :     MVDependency *strongest = NULL;
     915                 :             : 
     916                 :             :     /* number of attnums in clauses */
     917                 :        2905 :     int         nattnums = bms_num_members(attnums);
     918                 :             : 
     919                 :             :     /*
     920                 :             :      * Iterate over the MVDependency items and find the strongest one from the
     921                 :             :      * fully-matched dependencies. We do the cheap checks first, before
     922                 :             :      * matching it against the attnums.
     923                 :             :      */
     924         [ +  + ]:        5840 :     for (int i = 0; i < ndependencies; i++)
     925                 :             :     {
     926         [ +  + ]:       16900 :         for (uint32 j = 0; j < dependencies[i]->ndeps; j++)
     927                 :             :         {
     928                 :       13965 :             MVDependency *dependency = dependencies[i]->deps[j];
     929                 :             : 
     930                 :             :             /*
     931                 :             :              * Skip dependencies referencing more attributes than available
     932                 :             :              * clauses, as those can't be fully matched.
     933                 :             :              */
     934         [ +  + ]:       13965 :             if (dependency->nattributes > nattnums)
     935                 :        8835 :                 continue;
     936                 :             : 
     937         [ +  + ]:        5130 :             if (strongest)
     938                 :             :             {
     939                 :             :                 /* skip dependencies on fewer attributes than the strongest. */
     940         [ -  + ]:        3280 :                 if (dependency->nattributes < strongest->nattributes)
     941                 :           0 :                     continue;
     942                 :             : 
     943                 :             :                 /* also skip weaker dependencies when attribute count matches */
     944         [ +  + ]:        3280 :                 if (strongest->nattributes == dependency->nattributes &&
     945         [ -  + ]:        3045 :                     strongest->degree > dependency->degree)
     946                 :           0 :                     continue;
     947                 :             :             }
     948                 :             : 
     949                 :             :             /*
     950                 :             :              * this dependency is stronger, but we must still check that it's
     951                 :             :              * fully matched to these attnums. We perform this check last as
     952                 :             :              * it's slightly more expensive than the previous checks.
     953                 :             :              */
     954         [ +  + ]:        5130 :             if (dependency_is_fully_matched(dependency, attnums))
     955                 :        2570 :                 strongest = dependency; /* save new best match */
     956                 :             :         }
     957                 :             :     }
     958                 :             : 
     959                 :        2905 :     return strongest;
     960                 :             : }
     961                 :             : 
     962                 :             : /*
     963                 :             :  * clauselist_apply_dependencies
     964                 :             :  *      Apply the specified functional dependencies to a list of clauses and
     965                 :             :  *      return the estimated selectivity of the clauses that are compatible
     966                 :             :  *      with any of the given dependencies.
     967                 :             :  *
     968                 :             :  * This will estimate all not-already-estimated clauses that are compatible
     969                 :             :  * with functional dependencies, and which have an attribute mentioned by any
     970                 :             :  * of the given dependencies (either as an implying or implied attribute).
     971                 :             :  *
     972                 :             :  * Given (lists of) clauses on attributes (a,b) and a functional dependency
     973                 :             :  * (a=>b), the per-column selectivities P(a) and P(b) are notionally combined
     974                 :             :  * using the formula
     975                 :             :  *
     976                 :             :  *      P(a,b) = f * P(a) + (1-f) * P(a) * P(b)
     977                 :             :  *
     978                 :             :  * where 'f' is the degree of dependency.  This reflects the fact that we
     979                 :             :  * expect a fraction f of all rows to be consistent with the dependency
     980                 :             :  * (a=>b), and so have a selectivity of P(a), while the remaining rows are
     981                 :             :  * treated as independent.
     982                 :             :  *
     983                 :             :  * In practice, we use a slightly modified version of this formula, which uses
     984                 :             :  * a selectivity of Min(P(a), P(b)) for the dependent rows, since the result
     985                 :             :  * should obviously not exceed either column's individual selectivity.  I.e.,
     986                 :             :  * we actually combine selectivities using the formula
     987                 :             :  *
     988                 :             :  *      P(a,b) = f * Min(P(a), P(b)) + (1-f) * P(a) * P(b)
     989                 :             :  *
     990                 :             :  * This can make quite a difference if the specific values matching the
     991                 :             :  * clauses are not consistent with the functional dependency.
     992                 :             :  */
     993                 :             : static Selectivity
     994                 :        1330 : clauselist_apply_dependencies(PlannerInfo *root, List *clauses,
     995                 :             :                               int varRelid, JoinType jointype,
     996                 :             :                               SpecialJoinInfo *sjinfo,
     997                 :             :                               MVDependency **dependencies, int ndependencies,
     998                 :             :                               AttrNumber *list_attnums,
     999                 :             :                               Bitmapset **estimatedclauses)
    1000                 :             : {
    1001                 :             :     Bitmapset  *attnums;
    1002                 :             :     int         i;
    1003                 :             :     int         j;
    1004                 :             :     int         nattrs;
    1005                 :             :     Selectivity *attr_sel;
    1006                 :             :     int         attidx;
    1007                 :             :     int         listidx;
    1008                 :             :     ListCell   *l;
    1009                 :             :     Selectivity s1;
    1010                 :             : 
    1011                 :             :     /*
    1012                 :             :      * Extract the attnums of all implying and implied attributes from all the
    1013                 :             :      * given dependencies.  Each of these attributes is expected to have at
    1014                 :             :      * least 1 not-already-estimated compatible clause that we will estimate
    1015                 :             :      * here.
    1016                 :             :      */
    1017                 :        1330 :     attnums = NULL;
    1018         [ +  + ]:        2905 :     for (i = 0; i < ndependencies; i++)
    1019                 :             :     {
    1020         [ +  + ]:        4960 :         for (j = 0; j < dependencies[i]->nattributes; j++)
    1021                 :             :         {
    1022                 :        3385 :             AttrNumber  attnum = dependencies[i]->attributes[j];
    1023                 :             : 
    1024                 :        3385 :             attnums = bms_add_member(attnums, attnum);
    1025                 :             :         }
    1026                 :             :     }
    1027                 :             : 
    1028                 :             :     /*
    1029                 :             :      * Compute per-column selectivity estimates for each of these attributes,
    1030                 :             :      * and mark all the corresponding clauses as estimated.
    1031                 :             :      */
    1032                 :        1330 :     nattrs = bms_num_members(attnums);
    1033                 :        1330 :     attr_sel = palloc_array(Selectivity, nattrs);
    1034                 :             : 
    1035                 :        1330 :     attidx = 0;
    1036                 :        1330 :     i = -1;
    1037         [ +  + ]:        4245 :     while ((i = bms_next_member(attnums, i)) >= 0)
    1038                 :             :     {
    1039                 :        2915 :         List       *attr_clauses = NIL;
    1040                 :             :         Selectivity simple_sel;
    1041                 :             : 
    1042                 :        2915 :         listidx = -1;
    1043   [ +  -  +  +  :        9530 :         foreach(l, clauses)
                   +  + ]
    1044                 :             :         {
    1045                 :        6615 :             Node       *clause = (Node *) lfirst(l);
    1046                 :             : 
    1047                 :        6615 :             listidx++;
    1048         [ +  + ]:        6615 :             if (list_attnums[listidx] == i)
    1049                 :             :             {
    1050                 :        2915 :                 attr_clauses = lappend(attr_clauses, clause);
    1051                 :        2915 :                 *estimatedclauses = bms_add_member(*estimatedclauses, listidx);
    1052                 :             :             }
    1053                 :             :         }
    1054                 :             : 
    1055                 :        2915 :         simple_sel = clauselist_selectivity_ext(root, attr_clauses, varRelid,
    1056                 :             :                                                 jointype, sjinfo, false);
    1057                 :        2915 :         attr_sel[attidx++] = simple_sel;
    1058                 :             :     }
    1059                 :             : 
    1060                 :             :     /*
    1061                 :             :      * Now combine these selectivities using the dependency information.  For
    1062                 :             :      * chains of dependencies such as a -> b -> c, the b -> c dependency will
    1063                 :             :      * come before the a -> b dependency in the array, so we traverse the
    1064                 :             :      * array backwards to ensure such chains are computed in the right order.
    1065                 :             :      *
    1066                 :             :      * As explained above, pairs of selectivities are combined using the
    1067                 :             :      * formula
    1068                 :             :      *
    1069                 :             :      * P(a,b) = f * Min(P(a), P(b)) + (1-f) * P(a) * P(b)
    1070                 :             :      *
    1071                 :             :      * to ensure that the combined selectivity is never greater than either
    1072                 :             :      * individual selectivity.
    1073                 :             :      *
    1074                 :             :      * Where multiple dependencies apply (e.g., a -> b -> c), we use
    1075                 :             :      * conditional probabilities to compute the overall result as follows:
    1076                 :             :      *
    1077                 :             :      * P(a,b,c) = P(c|a,b) * P(a,b) = P(c|a,b) * P(b|a) * P(a)
    1078                 :             :      *
    1079                 :             :      * so we replace the selectivities of all implied attributes with
    1080                 :             :      * conditional probabilities, that are conditional on all their implying
    1081                 :             :      * attributes.  The selectivities of all other non-implied attributes are
    1082                 :             :      * left as they are.
    1083                 :             :      */
    1084         [ +  + ]:        2905 :     for (i = ndependencies - 1; i >= 0; i--)
    1085                 :             :     {
    1086                 :        1575 :         MVDependency *dependency = dependencies[i];
    1087                 :             :         AttrNumber  attnum;
    1088                 :             :         Selectivity s2;
    1089                 :             :         double      f;
    1090                 :             : 
    1091                 :             :         /* Selectivity of all the implying attributes */
    1092                 :        1575 :         s1 = 1.0;
    1093         [ +  + ]:        3385 :         for (j = 0; j < dependency->nattributes - 1; j++)
    1094                 :             :         {
    1095                 :        1810 :             attnum = dependency->attributes[j];
    1096                 :        1810 :             attidx = bms_member_index(attnums, attnum);
    1097                 :        1810 :             s1 *= attr_sel[attidx];
    1098                 :             :         }
    1099                 :             : 
    1100                 :             :         /* Original selectivity of the implied attribute */
    1101                 :        1575 :         attnum = dependency->attributes[j];
    1102                 :        1575 :         attidx = bms_member_index(attnums, attnum);
    1103                 :        1575 :         s2 = attr_sel[attidx];
    1104                 :             : 
    1105                 :             :         /*
    1106                 :             :          * Replace s2 with the conditional probability s2 given s1, computed
    1107                 :             :          * using the formula P(b|a) = P(a,b) / P(a), which simplifies to
    1108                 :             :          *
    1109                 :             :          * P(b|a) = f * Min(P(a), P(b)) / P(a) + (1-f) * P(b)
    1110                 :             :          *
    1111                 :             :          * where P(a) = s1, the selectivity of the implying attributes, and
    1112                 :             :          * P(b) = s2, the selectivity of the implied attribute.
    1113                 :             :          */
    1114                 :        1575 :         f = dependency->degree;
    1115                 :             : 
    1116         [ +  + ]:        1575 :         if (s1 <= s2)
    1117                 :        1485 :             attr_sel[attidx] = f + (1 - f) * s2;
    1118                 :             :         else
    1119                 :          90 :             attr_sel[attidx] = f * s2 / s1 + (1 - f) * s2;
    1120                 :             :     }
    1121                 :             : 
    1122                 :             :     /*
    1123                 :             :      * The overall selectivity of all the clauses on all these attributes is
    1124                 :             :      * then the product of all the original (non-implied) probabilities and
    1125                 :             :      * the new conditional (implied) probabilities.
    1126                 :             :      */
    1127                 :        1330 :     s1 = 1.0;
    1128         [ +  + ]:        4245 :     for (i = 0; i < nattrs; i++)
    1129                 :        2915 :         s1 *= attr_sel[i];
    1130                 :             : 
    1131   [ -  +  -  + ]:        1330 :     CLAMP_PROBABILITY(s1);
    1132                 :             : 
    1133                 :        1330 :     pfree(attr_sel);
    1134                 :        1330 :     bms_free(attnums);
    1135                 :             : 
    1136                 :        1330 :     return s1;
    1137                 :             : }
    1138                 :             : 
    1139                 :             : /*
    1140                 :             :  * dependency_is_compatible_expression
    1141                 :             :  *      Determines if the expression is compatible with functional dependencies
    1142                 :             :  *
    1143                 :             :  * Similar to dependency_is_compatible_clause, but doesn't enforce that the
    1144                 :             :  * expression is a simple Var.  On success, return the matching statistics
    1145                 :             :  * expression into *expr.
    1146                 :             :  */
    1147                 :             : static bool
    1148                 :         535 : dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
    1149                 :             : {
    1150                 :             :     ListCell   *lc,
    1151                 :             :                *lc2;
    1152                 :             :     Node       *clause_expr;
    1153                 :             : 
    1154         [ +  + ]:         535 :     if (IsA(clause, RestrictInfo))
    1155                 :             :     {
    1156                 :         460 :         RestrictInfo *rinfo = (RestrictInfo *) clause;
    1157                 :             : 
    1158                 :             :         /* Pseudoconstants are not interesting (they couldn't contain a Var) */
    1159         [ +  + ]:         460 :         if (rinfo->pseudoconstant)
    1160                 :           5 :             return false;
    1161                 :             : 
    1162                 :             :         /* Clauses referencing multiple, or no, varnos are incompatible */
    1163         [ -  + ]:         455 :         if (bms_membership(rinfo->clause_relids) != BMS_SINGLETON)
    1164                 :           0 :             return false;
    1165                 :             : 
    1166                 :         455 :         clause = (Node *) rinfo->clause;
    1167                 :             :     }
    1168                 :             : 
    1169         [ +  + ]:         530 :     if (is_opclause(clause))
    1170                 :             :     {
    1171                 :             :         /* If it's an opclause, check for Var = Const or Const = Var. */
    1172                 :         170 :         OpExpr     *expr = (OpExpr *) clause;
    1173                 :             : 
    1174                 :             :         /* Only expressions with two arguments are candidates. */
    1175         [ -  + ]:         170 :         if (list_length(expr->args) != 2)
    1176                 :           0 :             return false;
    1177                 :             : 
    1178                 :             :         /* Make sure non-selected argument is a pseudoconstant. */
    1179         [ +  - ]:         170 :         if (is_pseudo_constant_clause(lsecond(expr->args)))
    1180                 :         170 :             clause_expr = linitial(expr->args);
    1181         [ #  # ]:           0 :         else if (is_pseudo_constant_clause(linitial(expr->args)))
    1182                 :           0 :             clause_expr = lsecond(expr->args);
    1183                 :             :         else
    1184                 :           0 :             return false;
    1185                 :             : 
    1186                 :             :         /*
    1187                 :             :          * If it's not an "=" operator, just ignore the clause, as it's not
    1188                 :             :          * compatible with functional dependencies.
    1189                 :             :          *
    1190                 :             :          * This uses the function for estimating selectivity, not the operator
    1191                 :             :          * directly (a bit awkward, but well ...).
    1192                 :             :          *
    1193                 :             :          * XXX this is pretty dubious; probably it'd be better to check btree
    1194                 :             :          * or hash opclass membership, so as not to be fooled by custom
    1195                 :             :          * selectivity functions, and to be more consistent with decisions
    1196                 :             :          * elsewhere in the planner.
    1197                 :             :          */
    1198         [ +  + ]:         170 :         if (get_oprrest(expr->opno) != F_EQSEL)
    1199                 :          30 :             return false;
    1200                 :             : 
    1201                 :             :         /* OK to proceed with checking "var" */
    1202                 :             :     }
    1203         [ +  + ]:         360 :     else if (IsA(clause, ScalarArrayOpExpr))
    1204                 :             :     {
    1205                 :             :         /* If it's a scalar array operator, check for Var IN Const. */
    1206                 :         325 :         ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
    1207                 :             : 
    1208                 :             :         /*
    1209                 :             :          * Reject ALL() variant, we only care about ANY/IN.
    1210                 :             :          *
    1211                 :             :          * FIXME Maybe we should check if all the values are the same, and
    1212                 :             :          * allow ALL in that case? Doesn't seem very practical, though.
    1213                 :             :          */
    1214         [ +  + ]:         325 :         if (!expr->useOr)
    1215                 :          30 :             return false;
    1216                 :             : 
    1217                 :             :         /* Only expressions with two arguments are candidates. */
    1218         [ -  + ]:         295 :         if (list_length(expr->args) != 2)
    1219                 :           0 :             return false;
    1220                 :             : 
    1221                 :             :         /*
    1222                 :             :          * We know it's always (Var IN Const), so we assume the var is the
    1223                 :             :          * first argument, and pseudoconstant is the second one.
    1224                 :             :          */
    1225         [ -  + ]:         295 :         if (!is_pseudo_constant_clause(lsecond(expr->args)))
    1226                 :           0 :             return false;
    1227                 :             : 
    1228                 :         295 :         clause_expr = linitial(expr->args);
    1229                 :             : 
    1230                 :             :         /*
    1231                 :             :          * If it's not an "=" operator, just ignore the clause, as it's not
    1232                 :             :          * compatible with functional dependencies. The operator is identified
    1233                 :             :          * simply by looking at which function it uses to estimate
    1234                 :             :          * selectivity. That's a bit strange, but it's what other similar
    1235                 :             :          * places do.
    1236                 :             :          */
    1237         [ +  + ]:         295 :         if (get_oprrest(expr->opno) != F_EQSEL)
    1238                 :         150 :             return false;
    1239                 :             : 
    1240                 :             :         /* OK to proceed with checking "var" */
    1241                 :             :     }
    1242         [ +  - ]:          35 :     else if (is_orclause(clause))
    1243                 :             :     {
    1244                 :          35 :         BoolExpr   *bool_expr = (BoolExpr *) clause;
    1245                 :             : 
    1246                 :             :         /* start with no expression (we'll use the first match) */
    1247                 :          35 :         *expr = NULL;
    1248                 :             : 
    1249   [ +  -  +  +  :         100 :         foreach(lc, bool_expr->args)
                   +  + ]
    1250                 :             :         {
    1251                 :          75 :             Node       *or_expr = NULL;
    1252                 :             : 
    1253                 :             :             /*
    1254                 :             :              * Had we found incompatible expression in the arguments, treat
    1255                 :             :              * the whole expression as incompatible.
    1256                 :             :              */
    1257         [ +  + ]:          75 :             if (!dependency_is_compatible_expression((Node *) lfirst(lc), relid,
    1258                 :             :                                                      statlist, &or_expr))
    1259                 :          10 :                 return false;
    1260                 :             : 
    1261         [ +  + ]:          70 :             if (*expr == NULL)
    1262                 :          30 :                 *expr = or_expr;
    1263                 :             : 
    1264                 :             :             /* ensure all the expressions are the same */
    1265         [ +  + ]:          70 :             if (!equal(or_expr, *expr))
    1266                 :           5 :                 return false;
    1267                 :             :         }
    1268                 :             : 
    1269                 :             :         /* the expression is already checked by the recursive call */
    1270                 :          25 :         return true;
    1271                 :             :     }
    1272         [ #  # ]:           0 :     else if (is_notclause(clause))
    1273                 :             :     {
    1274                 :             :         /*
    1275                 :             :          * "NOT x" can be interpreted as "x = false", so get the argument and
    1276                 :             :          * proceed with seeing if it's a suitable Var.
    1277                 :             :          */
    1278                 :           0 :         clause_expr = (Node *) get_notclausearg(clause);
    1279                 :             :     }
    1280                 :             :     else
    1281                 :             :     {
    1282                 :             :         /*
    1283                 :             :          * A boolean expression "x" can be interpreted as "x = true", so
    1284                 :             :          * proceed with seeing if it's a suitable Var.
    1285                 :             :          */
    1286                 :           0 :         clause_expr = clause;
    1287                 :             :     }
    1288                 :             : 
    1289                 :             :     /*
    1290                 :             :      * We may ignore any RelabelType node above the operand.  (There won't be
    1291                 :             :      * more than one, since eval_const_expressions has been applied already.)
    1292                 :             :      */
    1293         [ -  + ]:         285 :     if (IsA(clause_expr, RelabelType))
    1294                 :           0 :         clause_expr = (Node *) ((RelabelType *) clause_expr)->arg;
    1295                 :             : 
    1296                 :             :     /*
    1297                 :             :      * Search for a matching statistics expression.
    1298                 :             :      */
    1299   [ +  -  +  +  :         290 :     foreach(lc, statlist)
                   +  + ]
    1300                 :             :     {
    1301                 :         285 :         StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
    1302                 :             : 
    1303                 :             :         /* ignore stats without dependencies */
    1304         [ -  + ]:         285 :         if (info->kind != STATS_EXT_DEPENDENCIES)
    1305                 :           0 :             continue;
    1306                 :             : 
    1307   [ +  +  +  -  :         465 :         foreach(lc2, info->exprs)
                   +  + ]
    1308                 :             :         {
    1309                 :         460 :             Node       *stat_expr = (Node *) lfirst(lc2);
    1310                 :             : 
    1311         [ +  + ]:         460 :             if (equal(clause_expr, stat_expr))
    1312                 :             :             {
    1313                 :         280 :                 *expr = stat_expr;
    1314                 :         280 :                 return true;
    1315                 :             :             }
    1316                 :             :         }
    1317                 :             :     }
    1318                 :             : 
    1319                 :           5 :     return false;
    1320                 :             : }
    1321                 :             : 
    1322                 :             : /*
    1323                 :             :  * dependencies_clauselist_selectivity
    1324                 :             :  *      Return the estimated selectivity of (a subset of) the given clauses
    1325                 :             :  *      using functional dependency statistics, or 1.0 if no useful functional
    1326                 :             :  *      dependency statistic exists.
    1327                 :             :  *
    1328                 :             :  * 'estimatedclauses' is an input/output argument that gets a bit set
    1329                 :             :  * corresponding to the (zero-based) list index of each clause that is included
    1330                 :             :  * in the estimated selectivity.
    1331                 :             :  *
    1332                 :             :  * Given equality clauses on attributes (a,b) we find the strongest dependency
    1333                 :             :  * between them, i.e. either (a=>b) or (b=>a). Assuming (a=>b) is the selected
    1334                 :             :  * dependency, we then combine the per-clause selectivities using the formula
    1335                 :             :  *
    1336                 :             :  *     P(a,b) = f * P(a) + (1-f) * P(a) * P(b)
    1337                 :             :  *
    1338                 :             :  * where 'f' is the degree of the dependency.  (Actually we use a slightly
    1339                 :             :  * modified version of this formula -- see clauselist_apply_dependencies()).
    1340                 :             :  *
    1341                 :             :  * With clauses on more than two attributes, the dependencies are applied
    1342                 :             :  * recursively, starting with the widest/strongest dependencies. For example
    1343                 :             :  * P(a,b,c) is first split like this:
    1344                 :             :  *
    1345                 :             :  *     P(a,b,c) = f * P(a,b) + (1-f) * P(a,b) * P(c)
    1346                 :             :  *
    1347                 :             :  * assuming (a,b=>c) is the strongest dependency.
    1348                 :             :  */
    1349                 :             : Selectivity
    1350                 :        2040 : dependencies_clauselist_selectivity(PlannerInfo *root,
    1351                 :             :                                     List *clauses,
    1352                 :             :                                     int varRelid,
    1353                 :             :                                     JoinType jointype,
    1354                 :             :                                     SpecialJoinInfo *sjinfo,
    1355                 :             :                                     RelOptInfo *rel,
    1356                 :             :                                     Bitmapset **estimatedclauses)
    1357                 :             : {
    1358                 :        2040 :     Selectivity s1 = 1.0;
    1359                 :             :     ListCell   *l;
    1360                 :        2040 :     Bitmapset  *clauses_attnums = NULL;
    1361                 :             :     AttrNumber *list_attnums;
    1362                 :             :     int         listidx;
    1363                 :             :     MVDependencies **func_dependencies;
    1364                 :             :     int         nfunc_dependencies;
    1365                 :             :     int         total_ndeps;
    1366                 :             :     MVDependency **dependencies;
    1367                 :             :     int         ndependencies;
    1368                 :             :     AttrNumber  attnum_offset;
    1369         [ +  - ]:        2040 :     RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
    1370                 :             : 
    1371                 :             :     /* unique expressions */
    1372                 :             :     Node      **unique_exprs;
    1373                 :             :     int         unique_exprs_cnt;
    1374                 :             : 
    1375                 :             :     /* check if there's any stats that might be useful for us. */
    1376         [ +  + ]:        2040 :     if (!has_stats_of_kind(rel->statlist, STATS_EXT_DEPENDENCIES))
    1377                 :         550 :         return 1.0;
    1378                 :             : 
    1379                 :        1490 :     list_attnums = palloc_array(AttrNumber, list_length(clauses));
    1380                 :             : 
    1381                 :             :     /*
    1382                 :             :      * We allocate space as if every clause was a unique expression, although
    1383                 :             :      * that's probably overkill. Some will be simple column references that
    1384                 :             :      * we'll translate to attnums, and there might be duplicates. But it's
    1385                 :             :      * easier and cheaper to just do one allocation than repalloc later.
    1386                 :             :      */
    1387                 :        1490 :     unique_exprs = palloc_array(Node *, list_length(clauses));
    1388                 :        1490 :     unique_exprs_cnt = 0;
    1389                 :             : 
    1390                 :             :     /*
    1391                 :             :      * Pre-process the clauses list to extract the attnums seen in each item.
    1392                 :             :      * We need to determine if there's any clauses which will be useful for
    1393                 :             :      * dependency selectivity estimations. Along the way we'll record all of
    1394                 :             :      * the attnums for each clause in a list which we'll reference later so we
    1395                 :             :      * don't need to repeat the same work again. We'll also keep track of all
    1396                 :             :      * attnums seen.
    1397                 :             :      *
    1398                 :             :      * We also skip clauses that we already estimated using different types of
    1399                 :             :      * statistics (we treat them as incompatible).
    1400                 :             :      *
    1401                 :             :      * To handle expressions, we assign them negative attnums, as if it was a
    1402                 :             :      * system attribute (this is fine, as we only allow extended stats on user
    1403                 :             :      * attributes). And then we offset everything by the number of
    1404                 :             :      * expressions, so that we can store the values in a bitmapset.
    1405                 :             :      */
    1406                 :        1490 :     listidx = 0;
    1407   [ +  -  +  +  :        4725 :     foreach(l, clauses)
                   +  + ]
    1408                 :             :     {
    1409                 :        3235 :         Node       *clause = (Node *) lfirst(l);
    1410                 :             :         AttrNumber  attnum;
    1411                 :        3235 :         Node       *expr = NULL;
    1412                 :             : 
    1413                 :             :         /* ignore clause by default */
    1414                 :        3235 :         list_attnums[listidx] = InvalidAttrNumber;
    1415                 :             : 
    1416         [ +  + ]:        3235 :         if (!bms_is_member(listidx, *estimatedclauses))
    1417                 :             :         {
    1418                 :             :             /*
    1419                 :             :              * If it's a simple column reference, just extract the attnum. If
    1420                 :             :              * it's an expression, assign a negative attnum as if it was a
    1421                 :             :              * system attribute.
    1422                 :             :              */
    1423         [ +  + ]:        3200 :             if (dependency_is_compatible_clause(clause, rel->relid, &attnum))
    1424                 :             :             {
    1425                 :        2740 :                 list_attnums[listidx] = attnum;
    1426                 :             :             }
    1427         [ +  + ]:         460 :             else if (dependency_is_compatible_expression(clause, rel->relid,
    1428                 :             :                                                          rel->statlist,
    1429                 :             :                                                          &expr))
    1430                 :             :             {
    1431                 :             :                 /* special attnum assigned to this expression */
    1432                 :         235 :                 attnum = InvalidAttrNumber;
    1433                 :             : 
    1434                 :             :                 Assert(expr != NULL);
    1435                 :             : 
    1436                 :             :                 /* If the expression is duplicate, use the same attnum. */
    1437         [ +  + ]:         395 :                 for (int i = 0; i < unique_exprs_cnt; i++)
    1438                 :             :                 {
    1439         [ -  + ]:         160 :                     if (equal(unique_exprs[i], expr))
    1440                 :             :                     {
    1441                 :             :                         /* negative attribute number to expression */
    1442                 :           0 :                         attnum = -(i + 1);
    1443                 :           0 :                         break;
    1444                 :             :                     }
    1445                 :             :                 }
    1446                 :             : 
    1447                 :             :                 /* not found in the list, so add it */
    1448         [ +  - ]:         235 :                 if (attnum == InvalidAttrNumber)
    1449                 :             :                 {
    1450                 :         235 :                     unique_exprs[unique_exprs_cnt++] = expr;
    1451                 :             : 
    1452                 :             :                     /* after incrementing the value, to get -1, -2, ... */
    1453                 :         235 :                     attnum = (-unique_exprs_cnt);
    1454                 :             :                 }
    1455                 :             : 
    1456                 :             :                 /* remember which attnum was assigned to this clause */
    1457                 :         235 :                 list_attnums[listidx] = attnum;
    1458                 :             :             }
    1459                 :             :         }
    1460                 :             : 
    1461                 :        3235 :         listidx++;
    1462                 :             :     }
    1463                 :             : 
    1464                 :             :     Assert(listidx == list_length(clauses));
    1465                 :             : 
    1466                 :             :     /*
    1467                 :             :      * How much we need to offset the attnums? If there are no expressions,
    1468                 :             :      * then no offset is needed. Otherwise we need to offset enough for the
    1469                 :             :      * lowest value (-unique_exprs_cnt) to become 1.
    1470                 :             :      */
    1471         [ +  + ]:        1490 :     if (unique_exprs_cnt > 0)
    1472                 :         110 :         attnum_offset = (unique_exprs_cnt + 1);
    1473                 :             :     else
    1474                 :        1380 :         attnum_offset = 0;
    1475                 :             : 
    1476                 :             :     /*
    1477                 :             :      * Now that we know how many expressions there are, we can offset the
    1478                 :             :      * values just enough to build the bitmapset.
    1479                 :             :      */
    1480         [ +  + ]:        4725 :     for (int i = 0; i < list_length(clauses); i++)
    1481                 :             :     {
    1482                 :             :         AttrNumber  attnum;
    1483                 :             : 
    1484                 :             :         /* ignore incompatible or already estimated clauses */
    1485         [ +  + ]:        3235 :         if (list_attnums[i] == InvalidAttrNumber)
    1486                 :         260 :             continue;
    1487                 :             : 
    1488                 :             :         /* make sure the attnum is in the expected range */
    1489                 :             :         Assert(list_attnums[i] >= (-unique_exprs_cnt));
    1490                 :             :         Assert(list_attnums[i] <= MaxHeapAttributeNumber);
    1491                 :             : 
    1492                 :             :         /* make sure the attnum is positive (valid AttrNumber) */
    1493                 :        2975 :         attnum = list_attnums[i] + attnum_offset;
    1494                 :             : 
    1495                 :             :         /*
    1496                 :             :          * Either it's a regular attribute, or it's an expression, in which
    1497                 :             :          * case we must not have seen it before (expressions are unique).
    1498                 :             :          *
    1499                 :             :          * XXX Check whether it's a regular attribute has to be done using the
    1500                 :             :          * original attnum, while the second check has to use the value with
    1501                 :             :          * an offset.
    1502                 :             :          */
    1503                 :             :         Assert(AttrNumberIsForUserDefinedAttr(list_attnums[i]) ||
    1504                 :             :                !bms_is_member(attnum, clauses_attnums));
    1505                 :             : 
    1506                 :             :         /*
    1507                 :             :          * Remember the offset attnum, both for attributes and expressions.
    1508                 :             :          * We'll pass list_attnums to clauselist_apply_dependencies, which
    1509                 :             :          * uses it to identify clauses in a bitmap. We could also pass the
    1510                 :             :          * offset, but this is more convenient.
    1511                 :             :          */
    1512                 :        2975 :         list_attnums[i] = attnum;
    1513                 :             : 
    1514                 :        2975 :         clauses_attnums = bms_add_member(clauses_attnums, attnum);
    1515                 :             :     }
    1516                 :             : 
    1517                 :             :     /*
    1518                 :             :      * If there's not at least two distinct attnums and expressions, then
    1519                 :             :      * reject the whole list of clauses. We must return 1.0 so the calling
    1520                 :             :      * function's selectivity is unaffected.
    1521                 :             :      */
    1522         [ +  + ]:        1490 :     if (bms_membership(clauses_attnums) != BMS_MULTIPLE)
    1523                 :             :     {
    1524                 :         160 :         bms_free(clauses_attnums);
    1525                 :         160 :         pfree(list_attnums);
    1526                 :         160 :         return 1.0;
    1527                 :             :     }
    1528                 :             : 
    1529                 :             :     /*
    1530                 :             :      * Load all functional dependencies matching at least two parameters. We
    1531                 :             :      * can simply consider all dependencies at once, without having to search
    1532                 :             :      * for the best statistics object.
    1533                 :             :      *
    1534                 :             :      * To not waste cycles and memory, we deserialize dependencies only for
    1535                 :             :      * statistics that match at least two attributes. The array is allocated
    1536                 :             :      * with the assumption that all objects match - we could grow the array to
    1537                 :             :      * make it just the right size, but it's likely wasteful anyway thanks to
    1538                 :             :      * moving the freed chunks to freelists etc.
    1539                 :             :      */
    1540                 :        1330 :     func_dependencies = palloc_array(MVDependencies *, list_length(rel->statlist));
    1541                 :        1330 :     nfunc_dependencies = 0;
    1542                 :        1330 :     total_ndeps = 0;
    1543                 :             : 
    1544   [ +  -  +  +  :        2775 :     foreach(l, rel->statlist)
                   +  + ]
    1545                 :             :     {
    1546                 :        1445 :         StatisticExtInfo *stat = (StatisticExtInfo *) lfirst(l);
    1547                 :             :         int         nmatched;
    1548                 :             :         int         nexprs;
    1549                 :             :         int         k;
    1550                 :             :         MVDependencies *deps;
    1551                 :             : 
    1552                 :             :         /* skip statistics that are not of the correct type */
    1553         [ +  + ]:        1445 :         if (stat->kind != STATS_EXT_DEPENDENCIES)
    1554                 :          90 :             continue;
    1555                 :             : 
    1556                 :             :         /* skip statistics with mismatching stxdinherit value */
    1557         [ -  + ]:        1355 :         if (stat->inherit != rte->inh)
    1558                 :           0 :             continue;
    1559                 :             : 
    1560                 :             :         /*
    1561                 :             :          * Count matching attributes - we have to undo the attnum offsets. The
    1562                 :             :          * input attribute numbers are not offset (expressions are not
    1563                 :             :          * included in stat->keys, so it's not necessary). But we need to
    1564                 :             :          * offset it before checking against clauses_attnums.
    1565                 :             :          */
    1566                 :        1355 :         nmatched = 0;
    1567                 :        1355 :         k = -1;
    1568         [ +  + ]:        5100 :         while ((k = bms_next_member(stat->keys, k)) >= 0)
    1569                 :             :         {
    1570                 :        3745 :             AttrNumber  attnum = (AttrNumber) k;
    1571                 :             : 
    1572                 :             :             /* skip expressions */
    1573         [ -  + ]:        3745 :             if (!AttrNumberIsForUserDefinedAttr(attnum))
    1574                 :           0 :                 continue;
    1575                 :             : 
    1576                 :             :             /* apply the same offset as above */
    1577                 :        3745 :             attnum += attnum_offset;
    1578                 :             : 
    1579         [ +  + ]:        3745 :             if (bms_is_member(attnum, clauses_attnums))
    1580                 :        2700 :                 nmatched++;
    1581                 :             :         }
    1582                 :             : 
    1583                 :             :         /* count matching expressions */
    1584                 :        1355 :         nexprs = 0;
    1585         [ +  + ]:        1570 :         for (int i = 0; i < unique_exprs_cnt; i++)
    1586                 :             :         {
    1587                 :             :             ListCell   *lc;
    1588                 :             : 
    1589   [ +  -  +  +  :         860 :             foreach(lc, stat->exprs)
                   +  + ]
    1590                 :             :             {
    1591                 :         645 :                 Node       *stat_expr = (Node *) lfirst(lc);
    1592                 :             : 
    1593                 :             :                 /* try to match it */
    1594         [ +  + ]:         645 :                 if (equal(stat_expr, unique_exprs[i]))
    1595                 :         215 :                     nexprs++;
    1596                 :             :             }
    1597                 :             :         }
    1598                 :             : 
    1599                 :             :         /*
    1600                 :             :          * Skip objects matching fewer than two attributes/expressions from
    1601                 :             :          * clauses.
    1602                 :             :          */
    1603         [ +  + ]:        1355 :         if (nmatched + nexprs < 2)
    1604                 :          15 :             continue;
    1605                 :             : 
    1606                 :        1340 :         deps = statext_dependencies_load(stat->statOid, rte->inh);
    1607                 :             : 
    1608                 :             :         /*
    1609                 :             :          * The expressions may be represented by different attnums in the
    1610                 :             :          * stats, we need to remap them to be consistent with the clauses.
    1611                 :             :          * That will make the later steps (e.g. picking the strongest item and
    1612                 :             :          * so on) much simpler and cheaper, because it won't need to care
    1613                 :             :          * about the offset at all.
    1614                 :             :          *
    1615                 :             :          * When we're at it, we can ignore dependencies that are not fully
    1616                 :             :          * matched by clauses (i.e. referencing attributes or expressions that
    1617                 :             :          * are not in the clauses).
    1618                 :             :          *
    1619                 :             :          * We have to do this for all statistics, as long as there are any
    1620                 :             :          * expressions - we need to shift the attnums in all dependencies.
    1621                 :             :          *
    1622                 :             :          * XXX Maybe we should do this always, because it also eliminates some
    1623                 :             :          * of the dependencies early. It might be cheaper than having to walk
    1624                 :             :          * the longer list in find_strongest_dependency later, especially as
    1625                 :             :          * we need to do that repeatedly?
    1626                 :             :          *
    1627                 :             :          * XXX We have to do this even when there are no expressions in
    1628                 :             :          * clauses, otherwise find_strongest_dependency may fail for stats
    1629                 :             :          * with expressions (due to lookup of negative value in bitmap). So we
    1630                 :             :          * need to at least filter out those dependencies. Maybe we could do
    1631                 :             :          * it in a cheaper way (if there are no expr clauses, we can just
    1632                 :             :          * discard all negative attnums without any lookups).
    1633                 :             :          */
    1634   [ +  +  -  + ]:        1340 :         if (unique_exprs_cnt > 0 || stat->exprs != NIL)
    1635                 :             :         {
    1636                 :          90 :             uint32      ndeps = 0;
    1637                 :             : 
    1638         [ +  + ]:         540 :             for (uint32 i = 0; i < deps->ndeps; i++)
    1639                 :             :             {
    1640                 :         450 :                 bool        skip = false;
    1641                 :         450 :                 MVDependency *dep = deps->deps[i];
    1642                 :             : 
    1643         [ +  + ]:        1255 :                 for (int j = 0; j < dep->nattributes; j++)
    1644                 :             :                 {
    1645                 :             :                     int         idx;
    1646                 :             :                     Node       *expr;
    1647                 :        1025 :                     AttrNumber  unique_attnum = InvalidAttrNumber;
    1648                 :             :                     AttrNumber  attnum;
    1649                 :             : 
    1650                 :             :                     /* undo the per-statistics offset */
    1651                 :        1025 :                     attnum = dep->attributes[j];
    1652                 :             : 
    1653                 :             :                     /*
    1654                 :             :                      * For regular attributes we can simply check if it
    1655                 :             :                      * matches any clause. If there's no matching clause, we
    1656                 :             :                      * can just ignore it. We need to offset the attnum
    1657                 :             :                      * though.
    1658                 :             :                      */
    1659         [ -  + ]:        1025 :                     if (AttrNumberIsForUserDefinedAttr(attnum))
    1660                 :             :                     {
    1661                 :           0 :                         dep->attributes[j] = attnum + attnum_offset;
    1662                 :             : 
    1663         [ #  # ]:           0 :                         if (!bms_is_member(dep->attributes[j], clauses_attnums))
    1664                 :             :                         {
    1665                 :           0 :                             skip = true;
    1666                 :           0 :                             break;
    1667                 :             :                         }
    1668                 :             : 
    1669                 :           0 :                         continue;
    1670                 :             :                     }
    1671                 :             : 
    1672                 :             :                     /*
    1673                 :             :                      * the attnum should be a valid system attnum (-1, -2,
    1674                 :             :                      * ...)
    1675                 :             :                      */
    1676                 :             :                     Assert(AttributeNumberIsValid(attnum));
    1677                 :             : 
    1678                 :             :                     /*
    1679                 :             :                      * For expressions, we need to do two translations. First
    1680                 :             :                      * we have to translate the negative attnum to index in
    1681                 :             :                      * the list of expressions (in the statistics object).
    1682                 :             :                      * Then we need to see if there's a matching clause. The
    1683                 :             :                      * index of the unique expression determines the attnum
    1684                 :             :                      * (and we offset it).
    1685                 :             :                      */
    1686                 :        1025 :                     idx = -(1 + attnum);
    1687                 :             : 
    1688                 :             :                     /* Is the expression index is valid? */
    1689                 :             :                     Assert((idx >= 0) && (idx < list_length(stat->exprs)));
    1690                 :             : 
    1691                 :        1025 :                     expr = (Node *) list_nth(stat->exprs, idx);
    1692                 :             : 
    1693                 :             :                     /* try to find the expression in the unique list */
    1694         [ +  + ]:        2050 :                     for (int m = 0; m < unique_exprs_cnt; m++)
    1695                 :             :                     {
    1696                 :             :                         /*
    1697                 :             :                          * found a matching unique expression, use the attnum
    1698                 :             :                          * (derived from index of the unique expression)
    1699                 :             :                          */
    1700         [ +  + ]:        1830 :                         if (equal(unique_exprs[m], expr))
    1701                 :             :                         {
    1702                 :         805 :                             unique_attnum = -(m + 1) + attnum_offset;
    1703                 :         805 :                             break;
    1704                 :             :                         }
    1705                 :             :                     }
    1706                 :             : 
    1707                 :             :                     /*
    1708                 :             :                      * Found no matching expression, so we can simply skip
    1709                 :             :                      * this dependency, because there's no chance it will be
    1710                 :             :                      * fully covered.
    1711                 :             :                      */
    1712         [ +  + ]:        1025 :                     if (unique_attnum == InvalidAttrNumber)
    1713                 :             :                     {
    1714                 :         220 :                         skip = true;
    1715                 :         220 :                         break;
    1716                 :             :                     }
    1717                 :             : 
    1718                 :             :                     /* otherwise remap it to the new attnum */
    1719                 :         805 :                     dep->attributes[j] = unique_attnum;
    1720                 :             :                 }
    1721                 :             : 
    1722                 :             :                 /* if found a matching dependency, keep it */
    1723         [ +  + ]:         450 :                 if (!skip)
    1724                 :             :                 {
    1725                 :             :                     /* maybe we've skipped something earlier, so move it */
    1726         [ -  + ]:         230 :                     if (ndeps != i)
    1727                 :           0 :                         deps->deps[ndeps] = deps->deps[i];
    1728                 :             : 
    1729                 :         230 :                     ndeps++;
    1730                 :             :                 }
    1731                 :             :             }
    1732                 :             : 
    1733                 :          90 :             deps->ndeps = ndeps;
    1734                 :             :         }
    1735                 :             : 
    1736                 :             :         /*
    1737                 :             :          * It's possible we've removed all dependencies, in which case we
    1738                 :             :          * don't bother adding it to the list.
    1739                 :             :          */
    1740         [ +  - ]:        1340 :         if (deps->ndeps > 0)
    1741                 :             :         {
    1742                 :        1340 :             func_dependencies[nfunc_dependencies] = deps;
    1743                 :        1340 :             total_ndeps += deps->ndeps;
    1744                 :        1340 :             nfunc_dependencies++;
    1745                 :             :         }
    1746                 :             :     }
    1747                 :             : 
    1748                 :             :     /* if no matching stats could be found then we've nothing to do */
    1749         [ -  + ]:        1330 :     if (nfunc_dependencies == 0)
    1750                 :             :     {
    1751                 :           0 :         pfree(func_dependencies);
    1752                 :           0 :         bms_free(clauses_attnums);
    1753                 :           0 :         pfree(list_attnums);
    1754                 :           0 :         pfree(unique_exprs);
    1755                 :           0 :         return 1.0;
    1756                 :             :     }
    1757                 :             : 
    1758                 :             :     /*
    1759                 :             :      * Work out which dependencies we can apply, starting with the
    1760                 :             :      * widest/strongest ones, and proceeding to smaller/weaker ones.
    1761                 :             :      */
    1762                 :        1330 :     dependencies = palloc_array(MVDependency *, total_ndeps);
    1763                 :        1330 :     ndependencies = 0;
    1764                 :             : 
    1765                 :             :     while (true)
    1766                 :        1575 :     {
    1767                 :             :         MVDependency *dependency;
    1768                 :             :         AttrNumber  attnum;
    1769                 :             : 
    1770                 :             :         /* the widest/strongest dependency, fully matched by clauses */
    1771                 :        2905 :         dependency = find_strongest_dependency(func_dependencies,
    1772                 :             :                                                nfunc_dependencies,
    1773                 :             :                                                clauses_attnums);
    1774         [ +  + ]:        2905 :         if (!dependency)
    1775                 :        1330 :             break;
    1776                 :             : 
    1777                 :        1575 :         dependencies[ndependencies++] = dependency;
    1778                 :             : 
    1779                 :             :         /* Ignore dependencies using this implied attribute in later loops */
    1780                 :        1575 :         attnum = dependency->attributes[dependency->nattributes - 1];
    1781                 :        1575 :         clauses_attnums = bms_del_member(clauses_attnums, attnum);
    1782                 :             :     }
    1783                 :             : 
    1784                 :             :     /*
    1785                 :             :      * If we found applicable dependencies, use them to estimate all
    1786                 :             :      * compatible clauses on attributes that they refer to.
    1787                 :             :      */
    1788         [ +  - ]:        1330 :     if (ndependencies != 0)
    1789                 :        1330 :         s1 = clauselist_apply_dependencies(root, clauses, varRelid, jointype,
    1790                 :             :                                            sjinfo, dependencies, ndependencies,
    1791                 :             :                                            list_attnums, estimatedclauses);
    1792                 :             : 
    1793                 :             :     /* free deserialized functional dependencies (and then the array) */
    1794         [ +  + ]:        2670 :     for (int i = 0; i < nfunc_dependencies; i++)
    1795                 :        1340 :         pfree(func_dependencies[i]);
    1796                 :             : 
    1797                 :        1330 :     pfree(dependencies);
    1798                 :        1330 :     pfree(func_dependencies);
    1799                 :        1330 :     bms_free(clauses_attnums);
    1800                 :        1330 :     pfree(list_attnums);
    1801                 :        1330 :     pfree(unique_exprs);
    1802                 :             : 
    1803                 :        1330 :     return s1;
    1804                 :             : }
        

Generated by: LCOV version 2.0-1