LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Coverage Total Hit LBC UBC GBC GNC CBC EUB DCB
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 87.8 % 2520 2213 1 306 3 2210 3
Current Date: 2025-09-06 07:49:51 +0900 Functions: 96.0 % 75 72 3 2 70
Baseline: lcov-20250906-005545-baseline Branches: 75.4 % 1975 1490 2 483 1 1489 36
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 93.2 % 59 55 4 55
(30,360] days: 90.1 % 203 183 20 3 180
(360..) days: 87.5 % 2258 1975 1 282 1975
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 3 3 1 2
(360..) days: 95.8 % 71 68 3 1 67
Branch coverage date bins:
(7,30] days: 79.2 % 48 38 10 38
(30,360] days: 71.9 % 178 128 50 128
(360..) days: 74.2 % 1785 1324 2 423 1 1323 36

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

Generated by: LCOV version 2.4-beta