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

Generated by: LCOV version 1.13