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

Generated by: LCOV version 1.13