LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 2192 2507 87.4 %
Date: 2025-07-30 23:18:15 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      633114 : eqsel(PG_FUNCTION_ARGS)
     232             : {
     233      633114 :     PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
     234             : }
     235             : 
     236             : /*
     237             :  * Common code for eqsel() and neqsel()
     238             :  */
     239             : static double
     240      678974 : eqsel_internal(PG_FUNCTION_ARGS, bool negate)
     241             : {
     242      678974 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
     243      678974 :     Oid         operator = PG_GETARG_OID(1);
     244      678974 :     List       *args = (List *) PG_GETARG_POINTER(2);
     245      678974 :     int         varRelid = PG_GETARG_INT32(3);
     246      678974 :     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      678974 :     if (negate)
     257             :     {
     258       45860 :         operator = get_negator(operator);
     259       45860 :         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      678974 :     if (!get_restriction_variable(root, args, varRelid,
     271             :                                   &vardata, &other, &varonleft))
     272        5184 :         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      673784 :     if (IsA(other, Const))
     280      299746 :         selec = var_eq_const(&vardata, operator, collation,
     281      299746 :                              ((Const *) other)->constvalue,
     282      299746 :                              ((Const *) other)->constisnull,
     283             :                              varonleft, negate);
     284             :     else
     285      374038 :         selec = var_eq_non_const(&vardata, operator, collation, other,
     286             :                                  varonleft, negate);
     287             : 
     288      673784 :     ReleaseVariableStats(vardata);
     289             : 
     290      673784 :     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      344202 : var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
     300             :              Datum constval, bool constisnull,
     301             :              bool varonleft, bool negate)
     302             : {
     303             :     double      selec;
     304      344202 :     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      344202 :     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      343798 :     if (HeapTupleIsValid(vardata->statsTuple))
     320             :     {
     321             :         Form_pg_statistic stats;
     322             : 
     323      262362 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     324      262362 :         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      343798 :     if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
     335             :     {
     336       82922 :         selec = 1.0 / vardata->rel->tuples;
     337             :     }
     338      457220 :     else if (HeapTupleIsValid(vardata->statsTuple) &&
     339      196344 :              statistic_proc_security_check(vardata,
     340      196344 :                                            (opfuncoid = get_opcode(oproid))))
     341      196344 :     {
     342             :         AttStatsSlot sslot;
     343      196344 :         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      196344 :         if (get_attstatsslot(&sslot, vardata->statsTuple,
     354             :                              STATISTIC_KIND_MCV, InvalidOid,
     355             :                              ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
     356             :         {
     357      175690 :             LOCAL_FCINFO(fcinfo, 2);
     358             :             FmgrInfo    eqproc;
     359             : 
     360      175690 :             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      175690 :             InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
     369             :                                      NULL, NULL);
     370      175690 :             fcinfo->args[0].isnull = false;
     371      175690 :             fcinfo->args[1].isnull = false;
     372             :             /* be careful to apply operator right way 'round */
     373      175690 :             if (varonleft)
     374      175658 :                 fcinfo->args[1].value = constval;
     375             :             else
     376          32 :                 fcinfo->args[0].value = constval;
     377             : 
     378     2992470 :             for (i = 0; i < sslot.nvalues; i++)
     379             :             {
     380             :                 Datum       fresult;
     381             : 
     382     2909378 :                 if (varonleft)
     383     2909322 :                     fcinfo->args[0].value = sslot.values[i];
     384             :                 else
     385          56 :                     fcinfo->args[1].value = sslot.values[i];
     386     2909378 :                 fcinfo->isnull = false;
     387     2909378 :                 fresult = FunctionCallInvoke(fcinfo);
     388     2909378 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
     389             :                 {
     390       92598 :                     match = true;
     391       92598 :                     break;
     392             :                 }
     393             :             }
     394             :         }
     395             :         else
     396             :         {
     397             :             /* no most-common-value info available */
     398       20654 :             i = 0;              /* keep compiler quiet */
     399             :         }
     400             : 
     401      196344 :         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       92598 :             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      103746 :             double      sumcommon = 0.0;
     417             :             double      otherdistinct;
     418             : 
     419     2551818 :             for (i = 0; i < sslot.nnumbers; i++)
     420     2448072 :                 sumcommon += sslot.numbers[i];
     421      103746 :             selec = 1.0 - sumcommon - nullfrac;
     422      103746 :             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      103746 :             otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
     430      103746 :                 sslot.nnumbers;
     431      103746 :             if (otherdistinct > 1)
     432       52090 :                 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      103746 :             if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
     439           0 :                 selec = sslot.numbers[sslot.nnumbers - 1];
     440             :         }
     441             : 
     442      196344 :         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       64532 :         selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
     452             :     }
     453             : 
     454             :     /* now adjust if we wanted <> rather than = */
     455      343798 :     if (negate)
     456       37042 :         selec = 1.0 - selec - nullfrac;
     457             : 
     458             :     /* result should be in range, but make sure... */
     459      343798 :     CLAMP_PROBABILITY(selec);
     460             : 
     461      343798 :     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      374038 : var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
     471             :                  Node *other,
     472             :                  bool varonleft, bool negate)
     473             : {
     474             :     double      selec;
     475      374038 :     double      nullfrac = 0.0;
     476             :     bool        isdefault;
     477             : 
     478             :     /*
     479             :      * Grab the nullfrac for use below.
     480             :      */
     481      374038 :     if (HeapTupleIsValid(vardata->statsTuple))
     482             :     {
     483             :         Form_pg_statistic stats;
     484             : 
     485      272582 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     486      272582 :         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      374038 :     if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
     497             :     {
     498      150310 :         selec = 1.0 / vardata->rel->tuples;
     499             :     }
     500      223728 :     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      138066 :         selec = 1.0 - nullfrac;
     516      138066 :         ndistinct = get_variable_numdistinct(vardata, &isdefault);
     517      138066 :         if (ndistinct > 1)
     518      134216 :             selec /= ndistinct;
     519             : 
     520             :         /*
     521             :          * Cross-check: selectivity should never be estimated as more than the
     522             :          * most common value's.
     523             :          */
     524      138066 :         if (get_attstatsslot(&sslot, vardata->statsTuple,
     525             :                              STATISTIC_KIND_MCV, InvalidOid,
     526             :                              ATTSTATSSLOT_NUMBERS))
     527             :         {
     528      118932 :             if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
     529         558 :                 selec = sslot.numbers[0];
     530      118932 :             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       85662 :         selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
     541             :     }
     542             : 
     543             :     /* now adjust if we wanted <> rather than = */
     544      374038 :     if (negate)
     545        6490 :         selec = 1.0 - selec - nullfrac;
     546             : 
     547             :     /* result should be in range, but make sure... */
     548      374038 :     CLAMP_PROBABILITY(selec);
     549             : 
     550      374038 :     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       45860 : neqsel(PG_FUNCTION_ARGS)
     562             : {
     563       45860 :     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      305262 : 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      305262 :     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       22308 :         if (vardata->var && IsA(vardata->var, Var) &&
     603       17552 :             ((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       20356 :         return DEFAULT_INEQ_SEL;
     674             :     }
     675      282954 :     stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     676             : 
     677      282954 :     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      282954 :     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      282954 :     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      282954 :     selec = 1.0 - stats->stanullfrac - sumcommon;
     703             : 
     704      282954 :     if (hist_selec >= 0.0)
     705      211338 :         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       71616 :         selec *= 0.5;
     713             :     }
     714             : 
     715      282954 :     selec += mcv_selec;
     716             : 
     717             :     /* result should be in range, but make sure... */
     718      282954 :     CLAMP_PROBABILITY(selec);
     719             : 
     720      282954 :     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      289094 : 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      289094 :     mcv_selec = 0.0;
     746      289094 :     sumcommon = 0.0;
     747             : 
     748      575760 :     if (HeapTupleIsValid(vardata->statsTuple) &&
     749      573278 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
     750      286612 :         get_attstatsslot(&sslot, vardata->statsTuple,
     751             :                          STATISTIC_KIND_MCV, InvalidOid,
     752             :                          ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
     753             :     {
     754      133272 :         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      133272 :         InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
     764             :                                  NULL, NULL);
     765      133272 :         fcinfo->args[0].isnull = false;
     766      133272 :         fcinfo->args[1].isnull = false;
     767             :         /* be careful to apply operator right way 'round */
     768      133272 :         if (varonleft)
     769      133272 :             fcinfo->args[1].value = constval;
     770             :         else
     771           0 :             fcinfo->args[0].value = constval;
     772             : 
     773     4091490 :         for (i = 0; i < sslot.nvalues; i++)
     774             :         {
     775             :             Datum       fresult;
     776             : 
     777     3958218 :             if (varonleft)
     778     3958218 :                 fcinfo->args[0].value = sslot.values[i];
     779             :             else
     780           0 :                 fcinfo->args[1].value = sslot.values[i];
     781     3958218 :             fcinfo->isnull = false;
     782     3958218 :             fresult = FunctionCallInvoke(fcinfo);
     783     3958218 :             if (!fcinfo->isnull && DatumGetBool(fresult))
     784     1454700 :                 mcv_selec += sslot.numbers[i];
     785     3958218 :             sumcommon += sslot.numbers[i];
     786             :         }
     787      133272 :         free_attstatsslot(&sslot);
     788             :     }
     789             : 
     790      289094 :     *sumcommonp = sumcommon;
     791      289094 :     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        6140 : 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        9852 :     if (HeapTupleIsValid(vardata->statsTuple) &&
     841        7418 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
     842        3706 :         get_attstatsslot(&sslot, vardata->statsTuple,
     843             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
     844             :                          ATTSTATSSLOT_VALUES))
     845             :     {
     846        3612 :         *hist_size = sslot.nvalues;
     847        3612 :         if (sslot.nvalues >= min_hist_size)
     848             :         {
     849        1776 :             LOCAL_FCINFO(fcinfo, 2);
     850        1776 :             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        1776 :             InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
     862             :                                      NULL, NULL);
     863        1776 :             fcinfo->args[0].isnull = false;
     864        1776 :             fcinfo->args[1].isnull = false;
     865             :             /* be careful to apply operator right way 'round */
     866        1776 :             if (varonleft)
     867        1776 :                 fcinfo->args[1].value = constval;
     868             :             else
     869           0 :                 fcinfo->args[0].value = constval;
     870             : 
     871      146794 :             for (i = n_skip; i < sslot.nvalues - n_skip; i++)
     872             :             {
     873             :                 Datum       fresult;
     874             : 
     875      145018 :                 if (varonleft)
     876      145018 :                     fcinfo->args[0].value = sslot.values[i];
     877             :                 else
     878           0 :                     fcinfo->args[1].value = sslot.values[i];
     879      145018 :                 fcinfo->isnull = false;
     880      145018 :                 fresult = FunctionCallInvoke(fcinfo);
     881      145018 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
     882        9534 :                     nmatch++;
     883             :             }
     884        1776 :             result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
     885             :         }
     886             :         else
     887        1836 :             result = -1;
     888        3612 :         free_attstatsslot(&sslot);
     889             :     }
     890             :     else
     891             :     {
     892        2528 :         *hist_size = 0;
     893        2528 :         result = -1;
     894             :     }
     895             : 
     896        6140 :     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      288030 : 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      288030 :     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      575370 :     if (HeapTupleIsValid(vardata->statsTuple) &&
    1069      574632 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
    1070      287292 :         get_attstatsslot(&sslot, vardata->statsTuple,
    1071             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
    1072             :                          ATTSTATSSLOT_VALUES))
    1073             :     {
    1074      215722 :         if (sslot.nvalues > 1 &&
    1075      431368 :             sslot.stacoll == collation &&
    1076      215646 :             comparison_ops_are_compatible(sslot.staop, opoid))
    1077      215538 :         {
    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      215538 :             int         lobound = 0;    /* first possible slot to search */
    1098      215538 :             int         hibound = sslot.nvalues;    /* last+1 slot to search */
    1099      215538 :             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      215538 :             if (sslot.nvalues == 2)
    1108        2098 :                 have_end = get_actual_variable_range(root,
    1109             :                                                      vardata,
    1110             :                                                      sslot.staop,
    1111             :                                                      collation,
    1112             :                                                      &sslot.values[0],
    1113        2098 :                                                      &sslot.values[1]);
    1114             : 
    1115     1443340 :             while (lobound < hibound)
    1116             :             {
    1117     1227802 :                 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     1227802 :                 if (probe == 0 && sslot.nvalues > 2)
    1126      107282 :                     have_end = get_actual_variable_range(root,
    1127             :                                                          vardata,
    1128             :                                                          sslot.staop,
    1129             :                                                          collation,
    1130             :                                                          &sslot.values[0],
    1131             :                                                          NULL);
    1132     1120520 :                 else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
    1133       72876 :                     have_end = get_actual_variable_range(root,
    1134             :                                                          vardata,
    1135             :                                                          sslot.staop,
    1136             :                                                          collation,
    1137             :                                                          NULL,
    1138       72876 :                                                          &sslot.values[probe]);
    1139             : 
    1140     1227802 :                 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
    1141             :                                                        collation,
    1142     1227802 :                                                        sslot.values[probe],
    1143             :                                                        constval));
    1144     1227802 :                 if (isgt)
    1145       68340 :                     ltcmp = !ltcmp;
    1146     1227802 :                 if (ltcmp)
    1147      458684 :                     lobound = probe + 1;
    1148             :                 else
    1149      769118 :                     hibound = probe;
    1150             :             }
    1151             : 
    1152      215538 :             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       92202 :                 histfrac = 0.0;
    1163             :             }
    1164      123336 :             else if (lobound >= sslot.nvalues)
    1165             :             {
    1166             :                 /*
    1167             :                  * Inverse case: constant is above upper histogram boundary.
    1168             :                  */
    1169       33514 :                 histfrac = 1.0;
    1170             :             }
    1171             :             else
    1172             :             {
    1173             :                 /* We have values[i-1] <= constant <= values[i]. */
    1174       89822 :                 int         i = lobound;
    1175       89822 :                 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       89822 :                 if (i == 1 || isgt == iseq)
    1198             :                 {
    1199             :                     double      otherdistinct;
    1200             :                     bool        isdefault;
    1201             :                     AttStatsSlot mcvslot;
    1202             : 
    1203             :                     /* Get estimated number of distinct values */
    1204       38092 :                     otherdistinct = get_variable_numdistinct(vardata,
    1205             :                                                              &isdefault);
    1206             : 
    1207             :                     /* Subtract off the number of known MCVs */
    1208       38092 :                     if (get_attstatsslot(&mcvslot, vardata->statsTuple,
    1209             :                                          STATISTIC_KIND_MCV, InvalidOid,
    1210             :                                          ATTSTATSSLOT_NUMBERS))
    1211             :                     {
    1212        3674 :                         otherdistinct -= mcvslot.nnumbers;
    1213        3674 :                         free_attstatsslot(&mcvslot);
    1214             :                     }
    1215             : 
    1216             :                     /* If result doesn't seem sane, leave eq_selec at 0 */
    1217       38092 :                     if (otherdistinct > 1)
    1218       38050 :                         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       89822 :                 if (convert_to_scalar(constval, consttype, collation,
    1227             :                                       &val,
    1228       89822 :                                       sslot.values[i - 1], sslot.values[i],
    1229             :                                       vardata->vartype,
    1230             :                                       &low, &high))
    1231             :                 {
    1232       89822 :                     if (high <= low)
    1233             :                     {
    1234             :                         /* cope if bin boundaries appear identical */
    1235           0 :                         binfrac = 0.5;
    1236             :                     }
    1237       89822 :                     else if (val <= low)
    1238       20424 :                         binfrac = 0.0;
    1239       69398 :                     else if (val >= high)
    1240        2688 :                         binfrac = 1.0;
    1241             :                     else
    1242             :                     {
    1243       66710 :                         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       66710 :                         if (isnan(binfrac) ||
    1252       66710 :                             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       89822 :                 histfrac = (double) (i - 1) + binfrac;
    1275       89822 :                 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       89822 :                 if (i == 1)
    1310       16558 :                     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       89822 :                 if (isgt == iseq)
    1318       28616 :                     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      215538 :             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      215538 :             if (have_end)
    1337      121236 :                 CLAMP_PROBABILITY(hist_selec);
    1338             :             else
    1339             :             {
    1340       94302 :                 double      cutoff = 0.01 / (double) (sslot.nvalues - 1);
    1341             : 
    1342       94302 :                 if (hist_selec < cutoff)
    1343       33730 :                     hist_selec = cutoff;
    1344       60572 :                 else if (hist_selec > 1.0 - cutoff)
    1345       21856 :                     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      962452 :             for (int i = 0; i < sslot.nvalues; i++)
    1366             :             {
    1367             :                 Datum       fresult;
    1368             : 
    1369      962268 :                 fcinfo->args[0].value = sslot.values[i];
    1370      962268 :                 fcinfo->isnull = false;
    1371      962268 :                 fresult = FunctionCallInvoke(fcinfo);
    1372      962268 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    1373        2196 :                     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          12 :                     hist_selec = cutoff;
    1388         172 :                 else if (hist_selec > 1.0 - cutoff)
    1389          12 :                     hist_selec = 1.0 - cutoff;
    1390             :             }
    1391             :         }
    1392             : 
    1393      215722 :         free_attstatsslot(&sslot);
    1394             :     }
    1395             : 
    1396      288030 :     return hist_selec;
    1397             : }
    1398             : 
    1399             : /*
    1400             :  * Common wrapper function for the selectivity estimators that simply
    1401             :  * invoke scalarineqsel().
    1402             :  */
    1403             : static Datum
    1404       44274 : scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
    1405             : {
    1406       44274 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    1407       44274 :     Oid         operator = PG_GETARG_OID(1);
    1408       44274 :     List       *args = (List *) PG_GETARG_POINTER(2);
    1409       44274 :     int         varRelid = PG_GETARG_INT32(3);
    1410       44274 :     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       44274 :     if (!get_restriction_variable(root, args, varRelid,
    1423             :                                   &vardata, &other, &varonleft))
    1424         650 :         PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
    1425             : 
    1426             :     /*
    1427             :      * Can't do anything useful if the something is not a constant, either.
    1428             :      */
    1429       43624 :     if (!IsA(other, Const))
    1430             :     {
    1431        2776 :         ReleaseVariableStats(vardata);
    1432        2776 :         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       40848 :     if (((Const *) other)->constisnull)
    1440             :     {
    1441          66 :         ReleaseVariableStats(vardata);
    1442          66 :         PG_RETURN_FLOAT8(0.0);
    1443             :     }
    1444       40782 :     constval = ((Const *) other)->constvalue;
    1445       40782 :     consttype = ((Const *) other)->consttype;
    1446             : 
    1447             :     /*
    1448             :      * Force the var to be on the left to simplify logic in scalarineqsel.
    1449             :      */
    1450       40782 :     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       40782 :     selec = scalarineqsel(root, operator, isgt, iseq, collation,
    1464             :                           &vardata, constval, consttype);
    1465             : 
    1466       40782 :     ReleaseVariableStats(vardata);
    1467             : 
    1468       40782 :     PG_RETURN_FLOAT8((float8) selec);
    1469             : }
    1470             : 
    1471             : /*
    1472             :  *      scalarltsel     - Selectivity of "<" for scalars.
    1473             :  */
    1474             : Datum
    1475       14486 : scalarltsel(PG_FUNCTION_ARGS)
    1476             : {
    1477       14486 :     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       15282 : scalargtsel(PG_FUNCTION_ARGS)
    1494             : {
    1495       15282 :     return scalarineqsel_wrapper(fcinfo, true, false);
    1496             : }
    1497             : 
    1498             : /*
    1499             :  *      scalargesel     - Selectivity of ">=" for scalars.
    1500             :  */
    1501             : Datum
    1502        9958 : scalargesel(PG_FUNCTION_ARGS)
    1503             : {
    1504        9958 :     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       44094 : boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
    1517             : {
    1518             :     VariableStatData vardata;
    1519             :     double      selec;
    1520             : 
    1521       44094 :     examine_variable(root, arg, varRelid, &vardata);
    1522       44094 :     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       35726 :         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        8368 :         selec = 0.5;
    1535             :     }
    1536       44094 :     ReleaseVariableStats(vardata);
    1537       44094 :     return selec;
    1538             : }
    1539             : 
    1540             : /*
    1541             :  *      booltestsel     - Selectivity of BooleanTest Node.
    1542             :  */
    1543             : Selectivity
    1544         886 : booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
    1545             :             int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
    1546             : {
    1547             :     VariableStatData vardata;
    1548             :     double      selec;
    1549             : 
    1550         886 :     examine_variable(root, arg, varRelid, &vardata);
    1551             : 
    1552         886 :     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         886 :         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         478 :             case IS_FALSE:
    1677             :             case IS_NOT_TRUE:
    1678         478 :                 selec = 1.0 - (double) clause_selectivity(root, arg,
    1679             :                                                           varRelid,
    1680             :                                                           jointype, sjinfo);
    1681         478 :                 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         886 :     ReleaseVariableStats(vardata);
    1691             : 
    1692             :     /* result should be in range, but make sure... */
    1693         886 :     CLAMP_PROBABILITY(selec);
    1694             : 
    1695         886 :     return (Selectivity) selec;
    1696             : }
    1697             : 
    1698             : /*
    1699             :  *      nulltestsel     - Selectivity of NullTest Node.
    1700             :  */
    1701             : Selectivity
    1702       17488 : nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
    1703             :             int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
    1704             : {
    1705             :     VariableStatData vardata;
    1706             :     double      selec;
    1707             : 
    1708       17488 :     examine_variable(root, arg, varRelid, &vardata);
    1709             : 
    1710       17488 :     if (HeapTupleIsValid(vardata.statsTuple))
    1711             :     {
    1712             :         Form_pg_statistic stats;
    1713             :         double      freq_null;
    1714             : 
    1715        9822 :         stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
    1716        9822 :         freq_null = stats->stanullfrac;
    1717             : 
    1718        9822 :         switch (nulltesttype)
    1719             :         {
    1720        7224 :             case IS_NULL:
    1721             : 
    1722             :                 /*
    1723             :                  * Use freq_null directly.
    1724             :                  */
    1725        7224 :                 selec = freq_null;
    1726        7224 :                 break;
    1727        2598 :             case IS_NOT_NULL:
    1728             : 
    1729             :                 /*
    1730             :                  * Select not unknown (not null) values. Calculate from
    1731             :                  * freq_null.
    1732             :                  */
    1733        2598 :                 selec = 1.0 - freq_null;
    1734        2598 :                 break;
    1735           0 :             default:
    1736           0 :                 elog(ERROR, "unrecognized nulltesttype: %d",
    1737             :                      (int) nulltesttype);
    1738             :                 return (Selectivity) 0; /* keep compiler quiet */
    1739             :         }
    1740             :     }
    1741        7666 :     else if (vardata.var && IsA(vardata.var, Var) &&
    1742        6958 :              ((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        7606 :         switch (nulltesttype)
    1756             :         {
    1757        2110 :             case IS_NULL:
    1758        2110 :                 selec = DEFAULT_UNK_SEL;
    1759        2110 :                 break;
    1760        5496 :             case IS_NOT_NULL:
    1761        5496 :                 selec = DEFAULT_NOT_UNK_SEL;
    1762        5496 :                 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       17488 :     ReleaseVariableStats(vardata);
    1771             : 
    1772             :     /* result should be in range, but make sure... */
    1773       17488 :     CLAMP_PROBABILITY(selec);
    1774             : 
    1775       17488 :     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      125186 : strip_array_coercion(Node *node)
    1788             : {
    1789             :     for (;;)
    1790             :     {
    1791      125268 :         if (node && IsA(node, ArrayCoerceExpr))
    1792          82 :         {
    1793        2946 :             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        2946 :             if (IsA(acoerce->elemexpr, RelabelType) &&
    1800          82 :                 IsA(((RelabelType *) acoerce->elemexpr)->arg, CaseTestExpr))
    1801          82 :                 node = (Node *) acoerce->arg;
    1802             :             else
    1803             :                 break;
    1804             :         }
    1805      122322 :         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      125186 :     return node;
    1814             : }
    1815             : 
    1816             : /*
    1817             :  *      scalararraysel      - Selectivity of ScalarArrayOpExpr Node.
    1818             :  */
    1819             : Selectivity
    1820       21412 : scalararraysel(PlannerInfo *root,
    1821             :                ScalarArrayOpExpr *clause,
    1822             :                bool is_join_clause,
    1823             :                int varRelid,
    1824             :                JoinType jointype,
    1825             :                SpecialJoinInfo *sjinfo)
    1826             : {
    1827       21412 :     Oid         operator = clause->opno;
    1828       21412 :     bool        useOr = clause->useOr;
    1829       21412 :     bool        isEquality = false;
    1830       21412 :     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       21412 :     leftop = (Node *) linitial(clause->args);
    1844       21412 :     rightop = (Node *) lsecond(clause->args);
    1845             : 
    1846             :     /* aggressively reduce both sides to constants */
    1847       21412 :     leftop = estimate_expression_value(root, leftop);
    1848       21412 :     rightop = estimate_expression_value(root, rightop);
    1849             : 
    1850             :     /* get nominal (after relabeling) element type of rightop */
    1851       21412 :     nominal_element_type = get_base_element_type(exprType(rightop));
    1852       21412 :     if (!OidIsValid(nominal_element_type))
    1853           0 :         return (Selectivity) 0.5;   /* probably shouldn't happen */
    1854             :     /* get nominal collation, too, for generating constants */
    1855       21412 :     nominal_element_collation = exprCollation(rightop);
    1856             : 
    1857             :     /* look through any binary-compatible relabeling of rightop */
    1858       21412 :     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       21412 :     typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
    1865       21412 :     if (OidIsValid(typentry->eq_opr))
    1866             :     {
    1867       21408 :         if (operator == typentry->eq_opr)
    1868       18136 :             isEquality = true;
    1869        3272 :         else if (get_negator(operator) == typentry->eq_opr)
    1870        2706 :             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       21412 :     if ((isEquality || isInequality) && !is_join_clause)
    1880             :     {
    1881       20842 :         s1 = scalararraysel_containment(root, leftop, rightop,
    1882             :                                         nominal_element_type,
    1883             :                                         isEquality, useOr, varRelid);
    1884       20842 :         if (s1 >= 0.0)
    1885         116 :             return s1;
    1886             :     }
    1887             : 
    1888             :     /*
    1889             :      * Look up the underlying operator's selectivity estimator. Punt if it
    1890             :      * hasn't got one.
    1891             :      */
    1892       21296 :     if (is_join_clause)
    1893           0 :         oprsel = get_oprjoin(operator);
    1894             :     else
    1895       21296 :         oprsel = get_oprrest(operator);
    1896       21296 :     if (!oprsel)
    1897           4 :         return (Selectivity) 0.5;
    1898       21292 :     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       21292 :     if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
    1909       18216 :         isEquality = true;
    1910        3076 :     else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
    1911        2596 :         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       21292 :     if (rightop && IsA(rightop, Const))
    1926       17118 :     {
    1927       17148 :         Datum       arraydatum = ((Const *) rightop)->constvalue;
    1928       17148 :         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       17148 :         if (arrayisnull)        /* qual can't succeed if null array */
    1939          30 :             return (Selectivity) 0.0;
    1940       17118 :         arrayval = DatumGetArrayTypeP(arraydatum);
    1941       17118 :         get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
    1942             :                              &elmlen, &elmbyval, &elmalign);
    1943       17118 :         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       17118 :         s1 = s1disjoint = (useOr ? 0.0 : 1.0);
    1963             : 
    1964       74230 :         for (i = 0; i < num_elems; i++)
    1965             :         {
    1966             :             List       *args;
    1967             :             Selectivity s2;
    1968             : 
    1969       57112 :             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       57112 :             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       57112 :                 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
    1987             :                                                       clause->inputcollid,
    1988             :                                                       PointerGetDatum(root),
    1989             :                                                       ObjectIdGetDatum(operator),
    1990             :                                                       PointerGetDatum(args),
    1991             :                                                       Int32GetDatum(varRelid)));
    1992             : 
    1993       57112 :             if (useOr)
    1994             :             {
    1995       48722 :                 s1 = s1 + s2 - s1 * s2;
    1996       48722 :                 if (isEquality)
    1997       47678 :                     s1disjoint += s2;
    1998             :             }
    1999             :             else
    2000             :             {
    2001        8390 :                 s1 = s1 * s2;
    2002        8390 :                 if (isInequality)
    2003        8078 :                     s1disjoint += s2 - 1.0;
    2004             :             }
    2005             :         }
    2006             : 
    2007             :         /* accept disjoint-probability estimate if in range */
    2008       17118 :         if ((useOr ? isEquality : isInequality) &&
    2009       16478 :             s1disjoint >= 0.0 && s1disjoint <= 1.0)
    2010       16448 :             s1 = s1disjoint;
    2011             :     }
    2012        4144 :     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        3850 :         dummyexpr = makeNode(CaseTestExpr);
    2092        3850 :         dummyexpr->typeId = nominal_element_type;
    2093        3850 :         dummyexpr->typeMod = -1;
    2094        3850 :         dummyexpr->collation = clause->inputcollid;
    2095        3850 :         args = list_make2(leftop, dummyexpr);
    2096        3850 :         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        3850 :             s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
    2106             :                                                   clause->inputcollid,
    2107             :                                                   PointerGetDatum(root),
    2108             :                                                   ObjectIdGetDatum(operator),
    2109             :                                                   PointerGetDatum(args),
    2110             :                                                   Int32GetDatum(varRelid)));
    2111        3850 :         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       42350 :         for (i = 0; i < 10; i++)
    2119             :         {
    2120       38500 :             if (useOr)
    2121       38500 :                 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       21262 :     CLAMP_PROBABILITY(s1);
    2129             : 
    2130       21262 :     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      103774 : estimate_array_length(PlannerInfo *root, Node *arrayexpr)
    2144             : {
    2145             :     /* look through any binary-compatible relabeling of arrayexpr */
    2146      103774 :     arrayexpr = strip_array_coercion(arrayexpr);
    2147             : 
    2148      103774 :     if (arrayexpr && IsA(arrayexpr, Const))
    2149             :     {
    2150       45856 :         Datum       arraydatum = ((Const *) arrayexpr)->constvalue;
    2151       45856 :         bool        arrayisnull = ((Const *) arrayexpr)->constisnull;
    2152             :         ArrayType  *arrayval;
    2153             : 
    2154       45856 :         if (arrayisnull)
    2155          90 :             return 0;
    2156       45766 :         arrayval = DatumGetArrayTypeP(arraydatum);
    2157       45766 :         return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
    2158             :     }
    2159       57918 :     else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
    2160         498 :              !((ArrayExpr *) arrayexpr)->multidims)
    2161             :     {
    2162         498 :         return list_length(((ArrayExpr *) arrayexpr)->elements);
    2163             :     }
    2164       57420 :     else if (arrayexpr && root)
    2165             :     {
    2166             :         /* See if we can find any statistics about it */
    2167             :         VariableStatData vardata;
    2168             :         AttStatsSlot sslot;
    2169       57420 :         double      nelem = 0;
    2170             : 
    2171       57420 :         examine_variable(root, arrayexpr, 0, &vardata);
    2172       57420 :         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        9900 :             if (get_attstatsslot(&sslot, vardata.statsTuple,
    2181             :                                  STATISTIC_KIND_DECHIST, InvalidOid,
    2182             :                                  ATTSTATSSLOT_NUMBERS))
    2183             :             {
    2184        9786 :                 if (sslot.nnumbers > 0)
    2185        9786 :                     nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
    2186        9786 :                 free_attstatsslot(&sslot);
    2187             :             }
    2188             :         }
    2189       57420 :         ReleaseVariableStats(vardata);
    2190             : 
    2191       57420 :         if (nelem > 0)
    2192        9786 :             return nelem;
    2193             :     }
    2194             : 
    2195             :     /* Else use a default guess --- this should match scalararraysel */
    2196       47634 :     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      226098 : eqjoinsel(PG_FUNCTION_ARGS)
    2277             : {
    2278      226098 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    2279      226098 :     Oid         operator = PG_GETARG_OID(1);
    2280      226098 :     List       *args = (List *) PG_GETARG_POINTER(2);
    2281             : 
    2282             : #ifdef NOT_USED
    2283             :     JoinType    jointype = (JoinType) PG_GETARG_INT16(3);
    2284             : #endif
    2285      226098 :     SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
    2286      226098 :     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      226098 :     Form_pg_statistic stats1 = NULL;
    2299      226098 :     Form_pg_statistic stats2 = NULL;
    2300      226098 :     bool        have_mcvs1 = false;
    2301      226098 :     bool        have_mcvs2 = false;
    2302             :     bool        get_mcv_stats;
    2303             :     bool        join_is_reversed;
    2304             :     RelOptInfo *inner_rel;
    2305             : 
    2306      226098 :     get_join_variables(root, args, sjinfo,
    2307             :                        &vardata1, &vardata2, &join_is_reversed);
    2308             : 
    2309      226098 :     nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
    2310      226098 :     nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
    2311             : 
    2312      226098 :     opfuncoid = get_opcode(operator);
    2313             : 
    2314      226098 :     memset(&sslot1, 0, sizeof(sslot1));
    2315      226098 :     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      633328 :     get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
    2322      319404 :                      HeapTupleIsValid(vardata2.statsTuple) &&
    2323      138272 :                      get_attstatsslot(&sslot1, vardata1.statsTuple,
    2324             :                                       STATISTIC_KIND_MCV, InvalidOid,
    2325      407230 :                                       0) &&
    2326       53832 :                      get_attstatsslot(&sslot2, vardata2.statsTuple,
    2327             :                                       STATISTIC_KIND_MCV, InvalidOid,
    2328             :                                       0));
    2329             : 
    2330      226098 :     if (HeapTupleIsValid(vardata1.statsTuple))
    2331             :     {
    2332             :         /* note we allow use of nullfrac regardless of security check */
    2333      181132 :         stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
    2334      195014 :         if (get_mcv_stats &&
    2335       13882 :             statistic_proc_security_check(&vardata1, opfuncoid))
    2336       13882 :             have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
    2337             :                                           STATISTIC_KIND_MCV, InvalidOid,
    2338             :                                           ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
    2339             :     }
    2340             : 
    2341      226098 :     if (HeapTupleIsValid(vardata2.statsTuple))
    2342             :     {
    2343             :         /* note we allow use of nullfrac regardless of security check */
    2344      150862 :         stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
    2345      164744 :         if (get_mcv_stats &&
    2346       13882 :             statistic_proc_security_check(&vardata2, opfuncoid))
    2347       13882 :             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      226098 :     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      226098 :     switch (sjinfo->jointype)
    2362             :     {
    2363      215416 :         case JOIN_INNER:
    2364             :         case JOIN_LEFT:
    2365             :         case JOIN_FULL:
    2366      215416 :             selec = selec_inner;
    2367      215416 :             break;
    2368       10682 :         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       10682 :             inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
    2378             : 
    2379       10682 :             if (!join_is_reversed)
    2380        6490 :                 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        4192 :                 Oid         commop = get_commutator(operator);
    2391        4192 :                 Oid         commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
    2392             : 
    2393        4192 :                 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       10682 :             selec = Min(selec, inner_rel->rows * selec_inner);
    2414       10682 :             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      226098 :     free_attstatsslot(&sslot1);
    2424      226098 :     free_attstatsslot(&sslot2);
    2425             : 
    2426      226098 :     ReleaseVariableStats(vardata1);
    2427      226098 :     ReleaseVariableStats(vardata2);
    2428             : 
    2429      226098 :     CLAMP_PROBABILITY(selec);
    2430             : 
    2431      226098 :     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      226098 : 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      226098 :     if (have_mcvs1 && have_mcvs2)
    2452       13882 :     {
    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       13882 :         LOCAL_FCINFO(fcinfo, 2);
    2466             :         FmgrInfo    eqproc;
    2467             :         bool       *hasmatch1;
    2468             :         bool       *hasmatch2;
    2469       13882 :         double      nullfrac1 = stats1->stanullfrac;
    2470       13882 :         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       13882 :         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       13882 :         InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
    2492             :                                  NULL, NULL);
    2493       13882 :         fcinfo->args[0].isnull = false;
    2494       13882 :         fcinfo->args[1].isnull = false;
    2495             : 
    2496       13882 :         hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
    2497       13882 :         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       13882 :         matchprodfreq = 0.0;
    2506       13882 :         nmatches = 0;
    2507      603902 :         for (i = 0; i < sslot1->nvalues; i++)
    2508             :         {
    2509             :             int         j;
    2510             : 
    2511      590020 :             fcinfo->args[0].value = sslot1->values[i];
    2512             : 
    2513    23077540 :             for (j = 0; j < sslot2->nvalues; j++)
    2514             :             {
    2515             :                 Datum       fresult;
    2516             : 
    2517    22681146 :                 if (hasmatch2[j])
    2518     5833444 :                     continue;
    2519    16847702 :                 fcinfo->args[1].value = sslot2->values[j];
    2520    16847702 :                 fcinfo->isnull = false;
    2521    16847702 :                 fresult = FunctionCallInvoke(fcinfo);
    2522    16847702 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    2523             :                 {
    2524      193626 :                     hasmatch1[i] = hasmatch2[j] = true;
    2525      193626 :                     matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
    2526      193626 :                     nmatches++;
    2527      193626 :                     break;
    2528             :                 }
    2529             :             }
    2530             :         }
    2531       13882 :         CLAMP_PROBABILITY(matchprodfreq);
    2532             :         /* Sum up frequencies of matched and unmatched MCVs */
    2533       13882 :         matchfreq1 = unmatchfreq1 = 0.0;
    2534      603902 :         for (i = 0; i < sslot1->nvalues; i++)
    2535             :         {
    2536      590020 :             if (hasmatch1[i])
    2537      193626 :                 matchfreq1 += sslot1->numbers[i];
    2538             :             else
    2539      396394 :                 unmatchfreq1 += sslot1->numbers[i];
    2540             :         }
    2541       13882 :         CLAMP_PROBABILITY(matchfreq1);
    2542       13882 :         CLAMP_PROBABILITY(unmatchfreq1);
    2543       13882 :         matchfreq2 = unmatchfreq2 = 0.0;
    2544      411978 :         for (i = 0; i < sslot2->nvalues; i++)
    2545             :         {
    2546      398096 :             if (hasmatch2[i])
    2547      193626 :                 matchfreq2 += sslot2->numbers[i];
    2548             :             else
    2549      204470 :                 unmatchfreq2 += sslot2->numbers[i];
    2550             :         }
    2551       13882 :         CLAMP_PROBABILITY(matchfreq2);
    2552       13882 :         CLAMP_PROBABILITY(unmatchfreq2);
    2553       13882 :         pfree(hasmatch1);
    2554       13882 :         pfree(hasmatch2);
    2555             : 
    2556             :         /*
    2557             :          * Compute total frequency of non-null values that are not in the MCV
    2558             :          * lists.
    2559             :          */
    2560       13882 :         otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
    2561       13882 :         otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
    2562       13882 :         CLAMP_PROBABILITY(otherfreq1);
    2563       13882 :         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       13882 :         totalsel1 = matchprodfreq;
    2574       13882 :         if (nd2 > sslot2->nvalues)
    2575        5968 :             totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
    2576       13882 :         if (nd2 > nmatches)
    2577       10822 :             totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
    2578       10822 :                 (nd2 - nmatches);
    2579             :         /* Same estimate from the point of view of relation 2. */
    2580       13882 :         totalsel2 = matchprodfreq;
    2581       13882 :         if (nd1 > sslot1->nvalues)
    2582        7138 :             totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
    2583       13882 :         if (nd1 > nmatches)
    2584        9550 :             totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
    2585        9550 :                 (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       13882 :         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      212216 :         double      nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
    2618      212216 :         double      nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
    2619             : 
    2620      212216 :         selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
    2621      212216 :         if (nd1 > nd2)
    2622      109674 :             selec /= nd1;
    2623             :         else
    2624      102542 :             selec /= nd2;
    2625             :     }
    2626             : 
    2627      226098 :     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       10682 : 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       10682 :     if (vardata2->rel)
    2669             :     {
    2670       10676 :         if (nd2 >= vardata2->rel->rows)
    2671             :         {
    2672        8608 :             nd2 = vardata2->rel->rows;
    2673        8608 :             isdefault2 = false;
    2674             :         }
    2675             :     }
    2676       10682 :     if (nd2 >= inner_rel->rows)
    2677             :     {
    2678        8550 :         nd2 = inner_rel->rows;
    2679        8550 :         isdefault2 = false;
    2680             :     }
    2681             : 
    2682       10682 :     if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
    2683         528 :     {
    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         528 :         LOCAL_FCINFO(fcinfo, 2);
    2693             :         FmgrInfo    eqproc;
    2694             :         bool       *hasmatch1;
    2695             :         bool       *hasmatch2;
    2696         528 :         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         528 :         clamped_nvalues2 = Min(sslot2->nvalues, nd2);
    2712             : 
    2713         528 :         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         528 :         InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
    2722             :                                  NULL, NULL);
    2723         528 :         fcinfo->args[0].isnull = false;
    2724         528 :         fcinfo->args[1].isnull = false;
    2725             : 
    2726         528 :         hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
    2727         528 :         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         528 :         nmatches = 0;
    2736       12570 :         for (i = 0; i < sslot1->nvalues; i++)
    2737             :         {
    2738             :             int         j;
    2739             : 
    2740       12042 :             fcinfo->args[0].value = sslot1->values[i];
    2741             : 
    2742      505738 :             for (j = 0; j < clamped_nvalues2; j++)
    2743             :             {
    2744             :                 Datum       fresult;
    2745             : 
    2746      503918 :                 if (hasmatch2[j])
    2747      382458 :                     continue;
    2748      121460 :                 fcinfo->args[1].value = sslot2->values[j];
    2749      121460 :                 fcinfo->isnull = false;
    2750      121460 :                 fresult = FunctionCallInvoke(fcinfo);
    2751      121460 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    2752             :                 {
    2753       10222 :                     hasmatch1[i] = hasmatch2[j] = true;
    2754       10222 :                     nmatches++;
    2755       10222 :                     break;
    2756             :                 }
    2757             :             }
    2758             :         }
    2759             :         /* Sum up frequencies of matched MCVs */
    2760         528 :         matchfreq1 = 0.0;
    2761       12570 :         for (i = 0; i < sslot1->nvalues; i++)
    2762             :         {
    2763       12042 :             if (hasmatch1[i])
    2764       10222 :                 matchfreq1 += sslot1->numbers[i];
    2765             :         }
    2766         528 :         CLAMP_PROBABILITY(matchfreq1);
    2767         528 :         pfree(hasmatch1);
    2768         528 :         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         528 :         if (!isdefault1 && !isdefault2)
    2786             :         {
    2787         528 :             nd1 -= nmatches;
    2788         528 :             nd2 -= nmatches;
    2789         528 :             if (nd1 <= nd2 || nd2 < 0)
    2790         498 :                 uncertainfrac = 1.0;
    2791             :             else
    2792          30 :                 uncertainfrac = nd2 / nd1;
    2793             :         }
    2794             :         else
    2795           0 :             uncertainfrac = 0.5;
    2796         528 :         uncertain = 1.0 - matchfreq1 - nullfrac1;
    2797         528 :         CLAMP_PROBABILITY(uncertain);
    2798         528 :         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       10154 :         double      nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
    2807             : 
    2808       10154 :         if (!isdefault1 && !isdefault2)
    2809             :         {
    2810        7744 :             if (nd1 <= nd2 || nd2 < 0)
    2811        4854 :                 selec = 1.0 - nullfrac1;
    2812             :             else
    2813        2890 :                 selec = (nd2 / nd1) * (1.0 - nullfrac1);
    2814             :         }
    2815             :         else
    2816        2410 :             selec = 0.5 * (1.0 - nullfrac1);
    2817             :     }
    2818             : 
    2819       10682 :     return selec;
    2820             : }
    2821             : 
    2822             : /*
    2823             :  *      neqjoinsel      - Join selectivity of "!="
    2824             :  */
    2825             : Datum
    2826        3734 : neqjoinsel(PG_FUNCTION_ARGS)
    2827             : {
    2828        3734 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    2829        3734 :     Oid         operator = PG_GETARG_OID(1);
    2830        3734 :     List       *args = (List *) PG_GETARG_POINTER(2);
    2831        3734 :     JoinType    jointype = (JoinType) PG_GETARG_INT16(3);
    2832        3734 :     SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
    2833        3734 :     Oid         collation = PG_GET_COLLATION();
    2834             :     float8      result;
    2835             : 
    2836        3734 :     if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
    2837        1264 :     {
    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        1264 :         get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
    2860        1264 :         statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
    2861        1264 :         if (HeapTupleIsValid(statsTuple))
    2862        1034 :             nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
    2863             :         else
    2864         230 :             nullfrac = 0.0;
    2865        1264 :         ReleaseVariableStats(leftvar);
    2866        1264 :         ReleaseVariableStats(rightvar);
    2867             : 
    2868        1264 :         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        2470 :         Oid         eqop = get_negator(operator);
    2877             : 
    2878        2470 :         if (eqop)
    2879             :         {
    2880             :             result =
    2881        2470 :                 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        2470 :         result = 1.0 - result;
    2895             :     }
    2896             : 
    2897        3734 :     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         276 : scalargtjoinsel(PG_FUNCTION_ARGS)
    2923             : {
    2924         276 :     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      115118 : 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      115118 :     *leftstart = *rightstart = 0.0;
    2996      115118 :     *leftend = *rightend = 1.0;
    2997             : 
    2998             :     /* Deconstruct the merge clause */
    2999      115118 :     if (!is_opclause(clause))
    3000           0 :         return;                 /* shouldn't happen */
    3001      115118 :     opno = ((OpExpr *) clause)->opno;
    3002      115118 :     collation = ((OpExpr *) clause)->inputcollid;
    3003      115118 :     left = get_leftop((Expr *) clause);
    3004      115118 :     right = get_rightop((Expr *) clause);
    3005      115118 :     if (!right)
    3006           0 :         return;                 /* shouldn't happen */
    3007             : 
    3008             :     /* Look for stats for the inputs */
    3009      115118 :     examine_variable(root, left, 0, &leftvar);
    3010      115118 :     examine_variable(root, right, 0, &rightvar);
    3011             : 
    3012      115118 :     opmethod = get_opfamily_method(opfamily);
    3013             : 
    3014             :     /* Extract the operator's declared left/right datatypes */
    3015      115118 :     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      115118 :     switch (cmptype)
    3029             :     {
    3030      115046 :         case COMPARE_LT:
    3031      115046 :             isgt = false;
    3032      115046 :             ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
    3033      115046 :             lestrat = IndexAmTranslateCompareType(COMPARE_LE, opmethod, opfamily, true);
    3034      115046 :             if (op_lefttype == op_righttype)
    3035             :             {
    3036             :                 /* easy case */
    3037      113640 :                 ltop = get_opfamily_member(opfamily,
    3038             :                                            op_lefttype, op_righttype,
    3039             :                                            ltstrat);
    3040      113640 :                 leop = get_opfamily_member(opfamily,
    3041             :                                            op_lefttype, op_righttype,
    3042             :                                            lestrat);
    3043      113640 :                 lsortop = ltop;
    3044      113640 :                 rsortop = ltop;
    3045      113640 :                 lstatop = lsortop;
    3046      113640 :                 rstatop = rsortop;
    3047      113640 :                 revltop = ltop;
    3048      113640 :                 revleop = leop;
    3049             :             }
    3050             :             else
    3051             :             {
    3052        1406 :                 ltop = get_opfamily_member(opfamily,
    3053             :                                            op_lefttype, op_righttype,
    3054             :                                            ltstrat);
    3055        1406 :                 leop = get_opfamily_member(opfamily,
    3056             :                                            op_lefttype, op_righttype,
    3057             :                                            lestrat);
    3058        1406 :                 lsortop = get_opfamily_member(opfamily,
    3059             :                                               op_lefttype, op_lefttype,
    3060             :                                               ltstrat);
    3061        1406 :                 rsortop = get_opfamily_member(opfamily,
    3062             :                                               op_righttype, op_righttype,
    3063             :                                               ltstrat);
    3064        1406 :                 lstatop = lsortop;
    3065        1406 :                 rstatop = rsortop;
    3066        1406 :                 revltop = get_opfamily_member(opfamily,
    3067             :                                               op_righttype, op_lefttype,
    3068             :                                               ltstrat);
    3069        1406 :                 revleop = get_opfamily_member(opfamily,
    3070             :                                               op_righttype, op_lefttype,
    3071             :                                               lestrat);
    3072             :             }
    3073      115046 :             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      115118 :     if (!OidIsValid(lsortop) ||
    3131      115118 :         !OidIsValid(rsortop) ||
    3132      115118 :         !OidIsValid(lstatop) ||
    3133      115118 :         !OidIsValid(rstatop) ||
    3134      115106 :         !OidIsValid(ltop) ||
    3135      115106 :         !OidIsValid(leop) ||
    3136      115106 :         !OidIsValid(revltop) ||
    3137             :         !OidIsValid(revleop))
    3138          12 :         goto fail;              /* insufficient info in catalogs */
    3139             : 
    3140             :     /* Try to get ranges of both inputs */
    3141      115106 :     if (!isgt)
    3142             :     {
    3143      115034 :         if (!get_variable_range(root, &leftvar, lstatop, collation,
    3144             :                                 &leftmin, &leftmax))
    3145       24986 :             goto fail;          /* no range available from stats */
    3146       90048 :         if (!get_variable_range(root, &rightvar, rstatop, collation,
    3147             :                                 &rightmin, &rightmax))
    3148       23970 :             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       66120 :     selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
    3167             :                           rightmax, op_righttype);
    3168       66120 :     if (selec != DEFAULT_INEQ_SEL)
    3169       66114 :         *leftend = selec;
    3170             : 
    3171             :     /* And similarly for the right variable. */
    3172       66120 :     selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
    3173             :                           leftmax, op_lefttype);
    3174       66120 :     if (selec != DEFAULT_INEQ_SEL)
    3175       66120 :         *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       66120 :     if (*leftend > *rightend)
    3184       24430 :         *leftend = 1.0;
    3185       41690 :     else if (*leftend < *rightend)
    3186       33634 :         *rightend = 1.0;
    3187             :     else
    3188        8056 :         *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       66120 :     selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
    3197             :                           rightmin, op_righttype);
    3198       66120 :     if (selec != DEFAULT_INEQ_SEL)
    3199       66120 :         *leftstart = selec;
    3200             : 
    3201             :     /* And similarly for the right variable. */
    3202       66120 :     selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
    3203             :                           leftmin, op_lefttype);
    3204       66120 :     if (selec != DEFAULT_INEQ_SEL)
    3205       66120 :         *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       66120 :     if (*leftstart < *rightstart)
    3214       17090 :         *leftstart = 0.0;
    3215       49030 :     else if (*leftstart > *rightstart)
    3216       23956 :         *rightstart = 0.0;
    3217             :     else
    3218       25074 :         *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       66120 :     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       66120 :     if (*leftstart >= *leftend)
    3250             :     {
    3251         194 :         *leftstart = 0.0;
    3252         194 :         *leftend = 1.0;
    3253             :     }
    3254       66120 :     if (*rightstart >= *rightend)
    3255             :     {
    3256        1084 :         *rightstart = 0.0;
    3257        1084 :         *rightend = 1.0;
    3258             :     }
    3259             : 
    3260       65036 : fail:
    3261      115118 :     ReleaseVariableStats(leftvar);
    3262      115118 :     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      357754 : 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      357754 :     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      357754 :     var = remove_nulling_relids(var, root->outer_join_rels, NULL);
    3333             : 
    3334      436030 :     foreach(lc, varinfos)
    3335             :     {
    3336       79254 :         varinfo = (GroupVarInfo *) lfirst(lc);
    3337             : 
    3338             :         /* Drop exact duplicates */
    3339       79254 :         if (equal(var, varinfo->var))
    3340         978 :             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       83346 :         if (vardata->rel != varinfo->rel &&
    3348        4854 :             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      356776 :     varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
    3364             : 
    3365      356776 :     varinfo->var = var;
    3366      356776 :     varinfo->rel = vardata->rel;
    3367      356776 :     varinfo->ndistinct = ndistinct;
    3368      356776 :     varinfo->isdefault = isdefault;
    3369      356776 :     varinfos = lappend(varinfos, varinfo);
    3370      356776 :     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      309586 : estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
    3446             :                     List **pgset, EstimationInfo *estinfo)
    3447             : {
    3448      309586 :     List       *varinfos = NIL;
    3449      309586 :     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      309586 :     if (estinfo != NULL)
    3456      274980 :         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      309586 :     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      309586 :     if (groupExprs == NIL || (pgset && *pgset == NIL))
    3472        1070 :         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      308516 :     numdistinct = 1.0;
    3482             : 
    3483      308516 :     i = 0;
    3484      664708 :     foreach(l, groupExprs)
    3485             :     {
    3486      356240 :         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      356240 :         if (pgset && !list_member_int(*pgset, i++))
    3494      295408 :             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      355452 :         this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
    3508      355452 :         if (srf_multiplier < this_srf_multiplier)
    3509         132 :             srf_multiplier = this_srf_multiplier;
    3510             : 
    3511             :         /* Short-circuit for expressions returning boolean */
    3512      355452 :         if (exprType(groupexpr) == BOOLOID)
    3513             :         {
    3514         198 :             numdistinct *= 2.0;
    3515         198 :             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      355254 :         examine_variable(root, groupexpr, 0, &vardata);
    3532      355254 :         if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
    3533             :         {
    3534      293744 :             varinfos = add_unique_group_var(root, varinfos,
    3535             :                                             groupexpr, &vardata);
    3536      293744 :             ReleaseVariableStats(vardata);
    3537      293744 :             continue;
    3538             :         }
    3539       61510 :         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       61510 :         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       61510 :         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      124794 :         foreach(l2, varshere)
    3569             :         {
    3570       64010 :             Node       *var = (Node *) lfirst(l2);
    3571             : 
    3572       64010 :             examine_variable(root, var, 0, &vardata);
    3573       64010 :             varinfos = add_unique_group_var(root, varinfos, var, &vardata);
    3574       64010 :             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      308468 :     if (varinfos == NIL)
    3583             :     {
    3584             :         /* Apply SRF multiplier as we would do in the long path */
    3585         394 :         numdistinct *= srf_multiplier;
    3586             :         /* Round off */
    3587         394 :         numdistinct = ceil(numdistinct);
    3588             :         /* Guard against out-of-range answers */
    3589         394 :         if (numdistinct > input_rows)
    3590          38 :             numdistinct = input_rows;
    3591         394 :         if (numdistinct < 1.0)
    3592           0 :             numdistinct = 1.0;
    3593         394 :         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      310054 :         GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
    3607      310054 :         RelOptInfo *rel = varinfo1->rel;
    3608      310054 :         double      reldistinct = 1;
    3609      310054 :         double      relmaxndistinct = reldistinct;
    3610      310054 :         int         relvarcount = 0;
    3611      310054 :         List       *newvarinfos = NIL;
    3612      310054 :         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      310054 :         relvarinfos = lappend(relvarinfos, varinfo1);
    3619      360700 :         for_each_from(l, varinfos, 1)
    3620             :         {
    3621       50646 :             GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
    3622             : 
    3623       50646 :             if (varinfo2->rel == varinfo1->rel)
    3624             :             {
    3625             :                 /* varinfos on current rel */
    3626       46698 :                 relvarinfos = lappend(relvarinfos, varinfo2);
    3627             :             }
    3628             :             else
    3629             :             {
    3630             :                 /* not time to process varinfo2 yet */
    3631        3948 :                 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      620234 :         while (relvarinfos)
    3648             :         {
    3649             :             double      mvndistinct;
    3650             : 
    3651      310180 :             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      665678 :                 foreach(l, relvarinfos)
    3662             :                 {
    3663      355900 :                     GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
    3664             : 
    3665      355900 :                     reldistinct *= varinfo2->ndistinct;
    3666      355900 :                     if (relmaxndistinct < varinfo2->ndistinct)
    3667      311892 :                         relmaxndistinct = varinfo2->ndistinct;
    3668      355900 :                     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      355900 :                     if (estinfo != NULL && varinfo2->isdefault)
    3675       17828 :                         estinfo->flags |= SELFLAG_USED_DEFAULT;
    3676             :                 }
    3677             : 
    3678             :                 /* we're done with this relation */
    3679      309778 :                 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      310054 :         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      309006 :             double      clamp = rel->tuples;
    3697             : 
    3698      309006 :             if (relvarcount > 1)
    3699             :             {
    3700       42154 :                 clamp *= 0.1;
    3701       42154 :                 if (clamp < relmaxndistinct)
    3702             :                 {
    3703       40154 :                     clamp = relmaxndistinct;
    3704             :                     /* for sanity in case some ndistinct is too large: */
    3705       40154 :                     if (clamp > rel->tuples)
    3706          78 :                         clamp = rel->tuples;
    3707             :                 }
    3708             :             }
    3709      309006 :             if (reldistinct > clamp)
    3710       34672 :                 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      309006 :             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      104344 :                 reldistinct *=
    3754      104344 :                     (1 - pow((rel->tuples - rel->rows) / rel->tuples,
    3755      104344 :                              rel->tuples / reldistinct));
    3756             :             }
    3757      309006 :             reldistinct = clamp_row_est(reldistinct);
    3758             : 
    3759             :             /*
    3760             :              * Update estimate of total distinct groups.
    3761             :              */
    3762      309006 :             numdistinct *= reldistinct;
    3763             :         }
    3764             : 
    3765      310054 :         varinfos = newvarinfos;
    3766      310054 :     } while (varinfos != NIL);
    3767             : 
    3768             :     /* Now we can account for the effects of any SRFs */
    3769      308074 :     numdistinct *= srf_multiplier;
    3770             : 
    3771             :     /* Round off */
    3772      308074 :     numdistinct = ceil(numdistinct);
    3773             : 
    3774             :     /* Guard against out-of-range answers */
    3775      308074 :     if (numdistinct > input_rows)
    3776       62232 :         numdistinct = input_rows;
    3777      308074 :     if (numdistinct < 1.0)
    3778           0 :         numdistinct = 1.0;
    3779             : 
    3780      308074 :     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      276976 : estimate_multivariate_bucketsize(PlannerInfo *root, RelOptInfo *inner,
    3798             :                                  List *hashclauses,
    3799             :                                  Selectivity *innerbucketsize)
    3800             : {
    3801             :     List       *clauses;
    3802             :     List       *otherclauses;
    3803             :     double      ndistinct;
    3804             : 
    3805      276976 :     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      245132 :         return hashclauses;
    3812             :     }
    3813             : 
    3814             :     /* "clauses" is the list of hashclauses we've not dealt with yet */
    3815       31844 :     clauses = list_copy(hashclauses);
    3816             :     /* "otherclauses" holds clauses we are going to return to caller */
    3817       31844 :     otherclauses = NIL;
    3818             :     /* current estimate of ndistinct */
    3819       31844 :     ndistinct = 1.0;
    3820       63700 :     while (clauses != NIL)
    3821             :     {
    3822             :         ListCell   *lc;
    3823       31856 :         int         relid = -1;
    3824       31856 :         List       *varinfos = NIL;
    3825       31856 :         List       *origin_rinfos = NIL;
    3826             :         double      mvndistinct;
    3827             :         List       *origin_varinfos;
    3828       31856 :         int         group_relid = -1;
    3829       31856 :         RelOptInfo *group_rel = NULL;
    3830             :         ListCell   *lc1,
    3831             :                    *lc2;
    3832             : 
    3833             :         /*
    3834             :          * Find clauses, referencing the same single base relation and try to
    3835             :          * estimate such a group with extended statistics.  Create varinfo for
    3836             :          * an approved clause, push it to otherclauses, if it can't be
    3837             :          * estimated here or ignore to process at the next iteration.
    3838             :          */
    3839       96180 :         foreach(lc, clauses)
    3840             :         {
    3841       64324 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
    3842             :             Node       *expr;
    3843             :             Relids      relids;
    3844             :             GroupVarInfo *varinfo;
    3845             : 
    3846             :             /*
    3847             :              * Find the inner side of the join, which we need to estimate the
    3848             :              * number of buckets.  Use outer_is_left because the
    3849             :              * clause_sides_match_join routine has called on hash clauses.
    3850             :              */
    3851      128648 :             relids = rinfo->outer_is_left ?
    3852       64324 :                 rinfo->right_relids : rinfo->left_relids;
    3853      128648 :             expr = rinfo->outer_is_left ?
    3854       64324 :                 get_rightop(rinfo->clause) : get_leftop(rinfo->clause);
    3855             : 
    3856       64324 :             if (bms_get_singleton_member(relids, &relid) &&
    3857       61686 :                 root->simple_rel_array[relid]->statlist != NIL)
    3858          48 :             {
    3859          60 :                 bool        is_duplicate = false;
    3860             : 
    3861             :                 /*
    3862             :                  * This inner-side expression references only one relation.
    3863             :                  * Extended statistics on this clause can exist.
    3864             :                  */
    3865          60 :                 if (group_relid < 0)
    3866             :                 {
    3867          30 :                     RangeTblEntry *rte = root->simple_rte_array[relid];
    3868             : 
    3869          30 :                     if (!rte || (rte->relkind != RELKIND_RELATION &&
    3870           0 :                                  rte->relkind != RELKIND_MATVIEW &&
    3871           0 :                                  rte->relkind != RELKIND_FOREIGN_TABLE &&
    3872           0 :                                  rte->relkind != RELKIND_PARTITIONED_TABLE))
    3873             :                     {
    3874             :                         /* Extended statistics can't exist in principle */
    3875           0 :                         otherclauses = lappend(otherclauses, rinfo);
    3876           0 :                         clauses = foreach_delete_current(clauses, lc);
    3877           0 :                         continue;
    3878             :                     }
    3879             : 
    3880          30 :                     group_relid = relid;
    3881          30 :                     group_rel = root->simple_rel_array[relid];
    3882             :                 }
    3883          30 :                 else if (group_relid != relid)
    3884             :                 {
    3885             :                     /*
    3886             :                      * Being in the group forming state we don't need other
    3887             :                      * clauses.
    3888             :                      */
    3889           0 :                     continue;
    3890             :                 }
    3891             : 
    3892             :                 /*
    3893             :                  * We're going to add the new clause to the varinfos list.  We
    3894             :                  * might re-use add_unique_group_var(), but we don't do so for
    3895             :                  * two reasons.
    3896             :                  *
    3897             :                  * 1) We must keep the origin_rinfos list ordered exactly the
    3898             :                  * same way as varinfos.
    3899             :                  *
    3900             :                  * 2) add_unique_group_var() is designed for
    3901             :                  * estimate_num_groups(), where a larger number of groups is
    3902             :                  * worse.   While estimating the number of hash buckets, we
    3903             :                  * have the opposite: a lesser number of groups is worse.
    3904             :                  * Therefore, we don't have to remove "known equal" vars: the
    3905             :                  * removed var may valuably contribute to the multivariate
    3906             :                  * statistics to grow the number of groups.
    3907             :                  */
    3908             : 
    3909             :                 /*
    3910             :                  * Clear nullingrels to correctly match hash keys.  See
    3911             :                  * add_unique_group_var()'s comment for details.
    3912             :                  */
    3913          60 :                 expr = remove_nulling_relids(expr, root->outer_join_rels, NULL);
    3914             : 
    3915             :                 /*
    3916             :                  * Detect and exclude exact duplicates from the list of hash
    3917             :                  * keys (like add_unique_group_var does).
    3918             :                  */
    3919          84 :                 foreach(lc1, varinfos)
    3920             :                 {
    3921          36 :                     varinfo = (GroupVarInfo *) lfirst(lc1);
    3922             : 
    3923          36 :                     if (!equal(expr, varinfo->var))
    3924          24 :                         continue;
    3925             : 
    3926          12 :                     is_duplicate = true;
    3927          12 :                     break;
    3928             :                 }
    3929             : 
    3930          60 :                 if (is_duplicate)
    3931             :                 {
    3932             :                     /*
    3933             :                      * Skip exact duplicates. Adding them to the otherclauses
    3934             :                      * list also doesn't make sense.
    3935             :                      */
    3936          12 :                     continue;
    3937             :                 }
    3938             : 
    3939             :                 /*
    3940             :                  * Initialize GroupVarInfo.  We only use it to call
    3941             :                  * estimate_multivariate_ndistinct(), which doesn't care about
    3942             :                  * ndistinct and isdefault fields.  Thus, skip these fields.
    3943             :                  */
    3944          48 :                 varinfo = (GroupVarInfo *) palloc0(sizeof(GroupVarInfo));
    3945          48 :                 varinfo->var = expr;
    3946          48 :                 varinfo->rel = root->simple_rel_array[relid];
    3947          48 :                 varinfos = lappend(varinfos, varinfo);
    3948             : 
    3949             :                 /*
    3950             :                  * Remember the link to RestrictInfo for the case the clause
    3951             :                  * is failed to be estimated.
    3952             :                  */
    3953          48 :                 origin_rinfos = lappend(origin_rinfos, rinfo);
    3954             :             }
    3955             :             else
    3956             :             {
    3957             :                 /* This clause can't be estimated with extended statistics */
    3958       64264 :                 otherclauses = lappend(otherclauses, rinfo);
    3959             :             }
    3960             : 
    3961       64312 :             clauses = foreach_delete_current(clauses, lc);
    3962             :         }
    3963             : 
    3964       31856 :         if (list_length(varinfos) < 2)
    3965             :         {
    3966             :             /*
    3967             :              * Multivariate statistics doesn't apply to single columns except
    3968             :              * for expressions, but it has not been implemented yet.
    3969             :              */
    3970       31844 :             otherclauses = list_concat(otherclauses, origin_rinfos);
    3971       31844 :             list_free_deep(varinfos);
    3972       31844 :             list_free(origin_rinfos);
    3973       31844 :             continue;
    3974             :         }
    3975             : 
    3976             :         Assert(group_rel != NULL);
    3977             : 
    3978             :         /* Employ the extended statistics. */
    3979          12 :         origin_varinfos = varinfos;
    3980             :         for (;;)
    3981          12 :         {
    3982          24 :             bool        estimated = estimate_multivariate_ndistinct(root,
    3983             :                                                                     group_rel,
    3984             :                                                                     &varinfos,
    3985             :                                                                     &mvndistinct);
    3986             : 
    3987          24 :             if (!estimated)
    3988          12 :                 break;
    3989             : 
    3990             :             /*
    3991             :              * We've got an estimation.  Use ndistinct value in a consistent
    3992             :              * way - according to the caller's logic (see
    3993             :              * final_cost_hashjoin).
    3994             :              */
    3995          12 :             if (ndistinct < mvndistinct)
    3996          12 :                 ndistinct = mvndistinct;
    3997             :             Assert(ndistinct >= 1.0);
    3998             :         }
    3999             : 
    4000             :         Assert(list_length(origin_varinfos) == list_length(origin_rinfos));
    4001             : 
    4002             :         /* Collect unmatched clauses as otherclauses. */
    4003          42 :         forboth(lc1, origin_varinfos, lc2, origin_rinfos)
    4004             :         {
    4005          30 :             GroupVarInfo *vinfo = lfirst(lc1);
    4006             : 
    4007          30 :             if (!list_member_ptr(varinfos, vinfo))
    4008             :                 /* Already estimated */
    4009          30 :                 continue;
    4010             : 
    4011             :             /* Can't be estimated here - push to the returning list */
    4012           0 :             otherclauses = lappend(otherclauses, lfirst(lc2));
    4013             :         }
    4014             :     }
    4015             : 
    4016       31844 :     *innerbucketsize = 1.0 / ndistinct;
    4017       31844 :     return otherclauses;
    4018             : }
    4019             : 
    4020             : /*
    4021             :  * Estimate hash bucket statistics when the specified expression is used
    4022             :  * as a hash key for the given number of buckets.
    4023             :  *
    4024             :  * This attempts to determine two values:
    4025             :  *
    4026             :  * 1. The frequency of the most common value of the expression (returns
    4027             :  * zero into *mcv_freq if we can't get that).
    4028             :  *
    4029             :  * 2. The "bucketsize fraction", ie, average number of entries in a bucket
    4030             :  * divided by total tuples in relation.
    4031             :  *
    4032             :  * XXX This is really pretty bogus since we're effectively assuming that the
    4033             :  * distribution of hash keys will be the same after applying restriction
    4034             :  * clauses as it was in the underlying relation.  However, we are not nearly
    4035             :  * smart enough to figure out how the restrict clauses might change the
    4036             :  * distribution, so this will have to do for now.
    4037             :  *
    4038             :  * We are passed the number of buckets the executor will use for the given
    4039             :  * input relation.  If the data were perfectly distributed, with the same
    4040             :  * number of tuples going into each available bucket, then the bucketsize
    4041             :  * fraction would be 1/nbuckets.  But this happy state of affairs will occur
    4042             :  * only if (a) there are at least nbuckets distinct data values, and (b)
    4043             :  * we have a not-too-skewed data distribution.  Otherwise the buckets will
    4044             :  * be nonuniformly occupied.  If the other relation in the join has a key
    4045             :  * distribution similar to this one's, then the most-loaded buckets are
    4046             :  * exactly those that will be probed most often.  Therefore, the "average"
    4047             :  * bucket size for costing purposes should really be taken as something close
    4048             :  * to the "worst case" bucket size.  We try to estimate this by adjusting the
    4049             :  * fraction if there are too few distinct data values, and then scaling up
    4050             :  * by the ratio of the most common value's frequency to the average frequency.
    4051             :  *
    4052             :  * If no statistics are available, use a default estimate of 0.1.  This will
    4053             :  * discourage use of a hash rather strongly if the inner relation is large,
    4054             :  * which is what we want.  We do not want to hash unless we know that the
    4055             :  * inner rel is well-dispersed (or the alternatives seem much worse).
    4056             :  *
    4057             :  * The caller should also check that the mcv_freq is not so large that the
    4058             :  * most common value would by itself require an impractically large bucket.
    4059             :  * In a hash join, the executor can split buckets if they get too big, but
    4060             :  * obviously that doesn't help for a bucket that contains many duplicates of
    4061             :  * the same value.
    4062             :  */
    4063             : void
    4064      164218 : estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets,
    4065             :                            Selectivity *mcv_freq,
    4066             :                            Selectivity *bucketsize_frac)
    4067             : {
    4068             :     VariableStatData vardata;
    4069             :     double      estfract,
    4070             :                 ndistinct,
    4071             :                 stanullfrac,
    4072             :                 avgfreq;
    4073             :     bool        isdefault;
    4074             :     AttStatsSlot sslot;
    4075             : 
    4076      164218 :     examine_variable(root, hashkey, 0, &vardata);
    4077             : 
    4078             :     /* Look up the frequency of the most common value, if available */
    4079      164218 :     *mcv_freq = 0.0;
    4080             : 
    4081      164218 :     if (HeapTupleIsValid(vardata.statsTuple))
    4082             :     {
    4083      114036 :         if (get_attstatsslot(&sslot, vardata.statsTuple,
    4084             :                              STATISTIC_KIND_MCV, InvalidOid,
    4085             :                              ATTSTATSSLOT_NUMBERS))
    4086             :         {
    4087             :             /*
    4088             :              * The first MCV stat is for the most common value.
    4089             :              */
    4090       56286 :             if (sslot.nnumbers > 0)
    4091       56286 :                 *mcv_freq = sslot.numbers[0];
    4092       56286 :             free_attstatsslot(&sslot);
    4093             :         }
    4094             :     }
    4095             : 
    4096             :     /* Get number of distinct values */
    4097      164218 :     ndistinct = get_variable_numdistinct(&vardata, &isdefault);
    4098             : 
    4099             :     /*
    4100             :      * If ndistinct isn't real, punt.  We normally return 0.1, but if the
    4101             :      * mcv_freq is known to be even higher than that, use it instead.
    4102             :      */
    4103      164218 :     if (isdefault)
    4104             :     {
    4105       21526 :         *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
    4106       21526 :         ReleaseVariableStats(vardata);
    4107       21526 :         return;
    4108             :     }
    4109             : 
    4110             :     /* Get fraction that are null */
    4111      142692 :     if (HeapTupleIsValid(vardata.statsTuple))
    4112             :     {
    4113             :         Form_pg_statistic stats;
    4114             : 
    4115      114018 :         stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
    4116      114018 :         stanullfrac = stats->stanullfrac;
    4117             :     }
    4118             :     else
    4119       28674 :         stanullfrac = 0.0;
    4120             : 
    4121             :     /* Compute avg freq of all distinct data values in raw relation */
    4122      142692 :     avgfreq = (1.0 - stanullfrac) / ndistinct;
    4123             : 
    4124             :     /*
    4125             :      * Adjust ndistinct to account for restriction clauses.  Observe we are
    4126             :      * assuming that the data distribution is affected uniformly by the
    4127             :      * restriction clauses!
    4128             :      *
    4129             :      * XXX Possibly better way, but much more expensive: multiply by
    4130             :      * selectivity of rel's restriction clauses that mention the target Var.
    4131             :      */
    4132      142692 :     if (vardata.rel && vardata.rel->tuples > 0)
    4133             :     {
    4134      142678 :         ndistinct *= vardata.rel->rows / vardata.rel->tuples;
    4135      142678 :         ndistinct = clamp_row_est(ndistinct);
    4136             :     }
    4137             : 
    4138             :     /*
    4139             :      * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
    4140             :      * number of buckets is less than the expected number of distinct values;
    4141             :      * otherwise it is 1/ndistinct.
    4142             :      */
    4143      142692 :     if (ndistinct > nbuckets)
    4144          84 :         estfract = 1.0 / nbuckets;
    4145             :     else
    4146      142608 :         estfract = 1.0 / ndistinct;
    4147             : 
    4148             :     /*
    4149             :      * Adjust estimated bucketsize upward to account for skewed distribution.
    4150             :      */
    4151      142692 :     if (avgfreq > 0.0 && *mcv_freq > avgfreq)
    4152       49262 :         estfract *= *mcv_freq / avgfreq;
    4153             : 
    4154             :     /*
    4155             :      * Clamp bucketsize to sane range (the above adjustment could easily
    4156             :      * produce an out-of-range result).  We set the lower bound a little above
    4157             :      * zero, since zero isn't a very sane result.
    4158             :      */
    4159      142692 :     if (estfract < 1.0e-6)
    4160           0 :         estfract = 1.0e-6;
    4161      142692 :     else if (estfract > 1.0)
    4162       35130 :         estfract = 1.0;
    4163             : 
    4164      142692 :     *bucketsize_frac = (Selectivity) estfract;
    4165             : 
    4166      142692 :     ReleaseVariableStats(vardata);
    4167             : }
    4168             : 
    4169             : /*
    4170             :  * estimate_hashagg_tablesize
    4171             :  *    estimate the number of bytes that a hash aggregate hashtable will
    4172             :  *    require based on the agg_costs, path width and number of groups.
    4173             :  *
    4174             :  * We return the result as "double" to forestall any possible overflow
    4175             :  * problem in the multiplication by dNumGroups.
    4176             :  *
    4177             :  * XXX this may be over-estimating the size now that hashagg knows to omit
    4178             :  * unneeded columns from the hashtable.  Also for mixed-mode grouping sets,
    4179             :  * grouping columns not in the hashed set are counted here even though hashagg
    4180             :  * won't store them.  Is this a problem?
    4181             :  */
    4182             : double
    4183        2350 : estimate_hashagg_tablesize(PlannerInfo *root, Path *path,
    4184             :                            const AggClauseCosts *agg_costs, double dNumGroups)
    4185             : {
    4186             :     Size        hashentrysize;
    4187             : 
    4188        2350 :     hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
    4189        2350 :                                         path->pathtarget->width,
    4190        2350 :                                         agg_costs->transitionSpace);
    4191             : 
    4192             :     /*
    4193             :      * Note that this disregards the effect of fill-factor and growth policy
    4194             :      * of the hash table.  That's probably ok, given that the default
    4195             :      * fill-factor is relatively high.  It'd be hard to meaningfully factor in
    4196             :      * "double-in-size" growth policies here.
    4197             :      */
    4198        2350 :     return hashentrysize * dNumGroups;
    4199             : }
    4200             : 
    4201             : 
    4202             : /*-------------------------------------------------------------------------
    4203             :  *
    4204             :  * Support routines
    4205             :  *
    4206             :  *-------------------------------------------------------------------------
    4207             :  */
    4208             : 
    4209             : /*
    4210             :  * Find the best matching ndistinct extended statistics for the given list of
    4211             :  * GroupVarInfos.
    4212             :  *
    4213             :  * Callers must ensure that the given GroupVarInfos all belong to 'rel' and
    4214             :  * the GroupVarInfos list does not contain any duplicate Vars or expressions.
    4215             :  *
    4216             :  * When statistics are found that match > 1 of the given GroupVarInfo, the
    4217             :  * *ndistinct parameter is set according to the ndistinct estimate and a new
    4218             :  * list is built with the matching GroupVarInfos removed, which is output via
    4219             :  * the *varinfos parameter before returning true.  When no matching stats are
    4220             :  * found, false is returned and the *varinfos and *ndistinct parameters are
    4221             :  * left untouched.
    4222             :  */
    4223             : static bool
    4224      310204 : estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel,
    4225             :                                 List **varinfos, double *ndistinct)
    4226             : {
    4227             :     ListCell   *lc;
    4228             :     int         nmatches_vars;
    4229             :     int         nmatches_exprs;
    4230      310204 :     Oid         statOid = InvalidOid;
    4231             :     MVNDistinct *stats;
    4232      310204 :     StatisticExtInfo *matched_info = NULL;
    4233      310204 :     RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
    4234             : 
    4235             :     /* bail out immediately if the table has no extended statistics */
    4236      310204 :     if (!rel->statlist)
    4237      309652 :         return false;
    4238             : 
    4239             :     /* look for the ndistinct statistics object matching the most vars */
    4240         552 :     nmatches_vars = 0;          /* we require at least two matches */
    4241         552 :     nmatches_exprs = 0;
    4242        2172 :     foreach(lc, rel->statlist)
    4243             :     {
    4244             :         ListCell   *lc2;
    4245        1620 :         StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
    4246        1620 :         int         nshared_vars = 0;
    4247        1620 :         int         nshared_exprs = 0;
    4248             : 
    4249             :         /* skip statistics of other kinds */
    4250        1620 :         if (info->kind != STATS_EXT_NDISTINCT)
    4251         750 :             continue;
    4252             : 
    4253             :         /* skip statistics with mismatching stxdinherit value */
    4254         870 :         if (info->inherit != rte->inh)
    4255          24 :             continue;
    4256             : 
    4257             :         /*
    4258             :          * Determine how many expressions (and variables in non-matched
    4259             :          * expressions) match. We'll then use these numbers to pick the
    4260             :          * statistics object that best matches the clauses.
    4261             :          */
    4262        2682 :         foreach(lc2, *varinfos)
    4263             :         {
    4264             :             ListCell   *lc3;
    4265        1836 :             GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
    4266             :             AttrNumber  attnum;
    4267             : 
    4268             :             Assert(varinfo->rel == rel);
    4269             : 
    4270             :             /* simple Var, search in statistics keys directly */
    4271        1836 :             if (IsA(varinfo->var, Var))
    4272             :             {
    4273        1470 :                 attnum = ((Var *) varinfo->var)->varattno;
    4274             : 
    4275             :                 /*
    4276             :                  * Ignore system attributes - we don't support statistics on
    4277             :                  * them, so can't match them (and it'd fail as the values are
    4278             :                  * negative).
    4279             :                  */
    4280        1470 :                 if (!AttrNumberIsForUserDefinedAttr(attnum))
    4281          12 :                     continue;
    4282             : 
    4283        1458 :                 if (bms_is_member(attnum, info->keys))
    4284         852 :                     nshared_vars++;
    4285             : 
    4286        1458 :                 continue;
    4287             :             }
    4288             : 
    4289             :             /* expression - see if it's in the statistics object */
    4290         660 :             foreach(lc3, info->exprs)
    4291             :             {
    4292         528 :                 Node       *expr = (Node *) lfirst(lc3);
    4293             : 
    4294         528 :                 if (equal(varinfo->var, expr))
    4295             :                 {
    4296         234 :                     nshared_exprs++;
    4297         234 :                     break;
    4298             :                 }
    4299             :             }
    4300             :         }
    4301             : 
    4302             :         /*
    4303             :          * The ndistinct extended statistics contain estimates for a minimum
    4304             :          * of pairs of columns which the statistics are defined on and
    4305             :          * certainly not single columns.  Here we skip unless we managed to
    4306             :          * match to at least two columns.
    4307             :          */
    4308         846 :         if (nshared_vars + nshared_exprs < 2)
    4309         396 :             continue;
    4310             : 
    4311             :         /*
    4312             :          * Check if these statistics are a better match than the previous best
    4313             :          * match and if so, take note of the StatisticExtInfo.
    4314             :          *
    4315             :          * The statslist is sorted by statOid, so the StatisticExtInfo we
    4316             :          * select as the best match is deterministic even when multiple sets
    4317             :          * of statistics match equally as well.
    4318             :          */
    4319         450 :         if ((nshared_exprs > nmatches_exprs) ||
    4320         342 :             (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
    4321             :         {
    4322         426 :             statOid = info->statOid;
    4323         426 :             nmatches_vars = nshared_vars;
    4324         426 :             nmatches_exprs = nshared_exprs;
    4325         426 :             matched_info = info;
    4326             :         }
    4327             :     }
    4328             : 
    4329             :     /* No match? */
    4330         552 :     if (statOid == InvalidOid)
    4331         138 :         return false;
    4332             : 
    4333             :     Assert(nmatches_vars + nmatches_exprs > 1);
    4334             : 
    4335         414 :     stats = statext_ndistinct_load(statOid, rte->inh);
    4336             : 
    4337             :     /*
    4338             :      * If we have a match, search it for the specific item that matches (there
    4339             :      * must be one), and construct the output values.
    4340             :      */
    4341         414 :     if (stats)
    4342             :     {
    4343             :         int         i;
    4344         414 :         List       *newlist = NIL;
    4345         414 :         MVNDistinctItem *item = NULL;
    4346             :         ListCell   *lc2;
    4347         414 :         Bitmapset  *matched = NULL;
    4348             :         AttrNumber  attnum_offset;
    4349             : 
    4350             :         /*
    4351             :          * How much we need to offset the attnums? If there are no
    4352             :          * expressions, no offset is needed. Otherwise offset enough to move
    4353             :          * the lowest one (which is equal to number of expressions) to 1.
    4354             :          */
    4355         414 :         if (matched_info->exprs)
    4356         144 :             attnum_offset = (list_length(matched_info->exprs) + 1);
    4357             :         else
    4358         270 :             attnum_offset = 0;
    4359             : 
    4360             :         /* see what actually matched */
    4361        1452 :         foreach(lc2, *varinfos)
    4362             :         {
    4363             :             ListCell   *lc3;
    4364             :             int         idx;
    4365        1038 :             bool        found = false;
    4366             : 
    4367        1038 :             GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
    4368             : 
    4369             :             /*
    4370             :              * Process a simple Var expression, by matching it to keys
    4371             :              * directly. If there's a matching expression, we'll try matching
    4372             :              * it later.
    4373             :              */
    4374        1038 :             if (IsA(varinfo->var, Var))
    4375             :             {
    4376         852 :                 AttrNumber  attnum = ((Var *) varinfo->var)->varattno;
    4377             : 
    4378             :                 /*
    4379             :                  * Ignore expressions on system attributes. Can't rely on the
    4380             :                  * bms check for negative values.
    4381             :                  */
    4382         852 :                 if (!AttrNumberIsForUserDefinedAttr(attnum))
    4383           6 :                     continue;
    4384             : 
    4385             :                 /* Is the variable covered by the statistics object? */
    4386         846 :                 if (!bms_is_member(attnum, matched_info->keys))
    4387         120 :                     continue;
    4388             : 
    4389         726 :                 attnum = attnum + attnum_offset;
    4390             : 
    4391             :                 /* ensure sufficient offset */
    4392             :                 Assert(AttrNumberIsForUserDefinedAttr(attnum));
    4393             : 
    4394         726 :                 matched = bms_add_member(matched, attnum);
    4395             : 
    4396         726 :                 found = true;
    4397             :             }
    4398             : 
    4399             :             /*
    4400             :              * XXX Maybe we should allow searching the expressions even if we
    4401             :              * found an attribute matching the expression? That would handle
    4402             :              * trivial expressions like "(a)" but it seems fairly useless.
    4403             :              */
    4404         912 :             if (found)
    4405         726 :                 continue;
    4406             : 
    4407             :             /* expression - see if it's in the statistics object */
    4408         186 :             idx = 0;
    4409         306 :             foreach(lc3, matched_info->exprs)
    4410             :             {
    4411         276 :                 Node       *expr = (Node *) lfirst(lc3);
    4412             : 
    4413         276 :                 if (equal(varinfo->var, expr))
    4414             :                 {
    4415         156 :                     AttrNumber  attnum = -(idx + 1);
    4416             : 
    4417         156 :                     attnum = attnum + attnum_offset;
    4418             : 
    4419             :                     /* ensure sufficient offset */
    4420             :                     Assert(AttrNumberIsForUserDefinedAttr(attnum));
    4421             : 
    4422         156 :                     matched = bms_add_member(matched, attnum);
    4423             : 
    4424             :                     /* there should be just one matching expression */
    4425         156 :                     break;
    4426             :                 }
    4427             : 
    4428         120 :                 idx++;
    4429             :             }
    4430             :         }
    4431             : 
    4432             :         /* Find the specific item that exactly matches the combination */
    4433         852 :         for (i = 0; i < stats->nitems; i++)
    4434             :         {
    4435             :             int         j;
    4436         852 :             MVNDistinctItem *tmpitem = &stats->items[i];
    4437             : 
    4438         852 :             if (tmpitem->nattributes != bms_num_members(matched))
    4439         162 :                 continue;
    4440             : 
    4441             :             /* assume it's the right item */
    4442         690 :             item = tmpitem;
    4443             : 
    4444             :             /* check that all item attributes/expressions fit the match */
    4445        1656 :             for (j = 0; j < tmpitem->nattributes; j++)
    4446             :             {
    4447        1242 :                 AttrNumber  attnum = tmpitem->attributes[j];
    4448             : 
    4449             :                 /*
    4450             :                  * Thanks to how we constructed the matched bitmap above, we
    4451             :                  * can just offset all attnums the same way.
    4452             :                  */
    4453        1242 :                 attnum = attnum + attnum_offset;
    4454             : 
    4455        1242 :                 if (!bms_is_member(attnum, matched))
    4456             :                 {
    4457             :                     /* nah, it's not this item */
    4458         276 :                     item = NULL;
    4459         276 :                     break;
    4460             :                 }
    4461             :             }
    4462             : 
    4463             :             /*
    4464             :              * If the item has all the matched attributes, we know it's the
    4465             :              * right one - there can't be a better one. matching more.
    4466             :              */
    4467         690 :             if (item)
    4468         414 :                 break;
    4469             :         }
    4470             : 
    4471             :         /*
    4472             :          * Make sure we found an item. There has to be one, because ndistinct
    4473             :          * statistics includes all combinations of attributes.
    4474             :          */
    4475         414 :         if (!item)
    4476           0 :             elog(ERROR, "corrupt MVNDistinct entry");
    4477             : 
    4478             :         /* Form the output varinfo list, keeping only unmatched ones */
    4479        1452 :         foreach(lc, *varinfos)
    4480             :         {
    4481        1038 :             GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
    4482             :             ListCell   *lc3;
    4483        1038 :             bool        found = false;
    4484             : 
    4485             :             /*
    4486             :              * Let's look at plain variables first, because it's the most
    4487             :              * common case and the check is quite cheap. We can simply get the
    4488             :              * attnum and check (with an offset) matched bitmap.
    4489             :              */
    4490        1038 :             if (IsA(varinfo->var, Var))
    4491         846 :             {
    4492         852 :                 AttrNumber  attnum = ((Var *) varinfo->var)->varattno;
    4493             : 
    4494             :                 /*
    4495             :                  * If it's a system attribute, we're done. We don't support
    4496             :                  * extended statistics on system attributes, so it's clearly
    4497             :                  * not matched. Just keep the expression and continue.
    4498             :                  */
    4499         852 :                 if (!AttrNumberIsForUserDefinedAttr(attnum))
    4500             :                 {
    4501           6 :                     newlist = lappend(newlist, varinfo);
    4502           6 :                     continue;
    4503             :                 }
    4504             : 
    4505             :                 /* apply the same offset as above */
    4506         846 :                 attnum += attnum_offset;
    4507             : 
    4508             :                 /* if it's not matched, keep the varinfo */
    4509         846 :                 if (!bms_is_member(attnum, matched))
    4510         120 :                     newlist = lappend(newlist, varinfo);
    4511             : 
    4512             :                 /* The rest of the loop deals with complex expressions. */
    4513         846 :                 continue;
    4514             :             }
    4515             : 
    4516             :             /*
    4517             :              * Process complex expressions, not just simple Vars.
    4518             :              *
    4519             :              * First, we search for an exact match of an expression. If we
    4520             :              * find one, we can just discard the whole GroupVarInfo, with all
    4521             :              * the variables we extracted from it.
    4522             :              *
    4523             :              * Otherwise we inspect the individual vars, and try matching it
    4524             :              * to variables in the item.
    4525             :              */
    4526         306 :             foreach(lc3, matched_info->exprs)
    4527             :             {
    4528         276 :                 Node       *expr = (Node *) lfirst(lc3);
    4529             : 
    4530         276 :                 if (equal(varinfo->var, expr))
    4531             :                 {
    4532         156 :                     found = true;
    4533         156 :                     break;
    4534             :                 }
    4535             :             }
    4536             : 
    4537             :             /* found exact match, skip */
    4538         186 :             if (found)
    4539         156 :                 continue;
    4540             : 
    4541          30 :             newlist = lappend(newlist, varinfo);
    4542             :         }
    4543             : 
    4544         414 :         *varinfos = newlist;
    4545         414 :         *ndistinct = item->ndistinct;
    4546         414 :         return true;
    4547             :     }
    4548             : 
    4549           0 :     return false;
    4550             : }
    4551             : 
    4552             : /*
    4553             :  * convert_to_scalar
    4554             :  *    Convert non-NULL values of the indicated types to the comparison
    4555             :  *    scale needed by scalarineqsel().
    4556             :  *    Returns "true" if successful.
    4557             :  *
    4558             :  * XXX this routine is a hack: ideally we should look up the conversion
    4559             :  * subroutines in pg_type.
    4560             :  *
    4561             :  * All numeric datatypes are simply converted to their equivalent
    4562             :  * "double" values.  (NUMERIC values that are outside the range of "double"
    4563             :  * are clamped to +/- HUGE_VAL.)
    4564             :  *
    4565             :  * String datatypes are converted by convert_string_to_scalar(),
    4566             :  * which is explained below.  The reason why this routine deals with
    4567             :  * three values at a time, not just one, is that we need it for strings.
    4568             :  *
    4569             :  * The bytea datatype is just enough different from strings that it has
    4570             :  * to be treated separately.
    4571             :  *
    4572             :  * The several datatypes representing absolute times are all converted
    4573             :  * to Timestamp, which is actually an int64, and then we promote that to
    4574             :  * a double.  Note this will give correct results even for the "special"
    4575             :  * values of Timestamp, since those are chosen to compare correctly;
    4576             :  * see timestamp_cmp.
    4577             :  *
    4578             :  * The several datatypes representing relative times (intervals) are all
    4579             :  * converted to measurements expressed in seconds.
    4580             :  */
    4581             : static bool
    4582       89822 : convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue,
    4583             :                   Datum lobound, Datum hibound, Oid boundstypid,
    4584             :                   double *scaledlobound, double *scaledhibound)
    4585             : {
    4586       89822 :     bool        failure = false;
    4587             : 
    4588             :     /*
    4589             :      * Both the valuetypid and the boundstypid should exactly match the
    4590             :      * declared input type(s) of the operator we are invoked for.  However,
    4591             :      * extensions might try to use scalarineqsel as estimator for operators
    4592             :      * with input type(s) we don't handle here; in such cases, we want to
    4593             :      * return false, not fail.  In any case, we mustn't assume that valuetypid
    4594             :      * and boundstypid are identical.
    4595             :      *
    4596             :      * XXX The histogram we are interpolating between points of could belong
    4597             :      * to a column that's only binary-compatible with the declared type. In
    4598             :      * essence we are assuming that the semantics of binary-compatible types
    4599             :      * are enough alike that we can use a histogram generated with one type's
    4600             :      * operators to estimate selectivity for the other's.  This is outright
    4601             :      * wrong in some cases --- in particular signed versus unsigned
    4602             :      * interpretation could trip us up.  But it's useful enough in the
    4603             :      * majority of cases that we do it anyway.  Should think about more
    4604             :      * rigorous ways to do it.
    4605             :      */
    4606       89822 :     switch (valuetypid)
    4607             :     {
    4608             :             /*
    4609             :              * Built-in numeric types
    4610             :              */
    4611       83014 :         case BOOLOID:
    4612             :         case INT2OID:
    4613             :         case INT4OID:
    4614             :         case INT8OID:
    4615             :         case FLOAT4OID:
    4616             :         case FLOAT8OID:
    4617             :         case NUMERICOID:
    4618             :         case OIDOID:
    4619             :         case REGPROCOID:
    4620             :         case REGPROCEDUREOID:
    4621             :         case REGOPEROID:
    4622             :         case REGOPERATOROID:
    4623             :         case REGCLASSOID:
    4624             :         case REGTYPEOID:
    4625             :         case REGCOLLATIONOID:
    4626             :         case REGCONFIGOID:
    4627             :         case REGDICTIONARYOID:
    4628             :         case REGROLEOID:
    4629             :         case REGNAMESPACEOID:
    4630             :         case REGDATABASEOID:
    4631       83014 :             *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
    4632             :                                                      &failure);
    4633       83014 :             *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
    4634             :                                                        &failure);
    4635       83014 :             *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
    4636             :                                                        &failure);
    4637       83014 :             return !failure;
    4638             : 
    4639             :             /*
    4640             :              * Built-in string types
    4641             :              */
    4642        6808 :         case CHAROID:
    4643             :         case BPCHAROID:
    4644             :         case VARCHAROID:
    4645             :         case TEXTOID:
    4646             :         case NAMEOID:
    4647             :             {
    4648        6808 :                 char       *valstr = convert_string_datum(value, valuetypid,
    4649             :                                                           collid, &failure);
    4650        6808 :                 char       *lostr = convert_string_datum(lobound, boundstypid,
    4651             :                                                          collid, &failure);
    4652        6808 :                 char       *histr = convert_string_datum(hibound, boundstypid,
    4653             :                                                          collid, &failure);
    4654             : 
    4655             :                 /*
    4656             :                  * Bail out if any of the values is not of string type.  We
    4657             :                  * might leak converted strings for the other value(s), but
    4658             :                  * that's not worth troubling over.
    4659             :                  */
    4660        6808 :                 if (failure)
    4661           0 :                     return false;
    4662             : 
    4663        6808 :                 convert_string_to_scalar(valstr, scaledvalue,
    4664             :                                          lostr, scaledlobound,
    4665             :                                          histr, scaledhibound);
    4666        6808 :                 pfree(valstr);
    4667        6808 :                 pfree(lostr);
    4668        6808 :                 pfree(histr);
    4669        6808 :                 return true;
    4670             :             }
    4671             : 
    4672             :             /*
    4673             :              * Built-in bytea type
    4674             :              */
    4675           0 :         case BYTEAOID:
    4676             :             {
    4677             :                 /* We only support bytea vs bytea comparison */
    4678           0 :                 if (boundstypid != BYTEAOID)
    4679           0 :                     return false;
    4680           0 :                 convert_bytea_to_scalar(value, scaledvalue,
    4681             :                                         lobound, scaledlobound,
    4682             :                                         hibound, scaledhibound);
    4683           0 :                 return true;
    4684             :             }
    4685             : 
    4686             :             /*
    4687             :              * Built-in time types
    4688             :              */
    4689           0 :         case TIMESTAMPOID:
    4690             :         case TIMESTAMPTZOID:
    4691             :         case DATEOID:
    4692             :         case INTERVALOID:
    4693             :         case TIMEOID:
    4694             :         case TIMETZOID:
    4695           0 :             *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
    4696             :                                                        &failure);
    4697           0 :             *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
    4698             :                                                          &failure);
    4699           0 :             *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
    4700             :                                                          &failure);
    4701           0 :             return !failure;
    4702             : 
    4703             :             /*
    4704             :              * Built-in network types
    4705             :              */
    4706           0 :         case INETOID:
    4707             :         case CIDROID:
    4708             :         case MACADDROID:
    4709             :         case MACADDR8OID:
    4710           0 :             *scaledvalue = convert_network_to_scalar(value, valuetypid,
    4711             :                                                      &failure);
    4712           0 :             *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
    4713             :                                                        &failure);
    4714           0 :             *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
    4715             :                                                        &failure);
    4716           0 :             return !failure;
    4717             :     }
    4718             :     /* Don't know how to convert */
    4719           0 :     *scaledvalue = *scaledlobound = *scaledhibound = 0;
    4720           0 :     return false;
    4721             : }
    4722             : 
    4723             : /*
    4724             :  * Do convert_to_scalar()'s work for any numeric data type.
    4725             :  *
    4726             :  * On failure (e.g., unsupported typid), set *failure to true;
    4727             :  * otherwise, that variable is not changed.
    4728             :  */
    4729             : static double
    4730      249042 : convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
    4731             : {
    4732      249042 :     switch (typid)
    4733             :     {
    4734           0 :         case BOOLOID:
    4735           0 :             return (double) DatumGetBool(value);
    4736          12 :         case INT2OID:
    4737          12 :             return (double) DatumGetInt16(value);
    4738       31422 :         case INT4OID:
    4739       31422 :             return (double) DatumGetInt32(value);
    4740           0 :         case INT8OID:
    4741           0 :             return (double) DatumGetInt64(value);
    4742           0 :         case FLOAT4OID:
    4743           0 :             return (double) DatumGetFloat4(value);
    4744          54 :         case FLOAT8OID:
    4745          54 :             return (double) DatumGetFloat8(value);
    4746           0 :         case NUMERICOID:
    4747             :             /* Note: out-of-range values will be clamped to +-HUGE_VAL */
    4748           0 :             return (double)
    4749           0 :                 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
    4750             :                                                    value));
    4751      217554 :         case OIDOID:
    4752             :         case REGPROCOID:
    4753             :         case REGPROCEDUREOID:
    4754             :         case REGOPEROID:
    4755             :         case REGOPERATOROID:
    4756             :         case REGCLASSOID:
    4757             :         case REGTYPEOID:
    4758             :         case REGCOLLATIONOID:
    4759             :         case REGCONFIGOID:
    4760             :         case REGDICTIONARYOID:
    4761             :         case REGROLEOID:
    4762             :         case REGNAMESPACEOID:
    4763             :         case REGDATABASEOID:
    4764             :             /* we can treat OIDs as integers... */
    4765      217554 :             return (double) DatumGetObjectId(value);
    4766             :     }
    4767             : 
    4768           0 :     *failure = true;
    4769           0 :     return 0;
    4770             : }
    4771             : 
    4772             : /*
    4773             :  * Do convert_to_scalar()'s work for any character-string data type.
    4774             :  *
    4775             :  * String datatypes are converted to a scale that ranges from 0 to 1,
    4776             :  * where we visualize the bytes of the string as fractional digits.
    4777             :  *
    4778             :  * We do not want the base to be 256, however, since that tends to
    4779             :  * generate inflated selectivity estimates; few databases will have
    4780             :  * occurrences of all 256 possible byte values at each position.
    4781             :  * Instead, use the smallest and largest byte values seen in the bounds
    4782             :  * as the estimated range for each byte, after some fudging to deal with
    4783             :  * the fact that we probably aren't going to see the full range that way.
    4784             :  *
    4785             :  * An additional refinement is that we discard any common prefix of the
    4786             :  * three strings before computing the scaled values.  This allows us to
    4787             :  * "zoom in" when we encounter a narrow data range.  An example is a phone
    4788             :  * number database where all the values begin with the same area code.
    4789             :  * (Actually, the bounds will be adjacent histogram-bin-boundary values,
    4790             :  * so this is more likely to happen than you might think.)
    4791             :  */
    4792             : static void
    4793        6808 : convert_string_to_scalar(char *value,
    4794             :                          double *scaledvalue,
    4795             :                          char *lobound,
    4796             :                          double *scaledlobound,
    4797             :                          char *hibound,
    4798             :                          double *scaledhibound)
    4799             : {
    4800             :     int         rangelo,
    4801             :                 rangehi;
    4802             :     char       *sptr;
    4803             : 
    4804        6808 :     rangelo = rangehi = (unsigned char) hibound[0];
    4805       83854 :     for (sptr = lobound; *sptr; sptr++)
    4806             :     {
    4807       77046 :         if (rangelo > (unsigned char) *sptr)
    4808       16198 :             rangelo = (unsigned char) *sptr;
    4809       77046 :         if (rangehi < (unsigned char) *sptr)
    4810        8516 :             rangehi = (unsigned char) *sptr;
    4811             :     }
    4812       79782 :     for (sptr = hibound; *sptr; sptr++)
    4813             :     {
    4814       72974 :         if (rangelo > (unsigned char) *sptr)
    4815         982 :             rangelo = (unsigned char) *sptr;
    4816       72974 :         if (rangehi < (unsigned char) *sptr)
    4817        3390 :             rangehi = (unsigned char) *sptr;
    4818             :     }
    4819             :     /* If range includes any upper-case ASCII chars, make it include all */
    4820        6808 :     if (rangelo <= 'Z' && rangehi >= 'A')
    4821             :     {
    4822        1282 :         if (rangelo > 'A')
    4823         222 :             rangelo = 'A';
    4824        1282 :         if (rangehi < 'Z')
    4825         480 :             rangehi = 'Z';
    4826             :     }
    4827             :     /* Ditto lower-case */
    4828        6808 :     if (rangelo <= 'z' && rangehi >= 'a')
    4829             :     {
    4830        6306 :         if (rangelo > 'a')
    4831          30 :             rangelo = 'a';
    4832        6306 :         if (rangehi < 'z')
    4833        6236 :             rangehi = 'z';
    4834             :     }
    4835             :     /* Ditto digits */
    4836        6808 :     if (rangelo <= '9' && rangehi >= '0')
    4837             :     {
    4838         602 :         if (rangelo > '0')
    4839         496 :             rangelo = '0';
    4840         602 :         if (rangehi < '9')
    4841          14 :             rangehi = '9';
    4842             :     }
    4843             : 
    4844             :     /*
    4845             :      * If range includes less than 10 chars, assume we have not got enough
    4846             :      * data, and make it include regular ASCII set.
    4847             :      */
    4848        6808 :     if (rangehi - rangelo < 9)
    4849             :     {
    4850           0 :         rangelo = ' ';
    4851           0 :         rangehi = 127;
    4852             :     }
    4853             : 
    4854             :     /*
    4855             :      * Now strip any common prefix of the three strings.
    4856             :      */
    4857       14180 :     while (*lobound)
    4858             :     {
    4859       14180 :         if (*lobound != *hibound || *lobound != *value)
    4860             :             break;
    4861        7372 :         lobound++, hibound++, value++;
    4862             :     }
    4863             : 
    4864             :     /*
    4865             :      * Now we can do the conversions.
    4866             :      */
    4867        6808 :     *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
    4868        6808 :     *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
    4869        6808 :     *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
    4870        6808 : }
    4871             : 
    4872             : static double
    4873       20424 : convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
    4874             : {
    4875       20424 :     int         slen = strlen(value);
    4876             :     double      num,
    4877             :                 denom,
    4878             :                 base;
    4879             : 
    4880       20424 :     if (slen <= 0)
    4881           0 :         return 0.0;             /* empty string has scalar value 0 */
    4882             : 
    4883             :     /*
    4884             :      * There seems little point in considering more than a dozen bytes from
    4885             :      * the string.  Since base is at least 10, that will give us nominal
    4886             :      * resolution of at least 12 decimal digits, which is surely far more
    4887             :      * precision than this estimation technique has got anyway (especially in
    4888             :      * non-C locales).  Also, even with the maximum possible base of 256, this
    4889             :      * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
    4890             :      * overflow on any known machine.
    4891             :      */
    4892       20424 :     if (slen > 12)
    4893        5080 :         slen = 12;
    4894             : 
    4895             :     /* Convert initial characters to fraction */
    4896       20424 :     base = rangehi - rangelo + 1;
    4897       20424 :     num = 0.0;
    4898       20424 :     denom = base;
    4899      169302 :     while (slen-- > 0)
    4900             :     {
    4901      148878 :         int         ch = (unsigned char) *value++;
    4902             : 
    4903      148878 :         if (ch < rangelo)
    4904         192 :             ch = rangelo - 1;
    4905      148686 :         else if (ch > rangehi)
    4906           0 :             ch = rangehi + 1;
    4907      148878 :         num += ((double) (ch - rangelo)) / denom;
    4908      148878 :         denom *= base;
    4909             :     }
    4910             : 
    4911       20424 :     return num;
    4912             : }
    4913             : 
    4914             : /*
    4915             :  * Convert a string-type Datum into a palloc'd, null-terminated string.
    4916             :  *
    4917             :  * On failure (e.g., unsupported typid), set *failure to true;
    4918             :  * otherwise, that variable is not changed.  (We'll return NULL on failure.)
    4919             :  *
    4920             :  * When using a non-C locale, we must pass the string through pg_strxfrm()
    4921             :  * before continuing, so as to generate correct locale-specific results.
    4922             :  */
    4923             : static char *
    4924       20424 : convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
    4925             : {
    4926             :     char       *val;
    4927             :     pg_locale_t mylocale;
    4928             : 
    4929       20424 :     switch (typid)
    4930             :     {
    4931           0 :         case CHAROID:
    4932           0 :             val = (char *) palloc(2);
    4933           0 :             val[0] = DatumGetChar(value);
    4934           0 :             val[1] = '\0';
    4935           0 :             break;
    4936        6272 :         case BPCHAROID:
    4937             :         case VARCHAROID:
    4938             :         case TEXTOID:
    4939        6272 :             val = TextDatumGetCString(value);
    4940        6272 :             break;
    4941       14152 :         case NAMEOID:
    4942             :             {
    4943       14152 :                 NameData   *nm = (NameData *) DatumGetPointer(value);
    4944             : 
    4945       14152 :                 val = pstrdup(NameStr(*nm));
    4946       14152 :                 break;
    4947             :             }
    4948           0 :         default:
    4949           0 :             *failure = true;
    4950           0 :             return NULL;
    4951             :     }
    4952             : 
    4953       20424 :     mylocale = pg_newlocale_from_collation(collid);
    4954             : 
    4955       20424 :     if (!mylocale->collate_is_c)
    4956             :     {
    4957             :         char       *xfrmstr;
    4958             :         size_t      xfrmlen;
    4959             :         size_t      xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
    4960             : 
    4961             :         /*
    4962             :          * XXX: We could guess at a suitable output buffer size and only call
    4963             :          * pg_strxfrm() twice if our guess is too small.
    4964             :          *
    4965             :          * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
    4966             :          * bogus data or set an error. This is not really a problem unless it
    4967             :          * crashes since it will only give an estimation error and nothing
    4968             :          * fatal.
    4969             :          *
    4970             :          * XXX: we do not check pg_strxfrm_enabled(). On some platforms and in
    4971             :          * some cases, libc strxfrm() may return the wrong results, but that
    4972             :          * will only lead to an estimation error.
    4973             :          */
    4974          72 :         xfrmlen = pg_strxfrm(NULL, val, 0, mylocale);
    4975             : #ifdef WIN32
    4976             : 
    4977             :         /*
    4978             :          * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
    4979             :          * of trying to allocate this much memory (and fail), just return the
    4980             :          * original string unmodified as if we were in the C locale.
    4981             :          */
    4982             :         if (xfrmlen == INT_MAX)
    4983             :             return val;
    4984             : #endif
    4985          72 :         xfrmstr = (char *) palloc(xfrmlen + 1);
    4986          72 :         xfrmlen2 = pg_strxfrm(xfrmstr, val, xfrmlen + 1, mylocale);
    4987             : 
    4988             :         /*
    4989             :          * Some systems (e.g., glibc) can return a smaller value from the
    4990             :          * second call than the first; thus the Assert must be <= not ==.
    4991             :          */
    4992             :         Assert(xfrmlen2 <= xfrmlen);
    4993          72 :         pfree(val);
    4994          72 :         val = xfrmstr;
    4995             :     }
    4996             : 
    4997       20424 :     return val;
    4998             : }
    4999             : 
    5000             : /*
    5001             :  * Do convert_to_scalar()'s work for any bytea data type.
    5002             :  *
    5003             :  * Very similar to convert_string_to_scalar except we can't assume
    5004             :  * null-termination and therefore pass explicit lengths around.
    5005             :  *
    5006             :  * Also, assumptions about likely "normal" ranges of characters have been
    5007             :  * removed - a data range of 0..255 is always used, for now.  (Perhaps
    5008             :  * someday we will add information about actual byte data range to
    5009             :  * pg_statistic.)
    5010             :  */
    5011             : static void
    5012           0 : convert_bytea_to_scalar(Datum value,
    5013             :                         double *scaledvalue,
    5014             :                         Datum lobound,
    5015             :                         double *scaledlobound,
    5016             :                         Datum hibound,
    5017             :                         double *scaledhibound)
    5018             : {
    5019           0 :     bytea      *valuep = DatumGetByteaPP(value);
    5020           0 :     bytea      *loboundp = DatumGetByteaPP(lobound);
    5021           0 :     bytea      *hiboundp = DatumGetByteaPP(hibound);
    5022             :     int         rangelo,
    5023             :                 rangehi,
    5024           0 :                 valuelen = VARSIZE_ANY_EXHDR(valuep),
    5025           0 :                 loboundlen = VARSIZE_ANY_EXHDR(loboundp),
    5026           0 :                 hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
    5027             :                 i,
    5028             :                 minlen;
    5029           0 :     unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
    5030           0 :     unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
    5031           0 :     unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
    5032             : 
    5033             :     /*
    5034             :      * Assume bytea data is uniformly distributed across all byte values.
    5035             :      */
    5036           0 :     rangelo = 0;
    5037           0 :     rangehi = 255;
    5038             : 
    5039             :     /*
    5040             :      * Now strip any common prefix of the three strings.
    5041             :      */
    5042           0 :     minlen = Min(Min(valuelen, loboundlen), hiboundlen);
    5043           0 :     for (i = 0; i < minlen; i++)
    5044             :     {
    5045           0 :         if (*lostr != *histr || *lostr != *valstr)
    5046             :             break;
    5047           0 :         lostr++, histr++, valstr++;
    5048           0 :         loboundlen--, hiboundlen--, valuelen--;
    5049             :     }
    5050             : 
    5051             :     /*
    5052             :      * Now we can do the conversions.
    5053             :      */
    5054           0 :     *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
    5055           0 :     *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
    5056           0 :     *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
    5057           0 : }
    5058             : 
    5059             : static double
    5060           0 : convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
    5061             :                             int rangelo, int rangehi)
    5062             : {
    5063             :     double      num,
    5064             :                 denom,
    5065             :                 base;
    5066             : 
    5067           0 :     if (valuelen <= 0)
    5068           0 :         return 0.0;             /* empty string has scalar value 0 */
    5069             : 
    5070             :     /*
    5071             :      * Since base is 256, need not consider more than about 10 chars (even
    5072             :      * this many seems like overkill)
    5073             :      */
    5074           0 :     if (valuelen > 10)
    5075           0 :         valuelen = 10;
    5076             : 
    5077             :     /* Convert initial characters to fraction */
    5078           0 :     base = rangehi - rangelo + 1;
    5079           0 :     num = 0.0;
    5080           0 :     denom = base;
    5081           0 :     while (valuelen-- > 0)
    5082             :     {
    5083           0 :         int         ch = *value++;
    5084             : 
    5085           0 :         if (ch < rangelo)
    5086           0 :             ch = rangelo - 1;
    5087           0 :         else if (ch > rangehi)
    5088           0 :             ch = rangehi + 1;
    5089           0 :         num += ((double) (ch - rangelo)) / denom;
    5090           0 :         denom *= base;
    5091             :     }
    5092             : 
    5093           0 :     return num;
    5094             : }
    5095             : 
    5096             : /*
    5097             :  * Do convert_to_scalar()'s work for any timevalue data type.
    5098             :  *
    5099             :  * On failure (e.g., unsupported typid), set *failure to true;
    5100             :  * otherwise, that variable is not changed.
    5101             :  */
    5102             : static double
    5103           0 : convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
    5104             : {
    5105           0 :     switch (typid)
    5106             :     {
    5107           0 :         case TIMESTAMPOID:
    5108           0 :             return DatumGetTimestamp(value);
    5109           0 :         case TIMESTAMPTZOID:
    5110           0 :             return DatumGetTimestampTz(value);
    5111           0 :         case DATEOID:
    5112           0 :             return date2timestamp_no_overflow(DatumGetDateADT(value));
    5113           0 :         case INTERVALOID:
    5114             :             {
    5115           0 :                 Interval   *interval = DatumGetIntervalP(value);
    5116             : 
    5117             :                 /*
    5118             :                  * Convert the month part of Interval to days using assumed
    5119             :                  * average month length of 365.25/12.0 days.  Not too
    5120             :                  * accurate, but plenty good enough for our purposes.
    5121             :                  *
    5122             :                  * This also works for infinite intervals, which just have all
    5123             :                  * fields set to INT_MIN/INT_MAX, and so will produce a result
    5124             :                  * smaller/larger than any finite interval.
    5125             :                  */
    5126           0 :                 return interval->time + interval->day * (double) USECS_PER_DAY +
    5127           0 :                     interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
    5128             :             }
    5129           0 :         case TIMEOID:
    5130           0 :             return DatumGetTimeADT(value);
    5131           0 :         case TIMETZOID:
    5132             :             {
    5133           0 :                 TimeTzADT  *timetz = DatumGetTimeTzADTP(value);
    5134             : 
    5135             :                 /* use GMT-equivalent time */
    5136           0 :                 return (double) (timetz->time + (timetz->zone * 1000000.0));
    5137             :             }
    5138             :     }
    5139             : 
    5140           0 :     *failure = true;
    5141           0 :     return 0;
    5142             : }
    5143             : 
    5144             : 
    5145             : /*
    5146             :  * get_restriction_variable
    5147             :  *      Examine the args of a restriction clause to see if it's of the
    5148             :  *      form (variable op pseudoconstant) or (pseudoconstant op variable),
    5149             :  *      where "variable" could be either a Var or an expression in vars of a
    5150             :  *      single relation.  If so, extract information about the variable,
    5151             :  *      and also indicate which side it was on and the other argument.
    5152             :  *
    5153             :  * Inputs:
    5154             :  *  root: the planner info
    5155             :  *  args: clause argument list
    5156             :  *  varRelid: see specs for restriction selectivity functions
    5157             :  *
    5158             :  * Outputs: (these are valid only if true is returned)
    5159             :  *  *vardata: gets information about variable (see examine_variable)
    5160             :  *  *other: gets other clause argument, aggressively reduced to a constant
    5161             :  *  *varonleft: set true if variable is on the left, false if on the right
    5162             :  *
    5163             :  * Returns true if a variable is identified, otherwise false.
    5164             :  *
    5165             :  * Note: if there are Vars on both sides of the clause, we must fail, because
    5166             :  * callers are expecting that the other side will act like a pseudoconstant.
    5167             :  */
    5168             : bool
    5169      742226 : get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
    5170             :                          VariableStatData *vardata, Node **other,
    5171             :                          bool *varonleft)
    5172             : {
    5173             :     Node       *left,
    5174             :                *right;
    5175             :     VariableStatData rdata;
    5176             : 
    5177             :     /* Fail if not a binary opclause (probably shouldn't happen) */
    5178      742226 :     if (list_length(args) != 2)
    5179           0 :         return false;
    5180             : 
    5181      742226 :     left = (Node *) linitial(args);
    5182      742226 :     right = (Node *) lsecond(args);
    5183             : 
    5184             :     /*
    5185             :      * Examine both sides.  Note that when varRelid is nonzero, Vars of other
    5186             :      * relations will be treated as pseudoconstants.
    5187             :      */
    5188      742226 :     examine_variable(root, left, varRelid, vardata);
    5189      742226 :     examine_variable(root, right, varRelid, &rdata);
    5190             : 
    5191             :     /*
    5192             :      * If one side is a variable and the other not, we win.
    5193             :      */
    5194      742226 :     if (vardata->rel && rdata.rel == NULL)
    5195             :     {
    5196      667636 :         *varonleft = true;
    5197      667636 :         *other = estimate_expression_value(root, rdata.var);
    5198             :         /* Assume we need no ReleaseVariableStats(rdata) here */
    5199      667630 :         return true;
    5200             :     }
    5201             : 
    5202       74590 :     if (vardata->rel == NULL && rdata.rel)
    5203             :     {
    5204       68336 :         *varonleft = false;
    5205       68336 :         *other = estimate_expression_value(root, vardata->var);
    5206             :         /* Assume we need no ReleaseVariableStats(*vardata) here */
    5207       68336 :         *vardata = rdata;
    5208       68336 :         return true;
    5209             :     }
    5210             : 
    5211             :     /* Oops, clause has wrong structure (probably var op var) */
    5212        6254 :     ReleaseVariableStats(*vardata);
    5213        6254 :     ReleaseVariableStats(rdata);
    5214             : 
    5215        6254 :     return false;
    5216             : }
    5217             : 
    5218             : /*
    5219             :  * get_join_variables
    5220             :  *      Apply examine_variable() to each side of a join clause.
    5221             :  *      Also, attempt to identify whether the join clause has the same
    5222             :  *      or reversed sense compared to the SpecialJoinInfo.
    5223             :  *
    5224             :  * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
    5225             :  * or "reversed" if it is "rhs_var OP lhs_var".  In complicated cases
    5226             :  * where we can't tell for sure, we default to assuming it's normal.
    5227             :  */
    5228             : void
    5229      227362 : get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
    5230             :                    VariableStatData *vardata1, VariableStatData *vardata2,
    5231             :                    bool *join_is_reversed)
    5232             : {
    5233             :     Node       *left,
    5234             :                *right;
    5235             : 
    5236      227362 :     if (list_length(args) != 2)
    5237           0 :         elog(ERROR, "join operator should take two arguments");
    5238             : 
    5239      227362 :     left = (Node *) linitial(args);
    5240      227362 :     right = (Node *) lsecond(args);
    5241             : 
    5242      227362 :     examine_variable(root, left, 0, vardata1);
    5243      227362 :     examine_variable(root, right, 0, vardata2);
    5244             : 
    5245      454546 :     if (vardata1->rel &&
    5246      227184 :         bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
    5247       84342 :         *join_is_reversed = true;   /* var1 is on RHS */
    5248      285898 :     else if (vardata2->rel &&
    5249      142878 :              bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
    5250         132 :         *join_is_reversed = true;   /* var2 is on LHS */
    5251             :     else
    5252      142888 :         *join_is_reversed = false;
    5253      227362 : }
    5254             : 
    5255             : /* statext_expressions_load copies the tuple, so just pfree it. */
    5256             : static void
    5257        1644 : ReleaseDummy(HeapTuple tuple)
    5258             : {
    5259        1644 :     pfree(tuple);
    5260        1644 : }
    5261             : 
    5262             : /*
    5263             :  * examine_variable
    5264             :  *      Try to look up statistical data about an expression.
    5265             :  *      Fill in a VariableStatData struct to describe the expression.
    5266             :  *
    5267             :  * Inputs:
    5268             :  *  root: the planner info
    5269             :  *  node: the expression tree to examine
    5270             :  *  varRelid: see specs for restriction selectivity functions
    5271             :  *
    5272             :  * Outputs: *vardata is filled as follows:
    5273             :  *  var: the input expression (with any binary relabeling stripped, if
    5274             :  *      it is or contains a variable; but otherwise the type is preserved)
    5275             :  *  rel: RelOptInfo for relation containing variable; NULL if expression
    5276             :  *      contains no Vars (NOTE this could point to a RelOptInfo of a
    5277             :  *      subquery, not one in the current query).
    5278             :  *  statsTuple: the pg_statistic entry for the variable, if one exists;
    5279             :  *      otherwise NULL.
    5280             :  *  freefunc: pointer to a function to release statsTuple with.
    5281             :  *  vartype: exposed type of the expression; this should always match
    5282             :  *      the declared input type of the operator we are estimating for.
    5283             :  *  atttype, atttypmod: actual type/typmod of the "var" expression.  This is
    5284             :  *      commonly the same as the exposed type of the variable argument,
    5285             :  *      but can be different in binary-compatible-type cases.
    5286             :  *  isunique: true if we were able to match the var to a unique index, a
    5287             :  *      single-column DISTINCT or GROUP-BY clause, implying its values are
    5288             :  *      unique for this query.  (Caution: this should be trusted for
    5289             :  *      statistical purposes only, since we do not check indimmediate nor
    5290             :  *      verify that the exact same definition of equality applies.)
    5291             :  *  acl_ok: true if current user has permission to read the column(s)
    5292             :  *      underlying the pg_statistic entry.  This is consulted by
    5293             :  *      statistic_proc_security_check().
    5294             :  *
    5295             :  * Caller is responsible for doing ReleaseVariableStats() before exiting.
    5296             :  */
    5297             : void
    5298     2893624 : examine_variable(PlannerInfo *root, Node *node, int varRelid,
    5299             :                  VariableStatData *vardata)
    5300             : {
    5301             :     Node       *basenode;
    5302             :     Relids      varnos;
    5303             :     Relids      basevarnos;
    5304             :     RelOptInfo *onerel;
    5305             : 
    5306             :     /* Make sure we don't return dangling pointers in vardata */
    5307    20255368 :     MemSet(vardata, 0, sizeof(VariableStatData));
    5308             : 
    5309             :     /* Save the exposed type of the expression */
    5310     2893624 :     vardata->vartype = exprType(node);
    5311             : 
    5312             :     /* Look inside any binary-compatible relabeling */
    5313             : 
    5314     2893624 :     if (IsA(node, RelabelType))
    5315       40896 :         basenode = (Node *) ((RelabelType *) node)->arg;
    5316             :     else
    5317     2852728 :         basenode = node;
    5318             : 
    5319             :     /* Fast path for a simple Var */
    5320             : 
    5321     2893624 :     if (IsA(basenode, Var) &&
    5322      671620 :         (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
    5323             :     {
    5324     2052616 :         Var        *var = (Var *) basenode;
    5325             : 
    5326             :         /* Set up result fields other than the stats tuple */
    5327     2052616 :         vardata->var = basenode; /* return Var without relabeling */
    5328     2052616 :         vardata->rel = find_base_rel(root, var->varno);
    5329     2052616 :         vardata->atttype = var->vartype;
    5330     2052616 :         vardata->atttypmod = var->vartypmod;
    5331     2052616 :         vardata->isunique = has_unique_index(vardata->rel, var->varattno);
    5332             : 
    5333             :         /* Try to locate some stats */
    5334     2052616 :         examine_simple_variable(root, var, vardata);
    5335             : 
    5336     2052616 :         return;
    5337             :     }
    5338             : 
    5339             :     /*
    5340             :      * Okay, it's a more complicated expression.  Determine variable
    5341             :      * membership.  Note that when varRelid isn't zero, only vars of that
    5342             :      * relation are considered "real" vars.
    5343             :      */
    5344      841008 :     varnos = pull_varnos(root, basenode);
    5345      841008 :     basevarnos = bms_difference(varnos, root->outer_join_rels);
    5346             : 
    5347      841008 :     onerel = NULL;
    5348             : 
    5349      841008 :     if (bms_is_empty(basevarnos))
    5350             :     {
    5351             :         /* No Vars at all ... must be pseudo-constant clause */
    5352             :     }
    5353             :     else
    5354             :     {
    5355             :         int         relid;
    5356             : 
    5357             :         /* Check if the expression is in vars of a single base relation */
    5358      400236 :         if (bms_get_singleton_member(basevarnos, &relid))
    5359             :         {
    5360      396054 :             if (varRelid == 0 || varRelid == relid)
    5361             :             {
    5362       58966 :                 onerel = find_base_rel(root, relid);
    5363       58966 :                 vardata->rel = onerel;
    5364       58966 :                 node = basenode;    /* strip any relabeling */
    5365             :             }
    5366             :             /* else treat it as a constant */
    5367             :         }
    5368             :         else
    5369             :         {
    5370             :             /* varnos has multiple relids */
    5371        4182 :             if (varRelid == 0)
    5372             :             {
    5373             :                 /* treat it as a variable of a join relation */
    5374        3842 :                 vardata->rel = find_join_rel(root, varnos);
    5375        3842 :                 node = basenode;    /* strip any relabeling */
    5376             :             }
    5377         340 :             else if (bms_is_member(varRelid, varnos))
    5378             :             {
    5379             :                 /* ignore the vars belonging to other relations */
    5380         166 :                 vardata->rel = find_base_rel(root, varRelid);
    5381         166 :                 node = basenode;    /* strip any relabeling */
    5382             :                 /* note: no point in expressional-index search here */
    5383             :             }
    5384             :             /* else treat it as a constant */
    5385             :         }
    5386             :     }
    5387             : 
    5388      841008 :     bms_free(basevarnos);
    5389             : 
    5390      841008 :     vardata->var = node;
    5391      841008 :     vardata->atttype = exprType(node);
    5392      841008 :     vardata->atttypmod = exprTypmod(node);
    5393             : 
    5394      841008 :     if (onerel)
    5395             :     {
    5396             :         /*
    5397             :          * We have an expression in vars of a single relation.  Try to match
    5398             :          * it to expressional index columns, in hopes of finding some
    5399             :          * statistics.
    5400             :          *
    5401             :          * Note that we consider all index columns including INCLUDE columns,
    5402             :          * since there could be stats for such columns.  But the test for
    5403             :          * uniqueness needs to be warier.
    5404             :          *
    5405             :          * XXX it's conceivable that there are multiple matches with different
    5406             :          * index opfamilies; if so, we need to pick one that matches the
    5407             :          * operator we are estimating for.  FIXME later.
    5408             :          */
    5409             :         ListCell   *ilist;
    5410             :         ListCell   *slist;
    5411             :         Oid         userid;
    5412             : 
    5413             :         /*
    5414             :          * The nullingrels bits within the expression could prevent us from
    5415             :          * matching it to expressional index columns or to the expressions in
    5416             :          * extended statistics.  So strip them out first.
    5417             :          */
    5418       58966 :         if (bms_overlap(varnos, root->outer_join_rels))
    5419        3052 :             node = remove_nulling_relids(node, root->outer_join_rels, NULL);
    5420             : 
    5421             :         /*
    5422             :          * Determine the user ID to use for privilege checks: either
    5423             :          * onerel->userid if it's set (e.g., in case we're accessing the table
    5424             :          * via a view), or the current user otherwise.
    5425             :          *
    5426             :          * If we drill down to child relations, we keep using the same userid:
    5427             :          * it's going to be the same anyway, due to how we set up the relation
    5428             :          * tree (q.v. build_simple_rel).
    5429             :          */
    5430       58966 :         userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
    5431             : 
    5432      118402 :         foreach(ilist, onerel->indexlist)
    5433             :         {
    5434       62250 :             IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
    5435             :             ListCell   *indexpr_item;
    5436             :             int         pos;
    5437             : 
    5438       62250 :             indexpr_item = list_head(index->indexprs);
    5439       62250 :             if (indexpr_item == NULL)
    5440       57504 :                 continue;       /* no expressions here... */
    5441             : 
    5442        6750 :             for (pos = 0; pos < index->ncolumns; pos++)
    5443             :             {
    5444        4818 :                 if (index->indexkeys[pos] == 0)
    5445             :                 {
    5446             :                     Node       *indexkey;
    5447             : 
    5448        4746 :                     if (indexpr_item == NULL)
    5449           0 :                         elog(ERROR, "too few entries in indexprs list");
    5450        4746 :                     indexkey = (Node *) lfirst(indexpr_item);
    5451        4746 :                     if (indexkey && IsA(indexkey, RelabelType))
    5452           0 :                         indexkey = (Node *) ((RelabelType *) indexkey)->arg;
    5453        4746 :                     if (equal(node, indexkey))
    5454             :                     {
    5455             :                         /*
    5456             :                          * Found a match ... is it a unique index? Tests here
    5457             :                          * should match has_unique_index().
    5458             :                          */
    5459        3450 :                         if (index->unique &&
    5460         438 :                             index->nkeycolumns == 1 &&
    5461         438 :                             pos == 0 &&
    5462         438 :                             (index->indpred == NIL || index->predOK))
    5463         438 :                             vardata->isunique = true;
    5464             : 
    5465             :                         /*
    5466             :                          * Has it got stats?  We only consider stats for
    5467             :                          * non-partial indexes, since partial indexes probably
    5468             :                          * don't reflect whole-relation statistics; the above
    5469             :                          * check for uniqueness is the only info we take from
    5470             :                          * a partial index.
    5471             :                          *
    5472             :                          * An index stats hook, however, must make its own
    5473             :                          * decisions about what to do with partial indexes.
    5474             :                          */
    5475        3450 :                         if (get_index_stats_hook &&
    5476           0 :                             (*get_index_stats_hook) (root, index->indexoid,
    5477           0 :                                                      pos + 1, vardata))
    5478             :                         {
    5479             :                             /*
    5480             :                              * The hook took control of acquiring a stats
    5481             :                              * tuple.  If it did supply a tuple, it'd better
    5482             :                              * have supplied a freefunc.
    5483             :                              */
    5484           0 :                             if (HeapTupleIsValid(vardata->statsTuple) &&
    5485           0 :                                 !vardata->freefunc)
    5486           0 :                                 elog(ERROR, "no function provided to release variable stats with");
    5487             :                         }
    5488        3450 :                         else if (index->indpred == NIL)
    5489             :                         {
    5490        3450 :                             vardata->statsTuple =
    5491        6900 :                                 SearchSysCache3(STATRELATTINH,
    5492             :                                                 ObjectIdGetDatum(index->indexoid),
    5493        3450 :                                                 Int16GetDatum(pos + 1),
    5494             :                                                 BoolGetDatum(false));
    5495        3450 :                             vardata->freefunc = ReleaseSysCache;
    5496             : 
    5497        3450 :                             if (HeapTupleIsValid(vardata->statsTuple))
    5498             :                             {
    5499             :                                 /* Get index's table for permission check */
    5500             :                                 RangeTblEntry *rte;
    5501             : 
    5502        2814 :                                 rte = planner_rt_fetch(index->rel->relid, root);
    5503             :                                 Assert(rte->rtekind == RTE_RELATION);
    5504             : 
    5505             :                                 /*
    5506             :                                  * For simplicity, we insist on the whole
    5507             :                                  * table being selectable, rather than trying
    5508             :                                  * to identify which column(s) the index
    5509             :                                  * depends on.  Also require all rows to be
    5510             :                                  * selectable --- there must be no
    5511             :                                  * securityQuals from security barrier views
    5512             :                                  * or RLS policies.
    5513             :                                  */
    5514        2814 :                                 vardata->acl_ok =
    5515        5628 :                                     rte->securityQuals == NIL &&
    5516        2814 :                                     (pg_class_aclcheck(rte->relid, userid,
    5517             :                                                        ACL_SELECT) == ACLCHECK_OK);
    5518             : 
    5519             :                                 /*
    5520             :                                  * If the user doesn't have permissions to
    5521             :                                  * access an inheritance child relation, check
    5522             :                                  * the permissions of the table actually
    5523             :                                  * mentioned in the query, since most likely
    5524             :                                  * the user does have that permission.  Note
    5525             :                                  * that whole-table select privilege on the
    5526             :                                  * parent doesn't quite guarantee that the
    5527             :                                  * user could read all columns of the child.
    5528             :                                  * But in practice it's unlikely that any
    5529             :                                  * interesting security violation could result
    5530             :                                  * from allowing access to the expression
    5531             :                                  * index's stats, so we allow it anyway.  See
    5532             :                                  * similar code in examine_simple_variable()
    5533             :                                  * for additional comments.
    5534             :                                  */
    5535        2814 :                                 if (!vardata->acl_ok &&
    5536          18 :                                     root->append_rel_array != NULL)
    5537             :                                 {
    5538             :                                     AppendRelInfo *appinfo;
    5539          12 :                                     Index       varno = index->rel->relid;
    5540             : 
    5541          12 :                                     appinfo = root->append_rel_array[varno];
    5542          36 :                                     while (appinfo &&
    5543          24 :                                            planner_rt_fetch(appinfo->parent_relid,
    5544          24 :                                                             root)->rtekind == RTE_RELATION)
    5545             :                                     {
    5546          24 :                                         varno = appinfo->parent_relid;
    5547          24 :                                         appinfo = root->append_rel_array[varno];
    5548             :                                     }
    5549          12 :                                     if (varno != index->rel->relid)
    5550             :                                     {
    5551             :                                         /* Repeat access check on this rel */
    5552          12 :                                         rte = planner_rt_fetch(varno, root);
    5553             :                                         Assert(rte->rtekind == RTE_RELATION);
    5554             : 
    5555          12 :                                         vardata->acl_ok =
    5556          24 :                                             rte->securityQuals == NIL &&
    5557          12 :                                             (pg_class_aclcheck(rte->relid,
    5558             :                                                                userid,
    5559             :                                                                ACL_SELECT) == ACLCHECK_OK);
    5560             :                                     }
    5561             :                                 }
    5562             :                             }
    5563             :                             else
    5564             :                             {
    5565             :                                 /* suppress leakproofness checks later */
    5566         636 :                                 vardata->acl_ok = true;
    5567             :                             }
    5568             :                         }
    5569        3450 :                         if (vardata->statsTuple)
    5570        2814 :                             break;
    5571             :                     }
    5572        1932 :                     indexpr_item = lnext(index->indexprs, indexpr_item);
    5573             :                 }
    5574             :             }
    5575        4746 :             if (vardata->statsTuple)
    5576        2814 :                 break;
    5577             :         }
    5578             : 
    5579             :         /*
    5580             :          * Search extended statistics for one with a matching expression.
    5581             :          * There might be multiple ones, so just grab the first one. In the
    5582             :          * future, we might consider the statistics target (and pick the most
    5583             :          * accurate statistics) and maybe some other parameters.
    5584             :          */
    5585       62992 :         foreach(slist, onerel->statlist)
    5586             :         {
    5587        4314 :             StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
    5588        4314 :             RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
    5589             :             ListCell   *expr_item;
    5590             :             int         pos;
    5591             : 
    5592             :             /*
    5593             :              * Stop once we've found statistics for the expression (either
    5594             :              * from extended stats, or for an index in the preceding loop).
    5595             :              */
    5596        4314 :             if (vardata->statsTuple)
    5597         288 :                 break;
    5598             : 
    5599             :             /* skip stats without per-expression stats */
    5600        4026 :             if (info->kind != STATS_EXT_EXPRESSIONS)
    5601        2022 :                 continue;
    5602             : 
    5603             :             /* skip stats with mismatching stxdinherit value */
    5604        2004 :             if (info->inherit != rte->inh)
    5605           6 :                 continue;
    5606             : 
    5607        1998 :             pos = 0;
    5608        3300 :             foreach(expr_item, info->exprs)
    5609             :             {
    5610        2946 :                 Node       *expr = (Node *) lfirst(expr_item);
    5611             : 
    5612             :                 Assert(expr);
    5613             : 
    5614             :                 /* strip RelabelType before comparing it */
    5615        2946 :                 if (expr && IsA(expr, RelabelType))
    5616           0 :                     expr = (Node *) ((RelabelType *) expr)->arg;
    5617             : 
    5618             :                 /* found a match, see if we can extract pg_statistic row */
    5619        2946 :                 if (equal(node, expr))
    5620             :                 {
    5621             :                     /*
    5622             :                      * XXX Not sure if we should cache the tuple somewhere.
    5623             :                      * Now we just create a new copy every time.
    5624             :                      */
    5625        1644 :                     vardata->statsTuple =
    5626        1644 :                         statext_expressions_load(info->statOid, rte->inh, pos);
    5627             : 
    5628        1644 :                     vardata->freefunc = ReleaseDummy;
    5629             : 
    5630             :                     /*
    5631             :                      * For simplicity, we insist on the whole table being
    5632             :                      * selectable, rather than trying to identify which
    5633             :                      * column(s) the statistics object depends on.  Also
    5634             :                      * require all rows to be selectable --- there must be no
    5635             :                      * securityQuals from security barrier views or RLS
    5636             :                      * policies.
    5637             :                      */
    5638        1644 :                     vardata->acl_ok =
    5639        3288 :                         rte->securityQuals == NIL &&
    5640        1644 :                         (pg_class_aclcheck(rte->relid, userid,
    5641             :                                            ACL_SELECT) == ACLCHECK_OK);
    5642             : 
    5643             :                     /*
    5644             :                      * If the user doesn't have permissions to access an
    5645             :                      * inheritance child relation, check the permissions of
    5646             :                      * the table actually mentioned in the query, since most
    5647             :                      * likely the user does have that permission.  Note that
    5648             :                      * whole-table select privilege on the parent doesn't
    5649             :                      * quite guarantee that the user could read all columns of
    5650             :                      * the child. But in practice it's unlikely that any
    5651             :                      * interesting security violation could result from
    5652             :                      * allowing access to the expression stats, so we allow it
    5653             :                      * anyway.  See similar code in examine_simple_variable()
    5654             :                      * for additional comments.
    5655             :                      */
    5656        1644 :                     if (!vardata->acl_ok &&
    5657           0 :                         root->append_rel_array != NULL)
    5658             :                     {
    5659             :                         AppendRelInfo *appinfo;
    5660           0 :                         Index       varno = onerel->relid;
    5661             : 
    5662           0 :                         appinfo = root->append_rel_array[varno];
    5663           0 :                         while (appinfo &&
    5664           0 :                                planner_rt_fetch(appinfo->parent_relid,
    5665           0 :                                                 root)->rtekind == RTE_RELATION)
    5666             :                         {
    5667           0 :                             varno = appinfo->parent_relid;
    5668           0 :                             appinfo = root->append_rel_array[varno];
    5669             :                         }
    5670           0 :                         if (varno != onerel->relid)
    5671             :                         {
    5672             :                             /* Repeat access check on this rel */
    5673           0 :                             rte = planner_rt_fetch(varno, root);
    5674             :                             Assert(rte->rtekind == RTE_RELATION);
    5675             : 
    5676           0 :                             vardata->acl_ok =
    5677           0 :                                 rte->securityQuals == NIL &&
    5678           0 :                                 (pg_class_aclcheck(rte->relid,
    5679             :                                                    userid,
    5680             :                                                    ACL_SELECT) == ACLCHECK_OK);
    5681             :                         }
    5682             :                     }
    5683             : 
    5684        1644 :                     break;
    5685             :                 }
    5686             : 
    5687        1302 :                 pos++;
    5688             :             }
    5689             :         }
    5690             :     }
    5691             : 
    5692      841008 :     bms_free(varnos);
    5693             : }
    5694             : 
    5695             : /*
    5696             :  * examine_simple_variable
    5697             :  *      Handle a simple Var for examine_variable
    5698             :  *
    5699             :  * This is split out as a subroutine so that we can recurse to deal with
    5700             :  * Vars referencing subqueries (either sub-SELECT-in-FROM or CTE style).
    5701             :  *
    5702             :  * We already filled in all the fields of *vardata except for the stats tuple.
    5703             :  */
    5704             : static void
    5705     2058776 : examine_simple_variable(PlannerInfo *root, Var *var,
    5706             :                         VariableStatData *vardata)
    5707             : {
    5708     2058776 :     RangeTblEntry *rte = root->simple_rte_array[var->varno];
    5709             : 
    5710             :     Assert(IsA(rte, RangeTblEntry));
    5711             : 
    5712     2058776 :     if (get_relation_stats_hook &&
    5713           0 :         (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
    5714             :     {
    5715             :         /*
    5716             :          * The hook took control of acquiring a stats tuple.  If it did supply
    5717             :          * a tuple, it'd better have supplied a freefunc.
    5718             :          */
    5719           0 :         if (HeapTupleIsValid(vardata->statsTuple) &&
    5720           0 :             !vardata->freefunc)
    5721           0 :             elog(ERROR, "no function provided to release variable stats with");
    5722             :     }
    5723     2058776 :     else if (rte->rtekind == RTE_RELATION)
    5724             :     {
    5725             :         /*
    5726             :          * Plain table or parent of an inheritance appendrel, so look up the
    5727             :          * column in pg_statistic
    5728             :          */
    5729     1955308 :         vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    5730             :                                               ObjectIdGetDatum(rte->relid),
    5731     1955308 :                                               Int16GetDatum(var->varattno),
    5732     1955308 :                                               BoolGetDatum(rte->inh));
    5733     1955308 :         vardata->freefunc = ReleaseSysCache;
    5734             : 
    5735     1955308 :         if (HeapTupleIsValid(vardata->statsTuple))
    5736             :         {
    5737     1473376 :             RelOptInfo *onerel = find_base_rel_noerr(root, var->varno);
    5738             :             Oid         userid;
    5739             : 
    5740             :             /*
    5741             :              * Check if user has permission to read this column.  We require
    5742             :              * all rows to be accessible, so there must be no securityQuals
    5743             :              * from security barrier views or RLS policies.
    5744             :              *
    5745             :              * Normally the Var will have an associated RelOptInfo from which
    5746             :              * we can find out which userid to do the check as; but it might
    5747             :              * not if it's a RETURNING Var for an INSERT target relation.  In
    5748             :              * that case use the RTEPermissionInfo associated with the RTE.
    5749             :              */
    5750     1473376 :             if (onerel)
    5751     1473334 :                 userid = onerel->userid;
    5752             :             else
    5753             :             {
    5754             :                 RTEPermissionInfo *perminfo;
    5755             : 
    5756          42 :                 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
    5757          42 :                 userid = perminfo->checkAsUser;
    5758             :             }
    5759     1473376 :             if (!OidIsValid(userid))
    5760     1364834 :                 userid = GetUserId();
    5761             : 
    5762     1473376 :             vardata->acl_ok =
    5763     2947012 :                 rte->securityQuals == NIL &&
    5764     1473376 :                 ((pg_class_aclcheck(rte->relid, userid,
    5765         260 :                                     ACL_SELECT) == ACLCHECK_OK) ||
    5766         260 :                  (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
    5767             :                                         ACL_SELECT) == ACLCHECK_OK));
    5768             : 
    5769             :             /*
    5770             :              * If the user doesn't have permissions to access an inheritance
    5771             :              * child relation or specifically this attribute, check the
    5772             :              * permissions of the table/column actually mentioned in the
    5773             :              * query, since most likely the user does have that permission
    5774             :              * (else the query will fail at runtime), and if the user can read
    5775             :              * the column there then he can get the values of the child table
    5776             :              * too.  To do that, we must find out which of the root parent's
    5777             :              * attributes the child relation's attribute corresponds to.
    5778             :              */
    5779     1473376 :             if (!vardata->acl_ok && var->varattno > 0 &&
    5780          60 :                 root->append_rel_array != NULL)
    5781             :             {
    5782             :                 AppendRelInfo *appinfo;
    5783          12 :                 Index       varno = var->varno;
    5784          12 :                 int         varattno = var->varattno;
    5785          12 :                 bool        found = false;
    5786             : 
    5787          12 :                 appinfo = root->append_rel_array[varno];
    5788             : 
    5789             :                 /*
    5790             :                  * Partitions are mapped to their immediate parent, not the
    5791             :                  * root parent, so must be ready to walk up multiple
    5792             :                  * AppendRelInfos.  But stop if we hit a parent that is not
    5793             :                  * RTE_RELATION --- that's a flattened UNION ALL subquery, not
    5794             :                  * an inheritance parent.
    5795             :                  */
    5796          36 :                 while (appinfo &&
    5797          24 :                        planner_rt_fetch(appinfo->parent_relid,
    5798          24 :                                         root)->rtekind == RTE_RELATION)
    5799             :                 {
    5800             :                     int         parent_varattno;
    5801             : 
    5802          24 :                     found = false;
    5803          24 :                     if (varattno <= 0 || varattno > appinfo->num_child_cols)
    5804             :                         break;  /* safety check */
    5805          24 :                     parent_varattno = appinfo->parent_colnos[varattno - 1];
    5806          24 :                     if (parent_varattno == 0)
    5807           0 :                         break;  /* Var is local to child */
    5808             : 
    5809          24 :                     varno = appinfo->parent_relid;
    5810          24 :                     varattno = parent_varattno;
    5811          24 :                     found = true;
    5812             : 
    5813             :                     /* If the parent is itself a child, continue up. */
    5814          24 :                     appinfo = root->append_rel_array[varno];
    5815             :                 }
    5816             : 
    5817             :                 /*
    5818             :                  * In rare cases, the Var may be local to the child table, in
    5819             :                  * which case, we've got to live with having no access to this
    5820             :                  * column's stats.
    5821             :                  */
    5822          12 :                 if (!found)
    5823           0 :                     return;
    5824             : 
    5825             :                 /* Repeat the access check on this parent rel & column */
    5826          12 :                 rte = planner_rt_fetch(varno, root);
    5827             :                 Assert(rte->rtekind == RTE_RELATION);
    5828             : 
    5829             :                 /*
    5830             :                  * Fine to use the same userid as it's the same in all
    5831             :                  * relations of a given inheritance tree.
    5832             :                  */
    5833          12 :                 vardata->acl_ok =
    5834          30 :                     rte->securityQuals == NIL &&
    5835          12 :                     ((pg_class_aclcheck(rte->relid, userid,
    5836           6 :                                         ACL_SELECT) == ACLCHECK_OK) ||
    5837           6 :                      (pg_attribute_aclcheck(rte->relid, varattno, userid,
    5838             :                                             ACL_SELECT) == ACLCHECK_OK));
    5839             :             }
    5840             :         }
    5841             :         else
    5842             :         {
    5843             :             /* suppress any possible leakproofness checks later */
    5844      481932 :             vardata->acl_ok = true;
    5845             :         }
    5846             :     }
    5847      103468 :     else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
    5848       93668 :              (rte->rtekind == RTE_CTE && !rte->self_reference))
    5849             :     {
    5850             :         /*
    5851             :          * Plain subquery (not one that was converted to an appendrel) or
    5852             :          * non-recursive CTE.  In either case, we can try to find out what the
    5853             :          * Var refers to within the subquery.  We skip this for appendrel and
    5854             :          * recursive-CTE cases because any column stats we did find would
    5855             :          * likely not be very relevant.
    5856             :          */
    5857             :         PlannerInfo *subroot;
    5858             :         Query      *subquery;
    5859             :         List       *subtlist;
    5860             :         TargetEntry *ste;
    5861             : 
    5862             :         /*
    5863             :          * Punt if it's a whole-row var rather than a plain column reference.
    5864             :          */
    5865       16756 :         if (var->varattno == InvalidAttrNumber)
    5866           0 :             return;
    5867             : 
    5868             :         /*
    5869             :          * Otherwise, find the subquery's planner subroot.
    5870             :          */
    5871       16756 :         if (rte->rtekind == RTE_SUBQUERY)
    5872             :         {
    5873             :             RelOptInfo *rel;
    5874             : 
    5875             :             /*
    5876             :              * Fetch RelOptInfo for subquery.  Note that we don't change the
    5877             :              * rel returned in vardata, since caller expects it to be a rel of
    5878             :              * the caller's query level.  Because we might already be
    5879             :              * recursing, we can't use that rel pointer either, but have to
    5880             :              * look up the Var's rel afresh.
    5881             :              */
    5882        9800 :             rel = find_base_rel(root, var->varno);
    5883             : 
    5884        9800 :             subroot = rel->subroot;
    5885             :         }
    5886             :         else
    5887             :         {
    5888             :             /* CTE case is more difficult */
    5889             :             PlannerInfo *cteroot;
    5890             :             Index       levelsup;
    5891             :             int         ndx;
    5892             :             int         plan_id;
    5893             :             ListCell   *lc;
    5894             : 
    5895             :             /*
    5896             :              * Find the referenced CTE, and locate the subroot previously made
    5897             :              * for it.
    5898             :              */
    5899        6956 :             levelsup = rte->ctelevelsup;
    5900        6956 :             cteroot = root;
    5901       12982 :             while (levelsup-- > 0)
    5902             :             {
    5903        6026 :                 cteroot = cteroot->parent_root;
    5904        6026 :                 if (!cteroot)   /* shouldn't happen */
    5905           0 :                     elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    5906             :             }
    5907             : 
    5908             :             /*
    5909             :              * Note: cte_plan_ids can be shorter than cteList, if we are still
    5910             :              * working on planning the CTEs (ie, this is a side-reference from
    5911             :              * another CTE).  So we mustn't use forboth here.
    5912             :              */
    5913        6956 :             ndx = 0;
    5914        9178 :             foreach(lc, cteroot->parse->cteList)
    5915             :             {
    5916        9178 :                 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
    5917             : 
    5918        9178 :                 if (strcmp(cte->ctename, rte->ctename) == 0)
    5919        6956 :                     break;
    5920        2222 :                 ndx++;
    5921             :             }
    5922        6956 :             if (lc == NULL)     /* shouldn't happen */
    5923           0 :                 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
    5924        6956 :             if (ndx >= list_length(cteroot->cte_plan_ids))
    5925           0 :                 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
    5926        6956 :             plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
    5927        6956 :             if (plan_id <= 0)
    5928           0 :                 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
    5929        6956 :             subroot = list_nth(root->glob->subroots, plan_id - 1);
    5930             :         }
    5931             : 
    5932             :         /* If the subquery hasn't been planned yet, we have to punt */
    5933       16756 :         if (subroot == NULL)
    5934           0 :             return;
    5935             :         Assert(IsA(subroot, PlannerInfo));
    5936             : 
    5937             :         /*
    5938             :          * We must use the subquery parsetree as mangled by the planner, not
    5939             :          * the raw version from the RTE, because we need a Var that will refer
    5940             :          * to the subroot's live RelOptInfos.  For instance, if any subquery
    5941             :          * pullup happened during planning, Vars in the targetlist might have
    5942             :          * gotten replaced, and we need to see the replacement expressions.
    5943             :          */
    5944       16756 :         subquery = subroot->parse;
    5945             :         Assert(IsA(subquery, Query));
    5946             : 
    5947             :         /*
    5948             :          * Punt if subquery uses set operations or grouping sets, as these
    5949             :          * will mash underlying columns' stats beyond recognition.  (Set ops
    5950             :          * are particularly nasty; if we forged ahead, we would return stats
    5951             :          * relevant to only the leftmost subselect...)  DISTINCT is also
    5952             :          * problematic, but we check that later because there is a possibility
    5953             :          * of learning something even with it.
    5954             :          */
    5955       16756 :         if (subquery->setOperations ||
    5956       14876 :             subquery->groupingSets)
    5957        1904 :             return;
    5958             : 
    5959             :         /* Get the subquery output expression referenced by the upper Var */
    5960       14852 :         if (subquery->returningList)
    5961         206 :             subtlist = subquery->returningList;
    5962             :         else
    5963       14646 :             subtlist = subquery->targetList;
    5964       14852 :         ste = get_tle_by_resno(subtlist, var->varattno);
    5965       14852 :         if (ste == NULL || ste->resjunk)
    5966           0 :             elog(ERROR, "subquery %s does not have attribute %d",
    5967             :                  rte->eref->aliasname, var->varattno);
    5968       14852 :         var = (Var *) ste->expr;
    5969             : 
    5970             :         /*
    5971             :          * If subquery uses DISTINCT, we can't make use of any stats for the
    5972             :          * variable ... but, if it's the only DISTINCT column, we are entitled
    5973             :          * to consider it unique.  We do the test this way so that it works
    5974             :          * for cases involving DISTINCT ON.
    5975             :          */
    5976       14852 :         if (subquery->distinctClause)
    5977             :         {
    5978        1838 :             if (list_length(subquery->distinctClause) == 1 &&
    5979         616 :                 targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
    5980         308 :                 vardata->isunique = true;
    5981             :             /* cannot go further */
    5982        1222 :             return;
    5983             :         }
    5984             : 
    5985             :         /* The same idea as with DISTINCT clause works for a GROUP-BY too */
    5986       13630 :         if (subquery->groupClause)
    5987             :         {
    5988        1040 :             if (list_length(subquery->groupClause) == 1 &&
    5989         430 :                 targetIsInSortList(ste, InvalidOid, subquery->groupClause))
    5990         334 :                 vardata->isunique = true;
    5991             :             /* cannot go further */
    5992         610 :             return;
    5993             :         }
    5994             : 
    5995             :         /*
    5996             :          * If the sub-query originated from a view with the security_barrier
    5997             :          * attribute, we must not look at the variable's statistics, though it
    5998             :          * seems all right to notice the existence of a DISTINCT clause. So
    5999             :          * stop here.
    6000             :          *
    6001             :          * This is probably a harsher restriction than necessary; it's
    6002             :          * certainly OK for the selectivity estimator (which is a C function,
    6003             :          * and therefore omnipotent anyway) to look at the statistics.  But
    6004             :          * many selectivity estimators will happily *invoke the operator
    6005             :          * function* to try to work out a good estimate - and that's not OK.
    6006             :          * So for now, don't dig down for stats.
    6007             :          */
    6008       13020 :         if (rte->security_barrier)
    6009        1374 :             return;
    6010             : 
    6011             :         /* Can only handle a simple Var of subquery's query level */
    6012       11646 :         if (var && IsA(var, Var) &&
    6013        6160 :             var->varlevelsup == 0)
    6014             :         {
    6015             :             /*
    6016             :              * OK, recurse into the subquery.  Note that the original setting
    6017             :              * of vardata->isunique (which will surely be false) is left
    6018             :              * unchanged in this situation.  That's what we want, since even
    6019             :              * if the underlying column is unique, the subquery may have
    6020             :              * joined to other tables in a way that creates duplicates.
    6021             :              */
    6022        6160 :             examine_simple_variable(subroot, var, vardata);
    6023             :         }
    6024             :     }
    6025             :     else
    6026             :     {
    6027             :         /*
    6028             :          * Otherwise, the Var comes from a FUNCTION or VALUES RTE.  (We won't
    6029             :          * see RTE_JOIN here because join alias Vars have already been
    6030             :          * flattened.)  There's not much we can do with function outputs, but
    6031             :          * maybe someday try to be smarter about VALUES.
    6032             :          */
    6033             :     }
    6034             : }
    6035             : 
    6036             : /*
    6037             :  * examine_indexcol_variable
    6038             :  *      Try to look up statistical data about an index column/expression.
    6039             :  *      Fill in a VariableStatData struct to describe the column.
    6040             :  *
    6041             :  * Inputs:
    6042             :  *  root: the planner info
    6043             :  *  index: the index whose column we're interested in
    6044             :  *  indexcol: 0-based index column number (subscripts index->indexkeys[])
    6045             :  *
    6046             :  * Outputs: *vardata is filled as follows:
    6047             :  *  var: the input expression (with any binary relabeling stripped, if
    6048             :  *      it is or contains a variable; but otherwise the type is preserved)
    6049             :  *  rel: RelOptInfo for table relation containing variable.
    6050             :  *  statsTuple: the pg_statistic entry for the variable, if one exists;
    6051             :  *      otherwise NULL.
    6052             :  *  freefunc: pointer to a function to release statsTuple with.
    6053             :  *
    6054             :  * Caller is responsible for doing ReleaseVariableStats() before exiting.
    6055             :  */
    6056             : static void
    6057      747598 : examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
    6058             :                           int indexcol, VariableStatData *vardata)
    6059             : {
    6060             :     AttrNumber  colnum;
    6061             :     Oid         relid;
    6062             : 
    6063      747598 :     if (index->indexkeys[indexcol] != 0)
    6064             :     {
    6065             :         /* Simple variable --- look to stats for the underlying table */
    6066      745408 :         RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
    6067             : 
    6068             :         Assert(rte->rtekind == RTE_RELATION);
    6069      745408 :         relid = rte->relid;
    6070             :         Assert(relid != InvalidOid);
    6071      745408 :         colnum = index->indexkeys[indexcol];
    6072      745408 :         vardata->rel = index->rel;
    6073             : 
    6074      745408 :         if (get_relation_stats_hook &&
    6075           0 :             (*get_relation_stats_hook) (root, rte, colnum, vardata))
    6076             :         {
    6077             :             /*
    6078             :              * The hook took control of acquiring a stats tuple.  If it did
    6079             :              * supply a tuple, it'd better have supplied a freefunc.
    6080             :              */
    6081           0 :             if (HeapTupleIsValid(vardata->statsTuple) &&
    6082           0 :                 !vardata->freefunc)
    6083           0 :                 elog(ERROR, "no function provided to release variable stats with");
    6084             :         }
    6085             :         else
    6086             :         {
    6087      745408 :             vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    6088             :                                                   ObjectIdGetDatum(relid),
    6089             :                                                   Int16GetDatum(colnum),
    6090      745408 :                                                   BoolGetDatum(rte->inh));
    6091      745408 :             vardata->freefunc = ReleaseSysCache;
    6092             :         }
    6093             :     }
    6094             :     else
    6095             :     {
    6096             :         /* Expression --- maybe there are stats for the index itself */
    6097        2190 :         relid = index->indexoid;
    6098        2190 :         colnum = indexcol + 1;
    6099             : 
    6100        2190 :         if (get_index_stats_hook &&
    6101           0 :             (*get_index_stats_hook) (root, relid, colnum, vardata))
    6102             :         {
    6103             :             /*
    6104             :              * The hook took control of acquiring a stats tuple.  If it did
    6105             :              * supply a tuple, it'd better have supplied a freefunc.
    6106             :              */
    6107           0 :             if (HeapTupleIsValid(vardata->statsTuple) &&
    6108           0 :                 !vardata->freefunc)
    6109           0 :                 elog(ERROR, "no function provided to release variable stats with");
    6110             :         }
    6111             :         else
    6112             :         {
    6113        2190 :             vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    6114             :                                                   ObjectIdGetDatum(relid),
    6115             :                                                   Int16GetDatum(colnum),
    6116             :                                                   BoolGetDatum(false));
    6117        2190 :             vardata->freefunc = ReleaseSysCache;
    6118             :         }
    6119             :     }
    6120      747598 : }
    6121             : 
    6122             : /*
    6123             :  * Check whether it is permitted to call func_oid passing some of the
    6124             :  * pg_statistic data in vardata.  We allow this either if the user has SELECT
    6125             :  * privileges on the table or column underlying the pg_statistic data or if
    6126             :  * the function is marked leakproof.
    6127             :  */
    6128             : bool
    6129      965924 : statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
    6130             : {
    6131      965924 :     if (vardata->acl_ok)
    6132      965330 :         return true;
    6133             : 
    6134         594 :     if (!OidIsValid(func_oid))
    6135           0 :         return false;
    6136             : 
    6137         594 :     if (get_func_leakproof(func_oid))
    6138         246 :         return true;
    6139             : 
    6140         348 :     ereport(DEBUG2,
    6141             :             (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
    6142             :                              get_func_name(func_oid))));
    6143         348 :     return false;
    6144             : }
    6145             : 
    6146             : /*
    6147             :  * get_variable_numdistinct
    6148             :  *    Estimate the number of distinct values of a variable.
    6149             :  *
    6150             :  * vardata: results of examine_variable
    6151             :  * *isdefault: set to true if the result is a default rather than based on
    6152             :  * anything meaningful.
    6153             :  *
    6154             :  * NB: be careful to produce a positive integral result, since callers may
    6155             :  * compare the result to exact integer counts, or might divide by it.
    6156             :  */
    6157             : double
    6158     1436356 : get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
    6159             : {
    6160             :     double      stadistinct;
    6161     1436356 :     double      stanullfrac = 0.0;
    6162             :     double      ntuples;
    6163             : 
    6164     1436356 :     *isdefault = false;
    6165             : 
    6166             :     /*
    6167             :      * Determine the stadistinct value to use.  There are cases where we can
    6168             :      * get an estimate even without a pg_statistic entry, or can get a better
    6169             :      * value than is in pg_statistic.  Grab stanullfrac too if we can find it
    6170             :      * (otherwise, assume no nulls, for lack of any better idea).
    6171             :      */
    6172     1436356 :     if (HeapTupleIsValid(vardata->statsTuple))
    6173             :     {
    6174             :         /* Use the pg_statistic entry */
    6175             :         Form_pg_statistic stats;
    6176             : 
    6177     1034356 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
    6178     1034356 :         stadistinct = stats->stadistinct;
    6179     1034356 :         stanullfrac = stats->stanullfrac;
    6180             :     }
    6181      402000 :     else if (vardata->vartype == BOOLOID)
    6182             :     {
    6183             :         /*
    6184             :          * Special-case boolean columns: presumably, two distinct values.
    6185             :          *
    6186             :          * Are there any other datatypes we should wire in special estimates
    6187             :          * for?
    6188             :          */
    6189         582 :         stadistinct = 2.0;
    6190             :     }
    6191      401418 :     else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
    6192             :     {
    6193             :         /*
    6194             :          * If the Var represents a column of a VALUES RTE, assume it's unique.
    6195             :          * This could of course be very wrong, but it should tend to be true
    6196             :          * in well-written queries.  We could consider examining the VALUES'
    6197             :          * contents to get some real statistics; but that only works if the
    6198             :          * entries are all constants, and it would be pretty expensive anyway.
    6199             :          */
    6200        3442 :         stadistinct = -1.0;     /* unique (and all non null) */
    6201             :     }
    6202             :     else
    6203             :     {
    6204             :         /*
    6205             :          * We don't keep statistics for system columns, but in some cases we
    6206             :          * can infer distinctness anyway.
    6207             :          */
    6208      397976 :         if (vardata->var && IsA(vardata->var, Var))
    6209             :         {
    6210      366986 :             switch (((Var *) vardata->var)->varattno)
    6211             :             {
    6212        1178 :                 case SelfItemPointerAttributeNumber:
    6213        1178 :                     stadistinct = -1.0; /* unique (and all non null) */
    6214        1178 :                     break;
    6215       10304 :                 case TableOidAttributeNumber:
    6216       10304 :                     stadistinct = 1.0;  /* only 1 value */
    6217       10304 :                     break;
    6218      355504 :                 default:
    6219      355504 :                     stadistinct = 0.0;  /* means "unknown" */
    6220      355504 :                     break;
    6221             :             }
    6222             :         }
    6223             :         else
    6224       30990 :             stadistinct = 0.0;  /* means "unknown" */
    6225             : 
    6226             :         /*
    6227             :          * XXX consider using estimate_num_groups on expressions?
    6228             :          */
    6229             :     }
    6230             : 
    6231             :     /*
    6232             :      * If there is a unique index, DISTINCT or GROUP-BY clause for the
    6233             :      * variable, assume it is unique no matter what pg_statistic says; the
    6234             :      * statistics could be out of date, or we might have found a partial
    6235             :      * unique index that proves the var is unique for this query.  However,
    6236             :      * we'd better still believe the null-fraction statistic.
    6237             :      */
    6238     1436356 :     if (vardata->isunique)
    6239      378688 :         stadistinct = -1.0 * (1.0 - stanullfrac);
    6240             : 
    6241             :     /*
    6242             :      * If we had an absolute estimate, use that.
    6243             :      */
    6244     1436356 :     if (stadistinct > 0.0)
    6245      332522 :         return clamp_row_est(stadistinct);
    6246             : 
    6247             :     /*
    6248             :      * Otherwise we need to get the relation size; punt if not available.
    6249             :      */
    6250     1103834 :     if (vardata->rel == NULL)
    6251             :     {
    6252         410 :         *isdefault = true;
    6253         410 :         return DEFAULT_NUM_DISTINCT;
    6254             :     }
    6255     1103424 :     ntuples = vardata->rel->tuples;
    6256     1103424 :     if (ntuples <= 0.0)
    6257             :     {
    6258       53730 :         *isdefault = true;
    6259       53730 :         return DEFAULT_NUM_DISTINCT;
    6260             :     }
    6261             : 
    6262             :     /*
    6263             :      * If we had a relative estimate, use that.
    6264             :      */
    6265     1049694 :     if (stadistinct < 0.0)
    6266      755026 :         return clamp_row_est(-stadistinct * ntuples);
    6267             : 
    6268             :     /*
    6269             :      * With no data, estimate ndistinct = ntuples if the table is small, else
    6270             :      * use default.  We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
    6271             :      * that the behavior isn't discontinuous.
    6272             :      */
    6273      294668 :     if (ntuples < DEFAULT_NUM_DISTINCT)
    6274      136522 :         return clamp_row_est(ntuples);
    6275             : 
    6276      158146 :     *isdefault = true;
    6277      158146 :     return DEFAULT_NUM_DISTINCT;
    6278             : }
    6279             : 
    6280             : /*
    6281             :  * get_variable_range
    6282             :  *      Estimate the minimum and maximum value of the specified variable.
    6283             :  *      If successful, store values in *min and *max, and return true.
    6284             :  *      If no data available, return false.
    6285             :  *
    6286             :  * sortop is the "<" comparison operator to use.  This should generally
    6287             :  * be "<" not ">", as only the former is likely to be found in pg_statistic.
    6288             :  * The collation must be specified too.
    6289             :  */
    6290             : static bool
    6291      205196 : get_variable_range(PlannerInfo *root, VariableStatData *vardata,
    6292             :                    Oid sortop, Oid collation,
    6293             :                    Datum *min, Datum *max)
    6294             : {
    6295      205196 :     Datum       tmin = 0;
    6296      205196 :     Datum       tmax = 0;
    6297      205196 :     bool        have_data = false;
    6298             :     int16       typLen;
    6299             :     bool        typByVal;
    6300             :     Oid         opfuncoid;
    6301             :     FmgrInfo    opproc;
    6302             :     AttStatsSlot sslot;
    6303             : 
    6304             :     /*
    6305             :      * XXX It's very tempting to try to use the actual column min and max, if
    6306             :      * we can get them relatively-cheaply with an index probe.  However, since
    6307             :      * this function is called many times during join planning, that could
    6308             :      * have unpleasant effects on planning speed.  Need more investigation
    6309             :      * before enabling this.
    6310             :      */
    6311             : #ifdef NOT_USED
    6312             :     if (get_actual_variable_range(root, vardata, sortop, collation, min, max))
    6313             :         return true;
    6314             : #endif
    6315             : 
    6316      205196 :     if (!HeapTupleIsValid(vardata->statsTuple))
    6317             :     {
    6318             :         /* no stats available, so default result */
    6319       45690 :         return false;
    6320             :     }
    6321             : 
    6322             :     /*
    6323             :      * If we can't apply the sortop to the stats data, just fail.  In
    6324             :      * principle, if there's a histogram and no MCVs, we could return the
    6325             :      * histogram endpoints without ever applying the sortop ... but it's
    6326             :      * probably not worth trying, because whatever the caller wants to do with
    6327             :      * the endpoints would likely fail the security check too.
    6328             :      */
    6329      159506 :     if (!statistic_proc_security_check(vardata,
    6330      159506 :                                        (opfuncoid = get_opcode(sortop))))
    6331           0 :         return false;
    6332             : 
    6333      159506 :     opproc.fn_oid = InvalidOid; /* mark this as not looked up yet */
    6334             : 
    6335      159506 :     get_typlenbyval(vardata->atttype, &typLen, &typByVal);
    6336             : 
    6337             :     /*
    6338             :      * If there is a histogram with the ordering we want, grab the first and
    6339             :      * last values.
    6340             :      */
    6341      159506 :     if (get_attstatsslot(&sslot, vardata->statsTuple,
    6342             :                          STATISTIC_KIND_HISTOGRAM, sortop,
    6343             :                          ATTSTATSSLOT_VALUES))
    6344             :     {
    6345      118046 :         if (sslot.stacoll == collation && sslot.nvalues > 0)
    6346             :         {
    6347      118046 :             tmin = datumCopy(sslot.values[0], typByVal, typLen);
    6348      118046 :             tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
    6349      118046 :             have_data = true;
    6350             :         }
    6351      118046 :         free_attstatsslot(&sslot);
    6352             :     }
    6353             : 
    6354             :     /*
    6355             :      * Otherwise, if there is a histogram with some other ordering, scan it
    6356             :      * and get the min and max values according to the ordering we want.  This
    6357             :      * of course may not find values that are really extremal according to our
    6358             :      * ordering, but it beats ignoring available data.
    6359             :      */
    6360      200966 :     if (!have_data &&
    6361       41460 :         get_attstatsslot(&sslot, vardata->statsTuple,
    6362             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
    6363             :                          ATTSTATSSLOT_VALUES))
    6364             :     {
    6365           0 :         get_stats_slot_range(&sslot, opfuncoid, &opproc,
    6366             :                              collation, typLen, typByVal,
    6367             :                              &tmin, &tmax, &have_data);
    6368           0 :         free_attstatsslot(&sslot);
    6369             :     }
    6370             : 
    6371             :     /*
    6372             :      * If we have most-common-values info, look for extreme MCVs.  This is
    6373             :      * needed even if we also have a histogram, since the histogram excludes
    6374             :      * the MCVs.  However, if we *only* have MCVs and no histogram, we should
    6375             :      * be pretty wary of deciding that that is a full representation of the
    6376             :      * data.  Proceed only if the MCVs represent the whole table (to within
    6377             :      * roundoff error).
    6378             :      */
    6379      159506 :     if (get_attstatsslot(&sslot, vardata->statsTuple,
    6380             :                          STATISTIC_KIND_MCV, InvalidOid,
    6381      159506 :                          have_data ? ATTSTATSSLOT_VALUES :
    6382             :                          (ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)))
    6383             :     {
    6384       77390 :         bool        use_mcvs = have_data;
    6385             : 
    6386       77390 :         if (!have_data)
    6387             :         {
    6388       40034 :             double      sumcommon = 0.0;
    6389             :             double      nullfrac;
    6390             :             int         i;
    6391             : 
    6392      304570 :             for (i = 0; i < sslot.nnumbers; i++)
    6393      264536 :                 sumcommon += sslot.numbers[i];
    6394       40034 :             nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata->statsTuple))->stanullfrac;
    6395       40034 :             if (sumcommon + nullfrac > 0.99999)
    6396       38164 :                 use_mcvs = true;
    6397             :         }
    6398             : 
    6399       77390 :         if (use_mcvs)
    6400       75520 :             get_stats_slot_range(&sslot, opfuncoid, &opproc,
    6401             :                                  collation, typLen, typByVal,
    6402             :                                  &tmin, &tmax, &have_data);
    6403       77390 :         free_attstatsslot(&sslot);
    6404             :     }
    6405             : 
    6406      159506 :     *min = tmin;
    6407      159506 :     *max = tmax;
    6408      159506 :     return have_data;
    6409             : }
    6410             : 
    6411             : /*
    6412             :  * get_stats_slot_range: scan sslot for min/max values
    6413             :  *
    6414             :  * Subroutine for get_variable_range: update min/max/have_data according
    6415             :  * to what we find in the statistics array.
    6416             :  */
    6417             : static void
    6418       75520 : get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
    6419             :                      Oid collation, int16 typLen, bool typByVal,
    6420             :                      Datum *min, Datum *max, bool *p_have_data)
    6421             : {
    6422       75520 :     Datum       tmin = *min;
    6423       75520 :     Datum       tmax = *max;
    6424       75520 :     bool        have_data = *p_have_data;
    6425       75520 :     bool        found_tmin = false;
    6426       75520 :     bool        found_tmax = false;
    6427             : 
    6428             :     /* Look up the comparison function, if we didn't already do so */
    6429       75520 :     if (opproc->fn_oid != opfuncoid)
    6430       75520 :         fmgr_info(opfuncoid, opproc);
    6431             : 
    6432             :     /* Scan all the slot's values */
    6433     2315056 :     for (int i = 0; i < sslot->nvalues; i++)
    6434             :     {
    6435     2239536 :         if (!have_data)
    6436             :         {
    6437       38164 :             tmin = tmax = sslot->values[i];
    6438       38164 :             found_tmin = found_tmax = true;
    6439       38164 :             *p_have_data = have_data = true;
    6440       38164 :             continue;
    6441             :         }
    6442     2201372 :         if (DatumGetBool(FunctionCall2Coll(opproc,
    6443             :                                            collation,
    6444     2201372 :                                            sslot->values[i], tmin)))
    6445             :         {
    6446       51802 :             tmin = sslot->values[i];
    6447       51802 :             found_tmin = true;
    6448             :         }
    6449     2201372 :         if (DatumGetBool(FunctionCall2Coll(opproc,
    6450             :                                            collation,
    6451     2201372 :                                            tmax, sslot->values[i])))
    6452             :         {
    6453       98222 :             tmax = sslot->values[i];
    6454       98222 :             found_tmax = true;
    6455             :         }
    6456             :     }
    6457             : 
    6458             :     /*
    6459             :      * Copy the slot's values, if we found new extreme values.
    6460             :      */
    6461       75520 :     if (found_tmin)
    6462       60410 :         *min = datumCopy(tmin, typByVal, typLen);
    6463       75520 :     if (found_tmax)
    6464       41558 :         *max = datumCopy(tmax, typByVal, typLen);
    6465       75520 : }
    6466             : 
    6467             : 
    6468             : /*
    6469             :  * get_actual_variable_range
    6470             :  *      Attempt to identify the current *actual* minimum and/or maximum
    6471             :  *      of the specified variable, by looking for a suitable btree index
    6472             :  *      and fetching its low and/or high values.
    6473             :  *      If successful, store values in *min and *max, and return true.
    6474             :  *      (Either pointer can be NULL if that endpoint isn't needed.)
    6475             :  *      If unsuccessful, return false.
    6476             :  *
    6477             :  * sortop is the "<" comparison operator to use.
    6478             :  * collation is the required collation.
    6479             :  */
    6480             : static bool
    6481      182256 : get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
    6482             :                           Oid sortop, Oid collation,
    6483             :                           Datum *min, Datum *max)
    6484             : {
    6485      182256 :     bool        have_data = false;
    6486      182256 :     RelOptInfo *rel = vardata->rel;
    6487             :     RangeTblEntry *rte;
    6488             :     ListCell   *lc;
    6489             : 
    6490             :     /* No hope if no relation or it doesn't have indexes */
    6491      182256 :     if (rel == NULL || rel->indexlist == NIL)
    6492       13470 :         return false;
    6493             :     /* If it has indexes it must be a plain relation */
    6494      168786 :     rte = root->simple_rte_array[rel->relid];
    6495             :     Assert(rte->rtekind == RTE_RELATION);
    6496             : 
    6497             :     /* ignore partitioned tables.  Any indexes here are not real indexes */
    6498      168786 :     if (rte->relkind == RELKIND_PARTITIONED_TABLE)
    6499         876 :         return false;
    6500             : 
    6501             :     /* Search through the indexes to see if any match our problem */
    6502      325038 :     foreach(lc, rel->indexlist)
    6503             :     {
    6504      278364 :         IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
    6505             :         ScanDirection indexscandir;
    6506             :         StrategyNumber strategy;
    6507             : 
    6508             :         /* Ignore non-ordering indexes */
    6509      278364 :         if (index->sortopfamily == NULL)
    6510           2 :             continue;
    6511             : 
    6512             :         /*
    6513             :          * Ignore partial indexes --- we only want stats that cover the entire
    6514             :          * relation.
    6515             :          */
    6516      278362 :         if (index->indpred != NIL)
    6517         288 :             continue;
    6518             : 
    6519             :         /*
    6520             :          * The index list might include hypothetical indexes inserted by a
    6521             :          * get_relation_info hook --- don't try to access them.
    6522             :          */
    6523      278074 :         if (index->hypothetical)
    6524           0 :             continue;
    6525             : 
    6526             :         /*
    6527             :          * The first index column must match the desired variable, sortop, and
    6528             :          * collation --- but we can use a descending-order index.
    6529             :          */
    6530      278074 :         if (collation != index->indexcollations[0])
    6531       35116 :             continue;           /* test first 'cause it's cheapest */
    6532      242958 :         if (!match_index_to_operand(vardata->var, 0, index))
    6533      121722 :             continue;
    6534      121236 :         strategy = get_op_opfamily_strategy(sortop, index->sortopfamily[0]);
    6535      121236 :         switch (IndexAmTranslateStrategy(strategy, index->relam, index->sortopfamily[0], true))
    6536             :         {
    6537      121236 :             case COMPARE_LT:
    6538      121236 :                 if (index->reverse_sort[0])
    6539           0 :                     indexscandir = BackwardScanDirection;
    6540             :                 else
    6541      121236 :                     indexscandir = ForwardScanDirection;
    6542      121236 :                 break;
    6543           0 :             case COMPARE_GT:
    6544           0 :                 if (index->reverse_sort[0])
    6545           0 :                     indexscandir = ForwardScanDirection;
    6546             :                 else
    6547           0 :                     indexscandir = BackwardScanDirection;
    6548           0 :                 break;
    6549           0 :             default:
    6550             :                 /* index doesn't match the sortop */
    6551           0 :                 continue;
    6552             :         }
    6553             : 
    6554             :         /*
    6555             :          * Found a suitable index to extract data from.  Set up some data that
    6556             :          * can be used by both invocations of get_actual_variable_endpoint.
    6557             :          */
    6558             :         {
    6559             :             MemoryContext tmpcontext;
    6560             :             MemoryContext oldcontext;
    6561             :             Relation    heapRel;
    6562             :             Relation    indexRel;
    6563             :             TupleTableSlot *slot;
    6564             :             int16       typLen;
    6565             :             bool        typByVal;
    6566             :             ScanKeyData scankeys[1];
    6567             : 
    6568             :             /* Make sure any cruft gets recycled when we're done */
    6569      121236 :             tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
    6570             :                                                "get_actual_variable_range workspace",
    6571             :                                                ALLOCSET_DEFAULT_SIZES);
    6572      121236 :             oldcontext = MemoryContextSwitchTo(tmpcontext);
    6573             : 
    6574             :             /*
    6575             :              * Open the table and index so we can read from them.  We should
    6576             :              * already have some type of lock on each.
    6577             :              */
    6578      121236 :             heapRel = table_open(rte->relid, NoLock);
    6579      121236 :             indexRel = index_open(index->indexoid, NoLock);
    6580             : 
    6581             :             /* build some stuff needed for indexscan execution */
    6582      121236 :             slot = table_slot_create(heapRel, NULL);
    6583      121236 :             get_typlenbyval(vardata->atttype, &typLen, &typByVal);
    6584             : 
    6585             :             /* set up an IS NOT NULL scan key so that we ignore nulls */
    6586      121236 :             ScanKeyEntryInitialize(&scankeys[0],
    6587             :                                    SK_ISNULL | SK_SEARCHNOTNULL,
    6588             :                                    1,   /* index col to scan */
    6589             :                                    InvalidStrategy, /* no strategy */
    6590             :                                    InvalidOid,  /* no strategy subtype */
    6591             :                                    InvalidOid,  /* no collation */
    6592             :                                    InvalidOid,  /* no reg proc for this */
    6593             :                                    (Datum) 0);  /* constant */
    6594             : 
    6595             :             /* If min is requested ... */
    6596      121236 :             if (min)
    6597             :             {
    6598       68918 :                 have_data = get_actual_variable_endpoint(heapRel,
    6599             :                                                          indexRel,
    6600             :                                                          indexscandir,
    6601             :                                                          scankeys,
    6602             :                                                          typLen,
    6603             :                                                          typByVal,
    6604             :                                                          slot,
    6605             :                                                          oldcontext,
    6606             :                                                          min);
    6607             :             }
    6608             :             else
    6609             :             {
    6610             :                 /* If min not requested, still want to fetch max */
    6611       52318 :                 have_data = true;
    6612             :             }
    6613             : 
    6614             :             /* If max is requested, and we didn't already fail ... */
    6615      121236 :             if (max && have_data)
    6616             :             {
    6617             :                 /* scan in the opposite direction; all else is the same */
    6618       53958 :                 have_data = get_actual_variable_endpoint(heapRel,
    6619             :                                                          indexRel,
    6620       53958 :                                                          -indexscandir,
    6621             :                                                          scankeys,
    6622             :                                                          typLen,
    6623             :                                                          typByVal,
    6624             :                                                          slot,
    6625             :                                                          oldcontext,
    6626             :                                                          max);
    6627             :             }
    6628             : 
    6629             :             /* Clean everything up */
    6630      121236 :             ExecDropSingleTupleTableSlot(slot);
    6631             : 
    6632      121236 :             index_close(indexRel, NoLock);
    6633      121236 :             table_close(heapRel, NoLock);
    6634             : 
    6635      121236 :             MemoryContextSwitchTo(oldcontext);
    6636      121236 :             MemoryContextDelete(tmpcontext);
    6637             : 
    6638             :             /* And we're done */
    6639      121236 :             break;
    6640             :         }
    6641             :     }
    6642             : 
    6643      167910 :     return have_data;
    6644             : }
    6645             : 
    6646             : /*
    6647             :  * Get one endpoint datum (min or max depending on indexscandir) from the
    6648             :  * specified index.  Return true if successful, false if not.
    6649             :  * On success, endpoint value is stored to *endpointDatum (and copied into
    6650             :  * outercontext).
    6651             :  *
    6652             :  * scankeys is a 1-element scankey array set up to reject nulls.
    6653             :  * typLen/typByVal describe the datatype of the index's first column.
    6654             :  * tableslot is a slot suitable to hold table tuples, in case we need
    6655             :  * to probe the heap.
    6656             :  * (We could compute these values locally, but that would mean computing them
    6657             :  * twice when get_actual_variable_range needs both the min and the max.)
    6658             :  *
    6659             :  * Failure occurs either when the index is empty, or we decide that it's
    6660             :  * taking too long to find a suitable tuple.
    6661             :  */
    6662             : static bool
    6663      122876 : get_actual_variable_endpoint(Relation heapRel,
    6664             :                              Relation indexRel,
    6665             :                              ScanDirection indexscandir,
    6666             :                              ScanKey scankeys,
    6667             :                              int16 typLen,
    6668             :                              bool typByVal,
    6669             :                              TupleTableSlot *tableslot,
    6670             :                              MemoryContext outercontext,
    6671             :                              Datum *endpointDatum)
    6672             : {
    6673      122876 :     bool        have_data = false;
    6674             :     SnapshotData SnapshotNonVacuumable;
    6675             :     IndexScanDesc index_scan;
    6676      122876 :     Buffer      vmbuffer = InvalidBuffer;
    6677      122876 :     BlockNumber last_heap_block = InvalidBlockNumber;
    6678      122876 :     int         n_visited_heap_pages = 0;
    6679             :     ItemPointer tid;
    6680             :     Datum       values[INDEX_MAX_KEYS];
    6681             :     bool        isnull[INDEX_MAX_KEYS];
    6682             :     MemoryContext oldcontext;
    6683             : 
    6684             :     /*
    6685             :      * We use the index-only-scan machinery for this.  With mostly-static
    6686             :      * tables that's a win because it avoids a heap visit.  It's also a win
    6687             :      * for dynamic data, but the reason is less obvious; read on for details.
    6688             :      *
    6689             :      * In principle, we should scan the index with our current active
    6690             :      * snapshot, which is the best approximation we've got to what the query
    6691             :      * will see when executed.  But that won't be exact if a new snap is taken
    6692             :      * before running the query, and it can be very expensive if a lot of
    6693             :      * recently-dead or uncommitted rows exist at the beginning or end of the
    6694             :      * index (because we'll laboriously fetch each one and reject it).
    6695             :      * Instead, we use SnapshotNonVacuumable.  That will accept recently-dead
    6696             :      * and uncommitted rows as well as normal visible rows.  On the other
    6697             :      * hand, it will reject known-dead rows, and thus not give a bogus answer
    6698             :      * when the extreme value has been deleted (unless the deletion was quite
    6699             :      * recent); that case motivates not using SnapshotAny here.
    6700             :      *
    6701             :      * A crucial point here is that SnapshotNonVacuumable, with
    6702             :      * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
    6703             :      * condition that the indexscan will use to decide that index entries are
    6704             :      * killable (see heap_hot_search_buffer()).  Therefore, if the snapshot
    6705             :      * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
    6706             :      * have to continue scanning past it, we know that the indexscan will mark
    6707             :      * that index entry killed.  That means that the next
    6708             :      * get_actual_variable_endpoint() call will not have to re-consider that
    6709             :      * index entry.  In this way we avoid repetitive work when this function
    6710             :      * is used a lot during planning.
    6711             :      *
    6712             :      * But using SnapshotNonVacuumable creates a hazard of its own.  In a
    6713             :      * recently-created index, some index entries may point at "broken" HOT
    6714             :      * chains in which not all the tuple versions contain data matching the
    6715             :      * index entry.  The live tuple version(s) certainly do match the index,
    6716             :      * but SnapshotNonVacuumable can accept recently-dead tuple versions that
    6717             :      * don't match.  Hence, if we took data from the selected heap tuple, we
    6718             :      * might get a bogus answer that's not close to the index extremal value,
    6719             :      * or could even be NULL.  We avoid this hazard because we take the data
    6720             :      * from the index entry not the heap.
    6721             :      *
    6722             :      * Despite all this care, there are situations where we might find many
    6723             :      * non-visible tuples near the end of the index.  We don't want to expend
    6724             :      * a huge amount of time here, so we give up once we've read too many heap
    6725             :      * pages.  When we fail for that reason, the caller will end up using
    6726             :      * whatever extremal value is recorded in pg_statistic.
    6727             :      */
    6728      122876 :     InitNonVacuumableSnapshot(SnapshotNonVacuumable,
    6729             :                               GlobalVisTestFor(heapRel));
    6730             : 
    6731      122876 :     index_scan = index_beginscan(heapRel, indexRel,
    6732             :                                  &SnapshotNonVacuumable, NULL,
    6733             :                                  1, 0);
    6734             :     /* Set it up for index-only scan */
    6735      122876 :     index_scan->xs_want_itup = true;
    6736      122876 :     index_rescan(index_scan, scankeys, 1, NULL, 0);
    6737             : 
    6738             :     /* Fetch first/next tuple in specified direction */
    6739      159230 :     while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
    6740             :     {
    6741      159230 :         BlockNumber block = ItemPointerGetBlockNumber(tid);
    6742             : 
    6743      159230 :         if (!VM_ALL_VISIBLE(heapRel,
    6744             :                             block,
    6745             :                             &vmbuffer))
    6746             :         {
    6747             :             /* Rats, we have to visit the heap to check visibility */
    6748      116976 :             if (!index_fetch_heap(index_scan, tableslot))
    6749             :             {
    6750             :                 /*
    6751             :                  * No visible tuple for this index entry, so we need to
    6752             :                  * advance to the next entry.  Before doing so, count heap
    6753             :                  * page fetches and give up if we've done too many.
    6754             :                  *
    6755             :                  * We don't charge a page fetch if this is the same heap page
    6756             :                  * as the previous tuple.  This is on the conservative side,
    6757             :                  * since other recently-accessed pages are probably still in
    6758             :                  * buffers too; but it's good enough for this heuristic.
    6759             :                  */
    6760             : #define VISITED_PAGES_LIMIT 100
    6761             : 
    6762       36354 :                 if (block != last_heap_block)
    6763             :                 {
    6764        3402 :                     last_heap_block = block;
    6765        3402 :                     n_visited_heap_pages++;
    6766        3402 :                     if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
    6767           0 :                         break;
    6768             :                 }
    6769             : 
    6770       36354 :                 continue;       /* no visible tuple, try next index entry */
    6771             :             }
    6772             : 
    6773             :             /* We don't actually need the heap tuple for anything */
    6774       80622 :             ExecClearTuple(tableslot);
    6775             : 
    6776             :             /*
    6777             :              * We don't care whether there's more than one visible tuple in
    6778             :              * the HOT chain; if any are visible, that's good enough.
    6779             :              */
    6780             :         }
    6781             : 
    6782             :         /*
    6783             :          * We expect that the index will return data in IndexTuple not
    6784             :          * HeapTuple format.
    6785             :          */
    6786      122876 :         if (!index_scan->xs_itup)
    6787           0 :             elog(ERROR, "no data returned for index-only scan");
    6788             : 
    6789             :         /*
    6790             :          * We do not yet support recheck here.
    6791             :          */
    6792      122876 :         if (index_scan->xs_recheck)
    6793           0 :             break;
    6794             : 
    6795             :         /* OK to deconstruct the index tuple */
    6796      122876 :         index_deform_tuple(index_scan->xs_itup,
    6797             :                            index_scan->xs_itupdesc,
    6798             :                            values, isnull);
    6799             : 
    6800             :         /* Shouldn't have got a null, but be careful */
    6801      122876 :         if (isnull[0])
    6802           0 :             elog(ERROR, "found unexpected null value in index \"%s\"",
    6803             :                  RelationGetRelationName(indexRel));
    6804             : 
    6805             :         /* Copy the index column value out to caller's context */
    6806      122876 :         oldcontext = MemoryContextSwitchTo(outercontext);
    6807      122876 :         *endpointDatum = datumCopy(values[0], typByVal, typLen);
    6808      122876 :         MemoryContextSwitchTo(oldcontext);
    6809      122876 :         have_data = true;
    6810      122876 :         break;
    6811             :     }
    6812             : 
    6813      122876 :     if (vmbuffer != InvalidBuffer)
    6814      109842 :         ReleaseBuffer(vmbuffer);
    6815      122876 :     index_endscan(index_scan);
    6816             : 
    6817      122876 :     return have_data;
    6818             : }
    6819             : 
    6820             : /*
    6821             :  * find_join_input_rel
    6822             :  *      Look up the input relation for a join.
    6823             :  *
    6824             :  * We assume that the input relation's RelOptInfo must have been constructed
    6825             :  * already.
    6826             :  */
    6827             : static RelOptInfo *
    6828       10682 : find_join_input_rel(PlannerInfo *root, Relids relids)
    6829             : {
    6830       10682 :     RelOptInfo *rel = NULL;
    6831             : 
    6832       10682 :     if (!bms_is_empty(relids))
    6833             :     {
    6834             :         int         relid;
    6835             : 
    6836       10682 :         if (bms_get_singleton_member(relids, &relid))
    6837       10378 :             rel = find_base_rel(root, relid);
    6838             :         else
    6839         304 :             rel = find_join_rel(root, relids);
    6840             :     }
    6841             : 
    6842       10682 :     if (rel == NULL)
    6843           0 :         elog(ERROR, "could not find RelOptInfo for given relids");
    6844             : 
    6845       10682 :     return rel;
    6846             : }
    6847             : 
    6848             : 
    6849             : /*-------------------------------------------------------------------------
    6850             :  *
    6851             :  * Index cost estimation functions
    6852             :  *
    6853             :  *-------------------------------------------------------------------------
    6854             :  */
    6855             : 
    6856             : /*
    6857             :  * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
    6858             :  */
    6859             : List *
    6860      765058 : get_quals_from_indexclauses(List *indexclauses)
    6861             : {
    6862      765058 :     List       *result = NIL;
    6863             :     ListCell   *lc;
    6864             : 
    6865     1347360 :     foreach(lc, indexclauses)
    6866             :     {
    6867      582302 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    6868             :         ListCell   *lc2;
    6869             : 
    6870     1167516 :         foreach(lc2, iclause->indexquals)
    6871             :         {
    6872      585214 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    6873             : 
    6874      585214 :             result = lappend(result, rinfo);
    6875             :         }
    6876             :     }
    6877      765058 :     return result;
    6878             : }
    6879             : 
    6880             : /*
    6881             :  * Compute the total evaluation cost of the comparison operands in a list
    6882             :  * of index qual expressions.  Since we know these will be evaluated just
    6883             :  * once per scan, there's no need to distinguish startup from per-row cost.
    6884             :  *
    6885             :  * This can be used either on the result of get_quals_from_indexclauses(),
    6886             :  * or directly on an indexorderbys list.  In both cases, we expect that the
    6887             :  * index key expression is on the left side of binary clauses.
    6888             :  */
    6889             : Cost
    6890     1517126 : index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
    6891             : {
    6892     1517126 :     Cost        qual_arg_cost = 0;
    6893             :     ListCell   *lc;
    6894             : 
    6895     2102802 :     foreach(lc, indexquals)
    6896             :     {
    6897      585676 :         Expr       *clause = (Expr *) lfirst(lc);
    6898             :         Node       *other_operand;
    6899             :         QualCost    index_qual_cost;
    6900             : 
    6901             :         /*
    6902             :          * Index quals will have RestrictInfos, indexorderbys won't.  Look
    6903             :          * through RestrictInfo if present.
    6904             :          */
    6905      585676 :         if (IsA(clause, RestrictInfo))
    6906      585202 :             clause = ((RestrictInfo *) clause)->clause;
    6907             : 
    6908      585676 :         if (IsA(clause, OpExpr))
    6909             :         {
    6910      571476 :             OpExpr     *op = (OpExpr *) clause;
    6911             : 
    6912      571476 :             other_operand = (Node *) lsecond(op->args);
    6913             :         }
    6914       14200 :         else if (IsA(clause, RowCompareExpr))
    6915             :         {
    6916         396 :             RowCompareExpr *rc = (RowCompareExpr *) clause;
    6917             : 
    6918         396 :             other_operand = (Node *) rc->rargs;
    6919             :         }
    6920       13804 :         else if (IsA(clause, ScalarArrayOpExpr))
    6921             :         {
    6922       10870 :             ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    6923             : 
    6924       10870 :             other_operand = (Node *) lsecond(saop->args);
    6925             :         }
    6926        2934 :         else if (IsA(clause, NullTest))
    6927             :         {
    6928        2934 :             other_operand = NULL;
    6929             :         }
    6930             :         else
    6931             :         {
    6932           0 :             elog(ERROR, "unsupported indexqual type: %d",
    6933             :                  (int) nodeTag(clause));
    6934             :             other_operand = NULL;   /* keep compiler quiet */
    6935             :         }
    6936             : 
    6937      585676 :         cost_qual_eval_node(&index_qual_cost, other_operand, root);
    6938      585676 :         qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
    6939             :     }
    6940     1517126 :     return qual_arg_cost;
    6941             : }
    6942             : 
    6943             : void
    6944      752080 : genericcostestimate(PlannerInfo *root,
    6945             :                     IndexPath *path,
    6946             :                     double loop_count,
    6947             :                     GenericCosts *costs)
    6948             : {
    6949      752080 :     IndexOptInfo *index = path->indexinfo;
    6950      752080 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    6951      752080 :     List       *indexOrderBys = path->indexorderbys;
    6952             :     Cost        indexStartupCost;
    6953             :     Cost        indexTotalCost;
    6954             :     Selectivity indexSelectivity;
    6955             :     double      indexCorrelation;
    6956             :     double      numIndexPages;
    6957             :     double      numIndexTuples;
    6958             :     double      spc_random_page_cost;
    6959             :     double      num_sa_scans;
    6960             :     double      num_outer_scans;
    6961             :     double      num_scans;
    6962             :     double      qual_op_cost;
    6963             :     double      qual_arg_cost;
    6964             :     List       *selectivityQuals;
    6965             :     ListCell   *l;
    6966             : 
    6967             :     /*
    6968             :      * If the index is partial, AND the index predicate with the explicitly
    6969             :      * given indexquals to produce a more accurate idea of the index
    6970             :      * selectivity.
    6971             :      */
    6972      752080 :     selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
    6973             : 
    6974             :     /*
    6975             :      * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
    6976             :      * just assume that the number of index descents is the number of distinct
    6977             :      * combinations of array elements from all of the scan's SAOP clauses.
    6978             :      */
    6979      752080 :     num_sa_scans = costs->num_sa_scans;
    6980      752080 :     if (num_sa_scans < 1)
    6981             :     {
    6982        7762 :         num_sa_scans = 1;
    6983       16238 :         foreach(l, indexQuals)
    6984             :         {
    6985        8476 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
    6986             : 
    6987        8476 :             if (IsA(rinfo->clause, ScalarArrayOpExpr))
    6988             :             {
    6989          26 :                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
    6990          26 :                 double      alength = estimate_array_length(root, lsecond(saop->args));
    6991             : 
    6992          26 :                 if (alength > 1)
    6993          26 :                     num_sa_scans *= alength;
    6994             :             }
    6995             :         }
    6996             :     }
    6997             : 
    6998             :     /* Estimate the fraction of main-table tuples that will be visited */
    6999      752080 :     indexSelectivity = clauselist_selectivity(root, selectivityQuals,
    7000      752080 :                                               index->rel->relid,
    7001             :                                               JOIN_INNER,
    7002             :                                               NULL);
    7003             : 
    7004             :     /*
    7005             :      * If caller didn't give us an estimate, estimate the number of index
    7006             :      * tuples that will be visited.  We do it in this rather peculiar-looking
    7007             :      * way in order to get the right answer for partial indexes.
    7008             :      */
    7009      752080 :     numIndexTuples = costs->numIndexTuples;
    7010      752080 :     if (numIndexTuples <= 0.0)
    7011             :     {
    7012       76230 :         numIndexTuples = indexSelectivity * index->rel->tuples;
    7013             : 
    7014             :         /*
    7015             :          * The above calculation counts all the tuples visited across all
    7016             :          * scans induced by ScalarArrayOpExpr nodes.  We want to consider the
    7017             :          * average per-indexscan number, so adjust.  This is a handy place to
    7018             :          * round to integer, too.  (If caller supplied tuple estimate, it's
    7019             :          * responsible for handling these considerations.)
    7020             :          */
    7021       76230 :         numIndexTuples = rint(numIndexTuples / num_sa_scans);
    7022             :     }
    7023             : 
    7024             :     /*
    7025             :      * We can bound the number of tuples by the index size in any case. Also,
    7026             :      * always estimate at least one tuple is touched, even when
    7027             :      * indexSelectivity estimate is tiny.
    7028             :      */
    7029      752080 :     if (numIndexTuples > index->tuples)
    7030        5884 :         numIndexTuples = index->tuples;
    7031      752080 :     if (numIndexTuples < 1.0)
    7032       76332 :         numIndexTuples = 1.0;
    7033             : 
    7034             :     /*
    7035             :      * Estimate the number of index pages that will be retrieved.
    7036             :      *
    7037             :      * We use the simplistic method of taking a pro-rata fraction of the total
    7038             :      * number of index pages.  In effect, this counts only leaf pages and not
    7039             :      * any overhead such as index metapage or upper tree levels.
    7040             :      *
    7041             :      * In practice access to upper index levels is often nearly free because
    7042             :      * those tend to stay in cache under load; moreover, the cost involved is
    7043             :      * highly dependent on index type.  We therefore ignore such costs here
    7044             :      * and leave it to the caller to add a suitable charge if needed.
    7045             :      */
    7046      752080 :     if (index->pages > 1 && index->tuples > 1)
    7047      704368 :         numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
    7048             :     else
    7049       47712 :         numIndexPages = 1.0;
    7050             : 
    7051             :     /* fetch estimated page cost for tablespace containing index */
    7052      752080 :     get_tablespace_page_costs(index->reltablespace,
    7053             :                               &spc_random_page_cost,
    7054             :                               NULL);
    7055             : 
    7056             :     /*
    7057             :      * Now compute the disk access costs.
    7058             :      *
    7059             :      * The above calculations are all per-index-scan.  However, if we are in a
    7060             :      * nestloop inner scan, we can expect the scan to be repeated (with
    7061             :      * different search keys) for each row of the outer relation.  Likewise,
    7062             :      * ScalarArrayOpExpr quals result in multiple index scans.  This creates
    7063             :      * the potential for cache effects to reduce the number of disk page
    7064             :      * fetches needed.  We want to estimate the average per-scan I/O cost in
    7065             :      * the presence of caching.
    7066             :      *
    7067             :      * We use the Mackert-Lohman formula (see costsize.c for details) to
    7068             :      * estimate the total number of page fetches that occur.  While this
    7069             :      * wasn't what it was designed for, it seems a reasonable model anyway.
    7070             :      * Note that we are counting pages not tuples anymore, so we take N = T =
    7071             :      * index size, as if there were one "tuple" per page.
    7072             :      */
    7073      752080 :     num_outer_scans = loop_count;
    7074      752080 :     num_scans = num_sa_scans * num_outer_scans;
    7075             : 
    7076      752080 :     if (num_scans > 1)
    7077             :     {
    7078             :         double      pages_fetched;
    7079             : 
    7080             :         /* total page fetches ignoring cache effects */
    7081       84146 :         pages_fetched = numIndexPages * num_scans;
    7082             : 
    7083             :         /* use Mackert and Lohman formula to adjust for cache effects */
    7084       84146 :         pages_fetched = index_pages_fetched(pages_fetched,
    7085             :                                             index->pages,
    7086       84146 :                                             (double) index->pages,
    7087             :                                             root);
    7088             : 
    7089             :         /*
    7090             :          * Now compute the total disk access cost, and then report a pro-rated
    7091             :          * share for each outer scan.  (Don't pro-rate for ScalarArrayOpExpr,
    7092             :          * since that's internal to the indexscan.)
    7093             :          */
    7094       84146 :         indexTotalCost = (pages_fetched * spc_random_page_cost)
    7095             :             / num_outer_scans;
    7096             :     }
    7097             :     else
    7098             :     {
    7099             :         /*
    7100             :          * For a single index scan, we just charge spc_random_page_cost per
    7101             :          * page touched.
    7102             :          */
    7103      667934 :         indexTotalCost = numIndexPages * spc_random_page_cost;
    7104             :     }
    7105             : 
    7106             :     /*
    7107             :      * CPU cost: any complex expressions in the indexquals will need to be
    7108             :      * evaluated once at the start of the scan to reduce them to runtime keys
    7109             :      * to pass to the index AM (see nodeIndexscan.c).  We model the per-tuple
    7110             :      * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
    7111             :      * indexqual operator.  Because we have numIndexTuples as a per-scan
    7112             :      * number, we have to multiply by num_sa_scans to get the correct result
    7113             :      * for ScalarArrayOpExpr cases.  Similarly add in costs for any index
    7114             :      * ORDER BY expressions.
    7115             :      *
    7116             :      * Note: this neglects the possible costs of rechecking lossy operators.
    7117             :      * Detecting that that might be needed seems more expensive than it's
    7118             :      * worth, though, considering all the other inaccuracies here ...
    7119             :      */
    7120      752080 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
    7121      752080 :         index_other_operands_eval_cost(root, indexOrderBys);
    7122      752080 :     qual_op_cost = cpu_operator_cost *
    7123      752080 :         (list_length(indexQuals) + list_length(indexOrderBys));
    7124             : 
    7125      752080 :     indexStartupCost = qual_arg_cost;
    7126      752080 :     indexTotalCost += qual_arg_cost;
    7127      752080 :     indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
    7128             : 
    7129             :     /*
    7130             :      * Generic assumption about index correlation: there isn't any.
    7131             :      */
    7132      752080 :     indexCorrelation = 0.0;
    7133             : 
    7134             :     /*
    7135             :      * Return everything to caller.
    7136             :      */
    7137      752080 :     costs->indexStartupCost = indexStartupCost;
    7138      752080 :     costs->indexTotalCost = indexTotalCost;
    7139      752080 :     costs->indexSelectivity = indexSelectivity;
    7140      752080 :     costs->indexCorrelation = indexCorrelation;
    7141      752080 :     costs->numIndexPages = numIndexPages;
    7142      752080 :     costs->numIndexTuples = numIndexTuples;
    7143      752080 :     costs->spc_random_page_cost = spc_random_page_cost;
    7144      752080 :     costs->num_sa_scans = num_sa_scans;
    7145      752080 : }
    7146             : 
    7147             : /*
    7148             :  * If the index is partial, add its predicate to the given qual list.
    7149             :  *
    7150             :  * ANDing the index predicate with the explicitly given indexquals produces
    7151             :  * a more accurate idea of the index's selectivity.  However, we need to be
    7152             :  * careful not to insert redundant clauses, because clauselist_selectivity()
    7153             :  * is easily fooled into computing a too-low selectivity estimate.  Our
    7154             :  * approach is to add only the predicate clause(s) that cannot be proven to
    7155             :  * be implied by the given indexquals.  This successfully handles cases such
    7156             :  * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
    7157             :  * There are many other cases where we won't detect redundancy, leading to a
    7158             :  * too-low selectivity estimate, which will bias the system in favor of using
    7159             :  * partial indexes where possible.  That is not necessarily bad though.
    7160             :  *
    7161             :  * Note that indexQuals contains RestrictInfo nodes while the indpred
    7162             :  * does not, so the output list will be mixed.  This is OK for both
    7163             :  * predicate_implied_by() and clauselist_selectivity(), but might be
    7164             :  * problematic if the result were passed to other things.
    7165             :  */
    7166             : List *
    7167     1262442 : add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
    7168             : {
    7169     1262442 :     List       *predExtraQuals = NIL;
    7170             :     ListCell   *lc;
    7171             : 
    7172     1262442 :     if (index->indpred == NIL)
    7173     1260416 :         return indexQuals;
    7174             : 
    7175        4064 :     foreach(lc, index->indpred)
    7176             :     {
    7177        2038 :         Node       *predQual = (Node *) lfirst(lc);
    7178        2038 :         List       *oneQual = list_make1(predQual);
    7179             : 
    7180        2038 :         if (!predicate_implied_by(oneQual, indexQuals, false))
    7181        1836 :             predExtraQuals = list_concat(predExtraQuals, oneQual);
    7182             :     }
    7183        2026 :     return list_concat(predExtraQuals, indexQuals);
    7184             : }
    7185             : 
    7186             : /*
    7187             :  * Estimate correlation of btree index's first column.
    7188             :  *
    7189             :  * If we can get an estimate of the first column's ordering correlation C
    7190             :  * from pg_statistic, estimate the index correlation as C for a single-column
    7191             :  * index, or C * 0.75 for multiple columns.  The idea here is that multiple
    7192             :  * columns dilute the importance of the first column's ordering, but don't
    7193             :  * negate it entirely.
    7194             :  *
    7195             :  * We already filled in the stats tuple for *vardata when called.
    7196             :  */
    7197             : static double
    7198      566316 : btcost_correlation(IndexOptInfo *index, VariableStatData *vardata)
    7199             : {
    7200             :     Oid         sortop;
    7201             :     AttStatsSlot sslot;
    7202      566316 :     double      indexCorrelation = 0;
    7203             : 
    7204             :     Assert(HeapTupleIsValid(vardata->statsTuple));
    7205             : 
    7206      566316 :     sortop = get_opfamily_member(index->opfamily[0],
    7207      566316 :                                  index->opcintype[0],
    7208      566316 :                                  index->opcintype[0],
    7209             :                                  BTLessStrategyNumber);
    7210     1132632 :     if (OidIsValid(sortop) &&
    7211      566316 :         get_attstatsslot(&sslot, vardata->statsTuple,
    7212             :                          STATISTIC_KIND_CORRELATION, sortop,
    7213             :                          ATTSTATSSLOT_NUMBERS))
    7214             :     {
    7215             :         double      varCorrelation;
    7216             : 
    7217             :         Assert(sslot.nnumbers == 1);
    7218      559440 :         varCorrelation = sslot.numbers[0];
    7219             : 
    7220      559440 :         if (index->reverse_sort[0])
    7221           0 :             varCorrelation = -varCorrelation;
    7222             : 
    7223      559440 :         if (index->nkeycolumns > 1)
    7224      197698 :             indexCorrelation = varCorrelation * 0.75;
    7225             :         else
    7226      361742 :             indexCorrelation = varCorrelation;
    7227             : 
    7228      559440 :         free_attstatsslot(&sslot);
    7229             :     }
    7230             : 
    7231      566316 :     return indexCorrelation;
    7232             : }
    7233             : 
    7234             : void
    7235      744318 : btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7236             :                Cost *indexStartupCost, Cost *indexTotalCost,
    7237             :                Selectivity *indexSelectivity, double *indexCorrelation,
    7238             :                double *indexPages)
    7239             : {
    7240      744318 :     IndexOptInfo *index = path->indexinfo;
    7241      744318 :     GenericCosts costs = {0};
    7242      744318 :     VariableStatData vardata = {0};
    7243             :     double      numIndexTuples;
    7244             :     Cost        descentCost;
    7245             :     List       *indexBoundQuals;
    7246             :     List       *indexSkipQuals;
    7247             :     int         indexcol;
    7248             :     bool        eqQualHere;
    7249             :     bool        found_row_compare;
    7250             :     bool        found_array;
    7251             :     bool        found_is_null_op;
    7252      744318 :     bool        have_correlation = false;
    7253             :     double      num_sa_scans;
    7254      744318 :     double      correlation = 0.0;
    7255             :     ListCell   *lc;
    7256             : 
    7257             :     /*
    7258             :      * For a btree scan, only leading '=' quals plus inequality quals for the
    7259             :      * immediately next attribute contribute to index selectivity (these are
    7260             :      * the "boundary quals" that determine the starting and stopping points of
    7261             :      * the index scan).  Additional quals can suppress visits to the heap, so
    7262             :      * it's OK to count them in indexSelectivity, but they should not count
    7263             :      * for estimating numIndexTuples.  So we must examine the given indexquals
    7264             :      * to find out which ones count as boundary quals.  We rely on the
    7265             :      * knowledge that they are given in index column order.  Note that nbtree
    7266             :      * preprocessing can add skip arrays that act as leading '=' quals in the
    7267             :      * absence of ordinary input '=' quals, so in practice _most_ input quals
    7268             :      * are able to act as index bound quals (which we take into account here).
    7269             :      *
    7270             :      * For a RowCompareExpr, we consider only the first column, just as
    7271             :      * rowcomparesel() does.
    7272             :      *
    7273             :      * If there's a SAOP or skip array in the quals, we'll actually perform up
    7274             :      * to N index descents (not just one), but the underlying array key's
    7275             :      * operator can be considered to act the same as it normally does.
    7276             :      */
    7277      744318 :     indexBoundQuals = NIL;
    7278      744318 :     indexSkipQuals = NIL;
    7279      744318 :     indexcol = 0;
    7280      744318 :     eqQualHere = false;
    7281      744318 :     found_row_compare = false;
    7282      744318 :     found_array = false;
    7283      744318 :     found_is_null_op = false;
    7284      744318 :     num_sa_scans = 1;
    7285     1273640 :     foreach(lc, path->indexclauses)
    7286             :     {
    7287      558336 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    7288             :         ListCell   *lc2;
    7289             : 
    7290      558336 :         if (indexcol < iclause->indexcol)
    7291             :         {
    7292       99504 :             double      num_sa_scans_prev_cols = num_sa_scans;
    7293             : 
    7294             :             /*
    7295             :              * Beginning of a new column's quals.
    7296             :              *
    7297             :              * Skip scans use skip arrays, which are ScalarArrayOp style
    7298             :              * arrays that generate their elements procedurally and on demand.
    7299             :              * Given a multi-column index on "(a, b)", and an SQL WHERE clause
    7300             :              * "WHERE b = 42", a skip scan will effectively use an indexqual
    7301             :              * "WHERE a = ANY('{every col a value}') AND b = 42".  (Obviously,
    7302             :              * the array on "a" must also return "IS NULL" matches, since our
    7303             :              * WHERE clause used no strict operator on "a").
    7304             :              *
    7305             :              * Here we consider how nbtree will backfill skip arrays for any
    7306             :              * index columns that lacked an '=' qual.  This maintains our
    7307             :              * num_sa_scans estimate, and determines if this new column (the
    7308             :              * "iclause->indexcol" column, not the prior "indexcol" column)
    7309             :              * can have its RestrictInfos/quals added to indexBoundQuals.
    7310             :              *
    7311             :              * We'll need to handle columns that have inequality quals, where
    7312             :              * the skip array generates values from a range constrained by the
    7313             :              * quals (not every possible value).  We've been maintaining
    7314             :              * indexSkipQuals to help with this; it will now contain all of
    7315             :              * the prior column's quals (that is, indexcol's quals) when they
    7316             :              * might be used for this.
    7317             :              */
    7318       99504 :             if (found_row_compare)
    7319             :             {
    7320             :                 /*
    7321             :                  * Skip arrays can't be added after a RowCompare input qual
    7322             :                  * due to limitations in nbtree
    7323             :                  */
    7324          24 :                 break;
    7325             :             }
    7326       99480 :             if (eqQualHere)
    7327             :             {
    7328             :                 /*
    7329             :                  * Don't need to add a skip array for an indexcol that already
    7330             :                  * has an '=' qual/equality constraint
    7331             :                  */
    7332       70658 :                 indexcol++;
    7333       70658 :                 indexSkipQuals = NIL;
    7334             :             }
    7335       99480 :             eqQualHere = false;
    7336             : 
    7337      102580 :             while (indexcol < iclause->indexcol)
    7338             :             {
    7339             :                 double      ndistinct;
    7340       32090 :                 bool        isdefault = true;
    7341             : 
    7342       32090 :                 found_array = true;
    7343             : 
    7344             :                 /*
    7345             :                  * A skipped attribute's ndistinct forms the basis of our
    7346             :                  * estimate of the total number of "array elements" used by
    7347             :                  * its skip array at runtime.  Look that up first.
    7348             :                  */
    7349       32090 :                 examine_indexcol_variable(root, index, indexcol, &vardata);
    7350       32090 :                 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
    7351             : 
    7352       32090 :                 if (indexcol == 0)
    7353             :                 {
    7354             :                     /*
    7355             :                      * Get an estimate of the leading column's correlation in
    7356             :                      * passing (avoids rereading variable stats below)
    7357             :                      */
    7358       28810 :                     if (HeapTupleIsValid(vardata.statsTuple))
    7359       21984 :                         correlation = btcost_correlation(index, &vardata);
    7360       28810 :                     have_correlation = true;
    7361             :                 }
    7362             : 
    7363       32090 :                 ReleaseVariableStats(vardata);
    7364             : 
    7365             :                 /*
    7366             :                  * If ndistinct is a default estimate, conservatively assume
    7367             :                  * that no skipping will happen at runtime
    7368             :                  */
    7369       32090 :                 if (isdefault)
    7370             :                 {
    7371        5330 :                     num_sa_scans = num_sa_scans_prev_cols;
    7372       28990 :                     break;      /* done building indexBoundQuals */
    7373             :                 }
    7374             : 
    7375             :                 /*
    7376             :                  * Apply indexcol's indexSkipQuals selectivity to ndistinct
    7377             :                  */
    7378       26760 :                 if (indexSkipQuals != NIL)
    7379             :                 {
    7380             :                     List       *partialSkipQuals;
    7381             :                     Selectivity ndistinctfrac;
    7382             : 
    7383             :                     /*
    7384             :                      * If the index is partial, AND the index predicate with
    7385             :                      * the index-bound quals to produce a more accurate idea
    7386             :                      * of the number of distinct values for prior indexcol
    7387             :                      */
    7388         664 :                     partialSkipQuals = add_predicate_to_index_quals(index,
    7389             :                                                                     indexSkipQuals);
    7390             : 
    7391         664 :                     ndistinctfrac = clauselist_selectivity(root, partialSkipQuals,
    7392         664 :                                                            index->rel->relid,
    7393             :                                                            JOIN_INNER,
    7394             :                                                            NULL);
    7395             : 
    7396             :                     /*
    7397             :                      * If ndistinctfrac is selective (on its own), the scan is
    7398             :                      * unlikely to benefit from repositioning itself using
    7399             :                      * later quals.  Do not allow iclause->indexcol's quals to
    7400             :                      * be added to indexBoundQuals (it would increase descent
    7401             :                      * costs, without lowering numIndexTuples costs by much).
    7402             :                      */
    7403         664 :                     if (ndistinctfrac < DEFAULT_RANGE_INEQ_SEL)
    7404             :                     {
    7405         372 :                         num_sa_scans = num_sa_scans_prev_cols;
    7406         372 :                         break;  /* done building indexBoundQuals */
    7407             :                     }
    7408             : 
    7409             :                     /* Adjust ndistinct downward */
    7410         292 :                     ndistinct = rint(ndistinct * ndistinctfrac);
    7411         292 :                     ndistinct = Max(ndistinct, 1);
    7412             :                 }
    7413             : 
    7414             :                 /*
    7415             :                  * When there's no inequality quals, account for the need to
    7416             :                  * find an initial value by counting -inf/+inf as a value.
    7417             :                  *
    7418             :                  * We don't charge anything extra for possible next/prior key
    7419             :                  * index probes, which are sometimes used to find the next
    7420             :                  * valid skip array element (ahead of using the located
    7421             :                  * element value to relocate the scan to the next position
    7422             :                  * that might contain matching tuples).  It seems hard to do
    7423             :                  * better here.  Use of the skip support infrastructure often
    7424             :                  * avoids most next/prior key probes.  But even when it can't,
    7425             :                  * there's a decent chance that most individual next/prior key
    7426             :                  * probes will locate a leaf page whose key space overlaps all
    7427             :                  * of the scan's keys (even the lower-order keys) -- which
    7428             :                  * also avoids the need for a separate, extra index descent.
    7429             :                  * Note also that these probes are much cheaper than non-probe
    7430             :                  * primitive index scans: they're reliably very selective.
    7431             :                  */
    7432       26388 :                 if (indexSkipQuals == NIL)
    7433       26096 :                     ndistinct += 1;
    7434             : 
    7435             :                 /*
    7436             :                  * Update num_sa_scans estimate by multiplying by ndistinct.
    7437             :                  *
    7438             :                  * We make the pessimistic assumption that there is no
    7439             :                  * naturally occurring cross-column correlation.  This is
    7440             :                  * often wrong, but it seems best to err on the side of not
    7441             :                  * expecting skipping to be helpful...
    7442             :                  */
    7443       26388 :                 num_sa_scans *= ndistinct;
    7444             : 
    7445             :                 /*
    7446             :                  * ...but back out of adding this latest group of 1 or more
    7447             :                  * skip arrays when num_sa_scans exceeds the total number of
    7448             :                  * index pages (revert to num_sa_scans from before indexcol).
    7449             :                  * This causes a sharp discontinuity in cost (as a function of
    7450             :                  * the indexcol's ndistinct), but that is representative of
    7451             :                  * actual runtime costs.
    7452             :                  *
    7453             :                  * Note that skipping is helpful when each primitive index
    7454             :                  * scan only manages to skip over 1 or 2 irrelevant leaf pages
    7455             :                  * on average.  Skip arrays bring savings in CPU costs due to
    7456             :                  * the scan not needing to evaluate indexquals against every
    7457             :                  * tuple, which can greatly exceed any savings in I/O costs.
    7458             :                  * This test is a test of whether num_sa_scans implies that
    7459             :                  * we're past the point where the ability to skip ceases to
    7460             :                  * lower the scan's costs (even qual evaluation CPU costs).
    7461             :                  */
    7462       26388 :                 if (index->pages < num_sa_scans)
    7463             :                 {
    7464       23288 :                     num_sa_scans = num_sa_scans_prev_cols;
    7465       23288 :                     break;      /* done building indexBoundQuals */
    7466             :                 }
    7467             : 
    7468        3100 :                 indexcol++;
    7469        3100 :                 indexSkipQuals = NIL;
    7470             :             }
    7471             : 
    7472             :             /*
    7473             :              * Finished considering the need to add skip arrays to bridge an
    7474             :              * initial eqQualHere gap between the old and new index columns
    7475             :              * (or there was no initial eqQualHere gap in the first place).
    7476             :              *
    7477             :              * If an initial gap could not be bridged, then new column's quals
    7478             :              * (i.e. iclause->indexcol's quals) won't go into indexBoundQuals,
    7479             :              * and so won't affect our final numIndexTuples estimate.
    7480             :              */
    7481       99480 :             if (indexcol != iclause->indexcol)
    7482       28990 :                 break;          /* done building indexBoundQuals */
    7483             :         }
    7484             : 
    7485             :         Assert(indexcol == iclause->indexcol);
    7486             : 
    7487             :         /* Examine each indexqual associated with this index clause */
    7488     1061384 :         foreach(lc2, iclause->indexquals)
    7489             :         {
    7490      532062 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    7491      532062 :             Expr       *clause = rinfo->clause;
    7492      532062 :             Oid         clause_op = InvalidOid;
    7493             :             int         op_strategy;
    7494             : 
    7495      532062 :             if (IsA(clause, OpExpr))
    7496             :             {
    7497      518934 :                 OpExpr     *op = (OpExpr *) clause;
    7498             : 
    7499      518934 :                 clause_op = op->opno;
    7500             :             }
    7501       13128 :             else if (IsA(clause, RowCompareExpr))
    7502             :             {
    7503         396 :                 RowCompareExpr *rc = (RowCompareExpr *) clause;
    7504             : 
    7505         396 :                 clause_op = linitial_oid(rc->opnos);
    7506         396 :                 found_row_compare = true;
    7507             :             }
    7508       12732 :             else if (IsA(clause, ScalarArrayOpExpr))
    7509             :             {
    7510       10442 :                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    7511       10442 :                 Node       *other_operand = (Node *) lsecond(saop->args);
    7512       10442 :                 double      alength = estimate_array_length(root, other_operand);
    7513             : 
    7514       10442 :                 clause_op = saop->opno;
    7515       10442 :                 found_array = true;
    7516             :                 /* estimate SA descents by indexBoundQuals only */
    7517       10442 :                 if (alength > 1)
    7518       10242 :                     num_sa_scans *= alength;
    7519             :             }
    7520        2290 :             else if (IsA(clause, NullTest))
    7521             :             {
    7522        2290 :                 NullTest   *nt = (NullTest *) clause;
    7523             : 
    7524        2290 :                 if (nt->nulltesttype == IS_NULL)
    7525             :                 {
    7526         240 :                     found_is_null_op = true;
    7527             :                     /* IS NULL is like = for selectivity/skip scan purposes */
    7528         240 :                     eqQualHere = true;
    7529             :                 }
    7530             :             }
    7531             :             else
    7532           0 :                 elog(ERROR, "unsupported indexqual type: %d",
    7533             :                      (int) nodeTag(clause));
    7534             : 
    7535             :             /* check for equality operator */
    7536      532062 :             if (OidIsValid(clause_op))
    7537             :             {
    7538      529772 :                 op_strategy = get_op_opfamily_strategy(clause_op,
    7539      529772 :                                                        index->opfamily[indexcol]);
    7540             :                 Assert(op_strategy != 0);   /* not a member of opfamily?? */
    7541      529772 :                 if (op_strategy == BTEqualStrategyNumber)
    7542      503436 :                     eqQualHere = true;
    7543             :             }
    7544             : 
    7545      532062 :             indexBoundQuals = lappend(indexBoundQuals, rinfo);
    7546             : 
    7547             :             /*
    7548             :              * We apply inequality selectivities to estimate index descent
    7549             :              * costs with scans that use skip arrays.  Save this indexcol's
    7550             :              * RestrictInfos if it looks like they'll be needed for that.
    7551             :              */
    7552      532062 :             if (!eqQualHere && !found_row_compare &&
    7553       27288 :                 indexcol < index->nkeycolumns - 1)
    7554        5706 :                 indexSkipQuals = lappend(indexSkipQuals, rinfo);
    7555             :         }
    7556             :     }
    7557             : 
    7558             :     /*
    7559             :      * If index is unique and we found an '=' clause for each column, we can
    7560             :      * just assume numIndexTuples = 1 and skip the expensive
    7561             :      * clauselist_selectivity calculations.  However, an array or NullTest
    7562             :      * always invalidates that theory (even when eqQualHere has been set).
    7563             :      */
    7564      744318 :     if (index->unique &&
    7565      598762 :         indexcol == index->nkeycolumns - 1 &&
    7566      242900 :         eqQualHere &&
    7567      242900 :         !found_array &&
    7568      236916 :         !found_is_null_op)
    7569      236868 :         numIndexTuples = 1.0;
    7570             :     else
    7571             :     {
    7572             :         List       *selectivityQuals;
    7573             :         Selectivity btreeSelectivity;
    7574             : 
    7575             :         /*
    7576             :          * If the index is partial, AND the index predicate with the
    7577             :          * index-bound quals to produce a more accurate idea of the number of
    7578             :          * rows covered by the bound conditions.
    7579             :          */
    7580      507450 :         selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
    7581             : 
    7582      507450 :         btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
    7583      507450 :                                                   index->rel->relid,
    7584             :                                                   JOIN_INNER,
    7585             :                                                   NULL);
    7586      507450 :         numIndexTuples = btreeSelectivity * index->rel->tuples;
    7587             : 
    7588             :         /*
    7589             :          * btree automatically combines individual array element primitive
    7590             :          * index scans whenever the tuples covered by the next set of array
    7591             :          * keys are close to tuples covered by the current set.  That puts a
    7592             :          * natural ceiling on the worst case number of descents -- there
    7593             :          * cannot possibly be more than one descent per leaf page scanned.
    7594             :          *
    7595             :          * Clamp the number of descents to at most 1/3 the number of index
    7596             :          * pages.  This avoids implausibly high estimates with low selectivity
    7597             :          * paths, where scans usually require only one or two descents.  This
    7598             :          * is most likely to help when there are several SAOP clauses, where
    7599             :          * naively accepting the total number of distinct combinations of
    7600             :          * array elements as the number of descents would frequently lead to
    7601             :          * wild overestimates.
    7602             :          *
    7603             :          * We somewhat arbitrarily don't just make the cutoff the total number
    7604             :          * of leaf pages (we make it 1/3 the total number of pages instead) to
    7605             :          * give the btree code credit for its ability to continue on the leaf
    7606             :          * level with low selectivity scans.
    7607             :          *
    7608             :          * Note: num_sa_scans includes both ScalarArrayOp array elements and
    7609             :          * skip array elements whose qual affects our numIndexTuples estimate.
    7610             :          */
    7611      507450 :         num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
    7612      507450 :         num_sa_scans = Max(num_sa_scans, 1);
    7613             : 
    7614             :         /*
    7615             :          * As in genericcostestimate(), we have to adjust for any array quals
    7616             :          * included in indexBoundQuals, and then round to integer.
    7617             :          *
    7618             :          * It is tempting to make genericcostestimate behave as if array
    7619             :          * clauses work in almost the same way as scalar operators during
    7620             :          * btree scans, making the top-level scan look like a continuous scan
    7621             :          * (as opposed to num_sa_scans-many primitive index scans).  After
    7622             :          * all, btree scans mostly work like that at runtime.  However, such a
    7623             :          * scheme would badly bias genericcostestimate's simplistic approach
    7624             :          * to calculating numIndexPages through prorating.
    7625             :          *
    7626             :          * Stick with the approach taken by non-native SAOP scans for now.
    7627             :          * genericcostestimate will use the Mackert-Lohman formula to
    7628             :          * compensate for repeat page fetches, even though that definitely
    7629             :          * won't happen during btree scans (not for leaf pages, at least).
    7630             :          * We're usually very pessimistic about the number of primitive index
    7631             :          * scans that will be required, but it's not clear how to do better.
    7632             :          */
    7633      507450 :         numIndexTuples = rint(numIndexTuples / num_sa_scans);
    7634             :     }
    7635             : 
    7636             :     /*
    7637             :      * Now do generic index cost estimation.
    7638             :      */
    7639      744318 :     costs.numIndexTuples = numIndexTuples;
    7640      744318 :     costs.num_sa_scans = num_sa_scans;
    7641             : 
    7642      744318 :     genericcostestimate(root, path, loop_count, &costs);
    7643             : 
    7644             :     /*
    7645             :      * Add a CPU-cost component to represent the costs of initial btree
    7646             :      * descent.  We don't charge any I/O cost for touching upper btree levels,
    7647             :      * since they tend to stay in cache, but we still have to do about log2(N)
    7648             :      * comparisons to descend a btree of N leaf tuples.  We charge one
    7649             :      * cpu_operator_cost per comparison.
    7650             :      *
    7651             :      * If there are SAOP or skip array keys, charge this once per estimated
    7652             :      * index descent.  The ones after the first one are not startup cost so
    7653             :      * far as the overall plan goes, so just add them to "total" cost.
    7654             :      */
    7655      744318 :     if (index->tuples > 1)        /* avoid computing log(0) */
    7656             :     {
    7657      705386 :         descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
    7658      705386 :         costs.indexStartupCost += descentCost;
    7659      705386 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7660             :     }
    7661             : 
    7662             :     /*
    7663             :      * Even though we're not charging I/O cost for touching upper btree pages,
    7664             :      * it's still reasonable to charge some CPU cost per page descended
    7665             :      * through.  Moreover, if we had no such charge at all, bloated indexes
    7666             :      * would appear to have the same search cost as unbloated ones, at least
    7667             :      * in cases where only a single leaf page is expected to be visited.  This
    7668             :      * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
    7669             :      * touched.  The number of such pages is btree tree height plus one (ie,
    7670             :      * we charge for the leaf page too).  As above, charge once per estimated
    7671             :      * SAOP/skip array descent.
    7672             :      */
    7673      744318 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    7674      744318 :     costs.indexStartupCost += descentCost;
    7675      744318 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7676             : 
    7677      744318 :     if (!have_correlation)
    7678             :     {
    7679      715508 :         examine_indexcol_variable(root, index, 0, &vardata);
    7680      715508 :         if (HeapTupleIsValid(vardata.statsTuple))
    7681      544332 :             costs.indexCorrelation = btcost_correlation(index, &vardata);
    7682      715508 :         ReleaseVariableStats(vardata);
    7683             :     }
    7684             :     else
    7685             :     {
    7686             :         /* btcost_correlation already called earlier on */
    7687       28810 :         costs.indexCorrelation = correlation;
    7688             :     }
    7689             : 
    7690      744318 :     *indexStartupCost = costs.indexStartupCost;
    7691      744318 :     *indexTotalCost = costs.indexTotalCost;
    7692      744318 :     *indexSelectivity = costs.indexSelectivity;
    7693      744318 :     *indexCorrelation = costs.indexCorrelation;
    7694      744318 :     *indexPages = costs.numIndexPages;
    7695      744318 : }
    7696             : 
    7697             : void
    7698         410 : hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7699             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    7700             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    7701             :                  double *indexPages)
    7702             : {
    7703         410 :     GenericCosts costs = {0};
    7704             : 
    7705         410 :     genericcostestimate(root, path, loop_count, &costs);
    7706             : 
    7707             :     /*
    7708             :      * A hash index has no descent costs as such, since the index AM can go
    7709             :      * directly to the target bucket after computing the hash value.  There
    7710             :      * are a couple of other hash-specific costs that we could conceivably add
    7711             :      * here, though:
    7712             :      *
    7713             :      * Ideally we'd charge spc_random_page_cost for each page in the target
    7714             :      * bucket, not just the numIndexPages pages that genericcostestimate
    7715             :      * thought we'd visit.  However in most cases we don't know which bucket
    7716             :      * that will be.  There's no point in considering the average bucket size
    7717             :      * because the hash AM makes sure that's always one page.
    7718             :      *
    7719             :      * Likewise, we could consider charging some CPU for each index tuple in
    7720             :      * the bucket, if we knew how many there were.  But the per-tuple cost is
    7721             :      * just a hash value comparison, not a general datatype-dependent
    7722             :      * comparison, so any such charge ought to be quite a bit less than
    7723             :      * cpu_operator_cost; which makes it probably not worth worrying about.
    7724             :      *
    7725             :      * A bigger issue is that chance hash-value collisions will result in
    7726             :      * wasted probes into the heap.  We don't currently attempt to model this
    7727             :      * cost on the grounds that it's rare, but maybe it's not rare enough.
    7728             :      * (Any fix for this ought to consider the generic lossy-operator problem,
    7729             :      * though; it's not entirely hash-specific.)
    7730             :      */
    7731             : 
    7732         410 :     *indexStartupCost = costs.indexStartupCost;
    7733         410 :     *indexTotalCost = costs.indexTotalCost;
    7734         410 :     *indexSelectivity = costs.indexSelectivity;
    7735         410 :     *indexCorrelation = costs.indexCorrelation;
    7736         410 :     *indexPages = costs.numIndexPages;
    7737         410 : }
    7738             : 
    7739             : void
    7740        4756 : gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7741             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    7742             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    7743             :                  double *indexPages)
    7744             : {
    7745        4756 :     IndexOptInfo *index = path->indexinfo;
    7746        4756 :     GenericCosts costs = {0};
    7747             :     Cost        descentCost;
    7748             : 
    7749        4756 :     genericcostestimate(root, path, loop_count, &costs);
    7750             : 
    7751             :     /*
    7752             :      * We model index descent costs similarly to those for btree, but to do
    7753             :      * that we first need an idea of the tree height.  We somewhat arbitrarily
    7754             :      * assume that the fanout is 100, meaning the tree height is at most
    7755             :      * log100(index->pages).
    7756             :      *
    7757             :      * Although this computation isn't really expensive enough to require
    7758             :      * caching, we might as well use index->tree_height to cache it.
    7759             :      */
    7760        4756 :     if (index->tree_height < 0) /* unknown? */
    7761             :     {
    7762        4742 :         if (index->pages > 1) /* avoid computing log(0) */
    7763        2712 :             index->tree_height = (int) (log(index->pages) / log(100.0));
    7764             :         else
    7765        2030 :             index->tree_height = 0;
    7766             :     }
    7767             : 
    7768             :     /*
    7769             :      * Add a CPU-cost component to represent the costs of initial descent. We
    7770             :      * just use log(N) here not log2(N) since the branching factor isn't
    7771             :      * necessarily two anyway.  As for btree, charge once per SA scan.
    7772             :      */
    7773        4756 :     if (index->tuples > 1)        /* avoid computing log(0) */
    7774             :     {
    7775        4756 :         descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
    7776        4756 :         costs.indexStartupCost += descentCost;
    7777        4756 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7778             :     }
    7779             : 
    7780             :     /*
    7781             :      * Likewise add a per-page charge, calculated the same as for btrees.
    7782             :      */
    7783        4756 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    7784        4756 :     costs.indexStartupCost += descentCost;
    7785        4756 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7786             : 
    7787        4756 :     *indexStartupCost = costs.indexStartupCost;
    7788        4756 :     *indexTotalCost = costs.indexTotalCost;
    7789        4756 :     *indexSelectivity = costs.indexSelectivity;
    7790        4756 :     *indexCorrelation = costs.indexCorrelation;
    7791        4756 :     *indexPages = costs.numIndexPages;
    7792        4756 : }
    7793             : 
    7794             : void
    7795        1784 : spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7796             :                 Cost *indexStartupCost, Cost *indexTotalCost,
    7797             :                 Selectivity *indexSelectivity, double *indexCorrelation,
    7798             :                 double *indexPages)
    7799             : {
    7800        1784 :     IndexOptInfo *index = path->indexinfo;
    7801        1784 :     GenericCosts costs = {0};
    7802             :     Cost        descentCost;
    7803             : 
    7804        1784 :     genericcostestimate(root, path, loop_count, &costs);
    7805             : 
    7806             :     /*
    7807             :      * We model index descent costs similarly to those for btree, but to do
    7808             :      * that we first need an idea of the tree height.  We somewhat arbitrarily
    7809             :      * assume that the fanout is 100, meaning the tree height is at most
    7810             :      * log100(index->pages).
    7811             :      *
    7812             :      * Although this computation isn't really expensive enough to require
    7813             :      * caching, we might as well use index->tree_height to cache it.
    7814             :      */
    7815        1784 :     if (index->tree_height < 0) /* unknown? */
    7816             :     {
    7817        1778 :         if (index->pages > 1) /* avoid computing log(0) */
    7818        1778 :             index->tree_height = (int) (log(index->pages) / log(100.0));
    7819             :         else
    7820           0 :             index->tree_height = 0;
    7821             :     }
    7822             : 
    7823             :     /*
    7824             :      * Add a CPU-cost component to represent the costs of initial descent. We
    7825             :      * just use log(N) here not log2(N) since the branching factor isn't
    7826             :      * necessarily two anyway.  As for btree, charge once per SA scan.
    7827             :      */
    7828        1784 :     if (index->tuples > 1)        /* avoid computing log(0) */
    7829             :     {
    7830        1784 :         descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
    7831        1784 :         costs.indexStartupCost += descentCost;
    7832        1784 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7833             :     }
    7834             : 
    7835             :     /*
    7836             :      * Likewise add a per-page charge, calculated the same as for btrees.
    7837             :      */
    7838        1784 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    7839        1784 :     costs.indexStartupCost += descentCost;
    7840        1784 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7841             : 
    7842        1784 :     *indexStartupCost = costs.indexStartupCost;
    7843        1784 :     *indexTotalCost = costs.indexTotalCost;
    7844        1784 :     *indexSelectivity = costs.indexSelectivity;
    7845        1784 :     *indexCorrelation = costs.indexCorrelation;
    7846        1784 :     *indexPages = costs.numIndexPages;
    7847        1784 : }
    7848             : 
    7849             : 
    7850             : /*
    7851             :  * Support routines for gincostestimate
    7852             :  */
    7853             : 
    7854             : typedef struct
    7855             : {
    7856             :     bool        attHasFullScan[INDEX_MAX_KEYS];
    7857             :     bool        attHasNormalScan[INDEX_MAX_KEYS];
    7858             :     double      partialEntries;
    7859             :     double      exactEntries;
    7860             :     double      searchEntries;
    7861             :     double      arrayScans;
    7862             : } GinQualCounts;
    7863             : 
    7864             : /*
    7865             :  * Estimate the number of index terms that need to be searched for while
    7866             :  * testing the given GIN query, and increment the counts in *counts
    7867             :  * appropriately.  If the query is unsatisfiable, return false.
    7868             :  */
    7869             : static bool
    7870        2452 : gincost_pattern(IndexOptInfo *index, int indexcol,
    7871             :                 Oid clause_op, Datum query,
    7872             :                 GinQualCounts *counts)
    7873             : {
    7874             :     FmgrInfo    flinfo;
    7875             :     Oid         extractProcOid;
    7876             :     Oid         collation;
    7877             :     int         strategy_op;
    7878             :     Oid         lefttype,
    7879             :                 righttype;
    7880        2452 :     int32       nentries = 0;
    7881        2452 :     bool       *partial_matches = NULL;
    7882        2452 :     Pointer    *extra_data = NULL;
    7883        2452 :     bool       *nullFlags = NULL;
    7884        2452 :     int32       searchMode = GIN_SEARCH_MODE_DEFAULT;
    7885             :     int32       i;
    7886             : 
    7887             :     Assert(indexcol < index->nkeycolumns);
    7888             : 
    7889             :     /*
    7890             :      * Get the operator's strategy number and declared input data types within
    7891             :      * the index opfamily.  (We don't need the latter, but we use
    7892             :      * get_op_opfamily_properties because it will throw error if it fails to
    7893             :      * find a matching pg_amop entry.)
    7894             :      */
    7895        2452 :     get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
    7896             :                                &strategy_op, &lefttype, &righttype);
    7897             : 
    7898             :     /*
    7899             :      * GIN always uses the "default" support functions, which are those with
    7900             :      * lefttype == righttype == the opclass' opcintype (see
    7901             :      * IndexSupportInitialize in relcache.c).
    7902             :      */
    7903        2452 :     extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
    7904        2452 :                                        index->opcintype[indexcol],
    7905        2452 :                                        index->opcintype[indexcol],
    7906             :                                        GIN_EXTRACTQUERY_PROC);
    7907             : 
    7908        2452 :     if (!OidIsValid(extractProcOid))
    7909             :     {
    7910             :         /* should not happen; throw same error as index_getprocinfo */
    7911           0 :         elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
    7912             :              GIN_EXTRACTQUERY_PROC, indexcol + 1,
    7913             :              get_rel_name(index->indexoid));
    7914             :     }
    7915             : 
    7916             :     /*
    7917             :      * Choose collation to pass to extractProc (should match initGinState).
    7918             :      */
    7919        2452 :     if (OidIsValid(index->indexcollations[indexcol]))
    7920         390 :         collation = index->indexcollations[indexcol];
    7921             :     else
    7922        2062 :         collation = DEFAULT_COLLATION_OID;
    7923             : 
    7924        2452 :     fmgr_info(extractProcOid, &flinfo);
    7925             : 
    7926        2452 :     set_fn_opclass_options(&flinfo, index->opclassoptions[indexcol]);
    7927             : 
    7928        2452 :     FunctionCall7Coll(&flinfo,
    7929             :                       collation,
    7930             :                       query,
    7931             :                       PointerGetDatum(&nentries),
    7932             :                       UInt16GetDatum(strategy_op),
    7933             :                       PointerGetDatum(&partial_matches),
    7934             :                       PointerGetDatum(&extra_data),
    7935             :                       PointerGetDatum(&nullFlags),
    7936             :                       PointerGetDatum(&searchMode));
    7937             : 
    7938        2452 :     if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
    7939             :     {
    7940             :         /* No match is possible */
    7941          12 :         return false;
    7942             :     }
    7943             : 
    7944        9560 :     for (i = 0; i < nentries; i++)
    7945             :     {
    7946             :         /*
    7947             :          * For partial match we haven't any information to estimate number of
    7948             :          * matched entries in index, so, we just estimate it as 100
    7949             :          */
    7950        7120 :         if (partial_matches && partial_matches[i])
    7951         694 :             counts->partialEntries += 100;
    7952             :         else
    7953        6426 :             counts->exactEntries++;
    7954             : 
    7955        7120 :         counts->searchEntries++;
    7956             :     }
    7957             : 
    7958        2440 :     if (searchMode == GIN_SEARCH_MODE_DEFAULT)
    7959             :     {
    7960        1968 :         counts->attHasNormalScan[indexcol] = true;
    7961             :     }
    7962         472 :     else if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
    7963             :     {
    7964             :         /* Treat "include empty" like an exact-match item */
    7965          44 :         counts->attHasNormalScan[indexcol] = true;
    7966          44 :         counts->exactEntries++;
    7967          44 :         counts->searchEntries++;
    7968             :     }
    7969             :     else
    7970             :     {
    7971             :         /* It's GIN_SEARCH_MODE_ALL */
    7972         428 :         counts->attHasFullScan[indexcol] = true;
    7973             :     }
    7974             : 
    7975        2440 :     return true;
    7976             : }
    7977             : 
    7978             : /*
    7979             :  * Estimate the number of index terms that need to be searched for while
    7980             :  * testing the given GIN index clause, and increment the counts in *counts
    7981             :  * appropriately.  If the query is unsatisfiable, return false.
    7982             :  */
    7983             : static bool
    7984        2440 : gincost_opexpr(PlannerInfo *root,
    7985             :                IndexOptInfo *index,
    7986             :                int indexcol,
    7987             :                OpExpr *clause,
    7988             :                GinQualCounts *counts)
    7989             : {
    7990        2440 :     Oid         clause_op = clause->opno;
    7991        2440 :     Node       *operand = (Node *) lsecond(clause->args);
    7992             : 
    7993             :     /* aggressively reduce to a constant, and look through relabeling */
    7994        2440 :     operand = estimate_expression_value(root, operand);
    7995             : 
    7996        2440 :     if (IsA(operand, RelabelType))
    7997           0 :         operand = (Node *) ((RelabelType *) operand)->arg;
    7998             : 
    7999             :     /*
    8000             :      * It's impossible to call extractQuery method for unknown operand. So
    8001             :      * unless operand is a Const we can't do much; just assume there will be
    8002             :      * one ordinary search entry from the operand at runtime.
    8003             :      */
    8004        2440 :     if (!IsA(operand, Const))
    8005             :     {
    8006           0 :         counts->exactEntries++;
    8007           0 :         counts->searchEntries++;
    8008           0 :         return true;
    8009             :     }
    8010             : 
    8011             :     /* If Const is null, there can be no matches */
    8012        2440 :     if (((Const *) operand)->constisnull)
    8013           0 :         return false;
    8014             : 
    8015             :     /* Otherwise, apply extractQuery and get the actual term counts */
    8016        2440 :     return gincost_pattern(index, indexcol, clause_op,
    8017             :                            ((Const *) operand)->constvalue,
    8018             :                            counts);
    8019             : }
    8020             : 
    8021             : /*
    8022             :  * Estimate the number of index terms that need to be searched for while
    8023             :  * testing the given GIN index clause, and increment the counts in *counts
    8024             :  * appropriately.  If the query is unsatisfiable, return false.
    8025             :  *
    8026             :  * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
    8027             :  * each of which involves one value from the RHS array, plus all the
    8028             :  * non-array quals (if any).  To model this, we average the counts across
    8029             :  * the RHS elements, and add the averages to the counts in *counts (which
    8030             :  * correspond to per-indexscan costs).  We also multiply counts->arrayScans
    8031             :  * by N, causing gincostestimate to scale up its estimates accordingly.
    8032             :  */
    8033             : static bool
    8034           6 : gincost_scalararrayopexpr(PlannerInfo *root,
    8035             :                           IndexOptInfo *index,
    8036             :                           int indexcol,
    8037             :                           ScalarArrayOpExpr *clause,
    8038             :                           double numIndexEntries,
    8039             :                           GinQualCounts *counts)
    8040             : {
    8041           6 :     Oid         clause_op = clause->opno;
    8042           6 :     Node       *rightop = (Node *) lsecond(clause->args);
    8043             :     ArrayType  *arrayval;
    8044             :     int16       elmlen;
    8045             :     bool        elmbyval;
    8046             :     char        elmalign;
    8047             :     int         numElems;
    8048             :     Datum      *elemValues;
    8049             :     bool       *elemNulls;
    8050             :     GinQualCounts arraycounts;
    8051           6 :     int         numPossible = 0;
    8052             :     int         i;
    8053             : 
    8054             :     Assert(clause->useOr);
    8055             : 
    8056             :     /* aggressively reduce to a constant, and look through relabeling */
    8057           6 :     rightop = estimate_expression_value(root, rightop);
    8058             : 
    8059           6 :     if (IsA(rightop, RelabelType))
    8060           0 :         rightop = (Node *) ((RelabelType *) rightop)->arg;
    8061             : 
    8062             :     /*
    8063             :      * It's impossible to call extractQuery method for unknown operand. So
    8064             :      * unless operand is a Const we can't do much; just assume there will be
    8065             :      * one ordinary search entry from each array entry at runtime, and fall
    8066             :      * back on a probably-bad estimate of the number of array entries.
    8067             :      */
    8068           6 :     if (!IsA(rightop, Const))
    8069             :     {
    8070           0 :         counts->exactEntries++;
    8071           0 :         counts->searchEntries++;
    8072           0 :         counts->arrayScans *= estimate_array_length(root, rightop);
    8073           0 :         return true;
    8074             :     }
    8075             : 
    8076             :     /* If Const is null, there can be no matches */
    8077           6 :     if (((Const *) rightop)->constisnull)
    8078           0 :         return false;
    8079             : 
    8080             :     /* Otherwise, extract the array elements and iterate over them */
    8081           6 :     arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
    8082           6 :     get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
    8083             :                          &elmlen, &elmbyval, &elmalign);
    8084           6 :     deconstruct_array(arrayval,
    8085             :                       ARR_ELEMTYPE(arrayval),
    8086             :                       elmlen, elmbyval, elmalign,
    8087             :                       &elemValues, &elemNulls, &numElems);
    8088             : 
    8089           6 :     memset(&arraycounts, 0, sizeof(arraycounts));
    8090             : 
    8091          18 :     for (i = 0; i < numElems; i++)
    8092             :     {
    8093             :         GinQualCounts elemcounts;
    8094             : 
    8095             :         /* NULL can't match anything, so ignore, as the executor will */
    8096          12 :         if (elemNulls[i])
    8097           0 :             continue;
    8098             : 
    8099             :         /* Otherwise, apply extractQuery and get the actual term counts */
    8100          12 :         memset(&elemcounts, 0, sizeof(elemcounts));
    8101             : 
    8102          12 :         if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
    8103             :                             &elemcounts))
    8104             :         {
    8105             :             /* We ignore array elements that are unsatisfiable patterns */
    8106          12 :             numPossible++;
    8107             : 
    8108          12 :             if (elemcounts.attHasFullScan[indexcol] &&
    8109           0 :                 !elemcounts.attHasNormalScan[indexcol])
    8110             :             {
    8111             :                 /*
    8112             :                  * Full index scan will be required.  We treat this as if
    8113             :                  * every key in the index had been listed in the query; is
    8114             :                  * that reasonable?
    8115             :                  */
    8116           0 :                 elemcounts.partialEntries = 0;
    8117           0 :                 elemcounts.exactEntries = numIndexEntries;
    8118           0 :                 elemcounts.searchEntries = numIndexEntries;
    8119             :             }
    8120          12 :             arraycounts.partialEntries += elemcounts.partialEntries;
    8121          12 :             arraycounts.exactEntries += elemcounts.exactEntries;
    8122          12 :             arraycounts.searchEntries += elemcounts.searchEntries;
    8123             :         }
    8124             :     }
    8125             : 
    8126           6 :     if (numPossible == 0)
    8127             :     {
    8128             :         /* No satisfiable patterns in the array */
    8129           0 :         return false;
    8130             :     }
    8131             : 
    8132             :     /*
    8133             :      * Now add the averages to the global counts.  This will give us an
    8134             :      * estimate of the average number of terms searched for in each indexscan,
    8135             :      * including contributions from both array and non-array quals.
    8136             :      */
    8137           6 :     counts->partialEntries += arraycounts.partialEntries / numPossible;
    8138           6 :     counts->exactEntries += arraycounts.exactEntries / numPossible;
    8139           6 :     counts->searchEntries += arraycounts.searchEntries / numPossible;
    8140             : 
    8141           6 :     counts->arrayScans *= numPossible;
    8142             : 
    8143           6 :     return true;
    8144             : }
    8145             : 
    8146             : /*
    8147             :  * GIN has search behavior completely different from other index types
    8148             :  */
    8149             : void
    8150        2248 : gincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8151             :                 Cost *indexStartupCost, Cost *indexTotalCost,
    8152             :                 Selectivity *indexSelectivity, double *indexCorrelation,
    8153             :                 double *indexPages)
    8154             : {
    8155        2248 :     IndexOptInfo *index = path->indexinfo;
    8156        2248 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    8157             :     List       *selectivityQuals;
    8158        2248 :     double      numPages = index->pages,
    8159        2248 :                 numTuples = index->tuples;
    8160             :     double      numEntryPages,
    8161             :                 numDataPages,
    8162             :                 numPendingPages,
    8163             :                 numEntries;
    8164             :     GinQualCounts counts;
    8165             :     bool        matchPossible;
    8166             :     bool        fullIndexScan;
    8167             :     double      partialScale;
    8168             :     double      entryPagesFetched,
    8169             :                 dataPagesFetched,
    8170             :                 dataPagesFetchedBySel;
    8171             :     double      qual_op_cost,
    8172             :                 qual_arg_cost,
    8173             :                 spc_random_page_cost,
    8174             :                 outer_scans;
    8175             :     Cost        descentCost;
    8176             :     Relation    indexRel;
    8177             :     GinStatsData ginStats;
    8178             :     ListCell   *lc;
    8179             :     int         i;
    8180             : 
    8181             :     /*
    8182             :      * Obtain statistical information from the meta page, if possible.  Else
    8183             :      * set ginStats to zeroes, and we'll cope below.
    8184             :      */
    8185        2248 :     if (!index->hypothetical)
    8186             :     {
    8187             :         /* Lock should have already been obtained in plancat.c */
    8188        2248 :         indexRel = index_open(index->indexoid, NoLock);
    8189        2248 :         ginGetStats(indexRel, &ginStats);
    8190        2248 :         index_close(indexRel, NoLock);
    8191             :     }
    8192             :     else
    8193             :     {
    8194           0 :         memset(&ginStats, 0, sizeof(ginStats));
    8195             :     }
    8196             : 
    8197             :     /*
    8198             :      * Assuming we got valid (nonzero) stats at all, nPendingPages can be
    8199             :      * trusted, but the other fields are data as of the last VACUUM.  We can
    8200             :      * scale them up to account for growth since then, but that method only
    8201             :      * goes so far; in the worst case, the stats might be for a completely
    8202             :      * empty index, and scaling them will produce pretty bogus numbers.
    8203             :      * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
    8204             :      * it's grown more than that, fall back to estimating things only from the
    8205             :      * assumed-accurate index size.  But we'll trust nPendingPages in any case
    8206             :      * so long as it's not clearly insane, ie, more than the index size.
    8207             :      */
    8208        2248 :     if (ginStats.nPendingPages < numPages)
    8209        2248 :         numPendingPages = ginStats.nPendingPages;
    8210             :     else
    8211           0 :         numPendingPages = 0;
    8212             : 
    8213        2248 :     if (numPages > 0 && ginStats.nTotalPages <= numPages &&
    8214        2248 :         ginStats.nTotalPages > numPages / 4 &&
    8215        2196 :         ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
    8216        1938 :     {
    8217             :         /*
    8218             :          * OK, the stats seem close enough to sane to be trusted.  But we
    8219             :          * still need to scale them by the ratio numPages / nTotalPages to
    8220             :          * account for growth since the last VACUUM.
    8221             :          */
    8222        1938 :         double      scale = numPages / ginStats.nTotalPages;
    8223             : 
    8224        1938 :         numEntryPages = ceil(ginStats.nEntryPages * scale);
    8225        1938 :         numDataPages = ceil(ginStats.nDataPages * scale);
    8226        1938 :         numEntries = ceil(ginStats.nEntries * scale);
    8227             :         /* ensure we didn't round up too much */
    8228        1938 :         numEntryPages = Min(numEntryPages, numPages - numPendingPages);
    8229        1938 :         numDataPages = Min(numDataPages,
    8230             :                            numPages - numPendingPages - numEntryPages);
    8231             :     }
    8232             :     else
    8233             :     {
    8234             :         /*
    8235             :          * We might get here because it's a hypothetical index, or an index
    8236             :          * created pre-9.1 and never vacuumed since upgrading (in which case
    8237             :          * its stats would read as zeroes), or just because it's grown too
    8238             :          * much since the last VACUUM for us to put our faith in scaling.
    8239             :          *
    8240             :          * Invent some plausible internal statistics based on the index page
    8241             :          * count (and clamp that to at least 10 pages, just in case).  We
    8242             :          * estimate that 90% of the index is entry pages, and the rest is data
    8243             :          * pages.  Estimate 100 entries per entry page; this is rather bogus
    8244             :          * since it'll depend on the size of the keys, but it's more robust
    8245             :          * than trying to predict the number of entries per heap tuple.
    8246             :          */
    8247         310 :         numPages = Max(numPages, 10);
    8248         310 :         numEntryPages = floor((numPages - numPendingPages) * 0.90);
    8249         310 :         numDataPages = numPages - numPendingPages - numEntryPages;
    8250         310 :         numEntries = floor(numEntryPages * 100);
    8251             :     }
    8252             : 
    8253             :     /* In an empty index, numEntries could be zero.  Avoid divide-by-zero */
    8254        2248 :     if (numEntries < 1)
    8255           0 :         numEntries = 1;
    8256             : 
    8257             :     /*
    8258             :      * If the index is partial, AND the index predicate with the index-bound
    8259             :      * quals to produce a more accurate idea of the number of rows covered by
    8260             :      * the bound conditions.
    8261             :      */
    8262        2248 :     selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
    8263             : 
    8264             :     /* Estimate the fraction of main-table tuples that will be visited */
    8265        4496 :     *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
    8266        2248 :                                                index->rel->relid,
    8267             :                                                JOIN_INNER,
    8268             :                                                NULL);
    8269             : 
    8270             :     /* fetch estimated page cost for tablespace containing index */
    8271        2248 :     get_tablespace_page_costs(index->reltablespace,
    8272             :                               &spc_random_page_cost,
    8273             :                               NULL);
    8274             : 
    8275             :     /*
    8276             :      * Generic assumption about index correlation: there isn't any.
    8277             :      */
    8278        2248 :     *indexCorrelation = 0.0;
    8279             : 
    8280             :     /*
    8281             :      * Examine quals to estimate number of search entries & partial matches
    8282             :      */
    8283        2248 :     memset(&counts, 0, sizeof(counts));
    8284        2248 :     counts.arrayScans = 1;
    8285        2248 :     matchPossible = true;
    8286             : 
    8287        4694 :     foreach(lc, path->indexclauses)
    8288             :     {
    8289        2446 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    8290             :         ListCell   *lc2;
    8291             : 
    8292        4880 :         foreach(lc2, iclause->indexquals)
    8293             :         {
    8294        2446 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    8295        2446 :             Expr       *clause = rinfo->clause;
    8296             : 
    8297        2446 :             if (IsA(clause, OpExpr))
    8298             :             {
    8299        2440 :                 matchPossible = gincost_opexpr(root,
    8300             :                                                index,
    8301        2440 :                                                iclause->indexcol,
    8302             :                                                (OpExpr *) clause,
    8303             :                                                &counts);
    8304        2440 :                 if (!matchPossible)
    8305          12 :                     break;
    8306             :             }
    8307           6 :             else if (IsA(clause, ScalarArrayOpExpr))
    8308             :             {
    8309           6 :                 matchPossible = gincost_scalararrayopexpr(root,
    8310             :                                                           index,
    8311           6 :                                                           iclause->indexcol,
    8312             :                                                           (ScalarArrayOpExpr *) clause,
    8313             :                                                           numEntries,
    8314             :                                                           &counts);
    8315           6 :                 if (!matchPossible)
    8316           0 :                     break;
    8317             :             }
    8318             :             else
    8319             :             {
    8320             :                 /* shouldn't be anything else for a GIN index */
    8321           0 :                 elog(ERROR, "unsupported GIN indexqual type: %d",
    8322             :                      (int) nodeTag(clause));
    8323             :             }
    8324             :         }
    8325             :     }
    8326             : 
    8327             :     /* Fall out if there were any provably-unsatisfiable quals */
    8328        2248 :     if (!matchPossible)
    8329             :     {
    8330          12 :         *indexStartupCost = 0;
    8331          12 :         *indexTotalCost = 0;
    8332          12 :         *indexSelectivity = 0;
    8333          12 :         return;
    8334             :     }
    8335             : 
    8336             :     /*
    8337             :      * If attribute has a full scan and at the same time doesn't have normal
    8338             :      * scan, then we'll have to scan all non-null entries of that attribute.
    8339             :      * Currently, we don't have per-attribute statistics for GIN.  Thus, we
    8340             :      * must assume the whole GIN index has to be scanned in this case.
    8341             :      */
    8342        2236 :     fullIndexScan = false;
    8343        4362 :     for (i = 0; i < index->nkeycolumns; i++)
    8344             :     {
    8345        2464 :         if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
    8346             :         {
    8347         338 :             fullIndexScan = true;
    8348         338 :             break;
    8349             :         }
    8350             :     }
    8351             : 
    8352        2236 :     if (fullIndexScan || indexQuals == NIL)
    8353             :     {
    8354             :         /*
    8355             :          * Full index scan will be required.  We treat this as if every key in
    8356             :          * the index had been listed in the query; is that reasonable?
    8357             :          */
    8358         338 :         counts.partialEntries = 0;
    8359         338 :         counts.exactEntries = numEntries;
    8360         338 :         counts.searchEntries = numEntries;
    8361             :     }
    8362             : 
    8363             :     /* Will we have more than one iteration of a nestloop scan? */
    8364        2236 :     outer_scans = loop_count;
    8365             : 
    8366             :     /*
    8367             :      * Compute cost to begin scan, first of all, pay attention to pending
    8368             :      * list.
    8369             :      */
    8370        2236 :     entryPagesFetched = numPendingPages;
    8371             : 
    8372             :     /*
    8373             :      * Estimate number of entry pages read.  We need to do
    8374             :      * counts.searchEntries searches.  Use a power function as it should be,
    8375             :      * but tuples on leaf pages usually is much greater. Here we include all
    8376             :      * searches in entry tree, including search of first entry in partial
    8377             :      * match algorithm
    8378             :      */
    8379        2236 :     entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
    8380             : 
    8381             :     /*
    8382             :      * Add an estimate of entry pages read by partial match algorithm. It's a
    8383             :      * scan over leaf pages in entry tree.  We haven't any useful stats here,
    8384             :      * so estimate it as proportion.  Because counts.partialEntries is really
    8385             :      * pretty bogus (see code above), it's possible that it is more than
    8386             :      * numEntries; clamp the proportion to ensure sanity.
    8387             :      */
    8388        2236 :     partialScale = counts.partialEntries / numEntries;
    8389        2236 :     partialScale = Min(partialScale, 1.0);
    8390             : 
    8391        2236 :     entryPagesFetched += ceil(numEntryPages * partialScale);
    8392             : 
    8393             :     /*
    8394             :      * Partial match algorithm reads all data pages before doing actual scan,
    8395             :      * so it's a startup cost.  Again, we haven't any useful stats here, so
    8396             :      * estimate it as proportion.
    8397             :      */
    8398        2236 :     dataPagesFetched = ceil(numDataPages * partialScale);
    8399             : 
    8400        2236 :     *indexStartupCost = 0;
    8401        2236 :     *indexTotalCost = 0;
    8402             : 
    8403             :     /*
    8404             :      * Add a CPU-cost component to represent the costs of initial entry btree
    8405             :      * descent.  We don't charge any I/O cost for touching upper btree levels,
    8406             :      * since they tend to stay in cache, but we still have to do about log2(N)
    8407             :      * comparisons to descend a btree of N leaf tuples.  We charge one
    8408             :      * cpu_operator_cost per comparison.
    8409             :      *
    8410             :      * If there are ScalarArrayOpExprs, charge this once per SA scan.  The
    8411             :      * ones after the first one are not startup cost so far as the overall
    8412             :      * plan is concerned, so add them only to "total" cost.
    8413             :      */
    8414        2236 :     if (numEntries > 1)          /* avoid computing log(0) */
    8415             :     {
    8416        2236 :         descentCost = ceil(log(numEntries) / log(2.0)) * cpu_operator_cost;
    8417        2236 :         *indexStartupCost += descentCost * counts.searchEntries;
    8418        2236 :         *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
    8419             :     }
    8420             : 
    8421             :     /*
    8422             :      * Add a cpu cost per entry-page fetched. This is not amortized over a
    8423             :      * loop.
    8424             :      */
    8425        2236 :     *indexStartupCost += entryPagesFetched * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8426        2236 :     *indexTotalCost += entryPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8427             : 
    8428             :     /*
    8429             :      * Add a cpu cost per data-page fetched. This is also not amortized over a
    8430             :      * loop. Since those are the data pages from the partial match algorithm,
    8431             :      * charge them as startup cost.
    8432             :      */
    8433        2236 :     *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * dataPagesFetched;
    8434             : 
    8435             :     /*
    8436             :      * Since we add the startup cost to the total cost later on, remove the
    8437             :      * initial arrayscan from the total.
    8438             :      */
    8439        2236 :     *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8440             : 
    8441             :     /*
    8442             :      * Calculate cache effects if more than one scan due to nestloops or array
    8443             :      * quals.  The result is pro-rated per nestloop scan, but the array qual
    8444             :      * factor shouldn't be pro-rated (compare genericcostestimate).
    8445             :      */
    8446        2236 :     if (outer_scans > 1 || counts.arrayScans > 1)
    8447             :     {
    8448           6 :         entryPagesFetched *= outer_scans * counts.arrayScans;
    8449           6 :         entryPagesFetched = index_pages_fetched(entryPagesFetched,
    8450             :                                                 (BlockNumber) numEntryPages,
    8451             :                                                 numEntryPages, root);
    8452           6 :         entryPagesFetched /= outer_scans;
    8453           6 :         dataPagesFetched *= outer_scans * counts.arrayScans;
    8454           6 :         dataPagesFetched = index_pages_fetched(dataPagesFetched,
    8455             :                                                (BlockNumber) numDataPages,
    8456             :                                                numDataPages, root);
    8457           6 :         dataPagesFetched /= outer_scans;
    8458             :     }
    8459             : 
    8460             :     /*
    8461             :      * Here we use random page cost because logically-close pages could be far
    8462             :      * apart on disk.
    8463             :      */
    8464        2236 :     *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
    8465             : 
    8466             :     /*
    8467             :      * Now compute the number of data pages fetched during the scan.
    8468             :      *
    8469             :      * We assume every entry to have the same number of items, and that there
    8470             :      * is no overlap between them. (XXX: tsvector and array opclasses collect
    8471             :      * statistics on the frequency of individual keys; it would be nice to use
    8472             :      * those here.)
    8473             :      */
    8474        2236 :     dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
    8475             : 
    8476             :     /*
    8477             :      * If there is a lot of overlap among the entries, in particular if one of
    8478             :      * the entries is very frequent, the above calculation can grossly
    8479             :      * under-estimate.  As a simple cross-check, calculate a lower bound based
    8480             :      * on the overall selectivity of the quals.  At a minimum, we must read
    8481             :      * one item pointer for each matching entry.
    8482             :      *
    8483             :      * The width of each item pointer varies, based on the level of
    8484             :      * compression.  We don't have statistics on that, but an average of
    8485             :      * around 3 bytes per item is fairly typical.
    8486             :      */
    8487        2236 :     dataPagesFetchedBySel = ceil(*indexSelectivity *
    8488        2236 :                                  (numTuples / (BLCKSZ / 3)));
    8489        2236 :     if (dataPagesFetchedBySel > dataPagesFetched)
    8490        1856 :         dataPagesFetched = dataPagesFetchedBySel;
    8491             : 
    8492             :     /* Add one page cpu-cost to the startup cost */
    8493        2236 :     *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
    8494             : 
    8495             :     /*
    8496             :      * Add once again a CPU-cost for those data pages, before amortizing for
    8497             :      * cache.
    8498             :      */
    8499        2236 :     *indexTotalCost += dataPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8500             : 
    8501             :     /* Account for cache effects, the same as above */
    8502        2236 :     if (outer_scans > 1 || counts.arrayScans > 1)
    8503             :     {
    8504           6 :         dataPagesFetched *= outer_scans * counts.arrayScans;
    8505           6 :         dataPagesFetched = index_pages_fetched(dataPagesFetched,
    8506             :                                                (BlockNumber) numDataPages,
    8507             :                                                numDataPages, root);
    8508           6 :         dataPagesFetched /= outer_scans;
    8509             :     }
    8510             : 
    8511             :     /* And apply random_page_cost as the cost per page */
    8512        2236 :     *indexTotalCost += *indexStartupCost +
    8513        2236 :         dataPagesFetched * spc_random_page_cost;
    8514             : 
    8515             :     /*
    8516             :      * Add on index qual eval costs, much as in genericcostestimate. We charge
    8517             :      * cpu but we can disregard indexorderbys, since GIN doesn't support
    8518             :      * those.
    8519             :      */
    8520        2236 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
    8521        2236 :     qual_op_cost = cpu_operator_cost * list_length(indexQuals);
    8522             : 
    8523        2236 :     *indexStartupCost += qual_arg_cost;
    8524        2236 :     *indexTotalCost += qual_arg_cost;
    8525             : 
    8526             :     /*
    8527             :      * Add a cpu cost per search entry, corresponding to the actual visited
    8528             :      * entries.
    8529             :      */
    8530        2236 :     *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
    8531             :     /* Now add a cpu cost per tuple in the posting lists / trees */
    8532        2236 :     *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
    8533        2236 :     *indexPages = dataPagesFetched;
    8534             : }
    8535             : 
    8536             : /*
    8537             :  * BRIN has search behavior completely different from other index types
    8538             :  */
    8539             : void
    8540       10730 : brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8541             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    8542             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    8543             :                  double *indexPages)
    8544             : {
    8545       10730 :     IndexOptInfo *index = path->indexinfo;
    8546       10730 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    8547       10730 :     double      numPages = index->pages;
    8548       10730 :     RelOptInfo *baserel = index->rel;
    8549       10730 :     RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
    8550             :     Cost        spc_seq_page_cost;
    8551             :     Cost        spc_random_page_cost;
    8552             :     double      qual_arg_cost;
    8553             :     double      qualSelectivity;
    8554             :     BrinStatsData statsData;
    8555             :     double      indexRanges;
    8556             :     double      minimalRanges;
    8557             :     double      estimatedRanges;
    8558             :     double      selec;
    8559             :     Relation    indexRel;
    8560             :     ListCell   *l;
    8561             :     VariableStatData vardata;
    8562             : 
    8563             :     Assert(rte->rtekind == RTE_RELATION);
    8564             : 
    8565             :     /* fetch estimated page cost for the tablespace containing the index */
    8566       10730 :     get_tablespace_page_costs(index->reltablespace,
    8567             :                               &spc_random_page_cost,
    8568             :                               &spc_seq_page_cost);
    8569             : 
    8570             :     /*
    8571             :      * Obtain some data from the index itself, if possible.  Otherwise invent
    8572             :      * some plausible internal statistics based on the relation page count.
    8573             :      */
    8574       10730 :     if (!index->hypothetical)
    8575             :     {
    8576             :         /*
    8577             :          * A lock should have already been obtained on the index in plancat.c.
    8578             :          */
    8579       10730 :         indexRel = index_open(index->indexoid, NoLock);
    8580       10730 :         brinGetStats(indexRel, &statsData);
    8581       10730 :         index_close(indexRel, NoLock);
    8582             : 
    8583             :         /* work out the actual number of ranges in the index */
    8584       10730 :         indexRanges = Max(ceil((double) baserel->pages /
    8585             :                                statsData.pagesPerRange), 1.0);
    8586             :     }
    8587             :     else
    8588             :     {
    8589             :         /*
    8590             :          * Assume default number of pages per range, and estimate the number
    8591             :          * of ranges based on that.
    8592             :          */
    8593           0 :         indexRanges = Max(ceil((double) baserel->pages /
    8594             :                                BRIN_DEFAULT_PAGES_PER_RANGE), 1.0);
    8595             : 
    8596           0 :         statsData.pagesPerRange = BRIN_DEFAULT_PAGES_PER_RANGE;
    8597           0 :         statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
    8598             :     }
    8599             : 
    8600             :     /*
    8601             :      * Compute index correlation
    8602             :      *
    8603             :      * Because we can use all index quals equally when scanning, we can use
    8604             :      * the largest correlation (in absolute value) among columns used by the
    8605             :      * query.  Start at zero, the worst possible case.  If we cannot find any
    8606             :      * correlation statistics, we will keep it as 0.
    8607             :      */
    8608       10730 :     *indexCorrelation = 0;
    8609             : 
    8610       21462 :     foreach(l, path->indexclauses)
    8611             :     {
    8612       10732 :         IndexClause *iclause = lfirst_node(IndexClause, l);
    8613       10732 :         AttrNumber  attnum = index->indexkeys[iclause->indexcol];
    8614             : 
    8615             :         /* attempt to lookup stats in relation for this index column */
    8616       10732 :         if (attnum != 0)
    8617             :         {
    8618             :             /* Simple variable -- look to stats for the underlying table */
    8619       10732 :             if (get_relation_stats_hook &&
    8620           0 :                 (*get_relation_stats_hook) (root, rte, attnum, &vardata))
    8621             :             {
    8622             :                 /*
    8623             :                  * The hook took control of acquiring a stats tuple.  If it
    8624             :                  * did supply a tuple, it'd better have supplied a freefunc.
    8625             :                  */
    8626           0 :                 if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
    8627           0 :                     elog(ERROR,
    8628             :                          "no function provided to release variable stats with");
    8629             :             }
    8630             :             else
    8631             :             {
    8632       10732 :                 vardata.statsTuple =
    8633       10732 :                     SearchSysCache3(STATRELATTINH,
    8634             :                                     ObjectIdGetDatum(rte->relid),
    8635             :                                     Int16GetDatum(attnum),
    8636             :                                     BoolGetDatum(false));
    8637       10732 :                 vardata.freefunc = ReleaseSysCache;
    8638             :             }
    8639             :         }
    8640             :         else
    8641             :         {
    8642             :             /*
    8643             :              * Looks like we've found an expression column in the index. Let's
    8644             :              * see if there's any stats for it.
    8645             :              */
    8646             : 
    8647             :             /* get the attnum from the 0-based index. */
    8648           0 :             attnum = iclause->indexcol + 1;
    8649             : 
    8650           0 :             if (get_index_stats_hook &&
    8651           0 :                 (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
    8652             :             {
    8653             :                 /*
    8654             :                  * The hook took control of acquiring a stats tuple.  If it
    8655             :                  * did supply a tuple, it'd better have supplied a freefunc.
    8656             :                  */
    8657           0 :                 if (HeapTupleIsValid(vardata.statsTuple) &&
    8658           0 :                     !vardata.freefunc)
    8659           0 :                     elog(ERROR, "no function provided to release variable stats with");
    8660             :             }
    8661             :             else
    8662             :             {
    8663           0 :                 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
    8664             :                                                      ObjectIdGetDatum(index->indexoid),
    8665             :                                                      Int16GetDatum(attnum),
    8666             :                                                      BoolGetDatum(false));
    8667           0 :                 vardata.freefunc = ReleaseSysCache;
    8668             :             }
    8669             :         }
    8670             : 
    8671       10732 :         if (HeapTupleIsValid(vardata.statsTuple))
    8672             :         {
    8673             :             AttStatsSlot sslot;
    8674             : 
    8675          36 :             if (get_attstatsslot(&sslot, vardata.statsTuple,
    8676             :                                  STATISTIC_KIND_CORRELATION, InvalidOid,
    8677             :                                  ATTSTATSSLOT_NUMBERS))
    8678             :             {
    8679          36 :                 double      varCorrelation = 0.0;
    8680             : 
    8681          36 :                 if (sslot.nnumbers > 0)
    8682          36 :                     varCorrelation = fabs(sslot.numbers[0]);
    8683             : 
    8684          36 :                 if (varCorrelation > *indexCorrelation)
    8685          36 :                     *indexCorrelation = varCorrelation;
    8686             : 
    8687          36 :                 free_attstatsslot(&sslot);
    8688             :             }
    8689             :         }
    8690             : 
    8691       10732 :         ReleaseVariableStats(vardata);
    8692             :     }
    8693             : 
    8694       10730 :     qualSelectivity = clauselist_selectivity(root, indexQuals,
    8695       10730 :                                              baserel->relid,
    8696             :                                              JOIN_INNER, NULL);
    8697             : 
    8698             :     /*
    8699             :      * Now calculate the minimum possible ranges we could match with if all of
    8700             :      * the rows were in the perfect order in the table's heap.
    8701             :      */
    8702       10730 :     minimalRanges = ceil(indexRanges * qualSelectivity);
    8703             : 
    8704             :     /*
    8705             :      * Now estimate the number of ranges that we'll touch by using the
    8706             :      * indexCorrelation from the stats. Careful not to divide by zero (note
    8707             :      * we're using the absolute value of the correlation).
    8708             :      */
    8709       10730 :     if (*indexCorrelation < 1.0e-10)
    8710       10694 :         estimatedRanges = indexRanges;
    8711             :     else
    8712          36 :         estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
    8713             : 
    8714             :     /* we expect to visit this portion of the table */
    8715       10730 :     selec = estimatedRanges / indexRanges;
    8716             : 
    8717       10730 :     CLAMP_PROBABILITY(selec);
    8718             : 
    8719       10730 :     *indexSelectivity = selec;
    8720             : 
    8721             :     /*
    8722             :      * Compute the index qual costs, much as in genericcostestimate, to add to
    8723             :      * the index costs.  We can disregard indexorderbys, since BRIN doesn't
    8724             :      * support those.
    8725             :      */
    8726       10730 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
    8727             : 
    8728             :     /*
    8729             :      * Compute the startup cost as the cost to read the whole revmap
    8730             :      * sequentially, including the cost to execute the index quals.
    8731             :      */
    8732       10730 :     *indexStartupCost =
    8733       10730 :         spc_seq_page_cost * statsData.revmapNumPages * loop_count;
    8734       10730 :     *indexStartupCost += qual_arg_cost;
    8735             : 
    8736             :     /*
    8737             :      * To read a BRIN index there might be a bit of back and forth over
    8738             :      * regular pages, as revmap might point to them out of sequential order;
    8739             :      * calculate the total cost as reading the whole index in random order.
    8740             :      */
    8741       10730 :     *indexTotalCost = *indexStartupCost +
    8742       10730 :         spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
    8743             : 
    8744             :     /*
    8745             :      * Charge a small amount per range tuple which we expect to match to. This
    8746             :      * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
    8747             :      * will set a bit for each page in the range when we find a matching
    8748             :      * range, so we must multiply the charge by the number of pages in the
    8749             :      * range.
    8750             :      */
    8751       10730 :     *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
    8752       10730 :         statsData.pagesPerRange;
    8753             : 
    8754       10730 :     *indexPages = index->pages;
    8755       10730 : }

Generated by: LCOV version 1.16