LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 88.6 % 2615 2318
Test Date: 2026-07-09 07:15:34 Functions: 96.3 % 82 79
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 77.0 % 1995 1537

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * selfuncs.c
       4                 :             :  *    Selectivity functions and index cost estimation functions for
       5                 :             :  *    standard operators and index access methods.
       6                 :             :  *
       7                 :             :  *    Selectivity routines are registered in the pg_operator catalog
       8                 :             :  *    in the "oprrest" and "oprjoin" attributes.
       9                 :             :  *
      10                 :             :  *    Index cost functions are located via the index AM's API struct,
      11                 :             :  *    which is obtained from the handler function registered in pg_am.
      12                 :             :  *
      13                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      14                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      15                 :             :  *
      16                 :             :  *
      17                 :             :  * IDENTIFICATION
      18                 :             :  *    src/backend/utils/adt/selfuncs.c
      19                 :             :  *
      20                 :             :  *-------------------------------------------------------------------------
      21                 :             :  */
      22                 :             : 
      23                 :             : /*----------
      24                 :             :  * Operator selectivity estimation functions are called to estimate the
      25                 :             :  * selectivity of WHERE clauses whose top-level operator is their operator.
      26                 :             :  * We divide the problem into two cases:
      27                 :             :  *      Restriction clause estimation: the clause involves vars of just
      28                 :             :  *          one relation.
      29                 :             :  *      Join clause estimation: the clause involves vars of multiple rels.
      30                 :             :  * Join selectivity estimation is far more difficult and usually less accurate
      31                 :             :  * than restriction estimation.
      32                 :             :  *
      33                 :             :  * When dealing with the inner scan of a nestloop join, we consider the
      34                 :             :  * join's joinclauses as restriction clauses for the inner relation, and
      35                 :             :  * treat vars of the outer relation as parameters (a/k/a constants of unknown
      36                 :             :  * values).  So, restriction estimators need to be able to accept an argument
      37                 :             :  * telling which relation is to be treated as the variable.
      38                 :             :  *
      39                 :             :  * The call convention for a restriction estimator (oprrest function) is
      40                 :             :  *
      41                 :             :  *      Selectivity oprrest (PlannerInfo *root,
      42                 :             :  *                           Oid operator,
      43                 :             :  *                           List *args,
      44                 :             :  *                           int varRelid);
      45                 :             :  *
      46                 :             :  * root: general information about the query (rtable and RelOptInfo lists
      47                 :             :  * are particularly important for the estimator).
      48                 :             :  * operator: OID of the specific operator in question.
      49                 :             :  * args: argument list from the operator clause.
      50                 :             :  * varRelid: if not zero, the relid (rtable index) of the relation to
      51                 :             :  * be treated as the variable relation.  May be zero if the args list
      52                 :             :  * is known to contain vars of only one relation.
      53                 :             :  *
      54                 :             :  * This is represented at the SQL level (in pg_proc) as
      55                 :             :  *
      56                 :             :  *      float8 oprrest (internal, oid, internal, int4);
      57                 :             :  *
      58                 :             :  * The result is a selectivity, that is, a fraction (0 to 1) of the rows
      59                 :             :  * of the relation that are expected to produce a TRUE result for the
      60                 :             :  * given operator.
      61                 :             :  *
      62                 :             :  * The call convention for a join estimator (oprjoin function) is similar
      63                 :             :  * except that varRelid is not needed, and instead join information is
      64                 :             :  * supplied:
      65                 :             :  *
      66                 :             :  *      Selectivity oprjoin (PlannerInfo *root,
      67                 :             :  *                           Oid operator,
      68                 :             :  *                           List *args,
      69                 :             :  *                           JoinType jointype,
      70                 :             :  *                           SpecialJoinInfo *sjinfo);
      71                 :             :  *
      72                 :             :  *      float8 oprjoin (internal, oid, internal, int2, internal);
      73                 :             :  *
      74                 :             :  * (Before Postgres 8.4, join estimators had only the first four of these
      75                 :             :  * parameters.  That signature is still allowed, but deprecated.)  The
      76                 :             :  * relationship between jointype and sjinfo is explained in the comments for
      77                 :             :  * clause_selectivity() --- the short version is that jointype is usually
      78                 :             :  * best ignored in favor of examining sjinfo.
      79                 :             :  *
      80                 :             :  * Join selectivity for regular inner and outer joins is defined as the
      81                 :             :  * fraction (0 to 1) of the cross product of the relations that is expected
      82                 :             :  * to produce a TRUE result for the given operator.  For both semi and anti
      83                 :             :  * joins, however, the selectivity is defined as the fraction of the left-hand
      84                 :             :  * side relation's rows that are expected to have a match (ie, at least one
      85                 :             :  * row with a TRUE result) in the right-hand side.
      86                 :             :  *
      87                 :             :  * For both oprrest and oprjoin functions, the operator's input collation OID
      88                 :             :  * (if any) is passed using the standard fmgr mechanism, so that the estimator
      89                 :             :  * function can fetch it with PG_GET_COLLATION().  Note, however, that all
      90                 :             :  * statistics in pg_statistic are currently built using the relevant column's
      91                 :             :  * collation.
      92                 :             :  *----------
      93                 :             :  */
      94                 :             : 
      95                 :             : #include "postgres.h"
      96                 :             : 
      97                 :             : #include <ctype.h>
      98                 :             : #include <math.h>
      99                 :             : 
     100                 :             : #include "access/brin.h"
     101                 :             : #include "access/brin_page.h"
     102                 :             : #include "access/gin.h"
     103                 :             : #include "access/table.h"
     104                 :             : #include "access/tableam.h"
     105                 :             : #include "access/visibilitymap.h"
     106                 :             : #include "catalog/pg_collation.h"
     107                 :             : #include "catalog/pg_operator.h"
     108                 :             : #include "catalog/pg_statistic.h"
     109                 :             : #include "catalog/pg_statistic_ext.h"
     110                 :             : #include "executor/nodeAgg.h"
     111                 :             : #include "miscadmin.h"
     112                 :             : #include "nodes/makefuncs.h"
     113                 :             : #include "nodes/nodeFuncs.h"
     114                 :             : #include "optimizer/clauses.h"
     115                 :             : #include "optimizer/cost.h"
     116                 :             : #include "optimizer/optimizer.h"
     117                 :             : #include "optimizer/pathnode.h"
     118                 :             : #include "optimizer/paths.h"
     119                 :             : #include "optimizer/plancat.h"
     120                 :             : #include "parser/parse_clause.h"
     121                 :             : #include "parser/parse_relation.h"
     122                 :             : #include "parser/parsetree.h"
     123                 :             : #include "rewrite/rewriteManip.h"
     124                 :             : #include "statistics/statistics.h"
     125                 :             : #include "storage/bufmgr.h"
     126                 :             : #include "utils/acl.h"
     127                 :             : #include "utils/array.h"
     128                 :             : #include "utils/builtins.h"
     129                 :             : #include "utils/date.h"
     130                 :             : #include "utils/datum.h"
     131                 :             : #include "utils/fmgroids.h"
     132                 :             : #include "utils/index_selfuncs.h"
     133                 :             : #include "utils/lsyscache.h"
     134                 :             : #include "utils/memutils.h"
     135                 :             : #include "utils/pg_locale.h"
     136                 :             : #include "utils/rel.h"
     137                 :             : #include "utils/selfuncs.h"
     138                 :             : #include "utils/snapmgr.h"
     139                 :             : #include "utils/spccache.h"
     140                 :             : #include "utils/syscache.h"
     141                 :             : #include "utils/timestamp.h"
     142                 :             : #include "utils/typcache.h"
     143                 :             : 
     144                 :             : #define DEFAULT_PAGE_CPU_MULTIPLIER 50.0
     145                 :             : 
     146                 :             : /*
     147                 :             :  * In production builds, switch to hash-based MCV matching when the lists are
     148                 :             :  * large enough to amortize hash setup cost.  (This threshold is compared to
     149                 :             :  * the sum of the lengths of the two MCV lists.  This is simplistic but seems
     150                 :             :  * to work well enough.)  In debug builds, we use a smaller threshold so that
     151                 :             :  * the regression tests cover both paths well.
     152                 :             :  */
     153                 :             : #ifndef USE_ASSERT_CHECKING
     154                 :             : #define EQJOINSEL_MCV_HASH_THRESHOLD 200
     155                 :             : #else
     156                 :             : #define EQJOINSEL_MCV_HASH_THRESHOLD 20
     157                 :             : #endif
     158                 :             : 
     159                 :             : /* Entries in the simplehash hash table used by eqjoinsel_find_matches */
     160                 :             : typedef struct MCVHashEntry
     161                 :             : {
     162                 :             :     Datum       value;          /* the value represented by this entry */
     163                 :             :     int         index;          /* its index in the relevant AttStatsSlot */
     164                 :             :     uint32      hash;           /* hash code for the Datum */
     165                 :             :     char        status;         /* status code used by simplehash.h */
     166                 :             : } MCVHashEntry;
     167                 :             : 
     168                 :             : /* private_data for the simplehash hash table */
     169                 :             : typedef struct MCVHashContext
     170                 :             : {
     171                 :             :     FunctionCallInfo equal_fcinfo;  /* the equality join operator */
     172                 :             :     FunctionCallInfo hash_fcinfo;   /* the hash function to use */
     173                 :             :     bool        op_is_reversed; /* equality compares hash type to probe type */
     174                 :             :     bool        insert_mode;    /* doing inserts or lookups? */
     175                 :             :     bool        hash_typbyval;  /* typbyval of hashed data type */
     176                 :             :     int16       hash_typlen;    /* typlen of hashed data type */
     177                 :             : } MCVHashContext;
     178                 :             : 
     179                 :             : /* forward reference */
     180                 :             : typedef struct MCVHashTable_hash MCVHashTable_hash;
     181                 :             : 
     182                 :             : /* Hooks for plugins to get control when we ask for stats */
     183                 :             : get_relation_stats_hook_type get_relation_stats_hook = NULL;
     184                 :             : get_index_stats_hook_type get_index_stats_hook = NULL;
     185                 :             : 
     186                 :             : static double eqsel_internal(PG_FUNCTION_ARGS, bool negate);
     187                 :             : static double eqjoinsel_inner(FmgrInfo *eqproc, Oid collation,
     188                 :             :                               Oid hashLeft, Oid hashRight,
     189                 :             :                               VariableStatData *vardata1, VariableStatData *vardata2,
     190                 :             :                               double nd1, double nd2,
     191                 :             :                               bool isdefault1, bool isdefault2,
     192                 :             :                               AttStatsSlot *sslot1, AttStatsSlot *sslot2,
     193                 :             :                               Form_pg_statistic stats1, Form_pg_statistic stats2,
     194                 :             :                               bool have_mcvs1, bool have_mcvs2,
     195                 :             :                               bool *hasmatch1, bool *hasmatch2,
     196                 :             :                               int *p_nmatches);
     197                 :             : static double eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
     198                 :             :                              Oid hashLeft, Oid hashRight,
     199                 :             :                              bool op_is_reversed,
     200                 :             :                              VariableStatData *vardata1, VariableStatData *vardata2,
     201                 :             :                              double nd1, double nd2,
     202                 :             :                              bool isdefault1, bool isdefault2,
     203                 :             :                              AttStatsSlot *sslot1, AttStatsSlot *sslot2,
     204                 :             :                              Form_pg_statistic stats1, Form_pg_statistic stats2,
     205                 :             :                              bool have_mcvs1, bool have_mcvs2,
     206                 :             :                              bool *hasmatch1, bool *hasmatch2,
     207                 :             :                              int *p_nmatches,
     208                 :             :                              RelOptInfo *inner_rel);
     209                 :             : static void eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
     210                 :             :                                    Oid hashLeft, Oid hashRight,
     211                 :             :                                    bool op_is_reversed,
     212                 :             :                                    AttStatsSlot *sslot1, AttStatsSlot *sslot2,
     213                 :             :                                    int nvalues1, int nvalues2,
     214                 :             :                                    bool *hasmatch1, bool *hasmatch2,
     215                 :             :                                    int *p_nmatches, double *p_matchprodfreq);
     216                 :             : static uint32 hash_mcv(MCVHashTable_hash *tab, Datum key);
     217                 :             : static bool mcvs_equal(MCVHashTable_hash *tab, Datum key0, Datum key1);
     218                 :             : static bool estimate_multivariate_ndistinct(PlannerInfo *root,
     219                 :             :                                             RelOptInfo *rel, List **varinfos, double *ndistinct);
     220                 :             : static bool convert_to_scalar(Datum value, Oid valuetypid, Oid collid,
     221                 :             :                               double *scaledvalue,
     222                 :             :                               Datum lobound, Datum hibound, Oid boundstypid,
     223                 :             :                               double *scaledlobound, double *scaledhibound);
     224                 :             : static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure);
     225                 :             : static void convert_string_to_scalar(char *value,
     226                 :             :                                      double *scaledvalue,
     227                 :             :                                      char *lobound,
     228                 :             :                                      double *scaledlobound,
     229                 :             :                                      char *hibound,
     230                 :             :                                      double *scaledhibound);
     231                 :             : static void convert_bytea_to_scalar(Datum value,
     232                 :             :                                     double *scaledvalue,
     233                 :             :                                     Datum lobound,
     234                 :             :                                     double *scaledlobound,
     235                 :             :                                     Datum hibound,
     236                 :             :                                     double *scaledhibound);
     237                 :             : static double convert_one_string_to_scalar(char *value,
     238                 :             :                                            int rangelo, int rangehi);
     239                 :             : static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
     240                 :             :                                           int rangelo, int rangehi);
     241                 :             : static char *convert_string_datum(Datum value, Oid typid, Oid collid,
     242                 :             :                                   bool *failure);
     243                 :             : static double convert_timevalue_to_scalar(Datum value, Oid typid,
     244                 :             :                                           bool *failure);
     245                 :             : static Node *strip_all_phvs_deep(PlannerInfo *root, Node *node);
     246                 :             : static bool contain_placeholder_walker(Node *node, void *context);
     247                 :             : static Node *strip_all_phvs_mutator(Node *node, void *context);
     248                 :             : static void examine_simple_variable(PlannerInfo *root, Var *var,
     249                 :             :                                     VariableStatData *vardata);
     250                 :             : static void adjust_statstuple_for_grouping(PlannerInfo *subroot, Var *var,
     251                 :             :                                            VariableStatData *vardata);
     252                 :             : static void examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
     253                 :             :                                       int indexcol, VariableStatData *vardata);
     254                 :             : static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
     255                 :             :                                Oid sortop, Oid collation,
     256                 :             :                                Datum *min, Datum *max);
     257                 :             : static void get_stats_slot_range(AttStatsSlot *sslot,
     258                 :             :                                  Oid opfuncoid, FmgrInfo *opproc,
     259                 :             :                                  Oid collation, int16 typLen, bool typByVal,
     260                 :             :                                  Datum *min, Datum *max, bool *p_have_data);
     261                 :             : static bool get_actual_variable_range(PlannerInfo *root,
     262                 :             :                                       VariableStatData *vardata,
     263                 :             :                                       Oid sortop, Oid collation,
     264                 :             :                                       Datum *min, Datum *max);
     265                 :             : static bool get_actual_variable_endpoint(Relation heapRel,
     266                 :             :                                          Relation indexRel,
     267                 :             :                                          ScanDirection indexscandir,
     268                 :             :                                          ScanKey scankeys,
     269                 :             :                                          int16 typLen,
     270                 :             :                                          bool typByVal,
     271                 :             :                                          TupleTableSlot *tableslot,
     272                 :             :                                          MemoryContext outercontext,
     273                 :             :                                          Datum *endpointDatum);
     274                 :             : static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
     275                 :             : static double btcost_correlation(IndexOptInfo *index,
     276                 :             :                                  VariableStatData *vardata);
     277                 :             : 
     278                 :             : /* Define support routines for MCV hash tables */
     279                 :             : #define SH_PREFIX               MCVHashTable
     280                 :             : #define SH_ELEMENT_TYPE         MCVHashEntry
     281                 :             : #define SH_KEY_TYPE             Datum
     282                 :             : #define SH_KEY                  value
     283                 :             : #define SH_HASH_KEY(tab,key)    hash_mcv(tab, key)
     284                 :             : #define SH_EQUAL(tab,key0,key1) mcvs_equal(tab, key0, key1)
     285                 :             : #define SH_SCOPE                static inline
     286                 :             : #define SH_STORE_HASH
     287                 :             : #define SH_GET_HASH(tab,ent)    (ent)->hash
     288                 :             : #define SH_DEFINE
     289                 :             : #define SH_DECLARE
     290                 :             : #include "lib/simplehash.h"
     291                 :             : 
     292                 :             : 
     293                 :             : /*
     294                 :             :  *      eqsel           - Selectivity of "=" for any data types.
     295                 :             :  *
     296                 :             :  * Note: this routine is also used to estimate selectivity for some
     297                 :             :  * operators that are not "=" but have comparable selectivity behavior,
     298                 :             :  * such as "~=" (geometric approximate-match).  Even for "=", we must
     299                 :             :  * keep in mind that the left and right datatypes may differ.
     300                 :             :  */
     301                 :             : Datum
     302                 :      541656 : eqsel(PG_FUNCTION_ARGS)
     303                 :             : {
     304                 :      541656 :     PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
     305                 :             : }
     306                 :             : 
     307                 :             : /*
     308                 :             :  * Common code for eqsel() and neqsel()
     309                 :             :  */
     310                 :             : static double
     311                 :      571912 : eqsel_internal(PG_FUNCTION_ARGS, bool negate)
     312                 :             : {
     313                 :      571912 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
     314                 :      571912 :     Oid         operator = PG_GETARG_OID(1);
     315                 :      571912 :     List       *args = (List *) PG_GETARG_POINTER(2);
     316                 :      571912 :     int         varRelid = PG_GETARG_INT32(3);
     317                 :      571912 :     Oid         collation = PG_GET_COLLATION();
     318                 :             :     VariableStatData vardata;
     319                 :             :     Node       *other;
     320                 :             :     bool        varonleft;
     321                 :             :     double      selec;
     322                 :             : 
     323                 :             :     /*
     324                 :             :      * When asked about <>, we do the estimation using the corresponding =
     325                 :             :      * operator, then convert to <> via "1.0 - eq_selectivity - nullfrac".
     326                 :             :      */
     327         [ +  + ]:      571912 :     if (negate)
     328                 :             :     {
     329                 :       30256 :         operator = get_negator(operator);
     330         [ -  + ]:       30256 :         if (!OidIsValid(operator))
     331                 :             :         {
     332                 :             :             /* Use default selectivity (should we raise an error instead?) */
     333                 :           0 :             return 1.0 - DEFAULT_EQ_SEL;
     334                 :             :         }
     335                 :             :     }
     336                 :             : 
     337                 :             :     /*
     338                 :             :      * If expression is not variable = something or something = variable, then
     339                 :             :      * punt and return a default estimate.
     340                 :             :      */
     341         [ +  + ]:      571912 :     if (!get_restriction_variable(root, args, varRelid,
     342                 :             :                                   &vardata, &other, &varonleft))
     343         [ +  + ]:        3345 :         return negate ? (1.0 - DEFAULT_EQ_SEL) : DEFAULT_EQ_SEL;
     344                 :             : 
     345                 :             :     /*
     346                 :             :      * We can do a lot better if the something is a constant.  (Note: the
     347                 :             :      * Const might result from estimation rather than being a simple constant
     348                 :             :      * in the query.)
     349                 :             :      */
     350         [ +  + ]:      568563 :     if (IsA(other, Const))
     351                 :      221451 :         selec = var_eq_const(&vardata, operator, collation,
     352                 :      221451 :                              ((Const *) other)->constvalue,
     353                 :      221451 :                              ((Const *) other)->constisnull,
     354                 :             :                              varonleft, negate);
     355                 :             :     else
     356                 :      347112 :         selec = var_eq_non_const(&vardata, operator, collation, other,
     357                 :             :                                  varonleft, negate);
     358                 :             : 
     359         [ +  + ]:      568563 :     ReleaseVariableStats(vardata);
     360                 :             : 
     361                 :      568563 :     return selec;
     362                 :             : }
     363                 :             : 
     364                 :             : /*
     365                 :             :  * var_eq_const --- eqsel for var = const case
     366                 :             :  *
     367                 :             :  * This is exported so that some other estimation functions can use it.
     368                 :             :  */
     369                 :             : double
     370                 :      250239 : var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
     371                 :             :              Datum constval, bool constisnull,
     372                 :             :              bool varonleft, bool negate)
     373                 :             : {
     374                 :             :     double      selec;
     375                 :      250239 :     double      nullfrac = 0.0;
     376                 :             :     bool        isdefault;
     377                 :             :     Oid         opfuncoid;
     378                 :             : 
     379                 :             :     /*
     380                 :             :      * If the constant is NULL, assume operator is strict and return zero, ie,
     381                 :             :      * operator will never return TRUE.  (It's zero even for a negator op.)
     382                 :             :      */
     383         [ +  + ]:      250239 :     if (constisnull)
     384                 :         271 :         return 0.0;
     385                 :             : 
     386                 :             :     /*
     387                 :             :      * Grab the nullfrac for use below.  Note we allow use of nullfrac
     388                 :             :      * regardless of security check.
     389                 :             :      */
     390         [ +  + ]:      249968 :     if (HeapTupleIsValid(vardata->statsTuple))
     391                 :             :     {
     392                 :             :         Form_pg_statistic stats;
     393                 :             : 
     394                 :      176351 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     395                 :      176351 :         nullfrac = stats->stanullfrac;
     396                 :             :     }
     397                 :             : 
     398                 :             :     /*
     399                 :             :      * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
     400                 :             :      * assume there is exactly one match regardless of anything else.  (This
     401                 :             :      * is slightly bogus, since the index or clause's equality operator might
     402                 :             :      * be different from ours, but it's much more likely to be right than
     403                 :             :      * ignoring the information.)
     404                 :             :      */
     405   [ +  +  +  -  :      249968 :     if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
                   +  + ]
     406                 :             :     {
     407                 :       51370 :         selec = 1.0 / vardata->rel->tuples;
     408                 :             :     }
     409   [ +  +  +  - ]:      333118 :     else if (HeapTupleIsValid(vardata->statsTuple) &&
     410                 :      134520 :              statistic_proc_security_check(vardata,
     411                 :      134520 :                                            (opfuncoid = get_opcode(oproid))))
     412                 :      134520 :     {
     413                 :             :         AttStatsSlot sslot;
     414                 :      134520 :         bool        match = false;
     415                 :             :         int         i;
     416                 :             : 
     417                 :             :         /*
     418                 :             :          * Is the constant "=" to any of the column's most common values?
     419                 :             :          * (Although the given operator may not really be "=", we will assume
     420                 :             :          * that seeing whether it returns TRUE is an appropriate test.  If you
     421                 :             :          * don't like this, maybe you shouldn't be using eqsel for your
     422                 :             :          * operator...)
     423                 :             :          */
     424         [ +  + ]:      134520 :         if (get_attstatsslot(&sslot, vardata->statsTuple,
     425                 :             :                              STATISTIC_KIND_MCV, InvalidOid,
     426                 :             :                              ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
     427                 :             :         {
     428                 :      117713 :             LOCAL_FCINFO(fcinfo, 2);
     429                 :             :             FmgrInfo    eqproc;
     430                 :             : 
     431                 :      117713 :             fmgr_info(opfuncoid, &eqproc);
     432                 :             : 
     433                 :             :             /*
     434                 :             :              * Save a few cycles by setting up the fcinfo struct just once.
     435                 :             :              * Using FunctionCallInvoke directly also avoids failure if the
     436                 :             :              * eqproc returns NULL, though really equality functions should
     437                 :             :              * never do that.
     438                 :             :              */
     439                 :      117713 :             InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
     440                 :             :                                      NULL, NULL);
     441                 :      117713 :             fcinfo->args[0].isnull = false;
     442                 :      117713 :             fcinfo->args[1].isnull = false;
     443                 :             :             /* be careful to apply operator right way 'round */
     444         [ +  + ]:      117713 :             if (varonleft)
     445                 :      117687 :                 fcinfo->args[1].value = constval;
     446                 :             :             else
     447                 :          26 :                 fcinfo->args[0].value = constval;
     448                 :             : 
     449         [ +  + ]:     2050356 :             for (i = 0; i < sslot.nvalues; i++)
     450                 :             :             {
     451                 :             :                 Datum       fresult;
     452                 :             : 
     453         [ +  + ]:     1991230 :                 if (varonleft)
     454                 :     1991184 :                     fcinfo->args[0].value = sslot.values[i];
     455                 :             :                 else
     456                 :          46 :                     fcinfo->args[1].value = sslot.values[i];
     457                 :     1991230 :                 fcinfo->isnull = false;
     458                 :     1991230 :                 fresult = FunctionCallInvoke(fcinfo);
     459   [ +  -  +  + ]:     1991230 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
     460                 :             :                 {
     461                 :       58587 :                     match = true;
     462                 :       58587 :                     break;
     463                 :             :                 }
     464                 :             :             }
     465                 :             :         }
     466                 :             :         else
     467                 :             :         {
     468                 :             :             /* no most-common-value info available */
     469                 :       16807 :             i = 0;              /* keep compiler quiet */
     470                 :             :         }
     471                 :             : 
     472         [ +  + ]:      134520 :         if (match)
     473                 :             :         {
     474                 :             :             /*
     475                 :             :              * Constant is "=" to this common value.  We know selectivity
     476                 :             :              * exactly (or as exactly as ANALYZE could calculate it, anyway).
     477                 :             :              */
     478                 :       58587 :             selec = sslot.numbers[i];
     479                 :             :         }
     480                 :             :         else
     481                 :             :         {
     482                 :             :             /*
     483                 :             :              * Comparison is against a constant that is neither NULL nor any
     484                 :             :              * of the common values.  Its selectivity cannot be more than
     485                 :             :              * this:
     486                 :             :              */
     487                 :       75933 :             double      sumcommon = 0.0;
     488                 :             :             double      otherdistinct;
     489                 :             : 
     490         [ +  + ]:     1755084 :             for (i = 0; i < sslot.nnumbers; i++)
     491                 :     1679151 :                 sumcommon += sslot.numbers[i];
     492                 :       75933 :             selec = 1.0 - sumcommon - nullfrac;
     493   [ +  +  -  + ]:       75933 :             CLAMP_PROBABILITY(selec);
     494                 :             : 
     495                 :             :             /*
     496                 :             :              * and in fact it's probably a good deal less. We approximate that
     497                 :             :              * all the not-common values share this remaining fraction
     498                 :             :              * equally, so we divide by the number of other distinct values.
     499                 :             :              */
     500                 :       75933 :             otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
     501                 :       75933 :                 sslot.nnumbers;
     502         [ +  + ]:       75933 :             if (otherdistinct > 1)
     503                 :       38364 :                 selec /= otherdistinct;
     504                 :             : 
     505                 :             :             /*
     506                 :             :              * Another cross-check: selectivity shouldn't be estimated as more
     507                 :             :              * than the least common "most common value".
     508                 :             :              */
     509   [ +  +  -  + ]:       75933 :             if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
     510                 :           0 :                 selec = sslot.numbers[sslot.nnumbers - 1];
     511                 :             :         }
     512                 :             : 
     513                 :      134520 :         free_attstatsslot(&sslot);
     514                 :             :     }
     515                 :             :     else
     516                 :             :     {
     517                 :             :         /*
     518                 :             :          * No ANALYZE stats available, so make a guess using estimated number
     519                 :             :          * of distinct values and assuming they are equally common. (The guess
     520                 :             :          * is unlikely to be very good, but we do know a few special cases.)
     521                 :             :          */
     522                 :       64078 :         selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
     523                 :             :     }
     524                 :             : 
     525                 :             :     /* now adjust if we wanted <> rather than = */
     526         [ +  + ]:      249968 :     if (negate)
     527                 :       24068 :         selec = 1.0 - selec - nullfrac;
     528                 :             : 
     529                 :             :     /* result should be in range, but make sure... */
     530   [ -  +  -  + ]:      249968 :     CLAMP_PROBABILITY(selec);
     531                 :             : 
     532                 :      249968 :     return selec;
     533                 :             : }
     534                 :             : 
     535                 :             : /*
     536                 :             :  * var_eq_non_const --- eqsel for var = something-other-than-const case
     537                 :             :  *
     538                 :             :  * This is exported so that some other estimation functions can use it.
     539                 :             :  */
     540                 :             : double
     541                 :      347112 : var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
     542                 :             :                  Node *other,
     543                 :             :                  bool varonleft, bool negate)
     544                 :             : {
     545                 :             :     double      selec;
     546                 :      347112 :     double      nullfrac = 0.0;
     547                 :             :     bool        isdefault;
     548                 :             : 
     549                 :             :     /*
     550                 :             :      * Grab the nullfrac for use below.
     551                 :             :      */
     552         [ +  + ]:      347112 :     if (HeapTupleIsValid(vardata->statsTuple))
     553                 :             :     {
     554                 :             :         Form_pg_statistic stats;
     555                 :             : 
     556                 :      203752 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     557                 :      203752 :         nullfrac = stats->stanullfrac;
     558                 :             :     }
     559                 :             : 
     560                 :             :     /*
     561                 :             :      * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
     562                 :             :      * assume there is exactly one match regardless of anything else.  (This
     563                 :             :      * is slightly bogus, since the index or clause's equality operator might
     564                 :             :      * be different from ours, but it's much more likely to be right than
     565                 :             :      * ignoring the information.)
     566                 :             :      */
     567   [ +  +  +  -  :      347112 :     if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
                   +  + ]
     568                 :             :     {
     569                 :      125083 :         selec = 1.0 / vardata->rel->tuples;
     570                 :             :     }
     571         [ +  + ]:      222029 :     else if (HeapTupleIsValid(vardata->statsTuple))
     572                 :             :     {
     573                 :             :         double      ndistinct;
     574                 :             :         AttStatsSlot sslot;
     575                 :             : 
     576                 :             :         /*
     577                 :             :          * Search is for a value that we do not know a priori, but we will
     578                 :             :          * assume it is not NULL.  Estimate the selectivity as non-null
     579                 :             :          * fraction divided by number of distinct values, so that we get a
     580                 :             :          * result averaged over all possible values whether common or
     581                 :             :          * uncommon.  (Essentially, we are assuming that the not-yet-known
     582                 :             :          * comparison value is equally likely to be any of the possible
     583                 :             :          * values, regardless of their frequency in the table.  Is that a good
     584                 :             :          * idea?)
     585                 :             :          */
     586                 :       99288 :         selec = 1.0 - nullfrac;
     587                 :       99288 :         ndistinct = get_variable_numdistinct(vardata, &isdefault);
     588         [ +  + ]:       99288 :         if (ndistinct > 1)
     589                 :       96833 :             selec /= ndistinct;
     590                 :             : 
     591                 :             :         /*
     592                 :             :          * Cross-check: selectivity should never be estimated as more than the
     593                 :             :          * most common value's.
     594                 :             :          */
     595         [ +  + ]:       99288 :         if (get_attstatsslot(&sslot, vardata->statsTuple,
     596                 :             :                              STATISTIC_KIND_MCV, InvalidOid,
     597                 :             :                              ATTSTATSSLOT_NUMBERS))
     598                 :             :         {
     599   [ +  -  +  + ]:       83654 :             if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
     600                 :         483 :                 selec = sslot.numbers[0];
     601                 :       83654 :             free_attstatsslot(&sslot);
     602                 :             :         }
     603                 :             :     }
     604                 :             :     else
     605                 :             :     {
     606                 :             :         /*
     607                 :             :          * No ANALYZE stats available, so make a guess using estimated number
     608                 :             :          * of distinct values and assuming they are equally common. (The guess
     609                 :             :          * is unlikely to be very good, but we do know a few special cases.)
     610                 :             :          */
     611                 :      122741 :         selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
     612                 :             :     }
     613                 :             : 
     614                 :             :     /* now adjust if we wanted <> rather than = */
     615         [ +  + ]:      347112 :     if (negate)
     616                 :        4740 :         selec = 1.0 - selec - nullfrac;
     617                 :             : 
     618                 :             :     /* result should be in range, but make sure... */
     619   [ -  +  -  + ]:      347112 :     CLAMP_PROBABILITY(selec);
     620                 :             : 
     621                 :      347112 :     return selec;
     622                 :             : }
     623                 :             : 
     624                 :             : /*
     625                 :             :  *      neqsel          - Selectivity of "!=" for any data types.
     626                 :             :  *
     627                 :             :  * This routine is also used for some operators that are not "!="
     628                 :             :  * but have comparable selectivity behavior.  See above comments
     629                 :             :  * for eqsel().
     630                 :             :  */
     631                 :             : Datum
     632                 :       30256 : neqsel(PG_FUNCTION_ARGS)
     633                 :             : {
     634                 :       30256 :     PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, true));
     635                 :             : }
     636                 :             : 
     637                 :             : /*
     638                 :             :  *  scalarineqsel       - Selectivity of "<", "<=", ">", ">=" for scalars.
     639                 :             :  *
     640                 :             :  * This is the guts of scalarltsel/scalarlesel/scalargtsel/scalargesel.
     641                 :             :  * The isgt and iseq flags distinguish which of the four cases apply.
     642                 :             :  *
     643                 :             :  * The caller has commuted the clause, if necessary, so that we can treat
     644                 :             :  * the variable as being on the left.  The caller must also make sure that
     645                 :             :  * the other side of the clause is a non-null Const, and dissect that into
     646                 :             :  * a value and datatype.  (This definition simplifies some callers that
     647                 :             :  * want to estimate against a computed value instead of a Const node.)
     648                 :             :  *
     649                 :             :  * This routine works for any datatype (or pair of datatypes) known to
     650                 :             :  * convert_to_scalar().  If it is applied to some other datatype,
     651                 :             :  * it will return an approximate estimate based on assuming that the constant
     652                 :             :  * value falls in the middle of the bin identified by binary search.
     653                 :             :  */
     654                 :             : static double
     655                 :      238963 : scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq,
     656                 :             :               Oid collation,
     657                 :             :               VariableStatData *vardata, Datum constval, Oid consttype)
     658                 :             : {
     659                 :             :     Form_pg_statistic stats;
     660                 :             :     FmgrInfo    opproc;
     661                 :             :     double      mcv_selec,
     662                 :             :                 hist_selec,
     663                 :             :                 sumcommon;
     664                 :             :     double      selec;
     665                 :             : 
     666         [ +  + ]:      238963 :     if (!HeapTupleIsValid(vardata->statsTuple))
     667                 :             :     {
     668                 :             :         /*
     669                 :             :          * No stats are available.  Typically this means we have to fall back
     670                 :             :          * on the default estimate; but if the variable is CTID then we can
     671                 :             :          * make an estimate based on comparing the constant to the table size.
     672                 :             :          */
     673   [ +  -  +  + ]:       21366 :         if (vardata->var && IsA(vardata->var, Var) &&
     674         [ +  + ]:       17338 :             ((Var *) vardata->var)->varattno == SelfItemPointerAttributeNumber)
     675                 :             :         {
     676                 :             :             ItemPointer itemptr;
     677                 :             :             double      block;
     678                 :             :             double      density;
     679                 :             : 
     680                 :             :             /*
     681                 :             :              * If the relation's empty, we're going to include all of it.
     682                 :             :              * (This is mostly to avoid divide-by-zero below.)
     683                 :             :              */
     684         [ -  + ]:        1679 :             if (vardata->rel->pages == 0)
     685                 :           0 :                 return 1.0;
     686                 :             : 
     687                 :        1679 :             itemptr = (ItemPointer) DatumGetPointer(constval);
     688                 :        1679 :             block = ItemPointerGetBlockNumberNoCheck(itemptr);
     689                 :             : 
     690                 :             :             /*
     691                 :             :              * Determine the average number of tuples per page (density).
     692                 :             :              *
     693                 :             :              * Since the last page will, on average, be only half full, we can
     694                 :             :              * estimate it to have half as many tuples as earlier pages.  So
     695                 :             :              * give it half the weight of a regular page.
     696                 :             :              */
     697                 :        1679 :             density = vardata->rel->tuples / (vardata->rel->pages - 0.5);
     698                 :             : 
     699                 :             :             /* If target is the last page, use half the density. */
     700         [ +  + ]:        1679 :             if (block >= vardata->rel->pages - 1)
     701                 :          25 :                 density *= 0.5;
     702                 :             : 
     703                 :             :             /*
     704                 :             :              * Using the average tuples per page, calculate how far into the
     705                 :             :              * page the itemptr is likely to be and adjust block accordingly,
     706                 :             :              * by adding that fraction of a whole block (but never more than a
     707                 :             :              * whole block, no matter how high the itemptr's offset is).  Here
     708                 :             :              * we are ignoring the possibility of dead-tuple line pointers,
     709                 :             :              * which is fairly bogus, but we lack the info to do better.
     710                 :             :              */
     711         [ +  - ]:        1679 :             if (density > 0.0)
     712                 :             :             {
     713                 :        1679 :                 OffsetNumber offset = ItemPointerGetOffsetNumberNoCheck(itemptr);
     714                 :             : 
     715         [ +  + ]:        1679 :                 block += Min(offset / density, 1.0);
     716                 :             :             }
     717                 :             : 
     718                 :             :             /*
     719                 :             :              * Convert relative block number to selectivity.  Again, the last
     720                 :             :              * page has only half weight.
     721                 :             :              */
     722                 :        1679 :             selec = block / (vardata->rel->pages - 0.5);
     723                 :             : 
     724                 :             :             /*
     725                 :             :              * The calculation so far gave us a selectivity for the "<=" case.
     726                 :             :              * We'll have one fewer tuple for "<" and one additional tuple for
     727                 :             :              * ">=", the latter of which we'll reverse the selectivity for
     728                 :             :              * below, so we can simply subtract one tuple for both cases.  The
     729                 :             :              * cases that need this adjustment can be identified by iseq being
     730                 :             :              * equal to isgt.
     731                 :             :              */
     732   [ +  +  +  - ]:        1679 :             if (iseq == isgt && vardata->rel->tuples >= 1.0)
     733                 :        1562 :                 selec -= (1.0 / vardata->rel->tuples);
     734                 :             : 
     735                 :             :             /* Finally, reverse the selectivity for the ">", ">=" cases. */
     736         [ +  + ]:        1679 :             if (isgt)
     737                 :        1547 :                 selec = 1.0 - selec;
     738                 :             : 
     739   [ +  +  -  + ]:        1679 :             CLAMP_PROBABILITY(selec);
     740                 :        1679 :             return selec;
     741                 :             :         }
     742                 :             : 
     743                 :             :         /* no stats available, so default result */
     744                 :       19687 :         return DEFAULT_INEQ_SEL;
     745                 :             :     }
     746                 :      217597 :     stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     747                 :             : 
     748                 :      217597 :     fmgr_info(get_opcode(operator), &opproc);
     749                 :             : 
     750                 :             :     /*
     751                 :             :      * If we have most-common-values info, add up the fractions of the MCV
     752                 :             :      * entries that satisfy MCV OP CONST.  These fractions contribute directly
     753                 :             :      * to the result selectivity.  Also add up the total fraction represented
     754                 :             :      * by MCV entries.
     755                 :             :      */
     756                 :      217597 :     mcv_selec = mcv_selectivity(vardata, &opproc, collation, constval, true,
     757                 :             :                                 &sumcommon);
     758                 :             : 
     759                 :             :     /*
     760                 :             :      * If there is a histogram, determine which bin the constant falls in, and
     761                 :             :      * compute the resulting contribution to selectivity.
     762                 :             :      */
     763                 :      217597 :     hist_selec = ineq_histogram_selectivity(root, vardata,
     764                 :             :                                             operator, &opproc, isgt, iseq,
     765                 :             :                                             collation,
     766                 :             :                                             constval, consttype);
     767                 :             : 
     768                 :             :     /*
     769                 :             :      * Now merge the results from the MCV and histogram calculations,
     770                 :             :      * realizing that the histogram covers only the non-null values that are
     771                 :             :      * not listed in MCV.
     772                 :             :      */
     773                 :      217597 :     selec = 1.0 - stats->stanullfrac - sumcommon;
     774                 :             : 
     775         [ +  + ]:      217597 :     if (hist_selec >= 0.0)
     776                 :      130514 :         selec *= hist_selec;
     777                 :             :     else
     778                 :             :     {
     779                 :             :         /*
     780                 :             :          * If no histogram but there are values not accounted for by MCV,
     781                 :             :          * arbitrarily assume half of them will match.
     782                 :             :          */
     783                 :       87083 :         selec *= 0.5;
     784                 :             :     }
     785                 :             : 
     786                 :      217597 :     selec += mcv_selec;
     787                 :             : 
     788                 :             :     /* result should be in range, but make sure... */
     789   [ +  +  +  + ]:      217597 :     CLAMP_PROBABILITY(selec);
     790                 :             : 
     791                 :      217597 :     return selec;
     792                 :             : }
     793                 :             : 
     794                 :             : /*
     795                 :             :  *  mcv_selectivity         - Examine the MCV list for selectivity estimates
     796                 :             :  *
     797                 :             :  * Determine the fraction of the variable's MCV population that satisfies
     798                 :             :  * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.  Also
     799                 :             :  * compute the fraction of the total column population represented by the MCV
     800                 :             :  * list.  This code will work for any boolean-returning predicate operator.
     801                 :             :  *
     802                 :             :  * The function result is the MCV selectivity, and the fraction of the
     803                 :             :  * total population is returned into *sumcommonp.  Zeroes are returned
     804                 :             :  * if there is no MCV list.
     805                 :             :  */
     806                 :             : double
     807                 :      221944 : mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation,
     808                 :             :                 Datum constval, bool varonleft,
     809                 :             :                 double *sumcommonp)
     810                 :             : {
     811                 :             :     double      mcv_selec,
     812                 :             :                 sumcommon;
     813                 :             :     AttStatsSlot sslot;
     814                 :             :     int         i;
     815                 :             : 
     816                 :      221944 :     mcv_selec = 0.0;
     817                 :      221944 :     sumcommon = 0.0;
     818                 :             : 
     819   [ +  +  +  + ]:      442085 :     if (HeapTupleIsValid(vardata->statsTuple) &&
     820         [ +  + ]:      440007 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
     821                 :      219866 :         get_attstatsslot(&sslot, vardata->statsTuple,
     822                 :             :                          STATISTIC_KIND_MCV, InvalidOid,
     823                 :             :                          ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
     824                 :             :     {
     825                 :      123313 :         LOCAL_FCINFO(fcinfo, 2);
     826                 :             : 
     827                 :             :         /*
     828                 :             :          * We invoke the opproc "by hand" so that we won't fail on NULL
     829                 :             :          * results.  Such cases won't arise for normal comparison functions,
     830                 :             :          * but generic_restriction_selectivity could perhaps be used with
     831                 :             :          * operators that can return NULL.  A small side benefit is to not
     832                 :             :          * need to re-initialize the fcinfo struct from scratch each time.
     833                 :             :          */
     834                 :      123313 :         InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
     835                 :             :                                  NULL, NULL);
     836                 :      123313 :         fcinfo->args[0].isnull = false;
     837                 :      123313 :         fcinfo->args[1].isnull = false;
     838                 :             :         /* be careful to apply operator right way 'round */
     839         [ +  - ]:      123313 :         if (varonleft)
     840                 :      123313 :             fcinfo->args[1].value = constval;
     841                 :             :         else
     842                 :           0 :             fcinfo->args[0].value = constval;
     843                 :             : 
     844         [ +  + ]:     2734115 :         for (i = 0; i < sslot.nvalues; i++)
     845                 :             :         {
     846                 :             :             Datum       fresult;
     847                 :             : 
     848         [ +  - ]:     2610802 :             if (varonleft)
     849                 :     2610802 :                 fcinfo->args[0].value = sslot.values[i];
     850                 :             :             else
     851                 :           0 :                 fcinfo->args[1].value = sslot.values[i];
     852                 :     2610802 :             fcinfo->isnull = false;
     853                 :     2610802 :             fresult = FunctionCallInvoke(fcinfo);
     854   [ +  -  +  + ]:     2610802 :             if (!fcinfo->isnull && DatumGetBool(fresult))
     855                 :     1056223 :                 mcv_selec += sslot.numbers[i];
     856                 :     2610802 :             sumcommon += sslot.numbers[i];
     857                 :             :         }
     858                 :      123313 :         free_attstatsslot(&sslot);
     859                 :             :     }
     860                 :             : 
     861                 :      221944 :     *sumcommonp = sumcommon;
     862                 :      221944 :     return mcv_selec;
     863                 :             : }
     864                 :             : 
     865                 :             : /*
     866                 :             :  *  histogram_selectivity   - Examine the histogram for selectivity estimates
     867                 :             :  *
     868                 :             :  * Determine the fraction of the variable's histogram entries that satisfy
     869                 :             :  * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
     870                 :             :  *
     871                 :             :  * This code will work for any boolean-returning predicate operator, whether
     872                 :             :  * or not it has anything to do with the histogram sort operator.  We are
     873                 :             :  * essentially using the histogram just as a representative sample.  However,
     874                 :             :  * small histograms are unlikely to be all that representative, so the caller
     875                 :             :  * should be prepared to fall back on some other estimation approach when the
     876                 :             :  * histogram is missing or very small.  It may also be prudent to combine this
     877                 :             :  * approach with another one when the histogram is small.
     878                 :             :  *
     879                 :             :  * If the actual histogram size is not at least min_hist_size, we won't bother
     880                 :             :  * to do the calculation at all.  Also, if the n_skip parameter is > 0, we
     881                 :             :  * ignore the first and last n_skip histogram elements, on the grounds that
     882                 :             :  * they are outliers and hence not very representative.  Typical values for
     883                 :             :  * these parameters are 10 and 1.
     884                 :             :  *
     885                 :             :  * The function result is the selectivity, or -1 if there is no histogram
     886                 :             :  * or it's smaller than min_hist_size.
     887                 :             :  *
     888                 :             :  * The output parameter *hist_size receives the actual histogram size,
     889                 :             :  * or zero if no histogram.  Callers may use this number to decide how
     890                 :             :  * much faith to put in the function result.
     891                 :             :  *
     892                 :             :  * Note that the result disregards both the most-common-values (if any) and
     893                 :             :  * null entries.  The caller is expected to combine this result with
     894                 :             :  * statistics for those portions of the column population.  It may also be
     895                 :             :  * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
     896                 :             :  */
     897                 :             : double
     898                 :        4347 : histogram_selectivity(VariableStatData *vardata,
     899                 :             :                       FmgrInfo *opproc, Oid collation,
     900                 :             :                       Datum constval, bool varonleft,
     901                 :             :                       int min_hist_size, int n_skip,
     902                 :             :                       int *hist_size)
     903                 :             : {
     904                 :             :     double      result;
     905                 :             :     AttStatsSlot sslot;
     906                 :             : 
     907                 :             :     /* check sanity of parameters */
     908                 :             :     Assert(n_skip >= 0);
     909                 :             :     Assert(min_hist_size > 2 * n_skip);
     910                 :             : 
     911   [ +  +  +  + ]:        6891 :     if (HeapTupleIsValid(vardata->statsTuple) &&
     912         [ +  + ]:        5083 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
     913                 :        2539 :         get_attstatsslot(&sslot, vardata->statsTuple,
     914                 :             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
     915                 :             :                          ATTSTATSSLOT_VALUES))
     916                 :             :     {
     917                 :        2462 :         *hist_size = sslot.nvalues;
     918         [ +  + ]:        2462 :         if (sslot.nvalues >= min_hist_size)
     919                 :             :         {
     920                 :        1336 :             LOCAL_FCINFO(fcinfo, 2);
     921                 :        1336 :             int         nmatch = 0;
     922                 :             :             int         i;
     923                 :             : 
     924                 :             :             /*
     925                 :             :              * We invoke the opproc "by hand" so that we won't fail on NULL
     926                 :             :              * results.  Such cases won't arise for normal comparison
     927                 :             :              * functions, but generic_restriction_selectivity could perhaps be
     928                 :             :              * used with operators that can return NULL.  A small side benefit
     929                 :             :              * is to not need to re-initialize the fcinfo struct from scratch
     930                 :             :              * each time.
     931                 :             :              */
     932                 :        1336 :             InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
     933                 :             :                                      NULL, NULL);
     934                 :        1336 :             fcinfo->args[0].isnull = false;
     935                 :        1336 :             fcinfo->args[1].isnull = false;
     936                 :             :             /* be careful to apply operator right way 'round */
     937         [ +  - ]:        1336 :             if (varonleft)
     938                 :        1336 :                 fcinfo->args[1].value = constval;
     939                 :             :             else
     940                 :           0 :                 fcinfo->args[0].value = constval;
     941                 :             : 
     942         [ +  + ]:      114971 :             for (i = n_skip; i < sslot.nvalues - n_skip; i++)
     943                 :             :             {
     944                 :             :                 Datum       fresult;
     945                 :             : 
     946         [ +  - ]:      113635 :                 if (varonleft)
     947                 :      113635 :                     fcinfo->args[0].value = sslot.values[i];
     948                 :             :                 else
     949                 :           0 :                     fcinfo->args[1].value = sslot.values[i];
     950                 :      113635 :                 fcinfo->isnull = false;
     951                 :      113635 :                 fresult = FunctionCallInvoke(fcinfo);
     952   [ +  -  +  + ]:      113635 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
     953                 :        3780 :                     nmatch++;
     954                 :             :             }
     955                 :        1336 :             result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
     956                 :             :         }
     957                 :             :         else
     958                 :        1126 :             result = -1;
     959                 :        2462 :         free_attstatsslot(&sslot);
     960                 :             :     }
     961                 :             :     else
     962                 :             :     {
     963                 :        1885 :         *hist_size = 0;
     964                 :        1885 :         result = -1;
     965                 :             :     }
     966                 :             : 
     967                 :        4347 :     return result;
     968                 :             : }
     969                 :             : 
     970                 :             : /*
     971                 :             :  *  generic_restriction_selectivity     - Selectivity for almost anything
     972                 :             :  *
     973                 :             :  * This function estimates selectivity for operators that we don't have any
     974                 :             :  * special knowledge about, but are on data types that we collect standard
     975                 :             :  * MCV and/or histogram statistics for.  (Additional assumptions are that
     976                 :             :  * the operator is strict and immutable, or at least stable.)
     977                 :             :  *
     978                 :             :  * If we have "VAR OP CONST" or "CONST OP VAR", selectivity is estimated by
     979                 :             :  * applying the operator to each element of the column's MCV and/or histogram
     980                 :             :  * stats, and merging the results using the assumption that the histogram is
     981                 :             :  * a reasonable random sample of the column's non-MCV population.  Note that
     982                 :             :  * if the operator's semantics are related to the histogram ordering, this
     983                 :             :  * might not be such a great assumption; other functions such as
     984                 :             :  * scalarineqsel() are probably a better match in such cases.
     985                 :             :  *
     986                 :             :  * Otherwise, fall back to the default selectivity provided by the caller.
     987                 :             :  */
     988                 :             : double
     989                 :         845 : generic_restriction_selectivity(PlannerInfo *root, Oid oproid, Oid collation,
     990                 :             :                                 List *args, int varRelid,
     991                 :             :                                 double default_selectivity)
     992                 :             : {
     993                 :             :     double      selec;
     994                 :             :     VariableStatData vardata;
     995                 :             :     Node       *other;
     996                 :             :     bool        varonleft;
     997                 :             : 
     998                 :             :     /*
     999                 :             :      * If expression is not variable OP something or something OP variable,
    1000                 :             :      * then punt and return the default estimate.
    1001                 :             :      */
    1002         [ -  + ]:         845 :     if (!get_restriction_variable(root, args, varRelid,
    1003                 :             :                                   &vardata, &other, &varonleft))
    1004                 :           0 :         return default_selectivity;
    1005                 :             : 
    1006                 :             :     /*
    1007                 :             :      * If the something is a NULL constant, assume operator is strict and
    1008                 :             :      * return zero, ie, operator will never return TRUE.
    1009                 :             :      */
    1010         [ +  - ]:         845 :     if (IsA(other, Const) &&
    1011         [ -  + ]:         845 :         ((Const *) other)->constisnull)
    1012                 :             :     {
    1013         [ #  # ]:           0 :         ReleaseVariableStats(vardata);
    1014                 :           0 :         return 0.0;
    1015                 :             :     }
    1016                 :             : 
    1017         [ +  - ]:         845 :     if (IsA(other, Const))
    1018                 :             :     {
    1019                 :             :         /* Variable is being compared to a known non-null constant */
    1020                 :         845 :         Datum       constval = ((Const *) other)->constvalue;
    1021                 :             :         FmgrInfo    opproc;
    1022                 :             :         double      mcvsum;
    1023                 :             :         double      mcvsel;
    1024                 :             :         double      nullfrac;
    1025                 :             :         int         hist_size;
    1026                 :             : 
    1027                 :         845 :         fmgr_info(get_opcode(oproid), &opproc);
    1028                 :             : 
    1029                 :             :         /*
    1030                 :             :          * Calculate the selectivity for the column's most common values.
    1031                 :             :          */
    1032                 :         845 :         mcvsel = mcv_selectivity(&vardata, &opproc, collation,
    1033                 :             :                                  constval, varonleft,
    1034                 :             :                                  &mcvsum);
    1035                 :             : 
    1036                 :             :         /*
    1037                 :             :          * If the histogram is large enough, see what fraction of it matches
    1038                 :             :          * the query, and assume that's representative of the non-MCV
    1039                 :             :          * population.  Otherwise use the default selectivity for the non-MCV
    1040                 :             :          * population.
    1041                 :             :          */
    1042                 :         845 :         selec = histogram_selectivity(&vardata, &opproc, collation,
    1043                 :             :                                       constval, varonleft,
    1044                 :             :                                       10, 1, &hist_size);
    1045         [ +  - ]:         845 :         if (selec < 0)
    1046                 :             :         {
    1047                 :             :             /* Nope, fall back on default */
    1048                 :         845 :             selec = default_selectivity;
    1049                 :             :         }
    1050         [ #  # ]:           0 :         else if (hist_size < 100)
    1051                 :             :         {
    1052                 :             :             /*
    1053                 :             :              * For histogram sizes from 10 to 100, we combine the histogram
    1054                 :             :              * and default selectivities, putting increasingly more trust in
    1055                 :             :              * the histogram for larger sizes.
    1056                 :             :              */
    1057                 :           0 :             double      hist_weight = hist_size / 100.0;
    1058                 :             : 
    1059                 :           0 :             selec = selec * hist_weight +
    1060                 :           0 :                 default_selectivity * (1.0 - hist_weight);
    1061                 :             :         }
    1062                 :             : 
    1063                 :             :         /* In any case, don't believe extremely small or large estimates. */
    1064         [ -  + ]:         845 :         if (selec < 0.0001)
    1065                 :           0 :             selec = 0.0001;
    1066         [ -  + ]:         845 :         else if (selec > 0.9999)
    1067                 :           0 :             selec = 0.9999;
    1068                 :             : 
    1069                 :             :         /* Don't forget to account for nulls. */
    1070         [ +  + ]:         845 :         if (HeapTupleIsValid(vardata.statsTuple))
    1071                 :          70 :             nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
    1072                 :             :         else
    1073                 :         775 :             nullfrac = 0.0;
    1074                 :             : 
    1075                 :             :         /*
    1076                 :             :          * Now merge the results from the MCV and histogram calculations,
    1077                 :             :          * realizing that the histogram covers only the non-null values that
    1078                 :             :          * are not listed in MCV.
    1079                 :             :          */
    1080                 :         845 :         selec *= 1.0 - nullfrac - mcvsum;
    1081                 :         845 :         selec += mcvsel;
    1082                 :             :     }
    1083                 :             :     else
    1084                 :             :     {
    1085                 :             :         /* Comparison value is not constant, so we can't do anything */
    1086                 :           0 :         selec = default_selectivity;
    1087                 :             :     }
    1088                 :             : 
    1089         [ +  + ]:         845 :     ReleaseVariableStats(vardata);
    1090                 :             : 
    1091                 :             :     /* result should be in range, but make sure... */
    1092   [ -  +  -  + ]:         845 :     CLAMP_PROBABILITY(selec);
    1093                 :             : 
    1094                 :         845 :     return selec;
    1095                 :             : }
    1096                 :             : 
    1097                 :             : /*
    1098                 :             :  *  ineq_histogram_selectivity  - Examine the histogram for scalarineqsel
    1099                 :             :  *
    1100                 :             :  * Determine the fraction of the variable's histogram population that
    1101                 :             :  * satisfies the inequality condition, ie, VAR < (or <=, >, >=) CONST.
    1102                 :             :  * The isgt and iseq flags distinguish which of the four cases apply.
    1103                 :             :  *
    1104                 :             :  * While opproc could be looked up from the operator OID, common callers
    1105                 :             :  * also need to call it separately, so we make the caller pass both.
    1106                 :             :  *
    1107                 :             :  * Returns -1 if there is no histogram (valid results will always be >= 0).
    1108                 :             :  *
    1109                 :             :  * Note that the result disregards both the most-common-values (if any) and
    1110                 :             :  * null entries.  The caller is expected to combine this result with
    1111                 :             :  * statistics for those portions of the column population.
    1112                 :             :  *
    1113                 :             :  * This is exported so that some other estimation functions can use it.
    1114                 :             :  */
    1115                 :             : double
    1116                 :      220763 : ineq_histogram_selectivity(PlannerInfo *root,
    1117                 :             :                            VariableStatData *vardata,
    1118                 :             :                            Oid opoid, FmgrInfo *opproc, bool isgt, bool iseq,
    1119                 :             :                            Oid collation,
    1120                 :             :                            Datum constval, Oid consttype)
    1121                 :             : {
    1122                 :             :     double      hist_selec;
    1123                 :             :     AttStatsSlot sslot;
    1124                 :             : 
    1125                 :      220763 :     hist_selec = -1.0;
    1126                 :             : 
    1127                 :             :     /*
    1128                 :             :      * Someday, ANALYZE might store more than one histogram per rel/att,
    1129                 :             :      * corresponding to more than one possible sort ordering defined for the
    1130                 :             :      * column type.  Right now, we know there is only one, so just grab it and
    1131                 :             :      * see if it matches the query.
    1132                 :             :      *
    1133                 :             :      * Note that we can't use opoid as search argument; the staop appearing in
    1134                 :             :      * pg_statistic will be for the relevant '<' operator, but what we have
    1135                 :             :      * might be some other inequality operator such as '>='.  (Even if opoid
    1136                 :             :      * is a '<' operator, it could be cross-type.)  Hence we must use
    1137                 :             :      * comparison_ops_are_compatible() to see if the operators match.
    1138                 :             :      */
    1139   [ +  +  +  + ]:      441015 :     if (HeapTupleIsValid(vardata->statsTuple) &&
    1140         [ +  + ]:      440234 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
    1141                 :      219982 :         get_attstatsslot(&sslot, vardata->statsTuple,
    1142                 :             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
    1143                 :             :                          ATTSTATSSLOT_VALUES))
    1144                 :             :     {
    1145         [ +  - ]:      133168 :         if (sslot.nvalues > 1 &&
    1146   [ +  +  +  + ]:      266274 :             sslot.stacoll == collation &&
    1147                 :      133106 :             comparison_ops_are_compatible(sslot.staop, opoid))
    1148                 :      133016 :         {
    1149                 :             :             /*
    1150                 :             :              * Use binary search to find the desired location, namely the
    1151                 :             :              * right end of the histogram bin containing the comparison value,
    1152                 :             :              * which is the leftmost entry for which the comparison operator
    1153                 :             :              * succeeds (if isgt) or fails (if !isgt).
    1154                 :             :              *
    1155                 :             :              * In this loop, we pay no attention to whether the operator iseq
    1156                 :             :              * or not; that detail will be mopped up below.  (We cannot tell,
    1157                 :             :              * anyway, whether the operator thinks the values are equal.)
    1158                 :             :              *
    1159                 :             :              * If the binary search accesses the first or last histogram
    1160                 :             :              * entry, we try to replace that endpoint with the true column min
    1161                 :             :              * or max as found by get_actual_variable_range().  This
    1162                 :             :              * ameliorates misestimates when the min or max is moving as a
    1163                 :             :              * result of changes since the last ANALYZE.  Note that this could
    1164                 :             :              * result in effectively including MCVs into the histogram that
    1165                 :             :              * weren't there before, but we don't try to correct for that.
    1166                 :             :              */
    1167                 :             :             double      histfrac;
    1168                 :      133016 :             int         lobound = 0;    /* first possible slot to search */
    1169                 :      133016 :             int         hibound = sslot.nvalues;    /* last+1 slot to search */
    1170                 :      133016 :             bool        have_end = false;
    1171                 :             : 
    1172                 :             :             /*
    1173                 :             :              * If there are only two histogram entries, we'll want up-to-date
    1174                 :             :              * values for both.  (If there are more than two, we need at most
    1175                 :             :              * one of them to be updated, so we deal with that within the
    1176                 :             :              * loop.)
    1177                 :             :              */
    1178         [ +  + ]:      133016 :             if (sslot.nvalues == 2)
    1179                 :        2574 :                 have_end = get_actual_variable_range(root,
    1180                 :             :                                                      vardata,
    1181                 :             :                                                      sslot.staop,
    1182                 :             :                                                      collation,
    1183                 :             :                                                      &sslot.values[0],
    1184                 :        2574 :                                                      &sslot.values[1]);
    1185                 :             : 
    1186         [ +  + ]:      871288 :             while (lobound < hibound)
    1187                 :             :             {
    1188                 :      738272 :                 int         probe = (lobound + hibound) / 2;
    1189                 :             :                 bool        ltcmp;
    1190                 :             : 
    1191                 :             :                 /*
    1192                 :             :                  * If we find ourselves about to compare to the first or last
    1193                 :             :                  * histogram entry, first try to replace it with the actual
    1194                 :             :                  * current min or max (unless we already did so above).
    1195                 :             :                  */
    1196   [ +  +  +  + ]:      738272 :                 if (probe == 0 && sslot.nvalues > 2)
    1197                 :       65653 :                     have_end = get_actual_variable_range(root,
    1198                 :             :                                                          vardata,
    1199                 :             :                                                          sslot.staop,
    1200                 :             :                                                          collation,
    1201                 :             :                                                          &sslot.values[0],
    1202                 :             :                                                          NULL);
    1203   [ +  +  +  + ]:      672619 :                 else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
    1204                 :       45213 :                     have_end = get_actual_variable_range(root,
    1205                 :             :                                                          vardata,
    1206                 :             :                                                          sslot.staop,
    1207                 :             :                                                          collation,
    1208                 :             :                                                          NULL,
    1209                 :       45213 :                                                          &sslot.values[probe]);
    1210                 :             : 
    1211                 :      738272 :                 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
    1212                 :             :                                                        collation,
    1213                 :      738272 :                                                        sslot.values[probe],
    1214                 :             :                                                        constval));
    1215         [ +  + ]:      738272 :                 if (isgt)
    1216                 :       49867 :                     ltcmp = !ltcmp;
    1217         [ +  + ]:      738272 :                 if (ltcmp)
    1218                 :      274074 :                     lobound = probe + 1;
    1219                 :             :                 else
    1220                 :      464198 :                     hibound = probe;
    1221                 :             :             }
    1222                 :             : 
    1223         [ +  + ]:      133016 :             if (lobound <= 0)
    1224                 :             :             {
    1225                 :             :                 /*
    1226                 :             :                  * Constant is below lower histogram boundary.  More
    1227                 :             :                  * precisely, we have found that no entry in the histogram
    1228                 :             :                  * satisfies the inequality clause (if !isgt) or they all do
    1229                 :             :                  * (if isgt).  We estimate that that's true of the entire
    1230                 :             :                  * table, so set histfrac to 0.0 (which we'll flip to 1.0
    1231                 :             :                  * below, if isgt).
    1232                 :             :                  */
    1233                 :       57860 :                 histfrac = 0.0;
    1234                 :             :             }
    1235         [ +  + ]:       75156 :             else if (lobound >= sslot.nvalues)
    1236                 :             :             {
    1237                 :             :                 /*
    1238                 :             :                  * Inverse case: constant is above upper histogram boundary.
    1239                 :             :                  */
    1240                 :       22048 :                 histfrac = 1.0;
    1241                 :             :             }
    1242                 :             :             else
    1243                 :             :             {
    1244                 :             :                 /* We have values[i-1] <= constant <= values[i]. */
    1245                 :       53108 :                 int         i = lobound;
    1246                 :       53108 :                 double      eq_selec = 0;
    1247                 :             :                 double      val,
    1248                 :             :                             high,
    1249                 :             :                             low;
    1250                 :             :                 double      binfrac;
    1251                 :             : 
    1252                 :             :                 /*
    1253                 :             :                  * In the cases where we'll need it below, obtain an estimate
    1254                 :             :                  * of the selectivity of "x = constval".  We use a calculation
    1255                 :             :                  * similar to what var_eq_const() does for a non-MCV constant,
    1256                 :             :                  * ie, estimate that all distinct non-MCV values occur equally
    1257                 :             :                  * often.  But multiplication by "1.0 - sumcommon - nullfrac"
    1258                 :             :                  * will be done by our caller, so we shouldn't do that here.
    1259                 :             :                  * Therefore we can't try to clamp the estimate by reference
    1260                 :             :                  * to the least common MCV; the result would be too small.
    1261                 :             :                  *
    1262                 :             :                  * Note: since this is effectively assuming that constval
    1263                 :             :                  * isn't an MCV, it's logically dubious if constval in fact is
    1264                 :             :                  * one.  But we have to apply *some* correction for equality,
    1265                 :             :                  * and anyway we cannot tell if constval is an MCV, since we
    1266                 :             :                  * don't have a suitable equality operator at hand.
    1267                 :             :                  */
    1268   [ +  +  +  + ]:       53108 :                 if (i == 1 || isgt == iseq)
    1269                 :             :                 {
    1270                 :             :                     double      otherdistinct;
    1271                 :             :                     bool        isdefault;
    1272                 :             :                     AttStatsSlot mcvslot;
    1273                 :             : 
    1274                 :             :                     /* Get estimated number of distinct values */
    1275                 :       22236 :                     otherdistinct = get_variable_numdistinct(vardata,
    1276                 :             :                                                              &isdefault);
    1277                 :             : 
    1278                 :             :                     /* Subtract off the number of known MCVs */
    1279         [ +  + ]:       22236 :                     if (get_attstatsslot(&mcvslot, vardata->statsTuple,
    1280                 :             :                                          STATISTIC_KIND_MCV, InvalidOid,
    1281                 :             :                                          ATTSTATSSLOT_NUMBERS))
    1282                 :             :                     {
    1283                 :        2310 :                         otherdistinct -= mcvslot.nnumbers;
    1284                 :        2310 :                         free_attstatsslot(&mcvslot);
    1285                 :             :                     }
    1286                 :             : 
    1287                 :             :                     /* If result doesn't seem sane, leave eq_selec at 0 */
    1288         [ +  + ]:       22236 :                     if (otherdistinct > 1)
    1289                 :       22215 :                         eq_selec = 1.0 / otherdistinct;
    1290                 :             :                 }
    1291                 :             : 
    1292                 :             :                 /*
    1293                 :             :                  * Convert the constant and the two nearest bin boundary
    1294                 :             :                  * values to a uniform comparison scale, and do a linear
    1295                 :             :                  * interpolation within this bin.
    1296                 :             :                  */
    1297         [ +  - ]:       53108 :                 if (convert_to_scalar(constval, consttype, collation,
    1298                 :             :                                       &val,
    1299                 :       53108 :                                       sslot.values[i - 1], sslot.values[i],
    1300                 :             :                                       vardata->vartype,
    1301                 :             :                                       &low, &high))
    1302                 :             :                 {
    1303         [ -  + ]:       53108 :                     if (high <= low)
    1304                 :             :                     {
    1305                 :             :                         /* cope if bin boundaries appear identical */
    1306                 :           0 :                         binfrac = 0.5;
    1307                 :             :                     }
    1308         [ +  + ]:       53108 :                     else if (val <= low)
    1309                 :       11300 :                         binfrac = 0.0;
    1310         [ +  + ]:       41808 :                     else if (val >= high)
    1311                 :        1742 :                         binfrac = 1.0;
    1312                 :             :                     else
    1313                 :             :                     {
    1314                 :       40066 :                         binfrac = (val - low) / (high - low);
    1315                 :             : 
    1316                 :             :                         /*
    1317                 :             :                          * Watch out for the possibility that we got a NaN or
    1318                 :             :                          * Infinity from the division.  This can happen
    1319                 :             :                          * despite the previous checks, if for example "low"
    1320                 :             :                          * is -Infinity.
    1321                 :             :                          */
    1322   [ +  -  +  - ]:       40066 :                         if (isnan(binfrac) ||
    1323         [ -  + ]:       40066 :                             binfrac < 0.0 || binfrac > 1.0)
    1324                 :           0 :                             binfrac = 0.5;
    1325                 :             :                     }
    1326                 :             :                 }
    1327                 :             :                 else
    1328                 :             :                 {
    1329                 :             :                     /*
    1330                 :             :                      * Ideally we'd produce an error here, on the grounds that
    1331                 :             :                      * the given operator shouldn't have scalarXXsel
    1332                 :             :                      * registered as its selectivity func unless we can deal
    1333                 :             :                      * with its operand types.  But currently, all manner of
    1334                 :             :                      * stuff is invoking scalarXXsel, so give a default
    1335                 :             :                      * estimate until that can be fixed.
    1336                 :             :                      */
    1337                 :           0 :                     binfrac = 0.5;
    1338                 :             :                 }
    1339                 :             : 
    1340                 :             :                 /*
    1341                 :             :                  * Now, compute the overall selectivity across the values
    1342                 :             :                  * represented by the histogram.  We have i-1 full bins and
    1343                 :             :                  * binfrac partial bin below the constant.
    1344                 :             :                  */
    1345                 :       53108 :                 histfrac = (double) (i - 1) + binfrac;
    1346                 :       53108 :                 histfrac /= (double) (sslot.nvalues - 1);
    1347                 :             : 
    1348                 :             :                 /*
    1349                 :             :                  * At this point, histfrac is an estimate of the fraction of
    1350                 :             :                  * the population represented by the histogram that satisfies
    1351                 :             :                  * "x <= constval".  Somewhat remarkably, this statement is
    1352                 :             :                  * true regardless of which operator we were doing the probes
    1353                 :             :                  * with, so long as convert_to_scalar() delivers reasonable
    1354                 :             :                  * results.  If the probe constant is equal to some histogram
    1355                 :             :                  * entry, we would have considered the bin to the left of that
    1356                 :             :                  * entry if probing with "<" or ">=", or the bin to the right
    1357                 :             :                  * if probing with "<=" or ">"; but binfrac would have come
    1358                 :             :                  * out as 1.0 in the first case and 0.0 in the second, leading
    1359                 :             :                  * to the same histfrac in either case.  For probe constants
    1360                 :             :                  * between histogram entries, we find the same bin and get the
    1361                 :             :                  * same estimate with any operator.
    1362                 :             :                  *
    1363                 :             :                  * The fact that the estimate corresponds to "x <= constval"
    1364                 :             :                  * and not "x < constval" is because of the way that ANALYZE
    1365                 :             :                  * constructs the histogram: each entry is, effectively, the
    1366                 :             :                  * rightmost value in its sample bucket.  So selectivity
    1367                 :             :                  * values that are exact multiples of 1/(histogram_size-1)
    1368                 :             :                  * should be understood as estimates including a histogram
    1369                 :             :                  * entry plus everything to its left.
    1370                 :             :                  *
    1371                 :             :                  * However, that breaks down for the first histogram entry,
    1372                 :             :                  * which necessarily is the leftmost value in its sample
    1373                 :             :                  * bucket.  That means the first histogram bin is slightly
    1374                 :             :                  * narrower than the rest, by an amount equal to eq_selec.
    1375                 :             :                  * Another way to say that is that we want "x <= leftmost" to
    1376                 :             :                  * be estimated as eq_selec not zero.  So, if we're dealing
    1377                 :             :                  * with the first bin (i==1), rescale to make that true while
    1378                 :             :                  * adjusting the rest of that bin linearly.
    1379                 :             :                  */
    1380         [ +  + ]:       53108 :                 if (i == 1)
    1381                 :        9452 :                     histfrac += eq_selec * (1.0 - binfrac);
    1382                 :             : 
    1383                 :             :                 /*
    1384                 :             :                  * "x <= constval" is good if we want an estimate for "<=" or
    1385                 :             :                  * ">", but if we are estimating for "<" or ">=", we now need
    1386                 :             :                  * to decrease the estimate by eq_selec.
    1387                 :             :                  */
    1388         [ +  + ]:       53108 :                 if (isgt == iseq)
    1389                 :       17166 :                     histfrac -= eq_selec;
    1390                 :             :             }
    1391                 :             : 
    1392                 :             :             /*
    1393                 :             :              * Now the estimate is finished for "<" and "<=" cases.  If we are
    1394                 :             :              * estimating for ">" or ">=", flip it.
    1395                 :             :              */
    1396         [ +  + ]:      133016 :             hist_selec = isgt ? (1.0 - histfrac) : histfrac;
    1397                 :             : 
    1398                 :             :             /*
    1399                 :             :              * The histogram boundaries are only approximate to begin with,
    1400                 :             :              * and may well be out of date anyway.  Therefore, don't believe
    1401                 :             :              * extremely small or large selectivity estimates --- unless we
    1402                 :             :              * got actual current endpoint values from the table, in which
    1403                 :             :              * case just do the usual sanity clamp.  Somewhat arbitrarily, we
    1404                 :             :              * set the cutoff for other cases at a hundredth of the histogram
    1405                 :             :              * resolution.
    1406                 :             :              */
    1407         [ +  + ]:      133016 :             if (have_end)
    1408   [ -  +  -  + ]:       75870 :                 CLAMP_PROBABILITY(hist_selec);
    1409                 :             :             else
    1410                 :             :             {
    1411                 :       57146 :                 double      cutoff = 0.01 / (double) (sslot.nvalues - 1);
    1412                 :             : 
    1413         [ +  + ]:       57146 :                 if (hist_selec < cutoff)
    1414                 :       19636 :                     hist_selec = cutoff;
    1415         [ +  + ]:       37510 :                 else if (hist_selec > 1.0 - cutoff)
    1416                 :       14918 :                     hist_selec = 1.0 - cutoff;
    1417                 :             :             }
    1418                 :             :         }
    1419         [ +  - ]:         152 :         else if (sslot.nvalues > 1)
    1420                 :             :         {
    1421                 :             :             /*
    1422                 :             :              * If we get here, we have a histogram but it's not sorted the way
    1423                 :             :              * we want.  Do a brute-force search to see how many of the
    1424                 :             :              * entries satisfy the comparison condition, and take that
    1425                 :             :              * fraction as our estimate.  (This is identical to the inner loop
    1426                 :             :              * of histogram_selectivity; maybe share code?)
    1427                 :             :              */
    1428                 :         152 :             LOCAL_FCINFO(fcinfo, 2);
    1429                 :         152 :             int         nmatch = 0;
    1430                 :             : 
    1431                 :         152 :             InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
    1432                 :             :                                      NULL, NULL);
    1433                 :         152 :             fcinfo->args[0].isnull = false;
    1434                 :         152 :             fcinfo->args[1].isnull = false;
    1435                 :         152 :             fcinfo->args[1].value = constval;
    1436         [ +  + ]:      801772 :             for (int i = 0; i < sslot.nvalues; i++)
    1437                 :             :             {
    1438                 :             :                 Datum       fresult;
    1439                 :             : 
    1440                 :      801620 :                 fcinfo->args[0].value = sslot.values[i];
    1441                 :      801620 :                 fcinfo->isnull = false;
    1442                 :      801620 :                 fresult = FunctionCallInvoke(fcinfo);
    1443   [ +  -  +  + ]:      801620 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    1444                 :        1626 :                     nmatch++;
    1445                 :             :             }
    1446                 :         152 :             hist_selec = ((double) nmatch) / ((double) sslot.nvalues);
    1447                 :             : 
    1448                 :             :             /*
    1449                 :             :              * As above, clamp to a hundredth of the histogram resolution.
    1450                 :             :              * This case is surely even less trustworthy than the normal one,
    1451                 :             :              * so we shouldn't believe exact 0 or 1 selectivity.  (Maybe the
    1452                 :             :              * clamp should be more restrictive in this case?)
    1453                 :             :              */
    1454                 :             :             {
    1455                 :         152 :                 double      cutoff = 0.01 / (double) (sslot.nvalues - 1);
    1456                 :             : 
    1457         [ +  + ]:         152 :                 if (hist_selec < cutoff)
    1458                 :          10 :                     hist_selec = cutoff;
    1459         [ +  + ]:         142 :                 else if (hist_selec > 1.0 - cutoff)
    1460                 :          10 :                     hist_selec = 1.0 - cutoff;
    1461                 :             :             }
    1462                 :             :         }
    1463                 :             : 
    1464                 :      133168 :         free_attstatsslot(&sslot);
    1465                 :             :     }
    1466                 :             : 
    1467                 :      220763 :     return hist_selec;
    1468                 :             : }
    1469                 :             : 
    1470                 :             : /*
    1471                 :             :  * Common wrapper function for the selectivity estimators that simply
    1472                 :             :  * invoke scalarineqsel().
    1473                 :             :  */
    1474                 :             : static Datum
    1475                 :       38641 : scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
    1476                 :             : {
    1477                 :       38641 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    1478                 :       38641 :     Oid         operator = PG_GETARG_OID(1);
    1479                 :       38641 :     List       *args = (List *) PG_GETARG_POINTER(2);
    1480                 :       38641 :     int         varRelid = PG_GETARG_INT32(3);
    1481                 :       38641 :     Oid         collation = PG_GET_COLLATION();
    1482                 :             :     VariableStatData vardata;
    1483                 :             :     Node       *other;
    1484                 :             :     bool        varonleft;
    1485                 :             :     Datum       constval;
    1486                 :             :     Oid         consttype;
    1487                 :             :     double      selec;
    1488                 :             : 
    1489                 :             :     /*
    1490                 :             :      * If expression is not variable op something or something op variable,
    1491                 :             :      * then punt and return a default estimate.
    1492                 :             :      */
    1493         [ +  + ]:       38641 :     if (!get_restriction_variable(root, args, varRelid,
    1494                 :             :                                   &vardata, &other, &varonleft))
    1495                 :         462 :         PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    1496                 :             : 
    1497                 :             :     /*
    1498                 :             :      * Can't do anything useful if the something is not a constant, either.
    1499                 :             :      */
    1500         [ +  + ]:       38179 :     if (!IsA(other, Const))
    1501                 :             :     {
    1502         [ +  + ]:        2365 :         ReleaseVariableStats(vardata);
    1503                 :        2365 :         PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    1504                 :             :     }
    1505                 :             : 
    1506                 :             :     /*
    1507                 :             :      * If the constant is NULL, assume operator is strict and return zero, ie,
    1508                 :             :      * operator will never return TRUE.
    1509                 :             :      */
    1510         [ +  + ]:       35814 :     if (((Const *) other)->constisnull)
    1511                 :             :     {
    1512         [ +  + ]:          55 :         ReleaseVariableStats(vardata);
    1513                 :          55 :         PG_RETURN_FLOAT8(0.0);
    1514                 :             :     }
    1515                 :       35759 :     constval = ((Const *) other)->constvalue;
    1516                 :       35759 :     consttype = ((Const *) other)->consttype;
    1517                 :             : 
    1518                 :             :     /*
    1519                 :             :      * Force the var to be on the left to simplify logic in scalarineqsel.
    1520                 :             :      */
    1521         [ +  + ]:       35759 :     if (!varonleft)
    1522                 :             :     {
    1523                 :         318 :         operator = get_commutator(operator);
    1524         [ -  + ]:         318 :         if (!operator)
    1525                 :             :         {
    1526                 :             :             /* Use default selectivity (should we raise an error instead?) */
    1527         [ #  # ]:           0 :             ReleaseVariableStats(vardata);
    1528                 :           0 :             PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    1529                 :             :         }
    1530                 :         318 :         isgt = !isgt;
    1531                 :             :     }
    1532                 :             : 
    1533                 :             :     /* The rest of the work is done by scalarineqsel(). */
    1534                 :       35759 :     selec = scalarineqsel(root, operator, isgt, iseq, collation,
    1535                 :             :                           &vardata, constval, consttype);
    1536                 :             : 
    1537         [ +  + ]:       35759 :     ReleaseVariableStats(vardata);
    1538                 :             : 
    1539                 :       35759 :     PG_RETURN_FLOAT8((float8) selec);
    1540                 :             : }
    1541                 :             : 
    1542                 :             : /*
    1543                 :             :  *      scalarltsel     - Selectivity of "<" for scalars.
    1544                 :             :  */
    1545                 :             : Datum
    1546                 :       12199 : scalarltsel(PG_FUNCTION_ARGS)
    1547                 :             : {
    1548                 :       12199 :     return scalarineqsel_wrapper(fcinfo, false, false);
    1549                 :             : }
    1550                 :             : 
    1551                 :             : /*
    1552                 :             :  *      scalarlesel     - Selectivity of "<=" for scalars.
    1553                 :             :  */
    1554                 :             : Datum
    1555                 :        3842 : scalarlesel(PG_FUNCTION_ARGS)
    1556                 :             : {
    1557                 :        3842 :     return scalarineqsel_wrapper(fcinfo, false, true);
    1558                 :             : }
    1559                 :             : 
    1560                 :             : /*
    1561                 :             :  *      scalargtsel     - Selectivity of ">" for scalars.
    1562                 :             :  */
    1563                 :             : Datum
    1564                 :       12137 : scalargtsel(PG_FUNCTION_ARGS)
    1565                 :             : {
    1566                 :       12137 :     return scalarineqsel_wrapper(fcinfo, true, false);
    1567                 :             : }
    1568                 :             : 
    1569                 :             : /*
    1570                 :             :  *      scalargesel     - Selectivity of ">=" for scalars.
    1571                 :             :  */
    1572                 :             : Datum
    1573                 :       10463 : scalargesel(PG_FUNCTION_ARGS)
    1574                 :             : {
    1575                 :       10463 :     return scalarineqsel_wrapper(fcinfo, true, true);
    1576                 :             : }
    1577                 :             : 
    1578                 :             : /*
    1579                 :             :  *      boolvarsel      - Selectivity of Boolean variable.
    1580                 :             :  *
    1581                 :             :  * This can actually be called on any boolean-valued expression.  If it
    1582                 :             :  * involves only Vars of the specified relation, and if there are statistics
    1583                 :             :  * about the Var or expression (the latter is possible if it's indexed) then
    1584                 :             :  * we'll produce a real estimate; otherwise it's just a default.
    1585                 :             :  */
    1586                 :             : Selectivity
    1587                 :       46553 : boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
    1588                 :             : {
    1589                 :             :     VariableStatData vardata;
    1590                 :             :     double      selec;
    1591                 :             : 
    1592                 :       46553 :     examine_variable(root, arg, varRelid, &vardata);
    1593         [ +  + ]:       46553 :     if (HeapTupleIsValid(vardata.statsTuple))
    1594                 :             :     {
    1595                 :             :         /*
    1596                 :             :          * A boolean variable V is equivalent to the clause V = 't', so we
    1597                 :             :          * compute the selectivity as if that is what we have.
    1598                 :             :          */
    1599                 :       21750 :         selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
    1600                 :             :                              BoolGetDatum(true), false, true, false);
    1601                 :             :     }
    1602         [ +  + ]:       24803 :     else if (is_funcclause(arg))
    1603                 :             :     {
    1604                 :             :         /*
    1605                 :             :          * If we have no stats and it's a function call, estimate 0.3333333.
    1606                 :             :          * This seems a pretty unprincipled choice, but Postgres has been
    1607                 :             :          * using that estimate for function calls since 1992.  The hoariness
    1608                 :             :          * of this behavior suggests that we should not be in too much hurry
    1609                 :             :          * to use another value.
    1610                 :             :          */
    1611                 :       11525 :         selec = 0.3333333;
    1612                 :             :     }
    1613                 :             :     else
    1614                 :             :     {
    1615                 :             :         /* Otherwise, the default estimate is 0.5 */
    1616                 :       13278 :         selec = 0.5;
    1617                 :             :     }
    1618         [ +  + ]:       46553 :     ReleaseVariableStats(vardata);
    1619                 :       46553 :     return selec;
    1620                 :             : }
    1621                 :             : 
    1622                 :             : /*
    1623                 :             :  *      booltestsel     - Selectivity of BooleanTest Node.
    1624                 :             :  */
    1625                 :             : Selectivity
    1626                 :         791 : booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
    1627                 :             :             int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
    1628                 :             : {
    1629                 :             :     VariableStatData vardata;
    1630                 :             :     double      selec;
    1631                 :             : 
    1632                 :         791 :     examine_variable(root, arg, varRelid, &vardata);
    1633                 :             : 
    1634         [ +  + ]:         791 :     if (HeapTupleIsValid(vardata.statsTuple))
    1635                 :             :     {
    1636                 :             :         Form_pg_statistic stats;
    1637                 :             :         double      freq_null;
    1638                 :             :         AttStatsSlot sslot;
    1639                 :             : 
    1640                 :          20 :         stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
    1641                 :          20 :         freq_null = stats->stanullfrac;
    1642                 :             : 
    1643         [ +  + ]:          20 :         if (get_attstatsslot(&sslot, vardata.statsTuple,
    1644                 :             :                              STATISTIC_KIND_MCV, InvalidOid,
    1645                 :             :                              ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)
    1646         [ +  - ]:          10 :             && sslot.nnumbers > 0)
    1647                 :          10 :         {
    1648                 :             :             double      freq_true;
    1649                 :             :             double      freq_false;
    1650                 :             : 
    1651                 :             :             /*
    1652                 :             :              * Get first MCV frequency and derive frequency for true.
    1653                 :             :              */
    1654         [ -  + ]:          10 :             if (DatumGetBool(sslot.values[0]))
    1655                 :           0 :                 freq_true = sslot.numbers[0];
    1656                 :             :             else
    1657                 :          10 :                 freq_true = 1.0 - sslot.numbers[0] - freq_null;
    1658                 :             : 
    1659                 :             :             /*
    1660                 :             :              * Next derive frequency for false. Then use these as appropriate
    1661                 :             :              * to derive frequency for each case.
    1662                 :             :              */
    1663                 :          10 :             freq_false = 1.0 - freq_true - freq_null;
    1664                 :             : 
    1665   [ -  -  +  -  :          10 :             switch (booltesttype)
                -  -  - ]
    1666                 :             :             {
    1667                 :           0 :                 case IS_UNKNOWN:
    1668                 :             :                     /* select only NULL values */
    1669                 :           0 :                     selec = freq_null;
    1670                 :           0 :                     break;
    1671                 :           0 :                 case IS_NOT_UNKNOWN:
    1672                 :             :                     /* select non-NULL values */
    1673                 :           0 :                     selec = 1.0 - freq_null;
    1674                 :           0 :                     break;
    1675                 :          10 :                 case IS_TRUE:
    1676                 :             :                     /* select only TRUE values */
    1677                 :          10 :                     selec = freq_true;
    1678                 :          10 :                     break;
    1679                 :           0 :                 case IS_NOT_TRUE:
    1680                 :             :                     /* select non-TRUE values */
    1681                 :           0 :                     selec = 1.0 - freq_true;
    1682                 :           0 :                     break;
    1683                 :           0 :                 case IS_FALSE:
    1684                 :             :                     /* select only FALSE values */
    1685                 :           0 :                     selec = freq_false;
    1686                 :           0 :                     break;
    1687                 :           0 :                 case IS_NOT_FALSE:
    1688                 :             :                     /* select non-FALSE values */
    1689                 :           0 :                     selec = 1.0 - freq_false;
    1690                 :           0 :                     break;
    1691                 :           0 :                 default:
    1692         [ #  # ]:           0 :                     elog(ERROR, "unrecognized booltesttype: %d",
    1693                 :             :                          (int) booltesttype);
    1694                 :             :                     selec = 0.0;    /* Keep compiler quiet */
    1695                 :             :                     break;
    1696                 :             :             }
    1697                 :             : 
    1698                 :          10 :             free_attstatsslot(&sslot);
    1699                 :             :         }
    1700                 :             :         else
    1701                 :             :         {
    1702                 :             :             /*
    1703                 :             :              * No most-common-value info available. Still have null fraction
    1704                 :             :              * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
    1705                 :             :              * for null fraction and assume a 50-50 split of TRUE and FALSE.
    1706                 :             :              */
    1707   [ +  -  -  -  :          10 :             switch (booltesttype)
                      - ]
    1708                 :             :             {
    1709                 :          10 :                 case IS_UNKNOWN:
    1710                 :             :                     /* select only NULL values */
    1711                 :          10 :                     selec = freq_null;
    1712                 :          10 :                     break;
    1713                 :           0 :                 case IS_NOT_UNKNOWN:
    1714                 :             :                     /* select non-NULL values */
    1715                 :           0 :                     selec = 1.0 - freq_null;
    1716                 :           0 :                     break;
    1717                 :           0 :                 case IS_TRUE:
    1718                 :             :                 case IS_FALSE:
    1719                 :             :                     /* Assume we select half of the non-NULL values */
    1720                 :           0 :                     selec = (1.0 - freq_null) / 2.0;
    1721                 :           0 :                     break;
    1722                 :           0 :                 case IS_NOT_TRUE:
    1723                 :             :                 case IS_NOT_FALSE:
    1724                 :             :                     /* Assume we select NULLs plus half of the non-NULLs */
    1725                 :             :                     /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
    1726                 :           0 :                     selec = (freq_null + 1.0) / 2.0;
    1727                 :           0 :                     break;
    1728                 :           0 :                 default:
    1729         [ #  # ]:           0 :                     elog(ERROR, "unrecognized booltesttype: %d",
    1730                 :             :                          (int) booltesttype);
    1731                 :             :                     selec = 0.0;    /* Keep compiler quiet */
    1732                 :             :                     break;
    1733                 :             :             }
    1734                 :             :         }
    1735                 :             :     }
    1736                 :             :     else
    1737                 :             :     {
    1738                 :             :         /*
    1739                 :             :          * If we can't get variable statistics for the argument, perhaps
    1740                 :             :          * clause_selectivity can do something with it.  We ignore the
    1741                 :             :          * possibility of a NULL value when using clause_selectivity, and just
    1742                 :             :          * assume the value is either TRUE or FALSE.
    1743                 :             :          */
    1744   [ +  +  +  +  :         771 :         switch (booltesttype)
                      - ]
    1745                 :             :         {
    1746                 :          40 :             case IS_UNKNOWN:
    1747                 :          40 :                 selec = DEFAULT_UNK_SEL;
    1748                 :          40 :                 break;
    1749                 :          90 :             case IS_NOT_UNKNOWN:
    1750                 :          90 :                 selec = DEFAULT_NOT_UNK_SEL;
    1751                 :          90 :                 break;
    1752                 :         220 :             case IS_TRUE:
    1753                 :             :             case IS_NOT_FALSE:
    1754                 :         220 :                 selec = (double) clause_selectivity(root, arg,
    1755                 :             :                                                     varRelid,
    1756                 :             :                                                     jointype, sjinfo);
    1757                 :         220 :                 break;
    1758                 :         421 :             case IS_FALSE:
    1759                 :             :             case IS_NOT_TRUE:
    1760                 :         421 :                 selec = 1.0 - (double) clause_selectivity(root, arg,
    1761                 :             :                                                           varRelid,
    1762                 :             :                                                           jointype, sjinfo);
    1763                 :         421 :                 break;
    1764                 :           0 :             default:
    1765         [ #  # ]:           0 :                 elog(ERROR, "unrecognized booltesttype: %d",
    1766                 :             :                      (int) booltesttype);
    1767                 :             :                 selec = 0.0;    /* Keep compiler quiet */
    1768                 :             :                 break;
    1769                 :             :         }
    1770                 :             :     }
    1771                 :             : 
    1772         [ +  + ]:         791 :     ReleaseVariableStats(vardata);
    1773                 :             : 
    1774                 :             :     /* result should be in range, but make sure... */
    1775   [ -  +  -  + ]:         791 :     CLAMP_PROBABILITY(selec);
    1776                 :             : 
    1777                 :         791 :     return (Selectivity) selec;
    1778                 :             : }
    1779                 :             : 
    1780                 :             : /*
    1781                 :             :  *      nulltestsel     - Selectivity of NullTest Node.
    1782                 :             :  */
    1783                 :             : Selectivity
    1784                 :       14113 : nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
    1785                 :             :             int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
    1786                 :             : {
    1787                 :             :     VariableStatData vardata;
    1788                 :             :     double      selec;
    1789                 :             : 
    1790                 :       14113 :     examine_variable(root, arg, varRelid, &vardata);
    1791                 :             : 
    1792         [ +  + ]:       14113 :     if (HeapTupleIsValid(vardata.statsTuple))
    1793                 :             :     {
    1794                 :             :         Form_pg_statistic stats;
    1795                 :             :         double      freq_null;
    1796                 :             : 
    1797                 :        7566 :         stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
    1798                 :        7566 :         freq_null = stats->stanullfrac;
    1799                 :             : 
    1800      [ +  +  - ]:        7566 :         switch (nulltesttype)
    1801                 :             :         {
    1802                 :        5972 :             case IS_NULL:
    1803                 :             : 
    1804                 :             :                 /*
    1805                 :             :                  * Use freq_null directly.
    1806                 :             :                  */
    1807                 :        5972 :                 selec = freq_null;
    1808                 :        5972 :                 break;
    1809                 :        1594 :             case IS_NOT_NULL:
    1810                 :             : 
    1811                 :             :                 /*
    1812                 :             :                  * Select not unknown (not null) values. Calculate from
    1813                 :             :                  * freq_null.
    1814                 :             :                  */
    1815                 :        1594 :                 selec = 1.0 - freq_null;
    1816                 :        1594 :                 break;
    1817                 :           0 :             default:
    1818         [ #  # ]:           0 :                 elog(ERROR, "unrecognized nulltesttype: %d",
    1819                 :             :                      (int) nulltesttype);
    1820                 :             :                 return (Selectivity) 0; /* keep compiler quiet */
    1821                 :             :         }
    1822                 :             :     }
    1823   [ +  -  +  + ]:        6547 :     else if (vardata.var && IsA(vardata.var, Var) &&
    1824         [ +  + ]:        6013 :              ((Var *) vardata.var)->varattno < 0)
    1825                 :             :     {
    1826                 :             :         /*
    1827                 :             :          * There are no stats for system columns, but we know they are never
    1828                 :             :          * NULL.
    1829                 :             :          */
    1830         [ +  - ]:          89 :         selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
    1831                 :             :     }
    1832                 :             :     else
    1833                 :             :     {
    1834                 :             :         /*
    1835                 :             :          * No ANALYZE stats available, so make a guess
    1836                 :             :          */
    1837      [ +  +  - ]:        6458 :         switch (nulltesttype)
    1838                 :             :         {
    1839                 :        1648 :             case IS_NULL:
    1840                 :        1648 :                 selec = DEFAULT_UNK_SEL;
    1841                 :        1648 :                 break;
    1842                 :        4810 :             case IS_NOT_NULL:
    1843                 :        4810 :                 selec = DEFAULT_NOT_UNK_SEL;
    1844                 :        4810 :                 break;
    1845                 :           0 :             default:
    1846         [ #  # ]:           0 :                 elog(ERROR, "unrecognized nulltesttype: %d",
    1847                 :             :                      (int) nulltesttype);
    1848                 :             :                 return (Selectivity) 0; /* keep compiler quiet */
    1849                 :             :         }
    1850                 :             :     }
    1851                 :             : 
    1852         [ +  + ]:       14113 :     ReleaseVariableStats(vardata);
    1853                 :             : 
    1854                 :             :     /* result should be in range, but make sure... */
    1855   [ -  +  -  + ]:       14113 :     CLAMP_PROBABILITY(selec);
    1856                 :             : 
    1857                 :       14113 :     return (Selectivity) selec;
    1858                 :             : }
    1859                 :             : 
    1860                 :             : /*
    1861                 :             :  * strip_array_coercion - strip binary-compatible relabeling from an array expr
    1862                 :             :  *
    1863                 :             :  * For array values, the parser normally generates ArrayCoerceExpr conversions,
    1864                 :             :  * but it seems possible that RelabelType might show up.  Also, the planner
    1865                 :             :  * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
    1866                 :             :  * so we need to be ready to deal with more than one level.
    1867                 :             :  */
    1868                 :             : static Node *
    1869                 :      102421 : strip_array_coercion(Node *node)
    1870                 :             : {
    1871                 :             :     for (;;)
    1872                 :             :     {
    1873   [ +  -  +  + ]:      102509 :         if (node && IsA(node, ArrayCoerceExpr))
    1874                 :          88 :         {
    1875                 :        1763 :             ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
    1876                 :             : 
    1877                 :             :             /*
    1878                 :             :              * If the per-element expression is just a RelabelType on top of
    1879                 :             :              * CaseTestExpr, then we know it's a binary-compatible relabeling.
    1880                 :             :              */
    1881         [ +  + ]:        1763 :             if (IsA(acoerce->elemexpr, RelabelType) &&
    1882         [ +  - ]:          88 :                 IsA(((RelabelType *) acoerce->elemexpr)->arg, CaseTestExpr))
    1883                 :          88 :                 node = (Node *) acoerce->arg;
    1884                 :             :             else
    1885                 :             :                 break;
    1886                 :             :         }
    1887   [ +  -  -  + ]:      100746 :         else if (node && IsA(node, RelabelType))
    1888                 :             :         {
    1889                 :             :             /* We don't really expect this case, but may as well cope */
    1890                 :           0 :             node = (Node *) ((RelabelType *) node)->arg;
    1891                 :             :         }
    1892                 :             :         else
    1893                 :             :             break;
    1894                 :             :     }
    1895                 :      102421 :     return node;
    1896                 :             : }
    1897                 :             : 
    1898                 :             : /*
    1899                 :             :  *      scalararraysel      - Selectivity of ScalarArrayOpExpr Node.
    1900                 :             :  */
    1901                 :             : Selectivity
    1902                 :       17593 : scalararraysel(PlannerInfo *root,
    1903                 :             :                ScalarArrayOpExpr *clause,
    1904                 :             :                bool is_join_clause,
    1905                 :             :                int varRelid,
    1906                 :             :                JoinType jointype,
    1907                 :             :                SpecialJoinInfo *sjinfo)
    1908                 :             : {
    1909                 :       17593 :     Oid         operator = clause->opno;
    1910                 :       17593 :     bool        useOr = clause->useOr;
    1911                 :       17593 :     bool        isEquality = false;
    1912                 :       17593 :     bool        isInequality = false;
    1913                 :             :     Node       *leftop;
    1914                 :             :     Node       *rightop;
    1915                 :             :     Oid         nominal_element_type;
    1916                 :             :     Oid         nominal_element_collation;
    1917                 :             :     TypeCacheEntry *typentry;
    1918                 :             :     RegProcedure oprsel;
    1919                 :             :     FmgrInfo    oprselproc;
    1920                 :             :     Selectivity s1;
    1921                 :             :     Selectivity s1disjoint;
    1922                 :             : 
    1923                 :             :     /* First, deconstruct the expression */
    1924                 :             :     Assert(list_length(clause->args) == 2);
    1925                 :       17593 :     leftop = (Node *) linitial(clause->args);
    1926                 :       17593 :     rightop = (Node *) lsecond(clause->args);
    1927                 :             : 
    1928                 :             :     /* aggressively reduce both sides to constants */
    1929                 :       17593 :     leftop = estimate_expression_value(root, leftop);
    1930                 :       17593 :     rightop = estimate_expression_value(root, rightop);
    1931                 :             : 
    1932                 :             :     /* get nominal (after relabeling) element type of rightop */
    1933                 :       17593 :     nominal_element_type = get_base_element_type(exprType(rightop));
    1934         [ -  + ]:       17593 :     if (!OidIsValid(nominal_element_type))
    1935                 :           0 :         return (Selectivity) 0.5;   /* probably shouldn't happen */
    1936                 :             :     /* get nominal collation, too, for generating constants */
    1937                 :       17593 :     nominal_element_collation = exprCollation(rightop);
    1938                 :             : 
    1939                 :             :     /* look through any binary-compatible relabeling of rightop */
    1940                 :       17593 :     rightop = strip_array_coercion(rightop);
    1941                 :             : 
    1942                 :             :     /*
    1943                 :             :      * Detect whether the operator is the default equality or inequality
    1944                 :             :      * operator of the array element type.
    1945                 :             :      */
    1946                 :       17593 :     typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
    1947         [ +  + ]:       17593 :     if (OidIsValid(typentry->eq_opr))
    1948                 :             :     {
    1949         [ +  + ]:       17591 :         if (operator == typentry->eq_opr)
    1950                 :       15412 :             isEquality = true;
    1951         [ +  + ]:        2179 :         else if (get_negator(operator) == typentry->eq_opr)
    1952                 :        1680 :             isInequality = true;
    1953                 :             :     }
    1954                 :             : 
    1955                 :             :     /*
    1956                 :             :      * If it is equality or inequality, we might be able to estimate this as a
    1957                 :             :      * form of array containment; for instance "const = ANY(column)" can be
    1958                 :             :      * treated as "ARRAY[const] <@ column".  scalararraysel_containment tries
    1959                 :             :      * that, and returns the selectivity estimate if successful, or -1 if not.
    1960                 :             :      */
    1961   [ +  +  +  +  :       17593 :     if ((isEquality || isInequality) && !is_join_clause)
                   +  + ]
    1962                 :             :     {
    1963                 :       17091 :         s1 = scalararraysel_containment(root, leftop, rightop,
    1964                 :             :                                         nominal_element_type,
    1965                 :             :                                         isEquality, useOr, varRelid);
    1966         [ +  + ]:       17091 :         if (s1 >= 0.0)
    1967                 :          95 :             return s1;
    1968                 :             :     }
    1969                 :             : 
    1970                 :             :     /*
    1971                 :             :      * Look up the underlying operator's selectivity estimator. Punt if it
    1972                 :             :      * hasn't got one.
    1973                 :             :      */
    1974         [ +  + ]:       17498 :     if (is_join_clause)
    1975                 :           1 :         oprsel = get_oprjoin(operator);
    1976                 :             :     else
    1977                 :       17497 :         oprsel = get_oprrest(operator);
    1978         [ +  + ]:       17498 :     if (!oprsel)
    1979                 :           2 :         return (Selectivity) 0.5;
    1980                 :       17496 :     fmgr_info(oprsel, &oprselproc);
    1981                 :             : 
    1982                 :             :     /*
    1983                 :             :      * In the array-containment check above, we must only believe that an
    1984                 :             :      * operator is equality or inequality if it is the default btree equality
    1985                 :             :      * operator (or its negator) for the element type, since those are the
    1986                 :             :      * operators that array containment will use.  But in what follows, we can
    1987                 :             :      * be a little laxer, and also believe that any operators using eqsel() or
    1988                 :             :      * neqsel() as selectivity estimator act like equality or inequality.
    1989                 :             :      */
    1990   [ +  +  +  + ]:       17496 :     if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
    1991                 :       15487 :         isEquality = true;
    1992   [ +  +  -  + ]:        2009 :     else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
    1993                 :        1609 :         isInequality = true;
    1994                 :             : 
    1995                 :             :     /*
    1996                 :             :      * We consider three cases:
    1997                 :             :      *
    1998                 :             :      * 1. rightop is an Array constant: deconstruct the array, apply the
    1999                 :             :      * operator's selectivity function for each array element, and merge the
    2000                 :             :      * results in the same way that clausesel.c does for AND/OR combinations.
    2001                 :             :      *
    2002                 :             :      * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
    2003                 :             :      * function for each element of the ARRAY[] construct, and merge.
    2004                 :             :      *
    2005                 :             :      * 3. otherwise, make a guess ...
    2006                 :             :      */
    2007   [ +  -  +  + ]:       17496 :     if (rightop && IsA(rightop, Const))
    2008                 :       14135 :     {
    2009                 :       14165 :         Datum       arraydatum = ((Const *) rightop)->constvalue;
    2010                 :       14165 :         bool        arrayisnull = ((Const *) rightop)->constisnull;
    2011                 :             :         ArrayType  *arrayval;
    2012                 :             :         int16       elmlen;
    2013                 :             :         bool        elmbyval;
    2014                 :             :         char        elmalign;
    2015                 :             :         int         num_elems;
    2016                 :             :         Datum      *elem_values;
    2017                 :             :         bool       *elem_nulls;
    2018                 :             :         int         i;
    2019                 :             : 
    2020         [ +  + ]:       14165 :         if (arrayisnull)        /* qual can't succeed if null array */
    2021                 :          30 :             return (Selectivity) 0.0;
    2022                 :       14140 :         arrayval = DatumGetArrayTypeP(arraydatum);
    2023                 :             : 
    2024                 :             :         /*
    2025                 :             :          * When the array contains a NULL constant, same as var_eq_const, we
    2026                 :             :          * assume the operator is strict and nothing will match, thus return
    2027                 :             :          * 0.0.
    2028                 :             :          */
    2029   [ +  +  +  + ]:       14140 :         if (!useOr && array_contains_nulls(arrayval))
    2030                 :           5 :             return (Selectivity) 0.0;
    2031                 :             : 
    2032                 :       14135 :         get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
    2033                 :             :                              &elmlen, &elmbyval, &elmalign);
    2034                 :       14135 :         deconstruct_array(arrayval,
    2035                 :             :                           ARR_ELEMTYPE(arrayval),
    2036                 :             :                           elmlen, elmbyval, elmalign,
    2037                 :             :                           &elem_values, &elem_nulls, &num_elems);
    2038                 :             : 
    2039                 :             :         /*
    2040                 :             :          * For generic operators, we assume the probability of success is
    2041                 :             :          * independent for each array element.  But for "= ANY" or "<> ALL",
    2042                 :             :          * if the array elements are distinct (which'd typically be the case)
    2043                 :             :          * then the probabilities are disjoint, and we should just sum them.
    2044                 :             :          *
    2045                 :             :          * If we were being really tense we would try to confirm that the
    2046                 :             :          * elements are all distinct, but that would be expensive and it
    2047                 :             :          * doesn't seem to be worth the cycles; it would amount to penalizing
    2048                 :             :          * well-written queries in favor of poorly-written ones.  However, we
    2049                 :             :          * do protect ourselves a little bit by checking whether the
    2050                 :             :          * disjointness assumption leads to an impossible (out of range)
    2051                 :             :          * probability; if so, we fall back to the normal calculation.
    2052                 :             :          */
    2053         [ +  + ]:       14135 :         s1 = s1disjoint = (useOr ? 0.0 : 1.0);
    2054                 :             : 
    2055         [ +  + ]:       54820 :         for (i = 0; i < num_elems; i++)
    2056                 :             :         {
    2057                 :             :             List       *args;
    2058                 :             :             Selectivity s2;
    2059                 :             : 
    2060                 :       40685 :             args = list_make2(leftop,
    2061                 :             :                               makeConst(nominal_element_type,
    2062                 :             :                                         -1,
    2063                 :             :                                         nominal_element_collation,
    2064                 :             :                                         elmlen,
    2065                 :             :                                         elem_values[i],
    2066                 :             :                                         elem_nulls[i],
    2067                 :             :                                         elmbyval));
    2068         [ -  + ]:       40685 :             if (is_join_clause)
    2069                 :           0 :                 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
    2070                 :             :                                                       clause->inputcollid,
    2071                 :             :                                                       PointerGetDatum(root),
    2072                 :             :                                                       ObjectIdGetDatum(operator),
    2073                 :             :                                                       PointerGetDatum(args),
    2074                 :             :                                                       Int16GetDatum(jointype),
    2075                 :             :                                                       PointerGetDatum(sjinfo)));
    2076                 :             :             else
    2077                 :       40685 :                 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
    2078                 :             :                                                       clause->inputcollid,
    2079                 :             :                                                       PointerGetDatum(root),
    2080                 :             :                                                       ObjectIdGetDatum(operator),
    2081                 :             :                                                       PointerGetDatum(args),
    2082                 :             :                                                       Int32GetDatum(varRelid)));
    2083                 :             : 
    2084         [ +  + ]:       40685 :             if (useOr)
    2085                 :             :             {
    2086                 :       35475 :                 s1 = s1 + s2 - s1 * s2;
    2087         [ +  + ]:       35475 :                 if (isEquality)
    2088                 :       34605 :                     s1disjoint += s2;
    2089                 :             :             }
    2090                 :             :             else
    2091                 :             :             {
    2092                 :        5210 :                 s1 = s1 * s2;
    2093         [ +  + ]:        5210 :                 if (isInequality)
    2094                 :        4950 :                     s1disjoint += s2 - 1.0;
    2095                 :             :             }
    2096                 :             :         }
    2097                 :             : 
    2098                 :             :         /* accept disjoint-probability estimate if in range */
    2099   [ +  +  +  +  :       14135 :         if ((useOr ? isEquality : isInequality) &&
                   +  + ]
    2100         [ +  + ]:       13610 :             s1disjoint >= 0.0 && s1disjoint <= 1.0)
    2101                 :       13563 :             s1 = s1disjoint;
    2102                 :             :     }
    2103   [ +  -  +  + ]:        3331 :     else if (rightop && IsA(rightop, ArrayExpr) &&
    2104         [ +  - ]:         269 :              !((ArrayExpr *) rightop)->multidims)
    2105                 :         264 :     {
    2106                 :         269 :         ArrayExpr  *arrayexpr = (ArrayExpr *) rightop;
    2107                 :             :         int16       elmlen;
    2108                 :             :         bool        elmbyval;
    2109                 :             :         ListCell   *l;
    2110                 :             : 
    2111                 :         269 :         get_typlenbyval(arrayexpr->element_typeid,
    2112                 :             :                         &elmlen, &elmbyval);
    2113                 :             : 
    2114                 :             :         /*
    2115                 :             :          * We use the assumption of disjoint probabilities here too, although
    2116                 :             :          * the odds of equal array elements are rather higher if the elements
    2117                 :             :          * are not all constants (which they won't be, else constant folding
    2118                 :             :          * would have reduced the ArrayExpr to a Const).  In this path it's
    2119                 :             :          * critical to have the sanity check on the s1disjoint estimate.
    2120                 :             :          */
    2121         [ +  + ]:         269 :         s1 = s1disjoint = (useOr ? 0.0 : 1.0);
    2122                 :             : 
    2123   [ +  -  +  +  :         967 :         foreach(l, arrayexpr->elements)
                   +  + ]
    2124                 :             :         {
    2125                 :         703 :             Node       *elem = (Node *) lfirst(l);
    2126                 :             :             List       *args;
    2127                 :             :             Selectivity s2;
    2128                 :             : 
    2129                 :             :             /*
    2130                 :             :              * When the array contains a NULL constant, same as var_eq_const,
    2131                 :             :              * we assume the operator is strict and nothing will match, thus
    2132                 :             :              * return 0.0.
    2133                 :             :              */
    2134   [ +  +  +  +  :         703 :             if (!useOr && IsA(elem, Const) && ((Const *) elem)->constisnull)
                   +  + ]
    2135                 :           5 :                 return (Selectivity) 0.0;
    2136                 :             : 
    2137                 :             :             /*
    2138                 :             :              * Theoretically, if elem isn't of nominal_element_type we should
    2139                 :             :              * insert a RelabelType, but it seems unlikely that any operator
    2140                 :             :              * estimation function would really care ...
    2141                 :             :              */
    2142                 :         698 :             args = list_make2(leftop, elem);
    2143         [ +  + ]:         698 :             if (is_join_clause)
    2144                 :           3 :                 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
    2145                 :             :                                                       clause->inputcollid,
    2146                 :             :                                                       PointerGetDatum(root),
    2147                 :             :                                                       ObjectIdGetDatum(operator),
    2148                 :             :                                                       PointerGetDatum(args),
    2149                 :             :                                                       Int16GetDatum(jointype),
    2150                 :             :                                                       PointerGetDatum(sjinfo)));
    2151                 :             :             else
    2152                 :         695 :                 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
    2153                 :             :                                                       clause->inputcollid,
    2154                 :             :                                                       PointerGetDatum(root),
    2155                 :             :                                                       ObjectIdGetDatum(operator),
    2156                 :             :                                                       PointerGetDatum(args),
    2157                 :             :                                                       Int32GetDatum(varRelid)));
    2158                 :             : 
    2159         [ +  + ]:         698 :             if (useOr)
    2160                 :             :             {
    2161                 :         678 :                 s1 = s1 + s2 - s1 * s2;
    2162         [ +  - ]:         678 :                 if (isEquality)
    2163                 :         678 :                     s1disjoint += s2;
    2164                 :             :             }
    2165                 :             :             else
    2166                 :             :             {
    2167                 :          20 :                 s1 = s1 * s2;
    2168         [ +  - ]:          20 :                 if (isInequality)
    2169                 :          20 :                     s1disjoint += s2 - 1.0;
    2170                 :             :             }
    2171                 :             :         }
    2172                 :             : 
    2173                 :             :         /* accept disjoint-probability estimate if in range */
    2174   [ +  -  +  -  :         264 :         if ((useOr ? isEquality : isInequality) &&
                   +  - ]
    2175         [ +  - ]:         264 :             s1disjoint >= 0.0 && s1disjoint <= 1.0)
    2176                 :         264 :             s1 = s1disjoint;
    2177                 :             :     }
    2178                 :             :     else
    2179                 :             :     {
    2180                 :             :         CaseTestExpr *dummyexpr;
    2181                 :             :         List       *args;
    2182                 :             :         Selectivity s2;
    2183                 :             :         int         i;
    2184                 :             : 
    2185                 :             :         /*
    2186                 :             :          * We need a dummy rightop to pass to the operator selectivity
    2187                 :             :          * routine.  It can be pretty much anything that doesn't look like a
    2188                 :             :          * constant; CaseTestExpr is a convenient choice.
    2189                 :             :          */
    2190                 :        3062 :         dummyexpr = makeNode(CaseTestExpr);
    2191                 :        3062 :         dummyexpr->typeId = nominal_element_type;
    2192                 :        3062 :         dummyexpr->typeMod = -1;
    2193                 :        3062 :         dummyexpr->collation = clause->inputcollid;
    2194                 :        3062 :         args = list_make2(leftop, dummyexpr);
    2195         [ -  + ]:        3062 :         if (is_join_clause)
    2196                 :           0 :             s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
    2197                 :             :                                                   clause->inputcollid,
    2198                 :             :                                                   PointerGetDatum(root),
    2199                 :             :                                                   ObjectIdGetDatum(operator),
    2200                 :             :                                                   PointerGetDatum(args),
    2201                 :             :                                                   Int16GetDatum(jointype),
    2202                 :             :                                                   PointerGetDatum(sjinfo)));
    2203                 :             :         else
    2204                 :        3062 :             s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
    2205                 :             :                                                   clause->inputcollid,
    2206                 :             :                                                   PointerGetDatum(root),
    2207                 :             :                                                   ObjectIdGetDatum(operator),
    2208                 :             :                                                   PointerGetDatum(args),
    2209                 :             :                                                   Int32GetDatum(varRelid)));
    2210         [ +  - ]:        3062 :         s1 = useOr ? 0.0 : 1.0;
    2211                 :             : 
    2212                 :             :         /*
    2213                 :             :          * Arbitrarily assume 10 elements in the eventual array value (see
    2214                 :             :          * also estimate_array_length).  We don't risk an assumption of
    2215                 :             :          * disjoint probabilities here.
    2216                 :             :          */
    2217         [ +  + ]:       33682 :         for (i = 0; i < 10; i++)
    2218                 :             :         {
    2219         [ +  - ]:       30620 :             if (useOr)
    2220                 :       30620 :                 s1 = s1 + s2 - s1 * s2;
    2221                 :             :             else
    2222                 :           0 :                 s1 = s1 * s2;
    2223                 :             :         }
    2224                 :             :     }
    2225                 :             : 
    2226                 :             :     /* result should be in range, but make sure... */
    2227   [ -  +  -  + ]:       17461 :     CLAMP_PROBABILITY(s1);
    2228                 :             : 
    2229                 :       17461 :     return s1;
    2230                 :             : }
    2231                 :             : 
    2232                 :             : /*
    2233                 :             :  * Estimate number of elements in the array yielded by an expression.
    2234                 :             :  *
    2235                 :             :  * Note: the result is integral, but we use "double" to avoid overflow
    2236                 :             :  * concerns.  Most callers will use it in double-type expressions anyway.
    2237                 :             :  *
    2238                 :             :  * Note: in some code paths root can be passed as NULL, resulting in
    2239                 :             :  * slightly worse estimates.
    2240                 :             :  */
    2241                 :             : double
    2242                 :       84828 : estimate_array_length(PlannerInfo *root, Node *arrayexpr)
    2243                 :             : {
    2244                 :             :     /* look through any binary-compatible relabeling of arrayexpr */
    2245                 :       84828 :     arrayexpr = strip_array_coercion(arrayexpr);
    2246                 :             : 
    2247   [ +  -  +  + ]:       84828 :     if (arrayexpr && IsA(arrayexpr, Const))
    2248                 :             :     {
    2249                 :       37013 :         Datum       arraydatum = ((Const *) arrayexpr)->constvalue;
    2250                 :       37013 :         bool        arrayisnull = ((Const *) arrayexpr)->constisnull;
    2251                 :             :         ArrayType  *arrayval;
    2252                 :             : 
    2253         [ +  + ]:       37013 :         if (arrayisnull)
    2254                 :          75 :             return 0;
    2255                 :       36938 :         arrayval = DatumGetArrayTypeP(arraydatum);
    2256                 :       36938 :         return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
    2257                 :             :     }
    2258   [ +  -  +  + ]:       47815 :     else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
    2259         [ +  - ]:         503 :              !((ArrayExpr *) arrayexpr)->multidims)
    2260                 :             :     {
    2261                 :         503 :         return list_length(((ArrayExpr *) arrayexpr)->elements);
    2262                 :             :     }
    2263   [ +  -  +  + ]:       47312 :     else if (arrayexpr && root)
    2264                 :             :     {
    2265                 :             :         /* See if we can find any statistics about it */
    2266                 :             :         VariableStatData vardata;
    2267                 :             :         AttStatsSlot sslot;
    2268                 :       47292 :         double      nelem = 0;
    2269                 :             : 
    2270                 :             :         /*
    2271                 :             :          * Skip calling examine_variable for Var with varno 0, which has no
    2272                 :             :          * valid relation entry and would error in find_base_rel.  Such a Var
    2273                 :             :          * can appear when a nested set operation's output type doesn't match
    2274                 :             :          * the parent's expected type, because recurse_set_operations builds a
    2275                 :             :          * projection target list using generate_setop_tlist with varno 0, and
    2276                 :             :          * if the required type coercion involves an ArrayCoerceExpr, we can
    2277                 :             :          * be called on that Var.
    2278                 :             :          */
    2279   [ +  +  +  + ]:       47292 :         if (IsA(arrayexpr, Var) && ((Var *) arrayexpr)->varno == 0)
    2280                 :        4485 :             return 10;          /* default guess, should match scalararraysel */
    2281                 :             : 
    2282                 :       47287 :         examine_variable(root, arrayexpr, 0, &vardata);
    2283         [ +  + ]:       47287 :         if (HeapTupleIsValid(vardata.statsTuple))
    2284                 :             :         {
    2285                 :             :             /*
    2286                 :             :              * Found stats, so use the average element count, which is stored
    2287                 :             :              * in the last stanumbers element of the DECHIST statistics.
    2288                 :             :              * Actually that is the average count of *distinct* elements;
    2289                 :             :              * perhaps we should scale it up somewhat?
    2290                 :             :              */
    2291         [ +  + ]:        4575 :             if (get_attstatsslot(&sslot, vardata.statsTuple,
    2292                 :             :                                  STATISTIC_KIND_DECHIST, InvalidOid,
    2293                 :             :                                  ATTSTATSSLOT_NUMBERS))
    2294                 :             :             {
    2295         [ +  - ]:        4480 :                 if (sslot.nnumbers > 0)
    2296                 :        4480 :                     nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
    2297                 :        4480 :                 free_attstatsslot(&sslot);
    2298                 :             :             }
    2299                 :             :         }
    2300         [ +  + ]:       47287 :         ReleaseVariableStats(vardata);
    2301                 :             : 
    2302         [ +  + ]:       47287 :         if (nelem > 0)
    2303                 :        4480 :             return nelem;
    2304                 :             :     }
    2305                 :             : 
    2306                 :             :     /* Else use a default guess --- this should match scalararraysel */
    2307                 :       42827 :     return 10;
    2308                 :             : }
    2309                 :             : 
    2310                 :             : /*
    2311                 :             :  *      rowcomparesel       - Selectivity of RowCompareExpr Node.
    2312                 :             :  *
    2313                 :             :  * We estimate RowCompare selectivity by considering just the first (high
    2314                 :             :  * order) columns, which makes it equivalent to an ordinary OpExpr.  While
    2315                 :             :  * this estimate could be refined by considering additional columns, it
    2316                 :             :  * seems unlikely that we could do a lot better without multi-column
    2317                 :             :  * statistics.
    2318                 :             :  */
    2319                 :             : Selectivity
    2320                 :         240 : rowcomparesel(PlannerInfo *root,
    2321                 :             :               RowCompareExpr *clause,
    2322                 :             :               int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
    2323                 :             : {
    2324                 :             :     Selectivity s1;
    2325                 :         240 :     Oid         opno = linitial_oid(clause->opnos);
    2326                 :         240 :     Oid         inputcollid = linitial_oid(clause->inputcollids);
    2327                 :             :     List       *opargs;
    2328                 :             :     bool        is_join_clause;
    2329                 :             : 
    2330                 :             :     /* Build equivalent arg list for single operator */
    2331                 :         240 :     opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
    2332                 :             : 
    2333                 :             :     /*
    2334                 :             :      * Decide if it's a join clause.  This should match clausesel.c's
    2335                 :             :      * treat_as_join_clause(), except that we intentionally consider only the
    2336                 :             :      * leading columns and not the rest of the clause.
    2337                 :             :      */
    2338         [ +  + ]:         240 :     if (varRelid != 0)
    2339                 :             :     {
    2340                 :             :         /*
    2341                 :             :          * Caller is forcing restriction mode (eg, because we are examining an
    2342                 :             :          * inner indexscan qual).
    2343                 :             :          */
    2344                 :          45 :         is_join_clause = false;
    2345                 :             :     }
    2346         [ +  + ]:         195 :     else if (sjinfo == NULL)
    2347                 :             :     {
    2348                 :             :         /*
    2349                 :             :          * It must be a restriction clause, since it's being evaluated at a
    2350                 :             :          * scan node.
    2351                 :             :          */
    2352                 :         175 :         is_join_clause = false;
    2353                 :             :     }
    2354                 :             :     else
    2355                 :             :     {
    2356                 :             :         /*
    2357                 :             :          * Otherwise, it's a join if there's more than one base relation used.
    2358                 :             :          */
    2359                 :          20 :         is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
    2360                 :             :     }
    2361                 :             : 
    2362         [ +  + ]:         240 :     if (is_join_clause)
    2363                 :             :     {
    2364                 :             :         /* Estimate selectivity for a join clause. */
    2365                 :          20 :         s1 = join_selectivity(root, opno,
    2366                 :             :                               opargs,
    2367                 :             :                               inputcollid,
    2368                 :             :                               jointype,
    2369                 :             :                               sjinfo);
    2370                 :             :     }
    2371                 :             :     else
    2372                 :             :     {
    2373                 :             :         /* Estimate selectivity for a restriction clause. */
    2374                 :         220 :         s1 = restriction_selectivity(root, opno,
    2375                 :             :                                      opargs,
    2376                 :             :                                      inputcollid,
    2377                 :             :                                      varRelid);
    2378                 :             :     }
    2379                 :             : 
    2380                 :         240 :     return s1;
    2381                 :             : }
    2382                 :             : 
    2383                 :             : /*
    2384                 :             :  *      eqjoinsel       - Join selectivity of "="
    2385                 :             :  */
    2386                 :             : Datum
    2387                 :      208629 : eqjoinsel(PG_FUNCTION_ARGS)
    2388                 :             : {
    2389                 :      208629 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    2390                 :      208629 :     Oid         operator = PG_GETARG_OID(1);
    2391                 :      208629 :     List       *args = (List *) PG_GETARG_POINTER(2);
    2392                 :             : 
    2393                 :             : #ifdef NOT_USED
    2394                 :             :     JoinType    jointype = (JoinType) PG_GETARG_INT16(3);
    2395                 :             : #endif
    2396                 :      208629 :     SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
    2397                 :      208629 :     Oid         collation = PG_GET_COLLATION();
    2398                 :             :     double      selec;
    2399                 :             :     double      selec_inner;
    2400                 :             :     VariableStatData vardata1;
    2401                 :             :     VariableStatData vardata2;
    2402                 :             :     double      nd1;
    2403                 :             :     double      nd2;
    2404                 :             :     bool        isdefault1;
    2405                 :             :     bool        isdefault2;
    2406                 :             :     Oid         opfuncoid;
    2407                 :             :     FmgrInfo    eqproc;
    2408                 :      208629 :     Oid         hashLeft = InvalidOid;
    2409                 :      208629 :     Oid         hashRight = InvalidOid;
    2410                 :             :     AttStatsSlot sslot1;
    2411                 :             :     AttStatsSlot sslot2;
    2412                 :      208629 :     Form_pg_statistic stats1 = NULL;
    2413                 :      208629 :     Form_pg_statistic stats2 = NULL;
    2414                 :      208629 :     bool        have_mcvs1 = false;
    2415                 :      208629 :     bool        have_mcvs2 = false;
    2416                 :      208629 :     bool       *hasmatch1 = NULL;
    2417                 :      208629 :     bool       *hasmatch2 = NULL;
    2418                 :      208629 :     int         nmatches = 0;
    2419                 :             :     bool        get_mcv_stats;
    2420                 :             :     bool        join_is_reversed;
    2421                 :             :     RelOptInfo *inner_rel;
    2422                 :             : 
    2423                 :      208629 :     get_join_variables(root, args, sjinfo,
    2424                 :             :                        &vardata1, &vardata2, &join_is_reversed);
    2425                 :             : 
    2426                 :      208629 :     nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
    2427                 :      208629 :     nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
    2428                 :             : 
    2429                 :      208629 :     opfuncoid = get_opcode(operator);
    2430                 :             : 
    2431                 :      208629 :     memset(&sslot1, 0, sizeof(sslot1));
    2432                 :      208629 :     memset(&sslot2, 0, sizeof(sslot2));
    2433                 :             : 
    2434                 :             :     /*
    2435                 :             :      * There is no use in fetching one side's MCVs if we lack MCVs for the
    2436                 :             :      * other side, so do a quick check to verify that both stats exist.
    2437                 :             :      */
    2438                 :      561559 :     get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
    2439   [ +  +  +  + ]:      249718 :                      HeapTupleIsValid(vardata2.statsTuple) &&
    2440                 :      105417 :                      get_attstatsslot(&sslot1, vardata1.statsTuple,
    2441                 :             :                                       STATISTIC_KIND_MCV, InvalidOid,
    2442   [ +  +  +  + ]:      352930 :                                       0) &&
    2443                 :       52526 :                      get_attstatsslot(&sslot2, vardata2.statsTuple,
    2444                 :             :                                       STATISTIC_KIND_MCV, InvalidOid,
    2445                 :             :                                       0));
    2446                 :             : 
    2447         [ +  + ]:      208629 :     if (HeapTupleIsValid(vardata1.statsTuple))
    2448                 :             :     {
    2449                 :             :         /* note we allow use of nullfrac regardless of security check */
    2450                 :      144301 :         stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
    2451   [ +  +  +  - ]:      165684 :         if (get_mcv_stats &&
    2452                 :       21383 :             statistic_proc_security_check(&vardata1, opfuncoid))
    2453                 :       21383 :             have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
    2454                 :             :                                           STATISTIC_KIND_MCV, InvalidOid,
    2455                 :             :                                           ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
    2456                 :             :     }
    2457                 :             : 
    2458         [ +  + ]:      208629 :     if (HeapTupleIsValid(vardata2.statsTuple))
    2459                 :             :     {
    2460                 :             :         /* note we allow use of nullfrac regardless of security check */
    2461                 :      121765 :         stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
    2462   [ +  +  +  - ]:      143148 :         if (get_mcv_stats &&
    2463                 :       21383 :             statistic_proc_security_check(&vardata2, opfuncoid))
    2464                 :       21383 :             have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
    2465                 :             :                                           STATISTIC_KIND_MCV, InvalidOid,
    2466                 :             :                                           ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
    2467                 :             :     }
    2468                 :             : 
    2469                 :             :     /* Prepare info usable by both eqjoinsel_inner and eqjoinsel_semi */
    2470   [ +  +  +  - ]:      208629 :     if (have_mcvs1 && have_mcvs2)
    2471                 :             :     {
    2472                 :       21383 :         fmgr_info(opfuncoid, &eqproc);
    2473                 :       21383 :         hasmatch1 = (bool *) palloc0(sslot1.nvalues * sizeof(bool));
    2474                 :       21383 :         hasmatch2 = (bool *) palloc0(sslot2.nvalues * sizeof(bool));
    2475                 :             : 
    2476                 :             :         /*
    2477                 :             :          * If the MCV lists are long enough to justify hashing, try to look up
    2478                 :             :          * hash functions for the join operator.
    2479                 :             :          */
    2480         [ +  + ]:       21383 :         if ((sslot1.nvalues + sslot2.nvalues) >= EQJOINSEL_MCV_HASH_THRESHOLD)
    2481                 :        1143 :             (void) get_op_hash_functions_ext(operator,
    2482                 :        1143 :                                              exprType((Node *) linitial(args)),
    2483                 :             :                                              &hashLeft, &hashRight);
    2484                 :             :     }
    2485                 :             :     else
    2486                 :      187246 :         memset(&eqproc, 0, sizeof(eqproc)); /* silence uninit-var warnings */
    2487                 :             : 
    2488                 :             :     /* We need to compute the inner-join selectivity in all cases */
    2489                 :      208629 :     selec_inner = eqjoinsel_inner(&eqproc, collation,
    2490                 :             :                                   hashLeft, hashRight,
    2491                 :             :                                   &vardata1, &vardata2,
    2492                 :             :                                   nd1, nd2,
    2493                 :             :                                   isdefault1, isdefault2,
    2494                 :             :                                   &sslot1, &sslot2,
    2495                 :             :                                   stats1, stats2,
    2496                 :             :                                   have_mcvs1, have_mcvs2,
    2497                 :             :                                   hasmatch1, hasmatch2,
    2498                 :             :                                   &nmatches);
    2499                 :             : 
    2500      [ +  +  - ]:      208629 :     switch (sjinfo->jointype)
    2501                 :             :     {
    2502                 :      197420 :         case JOIN_INNER:
    2503                 :             :         case JOIN_LEFT:
    2504                 :             :         case JOIN_FULL:
    2505                 :      197420 :             selec = selec_inner;
    2506                 :      197420 :             break;
    2507                 :       11209 :         case JOIN_SEMI:
    2508                 :             :         case JOIN_ANTI:
    2509                 :             : 
    2510                 :             :             /*
    2511                 :             :              * Look up the join's inner relation.  min_righthand is sufficient
    2512                 :             :              * information because neither SEMI nor ANTI joins permit any
    2513                 :             :              * reassociation into or out of their RHS, so the righthand will
    2514                 :             :              * always be exactly that set of rels.
    2515                 :             :              */
    2516                 :       11209 :             inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
    2517                 :             : 
    2518         [ +  + ]:       11209 :             if (!join_is_reversed)
    2519                 :        5283 :                 selec = eqjoinsel_semi(&eqproc, collation,
    2520                 :             :                                        hashLeft, hashRight,
    2521                 :             :                                        false,
    2522                 :             :                                        &vardata1, &vardata2,
    2523                 :             :                                        nd1, nd2,
    2524                 :             :                                        isdefault1, isdefault2,
    2525                 :             :                                        &sslot1, &sslot2,
    2526                 :             :                                        stats1, stats2,
    2527                 :             :                                        have_mcvs1, have_mcvs2,
    2528                 :             :                                        hasmatch1, hasmatch2,
    2529                 :             :                                        &nmatches,
    2530                 :             :                                        inner_rel);
    2531                 :             :             else
    2532                 :        5926 :                 selec = eqjoinsel_semi(&eqproc, collation,
    2533                 :             :                                        hashLeft, hashRight,
    2534                 :             :                                        true,
    2535                 :             :                                        &vardata2, &vardata1,
    2536                 :             :                                        nd2, nd1,
    2537                 :             :                                        isdefault2, isdefault1,
    2538                 :             :                                        &sslot2, &sslot1,
    2539                 :             :                                        stats2, stats1,
    2540                 :             :                                        have_mcvs2, have_mcvs1,
    2541                 :             :                                        hasmatch2, hasmatch1,
    2542                 :             :                                        &nmatches,
    2543                 :             :                                        inner_rel);
    2544                 :             : 
    2545                 :             :             /*
    2546                 :             :              * We should never estimate the output of a semijoin to be more
    2547                 :             :              * rows than we estimate for an inner join with the same input
    2548                 :             :              * rels and join condition; it's obviously impossible for that to
    2549                 :             :              * happen.  The former estimate is N1 * Ssemi while the latter is
    2550                 :             :              * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner.  Doing
    2551                 :             :              * this is worthwhile because of the shakier estimation rules we
    2552                 :             :              * use in eqjoinsel_semi, particularly in cases where it has to
    2553                 :             :              * punt entirely.
    2554                 :             :              */
    2555         [ +  + ]:       11209 :             selec = Min(selec, inner_rel->rows * selec_inner);
    2556                 :       11209 :             break;
    2557                 :           0 :         default:
    2558                 :             :             /* other values not expected here */
    2559         [ #  # ]:           0 :             elog(ERROR, "unrecognized join type: %d",
    2560                 :             :                  (int) sjinfo->jointype);
    2561                 :             :             selec = 0;          /* keep compiler quiet */
    2562                 :             :             break;
    2563                 :             :     }
    2564                 :             : 
    2565                 :      208629 :     free_attstatsslot(&sslot1);
    2566                 :      208629 :     free_attstatsslot(&sslot2);
    2567                 :             : 
    2568         [ +  + ]:      208629 :     ReleaseVariableStats(vardata1);
    2569         [ +  + ]:      208629 :     ReleaseVariableStats(vardata2);
    2570                 :             : 
    2571         [ +  + ]:      208629 :     if (hasmatch1)
    2572                 :       21383 :         pfree(hasmatch1);
    2573         [ +  + ]:      208629 :     if (hasmatch2)
    2574                 :       21383 :         pfree(hasmatch2);
    2575                 :             : 
    2576   [ -  +  -  + ]:      208629 :     CLAMP_PROBABILITY(selec);
    2577                 :             : 
    2578                 :      208629 :     PG_RETURN_FLOAT8((float8) selec);
    2579                 :             : }
    2580                 :             : 
    2581                 :             : /*
    2582                 :             :  * eqjoinsel_inner --- eqjoinsel for normal inner join
    2583                 :             :  *
    2584                 :             :  * In addition to computing the selectivity estimate, this will fill
    2585                 :             :  * hasmatch1[], hasmatch2[], and *p_nmatches (if have_mcvs1 && have_mcvs2).
    2586                 :             :  * We may be able to re-use that data in eqjoinsel_semi.
    2587                 :             :  *
    2588                 :             :  * We also use this for LEFT/FULL outer joins; it's not presently clear
    2589                 :             :  * that it's worth trying to distinguish them here.
    2590                 :             :  */
    2591                 :             : static double
    2592                 :      208629 : eqjoinsel_inner(FmgrInfo *eqproc, Oid collation,
    2593                 :             :                 Oid hashLeft, Oid hashRight,
    2594                 :             :                 VariableStatData *vardata1, VariableStatData *vardata2,
    2595                 :             :                 double nd1, double nd2,
    2596                 :             :                 bool isdefault1, bool isdefault2,
    2597                 :             :                 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
    2598                 :             :                 Form_pg_statistic stats1, Form_pg_statistic stats2,
    2599                 :             :                 bool have_mcvs1, bool have_mcvs2,
    2600                 :             :                 bool *hasmatch1, bool *hasmatch2,
    2601                 :             :                 int *p_nmatches)
    2602                 :             : {
    2603                 :             :     double      selec;
    2604                 :             : 
    2605   [ +  +  +  - ]:      208629 :     if (have_mcvs1 && have_mcvs2)
    2606                 :       21383 :     {
    2607                 :             :         /*
    2608                 :             :          * We have most-common-value lists for both relations.  Run through
    2609                 :             :          * the lists to see which MCVs actually join to each other with the
    2610                 :             :          * given operator.  This allows us to determine the exact join
    2611                 :             :          * selectivity for the portion of the relations represented by the MCV
    2612                 :             :          * lists.  We still have to estimate for the remaining population, but
    2613                 :             :          * in a skewed distribution this gives us a big leg up in accuracy.
    2614                 :             :          * For motivation see the analysis in Y. Ioannidis and S.
    2615                 :             :          * Christodoulakis, "On the propagation of errors in the size of join
    2616                 :             :          * results", Technical Report 1018, Computer Science Dept., University
    2617                 :             :          * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
    2618                 :             :          */
    2619                 :       21383 :         double      nullfrac1 = stats1->stanullfrac;
    2620                 :       21383 :         double      nullfrac2 = stats2->stanullfrac;
    2621                 :             :         double      matchprodfreq,
    2622                 :             :                     matchfreq1,
    2623                 :             :                     matchfreq2,
    2624                 :             :                     unmatchfreq1,
    2625                 :             :                     unmatchfreq2,
    2626                 :             :                     otherfreq1,
    2627                 :             :                     otherfreq2,
    2628                 :             :                     totalsel1,
    2629                 :             :                     totalsel2;
    2630                 :             :         int         i,
    2631                 :             :                     nmatches;
    2632                 :             : 
    2633                 :             :         /* Fill the match arrays */
    2634                 :       21383 :         eqjoinsel_find_matches(eqproc, collation,
    2635                 :             :                                hashLeft, hashRight,
    2636                 :             :                                false,
    2637                 :             :                                sslot1, sslot2,
    2638                 :             :                                sslot1->nvalues, sslot2->nvalues,
    2639                 :             :                                hasmatch1, hasmatch2,
    2640                 :             :                                p_nmatches, &matchprodfreq);
    2641                 :       21383 :         nmatches = *p_nmatches;
    2642   [ -  +  -  + ]:       21383 :         CLAMP_PROBABILITY(matchprodfreq);
    2643                 :             : 
    2644                 :             :         /* Sum up frequencies of matched and unmatched MCVs */
    2645                 :       21383 :         matchfreq1 = unmatchfreq1 = 0.0;
    2646         [ +  + ]:      455004 :         for (i = 0; i < sslot1->nvalues; i++)
    2647                 :             :         {
    2648         [ +  + ]:      433621 :             if (hasmatch1[i])
    2649                 :      220107 :                 matchfreq1 += sslot1->numbers[i];
    2650                 :             :             else
    2651                 :      213514 :                 unmatchfreq1 += sslot1->numbers[i];
    2652                 :             :         }
    2653   [ -  +  +  + ]:       21383 :         CLAMP_PROBABILITY(matchfreq1);
    2654   [ -  +  -  + ]:       21383 :         CLAMP_PROBABILITY(unmatchfreq1);
    2655                 :       21383 :         matchfreq2 = unmatchfreq2 = 0.0;
    2656         [ +  + ]:      364586 :         for (i = 0; i < sslot2->nvalues; i++)
    2657                 :             :         {
    2658         [ +  + ]:      343203 :             if (hasmatch2[i])
    2659                 :      220107 :                 matchfreq2 += sslot2->numbers[i];
    2660                 :             :             else
    2661                 :      123096 :                 unmatchfreq2 += sslot2->numbers[i];
    2662                 :             :         }
    2663   [ -  +  +  + ]:       21383 :         CLAMP_PROBABILITY(matchfreq2);
    2664   [ -  +  -  + ]:       21383 :         CLAMP_PROBABILITY(unmatchfreq2);
    2665                 :             : 
    2666                 :             :         /*
    2667                 :             :          * Compute total frequency of non-null values that are not in the MCV
    2668                 :             :          * lists.
    2669                 :             :          */
    2670                 :       21383 :         otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
    2671                 :       21383 :         otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
    2672   [ +  +  -  + ]:       21383 :         CLAMP_PROBABILITY(otherfreq1);
    2673   [ +  +  -  + ]:       21383 :         CLAMP_PROBABILITY(otherfreq2);
    2674                 :             : 
    2675                 :             :         /*
    2676                 :             :          * We can estimate the total selectivity from the point of view of
    2677                 :             :          * relation 1 as: the known selectivity for matched MCVs, plus
    2678                 :             :          * unmatched MCVs that are assumed to match against random members of
    2679                 :             :          * relation 2's non-MCV population, plus non-MCV values that are
    2680                 :             :          * assumed to match against random members of relation 2's unmatched
    2681                 :             :          * MCVs plus non-MCV values.
    2682                 :             :          */
    2683                 :       21383 :         totalsel1 = matchprodfreq;
    2684         [ +  + ]:       21383 :         if (nd2 > sslot2->nvalues)
    2685                 :        3625 :             totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
    2686         [ +  + ]:       21383 :         if (nd2 > nmatches)
    2687                 :        7068 :             totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
    2688                 :        7068 :                 (nd2 - nmatches);
    2689                 :             :         /* Same estimate from the point of view of relation 2. */
    2690                 :       21383 :         totalsel2 = matchprodfreq;
    2691         [ +  + ]:       21383 :         if (nd1 > sslot1->nvalues)
    2692                 :        4199 :             totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
    2693         [ +  + ]:       21383 :         if (nd1 > nmatches)
    2694                 :        6184 :             totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
    2695                 :        6184 :                 (nd1 - nmatches);
    2696                 :             : 
    2697                 :             :         /*
    2698                 :             :          * Use the smaller of the two estimates.  This can be justified in
    2699                 :             :          * essentially the same terms as given below for the no-stats case: to
    2700                 :             :          * a first approximation, we are estimating from the point of view of
    2701                 :             :          * the relation with smaller nd.
    2702                 :             :          */
    2703         [ +  + ]:       21383 :         selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
    2704                 :             :     }
    2705                 :             :     else
    2706                 :             :     {
    2707                 :             :         /*
    2708                 :             :          * We do not have MCV lists for both sides.  Estimate the join
    2709                 :             :          * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
    2710                 :             :          * is plausible if we assume that the join operator is strict and the
    2711                 :             :          * non-null values are about equally distributed: a given non-null
    2712                 :             :          * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
    2713                 :             :          * of rel2, so total join rows are at most
    2714                 :             :          * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
    2715                 :             :          * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
    2716                 :             :          * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
    2717                 :             :          * with MIN() is an upper bound.  Using the MIN() means we estimate
    2718                 :             :          * from the point of view of the relation with smaller nd (since the
    2719                 :             :          * larger nd is determining the MIN).  It is reasonable to assume that
    2720                 :             :          * most tuples in this rel will have join partners, so the bound is
    2721                 :             :          * probably reasonably tight and should be taken as-is.
    2722                 :             :          *
    2723                 :             :          * XXX Can we be smarter if we have an MCV list for just one side? It
    2724                 :             :          * seems that if we assume equal distribution for the other side, we
    2725                 :             :          * end up with the same answer anyway.
    2726                 :             :          */
    2727         [ +  + ]:      187246 :         double      nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
    2728         [ +  + ]:      187246 :         double      nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
    2729                 :             : 
    2730                 :      187246 :         selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
    2731         [ +  + ]:      187246 :         if (nd1 > nd2)
    2732                 :       89896 :             selec /= nd1;
    2733                 :             :         else
    2734                 :       97350 :             selec /= nd2;
    2735                 :             :     }
    2736                 :             : 
    2737                 :      208629 :     return selec;
    2738                 :             : }
    2739                 :             : 
    2740                 :             : /*
    2741                 :             :  * eqjoinsel_semi --- eqjoinsel for semi join
    2742                 :             :  *
    2743                 :             :  * (Also used for anti join, which we are supposed to estimate the same way.)
    2744                 :             :  * Caller has ensured that vardata1 is the LHS variable; however, eqproc
    2745                 :             :  * is for the original join operator, which might now need to have the inputs
    2746                 :             :  * swapped in order to apply correctly.  Also, if have_mcvs1 && have_mcvs2
    2747                 :             :  * then hasmatch1[], hasmatch2[], and *p_nmatches were filled by
    2748                 :             :  * eqjoinsel_inner.
    2749                 :             :  */
    2750                 :             : static double
    2751                 :       11209 : eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
    2752                 :             :                Oid hashLeft, Oid hashRight,
    2753                 :             :                bool op_is_reversed,
    2754                 :             :                VariableStatData *vardata1, VariableStatData *vardata2,
    2755                 :             :                double nd1, double nd2,
    2756                 :             :                bool isdefault1, bool isdefault2,
    2757                 :             :                AttStatsSlot *sslot1, AttStatsSlot *sslot2,
    2758                 :             :                Form_pg_statistic stats1, Form_pg_statistic stats2,
    2759                 :             :                bool have_mcvs1, bool have_mcvs2,
    2760                 :             :                bool *hasmatch1, bool *hasmatch2,
    2761                 :             :                int *p_nmatches,
    2762                 :             :                RelOptInfo *inner_rel)
    2763                 :             : {
    2764                 :             :     double      selec;
    2765                 :             : 
    2766                 :             :     /*
    2767                 :             :      * We clamp nd2 to be not more than what we estimate the inner relation's
    2768                 :             :      * size to be.  This is intuitively somewhat reasonable since obviously
    2769                 :             :      * there can't be more than that many distinct values coming from the
    2770                 :             :      * inner rel.  The reason for the asymmetry (ie, that we don't clamp nd1
    2771                 :             :      * likewise) is that this is the only pathway by which restriction clauses
    2772                 :             :      * applied to the inner rel will affect the join result size estimate,
    2773                 :             :      * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
    2774                 :             :      * only the outer rel's size.  If we clamped nd1 we'd be double-counting
    2775                 :             :      * the selectivity of outer-rel restrictions.
    2776                 :             :      *
    2777                 :             :      * We can apply this clamping both with respect to the base relation from
    2778                 :             :      * which the join variable comes (if there is just one), and to the
    2779                 :             :      * immediate inner input relation of the current join.
    2780                 :             :      *
    2781                 :             :      * If we clamp, we can treat nd2 as being a non-default estimate; it's not
    2782                 :             :      * great, maybe, but it didn't come out of nowhere either.  This is most
    2783                 :             :      * helpful when the inner relation is empty and consequently has no stats.
    2784                 :             :      */
    2785         [ +  + ]:       11209 :     if (vardata2->rel)
    2786                 :             :     {
    2787         [ +  + ]:       11204 :         if (nd2 >= vardata2->rel->rows)
    2788                 :             :         {
    2789                 :        9444 :             nd2 = vardata2->rel->rows;
    2790                 :        9444 :             isdefault2 = false;
    2791                 :             :         }
    2792                 :             :     }
    2793         [ +  + ]:       11209 :     if (nd2 >= inner_rel->rows)
    2794                 :             :     {
    2795                 :        9394 :         nd2 = inner_rel->rows;
    2796                 :        9394 :         isdefault2 = false;
    2797                 :             :     }
    2798                 :             : 
    2799   [ +  +  +  - ]:       11209 :     if (have_mcvs1 && have_mcvs2)
    2800                 :         513 :     {
    2801                 :             :         /*
    2802                 :             :          * We have most-common-value lists for both relations.  Run through
    2803                 :             :          * the lists to see which MCVs actually join to each other with the
    2804                 :             :          * given operator.  This allows us to determine the exact join
    2805                 :             :          * selectivity for the portion of the relations represented by the MCV
    2806                 :             :          * lists.  We still have to estimate for the remaining population, but
    2807                 :             :          * in a skewed distribution this gives us a big leg up in accuracy.
    2808                 :             :          */
    2809                 :         513 :         double      nullfrac1 = stats1->stanullfrac;
    2810                 :             :         double      matchprodfreq,
    2811                 :             :                     matchfreq1,
    2812                 :             :                     uncertainfrac,
    2813                 :             :                     uncertain;
    2814                 :             :         int         i,
    2815                 :             :                     nmatches,
    2816                 :             :                     clamped_nvalues2;
    2817                 :             : 
    2818                 :             :         /*
    2819                 :             :          * The clamping above could have resulted in nd2 being less than
    2820                 :             :          * sslot2->nvalues; in which case, we assume that precisely the nd2
    2821                 :             :          * most common values in the relation will appear in the join input,
    2822                 :             :          * and so compare to only the first nd2 members of the MCV list.  Of
    2823                 :             :          * course this is frequently wrong, but it's the best bet we can make.
    2824                 :             :          */
    2825         [ +  + ]:         513 :         clamped_nvalues2 = Min(sslot2->nvalues, nd2);
    2826                 :             : 
    2827                 :             :         /*
    2828                 :             :          * If we did not set clamped_nvalues2 to less than sslot2->nvalues,
    2829                 :             :          * then the hasmatch1[] and hasmatch2[] match flags computed by
    2830                 :             :          * eqjoinsel_inner are still perfectly applicable, so we need not
    2831                 :             :          * re-do the matching work.  Note that it does not matter if
    2832                 :             :          * op_is_reversed: we'd get the same answers.
    2833                 :             :          *
    2834                 :             :          * If we did clamp, then a different set of sslot2 values is to be
    2835                 :             :          * compared, so we have to re-do the matching.
    2836                 :             :          */
    2837         [ -  + ]:         513 :         if (clamped_nvalues2 != sslot2->nvalues)
    2838                 :             :         {
    2839                 :             :             /* Must re-zero the arrays */
    2840                 :           0 :             memset(hasmatch1, 0, sslot1->nvalues * sizeof(bool));
    2841                 :           0 :             memset(hasmatch2, 0, clamped_nvalues2 * sizeof(bool));
    2842                 :             :             /* Re-fill the match arrays */
    2843                 :           0 :             eqjoinsel_find_matches(eqproc, collation,
    2844                 :             :                                    hashLeft, hashRight,
    2845                 :             :                                    op_is_reversed,
    2846                 :             :                                    sslot1, sslot2,
    2847                 :             :                                    sslot1->nvalues, clamped_nvalues2,
    2848                 :             :                                    hasmatch1, hasmatch2,
    2849                 :             :                                    p_nmatches, &matchprodfreq);
    2850                 :             :         }
    2851                 :         513 :         nmatches = *p_nmatches;
    2852                 :             : 
    2853                 :             :         /* Sum up frequencies of matched MCVs */
    2854                 :         513 :         matchfreq1 = 0.0;
    2855         [ +  + ]:       11143 :         for (i = 0; i < sslot1->nvalues; i++)
    2856                 :             :         {
    2857         [ +  + ]:       10630 :             if (hasmatch1[i])
    2858                 :        9563 :                 matchfreq1 += sslot1->numbers[i];
    2859                 :             :         }
    2860   [ -  +  +  + ]:         513 :         CLAMP_PROBABILITY(matchfreq1);
    2861                 :             : 
    2862                 :             :         /*
    2863                 :             :          * Now we need to estimate the fraction of relation 1 that has at
    2864                 :             :          * least one join partner.  We know for certain that the matched MCVs
    2865                 :             :          * do, so that gives us a lower bound, but we're really in the dark
    2866                 :             :          * about everything else.  Our crude approach is: if nd1 <= nd2 then
    2867                 :             :          * assume all non-null rel1 rows have join partners, else assume for
    2868                 :             :          * the uncertain rows that a fraction nd2/nd1 have join partners. We
    2869                 :             :          * can discount the known-matched MCVs from the distinct-values counts
    2870                 :             :          * before doing the division.
    2871                 :             :          *
    2872                 :             :          * Crude as the above is, it's completely useless if we don't have
    2873                 :             :          * reliable ndistinct values for both sides.  Hence, if either nd1 or
    2874                 :             :          * nd2 is default, punt and assume half of the uncertain rows have
    2875                 :             :          * join partners.
    2876                 :             :          */
    2877   [ +  -  +  - ]:         513 :         if (!isdefault1 && !isdefault2)
    2878                 :             :         {
    2879                 :         513 :             nd1 -= nmatches;
    2880                 :         513 :             nd2 -= nmatches;
    2881   [ +  +  -  + ]:         513 :             if (nd1 <= nd2 || nd2 < 0)
    2882                 :         483 :                 uncertainfrac = 1.0;
    2883                 :             :             else
    2884                 :          30 :                 uncertainfrac = nd2 / nd1;
    2885                 :             :         }
    2886                 :             :         else
    2887                 :           0 :             uncertainfrac = 0.5;
    2888                 :         513 :         uncertain = 1.0 - matchfreq1 - nullfrac1;
    2889   [ -  +  -  + ]:         513 :         CLAMP_PROBABILITY(uncertain);
    2890                 :         513 :         selec = matchfreq1 + uncertainfrac * uncertain;
    2891                 :             :     }
    2892                 :             :     else
    2893                 :             :     {
    2894                 :             :         /*
    2895                 :             :          * Without MCV lists for both sides, we can only use the heuristic
    2896                 :             :          * about nd1 vs nd2.
    2897                 :             :          */
    2898         [ +  + ]:       10696 :         double      nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
    2899                 :             : 
    2900   [ +  +  +  + ]:       10696 :         if (!isdefault1 && !isdefault2)
    2901                 :             :         {
    2902   [ +  +  -  + ]:        7880 :             if (nd1 <= nd2 || nd2 < 0)
    2903                 :        4335 :                 selec = 1.0 - nullfrac1;
    2904                 :             :             else
    2905                 :        3545 :                 selec = (nd2 / nd1) * (1.0 - nullfrac1);
    2906                 :             :         }
    2907                 :             :         else
    2908                 :        2816 :             selec = 0.5 * (1.0 - nullfrac1);
    2909                 :             :     }
    2910                 :             : 
    2911                 :       11209 :     return selec;
    2912                 :             : }
    2913                 :             : 
    2914                 :             : /*
    2915                 :             :  * Identify matching MCVs for eqjoinsel_inner or eqjoinsel_semi.
    2916                 :             :  *
    2917                 :             :  * Inputs:
    2918                 :             :  *  eqproc: FmgrInfo for equality function to use (might be reversed)
    2919                 :             :  *  collation: OID of collation to use
    2920                 :             :  *  hashLeft, hashRight: OIDs of hash functions associated with equality op,
    2921                 :             :  *      or InvalidOid if we're not to use hashing
    2922                 :             :  *  op_is_reversed: indicates that eqproc compares right type to left type
    2923                 :             :  *  sslot1, sslot2: MCV values for the lefthand and righthand inputs
    2924                 :             :  *  nvalues1, nvalues2: number of values to be considered (can be less than
    2925                 :             :  *      sslotN->nvalues, but not more)
    2926                 :             :  * Outputs:
    2927                 :             :  *  hasmatch1[], hasmatch2[]: pre-zeroed arrays of lengths nvalues1, nvalues2;
    2928                 :             :  *      entries are set to true if that MCV has a match on the other side
    2929                 :             :  *  *p_nmatches: receives number of MCV pairs that match
    2930                 :             :  *  *p_matchprodfreq: receives sum(sslot1->numbers[i] * sslot2->numbers[j])
    2931                 :             :  *      for matching MCVs
    2932                 :             :  *
    2933                 :             :  * Note that hashLeft is for the eqproc's left-hand input type, hashRight
    2934                 :             :  * for its right, regardless of op_is_reversed.
    2935                 :             :  *
    2936                 :             :  * Note we assume that each MCV will match at most one member of the other
    2937                 :             :  * MCV list.  If the operator isn't really equality, there could be multiple
    2938                 :             :  * matches --- but we don't look for them, both for speed and because the
    2939                 :             :  * math wouldn't add up...
    2940                 :             :  */
    2941                 :             : static void
    2942                 :       21383 : eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
    2943                 :             :                        Oid hashLeft, Oid hashRight,
    2944                 :             :                        bool op_is_reversed,
    2945                 :             :                        AttStatsSlot *sslot1, AttStatsSlot *sslot2,
    2946                 :             :                        int nvalues1, int nvalues2,
    2947                 :             :                        bool *hasmatch1, bool *hasmatch2,
    2948                 :             :                        int *p_nmatches, double *p_matchprodfreq)
    2949                 :             : {
    2950                 :       21383 :     LOCAL_FCINFO(fcinfo, 2);
    2951                 :       21383 :     double      matchprodfreq = 0.0;
    2952                 :       21383 :     int         nmatches = 0;
    2953                 :             : 
    2954                 :             :     /*
    2955                 :             :      * Save a few cycles by setting up the fcinfo struct just once.  Using
    2956                 :             :      * FunctionCallInvoke directly also avoids failure if the eqproc returns
    2957                 :             :      * NULL, though really equality functions should never do that.
    2958                 :             :      */
    2959                 :       21383 :     InitFunctionCallInfoData(*fcinfo, eqproc, 2, collation,
    2960                 :             :                              NULL, NULL);
    2961                 :       21383 :     fcinfo->args[0].isnull = false;
    2962                 :       21383 :     fcinfo->args[1].isnull = false;
    2963                 :             : 
    2964   [ +  +  +  - ]:       21383 :     if (OidIsValid(hashLeft) && OidIsValid(hashRight))
    2965                 :        1143 :     {
    2966                 :             :         /* Use a hash table to speed up the matching */
    2967                 :        1143 :         LOCAL_FCINFO(hash_fcinfo, 1);
    2968                 :             :         FmgrInfo    hash_proc;
    2969                 :             :         MCVHashContext hashContext;
    2970                 :             :         MCVHashTable_hash *hashTable;
    2971                 :             :         AttStatsSlot *statsProbe;
    2972                 :             :         AttStatsSlot *statsHash;
    2973                 :             :         bool       *hasMatchProbe;
    2974                 :             :         bool       *hasMatchHash;
    2975                 :             :         int         nvaluesProbe;
    2976                 :             :         int         nvaluesHash;
    2977                 :             : 
    2978                 :             :         /* Make sure we build the hash table on the smaller array. */
    2979         [ +  - ]:        1143 :         if (sslot1->nvalues >= sslot2->nvalues)
    2980                 :             :         {
    2981                 :        1143 :             statsProbe = sslot1;
    2982                 :        1143 :             statsHash = sslot2;
    2983                 :        1143 :             hasMatchProbe = hasmatch1;
    2984                 :        1143 :             hasMatchHash = hasmatch2;
    2985                 :        1143 :             nvaluesProbe = nvalues1;
    2986                 :        1143 :             nvaluesHash = nvalues2;
    2987                 :             :         }
    2988                 :             :         else
    2989                 :             :         {
    2990                 :             :             /* We'll have to reverse the direction of use of the operator. */
    2991                 :           0 :             op_is_reversed = !op_is_reversed;
    2992                 :           0 :             statsProbe = sslot2;
    2993                 :           0 :             statsHash = sslot1;
    2994                 :           0 :             hasMatchProbe = hasmatch2;
    2995                 :           0 :             hasMatchHash = hasmatch1;
    2996                 :           0 :             nvaluesProbe = nvalues2;
    2997                 :           0 :             nvaluesHash = nvalues1;
    2998                 :             :         }
    2999                 :             : 
    3000                 :             :         /*
    3001                 :             :          * Build the hash table on the smaller array, using the appropriate
    3002                 :             :          * hash function for its data type.
    3003                 :             :          */
    3004         [ -  + ]:        1143 :         fmgr_info(op_is_reversed ? hashLeft : hashRight, &hash_proc);
    3005                 :        1143 :         InitFunctionCallInfoData(*hash_fcinfo, &hash_proc, 1, collation,
    3006                 :             :                                  NULL, NULL);
    3007                 :        1143 :         hash_fcinfo->args[0].isnull = false;
    3008                 :             : 
    3009                 :        1143 :         hashContext.equal_fcinfo = fcinfo;
    3010                 :        1143 :         hashContext.hash_fcinfo = hash_fcinfo;
    3011                 :        1143 :         hashContext.op_is_reversed = op_is_reversed;
    3012                 :        1143 :         hashContext.insert_mode = true;
    3013                 :        1143 :         get_typlenbyval(statsHash->valuetype,
    3014                 :             :                         &hashContext.hash_typlen,
    3015                 :             :                         &hashContext.hash_typbyval);
    3016                 :             : 
    3017                 :        1143 :         hashTable = MCVHashTable_create(CurrentMemoryContext,
    3018                 :             :                                         nvaluesHash,
    3019                 :             :                                         &hashContext);
    3020                 :             : 
    3021         [ +  + ]:      115443 :         for (int i = 0; i < nvaluesHash; i++)
    3022                 :             :         {
    3023                 :      114300 :             bool        found = false;
    3024                 :      114300 :             MCVHashEntry *entry = MCVHashTable_insert(hashTable,
    3025                 :      114300 :                                                       statsHash->values[i],
    3026                 :             :                                                       &found);
    3027                 :             : 
    3028                 :             :             /*
    3029                 :             :              * MCVHashTable_insert will only report "found" if the new value
    3030                 :             :              * is equal to some previous one per datum_image_eq().  That
    3031                 :             :              * probably shouldn't happen, since we're not expecting duplicates
    3032                 :             :              * in the MCV list.  If we do find a dup, just ignore it, leaving
    3033                 :             :              * the hash entry's index pointing at the first occurrence.  That
    3034                 :             :              * matches the behavior that the non-hashed code path would have.
    3035                 :             :              */
    3036         [ +  - ]:      114300 :             if (likely(!found))
    3037                 :      114300 :                 entry->index = i;
    3038                 :             :         }
    3039                 :             : 
    3040                 :             :         /*
    3041                 :             :          * Prepare to probe the hash table.  If the probe values are of a
    3042                 :             :          * different data type, then we need to change hash functions.  (This
    3043                 :             :          * code relies on the assumption that since we defined SH_STORE_HASH,
    3044                 :             :          * simplehash.h will never need to compute hash values for existing
    3045                 :             :          * hash table entries.)
    3046                 :             :          */
    3047                 :        1143 :         hashContext.insert_mode = false;
    3048         [ -  + ]:        1143 :         if (hashLeft != hashRight)
    3049                 :             :         {
    3050         [ #  # ]:           0 :             fmgr_info(op_is_reversed ? hashRight : hashLeft, &hash_proc);
    3051                 :             :             /* Resetting hash_fcinfo is probably unnecessary, but be safe */
    3052                 :           0 :             InitFunctionCallInfoData(*hash_fcinfo, &hash_proc, 1, collation,
    3053                 :             :                                      NULL, NULL);
    3054                 :           0 :             hash_fcinfo->args[0].isnull = false;
    3055                 :             :         }
    3056                 :             : 
    3057                 :             :         /* Look up each probe value in turn. */
    3058         [ +  + ]:      115443 :         for (int i = 0; i < nvaluesProbe; i++)
    3059                 :             :         {
    3060                 :      114300 :             MCVHashEntry *entry = MCVHashTable_lookup(hashTable,
    3061                 :      114300 :                                                       statsProbe->values[i]);
    3062                 :             : 
    3063                 :             :             /* As in the other code path, skip already-matched hash entries */
    3064   [ +  +  +  - ]:      114300 :             if (entry != NULL && !hasMatchHash[entry->index])
    3065                 :             :             {
    3066                 :       53265 :                 hasMatchHash[entry->index] = hasMatchProbe[i] = true;
    3067                 :       53265 :                 nmatches++;
    3068                 :       53265 :                 matchprodfreq += statsHash->numbers[entry->index] * statsProbe->numbers[i];
    3069                 :             :             }
    3070                 :             :         }
    3071                 :             : 
    3072                 :        1143 :         MCVHashTable_destroy(hashTable);
    3073                 :             :     }
    3074                 :             :     else
    3075                 :             :     {
    3076                 :             :         /* We're not to use hashing, so do it the O(N^2) way */
    3077                 :             :         int         index1,
    3078                 :             :                     index2;
    3079                 :             : 
    3080                 :             :         /* Set up to supply the values in the order the operator expects */
    3081         [ -  + ]:       20240 :         if (op_is_reversed)
    3082                 :             :         {
    3083                 :           0 :             index1 = 1;
    3084                 :           0 :             index2 = 0;
    3085                 :             :         }
    3086                 :             :         else
    3087                 :             :         {
    3088                 :       20240 :             index1 = 0;
    3089                 :       20240 :             index2 = 1;
    3090                 :             :         }
    3091                 :             : 
    3092         [ +  + ]:      339561 :         for (int i = 0; i < nvalues1; i++)
    3093                 :             :         {
    3094                 :      319321 :             fcinfo->args[index1].value = sslot1->values[i];
    3095                 :             : 
    3096         [ +  + ]:     6257729 :             for (int j = 0; j < nvalues2; j++)
    3097                 :             :             {
    3098                 :             :                 Datum       fresult;
    3099                 :             : 
    3100         [ +  + ]:     6105250 :                 if (hasmatch2[j])
    3101                 :     2072731 :                     continue;
    3102                 :     4032519 :                 fcinfo->args[index2].value = sslot2->values[j];
    3103                 :     4032519 :                 fcinfo->isnull = false;
    3104                 :     4032519 :                 fresult = FunctionCallInvoke(fcinfo);
    3105   [ +  -  +  + ]:     4032519 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    3106                 :             :                 {
    3107                 :      166842 :                     hasmatch1[i] = hasmatch2[j] = true;
    3108                 :      166842 :                     matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
    3109                 :      166842 :                     nmatches++;
    3110                 :      166842 :                     break;
    3111                 :             :                 }
    3112                 :             :             }
    3113                 :             :         }
    3114                 :             :     }
    3115                 :             : 
    3116                 :       21383 :     *p_nmatches = nmatches;
    3117                 :       21383 :     *p_matchprodfreq = matchprodfreq;
    3118                 :       21383 : }
    3119                 :             : 
    3120                 :             : /*
    3121                 :             :  * Support functions for the hash tables used by eqjoinsel_find_matches
    3122                 :             :  */
    3123                 :             : static uint32
    3124                 :      228600 : hash_mcv(MCVHashTable_hash *tab, Datum key)
    3125                 :             : {
    3126                 :      228600 :     MCVHashContext *context = (MCVHashContext *) tab->private_data;
    3127                 :      228600 :     FunctionCallInfo fcinfo = context->hash_fcinfo;
    3128                 :             :     Datum       fresult;
    3129                 :             : 
    3130                 :      228600 :     fcinfo->args[0].value = key;
    3131                 :      228600 :     fcinfo->isnull = false;
    3132                 :      228600 :     fresult = FunctionCallInvoke(fcinfo);
    3133                 :             :     Assert(!fcinfo->isnull);
    3134                 :      228600 :     return DatumGetUInt32(fresult);
    3135                 :             : }
    3136                 :             : 
    3137                 :             : static bool
    3138                 :       53265 : mcvs_equal(MCVHashTable_hash *tab, Datum key0, Datum key1)
    3139                 :             : {
    3140                 :       53265 :     MCVHashContext *context = (MCVHashContext *) tab->private_data;
    3141                 :             : 
    3142         [ -  + ]:       53265 :     if (context->insert_mode)
    3143                 :             :     {
    3144                 :             :         /*
    3145                 :             :          * During the insertion step, any comparisons will be between two
    3146                 :             :          * Datums of the hash table's data type, so if the given operator is
    3147                 :             :          * cross-type it will be the wrong thing to use.  Fortunately, we can
    3148                 :             :          * use datum_image_eq instead.  The MCV values should all be distinct
    3149                 :             :          * anyway, so it's mostly pro-forma to compare them at all.
    3150                 :             :          */
    3151                 :           0 :         return datum_image_eq(key0, key1,
    3152                 :           0 :                               context->hash_typbyval, context->hash_typlen);
    3153                 :             :     }
    3154                 :             :     else
    3155                 :             :     {
    3156                 :       53265 :         FunctionCallInfo fcinfo = context->equal_fcinfo;
    3157                 :             :         Datum       fresult;
    3158                 :             : 
    3159                 :             :         /*
    3160                 :             :          * Apply the operator the correct way around.  Although simplehash.h
    3161                 :             :          * doesn't document this explicitly, during lookups key0 is from the
    3162                 :             :          * hash table while key1 is the probe value, so we should compare them
    3163                 :             :          * in that order only if op_is_reversed.
    3164                 :             :          */
    3165         [ -  + ]:       53265 :         if (context->op_is_reversed)
    3166                 :             :         {
    3167                 :           0 :             fcinfo->args[0].value = key0;
    3168                 :           0 :             fcinfo->args[1].value = key1;
    3169                 :             :         }
    3170                 :             :         else
    3171                 :             :         {
    3172                 :       53265 :             fcinfo->args[0].value = key1;
    3173                 :       53265 :             fcinfo->args[1].value = key0;
    3174                 :             :         }
    3175                 :       53265 :         fcinfo->isnull = false;
    3176                 :       53265 :         fresult = FunctionCallInvoke(fcinfo);
    3177   [ +  -  +  - ]:       53265 :         return (!fcinfo->isnull && DatumGetBool(fresult));
    3178                 :             :     }
    3179                 :             : }
    3180                 :             : 
    3181                 :             : /*
    3182                 :             :  *      neqjoinsel      - Join selectivity of "!="
    3183                 :             :  */
    3184                 :             : Datum
    3185                 :        2459 : neqjoinsel(PG_FUNCTION_ARGS)
    3186                 :             : {
    3187                 :        2459 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    3188                 :        2459 :     Oid         operator = PG_GETARG_OID(1);
    3189                 :        2459 :     List       *args = (List *) PG_GETARG_POINTER(2);
    3190                 :        2459 :     JoinType    jointype = (JoinType) PG_GETARG_INT16(3);
    3191                 :        2459 :     SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
    3192                 :        2459 :     Oid         collation = PG_GET_COLLATION();
    3193                 :             :     float8      result;
    3194                 :             : 
    3195   [ +  +  -  + ]:        2459 :     if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
    3196                 :         879 :     {
    3197                 :             :         /*
    3198                 :             :          * For semi-joins, if there is more than one distinct value in the RHS
    3199                 :             :          * relation then every non-null LHS row must find a row to join since
    3200                 :             :          * it can only be equal to one of them.  We'll assume that there is
    3201                 :             :          * always more than one distinct RHS value for the sake of stability,
    3202                 :             :          * though in theory we could have special cases for empty RHS
    3203                 :             :          * (selectivity = 0) and single-distinct-value RHS (selectivity =
    3204                 :             :          * fraction of LHS that has the same value as the single RHS value).
    3205                 :             :          *
    3206                 :             :          * For anti-joins, if we use the same assumption that there is more
    3207                 :             :          * than one distinct key in the RHS relation, then every non-null LHS
    3208                 :             :          * row must be suppressed by the anti-join.
    3209                 :             :          *
    3210                 :             :          * So either way, the selectivity estimate should be 1 - nullfrac.
    3211                 :             :          */
    3212                 :             :         VariableStatData leftvar;
    3213                 :             :         VariableStatData rightvar;
    3214                 :             :         bool        reversed;
    3215                 :             :         HeapTuple   statsTuple;
    3216                 :             :         double      nullfrac;
    3217                 :             : 
    3218                 :         879 :         get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
    3219         [ +  + ]:         879 :         statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
    3220         [ +  + ]:         879 :         if (HeapTupleIsValid(statsTuple))
    3221                 :         702 :             nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
    3222                 :             :         else
    3223                 :         177 :             nullfrac = 0.0;
    3224         [ +  + ]:         879 :         ReleaseVariableStats(leftvar);
    3225         [ +  + ]:         879 :         ReleaseVariableStats(rightvar);
    3226                 :             : 
    3227                 :         879 :         result = 1.0 - nullfrac;
    3228                 :             :     }
    3229                 :             :     else
    3230                 :             :     {
    3231                 :             :         /*
    3232                 :             :          * We want 1 - eqjoinsel() where the equality operator is the one
    3233                 :             :          * associated with this != operator, that is, its negator.
    3234                 :             :          */
    3235                 :        1580 :         Oid         eqop = get_negator(operator);
    3236                 :             : 
    3237         [ +  - ]:        1580 :         if (eqop)
    3238                 :             :         {
    3239                 :             :             result =
    3240                 :        1580 :                 DatumGetFloat8(DirectFunctionCall5Coll(eqjoinsel,
    3241                 :             :                                                        collation,
    3242                 :             :                                                        PointerGetDatum(root),
    3243                 :             :                                                        ObjectIdGetDatum(eqop),
    3244                 :             :                                                        PointerGetDatum(args),
    3245                 :             :                                                        Int16GetDatum(jointype),
    3246                 :             :                                                        PointerGetDatum(sjinfo)));
    3247                 :             :         }
    3248                 :             :         else
    3249                 :             :         {
    3250                 :             :             /* Use default selectivity (should we raise an error instead?) */
    3251                 :           0 :             result = DEFAULT_EQ_SEL;
    3252                 :             :         }
    3253                 :        1580 :         result = 1.0 - result;
    3254                 :             :     }
    3255                 :             : 
    3256                 :        2459 :     PG_RETURN_FLOAT8(result);
    3257                 :             : }
    3258                 :             : 
    3259                 :             : /*
    3260                 :             :  *      scalarltjoinsel - Join selectivity of "<" for scalars
    3261                 :             :  */
    3262                 :             : Datum
    3263                 :         270 : scalarltjoinsel(PG_FUNCTION_ARGS)
    3264                 :             : {
    3265                 :         270 :     PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    3266                 :             : }
    3267                 :             : 
    3268                 :             : /*
    3269                 :             :  *      scalarlejoinsel - Join selectivity of "<=" for scalars
    3270                 :             :  */
    3271                 :             : Datum
    3272                 :         198 : scalarlejoinsel(PG_FUNCTION_ARGS)
    3273                 :             : {
    3274                 :         198 :     PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    3275                 :             : }
    3276                 :             : 
    3277                 :             : /*
    3278                 :             :  *      scalargtjoinsel - Join selectivity of ">" for scalars
    3279                 :             :  */
    3280                 :             : Datum
    3281                 :         240 : scalargtjoinsel(PG_FUNCTION_ARGS)
    3282                 :             : {
    3283                 :         240 :     PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    3284                 :             : }
    3285                 :             : 
    3286                 :             : /*
    3287                 :             :  *      scalargejoinsel - Join selectivity of ">=" for scalars
    3288                 :             :  */
    3289                 :             : Datum
    3290                 :         152 : scalargejoinsel(PG_FUNCTION_ARGS)
    3291                 :             : {
    3292                 :         152 :     PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    3293                 :             : }
    3294                 :             : 
    3295                 :             : 
    3296                 :             : /*
    3297                 :             :  * mergejoinscansel         - Scan selectivity of merge join.
    3298                 :             :  *
    3299                 :             :  * A merge join will stop as soon as it exhausts either input stream.
    3300                 :             :  * Therefore, if we can estimate the ranges of both input variables,
    3301                 :             :  * we can estimate how much of the input will actually be read.  This
    3302                 :             :  * can have a considerable impact on the cost when using indexscans.
    3303                 :             :  *
    3304                 :             :  * Also, we can estimate how much of each input has to be read before the
    3305                 :             :  * first join pair is found, which will affect the join's startup time.
    3306                 :             :  *
    3307                 :             :  * clause should be a clause already known to be mergejoinable.  opfamily,
    3308                 :             :  * cmptype, and nulls_first specify the sort ordering being used.
    3309                 :             :  *
    3310                 :             :  * The outputs are:
    3311                 :             :  *      *leftstart is set to the fraction of the left-hand variable expected
    3312                 :             :  *       to be scanned before the first join pair is found (0 to 1).
    3313                 :             :  *      *leftend is set to the fraction of the left-hand variable expected
    3314                 :             :  *       to be scanned before the join terminates (0 to 1).
    3315                 :             :  *      *rightstart, *rightend similarly for the right-hand variable.
    3316                 :             :  */
    3317                 :             : void
    3318                 :       97814 : mergejoinscansel(PlannerInfo *root, Node *clause,
    3319                 :             :                  Oid opfamily, CompareType cmptype, bool nulls_first,
    3320                 :             :                  Selectivity *leftstart, Selectivity *leftend,
    3321                 :             :                  Selectivity *rightstart, Selectivity *rightend)
    3322                 :             : {
    3323                 :             :     Node       *left,
    3324                 :             :                *right;
    3325                 :             :     VariableStatData leftvar,
    3326                 :             :                 rightvar;
    3327                 :             :     Oid         opmethod;
    3328                 :             :     int         op_strategy;
    3329                 :             :     Oid         op_lefttype;
    3330                 :             :     Oid         op_righttype;
    3331                 :             :     Oid         opno,
    3332                 :             :                 collation,
    3333                 :             :                 lsortop,
    3334                 :             :                 rsortop,
    3335                 :             :                 lstatop,
    3336                 :             :                 rstatop,
    3337                 :             :                 ltop,
    3338                 :             :                 leop,
    3339                 :             :                 revltop,
    3340                 :             :                 revleop;
    3341                 :             :     StrategyNumber ltstrat,
    3342                 :             :                 lestrat,
    3343                 :             :                 gtstrat,
    3344                 :             :                 gestrat;
    3345                 :             :     bool        isgt;
    3346                 :             :     Datum       leftmin,
    3347                 :             :                 leftmax,
    3348                 :             :                 rightmin,
    3349                 :             :                 rightmax;
    3350                 :             :     double      selec;
    3351                 :             : 
    3352                 :             :     /* Set default results if we can't figure anything out. */
    3353                 :             :     /* XXX should default "start" fraction be a bit more than 0? */
    3354                 :       97814 :     *leftstart = *rightstart = 0.0;
    3355                 :       97814 :     *leftend = *rightend = 1.0;
    3356                 :             : 
    3357                 :             :     /* Deconstruct the merge clause */
    3358         [ -  + ]:       97814 :     if (!is_opclause(clause))
    3359                 :           0 :         return;                 /* shouldn't happen */
    3360                 :       97814 :     opno = ((OpExpr *) clause)->opno;
    3361                 :       97814 :     collation = ((OpExpr *) clause)->inputcollid;
    3362                 :       97814 :     left = get_leftop((Expr *) clause);
    3363                 :       97814 :     right = get_rightop((Expr *) clause);
    3364         [ -  + ]:       97814 :     if (!right)
    3365                 :           0 :         return;                 /* shouldn't happen */
    3366                 :             : 
    3367                 :             :     /* Look for stats for the inputs */
    3368                 :       97814 :     examine_variable(root, left, 0, &leftvar);
    3369                 :       97814 :     examine_variable(root, right, 0, &rightvar);
    3370                 :             : 
    3371                 :       97814 :     opmethod = get_opfamily_method(opfamily);
    3372                 :             : 
    3373                 :             :     /* Extract the operator's declared left/right datatypes */
    3374                 :       97814 :     get_op_opfamily_properties(opno, opfamily, false,
    3375                 :             :                                &op_strategy,
    3376                 :             :                                &op_lefttype,
    3377                 :             :                                &op_righttype);
    3378                 :             :     Assert(IndexAmTranslateStrategy(op_strategy, opmethod, opfamily, true) == COMPARE_EQ);
    3379                 :             : 
    3380                 :             :     /*
    3381                 :             :      * Look up the various operators we need.  If we don't find them all, it
    3382                 :             :      * probably means the opfamily is broken, but we just fail silently.
    3383                 :             :      *
    3384                 :             :      * Note: we expect that pg_statistic histograms will be sorted by the '<'
    3385                 :             :      * operator, regardless of which sort direction we are considering.
    3386                 :             :      */
    3387      [ +  +  - ]:       97814 :     switch (cmptype)
    3388                 :             :     {
    3389                 :       97785 :         case COMPARE_LT:
    3390                 :       97785 :             isgt = false;
    3391                 :       97785 :             ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
    3392                 :       97785 :             lestrat = IndexAmTranslateCompareType(COMPARE_LE, opmethod, opfamily, true);
    3393         [ +  + ]:       97785 :             if (op_lefttype == op_righttype)
    3394                 :             :             {
    3395                 :             :                 /* easy case */
    3396                 :       96719 :                 ltop = get_opfamily_member(opfamily,
    3397                 :             :                                            op_lefttype, op_righttype,
    3398                 :             :                                            ltstrat);
    3399                 :       96719 :                 leop = get_opfamily_member(opfamily,
    3400                 :             :                                            op_lefttype, op_righttype,
    3401                 :             :                                            lestrat);
    3402                 :       96719 :                 lsortop = ltop;
    3403                 :       96719 :                 rsortop = ltop;
    3404                 :       96719 :                 lstatop = lsortop;
    3405                 :       96719 :                 rstatop = rsortop;
    3406                 :       96719 :                 revltop = ltop;
    3407                 :       96719 :                 revleop = leop;
    3408                 :             :             }
    3409                 :             :             else
    3410                 :             :             {
    3411                 :        1066 :                 ltop = get_opfamily_member(opfamily,
    3412                 :             :                                            op_lefttype, op_righttype,
    3413                 :             :                                            ltstrat);
    3414                 :        1066 :                 leop = get_opfamily_member(opfamily,
    3415                 :             :                                            op_lefttype, op_righttype,
    3416                 :             :                                            lestrat);
    3417                 :        1066 :                 lsortop = get_opfamily_member(opfamily,
    3418                 :             :                                               op_lefttype, op_lefttype,
    3419                 :             :                                               ltstrat);
    3420                 :        1066 :                 rsortop = get_opfamily_member(opfamily,
    3421                 :             :                                               op_righttype, op_righttype,
    3422                 :             :                                               ltstrat);
    3423                 :        1066 :                 lstatop = lsortop;
    3424                 :        1066 :                 rstatop = rsortop;
    3425                 :        1066 :                 revltop = get_opfamily_member(opfamily,
    3426                 :             :                                               op_righttype, op_lefttype,
    3427                 :             :                                               ltstrat);
    3428                 :        1066 :                 revleop = get_opfamily_member(opfamily,
    3429                 :             :                                               op_righttype, op_lefttype,
    3430                 :             :                                               lestrat);
    3431                 :             :             }
    3432                 :       97785 :             break;
    3433                 :          29 :         case COMPARE_GT:
    3434                 :             :             /* descending-order case */
    3435                 :          29 :             isgt = true;
    3436                 :          29 :             ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
    3437                 :          29 :             gtstrat = IndexAmTranslateCompareType(COMPARE_GT, opmethod, opfamily, true);
    3438                 :          29 :             gestrat = IndexAmTranslateCompareType(COMPARE_GE, opmethod, opfamily, true);
    3439         [ +  - ]:          29 :             if (op_lefttype == op_righttype)
    3440                 :             :             {
    3441                 :             :                 /* easy case */
    3442                 :          29 :                 ltop = get_opfamily_member(opfamily,
    3443                 :             :                                            op_lefttype, op_righttype,
    3444                 :             :                                            gtstrat);
    3445                 :          29 :                 leop = get_opfamily_member(opfamily,
    3446                 :             :                                            op_lefttype, op_righttype,
    3447                 :             :                                            gestrat);
    3448                 :          29 :                 lsortop = ltop;
    3449                 :          29 :                 rsortop = ltop;
    3450                 :          29 :                 lstatop = get_opfamily_member(opfamily,
    3451                 :             :                                               op_lefttype, op_lefttype,
    3452                 :             :                                               ltstrat);
    3453                 :          29 :                 rstatop = lstatop;
    3454                 :          29 :                 revltop = ltop;
    3455                 :          29 :                 revleop = leop;
    3456                 :             :             }
    3457                 :             :             else
    3458                 :             :             {
    3459                 :           0 :                 ltop = get_opfamily_member(opfamily,
    3460                 :             :                                            op_lefttype, op_righttype,
    3461                 :             :                                            gtstrat);
    3462                 :           0 :                 leop = get_opfamily_member(opfamily,
    3463                 :             :                                            op_lefttype, op_righttype,
    3464                 :             :                                            gestrat);
    3465                 :           0 :                 lsortop = get_opfamily_member(opfamily,
    3466                 :             :                                               op_lefttype, op_lefttype,
    3467                 :             :                                               gtstrat);
    3468                 :           0 :                 rsortop = get_opfamily_member(opfamily,
    3469                 :             :                                               op_righttype, op_righttype,
    3470                 :             :                                               gtstrat);
    3471                 :           0 :                 lstatop = get_opfamily_member(opfamily,
    3472                 :             :                                               op_lefttype, op_lefttype,
    3473                 :             :                                               ltstrat);
    3474                 :           0 :                 rstatop = get_opfamily_member(opfamily,
    3475                 :             :                                               op_righttype, op_righttype,
    3476                 :             :                                               ltstrat);
    3477                 :           0 :                 revltop = get_opfamily_member(opfamily,
    3478                 :             :                                               op_righttype, op_lefttype,
    3479                 :             :                                               gtstrat);
    3480                 :           0 :                 revleop = get_opfamily_member(opfamily,
    3481                 :             :                                               op_righttype, op_lefttype,
    3482                 :             :                                               gestrat);
    3483                 :             :             }
    3484                 :          29 :             break;
    3485                 :           0 :         default:
    3486                 :           0 :             goto fail;          /* shouldn't get here */
    3487                 :             :     }
    3488                 :             : 
    3489   [ +  -  +  - ]:       97814 :     if (!OidIsValid(lsortop) ||
    3490         [ +  - ]:       97814 :         !OidIsValid(rsortop) ||
    3491         [ +  - ]:       97814 :         !OidIsValid(lstatop) ||
    3492         [ +  + ]:       97814 :         !OidIsValid(rstatop) ||
    3493         [ +  - ]:       97804 :         !OidIsValid(ltop) ||
    3494         [ +  - ]:       97804 :         !OidIsValid(leop) ||
    3495         [ -  + ]:       97804 :         !OidIsValid(revltop) ||
    3496                 :             :         !OidIsValid(revleop))
    3497                 :          10 :         goto fail;              /* insufficient info in catalogs */
    3498                 :             : 
    3499                 :             :     /* Try to get ranges of both inputs */
    3500         [ +  + ]:       97804 :     if (!isgt)
    3501                 :             :     {
    3502         [ +  + ]:       97775 :         if (!get_variable_range(root, &leftvar, lstatop, collation,
    3503                 :             :                                 &leftmin, &leftmax))
    3504                 :       29622 :             goto fail;          /* no range available from stats */
    3505         [ +  + ]:       68153 :         if (!get_variable_range(root, &rightvar, rstatop, collation,
    3506                 :             :                                 &rightmin, &rightmax))
    3507                 :       17357 :             goto fail;          /* no range available from stats */
    3508                 :             :     }
    3509                 :             :     else
    3510                 :             :     {
    3511                 :             :         /* need to swap the max and min */
    3512         [ +  + ]:          29 :         if (!get_variable_range(root, &leftvar, lstatop, collation,
    3513                 :             :                                 &leftmax, &leftmin))
    3514                 :          24 :             goto fail;          /* no range available from stats */
    3515         [ -  + ]:           5 :         if (!get_variable_range(root, &rightvar, rstatop, collation,
    3516                 :             :                                 &rightmax, &rightmin))
    3517                 :           0 :             goto fail;          /* no range available from stats */
    3518                 :             :     }
    3519                 :             : 
    3520                 :             :     /*
    3521                 :             :      * Now, the fraction of the left variable that will be scanned is the
    3522                 :             :      * fraction that's <= the right-side maximum value.  But only believe
    3523                 :             :      * non-default estimates, else stick with our 1.0.
    3524                 :             :      */
    3525                 :       50801 :     selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
    3526                 :             :                           rightmax, op_righttype);
    3527         [ +  + ]:       50801 :     if (selec != DEFAULT_INEQ_SEL)
    3528                 :       50797 :         *leftend = selec;
    3529                 :             : 
    3530                 :             :     /* And similarly for the right variable. */
    3531                 :       50801 :     selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
    3532                 :             :                           leftmax, op_lefttype);
    3533         [ +  - ]:       50801 :     if (selec != DEFAULT_INEQ_SEL)
    3534                 :       50801 :         *rightend = selec;
    3535                 :             : 
    3536                 :             :     /*
    3537                 :             :      * Only one of the two "end" fractions can really be less than 1.0;
    3538                 :             :      * believe the smaller estimate and reset the other one to exactly 1.0. If
    3539                 :             :      * we get exactly equal estimates (as can easily happen with self-joins),
    3540                 :             :      * believe neither.
    3541                 :             :      */
    3542         [ +  + ]:       50801 :     if (*leftend > *rightend)
    3543                 :       16342 :         *leftend = 1.0;
    3544         [ +  + ]:       34459 :     else if (*leftend < *rightend)
    3545                 :       18444 :         *rightend = 1.0;
    3546                 :             :     else
    3547                 :       16015 :         *leftend = *rightend = 1.0;
    3548                 :             : 
    3549                 :             :     /*
    3550                 :             :      * Also, the fraction of the left variable that will be scanned before the
    3551                 :             :      * first join pair is found is the fraction that's < the right-side
    3552                 :             :      * minimum value.  But only believe non-default estimates, else stick with
    3553                 :             :      * our own default.
    3554                 :             :      */
    3555                 :       50801 :     selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
    3556                 :             :                           rightmin, op_righttype);
    3557         [ +  - ]:       50801 :     if (selec != DEFAULT_INEQ_SEL)
    3558                 :       50801 :         *leftstart = selec;
    3559                 :             : 
    3560                 :             :     /* And similarly for the right variable. */
    3561                 :       50801 :     selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
    3562                 :             :                           leftmin, op_lefttype);
    3563         [ +  - ]:       50801 :     if (selec != DEFAULT_INEQ_SEL)
    3564                 :       50801 :         *rightstart = selec;
    3565                 :             : 
    3566                 :             :     /*
    3567                 :             :      * Only one of the two "start" fractions can really be more than zero;
    3568                 :             :      * believe the larger estimate and reset the other one to exactly 0.0. If
    3569                 :             :      * we get exactly equal estimates (as can easily happen with self-joins),
    3570                 :             :      * believe neither.
    3571                 :             :      */
    3572         [ +  + ]:       50801 :     if (*leftstart < *rightstart)
    3573                 :        9604 :         *leftstart = 0.0;
    3574         [ +  + ]:       41197 :     else if (*leftstart > *rightstart)
    3575                 :       13554 :         *rightstart = 0.0;
    3576                 :             :     else
    3577                 :       27643 :         *leftstart = *rightstart = 0.0;
    3578                 :             : 
    3579                 :             :     /*
    3580                 :             :      * If the sort order is nulls-first, we're going to have to skip over any
    3581                 :             :      * nulls too.  These would not have been counted by scalarineqsel, and we
    3582                 :             :      * can safely add in this fraction regardless of whether we believe
    3583                 :             :      * scalarineqsel's results or not.  But be sure to clamp the sum to 1.0!
    3584                 :             :      */
    3585         [ +  + ]:       50801 :     if (nulls_first)
    3586                 :             :     {
    3587                 :             :         Form_pg_statistic stats;
    3588                 :             : 
    3589         [ +  - ]:           5 :         if (HeapTupleIsValid(leftvar.statsTuple))
    3590                 :             :         {
    3591                 :           5 :             stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
    3592                 :           5 :             *leftstart += stats->stanullfrac;
    3593   [ -  +  -  + ]:           5 :             CLAMP_PROBABILITY(*leftstart);
    3594                 :           5 :             *leftend += stats->stanullfrac;
    3595   [ -  +  -  + ]:           5 :             CLAMP_PROBABILITY(*leftend);
    3596                 :             :         }
    3597         [ +  - ]:           5 :         if (HeapTupleIsValid(rightvar.statsTuple))
    3598                 :             :         {
    3599                 :           5 :             stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
    3600                 :           5 :             *rightstart += stats->stanullfrac;
    3601   [ -  +  -  + ]:           5 :             CLAMP_PROBABILITY(*rightstart);
    3602                 :           5 :             *rightend += stats->stanullfrac;
    3603   [ -  +  -  + ]:           5 :             CLAMP_PROBABILITY(*rightend);
    3604                 :             :         }
    3605                 :             :     }
    3606                 :             : 
    3607                 :             :     /* Disbelieve start >= end, just in case that can happen */
    3608         [ +  + ]:       50801 :     if (*leftstart >= *leftend)
    3609                 :             :     {
    3610                 :         124 :         *leftstart = 0.0;
    3611                 :         124 :         *leftend = 1.0;
    3612                 :             :     }
    3613         [ +  + ]:       50801 :     if (*rightstart >= *rightend)
    3614                 :             :     {
    3615                 :         581 :         *rightstart = 0.0;
    3616                 :         581 :         *rightend = 1.0;
    3617                 :             :     }
    3618                 :             : 
    3619                 :       50220 : fail:
    3620         [ +  + ]:       97814 :     ReleaseVariableStats(leftvar);
    3621         [ +  + ]:       97814 :     ReleaseVariableStats(rightvar);
    3622                 :             : }
    3623                 :             : 
    3624                 :             : 
    3625                 :             : /*
    3626                 :             :  *  matchingsel -- generic matching-operator selectivity support
    3627                 :             :  *
    3628                 :             :  * Use these for any operators that (a) are on data types for which we collect
    3629                 :             :  * standard statistics, and (b) have behavior for which the default estimate
    3630                 :             :  * (twice DEFAULT_EQ_SEL) is sane.  Typically that is good for match-like
    3631                 :             :  * operators.
    3632                 :             :  */
    3633                 :             : 
    3634                 :             : Datum
    3635                 :         845 : matchingsel(PG_FUNCTION_ARGS)
    3636                 :             : {
    3637                 :         845 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    3638                 :         845 :     Oid         operator = PG_GETARG_OID(1);
    3639                 :         845 :     List       *args = (List *) PG_GETARG_POINTER(2);
    3640                 :         845 :     int         varRelid = PG_GETARG_INT32(3);
    3641                 :         845 :     Oid         collation = PG_GET_COLLATION();
    3642                 :             :     double      selec;
    3643                 :             : 
    3644                 :             :     /* Use generic restriction selectivity logic. */
    3645                 :         845 :     selec = generic_restriction_selectivity(root, operator, collation,
    3646                 :             :                                             args, varRelid,
    3647                 :             :                                             DEFAULT_MATCHING_SEL);
    3648                 :             : 
    3649                 :         845 :     PG_RETURN_FLOAT8((float8) selec);
    3650                 :             : }
    3651                 :             : 
    3652                 :             : Datum
    3653                 :           5 : matchingjoinsel(PG_FUNCTION_ARGS)
    3654                 :             : {
    3655                 :             :     /* Just punt, for the moment. */
    3656                 :           5 :     PG_RETURN_FLOAT8(DEFAULT_MATCHING_SEL);
    3657                 :             : }
    3658                 :             : 
    3659                 :             : 
    3660                 :             : /*
    3661                 :             :  * Helper routine for estimate_num_groups: add an item to a list of
    3662                 :             :  * GroupVarInfos, but only if it's not known equal to any of the existing
    3663                 :             :  * entries.
    3664                 :             :  */
    3665                 :             : typedef struct
    3666                 :             : {
    3667                 :             :     Node       *var;            /* might be an expression, not just a Var */
    3668                 :             :     RelOptInfo *rel;            /* relation it belongs to */
    3669                 :             :     double      ndistinct;      /* # distinct values */
    3670                 :             :     bool        isdefault;      /* true if DEFAULT_NUM_DISTINCT was used */
    3671                 :             : } GroupVarInfo;
    3672                 :             : 
    3673                 :             : static List *
    3674                 :      279682 : add_unique_group_var(PlannerInfo *root, List *varinfos,
    3675                 :             :                      Node *var, VariableStatData *vardata)
    3676                 :             : {
    3677                 :             :     GroupVarInfo *varinfo;
    3678                 :             :     double      ndistinct;
    3679                 :             :     bool        isdefault;
    3680                 :             :     ListCell   *lc;
    3681                 :             : 
    3682                 :      279682 :     ndistinct = get_variable_numdistinct(vardata, &isdefault);
    3683                 :             : 
    3684                 :             :     /*
    3685                 :             :      * The nullingrels bits within the var could cause the same var to be
    3686                 :             :      * counted multiple times if it's marked with different nullingrels.  They
    3687                 :             :      * could also prevent us from matching the var to the expressions in
    3688                 :             :      * extended statistics (see estimate_multivariate_ndistinct).  So strip
    3689                 :             :      * them out first.
    3690                 :             :      */
    3691                 :      279682 :     var = remove_nulling_relids(var, root->outer_join_rels, NULL);
    3692                 :             : 
    3693   [ +  +  +  +  :      372900 :     foreach(lc, varinfos)
                   +  + ]
    3694                 :             :     {
    3695                 :       96582 :         varinfo = (GroupVarInfo *) lfirst(lc);
    3696                 :             : 
    3697                 :             :         /* Drop exact duplicates */
    3698         [ +  + ]:       96582 :         if (equal(var, varinfo->var))
    3699                 :        3364 :             return varinfos;
    3700                 :             : 
    3701                 :             :         /*
    3702                 :             :          * Drop known-equal vars, but only if they belong to different
    3703                 :             :          * relations (see comments for estimate_num_groups).  We aren't too
    3704                 :             :          * fussy about the semantics of "equal" here.
    3705                 :             :          */
    3706   [ +  +  +  + ]:      118466 :         if (vardata->rel != varinfo->rel &&
    3707                 :       25054 :             exprs_known_equal(root, var, varinfo->var, InvalidOid))
    3708                 :             :         {
    3709         [ +  + ]:        2801 :             if (varinfo->ndistinct <= ndistinct)
    3710                 :             :             {
    3711                 :             :                 /* Keep older item, forget new one */
    3712                 :         194 :                 return varinfos;
    3713                 :             :             }
    3714                 :             :             else
    3715                 :             :             {
    3716                 :             :                 /* Delete the older item */
    3717                 :        2607 :                 varinfos = foreach_delete_current(varinfos, lc);
    3718                 :             :             }
    3719                 :             :         }
    3720                 :             :     }
    3721                 :             : 
    3722                 :      276318 :     varinfo = palloc_object(GroupVarInfo);
    3723                 :             : 
    3724                 :      276318 :     varinfo->var = var;
    3725                 :      276318 :     varinfo->rel = vardata->rel;
    3726                 :      276318 :     varinfo->ndistinct = ndistinct;
    3727                 :      276318 :     varinfo->isdefault = isdefault;
    3728                 :      276318 :     varinfos = lappend(varinfos, varinfo);
    3729                 :      276318 :     return varinfos;
    3730                 :             : }
    3731                 :             : 
    3732                 :             : /*
    3733                 :             :  * estimate_num_groups      - Estimate number of groups in a grouped query
    3734                 :             :  *
    3735                 :             :  * Given a query having a GROUP BY clause, estimate how many groups there
    3736                 :             :  * will be --- ie, the number of distinct combinations of the GROUP BY
    3737                 :             :  * expressions.
    3738                 :             :  *
    3739                 :             :  * This routine is also used to estimate the number of rows emitted by
    3740                 :             :  * a DISTINCT filtering step; that is an isomorphic problem.  (Note:
    3741                 :             :  * actually, we only use it for DISTINCT when there's no grouping or
    3742                 :             :  * aggregation ahead of the DISTINCT.)
    3743                 :             :  *
    3744                 :             :  * Inputs:
    3745                 :             :  *  root - the query
    3746                 :             :  *  groupExprs - list of expressions being grouped by
    3747                 :             :  *  input_rows - number of rows estimated to arrive at the group/unique
    3748                 :             :  *      filter step
    3749                 :             :  *  pgset - NULL, or a List** pointing to a grouping set to filter the
    3750                 :             :  *      groupExprs against
    3751                 :             :  *
    3752                 :             :  * Outputs:
    3753                 :             :  *  estinfo - When passed as non-NULL, the function will set bits in the
    3754                 :             :  *      "flags" field in order to provide callers with additional information
    3755                 :             :  *      about the estimation.  Currently, we only set the SELFLAG_USED_DEFAULT
    3756                 :             :  *      bit if we used any default values in the estimation.
    3757                 :             :  *
    3758                 :             :  * Given the lack of any cross-correlation statistics in the system, it's
    3759                 :             :  * impossible to do anything really trustworthy with GROUP BY conditions
    3760                 :             :  * involving multiple Vars.  We should however avoid assuming the worst
    3761                 :             :  * case (all possible cross-product terms actually appear as groups) since
    3762                 :             :  * very often the grouped-by Vars are highly correlated.  Our current approach
    3763                 :             :  * is as follows:
    3764                 :             :  *  1.  Expressions yielding boolean are assumed to contribute two groups,
    3765                 :             :  *      independently of their content, and are ignored in the subsequent
    3766                 :             :  *      steps.  This is mainly because tests like "col IS NULL" break the
    3767                 :             :  *      heuristic used in step 2 especially badly.
    3768                 :             :  *  2.  Reduce the given expressions to a list of unique Vars used.  For
    3769                 :             :  *      example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
    3770                 :             :  *      It is clearly correct not to count the same Var more than once.
    3771                 :             :  *      It is also reasonable to treat f(x) the same as x: f() cannot
    3772                 :             :  *      increase the number of distinct values (unless it is volatile,
    3773                 :             :  *      which we consider unlikely for grouping), but it probably won't
    3774                 :             :  *      reduce the number of distinct values much either.
    3775                 :             :  *      As a special case, if a GROUP BY expression can be matched to an
    3776                 :             :  *      expressional index for which we have statistics, then we treat the
    3777                 :             :  *      whole expression as though it were just a Var.
    3778                 :             :  *  3.  If the list contains Vars of different relations that are known equal
    3779                 :             :  *      due to equivalence classes, then drop all but one of the Vars from each
    3780                 :             :  *      known-equal set, keeping the one with smallest estimated # of values
    3781                 :             :  *      (since the extra values of the others can't appear in joined rows).
    3782                 :             :  *      Note the reason we only consider Vars of different relations is that
    3783                 :             :  *      if we considered ones of the same rel, we'd be double-counting the
    3784                 :             :  *      restriction selectivity of the equality in the next step.
    3785                 :             :  *  4.  For Vars within a single source rel, we multiply together the numbers
    3786                 :             :  *      of values, clamp to the number of rows in the rel (divided by 10 if
    3787                 :             :  *      more than one Var), and then multiply by a factor based on the
    3788                 :             :  *      selectivity of the restriction clauses for that rel.  When there's
    3789                 :             :  *      more than one Var, the initial product is probably too high (it's the
    3790                 :             :  *      worst case) but clamping to a fraction of the rel's rows seems to be a
    3791                 :             :  *      helpful heuristic for not letting the estimate get out of hand.  (The
    3792                 :             :  *      factor of 10 is derived from pre-Postgres-7.4 practice.)  The factor
    3793                 :             :  *      we multiply by to adjust for the restriction selectivity assumes that
    3794                 :             :  *      the restriction clauses are independent of the grouping, which may not
    3795                 :             :  *      be a valid assumption, but it's hard to do better.
    3796                 :             :  *  5.  If there are Vars from multiple rels, we repeat step 4 for each such
    3797                 :             :  *      rel, and multiply the results together.
    3798                 :             :  * Note that rels not containing grouped Vars are ignored completely, as are
    3799                 :             :  * join clauses.  Such rels cannot increase the number of groups, and we
    3800                 :             :  * assume such clauses do not reduce the number either (somewhat bogus,
    3801                 :             :  * but we don't have the info to do better).
    3802                 :             :  */
    3803                 :             : double
    3804                 :      234700 : estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
    3805                 :             :                     List **pgset, EstimationInfo *estinfo)
    3806                 :             : {
    3807                 :      234700 :     List       *varinfos = NIL;
    3808                 :      234700 :     double      srf_multiplier = 1.0;
    3809                 :             :     double      numdistinct;
    3810                 :             :     ListCell   *l;
    3811                 :             :     int         i;
    3812                 :             : 
    3813                 :             :     /* Zero the estinfo output parameter, if non-NULL */
    3814         [ +  + ]:      234700 :     if (estinfo != NULL)
    3815                 :      184577 :         memset(estinfo, 0, sizeof(EstimationInfo));
    3816                 :             : 
    3817                 :             :     /*
    3818                 :             :      * We don't ever want to return an estimate of zero groups, as that tends
    3819                 :             :      * to lead to division-by-zero and other unpleasantness.  The input_rows
    3820                 :             :      * estimate is usually already at least 1, but clamp it just in case it
    3821                 :             :      * isn't.
    3822                 :             :      */
    3823                 :      234700 :     input_rows = clamp_row_est(input_rows);
    3824                 :             : 
    3825                 :             :     /*
    3826                 :             :      * If no grouping columns, there's exactly one group.  (This can't happen
    3827                 :             :      * for normal cases with GROUP BY or DISTINCT, but it is possible for
    3828                 :             :      * corner cases with set operations.)
    3829                 :             :      */
    3830   [ +  +  +  +  :      234700 :     if (groupExprs == NIL || (pgset && *pgset == NIL))
                   +  + ]
    3831                 :        1025 :         return 1.0;
    3832                 :             : 
    3833                 :             :     /*
    3834                 :             :      * Count groups derived from boolean grouping expressions.  For other
    3835                 :             :      * expressions, find the unique Vars used, treating an expression as a Var
    3836                 :             :      * if we can find stats for it.  For each one, record the statistical
    3837                 :             :      * estimate of number of distinct values (total in its table, without
    3838                 :             :      * regard for filtering).
    3839                 :             :      */
    3840                 :      233675 :     numdistinct = 1.0;
    3841                 :             : 
    3842                 :      233675 :     i = 0;
    3843   [ +  -  +  +  :      516866 :     foreach(l, groupExprs)
                   +  + ]
    3844                 :             :     {
    3845                 :      283241 :         Node       *groupexpr = (Node *) lfirst(l);
    3846                 :             :         double      this_srf_multiplier;
    3847                 :             :         VariableStatData vardata;
    3848                 :             :         List       *varshere;
    3849                 :             :         ListCell   *l2;
    3850                 :             : 
    3851                 :             :         /* is expression in this grouping set? */
    3852   [ +  +  +  + ]:      283241 :         if (pgset && !list_member_int(*pgset, i++))
    3853                 :      219039 :             continue;
    3854                 :             : 
    3855                 :             :         /*
    3856                 :             :          * Set-returning functions in grouping columns are a bit problematic.
    3857                 :             :          * The code below will effectively ignore their SRF nature and come up
    3858                 :             :          * with a numdistinct estimate as though they were scalar functions.
    3859                 :             :          * We compensate by scaling up the end result by the largest SRF
    3860                 :             :          * rowcount estimate.  (This will be an overestimate if the SRF
    3861                 :             :          * produces multiple copies of any output value, but it seems best to
    3862                 :             :          * assume the SRF's outputs are distinct.  In any case, it's probably
    3863                 :             :          * pointless to worry too much about this without much better
    3864                 :             :          * estimates for SRF output rowcounts than we have today.)
    3865                 :             :          */
    3866                 :      282573 :         this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
    3867         [ +  + ]:      282573 :         if (srf_multiplier < this_srf_multiplier)
    3868                 :         170 :             srf_multiplier = this_srf_multiplier;
    3869                 :             : 
    3870                 :             :         /* Short-circuit for expressions returning boolean */
    3871         [ +  + ]:      282573 :         if (exprType(groupexpr) == BOOLOID)
    3872                 :             :         {
    3873                 :         732 :             numdistinct *= 2.0;
    3874                 :         732 :             continue;
    3875                 :             :         }
    3876                 :             : 
    3877                 :             :         /*
    3878                 :             :          * If examine_variable is able to deduce anything about the GROUP BY
    3879                 :             :          * expression, treat it as a single variable even if it's really more
    3880                 :             :          * complicated.
    3881                 :             :          *
    3882                 :             :          * XXX This has the consequence that if there's a statistics object on
    3883                 :             :          * the expression, we don't split it into individual Vars. This
    3884                 :             :          * affects our selection of statistics in
    3885                 :             :          * estimate_multivariate_ndistinct, because it's probably better to
    3886                 :             :          * use more accurate estimate for each expression and treat them as
    3887                 :             :          * independent, than to combine estimates for the extracted variables
    3888                 :             :          * when we don't know how that relates to the expressions.
    3889                 :             :          */
    3890                 :      281841 :         examine_variable(root, groupexpr, 0, &vardata);
    3891   [ +  +  +  + ]:      281841 :         if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
    3892                 :             :         {
    3893                 :      205677 :             varinfos = add_unique_group_var(root, varinfos,
    3894                 :             :                                             groupexpr, &vardata);
    3895         [ +  + ]:      205677 :             ReleaseVariableStats(vardata);
    3896                 :      205677 :             continue;
    3897                 :             :         }
    3898         [ -  + ]:       76164 :         ReleaseVariableStats(vardata);
    3899                 :             : 
    3900                 :             :         /*
    3901                 :             :          * Else pull out the component Vars.  Handle PlaceHolderVars by
    3902                 :             :          * recursing into their arguments (effectively assuming that the
    3903                 :             :          * PlaceHolderVar doesn't change the number of groups, which boils
    3904                 :             :          * down to ignoring the possible addition of nulls to the result set).
    3905                 :             :          */
    3906                 :       76164 :         varshere = pull_var_clause(groupexpr,
    3907                 :             :                                    PVC_RECURSE_AGGREGATES |
    3908                 :             :                                    PVC_RECURSE_WINDOWFUNCS |
    3909                 :             :                                    PVC_RECURSE_PLACEHOLDERS);
    3910                 :             : 
    3911                 :             :         /*
    3912                 :             :          * If we find any variable-free GROUP BY item, then either it is a
    3913                 :             :          * constant (and we can ignore it) or it contains a volatile function;
    3914                 :             :          * in the latter case we punt and assume that each input row will
    3915                 :             :          * yield a distinct group.
    3916                 :             :          */
    3917         [ +  + ]:       76164 :         if (varshere == NIL)
    3918                 :             :         {
    3919         [ +  + ]:       12012 :             if (contain_volatile_functions(groupexpr))
    3920                 :          50 :                 return input_rows;
    3921                 :       11962 :             continue;
    3922                 :             :         }
    3923                 :             : 
    3924                 :             :         /*
    3925                 :             :          * Else add variables to varinfos list
    3926                 :             :          */
    3927   [ +  -  +  +  :      138157 :         foreach(l2, varshere)
                   +  + ]
    3928                 :             :         {
    3929                 :       74005 :             Node       *var = (Node *) lfirst(l2);
    3930                 :             : 
    3931                 :       74005 :             examine_variable(root, var, 0, &vardata);
    3932                 :       74005 :             varinfos = add_unique_group_var(root, varinfos, var, &vardata);
    3933         [ +  + ]:       74005 :             ReleaseVariableStats(vardata);
    3934                 :             :         }
    3935                 :             :     }
    3936                 :             : 
    3937                 :             :     /*
    3938                 :             :      * If now no Vars, we must have an all-constant or all-boolean GROUP BY
    3939                 :             :      * list.
    3940                 :             :      */
    3941         [ +  + ]:      233625 :     if (varinfos == NIL)
    3942                 :             :     {
    3943                 :             :         /* Apply SRF multiplier as we would do in the long path */
    3944                 :         911 :         numdistinct *= srf_multiplier;
    3945                 :             :         /* Round off */
    3946                 :         911 :         numdistinct = ceil(numdistinct);
    3947                 :             :         /* Guard against out-of-range answers */
    3948         [ +  + ]:         911 :         if (numdistinct > input_rows)
    3949                 :          61 :             numdistinct = input_rows;
    3950         [ -  + ]:         911 :         if (numdistinct < 1.0)
    3951                 :           0 :             numdistinct = 1.0;
    3952                 :         911 :         return numdistinct;
    3953                 :             :     }
    3954                 :             : 
    3955                 :             :     /*
    3956                 :             :      * Group Vars by relation and estimate total numdistinct.
    3957                 :             :      *
    3958                 :             :      * For each iteration of the outer loop, we process the frontmost Var in
    3959                 :             :      * varinfos, plus all other Vars in the same relation.  We remove these
    3960                 :             :      * Vars from the newvarinfos list for the next iteration. This is the
    3961                 :             :      * easiest way to group Vars of same rel together.
    3962                 :             :      */
    3963                 :             :     do
    3964                 :             :     {
    3965                 :      237523 :         GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
    3966                 :      237523 :         RelOptInfo *rel = varinfo1->rel;
    3967                 :      237523 :         double      reldistinct = 1;
    3968                 :      237523 :         double      relmaxndistinct = reldistinct;
    3969                 :      237523 :         int         relvarcount = 0;
    3970                 :      237523 :         List       *newvarinfos = NIL;
    3971                 :      237523 :         List       *relvarinfos = NIL;
    3972                 :             : 
    3973                 :             :         /*
    3974                 :             :          * Split the list of varinfos in two - one for the current rel, one
    3975                 :             :          * for remaining Vars on other rels.
    3976                 :             :          */
    3977                 :      237523 :         relvarinfos = lappend(relvarinfos, varinfo1);
    3978   [ +  -  +  +  :      284711 :         for_each_from(l, varinfos, 1)
                   +  + ]
    3979                 :             :         {
    3980                 :       47188 :             GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
    3981                 :             : 
    3982         [ +  + ]:       47188 :             if (varinfo2->rel == varinfo1->rel)
    3983                 :             :             {
    3984                 :             :                 /* varinfos on current rel */
    3985                 :       36188 :                 relvarinfos = lappend(relvarinfos, varinfo2);
    3986                 :             :             }
    3987                 :             :             else
    3988                 :             :             {
    3989                 :             :                 /* not time to process varinfo2 yet */
    3990                 :       11000 :                 newvarinfos = lappend(newvarinfos, varinfo2);
    3991                 :             :             }
    3992                 :             :         }
    3993                 :             : 
    3994                 :             :         /*
    3995                 :             :          * Get the numdistinct estimate for the Vars of this rel.  We
    3996                 :             :          * iteratively search for multivariate n-distinct with maximum number
    3997                 :             :          * of vars; assuming that each var group is independent of the others,
    3998                 :             :          * we multiply them together.  Any remaining relvarinfos after no more
    3999                 :             :          * multivariate matches are found are assumed independent too, so
    4000                 :             :          * their individual ndistinct estimates are multiplied also.
    4001                 :             :          *
    4002                 :             :          * While iterating, count how many separate numdistinct values we
    4003                 :             :          * apply.  We apply a fudge factor below, but only if we multiplied
    4004                 :             :          * more than one such values.
    4005                 :             :          */
    4006         [ +  + ]:      475151 :         while (relvarinfos)
    4007                 :             :         {
    4008                 :             :             double      mvndistinct;
    4009                 :             : 
    4010         [ +  + ]:      237628 :             if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
    4011                 :             :                                                 &mvndistinct))
    4012                 :             :             {
    4013                 :         345 :                 reldistinct *= mvndistinct;
    4014         [ +  + ]:         345 :                 if (relmaxndistinct < mvndistinct)
    4015                 :         335 :                     relmaxndistinct = mvndistinct;
    4016                 :         345 :                 relvarcount++;
    4017                 :             :             }
    4018                 :             :             else
    4019                 :             :             {
    4020   [ +  -  +  +  :      510264 :                 foreach(l, relvarinfos)
                   +  + ]
    4021                 :             :                 {
    4022                 :      272981 :                     GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
    4023                 :             : 
    4024                 :      272981 :                     reldistinct *= varinfo2->ndistinct;
    4025         [ +  + ]:      272981 :                     if (relmaxndistinct < varinfo2->ndistinct)
    4026                 :      238029 :                         relmaxndistinct = varinfo2->ndistinct;
    4027                 :      272981 :                     relvarcount++;
    4028                 :             : 
    4029                 :             :                     /*
    4030                 :             :                      * When varinfo2's isdefault is set then we'd better set
    4031                 :             :                      * the SELFLAG_USED_DEFAULT bit in the EstimationInfo.
    4032                 :             :                      */
    4033   [ +  +  +  + ]:      272981 :                     if (estinfo != NULL && varinfo2->isdefault)
    4034                 :       18236 :                         estinfo->flags |= SELFLAG_USED_DEFAULT;
    4035                 :             :                 }
    4036                 :             : 
    4037                 :             :                 /* we're done with this relation */
    4038                 :      237283 :                 relvarinfos = NIL;
    4039                 :             :             }
    4040                 :             :         }
    4041                 :             : 
    4042                 :             :         /*
    4043                 :             :          * Sanity check --- don't divide by zero if empty relation.
    4044                 :             :          */
    4045                 :             :         Assert(IS_SIMPLE_REL(rel));
    4046         [ +  + ]:      237523 :         if (rel->tuples > 0)
    4047                 :             :         {
    4048                 :             :             /*
    4049                 :             :              * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
    4050                 :             :              * fudge factor is because the Vars are probably correlated but we
    4051                 :             :              * don't know by how much.  We should never clamp to less than the
    4052                 :             :              * largest ndistinct value for any of the Vars, though, since
    4053                 :             :              * there will surely be at least that many groups.
    4054                 :             :              */
    4055                 :      233313 :             double      clamp = rel->tuples;
    4056                 :             : 
    4057         [ +  + ]:      233313 :             if (relvarcount > 1)
    4058                 :             :             {
    4059                 :       27936 :                 clamp *= 0.1;
    4060         [ +  + ]:       27936 :                 if (clamp < relmaxndistinct)
    4061                 :             :                 {
    4062                 :       25750 :                     clamp = relmaxndistinct;
    4063                 :             :                     /* for sanity in case some ndistinct is too large: */
    4064         [ +  + ]:       25750 :                     if (clamp > rel->tuples)
    4065                 :         110 :                         clamp = rel->tuples;
    4066                 :             :                 }
    4067                 :             :             }
    4068         [ +  + ]:      233313 :             if (reldistinct > clamp)
    4069                 :       23258 :                 reldistinct = clamp;
    4070                 :             : 
    4071                 :             :             /*
    4072                 :             :              * Update the estimate based on the restriction selectivity,
    4073                 :             :              * guarding against division by zero when reldistinct is zero.
    4074                 :             :              * Also skip this if we know that we are returning all rows.
    4075                 :             :              */
    4076   [ +  -  +  + ]:      233313 :             if (reldistinct > 0 && rel->rows < rel->tuples)
    4077                 :             :             {
    4078                 :             :                 /*
    4079                 :             :                  * Given a table containing N rows with n distinct values in a
    4080                 :             :                  * uniform distribution, if we select p rows at random then
    4081                 :             :                  * the expected number of distinct values selected is
    4082                 :             :                  *
    4083                 :             :                  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
    4084                 :             :                  *
    4085                 :             :                  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
    4086                 :             :                  *
    4087                 :             :                  * See "Approximating block accesses in database
    4088                 :             :                  * organizations", S. B. Yao, Communications of the ACM,
    4089                 :             :                  * Volume 20 Issue 4, April 1977 Pages 260-261.
    4090                 :             :                  *
    4091                 :             :                  * Alternatively, re-arranging the terms from the factorials,
    4092                 :             :                  * this may be written as
    4093                 :             :                  *
    4094                 :             :                  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
    4095                 :             :                  *
    4096                 :             :                  * This form of the formula is more efficient to compute in
    4097                 :             :                  * the common case where p is larger than N/n.  Additionally,
    4098                 :             :                  * as pointed out by Dell'Era, if i << N for all terms in the
    4099                 :             :                  * product, it can be approximated by
    4100                 :             :                  *
    4101                 :             :                  * n * (1 - ((N-p)/N)^(N/n))
    4102                 :             :                  *
    4103                 :             :                  * See "Expected distinct values when selecting from a bag
    4104                 :             :                  * without replacement", Alberto Dell'Era,
    4105                 :             :                  * http://www.adellera.it/investigations/distinct_balls/.
    4106                 :             :                  *
    4107                 :             :                  * The condition i << N is equivalent to n >> 1, so this is a
    4108                 :             :                  * good approximation when the number of distinct values in
    4109                 :             :                  * the table is large.  It turns out that this formula also
    4110                 :             :                  * works well even when n is small.
    4111                 :             :                  */
    4112                 :       66393 :                 reldistinct *=
    4113                 :       66393 :                     (1 - pow((rel->tuples - rel->rows) / rel->tuples,
    4114                 :       66393 :                              rel->tuples / reldistinct));
    4115                 :             :             }
    4116                 :      233313 :             reldistinct = clamp_row_est(reldistinct);
    4117                 :             : 
    4118                 :             :             /*
    4119                 :             :              * Update estimate of total distinct groups.
    4120                 :             :              */
    4121                 :      233313 :             numdistinct *= reldistinct;
    4122                 :             :         }
    4123                 :             : 
    4124                 :      237523 :         varinfos = newvarinfos;
    4125         [ +  + ]:      237523 :     } while (varinfos != NIL);
    4126                 :             : 
    4127                 :             :     /* Now we can account for the effects of any SRFs */
    4128                 :      232714 :     numdistinct *= srf_multiplier;
    4129                 :             : 
    4130                 :             :     /* Round off */
    4131                 :      232714 :     numdistinct = ceil(numdistinct);
    4132                 :             : 
    4133                 :             :     /* Guard against out-of-range answers */
    4134         [ +  + ]:      232714 :     if (numdistinct > input_rows)
    4135                 :       49941 :         numdistinct = input_rows;
    4136         [ -  + ]:      232714 :     if (numdistinct < 1.0)
    4137                 :           0 :         numdistinct = 1.0;
    4138                 :             : 
    4139                 :      232714 :     return numdistinct;
    4140                 :             : }
    4141                 :             : 
    4142                 :             : /*
    4143                 :             :  * Try to estimate the bucket size of the hash join inner side when the join
    4144                 :             :  * condition contains two or more clauses by employing extended statistics.
    4145                 :             :  *
    4146                 :             :  * The main idea of this approach is that the distinct value generated by
    4147                 :             :  * multivariate estimation on two or more columns would provide less bucket size
    4148                 :             :  * than estimation on one separate column.
    4149                 :             :  *
    4150                 :             :  * IMPORTANT: It is crucial to synchronize the approach of combining different
    4151                 :             :  * estimations with the caller's method.
    4152                 :             :  *
    4153                 :             :  * Return a list of clauses that didn't fetch any extended statistics.
    4154                 :             :  */
    4155                 :             : List *
    4156                 :      335102 : estimate_multivariate_bucketsize(PlannerInfo *root, RelOptInfo *inner,
    4157                 :             :                                  List *hashclauses,
    4158                 :             :                                  Selectivity *innerbucketsize)
    4159                 :             : {
    4160                 :             :     List       *clauses;
    4161                 :             :     List       *otherclauses;
    4162                 :             :     double      ndistinct;
    4163                 :             : 
    4164         [ +  + ]:      335102 :     if (list_length(hashclauses) <= 1)
    4165                 :             :     {
    4166                 :             :         /*
    4167                 :             :          * Nothing to do for a single clause.  Could we employ univariate
    4168                 :             :          * extended stat here?
    4169                 :             :          */
    4170                 :      308321 :         return hashclauses;
    4171                 :             :     }
    4172                 :             : 
    4173                 :             :     /* "clauses" is the list of hashclauses we've not dealt with yet */
    4174                 :       26781 :     clauses = list_copy(hashclauses);
    4175                 :             :     /* "otherclauses" holds clauses we are going to return to caller */
    4176                 :       26781 :     otherclauses = NIL;
    4177                 :             :     /* current estimate of ndistinct */
    4178                 :       26781 :     ndistinct = 1.0;
    4179         [ +  + ]:       53572 :     while (clauses != NIL)
    4180                 :             :     {
    4181                 :             :         ListCell   *lc;
    4182                 :       26791 :         int         relid = -1;
    4183                 :       26791 :         List       *varinfos = NIL;
    4184                 :       26791 :         List       *origin_rinfos = NIL;
    4185                 :             :         double      mvndistinct;
    4186                 :             :         List       *origin_varinfos;
    4187                 :       26791 :         int         group_relid = -1;
    4188                 :       26791 :         RelOptInfo *group_rel = NULL;
    4189                 :             :         ListCell   *lc1,
    4190                 :             :                    *lc2;
    4191                 :             : 
    4192                 :             :         /*
    4193                 :             :          * Find clauses, referencing the same single base relation and try to
    4194                 :             :          * estimate such a group with extended statistics.  Create varinfo for
    4195                 :             :          * an approved clause, push it to otherclauses, if it can't be
    4196                 :             :          * estimated here or ignore to process at the next iteration.
    4197                 :             :          */
    4198   [ +  +  +  +  :       82412 :         foreach(lc, clauses)
                   +  + ]
    4199                 :             :         {
    4200                 :       55621 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
    4201                 :             :             Node       *expr;
    4202                 :             :             Relids      relids;
    4203                 :             :             GroupVarInfo *varinfo;
    4204                 :             : 
    4205                 :             :             /*
    4206                 :             :              * Find the inner side of the join, which we need to estimate the
    4207                 :             :              * number of buckets.  Use outer_is_left because the
    4208                 :             :              * clause_sides_match_join routine has called on hash clauses.
    4209                 :             :              */
    4210                 :      111242 :             relids = rinfo->outer_is_left ?
    4211         [ +  + ]:       55621 :                 rinfo->right_relids : rinfo->left_relids;
    4212                 :      111242 :             expr = rinfo->outer_is_left ?
    4213         [ +  + ]:       55621 :                 get_rightop(rinfo->clause) : get_leftop(rinfo->clause);
    4214                 :             : 
    4215         [ +  + ]:       55621 :             if (bms_get_singleton_member(relids, &relid) &&
    4216         [ +  + ]:       54305 :                 root->simple_rel_array[relid]->statlist != NIL)
    4217                 :          40 :             {
    4218                 :          50 :                 bool        is_duplicate = false;
    4219                 :             : 
    4220                 :             :                 /*
    4221                 :             :                  * This inner-side expression references only one relation.
    4222                 :             :                  * Extended statistics on this clause can exist.
    4223                 :             :                  */
    4224         [ +  + ]:          50 :                 if (group_relid < 0)
    4225                 :             :                 {
    4226                 :          25 :                     RangeTblEntry *rte = root->simple_rte_array[relid];
    4227                 :             : 
    4228   [ +  -  -  + ]:          25 :                     if (!rte || (rte->relkind != RELKIND_RELATION &&
    4229         [ #  # ]:           0 :                                  rte->relkind != RELKIND_MATVIEW &&
    4230         [ #  # ]:           0 :                                  rte->relkind != RELKIND_FOREIGN_TABLE &&
    4231         [ #  # ]:           0 :                                  rte->relkind != RELKIND_PARTITIONED_TABLE))
    4232                 :             :                     {
    4233                 :             :                         /* Extended statistics can't exist in principle */
    4234                 :           0 :                         otherclauses = lappend(otherclauses, rinfo);
    4235                 :           0 :                         clauses = foreach_delete_current(clauses, lc);
    4236                 :           0 :                         continue;
    4237                 :             :                     }
    4238                 :             : 
    4239                 :          25 :                     group_relid = relid;
    4240                 :          25 :                     group_rel = root->simple_rel_array[relid];
    4241                 :             :                 }
    4242         [ -  + ]:          25 :                 else if (group_relid != relid)
    4243                 :             :                 {
    4244                 :             :                     /*
    4245                 :             :                      * Being in the group forming state we don't need other
    4246                 :             :                      * clauses.
    4247                 :             :                      */
    4248                 :           0 :                     continue;
    4249                 :             :                 }
    4250                 :             : 
    4251                 :             :                 /*
    4252                 :             :                  * We're going to add the new clause to the varinfos list.  We
    4253                 :             :                  * might re-use add_unique_group_var(), but we don't do so for
    4254                 :             :                  * two reasons.
    4255                 :             :                  *
    4256                 :             :                  * 1) We must keep the origin_rinfos list ordered exactly the
    4257                 :             :                  * same way as varinfos.
    4258                 :             :                  *
    4259                 :             :                  * 2) add_unique_group_var() is designed for
    4260                 :             :                  * estimate_num_groups(), where a larger number of groups is
    4261                 :             :                  * worse.   While estimating the number of hash buckets, we
    4262                 :             :                  * have the opposite: a lesser number of groups is worse.
    4263                 :             :                  * Therefore, we don't have to remove "known equal" vars: the
    4264                 :             :                  * removed var may valuably contribute to the multivariate
    4265                 :             :                  * statistics to grow the number of groups.
    4266                 :             :                  */
    4267                 :             : 
    4268                 :             :                 /*
    4269                 :             :                  * Clear nullingrels to correctly match hash keys.  See
    4270                 :             :                  * add_unique_group_var()'s comment for details.
    4271                 :             :                  */
    4272                 :          50 :                 expr = remove_nulling_relids(expr, root->outer_join_rels, NULL);
    4273                 :             : 
    4274                 :             :                 /*
    4275                 :             :                  * Detect and exclude exact duplicates from the list of hash
    4276                 :             :                  * keys (like add_unique_group_var does).
    4277                 :             :                  */
    4278   [ +  +  +  +  :          70 :                 foreach(lc1, varinfos)
                   +  + ]
    4279                 :             :                 {
    4280                 :          30 :                     varinfo = (GroupVarInfo *) lfirst(lc1);
    4281                 :             : 
    4282         [ +  + ]:          30 :                     if (!equal(expr, varinfo->var))
    4283                 :          20 :                         continue;
    4284                 :             : 
    4285                 :          10 :                     is_duplicate = true;
    4286                 :          10 :                     break;
    4287                 :             :                 }
    4288                 :             : 
    4289         [ +  + ]:          50 :                 if (is_duplicate)
    4290                 :             :                 {
    4291                 :             :                     /*
    4292                 :             :                      * Skip exact duplicates. Adding them to the otherclauses
    4293                 :             :                      * list also doesn't make sense.
    4294                 :             :                      */
    4295                 :          10 :                     continue;
    4296                 :             :                 }
    4297                 :             : 
    4298                 :             :                 /*
    4299                 :             :                  * Initialize GroupVarInfo.  We only use it to call
    4300                 :             :                  * estimate_multivariate_ndistinct(), which doesn't care about
    4301                 :             :                  * ndistinct and isdefault fields.  Thus, skip these fields.
    4302                 :             :                  */
    4303                 :          40 :                 varinfo = palloc0_object(GroupVarInfo);
    4304                 :          40 :                 varinfo->var = expr;
    4305                 :          40 :                 varinfo->rel = root->simple_rel_array[relid];
    4306                 :          40 :                 varinfos = lappend(varinfos, varinfo);
    4307                 :             : 
    4308                 :             :                 /*
    4309                 :             :                  * Remember the link to RestrictInfo for the case the clause
    4310                 :             :                  * is failed to be estimated.
    4311                 :             :                  */
    4312                 :          40 :                 origin_rinfos = lappend(origin_rinfos, rinfo);
    4313                 :             :             }
    4314                 :             :             else
    4315                 :             :             {
    4316                 :             :                 /* This clause can't be estimated with extended statistics */
    4317                 :       55571 :                 otherclauses = lappend(otherclauses, rinfo);
    4318                 :             :             }
    4319                 :             : 
    4320                 :       55611 :             clauses = foreach_delete_current(clauses, lc);
    4321                 :             :         }
    4322                 :             : 
    4323         [ +  + ]:       26791 :         if (list_length(varinfos) < 2)
    4324                 :             :         {
    4325                 :             :             /*
    4326                 :             :              * Multivariate statistics doesn't apply to single columns except
    4327                 :             :              * for expressions, but it has not been implemented yet.
    4328                 :             :              */
    4329                 :       26781 :             otherclauses = list_concat(otherclauses, origin_rinfos);
    4330                 :       26781 :             list_free_deep(varinfos);
    4331                 :       26781 :             list_free(origin_rinfos);
    4332                 :       26781 :             continue;
    4333                 :             :         }
    4334                 :             : 
    4335                 :             :         Assert(group_rel != NULL);
    4336                 :             : 
    4337                 :             :         /* Employ the extended statistics. */
    4338                 :          10 :         origin_varinfos = varinfos;
    4339                 :             :         for (;;)
    4340                 :          10 :         {
    4341                 :          20 :             bool        estimated = estimate_multivariate_ndistinct(root,
    4342                 :             :                                                                     group_rel,
    4343                 :             :                                                                     &varinfos,
    4344                 :             :                                                                     &mvndistinct);
    4345                 :             : 
    4346         [ +  + ]:          20 :             if (!estimated)
    4347                 :          10 :                 break;
    4348                 :             : 
    4349                 :             :             /*
    4350                 :             :              * We've got an estimation.  Use ndistinct value in a consistent
    4351                 :             :              * way - according to the caller's logic (see
    4352                 :             :              * final_cost_hashjoin).
    4353                 :             :              */
    4354         [ +  - ]:          10 :             if (ndistinct < mvndistinct)
    4355                 :          10 :                 ndistinct = mvndistinct;
    4356                 :             :             Assert(ndistinct >= 1.0);
    4357                 :             :         }
    4358                 :             : 
    4359                 :             :         Assert(list_length(origin_varinfos) == list_length(origin_rinfos));
    4360                 :             : 
    4361                 :             :         /* Collect unmatched clauses as otherclauses. */
    4362   [ +  -  +  +  :          35 :         forboth(lc1, origin_varinfos, lc2, origin_rinfos)
          +  -  +  +  +  
             +  +  -  +  
                      + ]
    4363                 :             :         {
    4364                 :          25 :             GroupVarInfo *vinfo = lfirst(lc1);
    4365                 :             : 
    4366         [ +  - ]:          25 :             if (!list_member_ptr(varinfos, vinfo))
    4367                 :             :                 /* Already estimated */
    4368                 :          25 :                 continue;
    4369                 :             : 
    4370                 :             :             /* Can't be estimated here - push to the returning list */
    4371                 :           0 :             otherclauses = lappend(otherclauses, lfirst(lc2));
    4372                 :             :         }
    4373                 :             :     }
    4374                 :             : 
    4375                 :       26781 :     *innerbucketsize = 1.0 / ndistinct;
    4376                 :       26781 :     return otherclauses;
    4377                 :             : }
    4378                 :             : 
    4379                 :             : /*
    4380                 :             :  * Estimate hash bucket statistics when the specified expression is used
    4381                 :             :  * as a hash key for the given number of buckets.
    4382                 :             :  *
    4383                 :             :  * This attempts to determine two values:
    4384                 :             :  *
    4385                 :             :  * 1. The frequency of the most common value of the expression (returns
    4386                 :             :  * zero into *mcv_freq if we can't get that).  This will be frequency
    4387                 :             :  * relative to the entire underlying table.
    4388                 :             :  *
    4389                 :             :  * 2. The "bucketsize fraction", ie, average number of entries in a bucket
    4390                 :             :  * divided by total number of tuples to be hashed.
    4391                 :             :  *
    4392                 :             :  * XXX This is really pretty bogus since we're effectively assuming that the
    4393                 :             :  * distribution of hash keys will be the same after applying restriction
    4394                 :             :  * clauses as it was in the underlying relation.  However, we are not nearly
    4395                 :             :  * smart enough to figure out how the restrict clauses might change the
    4396                 :             :  * distribution, so this will have to do for now.
    4397                 :             :  *
    4398                 :             :  * We are passed the number of buckets the executor will use for the given
    4399                 :             :  * input relation.  If the data were perfectly distributed, with the same
    4400                 :             :  * number of tuples going into each available bucket, then the bucketsize
    4401                 :             :  * fraction would be 1/nbuckets.  But this happy state of affairs will occur
    4402                 :             :  * only if (a) there are at least nbuckets distinct data values, and (b)
    4403                 :             :  * we have a not-too-skewed data distribution.  Otherwise the buckets will
    4404                 :             :  * be nonuniformly occupied.  If the other relation in the join has a key
    4405                 :             :  * distribution similar to this one's, then the most-loaded buckets are
    4406                 :             :  * exactly those that will be probed most often.  Therefore, the "average"
    4407                 :             :  * bucket size for costing purposes should really be taken as something close
    4408                 :             :  * to the "worst case" bucket size.  We try to estimate this by adjusting the
    4409                 :             :  * fraction if there are too few distinct data values, and then clamping to
    4410                 :             :  * at least the bucket size implied by the most common value's frequency.
    4411                 :             :  *
    4412                 :             :  * If no statistics are available, use a default estimate of 0.1.  This will
    4413                 :             :  * discourage use of a hash rather strongly if the inner relation is large,
    4414                 :             :  * which is what we want.  We do not want to hash unless we know that the
    4415                 :             :  * inner rel is well-dispersed (or the alternatives seem much worse).
    4416                 :             :  *
    4417                 :             :  * The caller should also check that the mcv_freq is not so large that the
    4418                 :             :  * most common value would by itself require an impractically large bucket.
    4419                 :             :  * In a hash join, the executor can split buckets if they get too big, but
    4420                 :             :  * obviously that doesn't help for a bucket that contains many duplicates of
    4421                 :             :  * the same value.
    4422                 :             :  */
    4423                 :             : void
    4424                 :      149999 : estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets,
    4425                 :             :                            Selectivity *mcv_freq,
    4426                 :             :                            Selectivity *bucketsize_frac)
    4427                 :             : {
    4428                 :             :     VariableStatData vardata;
    4429                 :             :     double      estfract,
    4430                 :             :                 ndistinct;
    4431                 :             :     bool        isdefault;
    4432                 :             :     AttStatsSlot sslot;
    4433                 :             : 
    4434                 :      149999 :     examine_variable(root, hashkey, 0, &vardata);
    4435                 :             : 
    4436                 :             :     /* Initialize *mcv_freq to "unknown" */
    4437                 :      149999 :     *mcv_freq = 0.0;
    4438                 :             : 
    4439                 :             :     /* Look up the frequency of the most common value, if available */
    4440         [ +  + ]:      149999 :     if (HeapTupleIsValid(vardata.statsTuple))
    4441                 :             :     {
    4442         [ +  + ]:       97068 :         if (get_attstatsslot(&sslot, vardata.statsTuple,
    4443                 :             :                              STATISTIC_KIND_MCV, InvalidOid,
    4444                 :             :                              ATTSTATSSLOT_NUMBERS))
    4445                 :             :         {
    4446                 :             :             /*
    4447                 :             :              * The first MCV stat is for the most common value.
    4448                 :             :              */
    4449         [ +  - ]:       57944 :             if (sslot.nnumbers > 0)
    4450                 :       57944 :                 *mcv_freq = sslot.numbers[0];
    4451                 :       57944 :             free_attstatsslot(&sslot);
    4452                 :             :         }
    4453         [ +  + ]:       39124 :         else if (get_attstatsslot(&sslot, vardata.statsTuple,
    4454                 :             :                                   STATISTIC_KIND_HISTOGRAM, InvalidOid,
    4455                 :             :                                   0))
    4456                 :             :         {
    4457                 :             :             /*
    4458                 :             :              * If there are no recorded MCVs, but we do have a histogram, then
    4459                 :             :              * assume that ANALYZE determined that the column is unique.
    4460                 :             :              */
    4461   [ +  -  +  + ]:       37692 :             if (vardata.rel && vardata.rel->tuples > 0)
    4462                 :       37677 :                 *mcv_freq = 1.0 / vardata.rel->tuples;
    4463                 :             :         }
    4464                 :             :     }
    4465                 :             : 
    4466                 :             :     /* Get number of distinct values */
    4467                 :      149999 :     ndistinct = get_variable_numdistinct(&vardata, &isdefault);
    4468                 :             : 
    4469                 :             :     /*
    4470                 :             :      * If ndistinct isn't real, punt.  We normally return 0.1, but if the
    4471                 :             :      * mcv_freq is known to be even higher than that, use it instead.
    4472                 :             :      */
    4473         [ +  + ]:      149999 :     if (isdefault)
    4474                 :             :     {
    4475         [ +  - ]:       24787 :         *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
    4476         [ +  + ]:       24787 :         ReleaseVariableStats(vardata);
    4477                 :       24787 :         return;
    4478                 :             :     }
    4479                 :             : 
    4480                 :             :     /*
    4481                 :             :      * Adjust ndistinct to account for restriction clauses.  Observe we are
    4482                 :             :      * assuming that the data distribution is affected uniformly by the
    4483                 :             :      * restriction clauses!
    4484                 :             :      *
    4485                 :             :      * XXX Possibly better way, but much more expensive: multiply by
    4486                 :             :      * selectivity of rel's restriction clauses that mention the target Var.
    4487                 :             :      */
    4488   [ +  -  +  + ]:      125212 :     if (vardata.rel && vardata.rel->tuples > 0)
    4489                 :             :     {
    4490                 :      125181 :         ndistinct *= vardata.rel->rows / vardata.rel->tuples;
    4491                 :      125181 :         ndistinct = clamp_row_est(ndistinct);
    4492                 :             :     }
    4493                 :             : 
    4494                 :             :     /*
    4495                 :             :      * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
    4496                 :             :      * number of buckets is less than the expected number of distinct values;
    4497                 :             :      * otherwise it is 1/ndistinct.
    4498                 :             :      */
    4499         [ +  + ]:      125212 :     if (ndistinct > nbuckets)
    4500                 :          94 :         estfract = 1.0 / nbuckets;
    4501                 :             :     else
    4502                 :      125118 :         estfract = 1.0 / ndistinct;
    4503                 :             : 
    4504                 :             :     /*
    4505                 :             :      * Clamp the bucketsize fraction to be not less than the MCV frequency,
    4506                 :             :      * since whichever bucket the MCV values end up in will have at least that
    4507                 :             :      * size.  This has no effect if *mcv_freq is still zero.
    4508                 :             :      */
    4509         [ +  + ]:      125212 :     estfract = Max(estfract, *mcv_freq);
    4510                 :             : 
    4511                 :      125212 :     *bucketsize_frac = (Selectivity) estfract;
    4512                 :             : 
    4513         [ +  + ]:      125212 :     ReleaseVariableStats(vardata);
    4514                 :             : }
    4515                 :             : 
    4516                 :             : /*
    4517                 :             :  * estimate_hashagg_tablesize
    4518                 :             :  *    estimate the number of bytes that a hash aggregate hashtable will
    4519                 :             :  *    require based on the agg_costs, path width and number of groups.
    4520                 :             :  *
    4521                 :             :  * We return the result as "double" to forestall any possible overflow
    4522                 :             :  * problem in the multiplication by dNumGroups.
    4523                 :             :  *
    4524                 :             :  * XXX this may be over-estimating the size now that hashagg knows to omit
    4525                 :             :  * unneeded columns from the hashtable.  Also for mixed-mode grouping sets,
    4526                 :             :  * grouping columns not in the hashed set are counted here even though hashagg
    4527                 :             :  * won't store them.  Is this a problem?
    4528                 :             :  */
    4529                 :             : double
    4530                 :        2424 : estimate_hashagg_tablesize(PlannerInfo *root, Path *path,
    4531                 :             :                            const AggClauseCosts *agg_costs, double dNumGroups)
    4532                 :             : {
    4533                 :             :     Size        hashentrysize;
    4534                 :             : 
    4535                 :        2424 :     hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
    4536                 :        2424 :                                         path->pathtarget->width,
    4537                 :        2424 :                                         agg_costs->transitionSpace);
    4538                 :             : 
    4539                 :             :     /*
    4540                 :             :      * Note that this disregards the effect of fill-factor and growth policy
    4541                 :             :      * of the hash table.  That's probably ok, given that the default
    4542                 :             :      * fill-factor is relatively high.  It'd be hard to meaningfully factor in
    4543                 :             :      * "double-in-size" growth policies here.
    4544                 :             :      */
    4545                 :        2424 :     return hashentrysize * dNumGroups;
    4546                 :             : }
    4547                 :             : 
    4548                 :             : 
    4549                 :             : /*-------------------------------------------------------------------------
    4550                 :             :  *
    4551                 :             :  * Support routines
    4552                 :             :  *
    4553                 :             :  *-------------------------------------------------------------------------
    4554                 :             :  */
    4555                 :             : 
    4556                 :             : /*
    4557                 :             :  * Find the best matching ndistinct extended statistics for the given list of
    4558                 :             :  * GroupVarInfos.
    4559                 :             :  *
    4560                 :             :  * Callers must ensure that the given GroupVarInfos all belong to 'rel' and
    4561                 :             :  * the GroupVarInfos list does not contain any duplicate Vars or expressions.
    4562                 :             :  *
    4563                 :             :  * When statistics are found that match > 1 of the given GroupVarInfo, the
    4564                 :             :  * *ndistinct parameter is set according to the ndistinct estimate and a new
    4565                 :             :  * list is built with the matching GroupVarInfos removed, which is output via
    4566                 :             :  * the *varinfos parameter before returning true.  When no matching stats are
    4567                 :             :  * found, false is returned and the *varinfos and *ndistinct parameters are
    4568                 :             :  * left untouched.
    4569                 :             :  */
    4570                 :             : static bool
    4571                 :      237648 : estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel,
    4572                 :             :                                 List **varinfos, double *ndistinct)
    4573                 :             : {
    4574                 :             :     ListCell   *lc;
    4575                 :             :     int         nmatches_vars;
    4576                 :             :     int         nmatches_exprs;
    4577                 :      237648 :     Oid         statOid = InvalidOid;
    4578                 :             :     MVNDistinct *stats;
    4579                 :      237648 :     StatisticExtInfo *matched_info = NULL;
    4580         [ +  - ]:      237648 :     RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
    4581                 :             : 
    4582                 :             :     /* bail out immediately if the table has no extended statistics */
    4583         [ +  + ]:      237648 :     if (!rel->statlist)
    4584                 :      237177 :         return false;
    4585                 :             : 
    4586                 :             :     /* look for the ndistinct statistics object matching the most vars */
    4587                 :         471 :     nmatches_vars = 0;          /* we require at least two matches */
    4588                 :         471 :     nmatches_exprs = 0;
    4589   [ +  -  +  +  :        1875 :     foreach(lc, rel->statlist)
                   +  + ]
    4590                 :             :     {
    4591                 :             :         ListCell   *lc2;
    4592                 :        1404 :         StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
    4593                 :        1404 :         int         nshared_vars = 0;
    4594                 :        1404 :         int         nshared_exprs = 0;
    4595                 :             : 
    4596                 :             :         /* skip statistics of other kinds */
    4597         [ +  + ]:        1404 :         if (info->kind != STATS_EXT_NDISTINCT)
    4598                 :         663 :             continue;
    4599                 :             : 
    4600                 :             :         /* skip statistics with mismatching stxdinherit value */
    4601         [ +  + ]:         741 :         if (info->inherit != rte->inh)
    4602                 :          25 :             continue;
    4603                 :             : 
    4604                 :             :         /*
    4605                 :             :          * Determine how many expressions (and variables in non-matched
    4606                 :             :          * expressions) match. We'll then use these numbers to pick the
    4607                 :             :          * statistics object that best matches the clauses.
    4608                 :             :          */
    4609   [ +  +  +  +  :        2267 :         foreach(lc2, *varinfos)
                   +  + ]
    4610                 :             :         {
    4611                 :             :             ListCell   *lc3;
    4612                 :        1551 :             GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
    4613                 :             :             AttrNumber  attnum;
    4614                 :             : 
    4615                 :             :             Assert(varinfo->rel == rel);
    4616                 :             : 
    4617                 :             :             /* simple Var, search in statistics keys directly */
    4618         [ +  + ]:        1551 :             if (IsA(varinfo->var, Var))
    4619                 :             :             {
    4620                 :        1246 :                 attnum = ((Var *) varinfo->var)->varattno;
    4621                 :             : 
    4622                 :             :                 /*
    4623                 :             :                  * Ignore system attributes - we don't support statistics on
    4624                 :             :                  * them, so can't match them (and it'd fail as the values are
    4625                 :             :                  * negative).
    4626                 :             :                  */
    4627         [ +  + ]:        1246 :                 if (!AttrNumberIsForUserDefinedAttr(attnum))
    4628                 :          10 :                     continue;
    4629                 :             : 
    4630         [ +  + ]:        1236 :                 if (bms_is_member(attnum, info->keys))
    4631                 :         730 :                     nshared_vars++;
    4632                 :             : 
    4633                 :        1236 :                 continue;
    4634                 :             :             }
    4635                 :             : 
    4636                 :             :             /* expression - see if it's in the statistics object */
    4637   [ +  +  +  +  :         550 :             foreach(lc3, info->exprs)
                   +  + ]
    4638                 :             :             {
    4639                 :         440 :                 Node       *expr = (Node *) lfirst(lc3);
    4640                 :             : 
    4641         [ +  + ]:         440 :                 if (equal(varinfo->var, expr))
    4642                 :             :                 {
    4643                 :         195 :                     nshared_exprs++;
    4644                 :         195 :                     break;
    4645                 :             :                 }
    4646                 :             :             }
    4647                 :             :         }
    4648                 :             : 
    4649                 :             :         /*
    4650                 :             :          * The ndistinct extended statistics contain estimates for a minimum
    4651                 :             :          * of pairs of columns which the statistics are defined on and
    4652                 :             :          * certainly not single columns.  Here we skip unless we managed to
    4653                 :             :          * match to at least two columns.
    4654                 :             :          */
    4655         [ +  + ]:         716 :         if (nshared_vars + nshared_exprs < 2)
    4656                 :         331 :             continue;
    4657                 :             : 
    4658                 :             :         /*
    4659                 :             :          * Check if these statistics are a better match than the previous best
    4660                 :             :          * match and if so, take note of the StatisticExtInfo.
    4661                 :             :          *
    4662                 :             :          * The statslist is sorted by statOid, so the StatisticExtInfo we
    4663                 :             :          * select as the best match is deterministic even when multiple sets
    4664                 :             :          * of statistics match equally as well.
    4665                 :             :          */
    4666   [ +  +  +  - ]:         385 :         if ((nshared_exprs > nmatches_exprs) ||
    4667         [ +  + ]:         295 :             (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
    4668                 :             :         {
    4669                 :         365 :             statOid = info->statOid;
    4670                 :         365 :             nmatches_vars = nshared_vars;
    4671                 :         365 :             nmatches_exprs = nshared_exprs;
    4672                 :         365 :             matched_info = info;
    4673                 :             :         }
    4674                 :             :     }
    4675                 :             : 
    4676                 :             :     /* No match? */
    4677         [ +  + ]:         471 :     if (statOid == InvalidOid)
    4678                 :         116 :         return false;
    4679                 :             : 
    4680                 :             :     Assert(nmatches_vars + nmatches_exprs > 1);
    4681                 :             : 
    4682                 :         355 :     stats = statext_ndistinct_load(statOid, rte->inh);
    4683                 :             : 
    4684                 :             :     /*
    4685                 :             :      * If we have a match, search it for the specific item that matches (there
    4686                 :             :      * must be one), and construct the output values.
    4687                 :             :      */
    4688         [ +  - ]:         355 :     if (stats)
    4689                 :             :     {
    4690                 :             :         int         i;
    4691                 :         355 :         List       *newlist = NIL;
    4692                 :         355 :         MVNDistinctItem *item = NULL;
    4693                 :             :         ListCell   *lc2;
    4694                 :         355 :         Bitmapset  *matched = NULL;
    4695                 :             :         AttrNumber  attnum_offset;
    4696                 :             : 
    4697                 :             :         /*
    4698                 :             :          * How much we need to offset the attnums? If there are no
    4699                 :             :          * expressions, no offset is needed. Otherwise offset enough to move
    4700                 :             :          * the lowest one (which is equal to number of expressions) to 1.
    4701                 :             :          */
    4702         [ +  + ]:         355 :         if (matched_info->exprs)
    4703                 :         125 :             attnum_offset = (list_length(matched_info->exprs) + 1);
    4704                 :             :         else
    4705                 :         230 :             attnum_offset = 0;
    4706                 :             : 
    4707                 :             :         /* see what actually matched */
    4708   [ +  -  +  +  :        1240 :         foreach(lc2, *varinfos)
                   +  + ]
    4709                 :             :         {
    4710                 :             :             ListCell   *lc3;
    4711                 :             :             int         idx;
    4712                 :         885 :             bool        found = false;
    4713                 :             : 
    4714                 :         885 :             GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
    4715                 :             : 
    4716                 :             :             /*
    4717                 :             :              * Process a simple Var expression, by matching it to keys
    4718                 :             :              * directly. If there's a matching expression, we'll try matching
    4719                 :             :              * it later.
    4720                 :             :              */
    4721         [ +  + ]:         885 :             if (IsA(varinfo->var, Var))
    4722                 :             :             {
    4723                 :         730 :                 AttrNumber  attnum = ((Var *) varinfo->var)->varattno;
    4724                 :             : 
    4725                 :             :                 /*
    4726                 :             :                  * Ignore expressions on system attributes. Can't rely on the
    4727                 :             :                  * bms check for negative values.
    4728                 :             :                  */
    4729         [ +  + ]:         730 :                 if (!AttrNumberIsForUserDefinedAttr(attnum))
    4730                 :           5 :                     continue;
    4731                 :             : 
    4732                 :             :                 /* Is the variable covered by the statistics object? */
    4733         [ +  + ]:         725 :                 if (!bms_is_member(attnum, matched_info->keys))
    4734                 :         100 :                     continue;
    4735                 :             : 
    4736                 :         625 :                 attnum = attnum + attnum_offset;
    4737                 :             : 
    4738                 :             :                 /* ensure sufficient offset */
    4739                 :             :                 Assert(AttrNumberIsForUserDefinedAttr(attnum));
    4740                 :             : 
    4741                 :         625 :                 matched = bms_add_member(matched, attnum);
    4742                 :             : 
    4743                 :         625 :                 found = true;
    4744                 :             :             }
    4745                 :             : 
    4746                 :             :             /*
    4747                 :             :              * XXX Maybe we should allow searching the expressions even if we
    4748                 :             :              * found an attribute matching the expression? That would handle
    4749                 :             :              * trivial expressions like "(a)" but it seems fairly useless.
    4750                 :             :              */
    4751         [ +  + ]:         780 :             if (found)
    4752                 :         625 :                 continue;
    4753                 :             : 
    4754                 :             :             /* expression - see if it's in the statistics object */
    4755                 :         155 :             idx = 0;
    4756   [ +  +  +  +  :         255 :             foreach(lc3, matched_info->exprs)
                   +  + ]
    4757                 :             :             {
    4758                 :         230 :                 Node       *expr = (Node *) lfirst(lc3);
    4759                 :             : 
    4760         [ +  + ]:         230 :                 if (equal(varinfo->var, expr))
    4761                 :             :                 {
    4762                 :         130 :                     AttrNumber  attnum = -(idx + 1);
    4763                 :             : 
    4764                 :         130 :                     attnum = attnum + attnum_offset;
    4765                 :             : 
    4766                 :             :                     /* ensure sufficient offset */
    4767                 :             :                     Assert(AttrNumberIsForUserDefinedAttr(attnum));
    4768                 :             : 
    4769                 :         130 :                     matched = bms_add_member(matched, attnum);
    4770                 :             : 
    4771                 :             :                     /* there should be just one matching expression */
    4772                 :         130 :                     break;
    4773                 :             :                 }
    4774                 :             : 
    4775                 :         100 :                 idx++;
    4776                 :             :             }
    4777                 :             :         }
    4778                 :             : 
    4779                 :             :         /* Find the specific item that exactly matches the combination */
    4780         [ +  - ]:         720 :         for (i = 0; i < stats->nitems; i++)
    4781                 :             :         {
    4782                 :             :             int         j;
    4783                 :         720 :             MVNDistinctItem *tmpitem = &stats->items[i];
    4784                 :             : 
    4785         [ +  + ]:         720 :             if (tmpitem->nattributes != bms_num_members(matched))
    4786                 :         135 :                 continue;
    4787                 :             : 
    4788                 :             :             /* assume it's the right item */
    4789                 :         585 :             item = tmpitem;
    4790                 :             : 
    4791                 :             :             /* check that all item attributes/expressions fit the match */
    4792         [ +  + ]:        1410 :             for (j = 0; j < tmpitem->nattributes; j++)
    4793                 :             :             {
    4794                 :        1055 :                 AttrNumber  attnum = tmpitem->attributes[j];
    4795                 :             : 
    4796                 :             :                 /*
    4797                 :             :                  * Thanks to how we constructed the matched bitmap above, we
    4798                 :             :                  * can just offset all attnums the same way.
    4799                 :             :                  */
    4800                 :        1055 :                 attnum = attnum + attnum_offset;
    4801                 :             : 
    4802         [ +  + ]:        1055 :                 if (!bms_is_member(attnum, matched))
    4803                 :             :                 {
    4804                 :             :                     /* nah, it's not this item */
    4805                 :         230 :                     item = NULL;
    4806                 :         230 :                     break;
    4807                 :             :                 }
    4808                 :             :             }
    4809                 :             : 
    4810                 :             :             /*
    4811                 :             :              * If the item has all the matched attributes, we know it's the
    4812                 :             :              * right one - there can't be a better one. matching more.
    4813                 :             :              */
    4814         [ +  + ]:         585 :             if (item)
    4815                 :         355 :                 break;
    4816                 :             :         }
    4817                 :             : 
    4818                 :             :         /*
    4819                 :             :          * Make sure we found an item. There has to be one, because ndistinct
    4820                 :             :          * statistics includes all combinations of attributes.
    4821                 :             :          */
    4822         [ -  + ]:         355 :         if (!item)
    4823         [ #  # ]:           0 :             elog(ERROR, "corrupt MVNDistinct entry");
    4824                 :             : 
    4825                 :             :         /* Form the output varinfo list, keeping only unmatched ones */
    4826   [ +  -  +  +  :        1240 :         foreach(lc, *varinfos)
                   +  + ]
    4827                 :             :         {
    4828                 :         885 :             GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
    4829                 :             :             ListCell   *lc3;
    4830                 :         885 :             bool        found = false;
    4831                 :             : 
    4832                 :             :             /*
    4833                 :             :              * Let's look at plain variables first, because it's the most
    4834                 :             :              * common case and the check is quite cheap. We can simply get the
    4835                 :             :              * attnum and check (with an offset) matched bitmap.
    4836                 :             :              */
    4837         [ +  + ]:         885 :             if (IsA(varinfo->var, Var))
    4838                 :         725 :             {
    4839                 :         730 :                 AttrNumber  attnum = ((Var *) varinfo->var)->varattno;
    4840                 :             : 
    4841                 :             :                 /*
    4842                 :             :                  * If it's a system attribute, we're done. We don't support
    4843                 :             :                  * extended statistics on system attributes, so it's clearly
    4844                 :             :                  * not matched. Just keep the expression and continue.
    4845                 :             :                  */
    4846         [ +  + ]:         730 :                 if (!AttrNumberIsForUserDefinedAttr(attnum))
    4847                 :             :                 {
    4848                 :           5 :                     newlist = lappend(newlist, varinfo);
    4849                 :           5 :                     continue;
    4850                 :             :                 }
    4851                 :             : 
    4852                 :             :                 /* apply the same offset as above */
    4853                 :         725 :                 attnum += attnum_offset;
    4854                 :             : 
    4855                 :             :                 /* if it's not matched, keep the varinfo */
    4856         [ +  + ]:         725 :                 if (!bms_is_member(attnum, matched))
    4857                 :         100 :                     newlist = lappend(newlist, varinfo);
    4858                 :             : 
    4859                 :             :                 /* The rest of the loop deals with complex expressions. */
    4860                 :         725 :                 continue;
    4861                 :             :             }
    4862                 :             : 
    4863                 :             :             /*
    4864                 :             :              * Process complex expressions, not just simple Vars.
    4865                 :             :              *
    4866                 :             :              * First, we search for an exact match of an expression. If we
    4867                 :             :              * find one, we can just discard the whole GroupVarInfo, with all
    4868                 :             :              * the variables we extracted from it.
    4869                 :             :              *
    4870                 :             :              * Otherwise we inspect the individual vars, and try matching it
    4871                 :             :              * to variables in the item.
    4872                 :             :              */
    4873   [ +  +  +  +  :         255 :             foreach(lc3, matched_info->exprs)
                   +  + ]
    4874                 :             :             {
    4875                 :         230 :                 Node       *expr = (Node *) lfirst(lc3);
    4876                 :             : 
    4877         [ +  + ]:         230 :                 if (equal(varinfo->var, expr))
    4878                 :             :                 {
    4879                 :         130 :                     found = true;
    4880                 :         130 :                     break;
    4881                 :             :                 }
    4882                 :             :             }
    4883                 :             : 
    4884                 :             :             /* found exact match, skip */
    4885         [ +  + ]:         155 :             if (found)
    4886                 :         130 :                 continue;
    4887                 :             : 
    4888                 :          25 :             newlist = lappend(newlist, varinfo);
    4889                 :             :         }
    4890                 :             : 
    4891                 :         355 :         *varinfos = newlist;
    4892                 :         355 :         *ndistinct = item->ndistinct;
    4893                 :         355 :         return true;
    4894                 :             :     }
    4895                 :             : 
    4896                 :           0 :     return false;
    4897                 :             : }
    4898                 :             : 
    4899                 :             : /*
    4900                 :             :  * convert_to_scalar
    4901                 :             :  *    Convert non-NULL values of the indicated types to the comparison
    4902                 :             :  *    scale needed by scalarineqsel().
    4903                 :             :  *    Returns "true" if successful.
    4904                 :             :  *
    4905                 :             :  * XXX this routine is a hack: ideally we should look up the conversion
    4906                 :             :  * subroutines in pg_type.
    4907                 :             :  *
    4908                 :             :  * All numeric datatypes are simply converted to their equivalent
    4909                 :             :  * "double" values.  (NUMERIC values that are outside the range of "double"
    4910                 :             :  * are clamped to +/- HUGE_VAL.)
    4911                 :             :  *
    4912                 :             :  * String datatypes are converted by convert_string_to_scalar(),
    4913                 :             :  * which is explained below.  The reason why this routine deals with
    4914                 :             :  * three values at a time, not just one, is that we need it for strings.
    4915                 :             :  *
    4916                 :             :  * The bytea datatype is just enough different from strings that it has
    4917                 :             :  * to be treated separately.
    4918                 :             :  *
    4919                 :             :  * The several datatypes representing absolute times are all converted
    4920                 :             :  * to Timestamp, which is actually an int64, and then we promote that to
    4921                 :             :  * a double.  Note this will give correct results even for the "special"
    4922                 :             :  * values of Timestamp, since those are chosen to compare correctly;
    4923                 :             :  * see timestamp_cmp.
    4924                 :             :  *
    4925                 :             :  * The several datatypes representing relative times (intervals) are all
    4926                 :             :  * converted to measurements expressed in seconds.
    4927                 :             :  */
    4928                 :             : static bool
    4929                 :       53108 : convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue,
    4930                 :             :                   Datum lobound, Datum hibound, Oid boundstypid,
    4931                 :             :                   double *scaledlobound, double *scaledhibound)
    4932                 :             : {
    4933                 :       53108 :     bool        failure = false;
    4934                 :             : 
    4935                 :             :     /*
    4936                 :             :      * Both the valuetypid and the boundstypid should exactly match the
    4937                 :             :      * declared input type(s) of the operator we are invoked for.  However,
    4938                 :             :      * extensions might try to use scalarineqsel as estimator for operators
    4939                 :             :      * with input type(s) we don't handle here; in such cases, we want to
    4940                 :             :      * return false, not fail.  In any case, we mustn't assume that valuetypid
    4941                 :             :      * and boundstypid are identical.
    4942                 :             :      *
    4943                 :             :      * XXX The histogram we are interpolating between points of could belong
    4944                 :             :      * to a column that's only binary-compatible with the declared type. In
    4945                 :             :      * essence we are assuming that the semantics of binary-compatible types
    4946                 :             :      * are enough alike that we can use a histogram generated with one type's
    4947                 :             :      * operators to estimate selectivity for the other's.  This is outright
    4948                 :             :      * wrong in some cases --- in particular signed versus unsigned
    4949                 :             :      * interpretation could trip us up.  But it's useful enough in the
    4950                 :             :      * majority of cases that we do it anyway.  Should think about more
    4951                 :             :      * rigorous ways to do it.
    4952                 :             :      */
    4953   [ +  +  -  -  :       53108 :     switch (valuetypid)
                   -  - ]
    4954                 :             :     {
    4955                 :             :             /*
    4956                 :             :              * Built-in numeric types
    4957                 :             :              */
    4958                 :       48306 :         case BOOLOID:
    4959                 :             :         case INT2OID:
    4960                 :             :         case INT4OID:
    4961                 :             :         case INT8OID:
    4962                 :             :         case FLOAT4OID:
    4963                 :             :         case FLOAT8OID:
    4964                 :             :         case NUMERICOID:
    4965                 :             :         case OIDOID:
    4966                 :             :         case REGPROCOID:
    4967                 :             :         case REGPROCEDUREOID:
    4968                 :             :         case REGOPEROID:
    4969                 :             :         case REGOPERATOROID:
    4970                 :             :         case REGCLASSOID:
    4971                 :             :         case REGTYPEOID:
    4972                 :             :         case REGCOLLATIONOID:
    4973                 :             :         case REGCONFIGOID:
    4974                 :             :         case REGDICTIONARYOID:
    4975                 :             :         case REGROLEOID:
    4976                 :             :         case REGNAMESPACEOID:
    4977                 :             :         case REGDATABASEOID:
    4978                 :       48306 :             *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
    4979                 :             :                                                      &failure);
    4980                 :       48306 :             *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
    4981                 :             :                                                        &failure);
    4982                 :       48306 :             *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
    4983                 :             :                                                        &failure);
    4984                 :       48306 :             return !failure;
    4985                 :             : 
    4986                 :             :             /*
    4987                 :             :              * Built-in string types
    4988                 :             :              */
    4989                 :        4802 :         case CHAROID:
    4990                 :             :         case BPCHAROID:
    4991                 :             :         case VARCHAROID:
    4992                 :             :         case TEXTOID:
    4993                 :             :         case NAMEOID:
    4994                 :             :             {
    4995                 :        4802 :                 char       *valstr = convert_string_datum(value, valuetypid,
    4996                 :             :                                                           collid, &failure);
    4997                 :        4802 :                 char       *lostr = convert_string_datum(lobound, boundstypid,
    4998                 :             :                                                          collid, &failure);
    4999                 :        4802 :                 char       *histr = convert_string_datum(hibound, boundstypid,
    5000                 :             :                                                          collid, &failure);
    5001                 :             : 
    5002                 :             :                 /*
    5003                 :             :                  * Bail out if any of the values is not of string type.  We
    5004                 :             :                  * might leak converted strings for the other value(s), but
    5005                 :             :                  * that's not worth troubling over.
    5006                 :             :                  */
    5007         [ -  + ]:        4802 :                 if (failure)
    5008                 :           0 :                     return false;
    5009                 :             : 
    5010                 :        4802 :                 convert_string_to_scalar(valstr, scaledvalue,
    5011                 :             :                                          lostr, scaledlobound,
    5012                 :             :                                          histr, scaledhibound);
    5013                 :        4802 :                 pfree(valstr);
    5014                 :        4802 :                 pfree(lostr);
    5015                 :        4802 :                 pfree(histr);
    5016                 :        4802 :                 return true;
    5017                 :             :             }
    5018                 :             : 
    5019                 :             :             /*
    5020                 :             :              * Built-in bytea type
    5021                 :             :              */
    5022                 :           0 :         case BYTEAOID:
    5023                 :             :             {
    5024                 :             :                 /* We only support bytea vs bytea comparison */
    5025         [ #  # ]:           0 :                 if (boundstypid != BYTEAOID)
    5026                 :           0 :                     return false;
    5027                 :           0 :                 convert_bytea_to_scalar(value, scaledvalue,
    5028                 :             :                                         lobound, scaledlobound,
    5029                 :             :                                         hibound, scaledhibound);
    5030                 :           0 :                 return true;
    5031                 :             :             }
    5032                 :             : 
    5033                 :             :             /*
    5034                 :             :              * Built-in time types
    5035                 :             :              */
    5036                 :           0 :         case TIMESTAMPOID:
    5037                 :             :         case TIMESTAMPTZOID:
    5038                 :             :         case DATEOID:
    5039                 :             :         case INTERVALOID:
    5040                 :             :         case TIMEOID:
    5041                 :             :         case TIMETZOID:
    5042                 :           0 :             *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
    5043                 :             :                                                        &failure);
    5044                 :           0 :             *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
    5045                 :             :                                                          &failure);
    5046                 :           0 :             *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
    5047                 :             :                                                          &failure);
    5048                 :           0 :             return !failure;
    5049                 :             : 
    5050                 :             :             /*
    5051                 :             :              * Built-in network types
    5052                 :             :              */
    5053                 :           0 :         case INETOID:
    5054                 :             :         case CIDROID:
    5055                 :             :         case MACADDROID:
    5056                 :             :         case MACADDR8OID:
    5057                 :           0 :             *scaledvalue = convert_network_to_scalar(value, valuetypid,
    5058                 :             :                                                      &failure);
    5059                 :           0 :             *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
    5060                 :             :                                                        &failure);
    5061                 :           0 :             *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
    5062                 :             :                                                        &failure);
    5063                 :           0 :             return !failure;
    5064                 :             :     }
    5065                 :             :     /* Don't know how to convert */
    5066                 :           0 :     *scaledvalue = *scaledlobound = *scaledhibound = 0;
    5067                 :           0 :     return false;
    5068                 :             : }
    5069                 :             : 
    5070                 :             : /*
    5071                 :             :  * Do convert_to_scalar()'s work for any numeric data type.
    5072                 :             :  *
    5073                 :             :  * On failure (e.g., unsupported typid), set *failure to true;
    5074                 :             :  * otherwise, that variable is not changed.
    5075                 :             :  */
    5076                 :             : static double
    5077                 :      144918 : convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
    5078                 :             : {
    5079   [ -  +  +  -  :      144918 :     switch (typid)
             -  +  -  +  
                      - ]
    5080                 :             :     {
    5081                 :           0 :         case BOOLOID:
    5082                 :           0 :             return (double) DatumGetBool(value);
    5083                 :          10 :         case INT2OID:
    5084                 :          10 :             return (double) DatumGetInt16(value);
    5085                 :       22169 :         case INT4OID:
    5086                 :       22169 :             return (double) DatumGetInt32(value);
    5087                 :           0 :         case INT8OID:
    5088                 :           0 :             return (double) DatumGetInt64(value);
    5089                 :           0 :         case FLOAT4OID:
    5090                 :           0 :             return (double) DatumGetFloat4(value);
    5091                 :          45 :         case FLOAT8OID:
    5092                 :          45 :             return (double) DatumGetFloat8(value);
    5093                 :           0 :         case NUMERICOID:
    5094                 :             :             /* Note: out-of-range values will be clamped to +-HUGE_VAL */
    5095                 :           0 :             return (double)
    5096                 :           0 :                 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
    5097                 :             :                                                    value));
    5098                 :      122694 :         case OIDOID:
    5099                 :             :         case REGPROCOID:
    5100                 :             :         case REGPROCEDUREOID:
    5101                 :             :         case REGOPEROID:
    5102                 :             :         case REGOPERATOROID:
    5103                 :             :         case REGCLASSOID:
    5104                 :             :         case REGTYPEOID:
    5105                 :             :         case REGCOLLATIONOID:
    5106                 :             :         case REGCONFIGOID:
    5107                 :             :         case REGDICTIONARYOID:
    5108                 :             :         case REGROLEOID:
    5109                 :             :         case REGNAMESPACEOID:
    5110                 :             :         case REGDATABASEOID:
    5111                 :             :             /* we can treat OIDs as integers... */
    5112                 :      122694 :             return (double) DatumGetObjectId(value);
    5113                 :             :     }
    5114                 :             : 
    5115                 :           0 :     *failure = true;
    5116                 :           0 :     return 0;
    5117                 :             : }
    5118                 :             : 
    5119                 :             : /*
    5120                 :             :  * Do convert_to_scalar()'s work for any character-string data type.
    5121                 :             :  *
    5122                 :             :  * String datatypes are converted to a scale that ranges from 0 to 1,
    5123                 :             :  * where we visualize the bytes of the string as fractional digits.
    5124                 :             :  *
    5125                 :             :  * We do not want the base to be 256, however, since that tends to
    5126                 :             :  * generate inflated selectivity estimates; few databases will have
    5127                 :             :  * occurrences of all 256 possible byte values at each position.
    5128                 :             :  * Instead, use the smallest and largest byte values seen in the bounds
    5129                 :             :  * as the estimated range for each byte, after some fudging to deal with
    5130                 :             :  * the fact that we probably aren't going to see the full range that way.
    5131                 :             :  *
    5132                 :             :  * An additional refinement is that we discard any common prefix of the
    5133                 :             :  * three strings before computing the scaled values.  This allows us to
    5134                 :             :  * "zoom in" when we encounter a narrow data range.  An example is a phone
    5135                 :             :  * number database where all the values begin with the same area code.
    5136                 :             :  * (Actually, the bounds will be adjacent histogram-bin-boundary values,
    5137                 :             :  * so this is more likely to happen than you might think.)
    5138                 :             :  */
    5139                 :             : static void
    5140                 :        4802 : convert_string_to_scalar(char *value,
    5141                 :             :                          double *scaledvalue,
    5142                 :             :                          char *lobound,
    5143                 :             :                          double *scaledlobound,
    5144                 :             :                          char *hibound,
    5145                 :             :                          double *scaledhibound)
    5146                 :             : {
    5147                 :             :     int         rangelo,
    5148                 :             :                 rangehi;
    5149                 :             :     char       *sptr;
    5150                 :             : 
    5151                 :        4802 :     rangelo = rangehi = (unsigned char) hibound[0];
    5152         [ +  + ]:       69452 :     for (sptr = lobound; *sptr; sptr++)
    5153                 :             :     {
    5154         [ +  + ]:       64650 :         if (rangelo > (unsigned char) *sptr)
    5155                 :       11850 :             rangelo = (unsigned char) *sptr;
    5156         [ +  + ]:       64650 :         if (rangehi < (unsigned char) *sptr)
    5157                 :        6064 :             rangehi = (unsigned char) *sptr;
    5158                 :             :     }
    5159         [ +  + ]:       55856 :     for (sptr = hibound; *sptr; sptr++)
    5160                 :             :     {
    5161         [ +  + ]:       51054 :         if (rangelo > (unsigned char) *sptr)
    5162                 :         499 :             rangelo = (unsigned char) *sptr;
    5163         [ +  + ]:       51054 :         if (rangehi < (unsigned char) *sptr)
    5164                 :        1851 :             rangehi = (unsigned char) *sptr;
    5165                 :             :     }
    5166                 :             :     /* If range includes any upper-case ASCII chars, make it include all */
    5167   [ +  +  +  + ]:        4802 :     if (rangelo <= 'Z' && rangehi >= 'A')
    5168                 :             :     {
    5169         [ +  + ]:         976 :         if (rangelo > 'A')
    5170                 :         190 :             rangelo = 'A';
    5171         [ +  + ]:         976 :         if (rangehi < 'Z')
    5172                 :         430 :             rangehi = 'Z';
    5173                 :             :     }
    5174                 :             :     /* Ditto lower-case */
    5175   [ +  -  +  + ]:        4802 :     if (rangelo <= 'z' && rangehi >= 'a')
    5176                 :             :     {
    5177         [ +  + ]:        4357 :         if (rangelo > 'a')
    5178                 :          20 :             rangelo = 'a';
    5179         [ +  + ]:        4357 :         if (rangehi < 'z')
    5180                 :        4299 :             rangehi = 'z';
    5181                 :             :     }
    5182                 :             :     /* Ditto digits */
    5183   [ +  +  +  - ]:        4802 :     if (rangelo <= '9' && rangehi >= '0')
    5184                 :             :     {
    5185         [ +  + ]:         376 :         if (rangelo > '0')
    5186                 :         303 :             rangelo = '0';
    5187         [ +  + ]:         376 :         if (rangehi < '9')
    5188                 :           9 :             rangehi = '9';
    5189                 :             :     }
    5190                 :             : 
    5191                 :             :     /*
    5192                 :             :      * If range includes less than 10 chars, assume we have not got enough
    5193                 :             :      * data, and make it include regular ASCII set.
    5194                 :             :      */
    5195         [ -  + ]:        4802 :     if (rangehi - rangelo < 9)
    5196                 :             :     {
    5197                 :           0 :         rangelo = ' ';
    5198                 :           0 :         rangehi = 127;
    5199                 :             :     }
    5200                 :             : 
    5201                 :             :     /*
    5202                 :             :      * Now strip any common prefix of the three strings.
    5203                 :             :      */
    5204         [ +  - ]:        9239 :     while (*lobound)
    5205                 :             :     {
    5206   [ +  +  +  - ]:        9239 :         if (*lobound != *hibound || *lobound != *value)
    5207                 :             :             break;
    5208                 :        4437 :         lobound++, hibound++, value++;
    5209                 :             :     }
    5210                 :             : 
    5211                 :             :     /*
    5212                 :             :      * Now we can do the conversions.
    5213                 :             :      */
    5214                 :        4802 :     *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
    5215                 :        4802 :     *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
    5216                 :        4802 :     *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
    5217                 :        4802 : }
    5218                 :             : 
    5219                 :             : static double
    5220                 :       14406 : convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
    5221                 :             : {
    5222                 :       14406 :     int         slen = strlen(value);
    5223                 :             :     double      num,
    5224                 :             :                 denom,
    5225                 :             :                 base;
    5226                 :             : 
    5227         [ -  + ]:       14406 :     if (slen <= 0)
    5228                 :           0 :         return 0.0;             /* empty string has scalar value 0 */
    5229                 :             : 
    5230                 :             :     /*
    5231                 :             :      * There seems little point in considering more than a dozen bytes from
    5232                 :             :      * the string.  Since base is at least 10, that will give us nominal
    5233                 :             :      * resolution of at least 12 decimal digits, which is surely far more
    5234                 :             :      * precision than this estimation technique has got anyway (especially in
    5235                 :             :      * non-C locales).  Also, even with the maximum possible base of 256, this
    5236                 :             :      * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
    5237                 :             :      * overflow on any known machine.
    5238                 :             :      */
    5239         [ +  + ]:       14406 :     if (slen > 12)
    5240                 :        3969 :         slen = 12;
    5241                 :             : 
    5242                 :             :     /* Convert initial characters to fraction */
    5243                 :       14406 :     base = rangehi - rangelo + 1;
    5244                 :       14406 :     num = 0.0;
    5245                 :       14406 :     denom = base;
    5246         [ +  + ]:      124657 :     while (slen-- > 0)
    5247                 :             :     {
    5248                 :      110251 :         int         ch = (unsigned char) *value++;
    5249                 :             : 
    5250         [ +  + ]:      110251 :         if (ch < rangelo)
    5251                 :         180 :             ch = rangelo - 1;
    5252         [ -  + ]:      110071 :         else if (ch > rangehi)
    5253                 :           0 :             ch = rangehi + 1;
    5254                 :      110251 :         num += ((double) (ch - rangelo)) / denom;
    5255                 :      110251 :         denom *= base;
    5256                 :             :     }
    5257                 :             : 
    5258                 :       14406 :     return num;
    5259                 :             : }
    5260                 :             : 
    5261                 :             : /*
    5262                 :             :  * Convert a string-type Datum into a palloc'd, null-terminated string.
    5263                 :             :  *
    5264                 :             :  * On failure (e.g., unsupported typid), set *failure to true;
    5265                 :             :  * otherwise, that variable is not changed.  (We'll return NULL on failure.)
    5266                 :             :  *
    5267                 :             :  * When using a non-C locale, we must pass the string through pg_strxfrm()
    5268                 :             :  * before continuing, so as to generate correct locale-specific results.
    5269                 :             :  */
    5270                 :             : static char *
    5271                 :       14406 : convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
    5272                 :             : {
    5273                 :             :     char       *val;
    5274                 :             :     pg_locale_t mylocale;
    5275                 :             : 
    5276   [ +  +  +  - ]:       14406 :     switch (typid)
    5277                 :             :     {
    5278                 :          15 :         case CHAROID:
    5279                 :          15 :             val = (char *) palloc(2);
    5280                 :          15 :             val[0] = DatumGetChar(value);
    5281                 :          15 :             val[1] = '\0';
    5282                 :          15 :             break;
    5283                 :        4328 :         case BPCHAROID:
    5284                 :             :         case VARCHAROID:
    5285                 :             :         case TEXTOID:
    5286                 :        4328 :             val = TextDatumGetCString(value);
    5287                 :        4328 :             break;
    5288                 :       10063 :         case NAMEOID:
    5289                 :             :             {
    5290                 :       10063 :                 NameData   *nm = (NameData *) DatumGetPointer(value);
    5291                 :             : 
    5292                 :       10063 :                 val = pstrdup(NameStr(*nm));
    5293                 :       10063 :                 break;
    5294                 :             :             }
    5295                 :           0 :         default:
    5296                 :           0 :             *failure = true;
    5297                 :           0 :             return NULL;
    5298                 :             :     }
    5299                 :             : 
    5300                 :             :     /*
    5301                 :             :      * If we don't have a collation, act as though it's "C".  This would
    5302                 :             :      * normally happen only for the "char" type, but perhaps there are other
    5303                 :             :      * cases.
    5304                 :             :      */
    5305         [ +  + ]:       14406 :     if (!OidIsValid(collid))
    5306                 :          15 :         return val;
    5307                 :             : 
    5308                 :       14391 :     mylocale = pg_newlocale_from_collation(collid);
    5309                 :             : 
    5310         [ +  + ]:       14391 :     if (!mylocale->collate_is_c)
    5311                 :             :     {
    5312                 :             :         char       *xfrmstr;
    5313                 :             :         size_t      xfrmlen;
    5314                 :             :         size_t      xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
    5315                 :             : 
    5316                 :             :         /*
    5317                 :             :          * XXX: We could guess at a suitable output buffer size and only call
    5318                 :             :          * pg_strxfrm() twice if our guess is too small.
    5319                 :             :          *
    5320                 :             :          * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
    5321                 :             :          * bogus data or set an error. This is not really a problem unless it
    5322                 :             :          * crashes since it will only give an estimation error and nothing
    5323                 :             :          * fatal.
    5324                 :             :          *
    5325                 :             :          * XXX: we do not check pg_strxfrm_enabled(). On some platforms and in
    5326                 :             :          * some cases, libc strxfrm() may return the wrong results, but that
    5327                 :             :          * will only lead to an estimation error.
    5328                 :             :          */
    5329                 :          66 :         xfrmlen = pg_strxfrm(NULL, val, 0, mylocale);
    5330                 :             : #ifdef WIN32
    5331                 :             : 
    5332                 :             :         /*
    5333                 :             :          * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
    5334                 :             :          * of trying to allocate this much memory (and fail), just return the
    5335                 :             :          * original string unmodified as if we were in the C locale.
    5336                 :             :          */
    5337                 :             :         if (xfrmlen == INT_MAX)
    5338                 :             :             return val;
    5339                 :             : #endif
    5340                 :          66 :         xfrmstr = (char *) palloc(xfrmlen + 1);
    5341                 :          66 :         xfrmlen2 = pg_strxfrm(xfrmstr, val, xfrmlen + 1, mylocale);
    5342                 :             : 
    5343                 :             :         /*
    5344                 :             :          * Some systems (e.g., glibc) can return a smaller value from the
    5345                 :             :          * second call than the first; thus the Assert must be <= not ==.
    5346                 :             :          */
    5347                 :             :         Assert(xfrmlen2 <= xfrmlen);
    5348                 :          66 :         pfree(val);
    5349                 :          66 :         val = xfrmstr;
    5350                 :             :     }
    5351                 :             : 
    5352                 :       14391 :     return val;
    5353                 :             : }
    5354                 :             : 
    5355                 :             : /*
    5356                 :             :  * Do convert_to_scalar()'s work for any bytea data type.
    5357                 :             :  *
    5358                 :             :  * Very similar to convert_string_to_scalar except we can't assume
    5359                 :             :  * null-termination and therefore pass explicit lengths around.
    5360                 :             :  *
    5361                 :             :  * Also, assumptions about likely "normal" ranges of characters have been
    5362                 :             :  * removed - a data range of 0..255 is always used, for now.  (Perhaps
    5363                 :             :  * someday we will add information about actual byte data range to
    5364                 :             :  * pg_statistic.)
    5365                 :             :  */
    5366                 :             : static void
    5367                 :           0 : convert_bytea_to_scalar(Datum value,
    5368                 :             :                         double *scaledvalue,
    5369                 :             :                         Datum lobound,
    5370                 :             :                         double *scaledlobound,
    5371                 :             :                         Datum hibound,
    5372                 :             :                         double *scaledhibound)
    5373                 :             : {
    5374                 :           0 :     bytea      *valuep = DatumGetByteaPP(value);
    5375                 :           0 :     bytea      *loboundp = DatumGetByteaPP(lobound);
    5376                 :           0 :     bytea      *hiboundp = DatumGetByteaPP(hibound);
    5377                 :             :     int         rangelo,
    5378                 :             :                 rangehi,
    5379                 :           0 :                 valuelen = VARSIZE_ANY_EXHDR(valuep),
    5380                 :           0 :                 loboundlen = VARSIZE_ANY_EXHDR(loboundp),
    5381                 :           0 :                 hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
    5382                 :             :                 i,
    5383                 :             :                 minlen;
    5384                 :           0 :     unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
    5385                 :           0 :     unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
    5386                 :           0 :     unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
    5387                 :             : 
    5388                 :             :     /*
    5389                 :             :      * Assume bytea data is uniformly distributed across all byte values.
    5390                 :             :      */
    5391                 :           0 :     rangelo = 0;
    5392                 :           0 :     rangehi = 255;
    5393                 :             : 
    5394                 :             :     /*
    5395                 :             :      * Now strip any common prefix of the three strings.
    5396                 :             :      */
    5397                 :           0 :     minlen = Min(Min(valuelen, loboundlen), hiboundlen);
    5398         [ #  # ]:           0 :     for (i = 0; i < minlen; i++)
    5399                 :             :     {
    5400   [ #  #  #  # ]:           0 :         if (*lostr != *histr || *lostr != *valstr)
    5401                 :             :             break;
    5402                 :           0 :         lostr++, histr++, valstr++;
    5403                 :           0 :         loboundlen--, hiboundlen--, valuelen--;
    5404                 :             :     }
    5405                 :             : 
    5406                 :             :     /*
    5407                 :             :      * Now we can do the conversions.
    5408                 :             :      */
    5409                 :           0 :     *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
    5410                 :           0 :     *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
    5411                 :           0 :     *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
    5412                 :           0 : }
    5413                 :             : 
    5414                 :             : static double
    5415                 :           0 : convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
    5416                 :             :                             int rangelo, int rangehi)
    5417                 :             : {
    5418                 :             :     double      num,
    5419                 :             :                 denom,
    5420                 :             :                 base;
    5421                 :             : 
    5422         [ #  # ]:           0 :     if (valuelen <= 0)
    5423                 :           0 :         return 0.0;             /* empty string has scalar value 0 */
    5424                 :             : 
    5425                 :             :     /*
    5426                 :             :      * Since base is 256, need not consider more than about 10 chars (even
    5427                 :             :      * this many seems like overkill)
    5428                 :             :      */
    5429         [ #  # ]:           0 :     if (valuelen > 10)
    5430                 :           0 :         valuelen = 10;
    5431                 :             : 
    5432                 :             :     /* Convert initial characters to fraction */
    5433                 :           0 :     base = rangehi - rangelo + 1;
    5434                 :           0 :     num = 0.0;
    5435                 :           0 :     denom = base;
    5436         [ #  # ]:           0 :     while (valuelen-- > 0)
    5437                 :             :     {
    5438                 :           0 :         int         ch = *value++;
    5439                 :             : 
    5440         [ #  # ]:           0 :         if (ch < rangelo)
    5441                 :           0 :             ch = rangelo - 1;
    5442         [ #  # ]:           0 :         else if (ch > rangehi)
    5443                 :           0 :             ch = rangehi + 1;
    5444                 :           0 :         num += ((double) (ch - rangelo)) / denom;
    5445                 :           0 :         denom *= base;
    5446                 :             :     }
    5447                 :             : 
    5448                 :           0 :     return num;
    5449                 :             : }
    5450                 :             : 
    5451                 :             : /*
    5452                 :             :  * Do convert_to_scalar()'s work for any timevalue data type.
    5453                 :             :  *
    5454                 :             :  * On failure (e.g., unsupported typid), set *failure to true;
    5455                 :             :  * otherwise, that variable is not changed.
    5456                 :             :  */
    5457                 :             : static double
    5458                 :           0 : convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
    5459                 :             : {
    5460   [ #  #  #  #  :           0 :     switch (typid)
                #  #  # ]
    5461                 :             :     {
    5462                 :           0 :         case TIMESTAMPOID:
    5463                 :           0 :             return DatumGetTimestamp(value);
    5464                 :           0 :         case TIMESTAMPTZOID:
    5465                 :           0 :             return DatumGetTimestampTz(value);
    5466                 :           0 :         case DATEOID:
    5467                 :           0 :             return date2timestamp_no_overflow(DatumGetDateADT(value));
    5468                 :           0 :         case INTERVALOID:
    5469                 :             :             {
    5470                 :           0 :                 Interval   *interval = DatumGetIntervalP(value);
    5471                 :             : 
    5472                 :             :                 /*
    5473                 :             :                  * Convert the month part of Interval to days using assumed
    5474                 :             :                  * average month length of 365.25/12.0 days.  Not too
    5475                 :             :                  * accurate, but plenty good enough for our purposes.
    5476                 :             :                  *
    5477                 :             :                  * This also works for infinite intervals, which just have all
    5478                 :             :                  * fields set to INT_MIN/INT_MAX, and so will produce a result
    5479                 :             :                  * smaller/larger than any finite interval.
    5480                 :             :                  */
    5481                 :           0 :                 return interval->time + interval->day * (double) USECS_PER_DAY +
    5482                 :           0 :                     interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
    5483                 :             :             }
    5484                 :           0 :         case TIMEOID:
    5485                 :           0 :             return DatumGetTimeADT(value);
    5486                 :           0 :         case TIMETZOID:
    5487                 :             :             {
    5488                 :           0 :                 TimeTzADT  *timetz = DatumGetTimeTzADTP(value);
    5489                 :             : 
    5490                 :             :                 /* use GMT-equivalent time */
    5491                 :           0 :                 return (double) (timetz->time + (timetz->zone * 1000000.0));
    5492                 :             :             }
    5493                 :             :     }
    5494                 :             : 
    5495                 :           0 :     *failure = true;
    5496                 :           0 :     return 0;
    5497                 :             : }
    5498                 :             : 
    5499                 :             : 
    5500                 :             : /*
    5501                 :             :  * get_restriction_variable
    5502                 :             :  *      Examine the args of a restriction clause to see if it's of the
    5503                 :             :  *      form (variable op pseudoconstant) or (pseudoconstant op variable),
    5504                 :             :  *      where "variable" could be either a Var or an expression in vars of a
    5505                 :             :  *      single relation.  If so, extract information about the variable,
    5506                 :             :  *      and also indicate which side it was on and the other argument.
    5507                 :             :  *
    5508                 :             :  * Inputs:
    5509                 :             :  *  root: the planner info
    5510                 :             :  *  args: clause argument list
    5511                 :             :  *  varRelid: see specs for restriction selectivity functions
    5512                 :             :  *
    5513                 :             :  * Outputs: (these are valid only if true is returned)
    5514                 :             :  *  *vardata: gets information about variable (see examine_variable)
    5515                 :             :  *  *other: gets other clause argument, aggressively reduced to a constant
    5516                 :             :  *  *varonleft: set true if variable is on the left, false if on the right
    5517                 :             :  *
    5518                 :             :  * Returns true if a variable is identified, otherwise false.
    5519                 :             :  *
    5520                 :             :  * Note: if there are Vars on both sides of the clause, we must fail, because
    5521                 :             :  * callers are expecting that the other side will act like a pseudoconstant.
    5522                 :             :  */
    5523                 :             : bool
    5524                 :      626923 : get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
    5525                 :             :                          VariableStatData *vardata, Node **other,
    5526                 :             :                          bool *varonleft)
    5527                 :             : {
    5528                 :             :     Node       *left,
    5529                 :             :                *right;
    5530                 :             :     VariableStatData rdata;
    5531                 :             : 
    5532                 :             :     /* Fail if not a binary opclause (probably shouldn't happen) */
    5533         [ -  + ]:      626923 :     if (list_length(args) != 2)
    5534                 :           0 :         return false;
    5535                 :             : 
    5536                 :      626923 :     left = (Node *) linitial(args);
    5537                 :      626923 :     right = (Node *) lsecond(args);
    5538                 :             : 
    5539                 :             :     /*
    5540                 :             :      * Examine both sides.  Note that when varRelid is nonzero, Vars of other
    5541                 :             :      * relations will be treated as pseudoconstants.
    5542                 :             :      */
    5543                 :      626923 :     examine_variable(root, left, varRelid, vardata);
    5544                 :      626923 :     examine_variable(root, right, varRelid, &rdata);
    5545                 :             : 
    5546                 :             :     /*
    5547                 :             :      * If one side is a variable and the other not, we win.
    5548                 :             :      */
    5549   [ +  +  +  + ]:      626923 :     if (vardata->rel && rdata.rel == NULL)
    5550                 :             :     {
    5551                 :      559828 :         *varonleft = true;
    5552                 :      559828 :         *other = estimate_expression_value(root, rdata.var);
    5553                 :             :         /* Assume we need no ReleaseVariableStats(rdata) here */
    5554                 :      559824 :         return true;
    5555                 :             :     }
    5556                 :             : 
    5557   [ +  +  +  + ]:       67095 :     if (vardata->rel == NULL && rdata.rel)
    5558                 :             :     {
    5559                 :       63050 :         *varonleft = false;
    5560                 :       63050 :         *other = estimate_expression_value(root, vardata->var);
    5561                 :             :         /* Assume we need no ReleaseVariableStats(*vardata) here */
    5562                 :       63050 :         *vardata = rdata;
    5563                 :       63050 :         return true;
    5564                 :             :     }
    5565                 :             : 
    5566                 :             :     /* Oops, clause has wrong structure (probably var op var) */
    5567         [ +  + ]:        4045 :     ReleaseVariableStats(*vardata);
    5568         [ +  + ]:        4045 :     ReleaseVariableStats(rdata);
    5569                 :             : 
    5570                 :        4045 :     return false;
    5571                 :             : }
    5572                 :             : 
    5573                 :             : /*
    5574                 :             :  * get_join_variables
    5575                 :             :  *      Apply examine_variable() to each side of a join clause.
    5576                 :             :  *      Also, attempt to identify whether the join clause has the same
    5577                 :             :  *      or reversed sense compared to the SpecialJoinInfo.
    5578                 :             :  *
    5579                 :             :  * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
    5580                 :             :  * or "reversed" if it is "rhs_var OP lhs_var".  In complicated cases
    5581                 :             :  * where we can't tell for sure, we default to assuming it's normal.
    5582                 :             :  */
    5583                 :             : void
    5584                 :      209508 : get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
    5585                 :             :                    VariableStatData *vardata1, VariableStatData *vardata2,
    5586                 :             :                    bool *join_is_reversed)
    5587                 :             : {
    5588                 :             :     Node       *left,
    5589                 :             :                *right;
    5590                 :             : 
    5591         [ -  + ]:      209508 :     if (list_length(args) != 2)
    5592         [ #  # ]:           0 :         elog(ERROR, "join operator should take two arguments");
    5593                 :             : 
    5594                 :      209508 :     left = (Node *) linitial(args);
    5595                 :      209508 :     right = (Node *) lsecond(args);
    5596                 :             : 
    5597                 :      209508 :     examine_variable(root, left, 0, vardata1);
    5598                 :      209508 :     examine_variable(root, right, 0, vardata2);
    5599                 :             : 
    5600   [ +  +  +  + ]:      418806 :     if (vardata1->rel &&
    5601                 :      209298 :         bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
    5602                 :       69071 :         *join_is_reversed = true;   /* var1 is on RHS */
    5603   [ +  +  +  + ]:      280664 :     else if (vardata2->rel &&
    5604                 :      140227 :              bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
    5605                 :         304 :         *join_is_reversed = true;   /* var2 is on LHS */
    5606                 :             :     else
    5607                 :      140133 :         *join_is_reversed = false;
    5608                 :      209508 : }
    5609                 :             : 
    5610                 :             : /* statext_expressions_load copies the tuple, so just pfree it. */
    5611                 :             : static void
    5612                 :        1415 : ReleaseDummy(HeapTuple tuple)
    5613                 :             : {
    5614                 :        1415 :     pfree(tuple);
    5615                 :        1415 : }
    5616                 :             : 
    5617                 :             : /*
    5618                 :             :  * examine_variable
    5619                 :             :  *      Try to look up statistical data about an expression.
    5620                 :             :  *      Fill in a VariableStatData struct to describe the expression.
    5621                 :             :  *
    5622                 :             :  * Inputs:
    5623                 :             :  *  root: the planner info
    5624                 :             :  *  node: the expression tree to examine
    5625                 :             :  *  varRelid: see specs for restriction selectivity functions
    5626                 :             :  *
    5627                 :             :  * Outputs: *vardata is filled as follows:
    5628                 :             :  *  var: the input expression (with any phvs or binary relabeling stripped,
    5629                 :             :  *      if it is or contains a variable; but otherwise unchanged)
    5630                 :             :  *  rel: RelOptInfo for relation containing variable; NULL if expression
    5631                 :             :  *      contains no Vars (NOTE this could point to a RelOptInfo of a
    5632                 :             :  *      subquery, not one in the current query).
    5633                 :             :  *  statsTuple: the pg_statistic entry for the variable, if one exists;
    5634                 :             :  *      otherwise NULL.
    5635                 :             :  *  freefunc: pointer to a function to release statsTuple with.
    5636                 :             :  *  vartype: exposed type of the expression; this should always match
    5637                 :             :  *      the declared input type of the operator we are estimating for.
    5638                 :             :  *  atttype, atttypmod: actual type/typmod of the "var" expression.  This is
    5639                 :             :  *      commonly the same as the exposed type of the variable argument,
    5640                 :             :  *      but can be different in binary-compatible-type cases.
    5641                 :             :  *  isunique: true if we were able to match the var to a unique index, a
    5642                 :             :  *      single-column DISTINCT or GROUP-BY clause, implying its values are
    5643                 :             :  *      unique for this query.  (Caution: this should be trusted for
    5644                 :             :  *      statistical purposes only, since we do not check indimmediate nor
    5645                 :             :  *      verify that the exact same definition of equality applies.)
    5646                 :             :  *  acl_ok: true if current user has permission to read all table rows from
    5647                 :             :  *      the column(s) underlying the pg_statistic entry.  This is consulted by
    5648                 :             :  *      statistic_proc_security_check().
    5649                 :             :  *
    5650                 :             :  * Caller is responsible for doing ReleaseVariableStats() before exiting.
    5651                 :             :  */
    5652                 :             : void
    5653                 :     2500170 : examine_variable(PlannerInfo *root, Node *node, int varRelid,
    5654                 :             :                  VariableStatData *vardata)
    5655                 :             : {
    5656                 :             :     Node       *basenode;
    5657                 :             :     Relids      varnos;
    5658                 :             :     Relids      basevarnos;
    5659                 :             :     RelOptInfo *onerel;
    5660                 :             : 
    5661                 :             :     /* Make sure we don't return dangling pointers in vardata */
    5662   [ +  -  +  -  :    17501190 :     MemSet(vardata, 0, sizeof(VariableStatData));
          +  -  +  -  +  
                      + ]
    5663                 :             : 
    5664                 :             :     /* Save the exposed type of the expression */
    5665                 :     2500170 :     vardata->vartype = exprType(node);
    5666                 :             : 
    5667                 :             :     /*
    5668                 :             :      * PlaceHolderVars are transparent for the purpose of statistics lookup;
    5669                 :             :      * they do not alter the value distribution of the underlying expression.
    5670                 :             :      * However, they can obscure the structure, preventing us from recognizing
    5671                 :             :      * matches to base columns, index expressions, or extended statistics.  So
    5672                 :             :      * strip them out first.
    5673                 :             :      */
    5674                 :     2500170 :     basenode = strip_all_phvs_deep(root, node);
    5675                 :             : 
    5676                 :             :     /*
    5677                 :             :      * Look inside any binary-compatible relabeling.  We need to handle nested
    5678                 :             :      * RelabelType nodes here, because the prior stripping of PlaceHolderVars
    5679                 :             :      * may have brought separate RelabelTypes into adjacency.
    5680                 :             :      */
    5681         [ +  + ]:     2540625 :     while (IsA(basenode, RelabelType))
    5682                 :       40455 :         basenode = (Node *) ((RelabelType *) basenode)->arg;
    5683                 :             : 
    5684                 :             :     /* Fast path for a simple Var */
    5685   [ +  +  +  + ]:     2500170 :     if (IsA(basenode, Var) &&
    5686         [ +  + ]:      642916 :         (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
    5687                 :             :     {
    5688                 :     1769110 :         Var        *var = (Var *) basenode;
    5689                 :             : 
    5690                 :             :         /* Set up result fields other than the stats tuple */
    5691                 :     1769110 :         vardata->var = basenode; /* return Var without phvs or relabeling */
    5692                 :     1769110 :         vardata->rel = find_base_rel(root, var->varno);
    5693                 :     1769110 :         vardata->atttype = var->vartype;
    5694                 :     1769110 :         vardata->atttypmod = var->vartypmod;
    5695                 :     1769110 :         vardata->isunique = has_unique_index(vardata->rel, var->varattno);
    5696                 :             : 
    5697                 :             :         /* Try to locate some stats */
    5698                 :     1769110 :         examine_simple_variable(root, var, vardata);
    5699                 :             : 
    5700                 :     1769110 :         return;
    5701                 :             :     }
    5702                 :             : 
    5703                 :             :     /*
    5704                 :             :      * Okay, it's a more complicated expression.  Determine variable
    5705                 :             :      * membership.  Note that when varRelid isn't zero, only vars of that
    5706                 :             :      * relation are considered "real" vars.
    5707                 :             :      */
    5708                 :      731060 :     varnos = pull_varnos(root, basenode);
    5709                 :      731060 :     basevarnos = bms_difference(varnos, root->outer_join_rels);
    5710                 :             : 
    5711                 :      731060 :     onerel = NULL;
    5712                 :             : 
    5713         [ +  + ]:      731060 :     if (bms_is_empty(basevarnos))
    5714                 :             :     {
    5715                 :             :         /* No Vars at all ... must be pseudo-constant clause */
    5716                 :             :     }
    5717                 :             :     else
    5718                 :             :     {
    5719                 :             :         int         relid;
    5720                 :             : 
    5721                 :             :         /* Check if the expression is in vars of a single base relation */
    5722         [ +  + ]:      379678 :         if (bms_get_singleton_member(basevarnos, &relid))
    5723                 :             :         {
    5724   [ +  +  +  + ]:      373398 :             if (varRelid == 0 || varRelid == relid)
    5725                 :             :             {
    5726                 :       55679 :                 onerel = find_base_rel(root, relid);
    5727                 :       55679 :                 vardata->rel = onerel;
    5728                 :       55679 :                 node = basenode;    /* strip any phvs or relabeling */
    5729                 :             :             }
    5730                 :             :             /* else treat it as a constant */
    5731                 :             :         }
    5732                 :             :         else
    5733                 :             :         {
    5734                 :             :             /* varnos has multiple relids */
    5735         [ +  + ]:        6280 :             if (varRelid == 0)
    5736                 :             :             {
    5737                 :             :                 /* treat it as a variable of a join relation */
    5738                 :        5284 :                 vardata->rel = find_join_rel(root, varnos);
    5739                 :        5284 :                 node = basenode;    /* strip any phvs or relabeling */
    5740                 :             :             }
    5741         [ +  + ]:         996 :             else if (bms_is_member(varRelid, varnos))
    5742                 :             :             {
    5743                 :             :                 /* ignore the vars belonging to other relations */
    5744                 :         901 :                 vardata->rel = find_base_rel(root, varRelid);
    5745                 :         901 :                 node = basenode;    /* strip any phvs or relabeling */
    5746                 :             :                 /* note: no point in expressional-index search here */
    5747                 :             :             }
    5748                 :             :             /* else treat it as a constant */
    5749                 :             :         }
    5750                 :             :     }
    5751                 :             : 
    5752                 :      731060 :     bms_free(basevarnos);
    5753                 :             : 
    5754                 :      731060 :     vardata->var = node;
    5755                 :      731060 :     vardata->atttype = exprType(node);
    5756                 :      731060 :     vardata->atttypmod = exprTypmod(node);
    5757                 :             : 
    5758         [ +  + ]:      731060 :     if (onerel)
    5759                 :             :     {
    5760                 :             :         /*
    5761                 :             :          * We have an expression in vars of a single relation.  Try to match
    5762                 :             :          * it to expressional index columns, in hopes of finding some
    5763                 :             :          * statistics.
    5764                 :             :          *
    5765                 :             :          * Note that we consider all index columns including INCLUDE columns,
    5766                 :             :          * since there could be stats for such columns.  But the test for
    5767                 :             :          * uniqueness needs to be warier.
    5768                 :             :          *
    5769                 :             :          * XXX it's conceivable that there are multiple matches with different
    5770                 :             :          * index opfamilies; if so, we need to pick one that matches the
    5771                 :             :          * operator we are estimating for.  FIXME later.
    5772                 :             :          */
    5773                 :             :         ListCell   *ilist;
    5774                 :             :         ListCell   *slist;
    5775                 :             : 
    5776                 :             :         /*
    5777                 :             :          * The nullingrels bits within the expression could prevent us from
    5778                 :             :          * matching it to expressional index columns or to the expressions in
    5779                 :             :          * extended statistics.  So strip them out first.
    5780                 :             :          */
    5781         [ +  + ]:       55679 :         if (bms_overlap(varnos, root->outer_join_rels))
    5782                 :        1573 :             node = remove_nulling_relids(node, root->outer_join_rels, NULL);
    5783                 :             : 
    5784   [ +  +  +  +  :      127009 :         foreach(ilist, onerel->indexlist)
                   +  + ]
    5785                 :             :         {
    5786                 :       73707 :             IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
    5787                 :             :             ListCell   *indexpr_item;
    5788                 :             :             int         pos;
    5789                 :             : 
    5790                 :       73707 :             indexpr_item = list_head(index->indexprs);
    5791         [ +  + ]:       73707 :             if (indexpr_item == NULL)
    5792                 :       69746 :                 continue;       /* no expressions here... */
    5793                 :             : 
    5794         [ +  + ]:        5609 :             for (pos = 0; pos < index->ncolumns; pos++)
    5795                 :             :             {
    5796         [ +  + ]:        4025 :                 if (index->indexkeys[pos] == 0)
    5797                 :             :                 {
    5798                 :             :                     Node       *indexkey;
    5799                 :             : 
    5800         [ -  + ]:        3961 :                     if (indexpr_item == NULL)
    5801         [ #  # ]:           0 :                         elog(ERROR, "too few entries in indexprs list");
    5802                 :        3961 :                     indexkey = (Node *) lfirst(indexpr_item);
    5803   [ +  -  -  + ]:        3961 :                     if (indexkey && IsA(indexkey, RelabelType))
    5804                 :           0 :                         indexkey = (Node *) ((RelabelType *) indexkey)->arg;
    5805         [ +  + ]:        3961 :                     if (equal(node, indexkey))
    5806                 :             :                     {
    5807                 :             :                         /*
    5808                 :             :                          * Found a match ... is it a unique index? Tests here
    5809                 :             :                          * should match has_unique_index().
    5810                 :             :                          */
    5811         [ +  + ]:        2916 :                         if (index->unique &&
    5812   [ +  -  +  - ]:         365 :                             index->nkeycolumns == 1 &&
    5813                 :         365 :                             pos == 0 &&
    5814   [ -  +  -  - ]:         365 :                             (index->indpred == NIL || index->predOK))
    5815                 :         365 :                             vardata->isunique = true;
    5816                 :             : 
    5817                 :             :                         /*
    5818                 :             :                          * Has it got stats?  We only consider stats for
    5819                 :             :                          * non-partial indexes, since partial indexes probably
    5820                 :             :                          * don't reflect whole-relation statistics; the above
    5821                 :             :                          * check for uniqueness is the only info we take from
    5822                 :             :                          * a partial index.
    5823                 :             :                          *
    5824                 :             :                          * An index stats hook, however, must make its own
    5825                 :             :                          * decisions about what to do with partial indexes.
    5826                 :             :                          */
    5827   [ -  +  -  - ]:        2916 :                         if (get_index_stats_hook &&
    5828                 :           0 :                             (*get_index_stats_hook) (root, index->indexoid,
    5829                 :           0 :                                                      pos + 1, vardata))
    5830                 :             :                         {
    5831                 :             :                             /*
    5832                 :             :                              * The hook took control of acquiring a stats
    5833                 :             :                              * tuple.  If it did supply a tuple, it'd better
    5834                 :             :                              * have supplied a freefunc.
    5835                 :             :                              */
    5836         [ #  # ]:           0 :                             if (HeapTupleIsValid(vardata->statsTuple) &&
    5837         [ #  # ]:           0 :                                 !vardata->freefunc)
    5838         [ #  # ]:           0 :                                 elog(ERROR, "no function provided to release variable stats with");
    5839                 :             :                         }
    5840         [ +  - ]:        2916 :                         else if (index->indpred == NIL)
    5841                 :             :                         {
    5842                 :        2916 :                             vardata->statsTuple =
    5843                 :        5832 :                                 SearchSysCache3(STATRELATTINH,
    5844                 :             :                                                 ObjectIdGetDatum(index->indexoid),
    5845                 :        2916 :                                                 Int16GetDatum(pos + 1),
    5846                 :             :                                                 BoolGetDatum(false));
    5847                 :        2916 :                             vardata->freefunc = ReleaseSysCache;
    5848                 :             : 
    5849         [ +  + ]:        2916 :                             if (HeapTupleIsValid(vardata->statsTuple))
    5850                 :             :                             {
    5851                 :             :                                 /*
    5852                 :             :                                  * Test if user has permission to access all
    5853                 :             :                                  * rows from the index's table.
    5854                 :             :                                  *
    5855                 :             :                                  * For simplicity, we insist on the whole
    5856                 :             :                                  * table being selectable, rather than trying
    5857                 :             :                                  * to identify which column(s) the index
    5858                 :             :                                  * depends on.
    5859                 :             :                                  *
    5860                 :             :                                  * Note that for an inheritance child,
    5861                 :             :                                  * permissions are checked on the inheritance
    5862                 :             :                                  * root parent, and whole-table select
    5863                 :             :                                  * privilege on the parent doesn't quite
    5864                 :             :                                  * guarantee that the user could read all
    5865                 :             :                                  * columns of the child.  But in practice it's
    5866                 :             :                                  * unlikely that any interesting security
    5867                 :             :                                  * violation could result from allowing access
    5868                 :             :                                  * to the expression index's stats, so we
    5869                 :             :                                  * allow it anyway.  See similar code in
    5870                 :             :                                  * examine_simple_variable() for additional
    5871                 :             :                                  * comments.
    5872                 :             :                                  */
    5873                 :        2377 :                                 vardata->acl_ok =
    5874                 :        2377 :                                     all_rows_selectable(root,
    5875                 :        2377 :                                                         index->rel->relid,
    5876                 :             :                                                         NULL);
    5877                 :             :                             }
    5878                 :             :                             else
    5879                 :             :                             {
    5880                 :             :                                 /* suppress leakproofness checks later */
    5881                 :         539 :                                 vardata->acl_ok = true;
    5882                 :             :                             }
    5883                 :             :                         }
    5884         [ +  + ]:        2916 :                         if (vardata->statsTuple)
    5885                 :        2377 :                             break;
    5886                 :             :                     }
    5887                 :        1584 :                     indexpr_item = lnext(index->indexprs, indexpr_item);
    5888                 :             :                 }
    5889                 :             :             }
    5890         [ +  + ]:        3961 :             if (vardata->statsTuple)
    5891                 :        2377 :                 break;
    5892                 :             :         }
    5893                 :             : 
    5894                 :             :         /*
    5895                 :             :          * Search extended statistics for one with a matching expression.
    5896                 :             :          * There might be multiple ones, so just grab the first one. In the
    5897                 :             :          * future, we might consider the statistics target (and pick the most
    5898                 :             :          * accurate statistics) and maybe some other parameters.
    5899                 :             :          */
    5900   [ +  +  +  +  :       59208 :         foreach(slist, onerel->statlist)
                   +  + ]
    5901                 :             :         {
    5902                 :        3774 :             StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
    5903         [ +  - ]:        3774 :             RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
    5904                 :             :             ListCell   *expr_item;
    5905                 :             :             int         pos;
    5906                 :             : 
    5907                 :             :             /*
    5908                 :             :              * Stop once we've found statistics for the expression (either
    5909                 :             :              * from extended stats, or for an index in the preceding loop).
    5910                 :             :              */
    5911         [ +  + ]:        3774 :             if (vardata->statsTuple)
    5912                 :         245 :                 break;
    5913                 :             : 
    5914                 :             :             /* skip stats without per-expression stats */
    5915         [ +  + ]:        3529 :             if (info->kind != STATS_EXT_EXPRESSIONS)
    5916                 :        1808 :                 continue;
    5917                 :             : 
    5918                 :             :             /* skip stats with mismatching stxdinherit value */
    5919         [ +  + ]:        1721 :             if (info->inherit != rte->inh)
    5920                 :           5 :                 continue;
    5921                 :             : 
    5922                 :        1716 :             pos = 0;
    5923   [ +  -  +  +  :        2836 :             foreach(expr_item, info->exprs)
                   +  + ]
    5924                 :             :             {
    5925                 :        2536 :                 Node       *expr = (Node *) lfirst(expr_item);
    5926                 :             : 
    5927                 :             :                 Assert(expr);
    5928                 :             : 
    5929                 :             :                 /* strip RelabelType before comparing it */
    5930   [ +  -  -  + ]:        2536 :                 if (expr && IsA(expr, RelabelType))
    5931                 :           0 :                     expr = (Node *) ((RelabelType *) expr)->arg;
    5932                 :             : 
    5933                 :             :                 /* found a match, see if we can extract pg_statistic row */
    5934         [ +  + ]:        2536 :                 if (equal(node, expr))
    5935                 :             :                 {
    5936                 :             :                     /*
    5937                 :             :                      * XXX Not sure if we should cache the tuple somewhere.
    5938                 :             :                      * Now we just create a new copy every time.
    5939                 :             :                      */
    5940                 :        1416 :                     vardata->statsTuple =
    5941                 :        1416 :                         statext_expressions_load(info->statOid, rte->inh, pos);
    5942                 :             : 
    5943                 :             :                     /* Nothing to release if no data found */
    5944         [ +  + ]:        1416 :                     if (vardata->statsTuple != NULL)
    5945                 :             :                     {
    5946                 :        1415 :                         vardata->freefunc = ReleaseDummy;
    5947                 :             :                     }
    5948                 :             : 
    5949                 :             :                     /*
    5950                 :             :                      * Test if user has permission to access all rows from the
    5951                 :             :                      * table.
    5952                 :             :                      *
    5953                 :             :                      * For simplicity, we insist on the whole table being
    5954                 :             :                      * selectable, rather than trying to identify which
    5955                 :             :                      * column(s) the statistics object depends on.
    5956                 :             :                      *
    5957                 :             :                      * Note that for an inheritance child, permissions are
    5958                 :             :                      * checked on the inheritance root parent, and whole-table
    5959                 :             :                      * select privilege on the parent doesn't quite guarantee
    5960                 :             :                      * that the user could read all columns of the child.  But
    5961                 :             :                      * in practice it's unlikely that any interesting security
    5962                 :             :                      * violation could result from allowing access to the
    5963                 :             :                      * expression stats, so we allow it anyway.  See similar
    5964                 :             :                      * code in examine_simple_variable() for additional
    5965                 :             :                      * comments.
    5966                 :             :                      */
    5967                 :        1416 :                     vardata->acl_ok = all_rows_selectable(root,
    5968                 :             :                                                           onerel->relid,
    5969                 :             :                                                           NULL);
    5970                 :             : 
    5971                 :        1416 :                     break;
    5972                 :             :                 }
    5973                 :             : 
    5974                 :        1120 :                 pos++;
    5975                 :             :             }
    5976                 :             :         }
    5977                 :             :     }
    5978                 :             : 
    5979                 :      731060 :     bms_free(varnos);
    5980                 :             : }
    5981                 :             : 
    5982                 :             : /*
    5983                 :             :  * strip_all_phvs_deep
    5984                 :             :  *      Deeply strip all PlaceHolderVars in an expression.
    5985                 :             :  *
    5986                 :             :  * As a performance optimization, we first use a lightweight walker to check
    5987                 :             :  * for the presence of any PlaceHolderVars.  The expensive mutator is invoked
    5988                 :             :  * only if a PlaceHolderVar is found, avoiding unnecessary memory allocation
    5989                 :             :  * and tree copying in the common case where no PlaceHolderVars are present.
    5990                 :             :  */
    5991                 :             : static Node *
    5992                 :     2500170 : strip_all_phvs_deep(PlannerInfo *root, Node *node)
    5993                 :             : {
    5994                 :             :     /* If there are no PHVs anywhere, we needn't work hard */
    5995         [ +  + ]:     2500170 :     if (root->glob->lastPHId == 0)
    5996                 :     2474034 :         return node;
    5997                 :             : 
    5998         [ +  + ]:       26136 :     if (!contain_placeholder_walker(node, NULL))
    5999                 :       22398 :         return node;
    6000                 :        3738 :     return strip_all_phvs_mutator(node, NULL);
    6001                 :             : }
    6002                 :             : 
    6003                 :             : /*
    6004                 :             :  * contain_placeholder_walker
    6005                 :             :  *      Lightweight walker to check if an expression contains any
    6006                 :             :  *      PlaceHolderVars
    6007                 :             :  */
    6008                 :             : static bool
    6009                 :       29440 : contain_placeholder_walker(Node *node, void *context)
    6010                 :             : {
    6011         [ +  + ]:       29440 :     if (node == NULL)
    6012                 :         109 :         return false;
    6013         [ +  + ]:       29331 :     if (IsA(node, PlaceHolderVar))
    6014                 :        3738 :         return true;
    6015                 :             : 
    6016                 :       25593 :     return expression_tree_walker(node, contain_placeholder_walker, context);
    6017                 :             : }
    6018                 :             : 
    6019                 :             : /*
    6020                 :             :  * strip_all_phvs_mutator
    6021                 :             :  *      Mutator to deeply strip all PlaceHolderVars
    6022                 :             :  */
    6023                 :             : static Node *
    6024                 :        9929 : strip_all_phvs_mutator(Node *node, void *context)
    6025                 :             : {
    6026         [ +  + ]:        9929 :     if (node == NULL)
    6027                 :          34 :         return NULL;
    6028         [ +  + ]:        9895 :     if (IsA(node, PlaceHolderVar))
    6029                 :             :     {
    6030                 :             :         /* Strip it and recurse into its contained expression */
    6031                 :        3858 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
    6032                 :             : 
    6033                 :        3858 :         return strip_all_phvs_mutator((Node *) phv->phexpr, context);
    6034                 :             :     }
    6035                 :             : 
    6036                 :        6037 :     return expression_tree_mutator(node, strip_all_phvs_mutator, context);
    6037                 :             : }
    6038                 :             : 
    6039                 :             : /*
    6040                 :             :  * examine_simple_variable
    6041                 :             :  *      Handle a simple Var for examine_variable
    6042                 :             :  *
    6043                 :             :  * This is split out as a subroutine so that we can recurse to deal with
    6044                 :             :  * Vars referencing subqueries (either sub-SELECT-in-FROM or CTE style).
    6045                 :             :  *
    6046                 :             :  * We already filled in all the fields of *vardata except for the stats tuple.
    6047                 :             :  */
    6048                 :             : static void
    6049                 :     1778559 : examine_simple_variable(PlannerInfo *root, Var *var,
    6050                 :             :                         VariableStatData *vardata)
    6051                 :             : {
    6052                 :     1778559 :     RangeTblEntry *rte = root->simple_rte_array[var->varno];
    6053                 :             : 
    6054                 :             :     Assert(IsA(rte, RangeTblEntry));
    6055                 :             : 
    6056   [ -  +  -  - ]:     1778559 :     if (get_relation_stats_hook &&
    6057                 :           0 :         (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
    6058                 :             :     {
    6059                 :             :         /*
    6060                 :             :          * The hook took control of acquiring a stats tuple.  If it did supply
    6061                 :             :          * a tuple, it'd better have supplied a freefunc.
    6062                 :             :          */
    6063         [ #  # ]:           0 :         if (HeapTupleIsValid(vardata->statsTuple) &&
    6064         [ #  # ]:           0 :             !vardata->freefunc)
    6065         [ #  # ]:           0 :             elog(ERROR, "no function provided to release variable stats with");
    6066                 :             :     }
    6067         [ +  + ]:     1778559 :     else if (rte->rtekind == RTE_RELATION)
    6068                 :             :     {
    6069                 :             :         /*
    6070                 :             :          * Plain table or parent of an inheritance appendrel, so look up the
    6071                 :             :          * column in pg_statistic
    6072                 :             :          */
    6073                 :     1687224 :         vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    6074                 :             :                                               ObjectIdGetDatum(rte->relid),
    6075                 :     1687224 :                                               Int16GetDatum(var->varattno),
    6076                 :     1687224 :                                               BoolGetDatum(rte->inh));
    6077                 :     1687224 :         vardata->freefunc = ReleaseSysCache;
    6078                 :             : 
    6079         [ +  + ]:     1687224 :         if (HeapTupleIsValid(vardata->statsTuple))
    6080                 :             :         {
    6081                 :             :             /*
    6082                 :             :              * Test if user has permission to read all rows from this column.
    6083                 :             :              *
    6084                 :             :              * This requires that the user has the appropriate SELECT
    6085                 :             :              * privileges and that there are no securityQuals from security
    6086                 :             :              * barrier views or RLS policies.  If that's not the case, then we
    6087                 :             :              * only permit leakproof functions to be passed pg_statistic data
    6088                 :             :              * in vardata, otherwise the functions might reveal data that the
    6089                 :             :              * user doesn't have permission to see --- see
    6090                 :             :              * statistic_proc_security_check().
    6091                 :             :              */
    6092                 :     1087622 :             vardata->acl_ok =
    6093                 :     1087622 :                 all_rows_selectable(root, var->varno,
    6094                 :     1087622 :                                     bms_make_singleton(var->varattno - FirstLowInvalidHeapAttributeNumber));
    6095                 :             :         }
    6096                 :             :         else
    6097                 :             :         {
    6098                 :             :             /* suppress any possible leakproofness checks later */
    6099                 :      599602 :             vardata->acl_ok = true;
    6100                 :             :         }
    6101                 :             :     }
    6102   [ +  +  +  + ]:       91335 :     else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
    6103   [ +  +  +  + ]:       83210 :              (rte->rtekind == RTE_CTE && !rte->self_reference))
    6104                 :             :     {
    6105                 :             :         /*
    6106                 :             :          * Plain subquery (not one that was converted to an appendrel) or
    6107                 :             :          * non-recursive CTE.  In either case, we can try to find out what the
    6108                 :             :          * Var refers to within the subquery.  We skip this for appendrel and
    6109                 :             :          * recursive-CTE cases because any column stats we did find would
    6110                 :             :          * likely not be very relevant.
    6111                 :             :          */
    6112                 :             :         PlannerInfo *subroot;
    6113                 :             :         Query      *subquery;
    6114                 :             :         List       *subtlist;
    6115                 :             :         TargetEntry *ste;
    6116                 :       17052 :         bool        have_grouping = false;
    6117                 :             : 
    6118                 :             :         /*
    6119                 :             :          * Punt if it's a whole-row var rather than a plain column reference.
    6120                 :             :          */
    6121         [ -  + ]:       17052 :         if (var->varattno == InvalidAttrNumber)
    6122                 :           0 :             return;
    6123                 :             : 
    6124                 :             :         /*
    6125                 :             :          * Otherwise, find the subquery's planner subroot.
    6126                 :             :          */
    6127         [ +  + ]:       17052 :         if (rte->rtekind == RTE_SUBQUERY)
    6128                 :             :         {
    6129                 :             :             RelOptInfo *rel;
    6130                 :             : 
    6131                 :             :             /*
    6132                 :             :              * Fetch RelOptInfo for subquery.  Note that we don't change the
    6133                 :             :              * rel returned in vardata, since caller expects it to be a rel of
    6134                 :             :              * the caller's query level.  Because we might already be
    6135                 :             :              * recursing, we can't use that rel pointer either, but have to
    6136                 :             :              * look up the Var's rel afresh.
    6137                 :             :              */
    6138                 :        8125 :             rel = find_base_rel(root, var->varno);
    6139                 :             : 
    6140                 :        8125 :             subroot = rel->subroot;
    6141                 :             :         }
    6142                 :             :         else
    6143                 :             :         {
    6144                 :             :             /* CTE case is more difficult */
    6145                 :             :             PlannerInfo *cteroot;
    6146                 :             :             Index       levelsup;
    6147                 :             :             int         ndx;
    6148                 :             :             int         plan_id;
    6149                 :             :             ListCell   *lc;
    6150                 :             : 
    6151                 :             :             /*
    6152                 :             :              * Find the referenced CTE, and locate the subroot previously made
    6153                 :             :              * for it.
    6154                 :             :              */
    6155                 :        8927 :             levelsup = rte->ctelevelsup;
    6156                 :        8927 :             cteroot = root;
    6157         [ +  + ]:       21363 :             while (levelsup-- > 0)
    6158                 :             :             {
    6159                 :       12436 :                 cteroot = cteroot->parent_root;
    6160         [ -  + ]:       12436 :                 if (!cteroot)   /* shouldn't happen */
    6161         [ #  # ]:           0 :                     elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    6162                 :             :             }
    6163                 :             : 
    6164                 :             :             /*
    6165                 :             :              * Note: cte_plan_ids can be shorter than cteList, if we are still
    6166                 :             :              * working on planning the CTEs (ie, this is a side-reference from
    6167                 :             :              * another CTE).  So we mustn't use forboth here.
    6168                 :             :              */
    6169                 :        8927 :             ndx = 0;
    6170   [ +  -  +  -  :       13105 :             foreach(lc, cteroot->parse->cteList)
                   +  - ]
    6171                 :             :             {
    6172                 :       13105 :                 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
    6173                 :             : 
    6174         [ +  + ]:       13105 :                 if (strcmp(cte->ctename, rte->ctename) == 0)
    6175                 :        8927 :                     break;
    6176                 :        4178 :                 ndx++;
    6177                 :             :             }
    6178         [ -  + ]:        8927 :             if (lc == NULL)     /* shouldn't happen */
    6179         [ #  # ]:           0 :                 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
    6180         [ -  + ]:        8927 :             if (ndx >= list_length(cteroot->cte_plan_ids))
    6181         [ #  # ]:           0 :                 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
    6182                 :        8927 :             plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
    6183         [ -  + ]:        8927 :             if (plan_id <= 0)
    6184         [ #  # ]:           0 :                 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
    6185                 :        8927 :             subroot = list_nth(root->glob->subroots, plan_id - 1);
    6186                 :             :         }
    6187                 :             : 
    6188                 :             :         /* If the subquery hasn't been planned yet, we have to punt */
    6189         [ -  + ]:       17052 :         if (subroot == NULL)
    6190                 :           0 :             return;
    6191                 :             :         Assert(IsA(subroot, PlannerInfo));
    6192                 :             : 
    6193                 :             :         /*
    6194                 :             :          * We must use the subquery parsetree as mangled by the planner, not
    6195                 :             :          * the raw version from the RTE, because we need a Var that will refer
    6196                 :             :          * to the subroot's live RelOptInfos.  For instance, if any subquery
    6197                 :             :          * pullup happened during planning, Vars in the targetlist might have
    6198                 :             :          * gotten replaced, and we need to see the replacement expressions.
    6199                 :             :          */
    6200                 :       17052 :         subquery = subroot->parse;
    6201                 :             :         Assert(IsA(subquery, Query));
    6202                 :             : 
    6203                 :             :         /*
    6204                 :             :          * Punt if subquery uses set operations or grouping sets, as these
    6205                 :             :          * will mash underlying columns' stats beyond recognition.  (Set ops
    6206                 :             :          * are particularly nasty; if we forged ahead, we would return stats
    6207                 :             :          * relevant to only the leftmost subselect...)  DISTINCT and GROUP BY
    6208                 :             :          * are also problematic, but we check those later because there is a
    6209                 :             :          * possibility of learning something even with them: we can detect
    6210                 :             :          * uniqueness for single-column cases, and for key columns that are
    6211                 :             :          * simple Vars, we can obtain a useful stadistinct from the underlying
    6212                 :             :          * base table.
    6213                 :             :          */
    6214         [ +  + ]:       17052 :         if (subquery->setOperations ||
    6215         [ +  + ]:       15329 :             subquery->groupingSets)
    6216                 :        1800 :             return;
    6217                 :             : 
    6218                 :             :         /* Get the subquery output expression referenced by the upper Var */
    6219         [ +  + ]:       15252 :         if (subquery->returningList)
    6220                 :         179 :             subtlist = subquery->returningList;
    6221                 :             :         else
    6222                 :       15073 :             subtlist = subquery->targetList;
    6223                 :       15252 :         ste = get_tle_by_resno(subtlist, var->varattno);
    6224   [ +  -  -  + ]:       15252 :         if (ste == NULL || ste->resjunk)
    6225         [ #  # ]:           0 :             elog(ERROR, "subquery %s does not have attribute %d",
    6226                 :             :                  rte->eref->aliasname, var->varattno);
    6227                 :       15252 :         var = (Var *) ste->expr;
    6228                 :             : 
    6229                 :             :         /*
    6230                 :             :          * If subquery uses DISTINCT, we can't make full use of stats for the
    6231                 :             :          * variable ... but, if it's the only DISTINCT column, we are entitled
    6232                 :             :          * to consider it unique.  We do the test this way so that it works
    6233                 :             :          * for cases involving DISTINCT ON.
    6234                 :             :          *
    6235                 :             :          * If the target is a DISTINCT key that is a simple Var, we can still
    6236                 :             :          * obtain a useful stadistinct from the base table, though the
    6237                 :             :          * frequency-dependent stats must be adjusted since DISTINCT changes
    6238                 :             :          * the frequency distribution.  We set have_grouping and fall through
    6239                 :             :          * to the simple-Var recursion below.  Non-key columns cannot go
    6240                 :             :          * further.
    6241                 :             :          */
    6242         [ +  + ]:       15252 :         if (subquery->distinctClause)
    6243                 :             :         {
    6244         [ +  + ]:        1491 :             if (targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
    6245                 :             :             {
    6246                 :         845 :                 have_grouping = true;
    6247                 :             : 
    6248         [ +  + ]:         845 :                 if (list_length(subquery->distinctClause) == 1)
    6249                 :         374 :                     vardata->isunique = true;
    6250                 :             :             }
    6251                 :             :             else
    6252                 :         646 :                 return;
    6253                 :             :         }
    6254                 :             : 
    6255                 :             :         /* The same idea as with DISTINCT clause works for a GROUP-BY too */
    6256         [ +  + ]:       14606 :         if (subquery->groupClause)
    6257                 :             :         {
    6258         [ +  + ]:         619 :             if (targetIsInSortList(ste, InvalidOid, subquery->groupClause))
    6259                 :             :             {
    6260                 :         485 :                 have_grouping = true;
    6261                 :             : 
    6262         [ +  + ]:         485 :                 if (list_length(subquery->groupClause) == 1)
    6263                 :         322 :                     vardata->isunique = true;
    6264                 :             :             }
    6265         [ +  - ]:         134 :             else if (!have_grouping)
    6266                 :         134 :                 return;
    6267                 :             :         }
    6268                 :             : 
    6269                 :             :         /*
    6270                 :             :          * If the sub-query originated from a view with the security_barrier
    6271                 :             :          * attribute, we must not look at the variable's statistics, though it
    6272                 :             :          * seems all right to notice the existence of a DISTINCT clause. So
    6273                 :             :          * stop here.
    6274                 :             :          *
    6275                 :             :          * This is probably a harsher restriction than necessary; it's
    6276                 :             :          * certainly OK for the selectivity estimator (which is a C function,
    6277                 :             :          * and therefore omnipotent anyway) to look at the statistics.  But
    6278                 :             :          * many selectivity estimators will happily *invoke the operator
    6279                 :             :          * function* to try to work out a good estimate - and that's not OK.
    6280                 :             :          * So for now, don't dig down for stats.
    6281                 :             :          */
    6282         [ +  + ]:       14472 :         if (rte->security_barrier)
    6283                 :         488 :             return;
    6284                 :             : 
    6285                 :             :         /* Can only handle a simple Var of subquery's query level */
    6286   [ +  -  +  + ]:       13984 :         if (var && IsA(var, Var) &&
    6287         [ +  - ]:        9449 :             var->varlevelsup == 0)
    6288                 :             :         {
    6289                 :             :             /*
    6290                 :             :              * OK, recurse into the subquery.  Note that the original setting
    6291                 :             :              * of vardata->isunique (which will surely be false) is left
    6292                 :             :              * unchanged in this situation.  That's what we want, since even
    6293                 :             :              * if the underlying column is unique, the subquery may have
    6294                 :             :              * joined to other tables in a way that creates duplicates.
    6295                 :             :              */
    6296                 :        9449 :             examine_simple_variable(subroot, var, vardata);
    6297                 :             : 
    6298                 :             :             /*
    6299                 :             :              * If the subquery uses DISTINCT or GROUP BY and we got here
    6300                 :             :              * because the target is a key column, adjust the recursively
    6301                 :             :              * obtained stats tuple for the grouped context.
    6302                 :             :              */
    6303         [ +  + ]:        9449 :             if (have_grouping)
    6304                 :        1195 :                 adjust_statstuple_for_grouping(subroot, var, vardata);
    6305                 :             :         }
    6306                 :             :     }
    6307                 :             :     else
    6308                 :             :     {
    6309                 :             :         /*
    6310                 :             :          * Otherwise, the Var comes from a FUNCTION or VALUES RTE.  (We won't
    6311                 :             :          * see RTE_JOIN here because join alias Vars have already been
    6312                 :             :          * flattened.)  There's not much we can do with function outputs, but
    6313                 :             :          * maybe someday try to be smarter about VALUES.
    6314                 :             :          */
    6315                 :             :     }
    6316                 :             : }
    6317                 :             : 
    6318                 :             : /*
    6319                 :             :  * adjust_statstuple_for_grouping
    6320                 :             :  *      Adjust a stats tuple for use in a grouped or distinct context.
    6321                 :             :  *
    6322                 :             :  * This is used when the stats tuple was obtained by recursing into a subquery,
    6323                 :             :  * but the subquery's output invalidates frequency-related statistics (e.g. due
    6324                 :             :  * to GROUP BY or DISTINCT).  The set of distinct values is preserved by such
    6325                 :             :  * operations, so stadistinct remains valid, but MCV frequencies, histograms,
    6326                 :             :  * and correlation data are not.  Zeroing all stats slots causes callers (e.g.
    6327                 :             :  * var_eq_const) to fall through to the 1/ndistinct estimate instead.
    6328                 :             :  *
    6329                 :             :  * stanullfrac must also be adjusted.  When this column is the only GROUP BY or
    6330                 :             :  * DISTINCT column, its NULLs are collapsed into one group, so the null
    6331                 :             :  * fraction is 1/(ndistinct+1) if the base column had NULLs.  With multiple
    6332                 :             :  * grouping columns a NULL can pair with many combinations of the other keys,
    6333                 :             :  * so the null fraction depends on their joint distribution, which we don't
    6334                 :             :  * have.  We approximate it as zero: NULLs collapse far more aggressively than
    6335                 :             :  * non-NULLs, so the output fraction is well below the base table's, and erring
    6336                 :             :  * low keeps estimates on the hash-join-favoring side.
    6337                 :             :  *
    6338                 :             :  * If stadistinct is negative (a fraction of the base table's row count), we
    6339                 :             :  * convert it to an absolute count, since it would otherwise be misinterpreted
    6340                 :             :  * relative to the subquery output's row count.
    6341                 :             :  */
    6342                 :             : static void
    6343                 :        1195 : adjust_statstuple_for_grouping(PlannerInfo *subroot, Var *var,
    6344                 :             :                                VariableStatData *vardata)
    6345                 :             : {
    6346                 :             :     HeapTuple   copy;
    6347                 :             :     Form_pg_statistic stats;
    6348                 :             : 
    6349         [ +  + ]:        1195 :     if (!HeapTupleIsValid(vardata->statsTuple))
    6350                 :         621 :         return;
    6351                 :             : 
    6352                 :         574 :     copy = heap_copytuple(vardata->statsTuple);
    6353                 :         574 :     stats = (Form_pg_statistic) GETSTRUCT(copy);
    6354                 :             : 
    6355                 :             :     /* Convert negative stadistinct to absolute count */
    6356         [ +  + ]:         574 :     if (stats->stadistinct < 0)
    6357                 :             :     {
    6358                 :         340 :         RelOptInfo *baserel = find_base_rel(subroot, var->varno);
    6359                 :             : 
    6360         [ +  - ]:         340 :         if (baserel->tuples > 0)
    6361                 :             :         {
    6362                 :         340 :             stats->stadistinct = (float4)
    6363                 :         340 :                 clamp_row_est(-stats->stadistinct * baserel->tuples);
    6364                 :             :         }
    6365                 :             :     }
    6366                 :             : 
    6367                 :             :     /* Zero out all stats slots */
    6368         [ +  + ]:        3444 :     for (int k = 0; k < STATISTIC_NUM_SLOTS; k++)
    6369                 :        2870 :         (&stats->stakind1)[k] = 0;
    6370                 :             : 
    6371                 :             :     /* Adjust the null fraction (see comment above). */
    6372   [ +  +  -  +  :         574 :     if (vardata->isunique && stats->stanullfrac > 0.0 && stats->stadistinct > 0)
                   -  - ]
    6373                 :           0 :         stats->stanullfrac = 1.0 / (stats->stadistinct + 1.0);
    6374                 :             :     else
    6375                 :         574 :         stats->stanullfrac = 0.0;
    6376                 :             : 
    6377                 :             :     /* Replace original with our modified copy */
    6378                 :         574 :     vardata->freefunc(vardata->statsTuple);
    6379                 :         574 :     vardata->statsTuple = copy;
    6380                 :         574 :     vardata->freefunc = heap_freetuple;
    6381                 :             : }
    6382                 :             : 
    6383                 :             : /*
    6384                 :             :  * all_rows_selectable
    6385                 :             :  *      Test whether the user has permission to select all rows from a given
    6386                 :             :  *      relation.
    6387                 :             :  *
    6388                 :             :  * Inputs:
    6389                 :             :  *  root: the planner info
    6390                 :             :  *  varno: the index of the relation (assumed to be an RTE_RELATION)
    6391                 :             :  *  varattnos: the attributes for which permission is required, or NULL if
    6392                 :             :  *      whole-table access is required
    6393                 :             :  *
    6394                 :             :  * Returns true if the user has the required select permissions, and there are
    6395                 :             :  * no securityQuals from security barrier views or RLS policies.
    6396                 :             :  *
    6397                 :             :  * Note that if the relation is an inheritance child relation, securityQuals
    6398                 :             :  * and access permissions are checked against the inheritance root parent (the
    6399                 :             :  * relation actually mentioned in the query) --- see the comments in
    6400                 :             :  * expand_single_inheritance_child() for an explanation of why it has to be
    6401                 :             :  * done this way.
    6402                 :             :  *
    6403                 :             :  * If varattnos is non-NULL, its attribute numbers should be offset by
    6404                 :             :  * FirstLowInvalidHeapAttributeNumber so that system attributes can be
    6405                 :             :  * checked.  If varattnos is NULL, only table-level SELECT privileges are
    6406                 :             :  * checked, not any column-level privileges.
    6407                 :             :  *
    6408                 :             :  * Note: if the relation is accessed via a view, this function actually tests
    6409                 :             :  * whether the view owner has permission to select from the relation.  To
    6410                 :             :  * ensure that the current user has permission, it is also necessary to check
    6411                 :             :  * that the current user has permission to select from the view, which we do
    6412                 :             :  * at planner-startup --- see subquery_planner().
    6413                 :             :  *
    6414                 :             :  * This is exported so that other estimation functions can use it.
    6415                 :             :  */
    6416                 :             : bool
    6417                 :     1091625 : all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
    6418                 :             : {
    6419                 :     1091625 :     RelOptInfo *rel = find_base_rel_noerr(root, varno);
    6420         [ +  - ]:     1091625 :     RangeTblEntry *rte = planner_rt_fetch(varno, root);
    6421                 :             :     Oid         userid;
    6422                 :             :     int         varattno;
    6423                 :             : 
    6424                 :             :     Assert(rte->rtekind == RTE_RELATION);
    6425                 :             : 
    6426                 :             :     /*
    6427                 :             :      * Determine the user ID to use for privilege checks (either the current
    6428                 :             :      * user or the view owner, if we're accessing the table via a view).
    6429                 :             :      *
    6430                 :             :      * Normally the relation will have an associated RelOptInfo from which we
    6431                 :             :      * can find the userid, but it might not if it's a RETURNING Var for an
    6432                 :             :      * INSERT target relation.  In that case use the RTEPermissionInfo
    6433                 :             :      * associated with the RTE.
    6434                 :             :      *
    6435                 :             :      * If we navigate up to a parent relation, we keep using the same userid,
    6436                 :             :      * since it's the same in all relations of a given inheritance tree.
    6437                 :             :      */
    6438         [ +  + ]:     1091625 :     if (rel)
    6439                 :     1091592 :         userid = rel->userid;
    6440                 :             :     else
    6441                 :             :     {
    6442                 :             :         RTEPermissionInfo *perminfo;
    6443                 :             : 
    6444                 :          33 :         perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
    6445                 :          33 :         userid = perminfo->checkAsUser;
    6446                 :             :     }
    6447         [ +  + ]:     1091625 :     if (!OidIsValid(userid))
    6448                 :      970757 :         userid = GetUserId();
    6449                 :             : 
    6450                 :             :     /*
    6451                 :             :      * Permissions and securityQuals must be checked on the table actually
    6452                 :             :      * mentioned in the query, so if this is an inheritance child, navigate up
    6453                 :             :      * to the inheritance root parent.  If the user can read the whole table
    6454                 :             :      * or the required columns there, then they can read from the child table
    6455                 :             :      * too.  For per-column checks, we must find out which of the root
    6456                 :             :      * parent's attributes the child relation's attributes correspond to.
    6457                 :             :      */
    6458         [ +  + ]:     1091625 :     if (root->append_rel_array != NULL)
    6459                 :             :     {
    6460                 :             :         AppendRelInfo *appinfo;
    6461                 :             : 
    6462                 :      177748 :         appinfo = root->append_rel_array[varno];
    6463                 :             : 
    6464                 :             :         /*
    6465                 :             :          * Partitions are mapped to their immediate parent, not the root
    6466                 :             :          * parent, so must be ready to walk up multiple AppendRelInfos.  But
    6467                 :             :          * stop if we hit a parent that is not RTE_RELATION --- that's a
    6468                 :             :          * flattened UNION ALL subquery, not an inheritance parent.
    6469                 :             :          */
    6470         [ +  + ]:      334090 :         while (appinfo &&
    6471         [ +  - ]:      156727 :                planner_rt_fetch(appinfo->parent_relid,
    6472         [ +  + ]:      156727 :                                 root)->rtekind == RTE_RELATION)
    6473                 :             :         {
    6474                 :      156342 :             Bitmapset  *parent_varattnos = NULL;
    6475                 :             : 
    6476                 :             :             /*
    6477                 :             :              * For each child attribute, find the corresponding parent
    6478                 :             :              * attribute.  In rare cases, the attribute may be local to the
    6479                 :             :              * child table, in which case, we've got to live with having no
    6480                 :             :              * access to this column.
    6481                 :             :              */
    6482                 :      156342 :             varattno = -1;
    6483         [ +  + ]:      310417 :             while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
    6484                 :             :             {
    6485                 :             :                 AttrNumber  attno;
    6486                 :             :                 AttrNumber  parent_attno;
    6487                 :             : 
    6488                 :      154075 :                 attno = varattno + FirstLowInvalidHeapAttributeNumber;
    6489                 :             : 
    6490         [ +  + ]:      154075 :                 if (attno == InvalidAttrNumber)
    6491                 :             :                 {
    6492                 :             :                     /*
    6493                 :             :                      * Whole-row reference, so must map each column of the
    6494                 :             :                      * child to the parent table.
    6495                 :             :                      */
    6496         [ +  + ]:          30 :                     for (attno = 1; attno <= appinfo->num_child_cols; attno++)
    6497                 :             :                     {
    6498                 :          20 :                         parent_attno = appinfo->parent_colnos[attno - 1];
    6499         [ -  + ]:          20 :                         if (parent_attno == 0)
    6500                 :           0 :                             return false;   /* attr is local to child */
    6501                 :             :                         parent_varattnos =
    6502                 :          20 :                             bms_add_member(parent_varattnos,
    6503                 :             :                                            parent_attno - FirstLowInvalidHeapAttributeNumber);
    6504                 :             :                     }
    6505                 :             :                 }
    6506                 :             :                 else
    6507                 :             :                 {
    6508         [ -  + ]:      154065 :                     if (attno < 0)
    6509                 :             :                     {
    6510                 :             :                         /* System attnos are the same in all tables */
    6511                 :           0 :                         parent_attno = attno;
    6512                 :             :                     }
    6513                 :             :                     else
    6514                 :             :                     {
    6515         [ -  + ]:      154065 :                         if (attno > appinfo->num_child_cols)
    6516                 :           0 :                             return false;   /* safety check */
    6517                 :      154065 :                         parent_attno = appinfo->parent_colnos[attno - 1];
    6518         [ -  + ]:      154065 :                         if (parent_attno == 0)
    6519                 :           0 :                             return false;   /* attr is local to child */
    6520                 :             :                     }
    6521                 :             :                     parent_varattnos =
    6522                 :      154065 :                         bms_add_member(parent_varattnos,
    6523                 :             :                                        parent_attno - FirstLowInvalidHeapAttributeNumber);
    6524                 :             :                 }
    6525                 :             :             }
    6526                 :             : 
    6527                 :             :             /* If the parent is itself a child, continue up */
    6528                 :      156342 :             varno = appinfo->parent_relid;
    6529                 :      156342 :             varattnos = parent_varattnos;
    6530                 :      156342 :             appinfo = root->append_rel_array[varno];
    6531                 :             :         }
    6532                 :             : 
    6533                 :             :         /* Perform the access check on this parent rel */
    6534         [ +  - ]:      177748 :         rte = planner_rt_fetch(varno, root);
    6535                 :             :         Assert(rte->rtekind == RTE_RELATION);
    6536                 :             :     }
    6537                 :             : 
    6538                 :             :     /*
    6539                 :             :      * For all rows to be accessible, there must be no securityQuals from
    6540                 :             :      * security barrier views or RLS policies.
    6541                 :             :      */
    6542         [ +  + ]:     1091625 :     if (rte->securityQuals != NIL)
    6543                 :         690 :         return false;
    6544                 :             : 
    6545                 :             :     /*
    6546                 :             :      * Test for table-level SELECT privilege.
    6547                 :             :      *
    6548                 :             :      * If varattnos is non-NULL, this is sufficient to give access to all
    6549                 :             :      * requested attributes, even for a child table, since we have verified
    6550                 :             :      * that all required child columns have matching parent columns.
    6551                 :             :      *
    6552                 :             :      * If varattnos is NULL (whole-table access requested), this doesn't
    6553                 :             :      * necessarily guarantee that the user can read all columns of a child
    6554                 :             :      * table, but we allow it anyway (see comments in examine_variable()) and
    6555                 :             :      * don't bother checking any column privileges.
    6556                 :             :      */
    6557         [ +  + ]:     1090935 :     if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) == ACLCHECK_OK)
    6558                 :     1090592 :         return true;
    6559                 :             : 
    6560         [ +  + ]:         343 :     if (varattnos == NULL)
    6561                 :          10 :         return false;           /* whole-table access requested */
    6562                 :             : 
    6563                 :             :     /*
    6564                 :             :      * Don't have table-level SELECT privilege, so check per-column
    6565                 :             :      * privileges.
    6566                 :             :      */
    6567                 :         333 :     varattno = -1;
    6568         [ +  + ]:         471 :     while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
    6569                 :             :     {
    6570                 :         333 :         AttrNumber  attno = varattno + FirstLowInvalidHeapAttributeNumber;
    6571                 :             : 
    6572         [ +  + ]:         333 :         if (attno == InvalidAttrNumber)
    6573                 :             :         {
    6574                 :             :             /* Whole-row reference, so must have access to all columns */
    6575         [ +  - ]:           5 :             if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
    6576                 :             :                                           ACLMASK_ALL) != ACLCHECK_OK)
    6577                 :           5 :                 return false;
    6578                 :             :         }
    6579                 :             :         else
    6580                 :             :         {
    6581         [ +  + ]:         328 :             if (pg_attribute_aclcheck(rte->relid, attno, userid,
    6582                 :             :                                       ACL_SELECT) != ACLCHECK_OK)
    6583                 :         190 :                 return false;
    6584                 :             :         }
    6585                 :             :     }
    6586                 :             : 
    6587                 :             :     /* If we reach here, have all required column privileges */
    6588                 :         138 :     return true;
    6589                 :             : }
    6590                 :             : 
    6591                 :             : /*
    6592                 :             :  * examine_indexcol_variable
    6593                 :             :  *      Try to look up statistical data about an index column/expression.
    6594                 :             :  *      Fill in a VariableStatData struct to describe the column.
    6595                 :             :  *
    6596                 :             :  * Inputs:
    6597                 :             :  *  root: the planner info
    6598                 :             :  *  index: the index whose column we're interested in
    6599                 :             :  *  indexcol: 0-based index column number (subscripts index->indexkeys[])
    6600                 :             :  *
    6601                 :             :  * Outputs: *vardata is filled as follows:
    6602                 :             :  *  var: the input expression (with any binary relabeling stripped, if
    6603                 :             :  *      it is or contains a variable; but otherwise the type is preserved)
    6604                 :             :  *  rel: RelOptInfo for table relation containing variable.
    6605                 :             :  *  statsTuple: the pg_statistic entry for the variable, if one exists;
    6606                 :             :  *      otherwise NULL.
    6607                 :             :  *  freefunc: pointer to a function to release statsTuple with.
    6608                 :             :  *
    6609                 :             :  * Caller is responsible for doing ReleaseVariableStats() before exiting.
    6610                 :             :  */
    6611                 :             : static void
    6612                 :      638341 : examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
    6613                 :             :                           int indexcol, VariableStatData *vardata)
    6614                 :             : {
    6615                 :             :     AttrNumber  colnum;
    6616                 :             :     Oid         relid;
    6617                 :             : 
    6618         [ +  + ]:      638341 :     if (index->indexkeys[indexcol] != 0)
    6619                 :             :     {
    6620                 :             :         /* Simple variable --- look to stats for the underlying table */
    6621         [ +  - ]:      636508 :         RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
    6622                 :             : 
    6623                 :             :         Assert(rte->rtekind == RTE_RELATION);
    6624                 :      636508 :         relid = rte->relid;
    6625                 :             :         Assert(relid != InvalidOid);
    6626                 :      636508 :         colnum = index->indexkeys[indexcol];
    6627                 :      636508 :         vardata->rel = index->rel;
    6628                 :             : 
    6629   [ -  +  -  - ]:      636508 :         if (get_relation_stats_hook &&
    6630                 :           0 :             (*get_relation_stats_hook) (root, rte, colnum, vardata))
    6631                 :             :         {
    6632                 :             :             /*
    6633                 :             :              * The hook took control of acquiring a stats tuple.  If it did
    6634                 :             :              * supply a tuple, it'd better have supplied a freefunc.
    6635                 :             :              */
    6636         [ #  # ]:           0 :             if (HeapTupleIsValid(vardata->statsTuple) &&
    6637         [ #  # ]:           0 :                 !vardata->freefunc)
    6638         [ #  # ]:           0 :                 elog(ERROR, "no function provided to release variable stats with");
    6639                 :             :         }
    6640                 :             :         else
    6641                 :             :         {
    6642                 :      636508 :             vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    6643                 :             :                                                   ObjectIdGetDatum(relid),
    6644                 :             :                                                   Int16GetDatum(colnum),
    6645                 :      636508 :                                                   BoolGetDatum(rte->inh));
    6646                 :      636508 :             vardata->freefunc = ReleaseSysCache;
    6647                 :             :         }
    6648                 :             :     }
    6649                 :             :     else
    6650                 :             :     {
    6651                 :             :         /* Expression --- maybe there are stats for the index itself */
    6652                 :        1833 :         relid = index->indexoid;
    6653                 :        1833 :         colnum = indexcol + 1;
    6654                 :             : 
    6655   [ -  +  -  - ]:        1833 :         if (get_index_stats_hook &&
    6656                 :           0 :             (*get_index_stats_hook) (root, relid, colnum, vardata))
    6657                 :             :         {
    6658                 :             :             /*
    6659                 :             :              * The hook took control of acquiring a stats tuple.  If it did
    6660                 :             :              * supply a tuple, it'd better have supplied a freefunc.
    6661                 :             :              */
    6662         [ #  # ]:           0 :             if (HeapTupleIsValid(vardata->statsTuple) &&
    6663         [ #  # ]:           0 :                 !vardata->freefunc)
    6664         [ #  # ]:           0 :                 elog(ERROR, "no function provided to release variable stats with");
    6665                 :             :         }
    6666                 :             :         else
    6667                 :             :         {
    6668                 :        1833 :             vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    6669                 :             :                                                   ObjectIdGetDatum(relid),
    6670                 :             :                                                   Int16GetDatum(colnum),
    6671                 :             :                                                   BoolGetDatum(false));
    6672                 :        1833 :             vardata->freefunc = ReleaseSysCache;
    6673                 :             :         }
    6674                 :             :     }
    6675                 :      638341 : }
    6676                 :             : 
    6677                 :             : /*
    6678                 :             :  * Check whether it is permitted to call func_oid passing some of the
    6679                 :             :  * pg_statistic data in vardata.  We allow this if either of the following
    6680                 :             :  * conditions is met: (1) the user has SELECT privileges on the table or
    6681                 :             :  * column underlying the pg_statistic data and there are no securityQuals from
    6682                 :             :  * security barrier views or RLS policies, or (2) the function is marked
    6683                 :             :  * leakproof.
    6684                 :             :  */
    6685                 :             : bool
    6686                 :      746356 : statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
    6687                 :             : {
    6688         [ +  + ]:      746356 :     if (vardata->acl_ok)
    6689                 :      744845 :         return true;            /* have SELECT privs and no securityQuals */
    6690                 :             : 
    6691         [ -  + ]:        1511 :     if (!OidIsValid(func_oid))
    6692                 :           0 :         return false;
    6693                 :             : 
    6694         [ +  + ]:        1511 :     if (get_func_leakproof(func_oid))
    6695                 :         748 :         return true;
    6696                 :             : 
    6697         [ -  + ]:         763 :     ereport(DEBUG2,
    6698                 :             :             (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
    6699                 :             :                              get_func_name(func_oid))));
    6700                 :         763 :     return false;
    6701                 :             : }
    6702                 :             : 
    6703                 :             : /*
    6704                 :             :  * get_variable_numdistinct
    6705                 :             :  *    Estimate the number of distinct values of a variable.
    6706                 :             :  *
    6707                 :             :  * vardata: results of examine_variable
    6708                 :             :  * *isdefault: set to true if the result is a default rather than based on
    6709                 :             :  * anything meaningful.
    6710                 :             :  *
    6711                 :             :  * NB: be careful to produce a positive integral result, since callers may
    6712                 :             :  * compare the result to exact integer counts, or might divide by it.
    6713                 :             :  */
    6714                 :             : double
    6715                 :     1258298 : get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
    6716                 :             : {
    6717                 :             :     double      stadistinct;
    6718                 :     1258298 :     double      stanullfrac = 0.0;
    6719                 :             :     double      ntuples;
    6720                 :             : 
    6721                 :     1258298 :     *isdefault = false;
    6722                 :             : 
    6723                 :             :     /*
    6724                 :             :      * Determine the stadistinct value to use.  There are cases where we can
    6725                 :             :      * get an estimate even without a pg_statistic entry, or can get a better
    6726                 :             :      * value than is in pg_statistic.  Grab stanullfrac too if we can find it
    6727                 :             :      * (otherwise, assume no nulls, for lack of any better idea).
    6728                 :             :      */
    6729         [ +  + ]:     1258298 :     if (HeapTupleIsValid(vardata->statsTuple))
    6730                 :             :     {
    6731                 :             :         /* Use the pg_statistic entry */
    6732                 :             :         Form_pg_statistic stats;
    6733                 :             : 
    6734                 :      764483 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
    6735                 :      764483 :         stadistinct = stats->stadistinct;
    6736                 :      764483 :         stanullfrac = stats->stanullfrac;
    6737                 :             :     }
    6738         [ +  + ]:      493815 :     else if (vardata->vartype == BOOLOID)
    6739                 :             :     {
    6740                 :             :         /*
    6741                 :             :          * Special-case boolean columns: presumably, two distinct values.
    6742                 :             :          *
    6743                 :             :          * Are there any other datatypes we should wire in special estimates
    6744                 :             :          * for?
    6745                 :             :          */
    6746                 :         685 :         stadistinct = 2.0;
    6747                 :             :     }
    6748   [ +  +  +  + ]:      493130 :     else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
    6749                 :             :     {
    6750                 :             :         /*
    6751                 :             :          * If the Var represents a column of a VALUES RTE, assume it's unique.
    6752                 :             :          * This could of course be very wrong, but it should tend to be true
    6753                 :             :          * in well-written queries.  We could consider examining the VALUES'
    6754                 :             :          * contents to get some real statistics; but that only works if the
    6755                 :             :          * entries are all constants, and it would be pretty expensive anyway.
    6756                 :             :          */
    6757                 :        3163 :         stadistinct = -1.0;     /* unique (and all non null) */
    6758                 :             :     }
    6759                 :             :     else
    6760                 :             :     {
    6761                 :             :         /*
    6762                 :             :          * We don't keep statistics for system columns, but in some cases we
    6763                 :             :          * can infer distinctness anyway.
    6764                 :             :          */
    6765   [ +  +  +  + ]:      489967 :         if (vardata->var && IsA(vardata->var, Var))
    6766                 :             :         {
    6767      [ +  +  + ]:      459827 :             switch (((Var *) vardata->var)->varattno)
    6768                 :             :             {
    6769                 :         858 :                 case SelfItemPointerAttributeNumber:
    6770                 :         858 :                     stadistinct = -1.0; /* unique (and all non null) */
    6771                 :         858 :                     break;
    6772                 :       14053 :                 case TableOidAttributeNumber:
    6773                 :       14053 :                     stadistinct = 1.0;  /* only 1 value */
    6774                 :       14053 :                     break;
    6775                 :      444916 :                 default:
    6776                 :      444916 :                     stadistinct = 0.0;  /* means "unknown" */
    6777                 :      444916 :                     break;
    6778                 :             :             }
    6779                 :             :         }
    6780                 :             :         else
    6781                 :       30140 :             stadistinct = 0.0;  /* means "unknown" */
    6782                 :             : 
    6783                 :             :         /*
    6784                 :             :          * XXX consider using estimate_num_groups on expressions?
    6785                 :             :          */
    6786                 :             :     }
    6787                 :             : 
    6788                 :             :     /*
    6789                 :             :      * If there is a unique index, DISTINCT or GROUP-BY clause for the
    6790                 :             :      * variable, assume it is unique no matter what pg_statistic says; the
    6791                 :             :      * statistics could be out of date, or we might have found a partial
    6792                 :             :      * unique index that proves the var is unique for this query.  However,
    6793                 :             :      * we'd better still believe the null-fraction statistic.
    6794                 :             :      */
    6795         [ +  + ]:     1258298 :     if (vardata->isunique)
    6796                 :      301000 :         stadistinct = -1.0 * (1.0 - stanullfrac);
    6797                 :             : 
    6798                 :             :     /*
    6799                 :             :      * If we had an absolute estimate, use that.
    6800                 :             :      */
    6801         [ +  + ]:     1258298 :     if (stadistinct > 0.0)
    6802                 :      303970 :         return clamp_row_est(stadistinct);
    6803                 :             : 
    6804                 :             :     /*
    6805                 :             :      * Otherwise we need to get the relation size; punt if not available.
    6806                 :             :      */
    6807         [ +  + ]:      954328 :     if (vardata->rel == NULL)
    6808                 :             :     {
    6809                 :         589 :         *isdefault = true;
    6810                 :         589 :         return DEFAULT_NUM_DISTINCT;
    6811                 :             :     }
    6812                 :      953739 :     ntuples = vardata->rel->tuples;
    6813         [ +  + ]:      953739 :     if (ntuples <= 0.0)
    6814                 :             :     {
    6815                 :       99090 :         *isdefault = true;
    6816                 :       99090 :         return DEFAULT_NUM_DISTINCT;
    6817                 :             :     }
    6818                 :             : 
    6819                 :             :     /*
    6820                 :             :      * If we had a relative estimate, use that.
    6821                 :             :      */
    6822         [ +  + ]:      854649 :     if (stadistinct < 0.0)
    6823                 :      532228 :         return clamp_row_est(-stadistinct * ntuples);
    6824                 :             : 
    6825                 :             :     /*
    6826                 :             :      * With no data, estimate ndistinct = ntuples if the table is small, else
    6827                 :             :      * use default.  We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
    6828                 :             :      * that the behavior isn't discontinuous.
    6829                 :             :      */
    6830         [ +  + ]:      322421 :     if (ntuples < DEFAULT_NUM_DISTINCT)
    6831                 :      162752 :         return clamp_row_est(ntuples);
    6832                 :             : 
    6833                 :      159669 :     *isdefault = true;
    6834                 :      159669 :     return DEFAULT_NUM_DISTINCT;
    6835                 :             : }
    6836                 :             : 
    6837                 :             : /*
    6838                 :             :  * get_variable_range
    6839                 :             :  *      Estimate the minimum and maximum value of the specified variable.
    6840                 :             :  *      If successful, store values in *min and *max, and return true.
    6841                 :             :  *      If no data available, return false.
    6842                 :             :  *
    6843                 :             :  * sortop is the "<" comparison operator to use.  This should generally
    6844                 :             :  * be "<" not ">", as only the former is likely to be found in pg_statistic.
    6845                 :             :  * The collation must be specified too.
    6846                 :             :  */
    6847                 :             : static bool
    6848                 :      165962 : get_variable_range(PlannerInfo *root, VariableStatData *vardata,
    6849                 :             :                    Oid sortop, Oid collation,
    6850                 :             :                    Datum *min, Datum *max)
    6851                 :             : {
    6852                 :      165962 :     Datum       tmin = 0;
    6853                 :      165962 :     Datum       tmax = 0;
    6854                 :      165962 :     bool        have_data = false;
    6855                 :             :     int16       typLen;
    6856                 :             :     bool        typByVal;
    6857                 :             :     Oid         opfuncoid;
    6858                 :             :     FmgrInfo    opproc;
    6859                 :             :     AttStatsSlot sslot;
    6860                 :             : 
    6861                 :             :     /*
    6862                 :             :      * XXX It's very tempting to try to use the actual column min and max, if
    6863                 :             :      * we can get them relatively-cheaply with an index probe.  However, since
    6864                 :             :      * this function is called many times during join planning, that could
    6865                 :             :      * have unpleasant effects on planning speed.  Need more investigation
    6866                 :             :      * before enabling this.
    6867                 :             :      */
    6868                 :             : #ifdef NOT_USED
    6869                 :             :     if (get_actual_variable_range(root, vardata, sortop, collation, min, max))
    6870                 :             :         return true;
    6871                 :             : #endif
    6872                 :             : 
    6873         [ +  + ]:      165962 :     if (!HeapTupleIsValid(vardata->statsTuple))
    6874                 :             :     {
    6875                 :             :         /* no stats available, so default result */
    6876                 :       45915 :         return false;
    6877                 :             :     }
    6878                 :             : 
    6879                 :             :     /*
    6880                 :             :      * If we can't apply the sortop to the stats data, just fail.  In
    6881                 :             :      * principle, if there's a histogram and no MCVs, we could return the
    6882                 :             :      * histogram endpoints without ever applying the sortop ... but it's
    6883                 :             :      * probably not worth trying, because whatever the caller wants to do with
    6884                 :             :      * the endpoints would likely fail the security check too.
    6885                 :             :      */
    6886         [ -  + ]:      120047 :     if (!statistic_proc_security_check(vardata,
    6887                 :      120047 :                                        (opfuncoid = get_opcode(sortop))))
    6888                 :           0 :         return false;
    6889                 :             : 
    6890                 :      120047 :     opproc.fn_oid = InvalidOid; /* mark this as not looked up yet */
    6891                 :             : 
    6892                 :      120047 :     get_typlenbyval(vardata->atttype, &typLen, &typByVal);
    6893                 :             : 
    6894                 :             :     /*
    6895                 :             :      * If there is a histogram with the ordering we want, grab the first and
    6896                 :             :      * last values.
    6897                 :             :      */
    6898         [ +  + ]:      120047 :     if (get_attstatsslot(&sslot, vardata->statsTuple,
    6899                 :             :                          STATISTIC_KIND_HISTOGRAM, sortop,
    6900                 :             :                          ATTSTATSSLOT_VALUES))
    6901                 :             :     {
    6902   [ +  -  +  - ]:       73620 :         if (sslot.stacoll == collation && sslot.nvalues > 0)
    6903                 :             :         {
    6904                 :       73620 :             tmin = datumCopy(sslot.values[0], typByVal, typLen);
    6905                 :       73620 :             tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
    6906                 :       73620 :             have_data = true;
    6907                 :             :         }
    6908                 :       73620 :         free_attstatsslot(&sslot);
    6909                 :             :     }
    6910                 :             : 
    6911                 :             :     /*
    6912                 :             :      * Otherwise, if there is a histogram with some other ordering, scan it
    6913                 :             :      * and get the min and max values according to the ordering we want.  This
    6914                 :             :      * of course may not find values that are really extremal according to our
    6915                 :             :      * ordering, but it beats ignoring available data.
    6916                 :             :      */
    6917   [ +  +  -  + ]:      166474 :     if (!have_data &&
    6918                 :       46427 :         get_attstatsslot(&sslot, vardata->statsTuple,
    6919                 :             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
    6920                 :             :                          ATTSTATSSLOT_VALUES))
    6921                 :             :     {
    6922                 :           0 :         get_stats_slot_range(&sslot, opfuncoid, &opproc,
    6923                 :             :                              collation, typLen, typByVal,
    6924                 :             :                              &tmin, &tmax, &have_data);
    6925                 :           0 :         free_attstatsslot(&sslot);
    6926                 :             :     }
    6927                 :             : 
    6928                 :             :     /*
    6929                 :             :      * If we have most-common-values info, look for extreme MCVs.  This is
    6930                 :             :      * needed even if we also have a histogram, since the histogram excludes
    6931                 :             :      * the MCVs.  However, if we *only* have MCVs and no histogram, we should
    6932                 :             :      * be pretty wary of deciding that that is a full representation of the
    6933                 :             :      * data.  Proceed only if the MCVs represent the whole table (to within
    6934                 :             :      * roundoff error).
    6935                 :             :      */
    6936         [ +  + ]:      120047 :     if (get_attstatsslot(&sslot, vardata->statsTuple,
    6937                 :             :                          STATISTIC_KIND_MCV, InvalidOid,
    6938         [ +  + ]:      120047 :                          have_data ? ATTSTATSSLOT_VALUES :
    6939                 :             :                          (ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)))
    6940                 :             :     {
    6941                 :       67164 :         bool        use_mcvs = have_data;
    6942                 :             : 
    6943         [ +  + ]:       67164 :         if (!have_data)
    6944                 :             :         {
    6945                 :       45483 :             double      sumcommon = 0.0;
    6946                 :             :             double      nullfrac;
    6947                 :             :             int         i;
    6948                 :             : 
    6949         [ +  + ]:      358379 :             for (i = 0; i < sslot.nnumbers; i++)
    6950                 :      312896 :                 sumcommon += sslot.numbers[i];
    6951                 :       45483 :             nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata->statsTuple))->stanullfrac;
    6952         [ +  + ]:       45483 :             if (sumcommon + nullfrac > 0.99999)
    6953                 :       45339 :                 use_mcvs = true;
    6954                 :             :         }
    6955                 :             : 
    6956         [ +  + ]:       67164 :         if (use_mcvs)
    6957                 :       67020 :             get_stats_slot_range(&sslot, opfuncoid, &opproc,
    6958                 :             :                                  collation, typLen, typByVal,
    6959                 :             :                                  &tmin, &tmax, &have_data);
    6960                 :       67164 :         free_attstatsslot(&sslot);
    6961                 :             :     }
    6962                 :             : 
    6963                 :      120047 :     *min = tmin;
    6964                 :      120047 :     *max = tmax;
    6965                 :      120047 :     return have_data;
    6966                 :             : }
    6967                 :             : 
    6968                 :             : /*
    6969                 :             :  * get_stats_slot_range: scan sslot for min/max values
    6970                 :             :  *
    6971                 :             :  * Subroutine for get_variable_range: update min/max/have_data according
    6972                 :             :  * to what we find in the statistics array.
    6973                 :             :  */
    6974                 :             : static void
    6975                 :       67020 : get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
    6976                 :             :                      Oid collation, int16 typLen, bool typByVal,
    6977                 :             :                      Datum *min, Datum *max, bool *p_have_data)
    6978                 :             : {
    6979                 :       67020 :     Datum       tmin = *min;
    6980                 :       67020 :     Datum       tmax = *max;
    6981                 :       67020 :     bool        have_data = *p_have_data;
    6982                 :       67020 :     bool        found_tmin = false;
    6983                 :       67020 :     bool        found_tmax = false;
    6984                 :             : 
    6985                 :             :     /* Look up the comparison function, if we didn't already do so */
    6986         [ +  - ]:       67020 :     if (opproc->fn_oid != opfuncoid)
    6987                 :       67020 :         fmgr_info(opfuncoid, opproc);
    6988                 :             : 
    6989                 :             :     /* Scan all the slot's values */
    6990         [ +  + ]:     1512749 :     for (int i = 0; i < sslot->nvalues; i++)
    6991                 :             :     {
    6992         [ +  + ]:     1445729 :         if (!have_data)
    6993                 :             :         {
    6994                 :       45339 :             tmin = tmax = sslot->values[i];
    6995                 :       45339 :             found_tmin = found_tmax = true;
    6996                 :       45339 :             *p_have_data = have_data = true;
    6997                 :       45339 :             continue;
    6998                 :             :         }
    6999         [ +  + ]:     1400390 :         if (DatumGetBool(FunctionCall2Coll(opproc,
    7000                 :             :                                            collation,
    7001                 :     1400390 :                                            sslot->values[i], tmin)))
    7002                 :             :         {
    7003                 :       36811 :             tmin = sslot->values[i];
    7004                 :       36811 :             found_tmin = true;
    7005                 :             :         }
    7006         [ +  + ]:     1400390 :         if (DatumGetBool(FunctionCall2Coll(opproc,
    7007                 :             :                                            collation,
    7008                 :     1400390 :                                            tmax, sslot->values[i])))
    7009                 :             :         {
    7010                 :      185733 :             tmax = sslot->values[i];
    7011                 :      185733 :             found_tmax = true;
    7012                 :             :         }
    7013                 :             :     }
    7014                 :             : 
    7015                 :             :     /*
    7016                 :             :      * Copy the slot's values, if we found new extreme values.
    7017                 :             :      */
    7018         [ +  + ]:       67020 :     if (found_tmin)
    7019                 :       58956 :         *min = datumCopy(tmin, typByVal, typLen);
    7020         [ +  + ]:       67020 :     if (found_tmax)
    7021                 :       47232 :         *max = datumCopy(tmax, typByVal, typLen);
    7022                 :       67020 : }
    7023                 :             : 
    7024                 :             : 
    7025                 :             : /*
    7026                 :             :  * get_actual_variable_range
    7027                 :             :  *      Attempt to identify the current *actual* minimum and/or maximum
    7028                 :             :  *      of the specified variable, by looking for a suitable btree index
    7029                 :             :  *      and fetching its low and/or high values.
    7030                 :             :  *      If successful, store values in *min and *max, and return true.
    7031                 :             :  *      (Either pointer can be NULL if that endpoint isn't needed.)
    7032                 :             :  *      If unsuccessful, return false.
    7033                 :             :  *
    7034                 :             :  * sortop is the "<" comparison operator to use.
    7035                 :             :  * collation is the required collation.
    7036                 :             :  */
    7037                 :             : static bool
    7038                 :      113440 : get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
    7039                 :             :                           Oid sortop, Oid collation,
    7040                 :             :                           Datum *min, Datum *max)
    7041                 :             : {
    7042                 :      113440 :     bool        have_data = false;
    7043                 :      113440 :     RelOptInfo *rel = vardata->rel;
    7044                 :             :     RangeTblEntry *rte;
    7045                 :             :     ListCell   *lc;
    7046                 :             : 
    7047                 :             :     /* No hope if no relation or it doesn't have indexes */
    7048   [ +  -  +  + ]:      113440 :     if (rel == NULL || rel->indexlist == NIL)
    7049                 :        8979 :         return false;
    7050                 :             :     /* If it has indexes it must be a plain relation */
    7051                 :      104461 :     rte = root->simple_rte_array[rel->relid];
    7052                 :             :     Assert(rte->rtekind == RTE_RELATION);
    7053                 :             : 
    7054                 :             :     /* ignore partitioned tables.  Any indexes here are not real indexes */
    7055         [ +  + ]:      104461 :     if (rte->relkind == RELKIND_PARTITIONED_TABLE)
    7056                 :         560 :         return false;
    7057                 :             : 
    7058                 :             :     /* Search through the indexes to see if any match our problem */
    7059   [ +  -  +  +  :      201957 :     foreach(lc, rel->indexlist)
                   +  + ]
    7060                 :             :     {
    7061                 :      173926 :         IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
    7062                 :             :         ScanDirection indexscandir;
    7063                 :             :         StrategyNumber strategy;
    7064                 :             : 
    7065                 :             :         /* Ignore non-ordering indexes */
    7066         [ +  + ]:      173926 :         if (index->sortopfamily == NULL)
    7067                 :           3 :             continue;
    7068                 :             : 
    7069                 :             :         /*
    7070                 :             :          * Ignore partial indexes --- we only want stats that cover the entire
    7071                 :             :          * relation.
    7072                 :             :          */
    7073         [ +  + ]:      173923 :         if (index->indpred != NIL)
    7074                 :         240 :             continue;
    7075                 :             : 
    7076                 :             :         /*
    7077                 :             :          * The index list might include hypothetical indexes inserted by a
    7078                 :             :          * get_relation_info hook --- don't try to access them.
    7079                 :             :          */
    7080         [ -  + ]:      173683 :         if (index->hypothetical)
    7081                 :           0 :             continue;
    7082                 :             : 
    7083                 :             :         /*
    7084                 :             :          * get_actual_variable_endpoint uses the index-only-scan machinery, so
    7085                 :             :          * ignore indexes that can't use it on their first column.
    7086                 :             :          */
    7087         [ -  + ]:      173683 :         if (!index->canreturn[0])
    7088                 :           0 :             continue;
    7089                 :             : 
    7090                 :             :         /*
    7091                 :             :          * The first index column must match the desired variable, sortop, and
    7092                 :             :          * collation --- but we can use a descending-order index.
    7093                 :             :          */
    7094         [ +  + ]:      173683 :         if (collation != index->indexcollations[0])
    7095                 :       23826 :             continue;           /* test first 'cause it's cheapest */
    7096         [ +  + ]:      149857 :         if (!match_index_to_operand(vardata->var, 0, index))
    7097                 :       73987 :             continue;
    7098                 :       75870 :         strategy = get_op_opfamily_strategy(sortop, index->sortopfamily[0]);
    7099      [ +  -  - ]:       75870 :         switch (IndexAmTranslateStrategy(strategy, index->relam, index->sortopfamily[0], true))
    7100                 :             :         {
    7101                 :       75870 :             case COMPARE_LT:
    7102         [ -  + ]:       75870 :                 if (index->reverse_sort[0])
    7103                 :           0 :                     indexscandir = BackwardScanDirection;
    7104                 :             :                 else
    7105                 :       75870 :                     indexscandir = ForwardScanDirection;
    7106                 :       75870 :                 break;
    7107                 :           0 :             case COMPARE_GT:
    7108         [ #  # ]:           0 :                 if (index->reverse_sort[0])
    7109                 :           0 :                     indexscandir = ForwardScanDirection;
    7110                 :             :                 else
    7111                 :           0 :                     indexscandir = BackwardScanDirection;
    7112                 :           0 :                 break;
    7113                 :           0 :             default:
    7114                 :             :                 /* index doesn't match the sortop */
    7115                 :           0 :                 continue;
    7116                 :             :         }
    7117                 :             : 
    7118                 :             :         /*
    7119                 :             :          * Found a suitable index to extract data from.  Set up some data that
    7120                 :             :          * can be used by both invocations of get_actual_variable_endpoint.
    7121                 :             :          */
    7122                 :             :         {
    7123                 :             :             MemoryContext tmpcontext;
    7124                 :             :             MemoryContext oldcontext;
    7125                 :             :             Relation    heapRel;
    7126                 :             :             Relation    indexRel;
    7127                 :             :             TupleTableSlot *slot;
    7128                 :             :             int16       typLen;
    7129                 :             :             bool        typByVal;
    7130                 :             :             ScanKeyData scankeys[1];
    7131                 :             : 
    7132                 :             :             /* Make sure any cruft gets recycled when we're done */
    7133                 :       75870 :             tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
    7134                 :             :                                                "get_actual_variable_range workspace",
    7135                 :             :                                                ALLOCSET_DEFAULT_SIZES);
    7136                 :       75870 :             oldcontext = MemoryContextSwitchTo(tmpcontext);
    7137                 :             : 
    7138                 :             :             /*
    7139                 :             :              * Open the table and index so we can read from them.  We should
    7140                 :             :              * already have some type of lock on each.
    7141                 :             :              */
    7142                 :       75870 :             heapRel = table_open(rte->relid, NoLock);
    7143                 :       75870 :             indexRel = index_open(index->indexoid, NoLock);
    7144                 :             : 
    7145                 :             :             /* build some stuff needed for indexscan execution */
    7146                 :       75870 :             slot = table_slot_create(heapRel, NULL);
    7147                 :       75870 :             get_typlenbyval(vardata->atttype, &typLen, &typByVal);
    7148                 :             : 
    7149                 :             :             /* set up an IS NOT NULL scan key so that we ignore nulls */
    7150                 :       75870 :             ScanKeyEntryInitialize(&scankeys[0],
    7151                 :             :                                    SK_ISNULL | SK_SEARCHNOTNULL,
    7152                 :             :                                    1,   /* index col to scan */
    7153                 :             :                                    InvalidStrategy, /* no strategy */
    7154                 :             :                                    InvalidOid,  /* no strategy subtype */
    7155                 :             :                                    InvalidOid,  /* no collation */
    7156                 :             :                                    InvalidOid,  /* no reg proc for this */
    7157                 :             :                                    (Datum) 0);  /* constant */
    7158                 :             : 
    7159                 :             :             /* If min is requested ... */
    7160         [ +  + ]:       75870 :             if (min)
    7161                 :             :             {
    7162                 :       42780 :                 have_data = get_actual_variable_endpoint(heapRel,
    7163                 :             :                                                          indexRel,
    7164                 :             :                                                          indexscandir,
    7165                 :             :                                                          scankeys,
    7166                 :             :                                                          typLen,
    7167                 :             :                                                          typByVal,
    7168                 :             :                                                          slot,
    7169                 :             :                                                          oldcontext,
    7170                 :             :                                                          min);
    7171                 :             :             }
    7172                 :             :             else
    7173                 :             :             {
    7174                 :             :                 /* If min not requested, still want to fetch max */
    7175                 :       33090 :                 have_data = true;
    7176                 :             :             }
    7177                 :             : 
    7178                 :             :             /* If max is requested, and we didn't already fail ... */
    7179   [ +  +  +  - ]:       75870 :             if (max && have_data)
    7180                 :             :             {
    7181                 :             :                 /* scan in the opposite direction; all else is the same */
    7182                 :       34120 :                 have_data = get_actual_variable_endpoint(heapRel,
    7183                 :             :                                                          indexRel,
    7184                 :       34120 :                                                          -indexscandir,
    7185                 :             :                                                          scankeys,
    7186                 :             :                                                          typLen,
    7187                 :             :                                                          typByVal,
    7188                 :             :                                                          slot,
    7189                 :             :                                                          oldcontext,
    7190                 :             :                                                          max);
    7191                 :             :             }
    7192                 :             : 
    7193                 :             :             /* Clean everything up */
    7194                 :       75870 :             ExecDropSingleTupleTableSlot(slot);
    7195                 :             : 
    7196                 :       75870 :             index_close(indexRel, NoLock);
    7197                 :       75870 :             table_close(heapRel, NoLock);
    7198                 :             : 
    7199                 :       75870 :             MemoryContextSwitchTo(oldcontext);
    7200                 :       75870 :             MemoryContextDelete(tmpcontext);
    7201                 :             : 
    7202                 :             :             /* And we're done */
    7203                 :       75870 :             break;
    7204                 :             :         }
    7205                 :             :     }
    7206                 :             : 
    7207                 :      103901 :     return have_data;
    7208                 :             : }
    7209                 :             : 
    7210                 :             : /*
    7211                 :             :  * Get one endpoint datum (min or max depending on indexscandir) from the
    7212                 :             :  * specified index.  Return true if successful, false if not.
    7213                 :             :  * On success, endpoint value is stored to *endpointDatum (and copied into
    7214                 :             :  * outercontext).
    7215                 :             :  *
    7216                 :             :  * scankeys is a 1-element scankey array set up to reject nulls.
    7217                 :             :  * typLen/typByVal describe the datatype of the index's first column.
    7218                 :             :  * tableslot is a slot suitable to hold table tuples, in case we need
    7219                 :             :  * to probe the heap.
    7220                 :             :  * (We could compute these values locally, but that would mean computing them
    7221                 :             :  * twice when get_actual_variable_range needs both the min and the max.)
    7222                 :             :  *
    7223                 :             :  * Failure occurs either when the index is empty, or we decide that it's
    7224                 :             :  * taking too long to find a suitable tuple.
    7225                 :             :  */
    7226                 :             : static bool
    7227                 :       76900 : get_actual_variable_endpoint(Relation heapRel,
    7228                 :             :                              Relation indexRel,
    7229                 :             :                              ScanDirection indexscandir,
    7230                 :             :                              ScanKey scankeys,
    7231                 :             :                              int16 typLen,
    7232                 :             :                              bool typByVal,
    7233                 :             :                              TupleTableSlot *tableslot,
    7234                 :             :                              MemoryContext outercontext,
    7235                 :             :                              Datum *endpointDatum)
    7236                 :             : {
    7237                 :       76900 :     bool        have_data = false;
    7238                 :             :     SnapshotData SnapshotNonVacuumable;
    7239                 :             :     IndexScanDesc index_scan;
    7240                 :       76900 :     Buffer      vmbuffer = InvalidBuffer;
    7241                 :       76900 :     BlockNumber last_heap_block = InvalidBlockNumber;
    7242                 :       76900 :     int         n_visited_heap_pages = 0;
    7243                 :             :     ItemPointer tid;
    7244                 :             :     Datum       values[INDEX_MAX_KEYS];
    7245                 :             :     bool        isnull[INDEX_MAX_KEYS];
    7246                 :             :     MemoryContext oldcontext;
    7247                 :             : 
    7248                 :             :     /*
    7249                 :             :      * We use the index-only-scan machinery for this.  With mostly-static
    7250                 :             :      * tables that's a win because it avoids a heap visit.  It's also a win
    7251                 :             :      * for dynamic data, but the reason is less obvious; read on for details.
    7252                 :             :      *
    7253                 :             :      * In principle, we should scan the index with our current active
    7254                 :             :      * snapshot, which is the best approximation we've got to what the query
    7255                 :             :      * will see when executed.  But that won't be exact if a new snap is taken
    7256                 :             :      * before running the query, and it can be very expensive if a lot of
    7257                 :             :      * recently-dead or uncommitted rows exist at the beginning or end of the
    7258                 :             :      * index (because we'll laboriously fetch each one and reject it).
    7259                 :             :      * Instead, we use SnapshotNonVacuumable.  That will accept recently-dead
    7260                 :             :      * and uncommitted rows as well as normal visible rows.  On the other
    7261                 :             :      * hand, it will reject known-dead rows, and thus not give a bogus answer
    7262                 :             :      * when the extreme value has been deleted (unless the deletion was quite
    7263                 :             :      * recent); that case motivates not using SnapshotAny here.
    7264                 :             :      *
    7265                 :             :      * A crucial point here is that SnapshotNonVacuumable, with
    7266                 :             :      * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
    7267                 :             :      * condition that the indexscan will use to decide that index entries are
    7268                 :             :      * killable (see heap_hot_search_buffer()).  Therefore, if the snapshot
    7269                 :             :      * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
    7270                 :             :      * have to continue scanning past it, we know that the indexscan will mark
    7271                 :             :      * that index entry killed.  That means that the next
    7272                 :             :      * get_actual_variable_endpoint() call will not have to re-consider that
    7273                 :             :      * index entry.  In this way we avoid repetitive work when this function
    7274                 :             :      * is used a lot during planning.
    7275                 :             :      *
    7276                 :             :      * But using SnapshotNonVacuumable creates a hazard of its own.  In a
    7277                 :             :      * recently-created index, some index entries may point at "broken" HOT
    7278                 :             :      * chains in which not all the tuple versions contain data matching the
    7279                 :             :      * index entry.  The live tuple version(s) certainly do match the index,
    7280                 :             :      * but SnapshotNonVacuumable can accept recently-dead tuple versions that
    7281                 :             :      * don't match.  Hence, if we took data from the selected heap tuple, we
    7282                 :             :      * might get a bogus answer that's not close to the index extremal value,
    7283                 :             :      * or could even be NULL.  We avoid this hazard because we take the data
    7284                 :             :      * from the index entry not the heap.
    7285                 :             :      *
    7286                 :             :      * Despite all this care, there are situations where we might find many
    7287                 :             :      * non-visible tuples near the end of the index.  We don't want to expend
    7288                 :             :      * a huge amount of time here, so we give up once we've read too many heap
    7289                 :             :      * pages.  When we fail for that reason, the caller will end up using
    7290                 :             :      * whatever extremal value is recorded in pg_statistic.
    7291                 :             :      */
    7292                 :       76900 :     InitNonVacuumableSnapshot(SnapshotNonVacuumable,
    7293                 :             :                               GlobalVisTestFor(heapRel));
    7294                 :             : 
    7295                 :       76900 :     index_scan = index_beginscan(heapRel, indexRel,
    7296                 :             :                                  &SnapshotNonVacuumable, NULL,
    7297                 :             :                                  1, 0,
    7298                 :             :                                  SO_NONE);
    7299                 :             :     /* Set it up for index-only scan */
    7300                 :       76900 :     index_scan->xs_want_itup = true;
    7301                 :       76900 :     index_rescan(index_scan, scankeys, 1, NULL, 0);
    7302                 :             : 
    7303                 :             :     /* Fetch first/next tuple in specified direction */
    7304         [ +  - ]:       91499 :     while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
    7305                 :             :     {
    7306                 :       91499 :         BlockNumber block = ItemPointerGetBlockNumber(tid);
    7307                 :             : 
    7308         [ +  + ]:       91499 :         if (!VM_ALL_VISIBLE(heapRel,
    7309                 :             :                             block,
    7310                 :             :                             &vmbuffer))
    7311                 :             :         {
    7312                 :             :             /* Rats, we have to visit the heap to check visibility */
    7313         [ +  + ]:       63417 :             if (!index_fetch_heap(index_scan, tableslot))
    7314                 :             :             {
    7315                 :             :                 /*
    7316                 :             :                  * No visible tuple for this index entry, so we need to
    7317                 :             :                  * advance to the next entry.  Before doing so, count heap
    7318                 :             :                  * page fetches and give up if we've done too many.
    7319                 :             :                  *
    7320                 :             :                  * We don't charge a page fetch if this is the same heap page
    7321                 :             :                  * as the previous tuple.  This is on the conservative side,
    7322                 :             :                  * since other recently-accessed pages are probably still in
    7323                 :             :                  * buffers too; but it's good enough for this heuristic.
    7324                 :             :                  */
    7325                 :             : #define VISITED_PAGES_LIMIT 100
    7326                 :             : 
    7327         [ +  + ]:       14599 :                 if (block != last_heap_block)
    7328                 :             :                 {
    7329                 :        1564 :                     last_heap_block = block;
    7330                 :        1564 :                     n_visited_heap_pages++;
    7331         [ -  + ]:        1564 :                     if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
    7332                 :           0 :                         break;
    7333                 :             :                 }
    7334                 :             : 
    7335                 :       14599 :                 continue;       /* no visible tuple, try next index entry */
    7336                 :             :             }
    7337                 :             : 
    7338                 :             :             /* We don't actually need the heap tuple for anything */
    7339                 :       48818 :             ExecClearTuple(tableslot);
    7340                 :             : 
    7341                 :             :             /*
    7342                 :             :              * We don't care whether there's more than one visible tuple in
    7343                 :             :              * the HOT chain; if any are visible, that's good enough.
    7344                 :             :              */
    7345                 :             :         }
    7346                 :             : 
    7347                 :             :         /*
    7348                 :             :          * We expect that the index will return data in IndexTuple not
    7349                 :             :          * HeapTuple format.
    7350                 :             :          */
    7351         [ -  + ]:       76900 :         if (!index_scan->xs_itup)
    7352         [ #  # ]:           0 :             elog(ERROR, "no data returned for index-only scan");
    7353                 :             : 
    7354                 :             :         /*
    7355                 :             :          * We do not yet support recheck here.
    7356                 :             :          */
    7357         [ -  + ]:       76900 :         if (index_scan->xs_recheck)
    7358                 :           0 :             break;
    7359                 :             : 
    7360                 :             :         /* OK to deconstruct the index tuple */
    7361                 :       76900 :         index_deform_tuple(index_scan->xs_itup,
    7362                 :             :                            index_scan->xs_itupdesc,
    7363                 :             :                            values, isnull);
    7364                 :             : 
    7365                 :             :         /* Shouldn't have got a null, but be careful */
    7366         [ -  + ]:       76900 :         if (isnull[0])
    7367         [ #  # ]:           0 :             elog(ERROR, "found unexpected null value in index \"%s\"",
    7368                 :             :                  RelationGetRelationName(indexRel));
    7369                 :             : 
    7370                 :             :         /* Copy the index column value out to caller's context */
    7371                 :       76900 :         oldcontext = MemoryContextSwitchTo(outercontext);
    7372                 :       76900 :         *endpointDatum = datumCopy(values[0], typByVal, typLen);
    7373                 :       76900 :         MemoryContextSwitchTo(oldcontext);
    7374                 :       76900 :         have_data = true;
    7375                 :       76900 :         break;
    7376                 :             :     }
    7377                 :             : 
    7378         [ +  + ]:       76900 :     if (vmbuffer != InvalidBuffer)
    7379                 :       69971 :         ReleaseBuffer(vmbuffer);
    7380                 :       76900 :     index_endscan(index_scan);
    7381                 :             : 
    7382                 :       76900 :     return have_data;
    7383                 :             : }
    7384                 :             : 
    7385                 :             : /*
    7386                 :             :  * find_join_input_rel
    7387                 :             :  *      Look up the input relation for a join.
    7388                 :             :  *
    7389                 :             :  * We assume that the input relation's RelOptInfo must have been constructed
    7390                 :             :  * already.
    7391                 :             :  */
    7392                 :             : static RelOptInfo *
    7393                 :       11209 : find_join_input_rel(PlannerInfo *root, Relids relids)
    7394                 :             : {
    7395                 :       11209 :     RelOptInfo *rel = NULL;
    7396                 :             : 
    7397         [ +  - ]:       11209 :     if (!bms_is_empty(relids))
    7398                 :             :     {
    7399                 :             :         int         relid;
    7400                 :             : 
    7401         [ +  + ]:       11209 :         if (bms_get_singleton_member(relids, &relid))
    7402                 :       10933 :             rel = find_base_rel(root, relid);
    7403                 :             :         else
    7404                 :         276 :             rel = find_join_rel(root, relids);
    7405                 :             :     }
    7406                 :             : 
    7407         [ -  + ]:       11209 :     if (rel == NULL)
    7408         [ #  # ]:           0 :         elog(ERROR, "could not find RelOptInfo for given relids");
    7409                 :             : 
    7410                 :       11209 :     return rel;
    7411                 :             : }
    7412                 :             : 
    7413                 :             : 
    7414                 :             : /*-------------------------------------------------------------------------
    7415                 :             :  *
    7416                 :             :  * Index cost estimation functions
    7417                 :             :  *
    7418                 :             :  *-------------------------------------------------------------------------
    7419                 :             :  */
    7420                 :             : 
    7421                 :             : /*
    7422                 :             :  * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
    7423                 :             :  */
    7424                 :             : List *
    7425                 :      653877 : get_quals_from_indexclauses(List *indexclauses)
    7426                 :             : {
    7427                 :      653877 :     List       *result = NIL;
    7428                 :             :     ListCell   *lc;
    7429                 :             : 
    7430   [ +  +  +  +  :     1138772 :     foreach(lc, indexclauses)
                   +  + ]
    7431                 :             :     {
    7432                 :      484895 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    7433                 :             :         ListCell   *lc2;
    7434                 :             : 
    7435   [ +  -  +  +  :      972219 :         foreach(lc2, iclause->indexquals)
                   +  + ]
    7436                 :             :         {
    7437                 :      487324 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    7438                 :             : 
    7439                 :      487324 :             result = lappend(result, rinfo);
    7440                 :             :         }
    7441                 :             :     }
    7442                 :      653877 :     return result;
    7443                 :             : }
    7444                 :             : 
    7445                 :             : /*
    7446                 :             :  * Compute the total evaluation cost of the comparison operands in a list
    7447                 :             :  * of index qual expressions.  Since we know these will be evaluated just
    7448                 :             :  * once per scan, there's no need to distinguish startup from per-row cost.
    7449                 :             :  *
    7450                 :             :  * This can be used either on the result of get_quals_from_indexclauses(),
    7451                 :             :  * or directly on an indexorderbys list.  In both cases, we expect that the
    7452                 :             :  * index key expression is on the left side of binary clauses.
    7453                 :             :  */
    7454                 :             : Cost
    7455                 :     1297254 : index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
    7456                 :             : {
    7457                 :     1297254 :     Cost        qual_arg_cost = 0;
    7458                 :             :     ListCell   *lc;
    7459                 :             : 
    7460   [ +  +  +  +  :     1784927 :     foreach(lc, indexquals)
                   +  + ]
    7461                 :             :     {
    7462                 :      487673 :         Expr       *clause = (Expr *) lfirst(lc);
    7463                 :             :         Node       *other_operand;
    7464                 :             :         QualCost    index_qual_cost;
    7465                 :             : 
    7466                 :             :         /*
    7467                 :             :          * Index quals will have RestrictInfos, indexorderbys won't.  Look
    7468                 :             :          * through RestrictInfo if present.
    7469                 :             :          */
    7470         [ +  + ]:      487673 :         if (IsA(clause, RestrictInfo))
    7471                 :      487314 :             clause = ((RestrictInfo *) clause)->clause;
    7472                 :             : 
    7473         [ +  + ]:      487673 :         if (IsA(clause, OpExpr))
    7474                 :             :         {
    7475                 :      472291 :             OpExpr     *op = (OpExpr *) clause;
    7476                 :             : 
    7477                 :      472291 :             other_operand = (Node *) lsecond(op->args);
    7478                 :             :         }
    7479         [ +  + ]:       15382 :         else if (IsA(clause, RowCompareExpr))
    7480                 :             :         {
    7481                 :         330 :             RowCompareExpr *rc = (RowCompareExpr *) clause;
    7482                 :             : 
    7483                 :         330 :             other_operand = (Node *) rc->rargs;
    7484                 :             :         }
    7485         [ +  + ]:       15052 :         else if (IsA(clause, ScalarArrayOpExpr))
    7486                 :             :         {
    7487                 :       12613 :             ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    7488                 :             : 
    7489                 :       12613 :             other_operand = (Node *) lsecond(saop->args);
    7490                 :             :         }
    7491         [ +  - ]:        2439 :         else if (IsA(clause, NullTest))
    7492                 :             :         {
    7493                 :        2439 :             other_operand = NULL;
    7494                 :             :         }
    7495                 :             :         else
    7496                 :             :         {
    7497         [ #  # ]:           0 :             elog(ERROR, "unsupported indexqual type: %d",
    7498                 :             :                  (int) nodeTag(clause));
    7499                 :             :             other_operand = NULL;   /* keep compiler quiet */
    7500                 :             :         }
    7501                 :             : 
    7502                 :      487673 :         cost_qual_eval_node(&index_qual_cost, other_operand, root);
    7503                 :      487673 :         qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
    7504                 :             :     }
    7505                 :     1297254 :     return qual_arg_cost;
    7506                 :             : }
    7507                 :             : 
    7508                 :             : /*
    7509                 :             :  * Compute generic index access cost estimates.
    7510                 :             :  *
    7511                 :             :  * See struct GenericCosts in selfuncs.h for more info.
    7512                 :             :  */
    7513                 :             : void
    7514                 :      643387 : genericcostestimate(PlannerInfo *root,
    7515                 :             :                     IndexPath *path,
    7516                 :             :                     double loop_count,
    7517                 :             :                     GenericCosts *costs)
    7518                 :             : {
    7519                 :      643387 :     IndexOptInfo *index = path->indexinfo;
    7520                 :      643387 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    7521                 :      643387 :     List       *indexOrderBys = path->indexorderbys;
    7522                 :             :     Cost        indexStartupCost;
    7523                 :             :     Cost        indexTotalCost;
    7524                 :             :     Selectivity indexSelectivity;
    7525                 :             :     double      indexCorrelation;
    7526                 :             :     double      numIndexPages;
    7527                 :             :     double      numIndexTuples;
    7528                 :             :     double      spc_random_page_cost;
    7529                 :             :     double      num_sa_scans;
    7530                 :             :     double      num_outer_scans;
    7531                 :             :     double      num_scans;
    7532                 :             :     double      qual_op_cost;
    7533                 :             :     double      qual_arg_cost;
    7534                 :             :     List       *selectivityQuals;
    7535                 :             :     ListCell   *l;
    7536                 :             : 
    7537                 :             :     /*
    7538                 :             :      * If the index is partial, AND the index predicate with the explicitly
    7539                 :             :      * given indexquals to produce a more accurate idea of the index
    7540                 :             :      * selectivity.
    7541                 :             :      */
    7542                 :      643387 :     selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
    7543                 :             : 
    7544                 :             :     /*
    7545                 :             :      * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
    7546                 :             :      * just assume that the number of index descents is the number of distinct
    7547                 :             :      * combinations of array elements from all of the scan's SAOP clauses.
    7548                 :             :      */
    7549                 :      643387 :     num_sa_scans = costs->num_sa_scans;
    7550         [ +  + ]:      643387 :     if (num_sa_scans < 1)
    7551                 :             :     {
    7552                 :        6974 :         num_sa_scans = 1;
    7553   [ +  +  +  +  :       15252 :         foreach(l, indexQuals)
                   +  + ]
    7554                 :             :         {
    7555                 :        8278 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
    7556                 :             : 
    7557         [ +  + ]:        8278 :             if (IsA(rinfo->clause, ScalarArrayOpExpr))
    7558                 :             :             {
    7559                 :          46 :                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
    7560                 :          46 :                 double      alength = estimate_array_length(root, lsecond(saop->args));
    7561                 :             : 
    7562         [ +  - ]:          46 :                 if (alength > 1)
    7563                 :          46 :                     num_sa_scans *= alength;
    7564                 :             :             }
    7565                 :             :         }
    7566                 :             :     }
    7567                 :             : 
    7568                 :             :     /* Estimate the fraction of main-table tuples that will be visited */
    7569                 :      643387 :     indexSelectivity = clauselist_selectivity(root, selectivityQuals,
    7570                 :      643387 :                                               index->rel->relid,
    7571                 :             :                                               JOIN_INNER,
    7572                 :             :                                               NULL);
    7573                 :             : 
    7574                 :             :     /*
    7575                 :             :      * If caller didn't give us an estimate, estimate the number of index
    7576                 :             :      * tuples that will be visited.  We do it in this rather peculiar-looking
    7577                 :             :      * way in order to get the right answer for partial indexes.
    7578                 :             :      */
    7579                 :      643387 :     numIndexTuples = costs->numIndexTuples;
    7580         [ +  + ]:      643387 :     if (numIndexTuples <= 0.0)
    7581                 :             :     {
    7582                 :       77193 :         numIndexTuples = indexSelectivity * index->rel->tuples;
    7583                 :             : 
    7584                 :             :         /*
    7585                 :             :          * The above calculation counts all the tuples visited across all
    7586                 :             :          * scans induced by ScalarArrayOpExpr nodes.  We want to consider the
    7587                 :             :          * average per-indexscan number, so adjust.  This is a handy place to
    7588                 :             :          * round to integer, too.  (If caller supplied tuple estimate, it's
    7589                 :             :          * responsible for handling these considerations.)
    7590                 :             :          */
    7591                 :       77193 :         numIndexTuples = rint(numIndexTuples / num_sa_scans);
    7592                 :             :     }
    7593                 :             : 
    7594                 :             :     /*
    7595                 :             :      * We can bound the number of tuples by the index size in any case. Also,
    7596                 :             :      * always estimate at least one tuple is touched, even when
    7597                 :             :      * indexSelectivity estimate is tiny.
    7598                 :             :      */
    7599         [ +  + ]:      643387 :     if (numIndexTuples > index->tuples)
    7600                 :        7382 :         numIndexTuples = index->tuples;
    7601         [ +  + ]:      643387 :     if (numIndexTuples < 1.0)
    7602                 :       79739 :         numIndexTuples = 1.0;
    7603                 :             : 
    7604                 :             :     /*
    7605                 :             :      * Estimate the number of index pages that will be retrieved.
    7606                 :             :      *
    7607                 :             :      * We use the simplistic method of taking a pro-rata fraction of the total
    7608                 :             :      * number of index leaf pages.  We disregard any overhead such as index
    7609                 :             :      * metapages or upper tree levels.
    7610                 :             :      *
    7611                 :             :      * In practice access to upper index levels is often nearly free because
    7612                 :             :      * those tend to stay in cache under load; moreover, the cost involved is
    7613                 :             :      * highly dependent on index type.  We therefore ignore such costs here
    7614                 :             :      * and leave it to the caller to add a suitable charge if needed.
    7615                 :             :      */
    7616   [ +  +  +  + ]:      643387 :     if (index->pages > costs->numNonLeafPages && index->tuples > 1)
    7617                 :      583740 :         numIndexPages =
    7618                 :      583740 :             ceil(numIndexTuples * (index->pages - costs->numNonLeafPages)
    7619                 :      583740 :                  / index->tuples);
    7620                 :             :     else
    7621                 :       59647 :         numIndexPages = 1.0;
    7622                 :             : 
    7623                 :             :     /* fetch estimated page cost for tablespace containing index */
    7624                 :      643387 :     get_tablespace_page_costs(index->reltablespace,
    7625                 :             :                               &spc_random_page_cost,
    7626                 :             :                               NULL);
    7627                 :             : 
    7628                 :             :     /*
    7629                 :             :      * Now compute the disk access costs.
    7630                 :             :      *
    7631                 :             :      * The above calculations are all per-index-scan.  However, if we are in a
    7632                 :             :      * nestloop inner scan, we can expect the scan to be repeated (with
    7633                 :             :      * different search keys) for each row of the outer relation.  Likewise,
    7634                 :             :      * ScalarArrayOpExpr quals result in multiple index scans.  This creates
    7635                 :             :      * the potential for cache effects to reduce the number of disk page
    7636                 :             :      * fetches needed.  We want to estimate the average per-scan I/O cost in
    7637                 :             :      * the presence of caching.
    7638                 :             :      *
    7639                 :             :      * We use the Mackert-Lohman formula (see costsize.c for details) to
    7640                 :             :      * estimate the total number of page fetches that occur.  While this
    7641                 :             :      * wasn't what it was designed for, it seems a reasonable model anyway.
    7642                 :             :      * Note that we are counting pages not tuples anymore, so we take N = T =
    7643                 :             :      * index size, as if there were one "tuple" per page.
    7644                 :             :      */
    7645                 :      643387 :     num_outer_scans = loop_count;
    7646                 :      643387 :     num_scans = num_sa_scans * num_outer_scans;
    7647                 :             : 
    7648         [ +  + ]:      643387 :     if (num_scans > 1)
    7649                 :             :     {
    7650                 :             :         double      pages_fetched;
    7651                 :             : 
    7652                 :             :         /* total page fetches ignoring cache effects */
    7653                 :       77015 :         pages_fetched = numIndexPages * num_scans;
    7654                 :             : 
    7655                 :             :         /* use Mackert and Lohman formula to adjust for cache effects */
    7656                 :       77015 :         pages_fetched = index_pages_fetched(pages_fetched,
    7657                 :             :                                             index->pages,
    7658                 :       77015 :                                             (double) index->pages,
    7659                 :             :                                             root);
    7660                 :             : 
    7661                 :             :         /*
    7662                 :             :          * Now compute the total disk access cost, and then report a pro-rated
    7663                 :             :          * share for each outer scan.  (Don't pro-rate for ScalarArrayOpExpr,
    7664                 :             :          * since that's internal to the indexscan.)
    7665                 :             :          */
    7666                 :       77015 :         indexTotalCost = (pages_fetched * spc_random_page_cost)
    7667                 :             :             / num_outer_scans;
    7668                 :             :     }
    7669                 :             :     else
    7670                 :             :     {
    7671                 :             :         /*
    7672                 :             :          * For a single index scan, we just charge spc_random_page_cost per
    7673                 :             :          * page touched.
    7674                 :             :          */
    7675                 :      566372 :         indexTotalCost = numIndexPages * spc_random_page_cost;
    7676                 :             :     }
    7677                 :             : 
    7678                 :             :     /*
    7679                 :             :      * CPU cost: any complex expressions in the indexquals will need to be
    7680                 :             :      * evaluated once at the start of the scan to reduce them to runtime keys
    7681                 :             :      * to pass to the index AM (see nodeIndexscan.c).  We model the per-tuple
    7682                 :             :      * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
    7683                 :             :      * indexqual operator.  Because we have numIndexTuples as a per-scan
    7684                 :             :      * number, we have to multiply by num_sa_scans to get the correct result
    7685                 :             :      * for ScalarArrayOpExpr cases.  Similarly add in costs for any index
    7686                 :             :      * ORDER BY expressions.
    7687                 :             :      *
    7688                 :             :      * Note: this neglects the possible costs of rechecking lossy operators.
    7689                 :             :      * Detecting that that might be needed seems more expensive than it's
    7690                 :             :      * worth, though, considering all the other inaccuracies here ...
    7691                 :             :      */
    7692                 :      643387 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
    7693                 :      643387 :         index_other_operands_eval_cost(root, indexOrderBys);
    7694                 :      643387 :     qual_op_cost = cpu_operator_cost *
    7695                 :      643387 :         (list_length(indexQuals) + list_length(indexOrderBys));
    7696                 :             : 
    7697                 :      643387 :     indexStartupCost = qual_arg_cost;
    7698                 :      643387 :     indexTotalCost += qual_arg_cost;
    7699                 :      643387 :     indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
    7700                 :             : 
    7701                 :             :     /*
    7702                 :             :      * Generic assumption about index correlation: there isn't any.
    7703                 :             :      */
    7704                 :      643387 :     indexCorrelation = 0.0;
    7705                 :             : 
    7706                 :             :     /*
    7707                 :             :      * Return everything to caller.
    7708                 :             :      */
    7709                 :      643387 :     costs->indexStartupCost = indexStartupCost;
    7710                 :      643387 :     costs->indexTotalCost = indexTotalCost;
    7711                 :      643387 :     costs->indexSelectivity = indexSelectivity;
    7712                 :      643387 :     costs->indexCorrelation = indexCorrelation;
    7713                 :      643387 :     costs->numIndexPages = numIndexPages;
    7714                 :      643387 :     costs->numIndexTuples = numIndexTuples;
    7715                 :      643387 :     costs->spc_random_page_cost = spc_random_page_cost;
    7716                 :      643387 :     costs->num_sa_scans = num_sa_scans;
    7717                 :      643387 : }
    7718                 :             : 
    7719                 :             : /*
    7720                 :             :  * If the index is partial, add its predicate to the given qual list.
    7721                 :             :  *
    7722                 :             :  * ANDing the index predicate with the explicitly given indexquals produces
    7723                 :             :  * a more accurate idea of the index's selectivity.  However, we need to be
    7724                 :             :  * careful not to insert redundant clauses, because clauselist_selectivity()
    7725                 :             :  * is easily fooled into computing a too-low selectivity estimate.  Our
    7726                 :             :  * approach is to add only the predicate clause(s) that cannot be proven to
    7727                 :             :  * be implied by the given indexquals.  This successfully handles cases such
    7728                 :             :  * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
    7729                 :             :  * There are many other cases where we won't detect redundancy, leading to a
    7730                 :             :  * too-low selectivity estimate, which will bias the system in favor of using
    7731                 :             :  * partial indexes where possible.  That is not necessarily bad though.
    7732                 :             :  *
    7733                 :             :  * Note that indexQuals contains RestrictInfo nodes while the indpred
    7734                 :             :  * does not, so the output list will be mixed.  This is OK for both
    7735                 :             :  * predicate_implied_by() and clauselist_selectivity(), but might be
    7736                 :             :  * problematic if the result were passed to other things.
    7737                 :             :  */
    7738                 :             : List *
    7739                 :     1104207 : add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
    7740                 :             : {
    7741                 :     1104207 :     List       *predExtraQuals = NIL;
    7742                 :             :     ListCell   *lc;
    7743                 :             : 
    7744         [ +  + ]:     1104207 :     if (index->indpred == NIL)
    7745                 :     1102671 :         return indexQuals;
    7746                 :             : 
    7747   [ +  -  +  +  :        3082 :     foreach(lc, index->indpred)
                   +  + ]
    7748                 :             :     {
    7749                 :        1546 :         Node       *predQual = (Node *) lfirst(lc);
    7750                 :        1546 :         List       *oneQual = list_make1(predQual);
    7751                 :             : 
    7752         [ +  + ]:        1546 :         if (!predicate_implied_by(oneQual, indexQuals, false))
    7753                 :        1370 :             predExtraQuals = list_concat(predExtraQuals, oneQual);
    7754                 :             :     }
    7755                 :        1536 :     return list_concat(predExtraQuals, indexQuals);
    7756                 :             : }
    7757                 :             : 
    7758                 :             : /*
    7759                 :             :  * Estimate correlation of btree index's first column.
    7760                 :             :  *
    7761                 :             :  * If we can get an estimate of the first column's ordering correlation C
    7762                 :             :  * from pg_statistic, estimate the index correlation as C for a single-column
    7763                 :             :  * index, or C * 0.75 for multiple columns.  The idea here is that multiple
    7764                 :             :  * columns dilute the importance of the first column's ordering, but don't
    7765                 :             :  * negate it entirely.
    7766                 :             :  *
    7767                 :             :  * We already filled in the stats tuple for *vardata when called.
    7768                 :             :  */
    7769                 :             : static double
    7770                 :      413277 : btcost_correlation(IndexOptInfo *index, VariableStatData *vardata)
    7771                 :             : {
    7772                 :             :     Oid         sortop;
    7773                 :             :     AttStatsSlot sslot;
    7774                 :      413277 :     double      indexCorrelation = 0;
    7775                 :             : 
    7776                 :             :     Assert(HeapTupleIsValid(vardata->statsTuple));
    7777                 :             : 
    7778                 :      413277 :     sortop = get_opfamily_member(index->opfamily[0],
    7779                 :      413277 :                                  index->opcintype[0],
    7780                 :      413277 :                                  index->opcintype[0],
    7781                 :             :                                  BTLessStrategyNumber);
    7782   [ +  -  +  + ]:      826554 :     if (OidIsValid(sortop) &&
    7783                 :      413277 :         get_attstatsslot(&sslot, vardata->statsTuple,
    7784                 :             :                          STATISTIC_KIND_CORRELATION, sortop,
    7785                 :             :                          ATTSTATSSLOT_NUMBERS))
    7786                 :             :     {
    7787                 :             :         double      varCorrelation;
    7788                 :             : 
    7789                 :             :         Assert(sslot.nnumbers == 1);
    7790                 :      408448 :         varCorrelation = sslot.numbers[0];
    7791                 :             : 
    7792         [ -  + ]:      408448 :         if (index->reverse_sort[0])
    7793                 :           0 :             varCorrelation = -varCorrelation;
    7794                 :             : 
    7795         [ +  + ]:      408448 :         if (index->nkeycolumns > 1)
    7796                 :      144117 :             indexCorrelation = varCorrelation * 0.75;
    7797                 :             :         else
    7798                 :      264331 :             indexCorrelation = varCorrelation;
    7799                 :             : 
    7800                 :      408448 :         free_attstatsslot(&sslot);
    7801                 :             :     }
    7802                 :             : 
    7803                 :      413277 :     return indexCorrelation;
    7804                 :             : }
    7805                 :             : 
    7806                 :             : void
    7807                 :      636413 : btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7808                 :             :                Cost *indexStartupCost, Cost *indexTotalCost,
    7809                 :             :                Selectivity *indexSelectivity, double *indexCorrelation,
    7810                 :             :                double *indexPages)
    7811                 :             : {
    7812                 :      636413 :     IndexOptInfo *index = path->indexinfo;
    7813                 :      636413 :     GenericCosts costs = {0};
    7814                 :      636413 :     VariableStatData vardata = {0};
    7815                 :             :     double      numIndexTuples;
    7816                 :             :     Cost        descentCost;
    7817                 :             :     List       *indexBoundQuals;
    7818                 :             :     List       *indexSkipQuals;
    7819                 :             :     int         indexcol;
    7820                 :             :     bool        eqQualHere;
    7821                 :             :     bool        found_row_compare;
    7822                 :             :     bool        found_array;
    7823                 :             :     bool        found_is_null_op;
    7824                 :      636413 :     bool        have_correlation = false;
    7825                 :             :     double      num_sa_scans;
    7826                 :      636413 :     double      correlation = 0.0;
    7827                 :             :     ListCell   *lc;
    7828                 :             : 
    7829                 :             :     /*
    7830                 :             :      * For a btree scan, only leading '=' quals plus inequality quals for the
    7831                 :             :      * immediately next attribute contribute to index selectivity (these are
    7832                 :             :      * the "boundary quals" that determine the starting and stopping points of
    7833                 :             :      * the index scan).  Additional quals can suppress visits to the heap, so
    7834                 :             :      * it's OK to count them in indexSelectivity, but they should not count
    7835                 :             :      * for estimating numIndexTuples.  So we must examine the given indexquals
    7836                 :             :      * to find out which ones count as boundary quals.  We rely on the
    7837                 :             :      * knowledge that they are given in index column order.  Note that nbtree
    7838                 :             :      * preprocessing can add skip arrays that act as leading '=' quals in the
    7839                 :             :      * absence of ordinary input '=' quals, so in practice _most_ input quals
    7840                 :             :      * are able to act as index bound quals (which we take into account here).
    7841                 :             :      *
    7842                 :             :      * For a RowCompareExpr, we consider only the first column, just as
    7843                 :             :      * rowcomparesel() does.
    7844                 :             :      *
    7845                 :             :      * If there's a SAOP or skip array in the quals, we'll actually perform up
    7846                 :             :      * to N index descents (not just one), but the underlying array key's
    7847                 :             :      * operator can be considered to act the same as it normally does.
    7848                 :             :      */
    7849                 :      636413 :     indexBoundQuals = NIL;
    7850                 :      636413 :     indexSkipQuals = NIL;
    7851                 :      636413 :     indexcol = 0;
    7852                 :      636413 :     eqQualHere = false;
    7853                 :      636413 :     found_row_compare = false;
    7854                 :      636413 :     found_array = false;
    7855                 :      636413 :     found_is_null_op = false;
    7856                 :      636413 :     num_sa_scans = 1;
    7857   [ +  +  +  +  :     1075064 :     foreach(lc, path->indexclauses)
                   +  + ]
    7858                 :             :     {
    7859                 :      464278 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    7860                 :             :         ListCell   *lc2;
    7861                 :             : 
    7862         [ +  + ]:      464278 :         if (indexcol < iclause->indexcol)
    7863                 :             :         {
    7864                 :       87452 :             double      num_sa_scans_prev_cols = num_sa_scans;
    7865                 :             : 
    7866                 :             :             /*
    7867                 :             :              * Beginning of a new column's quals.
    7868                 :             :              *
    7869                 :             :              * Skip scans use skip arrays, which are ScalarArrayOp style
    7870                 :             :              * arrays that generate their elements procedurally and on demand.
    7871                 :             :              * Given a multi-column index on "(a, b)", and an SQL WHERE clause
    7872                 :             :              * "WHERE b = 42", a skip scan will effectively use an indexqual
    7873                 :             :              * "WHERE a = ANY('{every col a value}') AND b = 42".  (Obviously,
    7874                 :             :              * the array on "a" must also return "IS NULL" matches, since our
    7875                 :             :              * WHERE clause used no strict operator on "a").
    7876                 :             :              *
    7877                 :             :              * Here we consider how nbtree will backfill skip arrays for any
    7878                 :             :              * index columns that lacked an '=' qual.  This maintains our
    7879                 :             :              * num_sa_scans estimate, and determines if this new column (the
    7880                 :             :              * "iclause->indexcol" column, not the prior "indexcol" column)
    7881                 :             :              * can have its RestrictInfos/quals added to indexBoundQuals.
    7882                 :             :              *
    7883                 :             :              * We'll need to handle columns that have inequality quals, where
    7884                 :             :              * the skip array generates values from a range constrained by the
    7885                 :             :              * quals (not every possible value).  We've been maintaining
    7886                 :             :              * indexSkipQuals to help with this; it will now contain all of
    7887                 :             :              * the prior column's quals (that is, indexcol's quals) when they
    7888                 :             :              * might be used for this.
    7889                 :             :              */
    7890         [ +  + ]:       87452 :             if (found_row_compare)
    7891                 :             :             {
    7892                 :             :                 /*
    7893                 :             :                  * Skip arrays can't be added after a RowCompare input qual
    7894                 :             :                  * due to limitations in nbtree
    7895                 :             :                  */
    7896                 :          20 :                 break;
    7897                 :             :             }
    7898         [ +  + ]:       87432 :             if (eqQualHere)
    7899                 :             :             {
    7900                 :             :                 /*
    7901                 :             :                  * Don't need to add a skip array for an indexcol that already
    7902                 :             :                  * has an '=' qual/equality constraint
    7903                 :             :                  */
    7904                 :       62267 :                 indexcol++;
    7905                 :       62267 :                 indexSkipQuals = NIL;
    7906                 :             :             }
    7907                 :       87432 :             eqQualHere = false;
    7908                 :             : 
    7909         [ +  + ]:       88908 :             while (indexcol < iclause->indexcol)
    7910                 :             :             {
    7911                 :             :                 double      ndistinct;
    7912                 :       27083 :                 bool        isdefault = true;
    7913                 :             : 
    7914                 :       27083 :                 found_array = true;
    7915                 :             : 
    7916                 :             :                 /*
    7917                 :             :                  * A skipped attribute's ndistinct forms the basis of our
    7918                 :             :                  * estimate of the total number of "array elements" used by
    7919                 :             :                  * its skip array at runtime.  Look that up first.
    7920                 :             :                  */
    7921                 :       27083 :                 examine_indexcol_variable(root, index, indexcol, &vardata);
    7922                 :       27083 :                 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
    7923                 :             : 
    7924         [ +  + ]:       27083 :                 if (indexcol == 0)
    7925                 :             :                 {
    7926                 :             :                     /*
    7927                 :             :                      * Get an estimate of the leading column's correlation in
    7928                 :             :                      * passing (avoids rereading variable stats below)
    7929                 :             :                      */
    7930         [ +  + ]:       25155 :                     if (HeapTupleIsValid(vardata.statsTuple))
    7931                 :       14569 :                         correlation = btcost_correlation(index, &vardata);
    7932                 :       25155 :                     have_correlation = true;
    7933                 :             :                 }
    7934                 :             : 
    7935         [ +  + ]:       27083 :                 ReleaseVariableStats(vardata);
    7936                 :             : 
    7937                 :             :                 /*
    7938                 :             :                  * If ndistinct is a default estimate, conservatively assume
    7939                 :             :                  * that no skipping will happen at runtime
    7940                 :             :                  */
    7941         [ +  + ]:       27083 :                 if (isdefault)
    7942                 :             :                 {
    7943                 :        8026 :                     num_sa_scans = num_sa_scans_prev_cols;
    7944                 :       25607 :                     break;      /* done building indexBoundQuals */
    7945                 :             :                 }
    7946                 :             : 
    7947                 :             :                 /*
    7948                 :             :                  * Apply indexcol's indexSkipQuals selectivity to ndistinct
    7949                 :             :                  */
    7950         [ +  + ]:       19057 :                 if (indexSkipQuals != NIL)
    7951                 :             :                 {
    7952                 :             :                     List       *partialSkipQuals;
    7953                 :             :                     Selectivity ndistinctfrac;
    7954                 :             : 
    7955                 :             :                     /*
    7956                 :             :                      * If the index is partial, AND the index predicate with
    7957                 :             :                      * the index-bound quals to produce a more accurate idea
    7958                 :             :                      * of the number of distinct values for prior indexcol
    7959                 :             :                      */
    7960                 :         552 :                     partialSkipQuals = add_predicate_to_index_quals(index,
    7961                 :             :                                                                     indexSkipQuals);
    7962                 :             : 
    7963                 :         552 :                     ndistinctfrac = clauselist_selectivity(root, partialSkipQuals,
    7964                 :         552 :                                                            index->rel->relid,
    7965                 :             :                                                            JOIN_INNER,
    7966                 :             :                                                            NULL);
    7967                 :             : 
    7968                 :             :                     /*
    7969                 :             :                      * If ndistinctfrac is selective (on its own), the scan is
    7970                 :             :                      * unlikely to benefit from repositioning itself using
    7971                 :             :                      * later quals.  Do not allow iclause->indexcol's quals to
    7972                 :             :                      * be added to indexBoundQuals (it would increase descent
    7973                 :             :                      * costs, without lowering numIndexTuples costs by much).
    7974                 :             :                      */
    7975         [ +  + ]:         552 :                     if (ndistinctfrac < DEFAULT_RANGE_INEQ_SEL)
    7976                 :             :                     {
    7977                 :         311 :                         num_sa_scans = num_sa_scans_prev_cols;
    7978                 :         311 :                         break;  /* done building indexBoundQuals */
    7979                 :             :                     }
    7980                 :             : 
    7981                 :             :                     /* Adjust ndistinct downward */
    7982                 :         241 :                     ndistinct = rint(ndistinct * ndistinctfrac);
    7983         [ +  - ]:         241 :                     ndistinct = Max(ndistinct, 1);
    7984                 :             :                 }
    7985                 :             : 
    7986                 :             :                 /*
    7987                 :             :                  * When there's no inequality quals, account for the need to
    7988                 :             :                  * find an initial value by counting -inf/+inf as a value.
    7989                 :             :                  *
    7990                 :             :                  * We don't charge anything extra for possible next/prior key
    7991                 :             :                  * index probes, which are sometimes used to find the next
    7992                 :             :                  * valid skip array element (ahead of using the located
    7993                 :             :                  * element value to relocate the scan to the next position
    7994                 :             :                  * that might contain matching tuples).  It seems hard to do
    7995                 :             :                  * better here.  Use of the skip support infrastructure often
    7996                 :             :                  * avoids most next/prior key probes.  But even when it can't,
    7997                 :             :                  * there's a decent chance that most individual next/prior key
    7998                 :             :                  * probes will locate a leaf page whose key space overlaps all
    7999                 :             :                  * of the scan's keys (even the lower-order keys) -- which
    8000                 :             :                  * also avoids the need for a separate, extra index descent.
    8001                 :             :                  * Note also that these probes are much cheaper than non-probe
    8002                 :             :                  * primitive index scans: they're reliably very selective.
    8003                 :             :                  */
    8004         [ +  + ]:       18746 :                 if (indexSkipQuals == NIL)
    8005                 :       18505 :                     ndistinct += 1;
    8006                 :             : 
    8007                 :             :                 /*
    8008                 :             :                  * Update num_sa_scans estimate by multiplying by ndistinct.
    8009                 :             :                  *
    8010                 :             :                  * We make the pessimistic assumption that there is no
    8011                 :             :                  * naturally occurring cross-column correlation.  This is
    8012                 :             :                  * often wrong, but it seems best to err on the side of not
    8013                 :             :                  * expecting skipping to be helpful...
    8014                 :             :                  */
    8015                 :       18746 :                 num_sa_scans *= ndistinct;
    8016                 :             : 
    8017                 :             :                 /*
    8018                 :             :                  * ...but back out of adding this latest group of 1 or more
    8019                 :             :                  * skip arrays when num_sa_scans exceeds the total number of
    8020                 :             :                  * index pages (revert to num_sa_scans from before indexcol).
    8021                 :             :                  * This causes a sharp discontinuity in cost (as a function of
    8022                 :             :                  * the indexcol's ndistinct), but that is representative of
    8023                 :             :                  * actual runtime costs.
    8024                 :             :                  *
    8025                 :             :                  * Note that skipping is helpful when each primitive index
    8026                 :             :                  * scan only manages to skip over 1 or 2 irrelevant leaf pages
    8027                 :             :                  * on average.  Skip arrays bring savings in CPU costs due to
    8028                 :             :                  * the scan not needing to evaluate indexquals against every
    8029                 :             :                  * tuple, which can greatly exceed any savings in I/O costs.
    8030                 :             :                  * This test is a test of whether num_sa_scans implies that
    8031                 :             :                  * we're past the point where the ability to skip ceases to
    8032                 :             :                  * lower the scan's costs (even qual evaluation CPU costs).
    8033                 :             :                  */
    8034         [ +  + ]:       18746 :                 if (index->pages < num_sa_scans)
    8035                 :             :                 {
    8036                 :       17270 :                     num_sa_scans = num_sa_scans_prev_cols;
    8037                 :       17270 :                     break;      /* done building indexBoundQuals */
    8038                 :             :                 }
    8039                 :             : 
    8040                 :        1476 :                 indexcol++;
    8041                 :        1476 :                 indexSkipQuals = NIL;
    8042                 :             :             }
    8043                 :             : 
    8044                 :             :             /*
    8045                 :             :              * Finished considering the need to add skip arrays to bridge an
    8046                 :             :              * initial eqQualHere gap between the old and new index columns
    8047                 :             :              * (or there was no initial eqQualHere gap in the first place).
    8048                 :             :              *
    8049                 :             :              * If an initial gap could not be bridged, then new column's quals
    8050                 :             :              * (i.e. iclause->indexcol's quals) won't go into indexBoundQuals,
    8051                 :             :              * and so won't affect our final numIndexTuples estimate.
    8052                 :             :              */
    8053         [ +  + ]:       87432 :             if (indexcol != iclause->indexcol)
    8054                 :       25607 :                 break;          /* done building indexBoundQuals */
    8055                 :             :         }
    8056                 :             : 
    8057                 :             :         Assert(indexcol == iclause->indexcol);
    8058                 :             : 
    8059                 :             :         /* Examine each indexqual associated with this index clause */
    8060   [ +  -  +  +  :      879605 :         foreach(lc2, iclause->indexquals)
                   +  + ]
    8061                 :             :         {
    8062                 :      440954 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    8063                 :      440954 :             Expr       *clause = rinfo->clause;
    8064                 :      440954 :             Oid         clause_op = InvalidOid;
    8065                 :             :             int         op_strategy;
    8066                 :             : 
    8067         [ +  + ]:      440954 :             if (IsA(clause, OpExpr))
    8068                 :             :             {
    8069                 :      426480 :                 OpExpr     *op = (OpExpr *) clause;
    8070                 :             : 
    8071                 :      426480 :                 clause_op = op->opno;
    8072                 :             :             }
    8073         [ +  + ]:       14474 :             else if (IsA(clause, RowCompareExpr))
    8074                 :             :             {
    8075                 :         330 :                 RowCompareExpr *rc = (RowCompareExpr *) clause;
    8076                 :             : 
    8077                 :         330 :                 clause_op = linitial_oid(rc->opnos);
    8078                 :         330 :                 found_row_compare = true;
    8079                 :             :             }
    8080         [ +  + ]:       14144 :             else if (IsA(clause, ScalarArrayOpExpr))
    8081                 :             :             {
    8082                 :       12246 :                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    8083                 :       12246 :                 Node       *other_operand = (Node *) lsecond(saop->args);
    8084                 :       12246 :                 double      alength = estimate_array_length(root, other_operand);
    8085                 :             : 
    8086                 :       12246 :                 clause_op = saop->opno;
    8087                 :       12246 :                 found_array = true;
    8088                 :             :                 /* estimate SA descents by indexBoundQuals only */
    8089         [ +  + ]:       12246 :                 if (alength > 1)
    8090                 :       12022 :                     num_sa_scans *= alength;
    8091                 :             :             }
    8092         [ +  - ]:        1898 :             else if (IsA(clause, NullTest))
    8093                 :             :             {
    8094                 :        1898 :                 NullTest   *nt = (NullTest *) clause;
    8095                 :             : 
    8096         [ +  + ]:        1898 :                 if (nt->nulltesttype == IS_NULL)
    8097                 :             :                 {
    8098                 :         200 :                     found_is_null_op = true;
    8099                 :             :                     /* IS NULL is like = for selectivity/skip scan purposes */
    8100                 :         200 :                     eqQualHere = true;
    8101                 :             :                 }
    8102                 :             :             }
    8103                 :             :             else
    8104         [ #  # ]:           0 :                 elog(ERROR, "unsupported indexqual type: %d",
    8105                 :             :                      (int) nodeTag(clause));
    8106                 :             : 
    8107                 :             :             /* check for equality operator */
    8108         [ +  + ]:      440954 :             if (OidIsValid(clause_op))
    8109                 :             :             {
    8110                 :      439056 :                 op_strategy = get_op_opfamily_strategy(clause_op,
    8111                 :      439056 :                                                        index->opfamily[indexcol]);
    8112                 :             :                 Assert(op_strategy != 0);   /* not a member of opfamily?? */
    8113         [ +  + ]:      439056 :                 if (op_strategy == BTEqualStrategyNumber)
    8114                 :      415547 :                     eqQualHere = true;
    8115                 :             :             }
    8116                 :             : 
    8117                 :      440954 :             indexBoundQuals = lappend(indexBoundQuals, rinfo);
    8118                 :             : 
    8119                 :             :             /*
    8120                 :             :              * We apply inequality selectivities to estimate index descent
    8121                 :             :              * costs with scans that use skip arrays.  Save this indexcol's
    8122                 :             :              * RestrictInfos if it looks like they'll be needed for that.
    8123                 :             :              */
    8124   [ +  +  +  + ]:      440954 :             if (!eqQualHere && !found_row_compare &&
    8125         [ +  + ]:       24310 :                 indexcol < index->nkeycolumns - 1)
    8126                 :        4772 :                 indexSkipQuals = lappend(indexSkipQuals, rinfo);
    8127                 :             :         }
    8128                 :             :     }
    8129                 :             : 
    8130                 :             :     /*
    8131                 :             :      * If index is unique and we found an '=' clause for each column, we can
    8132                 :             :      * just assume numIndexTuples = 1 and skip the expensive
    8133                 :             :      * clauselist_selectivity calculations.  However, an array or NullTest
    8134                 :             :      * always invalidates that theory (even when eqQualHere has been set).
    8135                 :             :      */
    8136         [ +  + ]:      636413 :     if (index->unique &&
    8137   [ +  +  +  + ]:      508393 :         indexcol == index->nkeycolumns - 1 &&
    8138                 :      183137 :         eqQualHere &&
    8139         [ +  + ]:      183137 :         !found_array &&
    8140         [ +  + ]:      177731 :         !found_is_null_op)
    8141                 :      177691 :         numIndexTuples = 1.0;
    8142                 :             :     else
    8143                 :             :     {
    8144                 :             :         List       *selectivityQuals;
    8145                 :             :         Selectivity btreeSelectivity;
    8146                 :             : 
    8147                 :             :         /*
    8148                 :             :          * If the index is partial, AND the index predicate with the
    8149                 :             :          * index-bound quals to produce a more accurate idea of the number of
    8150                 :             :          * rows covered by the bound conditions.
    8151                 :             :          */
    8152                 :      458722 :         selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
    8153                 :             : 
    8154                 :      458722 :         btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
    8155                 :      458722 :                                                   index->rel->relid,
    8156                 :             :                                                   JOIN_INNER,
    8157                 :             :                                                   NULL);
    8158                 :      458722 :         numIndexTuples = btreeSelectivity * index->rel->tuples;
    8159                 :             : 
    8160                 :             :         /*
    8161                 :             :          * btree automatically combines individual array element primitive
    8162                 :             :          * index scans whenever the tuples covered by the next set of array
    8163                 :             :          * keys are close to tuples covered by the current set.  That puts a
    8164                 :             :          * natural ceiling on the worst case number of descents -- there
    8165                 :             :          * cannot possibly be more than one descent per leaf page scanned.
    8166                 :             :          *
    8167                 :             :          * Clamp the number of descents to at most 1/3 the number of index
    8168                 :             :          * pages.  This avoids implausibly high estimates with low selectivity
    8169                 :             :          * paths, where scans usually require only one or two descents.  This
    8170                 :             :          * is most likely to help when there are several SAOP clauses, where
    8171                 :             :          * naively accepting the total number of distinct combinations of
    8172                 :             :          * array elements as the number of descents would frequently lead to
    8173                 :             :          * wild overestimates.
    8174                 :             :          *
    8175                 :             :          * We somewhat arbitrarily don't just make the cutoff the total number
    8176                 :             :          * of leaf pages (we make it 1/3 the total number of pages instead) to
    8177                 :             :          * give the btree code credit for its ability to continue on the leaf
    8178                 :             :          * level with low selectivity scans.
    8179                 :             :          *
    8180                 :             :          * Note: num_sa_scans includes both ScalarArrayOp array elements and
    8181                 :             :          * skip array elements whose qual affects our numIndexTuples estimate.
    8182                 :             :          */
    8183         [ +  + ]:      458722 :         num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
    8184         [ +  + ]:      458722 :         num_sa_scans = Max(num_sa_scans, 1);
    8185                 :             : 
    8186                 :             :         /*
    8187                 :             :          * As in genericcostestimate(), we have to adjust for any array quals
    8188                 :             :          * included in indexBoundQuals, and then round to integer.
    8189                 :             :          *
    8190                 :             :          * It is tempting to make genericcostestimate behave as if array
    8191                 :             :          * clauses work in almost the same way as scalar operators during
    8192                 :             :          * btree scans, making the top-level scan look like a continuous scan
    8193                 :             :          * (as opposed to num_sa_scans-many primitive index scans).  After
    8194                 :             :          * all, btree scans mostly work like that at runtime.  However, such a
    8195                 :             :          * scheme would badly bias genericcostestimate's simplistic approach
    8196                 :             :          * to calculating numIndexPages through prorating.
    8197                 :             :          *
    8198                 :             :          * Stick with the approach taken by non-native SAOP scans for now.
    8199                 :             :          * genericcostestimate will use the Mackert-Lohman formula to
    8200                 :             :          * compensate for repeat page fetches, even though that definitely
    8201                 :             :          * won't happen during btree scans (not for leaf pages, at least).
    8202                 :             :          * We're usually very pessimistic about the number of primitive index
    8203                 :             :          * scans that will be required, but it's not clear how to do better.
    8204                 :             :          */
    8205                 :      458722 :         numIndexTuples = rint(numIndexTuples / num_sa_scans);
    8206                 :             :     }
    8207                 :             : 
    8208                 :             :     /*
    8209                 :             :      * Now do generic index cost estimation.
    8210                 :             :      *
    8211                 :             :      * While we expended effort to make realistic estimates of numIndexTuples
    8212                 :             :      * and num_sa_scans, we are content to count only the btree metapage as
    8213                 :             :      * non-leaf.  btree fanout is typically high enough that upper pages are
    8214                 :             :      * few relative to leaf pages, so accounting for them would move the
    8215                 :             :      * estimates at most a percent or two.  Given the uncertainty in just how
    8216                 :             :      * many upper pages exist in a particular index, we'll skip trying to
    8217                 :             :      * handle that.
    8218                 :             :      */
    8219                 :      636413 :     costs.numIndexTuples = numIndexTuples;
    8220                 :      636413 :     costs.num_sa_scans = num_sa_scans;
    8221                 :      636413 :     costs.numNonLeafPages = 1;
    8222                 :             : 
    8223                 :      636413 :     genericcostestimate(root, path, loop_count, &costs);
    8224                 :             : 
    8225                 :             :     /*
    8226                 :             :      * Add a CPU-cost component to represent the costs of initial btree
    8227                 :             :      * descent.  We don't charge any I/O cost for touching upper btree levels,
    8228                 :             :      * since they tend to stay in cache, but we still have to do about log2(N)
    8229                 :             :      * comparisons to descend a btree of N leaf tuples.  We charge one
    8230                 :             :      * cpu_operator_cost per comparison.
    8231                 :             :      *
    8232                 :             :      * If there are SAOP or skip array keys, charge this once per estimated
    8233                 :             :      * index descent.  The ones after the first one are not startup cost so
    8234                 :             :      * far as the overall plan goes, so just add them to "total" cost.
    8235                 :             :      */
    8236         [ +  + ]:      636413 :     if (index->tuples > 1)        /* avoid computing log(0) */
    8237                 :             :     {
    8238                 :      582406 :         descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
    8239                 :      582406 :         costs.indexStartupCost += descentCost;
    8240                 :      582406 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    8241                 :             :     }
    8242                 :             : 
    8243                 :             :     /*
    8244                 :             :      * Even though we're not charging I/O cost for touching upper btree pages,
    8245                 :             :      * it's still reasonable to charge some CPU cost per page descended
    8246                 :             :      * through.  Moreover, if we had no such charge at all, bloated indexes
    8247                 :             :      * would appear to have the same search cost as unbloated ones, at least
    8248                 :             :      * in cases where only a single leaf page is expected to be visited.  This
    8249                 :             :      * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
    8250                 :             :      * touched.  The number of such pages is btree tree height plus one (ie,
    8251                 :             :      * we charge for the leaf page too).  As above, charge once per estimated
    8252                 :             :      * SAOP/skip array descent.
    8253                 :             :      */
    8254                 :      636413 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8255                 :      636413 :     costs.indexStartupCost += descentCost;
    8256                 :      636413 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    8257                 :             : 
    8258         [ +  + ]:      636413 :     if (!have_correlation)
    8259                 :             :     {
    8260                 :      611258 :         examine_indexcol_variable(root, index, 0, &vardata);
    8261         [ +  + ]:      611258 :         if (HeapTupleIsValid(vardata.statsTuple))
    8262                 :      398708 :             costs.indexCorrelation = btcost_correlation(index, &vardata);
    8263         [ +  + ]:      611258 :         ReleaseVariableStats(vardata);
    8264                 :             :     }
    8265                 :             :     else
    8266                 :             :     {
    8267                 :             :         /* btcost_correlation already called earlier on */
    8268                 :       25155 :         costs.indexCorrelation = correlation;
    8269                 :             :     }
    8270                 :             : 
    8271                 :      636413 :     *indexStartupCost = costs.indexStartupCost;
    8272                 :      636413 :     *indexTotalCost = costs.indexTotalCost;
    8273                 :      636413 :     *indexSelectivity = costs.indexSelectivity;
    8274                 :      636413 :     *indexCorrelation = costs.indexCorrelation;
    8275                 :      636413 :     *indexPages = costs.numIndexPages;
    8276                 :      636413 : }
    8277                 :             : 
    8278                 :             : void
    8279                 :         308 : hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8280                 :             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    8281                 :             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    8282                 :             :                  double *indexPages)
    8283                 :             : {
    8284                 :         308 :     GenericCosts costs = {0};
    8285                 :             : 
    8286                 :             :     /* As in btcostestimate, count only the metapage as non-leaf */
    8287                 :         308 :     costs.numNonLeafPages = 1;
    8288                 :             : 
    8289                 :         308 :     genericcostestimate(root, path, loop_count, &costs);
    8290                 :             : 
    8291                 :             :     /*
    8292                 :             :      * A hash index has no descent costs as such, since the index AM can go
    8293                 :             :      * directly to the target bucket after computing the hash value.  There
    8294                 :             :      * are a couple of other hash-specific costs that we could conceivably add
    8295                 :             :      * here, though:
    8296                 :             :      *
    8297                 :             :      * Ideally we'd charge spc_random_page_cost for each page in the target
    8298                 :             :      * bucket, not just the numIndexPages pages that genericcostestimate
    8299                 :             :      * thought we'd visit.  However in most cases we don't know which bucket
    8300                 :             :      * that will be.  There's no point in considering the average bucket size
    8301                 :             :      * because the hash AM makes sure that's always one page.
    8302                 :             :      *
    8303                 :             :      * Likewise, we could consider charging some CPU for each index tuple in
    8304                 :             :      * the bucket, if we knew how many there were.  But the per-tuple cost is
    8305                 :             :      * just a hash value comparison, not a general datatype-dependent
    8306                 :             :      * comparison, so any such charge ought to be quite a bit less than
    8307                 :             :      * cpu_operator_cost; which makes it probably not worth worrying about.
    8308                 :             :      *
    8309                 :             :      * A bigger issue is that chance hash-value collisions will result in
    8310                 :             :      * wasted probes into the heap.  We don't currently attempt to model this
    8311                 :             :      * cost on the grounds that it's rare, but maybe it's not rare enough.
    8312                 :             :      * (Any fix for this ought to consider the generic lossy-operator problem,
    8313                 :             :      * though; it's not entirely hash-specific.)
    8314                 :             :      */
    8315                 :             : 
    8316                 :         308 :     *indexStartupCost = costs.indexStartupCost;
    8317                 :         308 :     *indexTotalCost = costs.indexTotalCost;
    8318                 :         308 :     *indexSelectivity = costs.indexSelectivity;
    8319                 :         308 :     *indexCorrelation = costs.indexCorrelation;
    8320                 :         308 :     *indexPages = costs.numIndexPages;
    8321                 :         308 : }
    8322                 :             : 
    8323                 :             : void
    8324                 :        4778 : gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8325                 :             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    8326                 :             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    8327                 :             :                  double *indexPages)
    8328                 :             : {
    8329                 :        4778 :     IndexOptInfo *index = path->indexinfo;
    8330                 :        4778 :     GenericCosts costs = {0};
    8331                 :             :     Cost        descentCost;
    8332                 :             : 
    8333                 :             :     /* GiST has no metapage, so we treat all pages as leaf pages */
    8334                 :             : 
    8335                 :        4778 :     genericcostestimate(root, path, loop_count, &costs);
    8336                 :             : 
    8337                 :             :     /*
    8338                 :             :      * We model index descent costs similarly to those for btree, but to do
    8339                 :             :      * that we first need an idea of the tree height.  We somewhat arbitrarily
    8340                 :             :      * assume that the fanout is 100, meaning the tree height is at most
    8341                 :             :      * log100(index->pages).
    8342                 :             :      *
    8343                 :             :      * Although this computation isn't really expensive enough to require
    8344                 :             :      * caching, we might as well use index->tree_height to cache it.
    8345                 :             :      */
    8346         [ +  + ]:        4778 :     if (index->tree_height < 0) /* unknown? */
    8347                 :             :     {
    8348         [ +  + ]:        4751 :         if (index->pages > 1) /* avoid computing log(0) */
    8349                 :        1964 :             index->tree_height = (int) (log(index->pages) / log(100.0));
    8350                 :             :         else
    8351                 :        2787 :             index->tree_height = 0;
    8352                 :             :     }
    8353                 :             : 
    8354                 :             :     /*
    8355                 :             :      * Add a CPU-cost component to represent the costs of initial descent. We
    8356                 :             :      * just use log(N) here not log2(N) since the branching factor isn't
    8357                 :             :      * necessarily two anyway.  As for btree, charge once per SA scan.
    8358                 :             :      */
    8359         [ +  - ]:        4778 :     if (index->tuples > 1)        /* avoid computing log(0) */
    8360                 :             :     {
    8361                 :        4778 :         descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
    8362                 :        4778 :         costs.indexStartupCost += descentCost;
    8363                 :        4778 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    8364                 :             :     }
    8365                 :             : 
    8366                 :             :     /*
    8367                 :             :      * Likewise add a per-page charge, calculated the same as for btrees.
    8368                 :             :      */
    8369                 :        4778 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8370                 :        4778 :     costs.indexStartupCost += descentCost;
    8371                 :        4778 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    8372                 :             : 
    8373                 :        4778 :     *indexStartupCost = costs.indexStartupCost;
    8374                 :        4778 :     *indexTotalCost = costs.indexTotalCost;
    8375                 :        4778 :     *indexSelectivity = costs.indexSelectivity;
    8376                 :        4778 :     *indexCorrelation = costs.indexCorrelation;
    8377                 :        4778 :     *indexPages = costs.numIndexPages;
    8378                 :        4778 : }
    8379                 :             : 
    8380                 :             : void
    8381                 :        1482 : spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8382                 :             :                 Cost *indexStartupCost, Cost *indexTotalCost,
    8383                 :             :                 Selectivity *indexSelectivity, double *indexCorrelation,
    8384                 :             :                 double *indexPages)
    8385                 :             : {
    8386                 :        1482 :     IndexOptInfo *index = path->indexinfo;
    8387                 :        1482 :     GenericCosts costs = {0};
    8388                 :             :     Cost        descentCost;
    8389                 :             : 
    8390                 :             :     /* As in btcostestimate, count only the metapage as non-leaf */
    8391                 :        1482 :     costs.numNonLeafPages = 1;
    8392                 :             : 
    8393                 :        1482 :     genericcostestimate(root, path, loop_count, &costs);
    8394                 :             : 
    8395                 :             :     /*
    8396                 :             :      * We model index descent costs similarly to those for btree, but to do
    8397                 :             :      * that we first need an idea of the tree height.  We somewhat arbitrarily
    8398                 :             :      * assume that the fanout is 100, meaning the tree height is at most
    8399                 :             :      * log100(index->pages).
    8400                 :             :      *
    8401                 :             :      * Although this computation isn't really expensive enough to require
    8402                 :             :      * caching, we might as well use index->tree_height to cache it.
    8403                 :             :      */
    8404         [ +  + ]:        1482 :     if (index->tree_height < 0) /* unknown? */
    8405                 :             :     {
    8406         [ +  - ]:        1477 :         if (index->pages > 1) /* avoid computing log(0) */
    8407                 :        1477 :             index->tree_height = (int) (log(index->pages) / log(100.0));
    8408                 :             :         else
    8409                 :           0 :             index->tree_height = 0;
    8410                 :             :     }
    8411                 :             : 
    8412                 :             :     /*
    8413                 :             :      * Add a CPU-cost component to represent the costs of initial descent. We
    8414                 :             :      * just use log(N) here not log2(N) since the branching factor isn't
    8415                 :             :      * necessarily two anyway.  As for btree, charge once per SA scan.
    8416                 :             :      */
    8417         [ +  - ]:        1482 :     if (index->tuples > 1)        /* avoid computing log(0) */
    8418                 :             :     {
    8419                 :        1482 :         descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
    8420                 :        1482 :         costs.indexStartupCost += descentCost;
    8421                 :        1482 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    8422                 :             :     }
    8423                 :             : 
    8424                 :             :     /*
    8425                 :             :      * Likewise add a per-page charge, calculated the same as for btrees.
    8426                 :             :      */
    8427                 :        1482 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8428                 :        1482 :     costs.indexStartupCost += descentCost;
    8429                 :        1482 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    8430                 :             : 
    8431                 :        1482 :     *indexStartupCost = costs.indexStartupCost;
    8432                 :        1482 :     *indexTotalCost = costs.indexTotalCost;
    8433                 :        1482 :     *indexSelectivity = costs.indexSelectivity;
    8434                 :        1482 :     *indexCorrelation = costs.indexCorrelation;
    8435                 :        1482 :     *indexPages = costs.numIndexPages;
    8436                 :        1482 : }
    8437                 :             : 
    8438                 :             : 
    8439                 :             : /*
    8440                 :             :  * Support routines for gincostestimate
    8441                 :             :  */
    8442                 :             : 
    8443                 :             : typedef struct
    8444                 :             : {
    8445                 :             :     bool        attHasFullScan[INDEX_MAX_KEYS];
    8446                 :             :     bool        attHasNormalScan[INDEX_MAX_KEYS];
    8447                 :             :     double      partialEntries;
    8448                 :             :     double      exactEntries;
    8449                 :             :     double      searchEntries;
    8450                 :             :     double      arrayScans;
    8451                 :             : } GinQualCounts;
    8452                 :             : 
    8453                 :             : /*
    8454                 :             :  * Estimate the number of index terms that need to be searched for while
    8455                 :             :  * testing the given GIN query, and increment the counts in *counts
    8456                 :             :  * appropriately.  If the query is unsatisfiable, return false.
    8457                 :             :  */
    8458                 :             : static bool
    8459                 :        1714 : gincost_pattern(IndexOptInfo *index, int indexcol,
    8460                 :             :                 Oid clause_op, Datum query,
    8461                 :             :                 GinQualCounts *counts)
    8462                 :             : {
    8463                 :             :     FmgrInfo    flinfo;
    8464                 :             :     Oid         extractProcOid;
    8465                 :             :     Oid         collation;
    8466                 :             :     int         strategy_op;
    8467                 :             :     Oid         lefttype,
    8468                 :             :                 righttype;
    8469                 :        1714 :     int32       nentries = 0;
    8470                 :        1714 :     bool       *partial_matches = NULL;
    8471                 :        1714 :     Pointer    *extra_data = NULL;
    8472                 :        1714 :     bool       *nullFlags = NULL;
    8473                 :        1714 :     int32       searchMode = GIN_SEARCH_MODE_DEFAULT;
    8474                 :             :     int32       i;
    8475                 :             : 
    8476                 :             :     Assert(indexcol < index->nkeycolumns);
    8477                 :             : 
    8478                 :             :     /*
    8479                 :             :      * Get the operator's strategy number and declared input data types within
    8480                 :             :      * the index opfamily.  (We don't need the latter, but we use
    8481                 :             :      * get_op_opfamily_properties because it will throw error if it fails to
    8482                 :             :      * find a matching pg_amop entry.)
    8483                 :             :      */
    8484                 :        1714 :     get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
    8485                 :             :                                &strategy_op, &lefttype, &righttype);
    8486                 :             : 
    8487                 :             :     /*
    8488                 :             :      * GIN always uses the "default" support functions, which are those with
    8489                 :             :      * lefttype == righttype == the opclass' opcintype (see
    8490                 :             :      * IndexSupportInitialize in relcache.c).
    8491                 :             :      */
    8492                 :        1714 :     extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
    8493                 :        1714 :                                        index->opcintype[indexcol],
    8494                 :        1714 :                                        index->opcintype[indexcol],
    8495                 :             :                                        GIN_EXTRACTQUERY_PROC);
    8496                 :             : 
    8497         [ -  + ]:        1714 :     if (!OidIsValid(extractProcOid))
    8498                 :             :     {
    8499                 :             :         /* should not happen; throw same error as index_getprocinfo */
    8500         [ #  # ]:           0 :         elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
    8501                 :             :              GIN_EXTRACTQUERY_PROC, indexcol + 1,
    8502                 :             :              get_rel_name(index->indexoid));
    8503                 :             :     }
    8504                 :             : 
    8505                 :             :     /*
    8506                 :             :      * Choose collation to pass to extractProc (should match initGinState).
    8507                 :             :      */
    8508         [ +  + ]:        1714 :     if (OidIsValid(index->indexcollations[indexcol]))
    8509                 :         243 :         collation = index->indexcollations[indexcol];
    8510                 :             :     else
    8511                 :        1471 :         collation = DEFAULT_COLLATION_OID;
    8512                 :             : 
    8513                 :        1714 :     fmgr_info(extractProcOid, &flinfo);
    8514                 :             : 
    8515                 :        1714 :     set_fn_opclass_options(&flinfo, index->opclassoptions[indexcol]);
    8516                 :             : 
    8517                 :        1714 :     FunctionCall7Coll(&flinfo,
    8518                 :             :                       collation,
    8519                 :             :                       query,
    8520                 :             :                       PointerGetDatum(&nentries),
    8521                 :             :                       UInt16GetDatum(strategy_op),
    8522                 :             :                       PointerGetDatum(&partial_matches),
    8523                 :             :                       PointerGetDatum(&extra_data),
    8524                 :             :                       PointerGetDatum(&nullFlags),
    8525                 :             :                       PointerGetDatum(&searchMode));
    8526                 :             : 
    8527   [ +  +  +  + ]:        1714 :     if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
    8528                 :             :     {
    8529                 :             :         /* No match is possible */
    8530                 :          10 :         return false;
    8531                 :             :     }
    8532                 :             : 
    8533         [ +  + ]:        5854 :     for (i = 0; i < nentries; i++)
    8534                 :             :     {
    8535                 :             :         /*
    8536                 :             :          * For partial match we haven't any information to estimate number of
    8537                 :             :          * matched entries in index, so, we just estimate it as 100
    8538                 :             :          */
    8539   [ +  +  +  + ]:        4150 :         if (partial_matches && partial_matches[i])
    8540                 :         361 :             counts->partialEntries += 100;
    8541                 :             :         else
    8542                 :        3789 :             counts->exactEntries++;
    8543                 :             : 
    8544                 :        4150 :         counts->searchEntries++;
    8545                 :             :     }
    8546                 :             : 
    8547         [ +  + ]:        1704 :     if (searchMode == GIN_SEARCH_MODE_DEFAULT)
    8548                 :             :     {
    8549                 :        1322 :         counts->attHasNormalScan[indexcol] = true;
    8550                 :             :     }
    8551         [ +  + ]:         382 :     else if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
    8552                 :             :     {
    8553                 :             :         /* Treat "include empty" like an exact-match item */
    8554                 :          36 :         counts->attHasNormalScan[indexcol] = true;
    8555                 :          36 :         counts->exactEntries++;
    8556                 :          36 :         counts->searchEntries++;
    8557                 :             :     }
    8558                 :             :     else
    8559                 :             :     {
    8560                 :             :         /* It's GIN_SEARCH_MODE_ALL */
    8561                 :         346 :         counts->attHasFullScan[indexcol] = true;
    8562                 :             :     }
    8563                 :             : 
    8564                 :        1704 :     return true;
    8565                 :             : }
    8566                 :             : 
    8567                 :             : /*
    8568                 :             :  * Estimate the number of index terms that need to be searched for while
    8569                 :             :  * testing the given GIN index clause, and increment the counts in *counts
    8570                 :             :  * appropriately.  If the query is unsatisfiable, return false.
    8571                 :             :  */
    8572                 :             : static bool
    8573                 :        1704 : gincost_opexpr(PlannerInfo *root,
    8574                 :             :                IndexOptInfo *index,
    8575                 :             :                int indexcol,
    8576                 :             :                OpExpr *clause,
    8577                 :             :                GinQualCounts *counts)
    8578                 :             : {
    8579                 :        1704 :     Oid         clause_op = clause->opno;
    8580                 :        1704 :     Node       *operand = (Node *) lsecond(clause->args);
    8581                 :             : 
    8582                 :             :     /* aggressively reduce to a constant, and look through relabeling */
    8583                 :        1704 :     operand = estimate_expression_value(root, operand);
    8584                 :             : 
    8585         [ -  + ]:        1704 :     if (IsA(operand, RelabelType))
    8586                 :           0 :         operand = (Node *) ((RelabelType *) operand)->arg;
    8587                 :             : 
    8588                 :             :     /*
    8589                 :             :      * It's impossible to call extractQuery method for unknown operand. So
    8590                 :             :      * unless operand is a Const we can't do much; just assume there will be
    8591                 :             :      * one ordinary search entry from the operand at runtime.
    8592                 :             :      */
    8593         [ -  + ]:        1704 :     if (!IsA(operand, Const))
    8594                 :             :     {
    8595                 :           0 :         counts->exactEntries++;
    8596                 :           0 :         counts->searchEntries++;
    8597                 :           0 :         return true;
    8598                 :             :     }
    8599                 :             : 
    8600                 :             :     /* If Const is null, there can be no matches */
    8601         [ -  + ]:        1704 :     if (((Const *) operand)->constisnull)
    8602                 :           0 :         return false;
    8603                 :             : 
    8604                 :             :     /* Otherwise, apply extractQuery and get the actual term counts */
    8605                 :        1704 :     return gincost_pattern(index, indexcol, clause_op,
    8606                 :             :                            ((Const *) operand)->constvalue,
    8607                 :             :                            counts);
    8608                 :             : }
    8609                 :             : 
    8610                 :             : /*
    8611                 :             :  * Estimate the number of index terms that need to be searched for while
    8612                 :             :  * testing the given GIN index clause, and increment the counts in *counts
    8613                 :             :  * appropriately.  If the query is unsatisfiable, return false.
    8614                 :             :  *
    8615                 :             :  * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
    8616                 :             :  * each of which involves one value from the RHS array, plus all the
    8617                 :             :  * non-array quals (if any).  To model this, we average the counts across
    8618                 :             :  * the RHS elements, and add the averages to the counts in *counts (which
    8619                 :             :  * correspond to per-indexscan costs).  We also multiply counts->arrayScans
    8620                 :             :  * by N, causing gincostestimate to scale up its estimates accordingly.
    8621                 :             :  */
    8622                 :             : static bool
    8623                 :           5 : gincost_scalararrayopexpr(PlannerInfo *root,
    8624                 :             :                           IndexOptInfo *index,
    8625                 :             :                           int indexcol,
    8626                 :             :                           ScalarArrayOpExpr *clause,
    8627                 :             :                           double numIndexEntries,
    8628                 :             :                           GinQualCounts *counts)
    8629                 :             : {
    8630                 :           5 :     Oid         clause_op = clause->opno;
    8631                 :           5 :     Node       *rightop = (Node *) lsecond(clause->args);
    8632                 :             :     ArrayType  *arrayval;
    8633                 :             :     int16       elmlen;
    8634                 :             :     bool        elmbyval;
    8635                 :             :     char        elmalign;
    8636                 :             :     int         numElems;
    8637                 :             :     Datum      *elemValues;
    8638                 :             :     bool       *elemNulls;
    8639                 :             :     GinQualCounts arraycounts;
    8640                 :           5 :     int         numPossible = 0;
    8641                 :             :     int         i;
    8642                 :             : 
    8643                 :             :     Assert(clause->useOr);
    8644                 :             : 
    8645                 :             :     /* aggressively reduce to a constant, and look through relabeling */
    8646                 :           5 :     rightop = estimate_expression_value(root, rightop);
    8647                 :             : 
    8648         [ -  + ]:           5 :     if (IsA(rightop, RelabelType))
    8649                 :           0 :         rightop = (Node *) ((RelabelType *) rightop)->arg;
    8650                 :             : 
    8651                 :             :     /*
    8652                 :             :      * It's impossible to call extractQuery method for unknown operand. So
    8653                 :             :      * unless operand is a Const we can't do much; just assume there will be
    8654                 :             :      * one ordinary search entry from each array entry at runtime, and fall
    8655                 :             :      * back on a probably-bad estimate of the number of array entries.
    8656                 :             :      */
    8657         [ -  + ]:           5 :     if (!IsA(rightop, Const))
    8658                 :             :     {
    8659                 :           0 :         counts->exactEntries++;
    8660                 :           0 :         counts->searchEntries++;
    8661                 :           0 :         counts->arrayScans *= estimate_array_length(root, rightop);
    8662                 :           0 :         return true;
    8663                 :             :     }
    8664                 :             : 
    8665                 :             :     /* If Const is null, there can be no matches */
    8666         [ -  + ]:           5 :     if (((Const *) rightop)->constisnull)
    8667                 :           0 :         return false;
    8668                 :             : 
    8669                 :             :     /* Otherwise, extract the array elements and iterate over them */
    8670                 :           5 :     arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
    8671                 :           5 :     get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
    8672                 :             :                          &elmlen, &elmbyval, &elmalign);
    8673                 :           5 :     deconstruct_array(arrayval,
    8674                 :             :                       ARR_ELEMTYPE(arrayval),
    8675                 :             :                       elmlen, elmbyval, elmalign,
    8676                 :             :                       &elemValues, &elemNulls, &numElems);
    8677                 :             : 
    8678                 :           5 :     memset(&arraycounts, 0, sizeof(arraycounts));
    8679                 :             : 
    8680         [ +  + ]:          15 :     for (i = 0; i < numElems; i++)
    8681                 :             :     {
    8682                 :             :         GinQualCounts elemcounts;
    8683                 :             : 
    8684                 :             :         /* NULL can't match anything, so ignore, as the executor will */
    8685         [ -  + ]:          10 :         if (elemNulls[i])
    8686                 :           0 :             continue;
    8687                 :             : 
    8688                 :             :         /* Otherwise, apply extractQuery and get the actual term counts */
    8689                 :          10 :         memset(&elemcounts, 0, sizeof(elemcounts));
    8690                 :             : 
    8691         [ +  - ]:          10 :         if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
    8692                 :             :                             &elemcounts))
    8693                 :             :         {
    8694                 :             :             /* We ignore array elements that are unsatisfiable patterns */
    8695                 :          10 :             numPossible++;
    8696                 :             : 
    8697         [ -  + ]:          10 :             if (elemcounts.attHasFullScan[indexcol] &&
    8698         [ #  # ]:           0 :                 !elemcounts.attHasNormalScan[indexcol])
    8699                 :             :             {
    8700                 :             :                 /*
    8701                 :             :                  * Full index scan will be required.  We treat this as if
    8702                 :             :                  * every key in the index had been listed in the query; is
    8703                 :             :                  * that reasonable?
    8704                 :             :                  */
    8705                 :           0 :                 elemcounts.partialEntries = 0;
    8706                 :           0 :                 elemcounts.exactEntries = numIndexEntries;
    8707                 :           0 :                 elemcounts.searchEntries = numIndexEntries;
    8708                 :             :             }
    8709                 :          10 :             arraycounts.partialEntries += elemcounts.partialEntries;
    8710                 :          10 :             arraycounts.exactEntries += elemcounts.exactEntries;
    8711                 :          10 :             arraycounts.searchEntries += elemcounts.searchEntries;
    8712                 :             :         }
    8713                 :             :     }
    8714                 :             : 
    8715         [ -  + ]:           5 :     if (numPossible == 0)
    8716                 :             :     {
    8717                 :             :         /* No satisfiable patterns in the array */
    8718                 :           0 :         return false;
    8719                 :             :     }
    8720                 :             : 
    8721                 :             :     /*
    8722                 :             :      * Now add the averages to the global counts.  This will give us an
    8723                 :             :      * estimate of the average number of terms searched for in each indexscan,
    8724                 :             :      * including contributions from both array and non-array quals.
    8725                 :             :      */
    8726                 :           5 :     counts->partialEntries += arraycounts.partialEntries / numPossible;
    8727                 :           5 :     counts->exactEntries += arraycounts.exactEntries / numPossible;
    8728                 :           5 :     counts->searchEntries += arraycounts.searchEntries / numPossible;
    8729                 :             : 
    8730                 :           5 :     counts->arrayScans *= numPossible;
    8731                 :             : 
    8732                 :           5 :     return true;
    8733                 :             : }
    8734                 :             : 
    8735                 :             : /*
    8736                 :             :  * GIN has search behavior completely different from other index types
    8737                 :             :  */
    8738                 :             : void
    8739                 :        1546 : gincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8740                 :             :                 Cost *indexStartupCost, Cost *indexTotalCost,
    8741                 :             :                 Selectivity *indexSelectivity, double *indexCorrelation,
    8742                 :             :                 double *indexPages)
    8743                 :             : {
    8744                 :        1546 :     IndexOptInfo *index = path->indexinfo;
    8745                 :        1546 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    8746                 :             :     List       *selectivityQuals;
    8747                 :        1546 :     double      numPages = index->pages,
    8748                 :        1546 :                 numTuples = index->tuples;
    8749                 :             :     double      numEntryPages,
    8750                 :             :                 numDataPages,
    8751                 :             :                 numPendingPages,
    8752                 :             :                 numEntries;
    8753                 :             :     GinQualCounts counts;
    8754                 :             :     bool        matchPossible;
    8755                 :             :     bool        fullIndexScan;
    8756                 :             :     double      partialScale;
    8757                 :             :     double      entryPagesFetched,
    8758                 :             :                 dataPagesFetched,
    8759                 :             :                 dataPagesFetchedBySel;
    8760                 :             :     double      qual_op_cost,
    8761                 :             :                 qual_arg_cost,
    8762                 :             :                 spc_random_page_cost,
    8763                 :             :                 outer_scans;
    8764                 :             :     Cost        descentCost;
    8765                 :             :     Relation    indexRel;
    8766                 :             :     GinStatsData ginStats;
    8767                 :             :     ListCell   *lc;
    8768                 :             :     int         i;
    8769                 :             : 
    8770                 :             :     /*
    8771                 :             :      * Obtain statistical information from the meta page, if possible.  Else
    8772                 :             :      * set ginStats to zeroes, and we'll cope below.
    8773                 :             :      */
    8774         [ +  - ]:        1546 :     if (!index->hypothetical)
    8775                 :             :     {
    8776                 :             :         /* Lock should have already been obtained in plancat.c */
    8777                 :        1546 :         indexRel = index_open(index->indexoid, NoLock);
    8778                 :        1546 :         ginGetStats(indexRel, &ginStats);
    8779                 :        1546 :         index_close(indexRel, NoLock);
    8780                 :             :     }
    8781                 :             :     else
    8782                 :             :     {
    8783                 :           0 :         memset(&ginStats, 0, sizeof(ginStats));
    8784                 :             :     }
    8785                 :             : 
    8786                 :             :     /*
    8787                 :             :      * Assuming we got valid (nonzero) stats at all, nPendingPages can be
    8788                 :             :      * trusted, but the other fields are data as of the last VACUUM.  We can
    8789                 :             :      * scale them up to account for growth since then, but that method only
    8790                 :             :      * goes so far; in the worst case, the stats might be for a completely
    8791                 :             :      * empty index, and scaling them will produce pretty bogus numbers.
    8792                 :             :      * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
    8793                 :             :      * it's grown more than that, fall back to estimating things only from the
    8794                 :             :      * assumed-accurate index size.  But we'll trust nPendingPages in any case
    8795                 :             :      * so long as it's not clearly insane, ie, more than the index size.
    8796                 :             :      */
    8797         [ +  - ]:        1546 :     if (ginStats.nPendingPages < numPages)
    8798                 :        1546 :         numPendingPages = ginStats.nPendingPages;
    8799                 :             :     else
    8800                 :           0 :         numPendingPages = 0;
    8801                 :             : 
    8802   [ +  -  +  - ]:        1546 :     if (numPages > 0 && ginStats.nTotalPages <= numPages &&
    8803         [ +  + ]:        1546 :         ginStats.nTotalPages > numPages / 4 &&
    8804   [ +  -  +  + ]:        1506 :         ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
    8805                 :        1292 :     {
    8806                 :             :         /*
    8807                 :             :          * OK, the stats seem close enough to sane to be trusted.  But we
    8808                 :             :          * still need to scale them by the ratio numPages / nTotalPages to
    8809                 :             :          * account for growth since the last VACUUM.
    8810                 :             :          */
    8811                 :        1292 :         double      scale = numPages / ginStats.nTotalPages;
    8812                 :             : 
    8813                 :        1292 :         numEntryPages = ceil(ginStats.nEntryPages * scale);
    8814                 :        1292 :         numDataPages = ceil(ginStats.nDataPages * scale);
    8815                 :        1292 :         numEntries = ceil(ginStats.nEntries * scale);
    8816                 :             :         /* ensure we didn't round up too much */
    8817         [ +  + ]:        1292 :         numEntryPages = Min(numEntryPages, numPages - numPendingPages);
    8818         [ +  + ]:        1292 :         numDataPages = Min(numDataPages,
    8819                 :             :                            numPages - numPendingPages - numEntryPages);
    8820                 :             :     }
    8821                 :             :     else
    8822                 :             :     {
    8823                 :             :         /*
    8824                 :             :          * We might get here because it's a hypothetical index, or an index
    8825                 :             :          * created pre-9.1 and never vacuumed since upgrading (in which case
    8826                 :             :          * its stats would read as zeroes), or just because it's grown too
    8827                 :             :          * much since the last VACUUM for us to put our faith in scaling.
    8828                 :             :          *
    8829                 :             :          * Invent some plausible internal statistics based on the index page
    8830                 :             :          * count (and clamp that to at least 10 pages, just in case).  We
    8831                 :             :          * estimate that 90% of the index is entry pages, and the rest is data
    8832                 :             :          * pages.  Estimate 100 entries per entry page; this is rather bogus
    8833                 :             :          * since it'll depend on the size of the keys, but it's more robust
    8834                 :             :          * than trying to predict the number of entries per heap tuple.
    8835                 :             :          */
    8836         [ +  + ]:         254 :         numPages = Max(numPages, 10);
    8837                 :         254 :         numEntryPages = floor((numPages - numPendingPages) * 0.90);
    8838                 :         254 :         numDataPages = numPages - numPendingPages - numEntryPages;
    8839                 :         254 :         numEntries = floor(numEntryPages * 100);
    8840                 :             :     }
    8841                 :             : 
    8842                 :             :     /* In an empty index, numEntries could be zero.  Avoid divide-by-zero */
    8843         [ -  + ]:        1546 :     if (numEntries < 1)
    8844                 :           0 :         numEntries = 1;
    8845                 :             : 
    8846                 :             :     /*
    8847                 :             :      * If the index is partial, AND the index predicate with the index-bound
    8848                 :             :      * quals to produce a more accurate idea of the number of rows covered by
    8849                 :             :      * the bound conditions.
    8850                 :             :      */
    8851                 :        1546 :     selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
    8852                 :             : 
    8853                 :             :     /* Estimate the fraction of main-table tuples that will be visited */
    8854                 :        3092 :     *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
    8855                 :        1546 :                                                index->rel->relid,
    8856                 :             :                                                JOIN_INNER,
    8857                 :             :                                                NULL);
    8858                 :             : 
    8859                 :             :     /* fetch estimated page cost for tablespace containing index */
    8860                 :        1546 :     get_tablespace_page_costs(index->reltablespace,
    8861                 :             :                               &spc_random_page_cost,
    8862                 :             :                               NULL);
    8863                 :             : 
    8864                 :             :     /*
    8865                 :             :      * Generic assumption about index correlation: there isn't any.
    8866                 :             :      */
    8867                 :        1546 :     *indexCorrelation = 0.0;
    8868                 :             : 
    8869                 :             :     /*
    8870                 :             :      * Examine quals to estimate number of search entries & partial matches
    8871                 :             :      */
    8872                 :        1546 :     memset(&counts, 0, sizeof(counts));
    8873                 :        1546 :     counts.arrayScans = 1;
    8874                 :        1546 :     matchPossible = true;
    8875                 :             : 
    8876   [ +  -  +  +  :        3255 :     foreach(lc, path->indexclauses)
                   +  + ]
    8877                 :             :     {
    8878                 :        1709 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    8879                 :             :         ListCell   *lc2;
    8880                 :             : 
    8881   [ +  -  +  +  :        3408 :         foreach(lc2, iclause->indexquals)
                   +  + ]
    8882                 :             :         {
    8883                 :        1709 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    8884                 :        1709 :             Expr       *clause = rinfo->clause;
    8885                 :             : 
    8886         [ +  + ]:        1709 :             if (IsA(clause, OpExpr))
    8887                 :             :             {
    8888                 :        1704 :                 matchPossible = gincost_opexpr(root,
    8889                 :             :                                                index,
    8890                 :        1704 :                                                iclause->indexcol,
    8891                 :             :                                                (OpExpr *) clause,
    8892                 :             :                                                &counts);
    8893         [ +  + ]:        1704 :                 if (!matchPossible)
    8894                 :          10 :                     break;
    8895                 :             :             }
    8896         [ +  - ]:           5 :             else if (IsA(clause, ScalarArrayOpExpr))
    8897                 :             :             {
    8898                 :           5 :                 matchPossible = gincost_scalararrayopexpr(root,
    8899                 :             :                                                           index,
    8900                 :           5 :                                                           iclause->indexcol,
    8901                 :             :                                                           (ScalarArrayOpExpr *) clause,
    8902                 :             :                                                           numEntries,
    8903                 :             :                                                           &counts);
    8904         [ -  + ]:           5 :                 if (!matchPossible)
    8905                 :           0 :                     break;
    8906                 :             :             }
    8907                 :             :             else
    8908                 :             :             {
    8909                 :             :                 /* shouldn't be anything else for a GIN index */
    8910         [ #  # ]:           0 :                 elog(ERROR, "unsupported GIN indexqual type: %d",
    8911                 :             :                      (int) nodeTag(clause));
    8912                 :             :             }
    8913                 :             :         }
    8914                 :             :     }
    8915                 :             : 
    8916                 :             :     /* Fall out if there were any provably-unsatisfiable quals */
    8917         [ +  + ]:        1546 :     if (!matchPossible)
    8918                 :             :     {
    8919                 :          10 :         *indexStartupCost = 0;
    8920                 :          10 :         *indexTotalCost = 0;
    8921                 :          10 :         *indexSelectivity = 0;
    8922                 :          10 :         return;
    8923                 :             :     }
    8924                 :             : 
    8925                 :             :     /*
    8926                 :             :      * If attribute has a full scan and at the same time doesn't have normal
    8927                 :             :      * scan, then we'll have to scan all non-null entries of that attribute.
    8928                 :             :      * Currently, we don't have per-attribute statistics for GIN.  Thus, we
    8929                 :             :      * must assume the whole GIN index has to be scanned in this case.
    8930                 :             :      */
    8931                 :        1536 :     fullIndexScan = false;
    8932         [ +  + ]:        2989 :     for (i = 0; i < index->nkeycolumns; i++)
    8933                 :             :     {
    8934   [ +  +  +  + ]:        1726 :         if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
    8935                 :             :         {
    8936                 :         273 :             fullIndexScan = true;
    8937                 :         273 :             break;
    8938                 :             :         }
    8939                 :             :     }
    8940                 :             : 
    8941   [ +  +  -  + ]:        1536 :     if (fullIndexScan || indexQuals == NIL)
    8942                 :             :     {
    8943                 :             :         /*
    8944                 :             :          * Full index scan will be required.  We treat this as if every key in
    8945                 :             :          * the index had been listed in the query; is that reasonable?
    8946                 :             :          */
    8947                 :         273 :         counts.partialEntries = 0;
    8948                 :         273 :         counts.exactEntries = numEntries;
    8949                 :         273 :         counts.searchEntries = numEntries;
    8950                 :             :     }
    8951                 :             : 
    8952                 :             :     /* Will we have more than one iteration of a nestloop scan? */
    8953                 :        1536 :     outer_scans = loop_count;
    8954                 :             : 
    8955                 :             :     /*
    8956                 :             :      * Compute cost to begin scan, first of all, pay attention to pending
    8957                 :             :      * list.
    8958                 :             :      */
    8959                 :        1536 :     entryPagesFetched = numPendingPages;
    8960                 :             : 
    8961                 :             :     /*
    8962                 :             :      * Estimate number of entry pages read.  We need to do
    8963                 :             :      * counts.searchEntries searches.  Use a power function as it should be,
    8964                 :             :      * but tuples on leaf pages usually is much greater. Here we include all
    8965                 :             :      * searches in entry tree, including search of first entry in partial
    8966                 :             :      * match algorithm
    8967                 :             :      */
    8968                 :        1536 :     entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
    8969                 :             : 
    8970                 :             :     /*
    8971                 :             :      * Add an estimate of entry pages read by partial match algorithm. It's a
    8972                 :             :      * scan over leaf pages in entry tree.  We haven't any useful stats here,
    8973                 :             :      * so estimate it as proportion.  Because counts.partialEntries is really
    8974                 :             :      * pretty bogus (see code above), it's possible that it is more than
    8975                 :             :      * numEntries; clamp the proportion to ensure sanity.
    8976                 :             :      */
    8977                 :        1536 :     partialScale = counts.partialEntries / numEntries;
    8978         [ +  + ]:        1536 :     partialScale = Min(partialScale, 1.0);
    8979                 :             : 
    8980                 :        1536 :     entryPagesFetched += ceil(numEntryPages * partialScale);
    8981                 :             : 
    8982                 :             :     /*
    8983                 :             :      * Partial match algorithm reads all data pages before doing actual scan,
    8984                 :             :      * so it's a startup cost.  Again, we haven't any useful stats here, so
    8985                 :             :      * estimate it as proportion.
    8986                 :             :      */
    8987                 :        1536 :     dataPagesFetched = ceil(numDataPages * partialScale);
    8988                 :             : 
    8989                 :        1536 :     *indexStartupCost = 0;
    8990                 :        1536 :     *indexTotalCost = 0;
    8991                 :             : 
    8992                 :             :     /*
    8993                 :             :      * Add a CPU-cost component to represent the costs of initial entry btree
    8994                 :             :      * descent.  We don't charge any I/O cost for touching upper btree levels,
    8995                 :             :      * since they tend to stay in cache, but we still have to do about log2(N)
    8996                 :             :      * comparisons to descend a btree of N leaf tuples.  We charge one
    8997                 :             :      * cpu_operator_cost per comparison.
    8998                 :             :      *
    8999                 :             :      * If there are ScalarArrayOpExprs, charge this once per SA scan.  The
    9000                 :             :      * ones after the first one are not startup cost so far as the overall
    9001                 :             :      * plan is concerned, so add them only to "total" cost.
    9002                 :             :      */
    9003         [ +  - ]:        1536 :     if (numEntries > 1)          /* avoid computing log(0) */
    9004                 :             :     {
    9005                 :        1536 :         descentCost = ceil(log(numEntries) / log(2.0)) * cpu_operator_cost;
    9006                 :        1536 :         *indexStartupCost += descentCost * counts.searchEntries;
    9007                 :        1536 :         *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
    9008                 :             :     }
    9009                 :             : 
    9010                 :             :     /*
    9011                 :             :      * Add a cpu cost per entry-page fetched. This is not amortized over a
    9012                 :             :      * loop.
    9013                 :             :      */
    9014                 :        1536 :     *indexStartupCost += entryPagesFetched * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    9015                 :        1536 :     *indexTotalCost += entryPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    9016                 :             : 
    9017                 :             :     /*
    9018                 :             :      * Add a cpu cost per data-page fetched. This is also not amortized over a
    9019                 :             :      * loop. Since those are the data pages from the partial match algorithm,
    9020                 :             :      * charge them as startup cost.
    9021                 :             :      */
    9022                 :        1536 :     *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * dataPagesFetched;
    9023                 :             : 
    9024                 :             :     /*
    9025                 :             :      * Since we add the startup cost to the total cost later on, remove the
    9026                 :             :      * initial arrayscan from the total.
    9027                 :             :      */
    9028                 :        1536 :     *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    9029                 :             : 
    9030                 :             :     /*
    9031                 :             :      * Calculate cache effects if more than one scan due to nestloops or array
    9032                 :             :      * quals.  The result is pro-rated per nestloop scan, but the array qual
    9033                 :             :      * factor shouldn't be pro-rated (compare genericcostestimate).
    9034                 :             :      */
    9035   [ +  -  +  + ]:        1536 :     if (outer_scans > 1 || counts.arrayScans > 1)
    9036                 :             :     {
    9037                 :           5 :         entryPagesFetched *= outer_scans * counts.arrayScans;
    9038                 :           5 :         entryPagesFetched = index_pages_fetched(entryPagesFetched,
    9039                 :             :                                                 (BlockNumber) numEntryPages,
    9040                 :             :                                                 numEntryPages, root);
    9041                 :           5 :         entryPagesFetched /= outer_scans;
    9042                 :           5 :         dataPagesFetched *= outer_scans * counts.arrayScans;
    9043                 :           5 :         dataPagesFetched = index_pages_fetched(dataPagesFetched,
    9044                 :             :                                                (BlockNumber) numDataPages,
    9045                 :             :                                                numDataPages, root);
    9046                 :           5 :         dataPagesFetched /= outer_scans;
    9047                 :             :     }
    9048                 :             : 
    9049                 :             :     /*
    9050                 :             :      * Here we use random page cost because logically-close pages could be far
    9051                 :             :      * apart on disk.
    9052                 :             :      */
    9053                 :        1536 :     *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
    9054                 :             : 
    9055                 :             :     /*
    9056                 :             :      * Now compute the number of data pages fetched during the scan.
    9057                 :             :      *
    9058                 :             :      * We assume every entry to have the same number of items, and that there
    9059                 :             :      * is no overlap between them. (XXX: tsvector and array opclasses collect
    9060                 :             :      * statistics on the frequency of individual keys; it would be nice to use
    9061                 :             :      * those here.)
    9062                 :             :      */
    9063                 :        1536 :     dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
    9064                 :             : 
    9065                 :             :     /*
    9066                 :             :      * If there is a lot of overlap among the entries, in particular if one of
    9067                 :             :      * the entries is very frequent, the above calculation can grossly
    9068                 :             :      * under-estimate.  As a simple cross-check, calculate a lower bound based
    9069                 :             :      * on the overall selectivity of the quals.  At a minimum, we must read
    9070                 :             :      * one item pointer for each matching entry.
    9071                 :             :      *
    9072                 :             :      * The width of each item pointer varies, based on the level of
    9073                 :             :      * compression.  We don't have statistics on that, but an average of
    9074                 :             :      * around 3 bytes per item is fairly typical.
    9075                 :             :      */
    9076                 :        1536 :     dataPagesFetchedBySel = ceil(*indexSelectivity *
    9077                 :        1536 :                                  (numTuples / (BLCKSZ / 3)));
    9078         [ +  + ]:        1536 :     if (dataPagesFetchedBySel > dataPagesFetched)
    9079                 :        1243 :         dataPagesFetched = dataPagesFetchedBySel;
    9080                 :             : 
    9081                 :             :     /* Add one page cpu-cost to the startup cost */
    9082                 :        1536 :     *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
    9083                 :             : 
    9084                 :             :     /*
    9085                 :             :      * Add once again a CPU-cost for those data pages, before amortizing for
    9086                 :             :      * cache.
    9087                 :             :      */
    9088                 :        1536 :     *indexTotalCost += dataPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    9089                 :             : 
    9090                 :             :     /* Account for cache effects, the same as above */
    9091   [ +  -  +  + ]:        1536 :     if (outer_scans > 1 || counts.arrayScans > 1)
    9092                 :             :     {
    9093                 :           5 :         dataPagesFetched *= outer_scans * counts.arrayScans;
    9094                 :           5 :         dataPagesFetched = index_pages_fetched(dataPagesFetched,
    9095                 :             :                                                (BlockNumber) numDataPages,
    9096                 :             :                                                numDataPages, root);
    9097                 :           5 :         dataPagesFetched /= outer_scans;
    9098                 :             :     }
    9099                 :             : 
    9100                 :             :     /* And apply random_page_cost as the cost per page */
    9101                 :        1536 :     *indexTotalCost += *indexStartupCost +
    9102                 :        1536 :         dataPagesFetched * spc_random_page_cost;
    9103                 :             : 
    9104                 :             :     /*
    9105                 :             :      * Add on index qual eval costs, much as in genericcostestimate. We charge
    9106                 :             :      * cpu but we can disregard indexorderbys, since GIN doesn't support
    9107                 :             :      * those.
    9108                 :             :      */
    9109                 :        1536 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
    9110                 :        1536 :     qual_op_cost = cpu_operator_cost * list_length(indexQuals);
    9111                 :             : 
    9112                 :        1536 :     *indexStartupCost += qual_arg_cost;
    9113                 :        1536 :     *indexTotalCost += qual_arg_cost;
    9114                 :             : 
    9115                 :             :     /*
    9116                 :             :      * Add a cpu cost per search entry, corresponding to the actual visited
    9117                 :             :      * entries.
    9118                 :             :      */
    9119                 :        1536 :     *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
    9120                 :             :     /* Now add a cpu cost per tuple in the posting lists / trees */
    9121                 :        1536 :     *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
    9122                 :        1536 :     *indexPages = dataPagesFetched;
    9123                 :             : }
    9124                 :             : 
    9125                 :             : /*
    9126                 :             :  * BRIN has search behavior completely different from other index types
    9127                 :             :  */
    9128                 :             : void
    9129                 :        8944 : brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    9130                 :             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    9131                 :             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    9132                 :             :                  double *indexPages)
    9133                 :             : {
    9134                 :        8944 :     IndexOptInfo *index = path->indexinfo;
    9135                 :        8944 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    9136                 :        8944 :     double      numPages = index->pages;
    9137                 :        8944 :     RelOptInfo *baserel = index->rel;
    9138         [ +  - ]:        8944 :     RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
    9139                 :             :     Cost        spc_seq_page_cost;
    9140                 :             :     Cost        spc_random_page_cost;
    9141                 :             :     double      qual_arg_cost;
    9142                 :             :     double      qualSelectivity;
    9143                 :             :     BrinStatsData statsData;
    9144                 :             :     double      indexRanges;
    9145                 :             :     double      minimalRanges;
    9146                 :             :     double      estimatedRanges;
    9147                 :             :     double      selec;
    9148                 :             :     Relation    indexRel;
    9149                 :             :     ListCell   *l;
    9150                 :             :     VariableStatData vardata;
    9151                 :             : 
    9152                 :             :     Assert(rte->rtekind == RTE_RELATION);
    9153                 :             : 
    9154                 :             :     /* fetch estimated page cost for the tablespace containing the index */
    9155                 :        8944 :     get_tablespace_page_costs(index->reltablespace,
    9156                 :             :                               &spc_random_page_cost,
    9157                 :             :                               &spc_seq_page_cost);
    9158                 :             : 
    9159                 :             :     /*
    9160                 :             :      * Obtain some data from the index itself, if possible.  Otherwise invent
    9161                 :             :      * some plausible internal statistics based on the relation page count.
    9162                 :             :      */
    9163         [ +  - ]:        8944 :     if (!index->hypothetical)
    9164                 :             :     {
    9165                 :             :         /*
    9166                 :             :          * A lock should have already been obtained on the index in plancat.c.
    9167                 :             :          */
    9168                 :        8944 :         indexRel = index_open(index->indexoid, NoLock);
    9169                 :        8944 :         brinGetStats(indexRel, &statsData);
    9170                 :        8944 :         index_close(indexRel, NoLock);
    9171                 :             : 
    9172                 :             :         /* work out the actual number of ranges in the index */
    9173         [ +  + ]:        8944 :         indexRanges = Max(ceil((double) baserel->pages /
    9174                 :             :                                statsData.pagesPerRange), 1.0);
    9175                 :             :     }
    9176                 :             :     else
    9177                 :             :     {
    9178                 :             :         /*
    9179                 :             :          * Assume default number of pages per range, and estimate the number
    9180                 :             :          * of ranges based on that.
    9181                 :             :          */
    9182         [ #  # ]:           0 :         indexRanges = Max(ceil((double) baserel->pages /
    9183                 :             :                                BRIN_DEFAULT_PAGES_PER_RANGE), 1.0);
    9184                 :             : 
    9185                 :           0 :         statsData.pagesPerRange = BRIN_DEFAULT_PAGES_PER_RANGE;
    9186                 :           0 :         statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
    9187                 :             :     }
    9188                 :             : 
    9189                 :             :     /*
    9190                 :             :      * Compute index correlation
    9191                 :             :      *
    9192                 :             :      * Because we can use all index quals equally when scanning, we can use
    9193                 :             :      * the largest correlation (in absolute value) among columns used by the
    9194                 :             :      * query.  Start at zero, the worst possible case.  If we cannot find any
    9195                 :             :      * correlation statistics, we will keep it as 0.
    9196                 :             :      */
    9197                 :        8944 :     *indexCorrelation = 0;
    9198                 :             : 
    9199   [ +  -  +  +  :       17889 :     foreach(l, path->indexclauses)
                   +  + ]
    9200                 :             :     {
    9201                 :        8945 :         IndexClause *iclause = lfirst_node(IndexClause, l);
    9202                 :        8945 :         AttrNumber  attnum = index->indexkeys[iclause->indexcol];
    9203                 :             : 
    9204                 :             :         /* attempt to lookup stats in relation for this index column */
    9205         [ +  - ]:        8945 :         if (attnum != 0)
    9206                 :             :         {
    9207                 :             :             /* Simple variable -- look to stats for the underlying table */
    9208   [ -  +  -  - ]:        8945 :             if (get_relation_stats_hook &&
    9209                 :           0 :                 (*get_relation_stats_hook) (root, rte, attnum, &vardata))
    9210                 :             :             {
    9211                 :             :                 /*
    9212                 :             :                  * The hook took control of acquiring a stats tuple.  If it
    9213                 :             :                  * did supply a tuple, it'd better have supplied a freefunc.
    9214                 :             :                  */
    9215   [ #  #  #  # ]:           0 :                 if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
    9216         [ #  # ]:           0 :                     elog(ERROR,
    9217                 :             :                          "no function provided to release variable stats with");
    9218                 :             :             }
    9219                 :             :             else
    9220                 :             :             {
    9221                 :        8945 :                 vardata.statsTuple =
    9222                 :        8945 :                     SearchSysCache3(STATRELATTINH,
    9223                 :             :                                     ObjectIdGetDatum(rte->relid),
    9224                 :             :                                     Int16GetDatum(attnum),
    9225                 :             :                                     BoolGetDatum(false));
    9226                 :        8945 :                 vardata.freefunc = ReleaseSysCache;
    9227                 :             :             }
    9228                 :             :         }
    9229                 :             :         else
    9230                 :             :         {
    9231                 :             :             /*
    9232                 :             :              * Looks like we've found an expression column in the index. Let's
    9233                 :             :              * see if there's any stats for it.
    9234                 :             :              */
    9235                 :             : 
    9236                 :             :             /* get the attnum from the 0-based index. */
    9237                 :           0 :             attnum = iclause->indexcol + 1;
    9238                 :             : 
    9239   [ #  #  #  # ]:           0 :             if (get_index_stats_hook &&
    9240                 :           0 :                 (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
    9241                 :             :             {
    9242                 :             :                 /*
    9243                 :             :                  * The hook took control of acquiring a stats tuple.  If it
    9244                 :             :                  * did supply a tuple, it'd better have supplied a freefunc.
    9245                 :             :                  */
    9246         [ #  # ]:           0 :                 if (HeapTupleIsValid(vardata.statsTuple) &&
    9247         [ #  # ]:           0 :                     !vardata.freefunc)
    9248         [ #  # ]:           0 :                     elog(ERROR, "no function provided to release variable stats with");
    9249                 :             :             }
    9250                 :             :             else
    9251                 :             :             {
    9252                 :           0 :                 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
    9253                 :             :                                                      ObjectIdGetDatum(index->indexoid),
    9254                 :             :                                                      Int16GetDatum(attnum),
    9255                 :             :                                                      BoolGetDatum(false));
    9256                 :           0 :                 vardata.freefunc = ReleaseSysCache;
    9257                 :             :             }
    9258                 :             :         }
    9259                 :             : 
    9260         [ +  + ]:        8945 :         if (HeapTupleIsValid(vardata.statsTuple))
    9261                 :             :         {
    9262                 :             :             AttStatsSlot sslot;
    9263                 :             : 
    9264         [ +  - ]:          33 :             if (get_attstatsslot(&sslot, vardata.statsTuple,
    9265                 :             :                                  STATISTIC_KIND_CORRELATION, InvalidOid,
    9266                 :             :                                  ATTSTATSSLOT_NUMBERS))
    9267                 :             :             {
    9268                 :          33 :                 double      varCorrelation = 0.0;
    9269                 :             : 
    9270         [ +  - ]:          33 :                 if (sslot.nnumbers > 0)
    9271                 :          33 :                     varCorrelation = fabs(sslot.numbers[0]);
    9272                 :             : 
    9273         [ +  - ]:          33 :                 if (varCorrelation > *indexCorrelation)
    9274                 :          33 :                     *indexCorrelation = varCorrelation;
    9275                 :             : 
    9276                 :          33 :                 free_attstatsslot(&sslot);
    9277                 :             :             }
    9278                 :             :         }
    9279                 :             : 
    9280         [ +  + ]:        8945 :         ReleaseVariableStats(vardata);
    9281                 :             :     }
    9282                 :             : 
    9283                 :        8944 :     qualSelectivity = clauselist_selectivity(root, indexQuals,
    9284                 :        8944 :                                              baserel->relid,
    9285                 :             :                                              JOIN_INNER, NULL);
    9286                 :             : 
    9287                 :             :     /*
    9288                 :             :      * Now calculate the minimum possible ranges we could match with if all of
    9289                 :             :      * the rows were in the perfect order in the table's heap.
    9290                 :             :      */
    9291                 :        8944 :     minimalRanges = ceil(indexRanges * qualSelectivity);
    9292                 :             : 
    9293                 :             :     /*
    9294                 :             :      * Now estimate the number of ranges that we'll touch by using the
    9295                 :             :      * indexCorrelation from the stats. Careful not to divide by zero (note
    9296                 :             :      * we're using the absolute value of the correlation).
    9297                 :             :      */
    9298         [ +  + ]:        8944 :     if (*indexCorrelation < 1.0e-10)
    9299                 :        8911 :         estimatedRanges = indexRanges;
    9300                 :             :     else
    9301         [ +  + ]:          33 :         estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
    9302                 :             : 
    9303                 :             :     /* we expect to visit this portion of the table */
    9304                 :        8944 :     selec = estimatedRanges / indexRanges;
    9305                 :             : 
    9306   [ -  +  -  + ]:        8944 :     CLAMP_PROBABILITY(selec);
    9307                 :             : 
    9308                 :        8944 :     *indexSelectivity = selec;
    9309                 :             : 
    9310                 :             :     /*
    9311                 :             :      * Compute the index qual costs, much as in genericcostestimate, to add to
    9312                 :             :      * the index costs.  We can disregard indexorderbys, since BRIN doesn't
    9313                 :             :      * support those.
    9314                 :             :      */
    9315                 :        8944 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
    9316                 :             : 
    9317                 :             :     /*
    9318                 :             :      * Compute the startup cost as the cost to read the whole revmap
    9319                 :             :      * sequentially, including the cost to execute the index quals.
    9320                 :             :      */
    9321                 :        8944 :     *indexStartupCost =
    9322                 :        8944 :         spc_seq_page_cost * statsData.revmapNumPages * loop_count;
    9323                 :        8944 :     *indexStartupCost += qual_arg_cost;
    9324                 :             : 
    9325                 :             :     /*
    9326                 :             :      * To read a BRIN index there might be a bit of back and forth over
    9327                 :             :      * regular pages, as revmap might point to them out of sequential order;
    9328                 :             :      * calculate the total cost as reading the whole index in random order.
    9329                 :             :      */
    9330                 :        8944 :     *indexTotalCost = *indexStartupCost +
    9331                 :        8944 :         spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
    9332                 :             : 
    9333                 :             :     /*
    9334                 :             :      * Charge a small amount per range tuple which we expect to match to. This
    9335                 :             :      * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
    9336                 :             :      * will set a bit for each page in the range when we find a matching
    9337                 :             :      * range, so we must multiply the charge by the number of pages in the
    9338                 :             :      * range.
    9339                 :             :      */
    9340                 :        8944 :     *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
    9341                 :        8944 :         statsData.pagesPerRange;
    9342                 :             : 
    9343                 :        8944 :     *indexPages = index->pages;
    9344                 :        8944 : }
        

Generated by: LCOV version 2.0-1