LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 2121 2438 87.0 %
Date: 2025-04-01 14:15:22 Functions: 69 72 95.8 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14