LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC EUB DCB
Current: 806555e3000d0b0e0c536c1dc65548128d457d86 vs 1d325ad99cb2dec0e8b45ba36909ee0a497d2a57 Lines: 88.4 % 2594 2293 7 294 13 124 2156 59
Current Date: 2025-12-17 08:58:58 +0900 Functions: 96.2 % 78 75 3 10 65 2
Baseline: lcov-20251217-005640-baseline Branches: 75.7 % 2011 1523 12 2 474 6 50 1467 36
Baseline Date: 2025-12-16 12:57:12 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 2 2 2
(7,30] days: 94.4 % 124 117 7 117
(30,360] days: 90.5 % 264 239 25 5 234
(360..) days: 87.8 % 2204 1935 269 13 1922
Function coverage date bins:
(7,30] days: 100.0 % 5 5 5
(30,360] days: 100.0 % 4 4 1 3
(360..) days: 95.7 % 69 66 3 4 62
Branch coverage date bins:
(7,30] days: 80.0 % 60 48 12 48
(30,360] days: 73.5 % 226 166 60 2 164
(360..) days: 74.3 % 1761 1309 2 414 6 1303 36

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

Generated by: LCOV version 2.4-beta