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 ECB DUB DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 87.0 % 2395 2084 6 1 304 3 71 2010 1 5 4 38
Current Date: 2024-04-14 14:21:10 Functions: 95.8 % 71 68 1 2 7 61 1
Baseline: 16@8cea358b128 Branches: 72.3 % 1947 1407 22 4 514 7 66 1334
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 100.0 % 13 13 13
(60,120] days: 95.5 % 22 21 1 21
(120,180] days: 88.1 % 42 37 5 37
(240..) days: 86.8 % 2318 2013 1 304 3 2010 1 5
Function coverage date bins:
(60,120] days: 100.0 % 1 1 1
(240..) days: 95.7 % 70 67 1 2 6 61
Branch coverage date bins:
[..60] days: 93.8 % 16 15 1 15
(60,120] days: 87.5 % 16 14 2 14
(120,180] days: 66.1 % 56 37 19 37
(240..) days: 72.1 % 1859 1341 4 514 7 1334

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

Generated by: LCOV version 2.1-beta2-3-g6141622