LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 16beta1 Lines: 2022 2332 86.7 %
Date: 2023-06-06 10:12:12 Functions: 68 71 95.8 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14