LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 2191 2507 87.4 %
Date: 2025-07-04 04:18:14 Functions: 71 74 95.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16