LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 2186 2491 87.8 %
Date: 2025-08-20 13:17:39 Functions: 72 75 96.0 %
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      628006 : eqsel(PG_FUNCTION_ARGS)
     232             : {
     233      628006 :     PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
     234             : }
     235             : 
     236             : /*
     237             :  * Common code for eqsel() and neqsel()
     238             :  */
     239             : static double
     240      673538 : eqsel_internal(PG_FUNCTION_ARGS, bool negate)
     241             : {
     242      673538 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
     243      673538 :     Oid         operator = PG_GETARG_OID(1);
     244      673538 :     List       *args = (List *) PG_GETARG_POINTER(2);
     245      673538 :     int         varRelid = PG_GETARG_INT32(3);
     246      673538 :     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      673538 :     if (negate)
     257             :     {
     258       45532 :         operator = get_negator(operator);
     259       45532 :         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      673538 :     if (!get_restriction_variable(root, args, varRelid,
     271             :                                   &vardata, &other, &varonleft))
     272        5162 :         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      668370 :     if (IsA(other, Const))
     280      297348 :         selec = var_eq_const(&vardata, operator, collation,
     281      297348 :                              ((Const *) other)->constvalue,
     282      297348 :                              ((Const *) other)->constisnull,
     283             :                              varonleft, negate);
     284             :     else
     285      371022 :         selec = var_eq_non_const(&vardata, operator, collation, other,
     286             :                                  varonleft, negate);
     287             : 
     288      668370 :     ReleaseVariableStats(vardata);
     289             : 
     290      668370 :     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      341784 : var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
     300             :              Datum constval, bool constisnull,
     301             :              bool varonleft, bool negate)
     302             : {
     303             :     double      selec;
     304      341784 :     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      341784 :     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      341380 :     if (HeapTupleIsValid(vardata->statsTuple))
     320             :     {
     321             :         Form_pg_statistic stats;
     322             : 
     323      259386 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     324      259386 :         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      341380 :     if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
     335             :     {
     336       82116 :         selec = 1.0 / vardata->rel->tuples;
     337             :     }
     338      453418 :     else if (HeapTupleIsValid(vardata->statsTuple) &&
     339      194154 :              statistic_proc_security_check(vardata,
     340      194154 :                                            (opfuncoid = get_opcode(oproid))))
     341      194154 :     {
     342             :         AttStatsSlot sslot;
     343      194154 :         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      194154 :         if (get_attstatsslot(&sslot, vardata->statsTuple,
     354             :                              STATISTIC_KIND_MCV, InvalidOid,
     355             :                              ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
     356             :         {
     357      172804 :             LOCAL_FCINFO(fcinfo, 2);
     358             :             FmgrInfo    eqproc;
     359             : 
     360      172804 :             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      172804 :             InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
     369             :                                      NULL, NULL);
     370      172804 :             fcinfo->args[0].isnull = false;
     371      172804 :             fcinfo->args[1].isnull = false;
     372             :             /* be careful to apply operator right way 'round */
     373      172804 :             if (varonleft)
     374      172772 :                 fcinfo->args[1].value = constval;
     375             :             else
     376          32 :                 fcinfo->args[0].value = constval;
     377             : 
     378     2888490 :             for (i = 0; i < sslot.nvalues; i++)
     379             :             {
     380             :                 Datum       fresult;
     381             : 
     382     2804630 :                 if (varonleft)
     383     2804574 :                     fcinfo->args[0].value = sslot.values[i];
     384             :                 else
     385          56 :                     fcinfo->args[1].value = sslot.values[i];
     386     2804630 :                 fcinfo->isnull = false;
     387     2804630 :                 fresult = FunctionCallInvoke(fcinfo);
     388     2804630 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
     389             :                 {
     390       88944 :                     match = true;
     391       88944 :                     break;
     392             :                 }
     393             :             }
     394             :         }
     395             :         else
     396             :         {
     397             :             /* no most-common-value info available */
     398       21350 :             i = 0;              /* keep compiler quiet */
     399             :         }
     400             : 
     401      194154 :         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       88944 :             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      105210 :             double      sumcommon = 0.0;
     417             :             double      otherdistinct;
     418             : 
     419     2463770 :             for (i = 0; i < sslot.nnumbers; i++)
     420     2358560 :                 sumcommon += sslot.numbers[i];
     421      105210 :             selec = 1.0 - sumcommon - nullfrac;
     422      105210 :             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      105210 :             otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
     430      105210 :                 sslot.nnumbers;
     431      105210 :             if (otherdistinct > 1)
     432       51254 :                 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      105210 :             if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
     439           0 :                 selec = sslot.numbers[sslot.nnumbers - 1];
     440             :         }
     441             : 
     442      194154 :         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       65110 :         selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
     452             :     }
     453             : 
     454             :     /* now adjust if we wanted <> rather than = */
     455      341380 :     if (negate)
     456       36758 :         selec = 1.0 - selec - nullfrac;
     457             : 
     458             :     /* result should be in range, but make sure... */
     459      341380 :     CLAMP_PROBABILITY(selec);
     460             : 
     461      341380 :     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      371022 : var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
     471             :                  Node *other,
     472             :                  bool varonleft, bool negate)
     473             : {
     474             :     double      selec;
     475      371022 :     double      nullfrac = 0.0;
     476             :     bool        isdefault;
     477             : 
     478             :     /*
     479             :      * Grab the nullfrac for use below.
     480             :      */
     481      371022 :     if (HeapTupleIsValid(vardata->statsTuple))
     482             :     {
     483             :         Form_pg_statistic stats;
     484             : 
     485      273040 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     486      273040 :         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      371022 :     if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
     497             :     {
     498      148382 :         selec = 1.0 / vardata->rel->tuples;
     499             :     }
     500      222640 :     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      139168 :         selec = 1.0 - nullfrac;
     516      139168 :         ndistinct = get_variable_numdistinct(vardata, &isdefault);
     517      139168 :         if (ndistinct > 1)
     518      135484 :             selec /= ndistinct;
     519             : 
     520             :         /*
     521             :          * Cross-check: selectivity should never be estimated as more than the
     522             :          * most common value's.
     523             :          */
     524      139168 :         if (get_attstatsslot(&sslot, vardata->statsTuple,
     525             :                              STATISTIC_KIND_MCV, InvalidOid,
     526             :                              ATTSTATSSLOT_NUMBERS))
     527             :         {
     528      120132 :             if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
     529         558 :                 selec = sslot.numbers[0];
     530      120132 :             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       83472 :         selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
     541             :     }
     542             : 
     543             :     /* now adjust if we wanted <> rather than = */
     544      371022 :     if (negate)
     545        6458 :         selec = 1.0 - selec - nullfrac;
     546             : 
     547             :     /* result should be in range, but make sure... */
     548      371022 :     CLAMP_PROBABILITY(selec);
     549             : 
     550      371022 :     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       45532 : neqsel(PG_FUNCTION_ARGS)
     562             : {
     563       45532 :     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      304288 : 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      304288 :     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       22470 :         if (vardata->var && IsA(vardata->var, Var) &&
     603       17642 :             ((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       20518 :         return DEFAULT_INEQ_SEL;
     674             :     }
     675      281818 :     stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
     676             : 
     677      281818 :     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      281818 :     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      281818 :     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      281818 :     selec = 1.0 - stats->stanullfrac - sumcommon;
     703             : 
     704      281818 :     if (hist_selec >= 0.0)
     705      209352 :         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       72466 :         selec *= 0.5;
     713             :     }
     714             : 
     715      281818 :     selec += mcv_selec;
     716             : 
     717             :     /* result should be in range, but make sure... */
     718      281818 :     CLAMP_PROBABILITY(selec);
     719             : 
     720      281818 :     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      287964 : 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      287964 :     mcv_selec = 0.0;
     746      287964 :     sumcommon = 0.0;
     747             : 
     748      573500 :     if (HeapTupleIsValid(vardata->statsTuple) &&
     749      570742 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
     750      285206 :         get_attstatsslot(&sslot, vardata->statsTuple,
     751             :                          STATISTIC_KIND_MCV, InvalidOid,
     752             :                          ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
     753             :     {
     754      133352 :         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      133352 :         InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
     764             :                                  NULL, NULL);
     765      133352 :         fcinfo->args[0].isnull = false;
     766      133352 :         fcinfo->args[1].isnull = false;
     767             :         /* be careful to apply operator right way 'round */
     768      133352 :         if (varonleft)
     769      133352 :             fcinfo->args[1].value = constval;
     770             :         else
     771           0 :             fcinfo->args[0].value = constval;
     772             : 
     773     3972050 :         for (i = 0; i < sslot.nvalues; i++)
     774             :         {
     775             :             Datum       fresult;
     776             : 
     777     3838698 :             if (varonleft)
     778     3838698 :                 fcinfo->args[0].value = sslot.values[i];
     779             :             else
     780           0 :                 fcinfo->args[1].value = sslot.values[i];
     781     3838698 :             fcinfo->isnull = false;
     782     3838698 :             fresult = FunctionCallInvoke(fcinfo);
     783     3838698 :             if (!fcinfo->isnull && DatumGetBool(fresult))
     784     1409198 :                 mcv_selec += sslot.numbers[i];
     785     3838698 :             sumcommon += sslot.numbers[i];
     786             :         }
     787      133352 :         free_attstatsslot(&sslot);
     788             :     }
     789             : 
     790      287964 :     *sumcommonp = sumcommon;
     791      287964 :     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        6146 : 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        9864 :     if (HeapTupleIsValid(vardata->statsTuple) &&
     841        7430 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
     842        3712 :         get_attstatsslot(&sslot, vardata->statsTuple,
     843             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
     844             :                          ATTSTATSSLOT_VALUES))
     845             :     {
     846        3618 :         *hist_size = sslot.nvalues;
     847        3618 :         if (sslot.nvalues >= min_hist_size)
     848             :         {
     849        1730 :             LOCAL_FCINFO(fcinfo, 2);
     850        1730 :             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        1730 :             InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
     862             :                                      NULL, NULL);
     863        1730 :             fcinfo->args[0].isnull = false;
     864        1730 :             fcinfo->args[1].isnull = false;
     865             :             /* be careful to apply operator right way 'round */
     866        1730 :             if (varonleft)
     867        1730 :                 fcinfo->args[1].value = constval;
     868             :             else
     869           0 :                 fcinfo->args[0].value = constval;
     870             : 
     871      141892 :             for (i = n_skip; i < sslot.nvalues - n_skip; i++)
     872             :             {
     873             :                 Datum       fresult;
     874             : 
     875      140162 :                 if (varonleft)
     876      140162 :                     fcinfo->args[0].value = sslot.values[i];
     877             :                 else
     878           0 :                     fcinfo->args[1].value = sslot.values[i];
     879      140162 :                 fcinfo->isnull = false;
     880      140162 :                 fresult = FunctionCallInvoke(fcinfo);
     881      140162 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
     882        7408 :                     nmatch++;
     883             :             }
     884        1730 :             result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
     885             :         }
     886             :         else
     887        1888 :             result = -1;
     888        3618 :         free_attstatsslot(&sslot);
     889             :     }
     890             :     else
     891             :     {
     892        2528 :         *hist_size = 0;
     893        2528 :         result = -1;
     894             :     }
     895             : 
     896        6146 :     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      287008 : 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      287008 :     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      573328 :     if (HeapTupleIsValid(vardata->statsTuple) &&
    1069      572316 :         statistic_proc_security_check(vardata, opproc->fn_oid) &&
    1070      285996 :         get_attstatsslot(&sslot, vardata->statsTuple,
    1071             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
    1072             :                          ATTSTATSSLOT_VALUES))
    1073             :     {
    1074      213852 :         if (sslot.nvalues > 1 &&
    1075      427628 :             sslot.stacoll == collation &&
    1076      213776 :             comparison_ops_are_compatible(sslot.staop, opoid))
    1077      213668 :         {
    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      213668 :             int         lobound = 0;    /* first possible slot to search */
    1098      213668 :             int         hibound = sslot.nvalues;    /* last+1 slot to search */
    1099      213668 :             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      213668 :             if (sslot.nvalues == 2)
    1108        3722 :                 have_end = get_actual_variable_range(root,
    1109             :                                                      vardata,
    1110             :                                                      sslot.staop,
    1111             :                                                      collation,
    1112             :                                                      &sslot.values[0],
    1113        3722 :                                                      &sslot.values[1]);
    1114             : 
    1115     1413042 :             while (lobound < hibound)
    1116             :             {
    1117     1199374 :                 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     1199374 :                 if (probe == 0 && sslot.nvalues > 2)
    1126      105518 :                     have_end = get_actual_variable_range(root,
    1127             :                                                          vardata,
    1128             :                                                          sslot.staop,
    1129             :                                                          collation,
    1130             :                                                          &sslot.values[0],
    1131             :                                                          NULL);
    1132     1093856 :                 else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
    1133       71456 :                     have_end = get_actual_variable_range(root,
    1134             :                                                          vardata,
    1135             :                                                          sslot.staop,
    1136             :                                                          collation,
    1137             :                                                          NULL,
    1138       71456 :                                                          &sslot.values[probe]);
    1139             : 
    1140     1199374 :                 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
    1141             :                                                        collation,
    1142     1199374 :                                                        sslot.values[probe],
    1143             :                                                        constval));
    1144     1199374 :                 if (isgt)
    1145       68162 :                     ltcmp = !ltcmp;
    1146     1199374 :                 if (ltcmp)
    1147      449094 :                     lobound = probe + 1;
    1148             :                 else
    1149      750280 :                     hibound = probe;
    1150             :             }
    1151             : 
    1152      213668 :             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       91448 :                 histfrac = 0.0;
    1163             :             }
    1164      122220 :             else if (lobound >= sslot.nvalues)
    1165             :             {
    1166             :                 /*
    1167             :                  * Inverse case: constant is above upper histogram boundary.
    1168             :                  */
    1169       32832 :                 histfrac = 1.0;
    1170             :             }
    1171             :             else
    1172             :             {
    1173             :                 /* We have values[i-1] <= constant <= values[i]. */
    1174       89388 :                 int         i = lobound;
    1175       89388 :                 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       89388 :                 if (i == 1 || isgt == iseq)
    1198             :                 {
    1199             :                     double      otherdistinct;
    1200             :                     bool        isdefault;
    1201             :                     AttStatsSlot mcvslot;
    1202             : 
    1203             :                     /* Get estimated number of distinct values */
    1204       38030 :                     otherdistinct = get_variable_numdistinct(vardata,
    1205             :                                                              &isdefault);
    1206             : 
    1207             :                     /* Subtract off the number of known MCVs */
    1208       38030 :                     if (get_attstatsslot(&mcvslot, vardata->statsTuple,
    1209             :                                          STATISTIC_KIND_MCV, InvalidOid,
    1210             :                                          ATTSTATSSLOT_NUMBERS))
    1211             :                     {
    1212        4340 :                         otherdistinct -= mcvslot.nnumbers;
    1213        4340 :                         free_attstatsslot(&mcvslot);
    1214             :                     }
    1215             : 
    1216             :                     /* If result doesn't seem sane, leave eq_selec at 0 */
    1217       38030 :                     if (otherdistinct > 1)
    1218       37988 :                         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       89388 :                 if (convert_to_scalar(constval, consttype, collation,
    1227             :                                       &val,
    1228       89388 :                                       sslot.values[i - 1], sslot.values[i],
    1229             :                                       vardata->vartype,
    1230             :                                       &low, &high))
    1231             :                 {
    1232       89388 :                     if (high <= low)
    1233             :                     {
    1234             :                         /* cope if bin boundaries appear identical */
    1235           0 :                         binfrac = 0.5;
    1236             :                     }
    1237       89388 :                     else if (val <= low)
    1238       20466 :                         binfrac = 0.0;
    1239       68922 :                     else if (val >= high)
    1240        3404 :                         binfrac = 1.0;
    1241             :                     else
    1242             :                     {
    1243       65518 :                         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       65518 :                         if (isnan(binfrac) ||
    1252       65518 :                             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       89388 :                 histfrac = (double) (i - 1) + binfrac;
    1275       89388 :                 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       89388 :                 if (i == 1)
    1310       16904 :                     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       89388 :                 if (isgt == iseq)
    1318       28252 :                     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      213668 :             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      213668 :             if (have_end)
    1337      119142 :                 CLAMP_PROBABILITY(hist_selec);
    1338             :             else
    1339             :             {
    1340       94526 :                 double      cutoff = 0.01 / (double) (sslot.nvalues - 1);
    1341             : 
    1342       94526 :                 if (hist_selec < cutoff)
    1343       33552 :                     hist_selec = cutoff;
    1344       60974 :                 else if (hist_selec > 1.0 - cutoff)
    1345       21910 :                     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      962556 :             for (int i = 0; i < sslot.nvalues; i++)
    1366             :             {
    1367             :                 Datum       fresult;
    1368             : 
    1369      962372 :                 fcinfo->args[0].value = sslot.values[i];
    1370      962372 :                 fcinfo->isnull = false;
    1371      962372 :                 fresult = FunctionCallInvoke(fcinfo);
    1372      962372 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    1373        2260 :                     nmatch++;
    1374             :             }
    1375         184 :             hist_selec = ((double) nmatch) / ((double) sslot.nvalues);
    1376             : 
    1377             :             /*
    1378             :              * As above, clamp to a hundredth of the histogram resolution.
    1379             :              * This case is surely even less trustworthy than the normal one,
    1380             :              * so we shouldn't believe exact 0 or 1 selectivity.  (Maybe the
    1381             :              * clamp should be more restrictive in this case?)
    1382             :              */
    1383             :             {
    1384         184 :                 double      cutoff = 0.01 / (double) (sslot.nvalues - 1);
    1385             : 
    1386         184 :                 if (hist_selec < cutoff)
    1387           8 :                     hist_selec = cutoff;
    1388         176 :                 else if (hist_selec > 1.0 - cutoff)
    1389           8 :                     hist_selec = 1.0 - cutoff;
    1390             :             }
    1391             :         }
    1392             : 
    1393      213852 :         free_attstatsslot(&sslot);
    1394             :     }
    1395             : 
    1396      287008 :     return hist_selec;
    1397             : }
    1398             : 
    1399             : /*
    1400             :  * Common wrapper function for the selectivity estimators that simply
    1401             :  * invoke scalarineqsel().
    1402             :  */
    1403             : static Datum
    1404       44788 : scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
    1405             : {
    1406       44788 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    1407       44788 :     Oid         operator = PG_GETARG_OID(1);
    1408       44788 :     List       *args = (List *) PG_GETARG_POINTER(2);
    1409       44788 :     int         varRelid = PG_GETARG_INT32(3);
    1410       44788 :     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       44788 :     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       44138 :     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       41362 :     if (((Const *) other)->constisnull)
    1440             :     {
    1441          66 :         ReleaseVariableStats(vardata);
    1442          66 :         PG_RETURN_FLOAT8(0.0);
    1443             :     }
    1444       41296 :     constval = ((Const *) other)->constvalue;
    1445       41296 :     consttype = ((Const *) other)->consttype;
    1446             : 
    1447             :     /*
    1448             :      * Force the var to be on the left to simplify logic in scalarineqsel.
    1449             :      */
    1450       41296 :     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       41296 :     selec = scalarineqsel(root, operator, isgt, iseq, collation,
    1464             :                           &vardata, constval, consttype);
    1465             : 
    1466       41296 :     ReleaseVariableStats(vardata);
    1467             : 
    1468       41296 :     PG_RETURN_FLOAT8((float8) selec);
    1469             : }
    1470             : 
    1471             : /*
    1472             :  *      scalarltsel     - Selectivity of "<" for scalars.
    1473             :  */
    1474             : Datum
    1475       15030 : scalarltsel(PG_FUNCTION_ARGS)
    1476             : {
    1477       15030 :     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       15264 : scalargtsel(PG_FUNCTION_ARGS)
    1494             : {
    1495       15264 :     return scalarineqsel_wrapper(fcinfo, true, false);
    1496             : }
    1497             : 
    1498             : /*
    1499             :  *      scalargesel     - Selectivity of ">=" for scalars.
    1500             :  */
    1501             : Datum
    1502        9946 : scalargesel(PG_FUNCTION_ARGS)
    1503             : {
    1504        9946 :     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       43798 : boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
    1517             : {
    1518             :     VariableStatData vardata;
    1519             :     double      selec;
    1520             : 
    1521       43798 :     examine_variable(root, arg, varRelid, &vardata);
    1522       43798 :     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       35650 :         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        8148 :         selec = 0.5;
    1535             :     }
    1536       43798 :     ReleaseVariableStats(vardata);
    1537       43798 :     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       17378 : nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
    1703             :             int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
    1704             : {
    1705             :     VariableStatData vardata;
    1706             :     double      selec;
    1707             : 
    1708       17378 :     examine_variable(root, arg, varRelid, &vardata);
    1709             : 
    1710       17378 :     if (HeapTupleIsValid(vardata.statsTuple))
    1711             :     {
    1712             :         Form_pg_statistic stats;
    1713             :         double      freq_null;
    1714             : 
    1715        9768 :         stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
    1716        9768 :         freq_null = stats->stanullfrac;
    1717             : 
    1718        9768 :         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        2544 :             case IS_NOT_NULL:
    1728             : 
    1729             :                 /*
    1730             :                  * Select not unknown (not null) values. Calculate from
    1731             :                  * freq_null.
    1732             :                  */
    1733        2544 :                 selec = 1.0 - freq_null;
    1734        2544 :                 break;
    1735           0 :             default:
    1736           0 :                 elog(ERROR, "unrecognized nulltesttype: %d",
    1737             :                      (int) nulltesttype);
    1738             :                 return (Selectivity) 0; /* keep compiler quiet */
    1739             :         }
    1740             :     }
    1741        7610 :     else if (vardata.var && IsA(vardata.var, Var) &&
    1742        6858 :              ((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        7550 :         switch (nulltesttype)
    1756             :         {
    1757        2108 :             case IS_NULL:
    1758        2108 :                 selec = DEFAULT_UNK_SEL;
    1759        2108 :                 break;
    1760        5442 :             case IS_NOT_NULL:
    1761        5442 :                 selec = DEFAULT_NOT_UNK_SEL;
    1762        5442 :                 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       17378 :     ReleaseVariableStats(vardata);
    1771             : 
    1772             :     /* result should be in range, but make sure... */
    1773       17378 :     CLAMP_PROBABILITY(selec);
    1774             : 
    1775       17378 :     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      124640 : strip_array_coercion(Node *node)
    1788             : {
    1789             :     for (;;)
    1790             :     {
    1791      124722 :         if (node && IsA(node, ArrayCoerceExpr))
    1792          82 :         {
    1793        2934 :             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        2934 :             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      121788 :         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      124640 :     return node;
    1814             : }
    1815             : 
    1816             : /*
    1817             :  *      scalararraysel      - Selectivity of ScalarArrayOpExpr Node.
    1818             :  */
    1819             : Selectivity
    1820       21260 : scalararraysel(PlannerInfo *root,
    1821             :                ScalarArrayOpExpr *clause,
    1822             :                bool is_join_clause,
    1823             :                int varRelid,
    1824             :                JoinType jointype,
    1825             :                SpecialJoinInfo *sjinfo)
    1826             : {
    1827       21260 :     Oid         operator = clause->opno;
    1828       21260 :     bool        useOr = clause->useOr;
    1829       21260 :     bool        isEquality = false;
    1830       21260 :     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       21260 :     leftop = (Node *) linitial(clause->args);
    1844       21260 :     rightop = (Node *) lsecond(clause->args);
    1845             : 
    1846             :     /* aggressively reduce both sides to constants */
    1847       21260 :     leftop = estimate_expression_value(root, leftop);
    1848       21260 :     rightop = estimate_expression_value(root, rightop);
    1849             : 
    1850             :     /* get nominal (after relabeling) element type of rightop */
    1851       21260 :     nominal_element_type = get_base_element_type(exprType(rightop));
    1852       21260 :     if (!OidIsValid(nominal_element_type))
    1853           0 :         return (Selectivity) 0.5;   /* probably shouldn't happen */
    1854             :     /* get nominal collation, too, for generating constants */
    1855       21260 :     nominal_element_collation = exprCollation(rightop);
    1856             : 
    1857             :     /* look through any binary-compatible relabeling of rightop */
    1858       21260 :     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       21260 :     typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
    1865       21260 :     if (OidIsValid(typentry->eq_opr))
    1866             :     {
    1867       21256 :         if (operator == typentry->eq_opr)
    1868       17982 :             isEquality = true;
    1869        3274 :         else if (get_negator(operator) == typentry->eq_opr)
    1870        2708 :             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       21260 :     if ((isEquality || isInequality) && !is_join_clause)
    1880             :     {
    1881       20690 :         s1 = scalararraysel_containment(root, leftop, rightop,
    1882             :                                         nominal_element_type,
    1883             :                                         isEquality, useOr, varRelid);
    1884       20690 :         if (s1 >= 0.0)
    1885         118 :             return s1;
    1886             :     }
    1887             : 
    1888             :     /*
    1889             :      * Look up the underlying operator's selectivity estimator. Punt if it
    1890             :      * hasn't got one.
    1891             :      */
    1892       21142 :     if (is_join_clause)
    1893           0 :         oprsel = get_oprjoin(operator);
    1894             :     else
    1895       21142 :         oprsel = get_oprrest(operator);
    1896       21142 :     if (!oprsel)
    1897           4 :         return (Selectivity) 0.5;
    1898       21138 :     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       21138 :     if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
    1909       18060 :         isEquality = true;
    1910        3078 :     else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
    1911        2598 :         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       21138 :     if (rightop && IsA(rightop, Const))
    1926       16974 :     {
    1927       17004 :         Datum       arraydatum = ((Const *) rightop)->constvalue;
    1928       17004 :         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       17004 :         if (arrayisnull)        /* qual can't succeed if null array */
    1939          30 :             return (Selectivity) 0.0;
    1940       16974 :         arrayval = DatumGetArrayTypeP(arraydatum);
    1941       16974 :         get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
    1942             :                              &elmlen, &elmbyval, &elmalign);
    1943       16974 :         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       16974 :         s1 = s1disjoint = (useOr ? 0.0 : 1.0);
    1963             : 
    1964       73822 :         for (i = 0; i < num_elems; i++)
    1965             :         {
    1966             :             List       *args;
    1967             :             Selectivity s2;
    1968             : 
    1969       56848 :             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       56848 :             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       56848 :                 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
    1987             :                                                       clause->inputcollid,
    1988             :                                                       PointerGetDatum(root),
    1989             :                                                       ObjectIdGetDatum(operator),
    1990             :                                                       PointerGetDatum(args),
    1991             :                                                       Int32GetDatum(varRelid)));
    1992             : 
    1993       56848 :             if (useOr)
    1994             :             {
    1995       48466 :                 s1 = s1 + s2 - s1 * s2;
    1996       48466 :                 if (isEquality)
    1997       47422 :                     s1disjoint += s2;
    1998             :             }
    1999             :             else
    2000             :             {
    2001        8382 :                 s1 = s1 * s2;
    2002        8382 :                 if (isInequality)
    2003        8070 :                     s1disjoint += s2 - 1.0;
    2004             :             }
    2005             :         }
    2006             : 
    2007             :         /* accept disjoint-probability estimate if in range */
    2008       16974 :         if ((useOr ? isEquality : isInequality) &&
    2009       16334 :             s1disjoint >= 0.0 && s1disjoint <= 1.0)
    2010       16304 :             s1 = s1disjoint;
    2011             :     }
    2012        4134 :     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        3840 :         dummyexpr = makeNode(CaseTestExpr);
    2092        3840 :         dummyexpr->typeId = nominal_element_type;
    2093        3840 :         dummyexpr->typeMod = -1;
    2094        3840 :         dummyexpr->collation = clause->inputcollid;
    2095        3840 :         args = list_make2(leftop, dummyexpr);
    2096        3840 :         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        3840 :             s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
    2106             :                                                   clause->inputcollid,
    2107             :                                                   PointerGetDatum(root),
    2108             :                                                   ObjectIdGetDatum(operator),
    2109             :                                                   PointerGetDatum(args),
    2110             :                                                   Int32GetDatum(varRelid)));
    2111        3840 :         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       42240 :         for (i = 0; i < 10; i++)
    2119             :         {
    2120       38400 :             if (useOr)
    2121       38400 :                 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       21108 :     CLAMP_PROBABILITY(s1);
    2129             : 
    2130       21108 :     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      103380 : estimate_array_length(PlannerInfo *root, Node *arrayexpr)
    2144             : {
    2145             :     /* look through any binary-compatible relabeling of arrayexpr */
    2146      103380 :     arrayexpr = strip_array_coercion(arrayexpr);
    2147             : 
    2148      103380 :     if (arrayexpr && IsA(arrayexpr, Const))
    2149             :     {
    2150       45532 :         Datum       arraydatum = ((Const *) arrayexpr)->constvalue;
    2151       45532 :         bool        arrayisnull = ((Const *) arrayexpr)->constisnull;
    2152             :         ArrayType  *arrayval;
    2153             : 
    2154       45532 :         if (arrayisnull)
    2155          90 :             return 0;
    2156       45442 :         arrayval = DatumGetArrayTypeP(arraydatum);
    2157       45442 :         return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
    2158             :     }
    2159       57848 :     else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
    2160         498 :              !((ArrayExpr *) arrayexpr)->multidims)
    2161             :     {
    2162         498 :         return list_length(((ArrayExpr *) arrayexpr)->elements);
    2163             :     }
    2164       57350 :     else if (arrayexpr && root)
    2165             :     {
    2166             :         /* See if we can find any statistics about it */
    2167             :         VariableStatData vardata;
    2168             :         AttStatsSlot sslot;
    2169       57350 :         double      nelem = 0;
    2170             : 
    2171       57350 :         examine_variable(root, arrayexpr, 0, &vardata);
    2172       57350 :         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        6960 :             if (get_attstatsslot(&sslot, vardata.statsTuple,
    2181             :                                  STATISTIC_KIND_DECHIST, InvalidOid,
    2182             :                                  ATTSTATSSLOT_NUMBERS))
    2183             :             {
    2184        6846 :                 if (sslot.nnumbers > 0)
    2185        6846 :                     nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
    2186        6846 :                 free_attstatsslot(&sslot);
    2187             :             }
    2188             :         }
    2189       57350 :         ReleaseVariableStats(vardata);
    2190             : 
    2191       57350 :         if (nelem > 0)
    2192        6846 :             return nelem;
    2193             :     }
    2194             : 
    2195             :     /* Else use a default guess --- this should match scalararraysel */
    2196       50504 :     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      224080 : eqjoinsel(PG_FUNCTION_ARGS)
    2277             : {
    2278      224080 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    2279      224080 :     Oid         operator = PG_GETARG_OID(1);
    2280      224080 :     List       *args = (List *) PG_GETARG_POINTER(2);
    2281             : 
    2282             : #ifdef NOT_USED
    2283             :     JoinType    jointype = (JoinType) PG_GETARG_INT16(3);
    2284             : #endif
    2285      224080 :     SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
    2286      224080 :     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      224080 :     Form_pg_statistic stats1 = NULL;
    2299      224080 :     Form_pg_statistic stats2 = NULL;
    2300      224080 :     bool        have_mcvs1 = false;
    2301      224080 :     bool        have_mcvs2 = false;
    2302             :     bool        get_mcv_stats;
    2303             :     bool        join_is_reversed;
    2304             :     RelOptInfo *inner_rel;
    2305             : 
    2306      224080 :     get_join_variables(root, args, sjinfo,
    2307             :                        &vardata1, &vardata2, &join_is_reversed);
    2308             : 
    2309      224080 :     nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
    2310      224080 :     nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
    2311             : 
    2312      224080 :     opfuncoid = get_opcode(operator);
    2313             : 
    2314      224080 :     memset(&sslot1, 0, sizeof(sslot1));
    2315      224080 :     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      629044 :     get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
    2322      318198 :                      HeapTupleIsValid(vardata2.statsTuple) &&
    2323      137314 :                      get_attstatsslot(&sslot1, vardata1.statsTuple,
    2324             :                                       STATISTIC_KIND_MCV, InvalidOid,
    2325      404964 :                                       0) &&
    2326       54030 :                      get_attstatsslot(&sslot2, vardata2.statsTuple,
    2327             :                                       STATISTIC_KIND_MCV, InvalidOid,
    2328             :                                       0));
    2329             : 
    2330      224080 :     if (HeapTupleIsValid(vardata1.statsTuple))
    2331             :     {
    2332             :         /* note we allow use of nullfrac regardless of security check */
    2333      180884 :         stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
    2334      195328 :         if (get_mcv_stats &&
    2335       14444 :             statistic_proc_security_check(&vardata1, opfuncoid))
    2336       14444 :             have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
    2337             :                                           STATISTIC_KIND_MCV, InvalidOid,
    2338             :                                           ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
    2339             :     }
    2340             : 
    2341      224080 :     if (HeapTupleIsValid(vardata2.statsTuple))
    2342             :     {
    2343             :         /* note we allow use of nullfrac regardless of security check */
    2344      149360 :         stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
    2345      163804 :         if (get_mcv_stats &&
    2346       14444 :             statistic_proc_security_check(&vardata2, opfuncoid))
    2347       14444 :             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      224080 :     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      224080 :     switch (sjinfo->jointype)
    2362             :     {
    2363      213390 :         case JOIN_INNER:
    2364             :         case JOIN_LEFT:
    2365             :         case JOIN_FULL:
    2366      213390 :             selec = selec_inner;
    2367      213390 :             break;
    2368       10690 :         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       10690 :             inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
    2378             : 
    2379       10690 :             if (!join_is_reversed)
    2380        6580 :                 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        4110 :                 Oid         commop = get_commutator(operator);
    2391        4110 :                 Oid         commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
    2392             : 
    2393        4110 :                 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       10690 :             selec = Min(selec, inner_rel->rows * selec_inner);
    2414       10690 :             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      224080 :     free_attstatsslot(&sslot1);
    2424      224080 :     free_attstatsslot(&sslot2);
    2425             : 
    2426      224080 :     ReleaseVariableStats(vardata1);
    2427      224080 :     ReleaseVariableStats(vardata2);
    2428             : 
    2429      224080 :     CLAMP_PROBABILITY(selec);
    2430             : 
    2431      224080 :     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      224080 : 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      224080 :     if (have_mcvs1 && have_mcvs2)
    2452       14444 :     {
    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       14444 :         LOCAL_FCINFO(fcinfo, 2);
    2466             :         FmgrInfo    eqproc;
    2467             :         bool       *hasmatch1;
    2468             :         bool       *hasmatch2;
    2469       14444 :         double      nullfrac1 = stats1->stanullfrac;
    2470       14444 :         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       14444 :         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       14444 :         InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
    2492             :                                  NULL, NULL);
    2493       14444 :         fcinfo->args[0].isnull = false;
    2494       14444 :         fcinfo->args[1].isnull = false;
    2495             : 
    2496       14444 :         hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
    2497       14444 :         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       14444 :         matchprodfreq = 0.0;
    2506       14444 :         nmatches = 0;
    2507      588716 :         for (i = 0; i < sslot1->nvalues; i++)
    2508             :         {
    2509             :             int         j;
    2510             : 
    2511      574272 :             fcinfo->args[0].value = sslot1->values[i];
    2512             : 
    2513    22590482 :             for (j = 0; j < sslot2->nvalues; j++)
    2514             :             {
    2515             :                 Datum       fresult;
    2516             : 
    2517    22210998 :                 if (hasmatch2[j])
    2518     5799468 :                     continue;
    2519    16411530 :                 fcinfo->args[1].value = sslot2->values[j];
    2520    16411530 :                 fcinfo->isnull = false;
    2521    16411530 :                 fresult = FunctionCallInvoke(fcinfo);
    2522    16411530 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    2523             :                 {
    2524      194788 :                     hasmatch1[i] = hasmatch2[j] = true;
    2525      194788 :                     matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
    2526      194788 :                     nmatches++;
    2527      194788 :                     break;
    2528             :                 }
    2529             :             }
    2530             :         }
    2531       14444 :         CLAMP_PROBABILITY(matchprodfreq);
    2532             :         /* Sum up frequencies of matched and unmatched MCVs */
    2533       14444 :         matchfreq1 = unmatchfreq1 = 0.0;
    2534      588716 :         for (i = 0; i < sslot1->nvalues; i++)
    2535             :         {
    2536      574272 :             if (hasmatch1[i])
    2537      194788 :                 matchfreq1 += sslot1->numbers[i];
    2538             :             else
    2539      379484 :                 unmatchfreq1 += sslot1->numbers[i];
    2540             :         }
    2541       14444 :         CLAMP_PROBABILITY(matchfreq1);
    2542       14444 :         CLAMP_PROBABILITY(unmatchfreq1);
    2543       14444 :         matchfreq2 = unmatchfreq2 = 0.0;
    2544      413826 :         for (i = 0; i < sslot2->nvalues; i++)
    2545             :         {
    2546      399382 :             if (hasmatch2[i])
    2547      194788 :                 matchfreq2 += sslot2->numbers[i];
    2548             :             else
    2549      204594 :                 unmatchfreq2 += sslot2->numbers[i];
    2550             :         }
    2551       14444 :         CLAMP_PROBABILITY(matchfreq2);
    2552       14444 :         CLAMP_PROBABILITY(unmatchfreq2);
    2553       14444 :         pfree(hasmatch1);
    2554       14444 :         pfree(hasmatch2);
    2555             : 
    2556             :         /*
    2557             :          * Compute total frequency of non-null values that are not in the MCV
    2558             :          * lists.
    2559             :          */
    2560       14444 :         otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
    2561       14444 :         otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
    2562       14444 :         CLAMP_PROBABILITY(otherfreq1);
    2563       14444 :         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       14444 :         totalsel1 = matchprodfreq;
    2574       14444 :         if (nd2 > sslot2->nvalues)
    2575        6292 :             totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
    2576       14444 :         if (nd2 > nmatches)
    2577       11148 :             totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
    2578       11148 :                 (nd2 - nmatches);
    2579             :         /* Same estimate from the point of view of relation 2. */
    2580       14444 :         totalsel2 = matchprodfreq;
    2581       14444 :         if (nd1 > sslot1->nvalues)
    2582        6940 :             totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
    2583       14444 :         if (nd1 > nmatches)
    2584        9884 :             totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
    2585        9884 :                 (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       14444 :         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      209636 :         double      nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
    2618      209636 :         double      nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
    2619             : 
    2620      209636 :         selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
    2621      209636 :         if (nd1 > nd2)
    2622      107742 :             selec /= nd1;
    2623             :         else
    2624      101894 :             selec /= nd2;
    2625             :     }
    2626             : 
    2627      224080 :     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       10690 : 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       10690 :     if (vardata2->rel)
    2669             :     {
    2670       10684 :         if (nd2 >= vardata2->rel->rows)
    2671             :         {
    2672        8562 :             nd2 = vardata2->rel->rows;
    2673        8562 :             isdefault2 = false;
    2674             :         }
    2675             :     }
    2676       10690 :     if (nd2 >= inner_rel->rows)
    2677             :     {
    2678        8504 :         nd2 = inner_rel->rows;
    2679        8504 :         isdefault2 = false;
    2680             :     }
    2681             : 
    2682       10690 :     if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
    2683         612 :     {
    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         612 :         LOCAL_FCINFO(fcinfo, 2);
    2693             :         FmgrInfo    eqproc;
    2694             :         bool       *hasmatch1;
    2695             :         bool       *hasmatch2;
    2696         612 :         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         612 :         clamped_nvalues2 = Min(sslot2->nvalues, nd2);
    2712             : 
    2713         612 :         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         612 :         InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
    2722             :                                  NULL, NULL);
    2723         612 :         fcinfo->args[0].isnull = false;
    2724         612 :         fcinfo->args[1].isnull = false;
    2725             : 
    2726         612 :         hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
    2727         612 :         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         612 :         nmatches = 0;
    2736       12772 :         for (i = 0; i < sslot1->nvalues; i++)
    2737             :         {
    2738             :             int         j;
    2739             : 
    2740       12160 :             fcinfo->args[0].value = sslot1->values[i];
    2741             : 
    2742      457932 :             for (j = 0; j < clamped_nvalues2; j++)
    2743             :             {
    2744             :                 Datum       fresult;
    2745             : 
    2746      456650 :                 if (hasmatch2[j])
    2747      382244 :                     continue;
    2748       74406 :                 fcinfo->args[1].value = sslot2->values[j];
    2749       74406 :                 fcinfo->isnull = false;
    2750       74406 :                 fresult = FunctionCallInvoke(fcinfo);
    2751       74406 :                 if (!fcinfo->isnull && DatumGetBool(fresult))
    2752             :                 {
    2753       10878 :                     hasmatch1[i] = hasmatch2[j] = true;
    2754       10878 :                     nmatches++;
    2755       10878 :                     break;
    2756             :                 }
    2757             :             }
    2758             :         }
    2759             :         /* Sum up frequencies of matched MCVs */
    2760         612 :         matchfreq1 = 0.0;
    2761       12772 :         for (i = 0; i < sslot1->nvalues; i++)
    2762             :         {
    2763       12160 :             if (hasmatch1[i])
    2764       10878 :                 matchfreq1 += sslot1->numbers[i];
    2765             :         }
    2766         612 :         CLAMP_PROBABILITY(matchfreq1);
    2767         612 :         pfree(hasmatch1);
    2768         612 :         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         612 :         if (!isdefault1 && !isdefault2)
    2786             :         {
    2787         612 :             nd1 -= nmatches;
    2788         612 :             nd2 -= nmatches;
    2789         612 :             if (nd1 <= nd2 || nd2 < 0)
    2790         582 :                 uncertainfrac = 1.0;
    2791             :             else
    2792          30 :                 uncertainfrac = nd2 / nd1;
    2793             :         }
    2794             :         else
    2795           0 :             uncertainfrac = 0.5;
    2796         612 :         uncertain = 1.0 - matchfreq1 - nullfrac1;
    2797         612 :         CLAMP_PROBABILITY(uncertain);
    2798         612 :         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       10078 :         double      nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
    2807             : 
    2808       10078 :         if (!isdefault1 && !isdefault2)
    2809             :         {
    2810        7728 :             if (nd1 <= nd2 || nd2 < 0)
    2811        5084 :                 selec = 1.0 - nullfrac1;
    2812             :             else
    2813        2644 :                 selec = (nd2 / nd1) * (1.0 - nullfrac1);
    2814             :         }
    2815             :         else
    2816        2350 :             selec = 0.5 * (1.0 - nullfrac1);
    2817             :     }
    2818             : 
    2819       10690 :     return selec;
    2820             : }
    2821             : 
    2822             : /*
    2823             :  *      neqjoinsel      - Join selectivity of "!="
    2824             :  */
    2825             : Datum
    2826        3700 : neqjoinsel(PG_FUNCTION_ARGS)
    2827             : {
    2828        3700 :     PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
    2829        3700 :     Oid         operator = PG_GETARG_OID(1);
    2830        3700 :     List       *args = (List *) PG_GETARG_POINTER(2);
    2831        3700 :     JoinType    jointype = (JoinType) PG_GETARG_INT16(3);
    2832        3700 :     SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
    2833        3700 :     Oid         collation = PG_GET_COLLATION();
    2834             :     float8      result;
    2835             : 
    2836        3700 :     if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
    2837        1254 :     {
    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        1254 :         get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
    2860        1254 :         statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
    2861        1254 :         if (HeapTupleIsValid(statsTuple))
    2862        1022 :             nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
    2863             :         else
    2864         232 :             nullfrac = 0.0;
    2865        1254 :         ReleaseVariableStats(leftvar);
    2866        1254 :         ReleaseVariableStats(rightvar);
    2867             : 
    2868        1254 :         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        2446 :         Oid         eqop = get_negator(operator);
    2877             : 
    2878        2446 :         if (eqop)
    2879             :         {
    2880             :             result =
    2881        2446 :                 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        2446 :         result = 1.0 - result;
    2895             :     }
    2896             : 
    2897        3700 :     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      114118 : 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      114118 :     *leftstart = *rightstart = 0.0;
    2996      114118 :     *leftend = *rightend = 1.0;
    2997             : 
    2998             :     /* Deconstruct the merge clause */
    2999      114118 :     if (!is_opclause(clause))
    3000           0 :         return;                 /* shouldn't happen */
    3001      114118 :     opno = ((OpExpr *) clause)->opno;
    3002      114118 :     collation = ((OpExpr *) clause)->inputcollid;
    3003      114118 :     left = get_leftop((Expr *) clause);
    3004      114118 :     right = get_rightop((Expr *) clause);
    3005      114118 :     if (!right)
    3006           0 :         return;                 /* shouldn't happen */
    3007             : 
    3008             :     /* Look for stats for the inputs */
    3009      114118 :     examine_variable(root, left, 0, &leftvar);
    3010      114118 :     examine_variable(root, right, 0, &rightvar);
    3011             : 
    3012      114118 :     opmethod = get_opfamily_method(opfamily);
    3013             : 
    3014             :     /* Extract the operator's declared left/right datatypes */
    3015      114118 :     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      114118 :     switch (cmptype)
    3029             :     {
    3030      114046 :         case COMPARE_LT:
    3031      114046 :             isgt = false;
    3032      114046 :             ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
    3033      114046 :             lestrat = IndexAmTranslateCompareType(COMPARE_LE, opmethod, opfamily, true);
    3034      114046 :             if (op_lefttype == op_righttype)
    3035             :             {
    3036             :                 /* easy case */
    3037      112664 :                 ltop = get_opfamily_member(opfamily,
    3038             :                                            op_lefttype, op_righttype,
    3039             :                                            ltstrat);
    3040      112664 :                 leop = get_opfamily_member(opfamily,
    3041             :                                            op_lefttype, op_righttype,
    3042             :                                            lestrat);
    3043      112664 :                 lsortop = ltop;
    3044      112664 :                 rsortop = ltop;
    3045      112664 :                 lstatop = lsortop;
    3046      112664 :                 rstatop = rsortop;
    3047      112664 :                 revltop = ltop;
    3048      112664 :                 revleop = leop;
    3049             :             }
    3050             :             else
    3051             :             {
    3052        1382 :                 ltop = get_opfamily_member(opfamily,
    3053             :                                            op_lefttype, op_righttype,
    3054             :                                            ltstrat);
    3055        1382 :                 leop = get_opfamily_member(opfamily,
    3056             :                                            op_lefttype, op_righttype,
    3057             :                                            lestrat);
    3058        1382 :                 lsortop = get_opfamily_member(opfamily,
    3059             :                                               op_lefttype, op_lefttype,
    3060             :                                               ltstrat);
    3061        1382 :                 rsortop = get_opfamily_member(opfamily,
    3062             :                                               op_righttype, op_righttype,
    3063             :                                               ltstrat);
    3064        1382 :                 lstatop = lsortop;
    3065        1382 :                 rstatop = rsortop;
    3066        1382 :                 revltop = get_opfamily_member(opfamily,
    3067             :                                               op_righttype, op_lefttype,
    3068             :                                               ltstrat);
    3069        1382 :                 revleop = get_opfamily_member(opfamily,
    3070             :                                               op_righttype, op_lefttype,
    3071             :                                               lestrat);
    3072             :             }
    3073      114046 :             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      114118 :     if (!OidIsValid(lsortop) ||
    3131      114118 :         !OidIsValid(rsortop) ||
    3132      114118 :         !OidIsValid(lstatop) ||
    3133      114118 :         !OidIsValid(rstatop) ||
    3134      114106 :         !OidIsValid(ltop) ||
    3135      114106 :         !OidIsValid(leop) ||
    3136      114106 :         !OidIsValid(revltop) ||
    3137             :         !OidIsValid(revleop))
    3138          12 :         goto fail;              /* insufficient info in catalogs */
    3139             : 
    3140             :     /* Try to get ranges of both inputs */
    3141      114106 :     if (!isgt)
    3142             :     {
    3143      114034 :         if (!get_variable_range(root, &leftvar, lstatop, collation,
    3144             :                                 &leftmin, &leftmax))
    3145       24074 :             goto fail;          /* no range available from stats */
    3146       89960 :         if (!get_variable_range(root, &rightvar, rstatop, collation,
    3147             :                                 &rightmin, &rightmax))
    3148       24254 :             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       65748 :     selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
    3167             :                           rightmax, op_righttype);
    3168       65748 :     if (selec != DEFAULT_INEQ_SEL)
    3169       65742 :         *leftend = selec;
    3170             : 
    3171             :     /* And similarly for the right variable. */
    3172       65748 :     selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
    3173             :                           leftmax, op_lefttype);
    3174       65748 :     if (selec != DEFAULT_INEQ_SEL)
    3175       65748 :         *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       65748 :     if (*leftend > *rightend)
    3184       24784 :         *leftend = 1.0;
    3185       40964 :     else if (*leftend < *rightend)
    3186       32728 :         *rightend = 1.0;
    3187             :     else
    3188        8236 :         *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       65748 :     selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
    3197             :                           rightmin, op_righttype);
    3198       65748 :     if (selec != DEFAULT_INEQ_SEL)
    3199       65748 :         *leftstart = selec;
    3200             : 
    3201             :     /* And similarly for the right variable. */
    3202       65748 :     selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
    3203             :                           leftmin, op_lefttype);
    3204       65748 :     if (selec != DEFAULT_INEQ_SEL)
    3205       65748 :         *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       65748 :     if (*leftstart < *rightstart)
    3214       17388 :         *leftstart = 0.0;
    3215       48360 :     else if (*leftstart > *rightstart)
    3216       23378 :         *rightstart = 0.0;
    3217             :     else
    3218       24982 :         *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       65748 :     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       65748 :     if (*leftstart >= *leftend)
    3250             :     {
    3251         202 :         *leftstart = 0.0;
    3252         202 :         *leftend = 1.0;
    3253             :     }
    3254       65748 :     if (*rightstart >= *rightend)
    3255             :     {
    3256        1044 :         *rightstart = 0.0;
    3257        1044 :         *rightend = 1.0;
    3258             :     }
    3259             : 
    3260       64704 : fail:
    3261      114118 :     ReleaseVariableStats(leftvar);
    3262      114118 :     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      363656 : 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      363656 :     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      363656 :     var = remove_nulling_relids(var, root->outer_join_rels, NULL);
    3333             : 
    3334      442044 :     foreach(lc, varinfos)
    3335             :     {
    3336       79440 :         varinfo = (GroupVarInfo *) lfirst(lc);
    3337             : 
    3338             :         /* Drop exact duplicates */
    3339       79440 :         if (equal(var, varinfo->var))
    3340        1052 :             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       83460 :         if (vardata->rel != varinfo->rel &&
    3348        4856 :             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      362604 :     varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
    3364             : 
    3365      362604 :     varinfo->var = var;
    3366      362604 :     varinfo->rel = vardata->rel;
    3367      362604 :     varinfo->ndistinct = ndistinct;
    3368      362604 :     varinfo->isdefault = isdefault;
    3369      362604 :     varinfos = lappend(varinfos, varinfo);
    3370      362604 :     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      315302 : estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
    3446             :                     List **pgset, EstimationInfo *estinfo)
    3447             : {
    3448      315302 :     List       *varinfos = NIL;
    3449      315302 :     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      315302 :     if (estinfo != NULL)
    3456      273314 :         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      315302 :     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      315302 :     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      314232 :     numdistinct = 1.0;
    3482             : 
    3483      314232 :     i = 0;
    3484      676154 :     foreach(l, groupExprs)
    3485             :     {
    3486      361970 :         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      361970 :         if (pgset && !list_member_int(*pgset, i++))
    3494      295006 :             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      361182 :         this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
    3508      361182 :         if (srf_multiplier < this_srf_multiplier)
    3509         132 :             srf_multiplier = this_srf_multiplier;
    3510             : 
    3511             :         /* Short-circuit for expressions returning boolean */
    3512      361182 :         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      360984 :         examine_variable(root, groupexpr, 0, &vardata);
    3532      360984 :         if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
    3533             :         {
    3534      293342 :             varinfos = add_unique_group_var(root, varinfos,
    3535             :                                             groupexpr, &vardata);
    3536      293342 :             ReleaseVariableStats(vardata);
    3537      293342 :             continue;
    3538             :         }
    3539       67642 :         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       67642 :         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       67642 :         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      137230 :         foreach(l2, varshere)
    3569             :         {
    3570       70314 :             Node       *var = (Node *) lfirst(l2);
    3571             : 
    3572       70314 :             examine_variable(root, var, 0, &vardata);
    3573       70314 :             varinfos = add_unique_group_var(root, varinfos, var, &vardata);
    3574       70314 :             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      314184 :     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          44 :             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      315772 :         GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
    3607      315772 :         RelOptInfo *rel = varinfo1->rel;
    3608      315772 :         double      reldistinct = 1;
    3609      315772 :         double      relmaxndistinct = reldistinct;
    3610      315772 :         int         relvarcount = 0;
    3611      315772 :         List       *newvarinfos = NIL;
    3612      315772 :         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      315772 :         relvarinfos = lappend(relvarinfos, varinfo1);
    3619      366530 :         for_each_from(l, varinfos, 1)
    3620             :         {
    3621       50758 :             GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
    3622             : 
    3623       50758 :             if (varinfo2->rel == varinfo1->rel)
    3624             :             {
    3625             :                 /* varinfos on current rel */
    3626       46808 :                 relvarinfos = lappend(relvarinfos, varinfo2);
    3627             :             }
    3628             :             else
    3629             :             {
    3630             :                 /* not time to process varinfo2 yet */
    3631        3950 :                 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      631670 :         while (relvarinfos)
    3648             :         {
    3649             :             double      mvndistinct;
    3650             : 
    3651      315898 :             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      677224 :                 foreach(l, relvarinfos)
    3662             :                 {
    3663      361728 :                     GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
    3664             : 
    3665      361728 :                     reldistinct *= varinfo2->ndistinct;
    3666      361728 :                     if (relmaxndistinct < varinfo2->ndistinct)
    3667      317208 :                         relmaxndistinct = varinfo2->ndistinct;
    3668      361728 :                     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      361728 :                     if (estinfo != NULL && varinfo2->isdefault)
    3675       17706 :                         estinfo->flags |= SELFLAG_USED_DEFAULT;
    3676             :                 }
    3677             : 
    3678             :                 /* we're done with this relation */
    3679      315496 :                 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      315772 :         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      314744 :             double      clamp = rel->tuples;
    3697             : 
    3698      314744 :             if (relvarcount > 1)
    3699             :             {
    3700       42264 :                 clamp *= 0.1;
    3701       42264 :                 if (clamp < relmaxndistinct)
    3702             :                 {
    3703       40168 :                     clamp = relmaxndistinct;
    3704             :                     /* for sanity in case some ndistinct is too large: */
    3705       40168 :                     if (clamp > rel->tuples)
    3706          78 :                         clamp = rel->tuples;
    3707             :                 }
    3708             :             }
    3709      314744 :             if (reldistinct > clamp)
    3710       34754 :                 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      314744 :             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      103430 :                 reldistinct *=
    3754      103430 :                     (1 - pow((rel->tuples - rel->rows) / rel->tuples,
    3755      103430 :                              rel->tuples / reldistinct));
    3756             :             }
    3757      314744 :             reldistinct = clamp_row_est(reldistinct);
    3758             : 
    3759             :             /*
    3760             :              * Update estimate of total distinct groups.
    3761             :              */
    3762      314744 :             numdistinct *= reldistinct;
    3763             :         }
    3764             : 
    3765      315772 :         varinfos = newvarinfos;
    3766      315772 :     } while (varinfos != NIL);
    3767             : 
    3768             :     /* Now we can account for the effects of any SRFs */
    3769      313790 :     numdistinct *= srf_multiplier;
    3770             : 
    3771             :     /* Round off */
    3772      313790 :     numdistinct = ceil(numdistinct);
    3773             : 
    3774             :     /* Guard against out-of-range answers */
    3775      313790 :     if (numdistinct > input_rows)
    3776       68730 :         numdistinct = input_rows;
    3777      313790 :     if (numdistinct < 1.0)
    3778           0 :         numdistinct = 1.0;
    3779             : 
    3780      313790 :     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      274872 : 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      274872 :     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      242988 :         return hashclauses;
    3812             :     }
    3813             : 
    3814             :     /* "clauses" is the list of hashclauses we've not dealt with yet */
    3815       31884 :     clauses = list_copy(hashclauses);
    3816             :     /* "otherclauses" holds clauses we are going to return to caller */
    3817       31884 :     otherclauses = NIL;
    3818             :     /* current estimate of ndistinct */
    3819       31884 :     ndistinct = 1.0;
    3820       63780 :     while (clauses != NIL)
    3821             :     {
    3822             :         ListCell   *lc;
    3823       31896 :         int         relid = -1;
    3824       31896 :         List       *varinfos = NIL;
    3825       31896 :         List       *origin_rinfos = NIL;
    3826             :         double      mvndistinct;
    3827             :         List       *origin_varinfos;
    3828       31896 :         int         group_relid = -1;
    3829       31896 :         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       96300 :         foreach(lc, clauses)
    3840             :         {
    3841       64404 :             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      128808 :             relids = rinfo->outer_is_left ?
    3852       64404 :                 rinfo->right_relids : rinfo->left_relids;
    3853      128808 :             expr = rinfo->outer_is_left ?
    3854       64404 :                 get_rightop(rinfo->clause) : get_leftop(rinfo->clause);
    3855             : 
    3856       64404 :             if (bms_get_singleton_member(relids, &relid) &&
    3857       61838 :                 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       64344 :                 otherclauses = lappend(otherclauses, rinfo);
    3959             :             }
    3960             : 
    3961       64392 :             clauses = foreach_delete_current(clauses, lc);
    3962             :         }
    3963             : 
    3964       31896 :         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       31884 :             otherclauses = list_concat(otherclauses, origin_rinfos);
    3971       31884 :             list_free_deep(varinfos);
    3972       31884 :             list_free(origin_rinfos);
    3973       31884 :             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       31884 :     *innerbucketsize = 1.0 / ndistinct;
    4017       31884 :     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      163000 : 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      163000 :     examine_variable(root, hashkey, 0, &vardata);
    4077             : 
    4078             :     /* Look up the frequency of the most common value, if available */
    4079      163000 :     *mcv_freq = 0.0;
    4080             : 
    4081      163000 :     if (HeapTupleIsValid(vardata.statsTuple))
    4082             :     {
    4083      113542 :         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       56436 :             if (sslot.nnumbers > 0)
    4091       56436 :                 *mcv_freq = sslot.numbers[0];
    4092       56436 :             free_attstatsslot(&sslot);
    4093             :         }
    4094             :     }
    4095             : 
    4096             :     /* Get number of distinct values */
    4097      163000 :     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      163000 :     if (isdefault)
    4104             :     {
    4105       20824 :         *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
    4106       20824 :         ReleaseVariableStats(vardata);
    4107       20824 :         return;
    4108             :     }
    4109             : 
    4110             :     /* Get fraction that are null */
    4111      142176 :     if (HeapTupleIsValid(vardata.statsTuple))
    4112             :     {
    4113             :         Form_pg_statistic stats;
    4114             : 
    4115      113524 :         stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
    4116      113524 :         stanullfrac = stats->stanullfrac;
    4117             :     }
    4118             :     else
    4119       28652 :         stanullfrac = 0.0;
    4120             : 
    4121             :     /* Compute avg freq of all distinct data values in raw relation */
    4122      142176 :     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      142176 :     if (vardata.rel && vardata.rel->tuples > 0)
    4133             :     {
    4134      142160 :         ndistinct *= vardata.rel->rows / vardata.rel->tuples;
    4135      142160 :         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      142176 :     if (ndistinct > nbuckets)
    4144          88 :         estfract = 1.0 / nbuckets;
    4145             :     else
    4146      142088 :         estfract = 1.0 / ndistinct;
    4147             : 
    4148             :     /*
    4149             :      * Adjust estimated bucketsize upward to account for skewed distribution.
    4150             :      */
    4151      142176 :     if (avgfreq > 0.0 && *mcv_freq > avgfreq)
    4152       49296 :         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      142176 :     if (estfract < 1.0e-6)
    4160           0 :         estfract = 1.0e-6;
    4161      142176 :     else if (estfract > 1.0)
    4162       34672 :         estfract = 1.0;
    4163             : 
    4164      142176 :     *bucketsize_frac = (Selectivity) estfract;
    4165             : 
    4166      142176 :     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      315922 : 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      315922 :     Oid         statOid = InvalidOid;
    4231             :     MVNDistinct *stats;
    4232      315922 :     StatisticExtInfo *matched_info = NULL;
    4233      315922 :     RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
    4234             : 
    4235             :     /* bail out immediately if the table has no extended statistics */
    4236      315922 :     if (!rel->statlist)
    4237      315370 :         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       89388 : 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       89388 :     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       89388 :     switch (valuetypid)
    4607             :     {
    4608             :             /*
    4609             :              * Built-in numeric types
    4610             :              */
    4611       82470 :         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       82470 :             *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
    4632             :                                                      &failure);
    4633       82470 :             *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
    4634             :                                                        &failure);
    4635       82470 :             *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
    4636             :                                                        &failure);
    4637       82470 :             return !failure;
    4638             : 
    4639             :             /*
    4640             :              * Built-in string types
    4641             :              */
    4642        6918 :         case CHAROID:
    4643             :         case BPCHAROID:
    4644             :         case VARCHAROID:
    4645             :         case TEXTOID:
    4646             :         case NAMEOID:
    4647             :             {
    4648        6918 :                 char       *valstr = convert_string_datum(value, valuetypid,
    4649             :                                                           collid, &failure);
    4650        6918 :                 char       *lostr = convert_string_datum(lobound, boundstypid,
    4651             :                                                          collid, &failure);
    4652        6918 :                 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        6918 :                 if (failure)
    4661           0 :                     return false;
    4662             : 
    4663        6918 :                 convert_string_to_scalar(valstr, scaledvalue,
    4664             :                                          lostr, scaledlobound,
    4665             :                                          histr, scaledhibound);
    4666        6918 :                 pfree(valstr);
    4667        6918 :                 pfree(lostr);
    4668        6918 :                 pfree(histr);
    4669        6918 :                 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      247410 : convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
    4731             : {
    4732      247410 :     switch (typid)
    4733             :     {
    4734           0 :         case BOOLOID:
    4735           0 :             return (double) DatumGetBool(value);
    4736          12 :         case INT2OID:
    4737          12 :             return (double) DatumGetInt16(value);
    4738       31410 :         case INT4OID:
    4739       31410 :             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      215934 :         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      215934 :             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        6918 : 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        6918 :     rangelo = rangehi = (unsigned char) hibound[0];
    4805       85996 :     for (sptr = lobound; *sptr; sptr++)
    4806             :     {
    4807       79078 :         if (rangelo > (unsigned char) *sptr)
    4808       16456 :             rangelo = (unsigned char) *sptr;
    4809       79078 :         if (rangehi < (unsigned char) *sptr)
    4810        8676 :             rangehi = (unsigned char) *sptr;
    4811             :     }
    4812       83440 :     for (sptr = hibound; *sptr; sptr++)
    4813             :     {
    4814       76522 :         if (rangelo > (unsigned char) *sptr)
    4815        1030 :             rangelo = (unsigned char) *sptr;
    4816       76522 :         if (rangehi < (unsigned char) *sptr)
    4817        3318 :             rangehi = (unsigned char) *sptr;
    4818             :     }
    4819             :     /* If range includes any upper-case ASCII chars, make it include all */
    4820        6918 :     if (rangelo <= 'Z' && rangehi >= 'A')
    4821             :     {
    4822        1210 :         if (rangelo > 'A')
    4823         222 :             rangelo = 'A';
    4824        1210 :         if (rangehi < 'Z')
    4825         480 :             rangehi = 'Z';
    4826             :     }
    4827             :     /* Ditto lower-case */
    4828        6918 :     if (rangelo <= 'z' && rangehi >= 'a')
    4829             :     {
    4830        6416 :         if (rangelo > 'a')
    4831          30 :             rangelo = 'a';
    4832        6416 :         if (rangehi < 'z')
    4833        6346 :             rangehi = 'z';
    4834             :     }
    4835             :     /* Ditto digits */
    4836        6918 :     if (rangelo <= '9' && rangehi >= '0')
    4837             :     {
    4838         530 :         if (rangelo > '0')
    4839         426 :             rangelo = '0';
    4840         530 :         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        6918 :     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       14450 :     while (*lobound)
    4858             :     {
    4859       14450 :         if (*lobound != *hibound || *lobound != *value)
    4860             :             break;
    4861        7532 :         lobound++, hibound++, value++;
    4862             :     }
    4863             : 
    4864             :     /*
    4865             :      * Now we can do the conversions.
    4866             :      */
    4867        6918 :     *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
    4868        6918 :     *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
    4869        6918 :     *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
    4870        6918 : }
    4871             : 
    4872             : static double
    4873       20754 : convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
    4874             : {
    4875       20754 :     int         slen = strlen(value);
    4876             :     double      num,
    4877             :                 denom,
    4878             :                 base;
    4879             : 
    4880       20754 :     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       20754 :     if (slen > 12)
    4893        5326 :         slen = 12;
    4894             : 
    4895             :     /* Convert initial characters to fraction */
    4896       20754 :     base = rangehi - rangelo + 1;
    4897       20754 :     num = 0.0;
    4898       20754 :     denom = base;
    4899      172586 :     while (slen-- > 0)
    4900             :     {
    4901      151832 :         int         ch = (unsigned char) *value++;
    4902             : 
    4903      151832 :         if (ch < rangelo)
    4904         188 :             ch = rangelo - 1;
    4905      151644 :         else if (ch > rangehi)
    4906           0 :             ch = rangehi + 1;
    4907      151832 :         num += ((double) (ch - rangelo)) / denom;
    4908      151832 :         denom *= base;
    4909             :     }
    4910             : 
    4911       20754 :     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       20754 : convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
    4925             : {
    4926             :     char       *val;
    4927             :     pg_locale_t mylocale;
    4928             : 
    4929       20754 :     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        6382 :         case BPCHAROID:
    4937             :         case VARCHAROID:
    4938             :         case TEXTOID:
    4939        6382 :             val = TextDatumGetCString(value);
    4940        6382 :             break;
    4941       14372 :         case NAMEOID:
    4942             :             {
    4943       14372 :                 NameData   *nm = (NameData *) DatumGetPointer(value);
    4944             : 
    4945       14372 :                 val = pstrdup(NameStr(*nm));
    4946       14372 :                 break;
    4947             :             }
    4948           0 :         default:
    4949           0 :             *failure = true;
    4950           0 :             return NULL;
    4951             :     }
    4952             : 
    4953       20754 :     mylocale = pg_newlocale_from_collation(collid);
    4954             : 
    4955       20754 :     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       20754 :     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      737324 : 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      737324 :     if (list_length(args) != 2)
    5179           0 :         return false;
    5180             : 
    5181      737324 :     left = (Node *) linitial(args);
    5182      737324 :     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      737324 :     examine_variable(root, left, varRelid, vardata);
    5189      737324 :     examine_variable(root, right, varRelid, &rdata);
    5190             : 
    5191             :     /*
    5192             :      * If one side is a variable and the other not, we win.
    5193             :      */
    5194      737324 :     if (vardata->rel && rdata.rel == NULL)
    5195             :     {
    5196      663098 :         *varonleft = true;
    5197      663098 :         *other = estimate_expression_value(root, rdata.var);
    5198             :         /* Assume we need no ReleaseVariableStats(rdata) here */
    5199      663092 :         return true;
    5200             :     }
    5201             : 
    5202       74226 :     if (vardata->rel == NULL && rdata.rel)
    5203             :     {
    5204       67994 :         *varonleft = false;
    5205       67994 :         *other = estimate_expression_value(root, vardata->var);
    5206             :         /* Assume we need no ReleaseVariableStats(*vardata) here */
    5207       67994 :         *vardata = rdata;
    5208       67994 :         return true;
    5209             :     }
    5210             : 
    5211             :     /* Oops, clause has wrong structure (probably var op var) */
    5212        6232 :     ReleaseVariableStats(*vardata);
    5213        6232 :     ReleaseVariableStats(rdata);
    5214             : 
    5215        6232 :     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      225334 : 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      225334 :     if (list_length(args) != 2)
    5237           0 :         elog(ERROR, "join operator should take two arguments");
    5238             : 
    5239      225334 :     left = (Node *) linitial(args);
    5240      225334 :     right = (Node *) lsecond(args);
    5241             : 
    5242      225334 :     examine_variable(root, left, 0, vardata1);
    5243      225334 :     examine_variable(root, right, 0, vardata2);
    5244             : 
    5245      450488 :     if (vardata1->rel &&
    5246      225154 :         bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
    5247       82964 :         *join_is_reversed = true;   /* var1 is on RHS */
    5248      284594 :     else if (vardata2->rel &&
    5249      142224 :              bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
    5250         132 :         *join_is_reversed = true;   /* var2 is on LHS */
    5251             :     else
    5252      142238 :         *join_is_reversed = false;
    5253      225334 : }
    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 all table rows from
    5292             :  *      the column(s) 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     2887952 : 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    20215664 :     MemSet(vardata, 0, sizeof(VariableStatData));
    5308             : 
    5309             :     /* Save the exposed type of the expression */
    5310     2887952 :     vardata->vartype = exprType(node);
    5311             : 
    5312             :     /* Look inside any binary-compatible relabeling */
    5313             : 
    5314     2887952 :     if (IsA(node, RelabelType))
    5315       46996 :         basenode = (Node *) ((RelabelType *) node)->arg;
    5316             :     else
    5317     2840956 :         basenode = node;
    5318             : 
    5319             :     /* Fast path for a simple Var */
    5320             : 
    5321     2887952 :     if (IsA(basenode, Var) &&
    5322      666102 :         (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
    5323             :     {
    5324     2051508 :         Var        *var = (Var *) basenode;
    5325             : 
    5326             :         /* Set up result fields other than the stats tuple */
    5327     2051508 :         vardata->var = basenode; /* return Var without relabeling */
    5328     2051508 :         vardata->rel = find_base_rel(root, var->varno);
    5329     2051508 :         vardata->atttype = var->vartype;
    5330     2051508 :         vardata->atttypmod = var->vartypmod;
    5331     2051508 :         vardata->isunique = has_unique_index(vardata->rel, var->varattno);
    5332             : 
    5333             :         /* Try to locate some stats */
    5334     2051508 :         examine_simple_variable(root, var, vardata);
    5335             : 
    5336     2051508 :         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      836444 :     varnos = pull_varnos(root, basenode);
    5345      836444 :     basevarnos = bms_difference(varnos, root->outer_join_rels);
    5346             : 
    5347      836444 :     onerel = NULL;
    5348             : 
    5349      836444 :     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      398020 :         if (bms_get_singleton_member(basevarnos, &relid))
    5359             :         {
    5360      393820 :             if (varRelid == 0 || varRelid == relid)
    5361             :             {
    5362       59480 :                 onerel = find_base_rel(root, relid);
    5363       59480 :                 vardata->rel = onerel;
    5364       59480 :                 node = basenode;    /* strip any relabeling */
    5365             :             }
    5366             :             /* else treat it as a constant */
    5367             :         }
    5368             :         else
    5369             :         {
    5370             :             /* varnos has multiple relids */
    5371        4200 :             if (varRelid == 0)
    5372             :             {
    5373             :                 /* treat it as a variable of a join relation */
    5374        3852 :                 vardata->rel = find_join_rel(root, varnos);
    5375        3852 :                 node = basenode;    /* strip any relabeling */
    5376             :             }
    5377         348 :             else if (bms_is_member(varRelid, varnos))
    5378             :             {
    5379             :                 /* ignore the vars belonging to other relations */
    5380         174 :                 vardata->rel = find_base_rel(root, varRelid);
    5381         174 :                 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      836444 :     bms_free(basevarnos);
    5389             : 
    5390      836444 :     vardata->var = node;
    5391      836444 :     vardata->atttype = exprType(node);
    5392      836444 :     vardata->atttypmod = exprTypmod(node);
    5393             : 
    5394      836444 :     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             : 
    5412             :         /*
    5413             :          * The nullingrels bits within the expression could prevent us from
    5414             :          * matching it to expressional index columns or to the expressions in
    5415             :          * extended statistics.  So strip them out first.
    5416             :          */
    5417       59480 :         if (bms_overlap(varnos, root->outer_join_rels))
    5418        3052 :             node = remove_nulling_relids(node, root->outer_join_rels, NULL);
    5419             : 
    5420      119044 :         foreach(ilist, onerel->indexlist)
    5421             :         {
    5422       62522 :             IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
    5423             :             ListCell   *indexpr_item;
    5424             :             int         pos;
    5425             : 
    5426       62522 :             indexpr_item = list_head(index->indexprs);
    5427       62522 :             if (indexpr_item == NULL)
    5428       57632 :                 continue;       /* no expressions here... */
    5429             : 
    5430        6894 :             for (pos = 0; pos < index->ncolumns; pos++)
    5431             :             {
    5432        4962 :                 if (index->indexkeys[pos] == 0)
    5433             :                 {
    5434             :                     Node       *indexkey;
    5435             : 
    5436        4890 :                     if (indexpr_item == NULL)
    5437           0 :                         elog(ERROR, "too few entries in indexprs list");
    5438        4890 :                     indexkey = (Node *) lfirst(indexpr_item);
    5439        4890 :                     if (indexkey && IsA(indexkey, RelabelType))
    5440           0 :                         indexkey = (Node *) ((RelabelType *) indexkey)->arg;
    5441        4890 :                     if (equal(node, indexkey))
    5442             :                     {
    5443             :                         /*
    5444             :                          * Found a match ... is it a unique index? Tests here
    5445             :                          * should match has_unique_index().
    5446             :                          */
    5447        3594 :                         if (index->unique &&
    5448         438 :                             index->nkeycolumns == 1 &&
    5449         438 :                             pos == 0 &&
    5450         438 :                             (index->indpred == NIL || index->predOK))
    5451         438 :                             vardata->isunique = true;
    5452             : 
    5453             :                         /*
    5454             :                          * Has it got stats?  We only consider stats for
    5455             :                          * non-partial indexes, since partial indexes probably
    5456             :                          * don't reflect whole-relation statistics; the above
    5457             :                          * check for uniqueness is the only info we take from
    5458             :                          * a partial index.
    5459             :                          *
    5460             :                          * An index stats hook, however, must make its own
    5461             :                          * decisions about what to do with partial indexes.
    5462             :                          */
    5463        3594 :                         if (get_index_stats_hook &&
    5464           0 :                             (*get_index_stats_hook) (root, index->indexoid,
    5465           0 :                                                      pos + 1, vardata))
    5466             :                         {
    5467             :                             /*
    5468             :                              * The hook took control of acquiring a stats
    5469             :                              * tuple.  If it did supply a tuple, it'd better
    5470             :                              * have supplied a freefunc.
    5471             :                              */
    5472           0 :                             if (HeapTupleIsValid(vardata->statsTuple) &&
    5473           0 :                                 !vardata->freefunc)
    5474           0 :                                 elog(ERROR, "no function provided to release variable stats with");
    5475             :                         }
    5476        3594 :                         else if (index->indpred == NIL)
    5477             :                         {
    5478        3594 :                             vardata->statsTuple =
    5479        7188 :                                 SearchSysCache3(STATRELATTINH,
    5480             :                                                 ObjectIdGetDatum(index->indexoid),
    5481        3594 :                                                 Int16GetDatum(pos + 1),
    5482             :                                                 BoolGetDatum(false));
    5483        3594 :                             vardata->freefunc = ReleaseSysCache;
    5484             : 
    5485        3594 :                             if (HeapTupleIsValid(vardata->statsTuple))
    5486             :                             {
    5487             :                                 /*
    5488             :                                  * Test if user has permission to access all
    5489             :                                  * rows from the index's table.
    5490             :                                  *
    5491             :                                  * For simplicity, we insist on the whole
    5492             :                                  * table being selectable, rather than trying
    5493             :                                  * to identify which column(s) the index
    5494             :                                  * depends on.
    5495             :                                  *
    5496             :                                  * Note that for an inheritance child,
    5497             :                                  * permissions are checked on the inheritance
    5498             :                                  * root parent, and whole-table select
    5499             :                                  * privilege on the parent doesn't quite
    5500             :                                  * guarantee that the user could read all
    5501             :                                  * columns of the child.  But in practice it's
    5502             :                                  * unlikely that any interesting security
    5503             :                                  * violation could result from allowing access
    5504             :                                  * to the expression index's stats, so we
    5505             :                                  * allow it anyway.  See similar code in
    5506             :                                  * examine_simple_variable() for additional
    5507             :                                  * comments.
    5508             :                                  */
    5509        2958 :                                 vardata->acl_ok =
    5510        2958 :                                     all_rows_selectable(root,
    5511        2958 :                                                         index->rel->relid,
    5512             :                                                         NULL);
    5513             :                             }
    5514             :                             else
    5515             :                             {
    5516             :                                 /* suppress leakproofness checks later */
    5517         636 :                                 vardata->acl_ok = true;
    5518             :                             }
    5519             :                         }
    5520        3594 :                         if (vardata->statsTuple)
    5521        2958 :                             break;
    5522             :                     }
    5523        1932 :                     indexpr_item = lnext(index->indexprs, indexpr_item);
    5524             :                 }
    5525             :             }
    5526        4890 :             if (vardata->statsTuple)
    5527        2958 :                 break;
    5528             :         }
    5529             : 
    5530             :         /*
    5531             :          * Search extended statistics for one with a matching expression.
    5532             :          * There might be multiple ones, so just grab the first one. In the
    5533             :          * future, we might consider the statistics target (and pick the most
    5534             :          * accurate statistics) and maybe some other parameters.
    5535             :          */
    5536       63578 :         foreach(slist, onerel->statlist)
    5537             :         {
    5538        4386 :             StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
    5539        4386 :             RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
    5540             :             ListCell   *expr_item;
    5541             :             int         pos;
    5542             : 
    5543             :             /*
    5544             :              * Stop once we've found statistics for the expression (either
    5545             :              * from extended stats, or for an index in the preceding loop).
    5546             :              */
    5547        4386 :             if (vardata->statsTuple)
    5548         288 :                 break;
    5549             : 
    5550             :             /* skip stats without per-expression stats */
    5551        4098 :             if (info->kind != STATS_EXT_EXPRESSIONS)
    5552        2094 :                 continue;
    5553             : 
    5554             :             /* skip stats with mismatching stxdinherit value */
    5555        2004 :             if (info->inherit != rte->inh)
    5556           6 :                 continue;
    5557             : 
    5558        1998 :             pos = 0;
    5559        3300 :             foreach(expr_item, info->exprs)
    5560             :             {
    5561        2946 :                 Node       *expr = (Node *) lfirst(expr_item);
    5562             : 
    5563             :                 Assert(expr);
    5564             : 
    5565             :                 /* strip RelabelType before comparing it */
    5566        2946 :                 if (expr && IsA(expr, RelabelType))
    5567           0 :                     expr = (Node *) ((RelabelType *) expr)->arg;
    5568             : 
    5569             :                 /* found a match, see if we can extract pg_statistic row */
    5570        2946 :                 if (equal(node, expr))
    5571             :                 {
    5572             :                     /*
    5573             :                      * XXX Not sure if we should cache the tuple somewhere.
    5574             :                      * Now we just create a new copy every time.
    5575             :                      */
    5576        1644 :                     vardata->statsTuple =
    5577        1644 :                         statext_expressions_load(info->statOid, rte->inh, pos);
    5578             : 
    5579        1644 :                     vardata->freefunc = ReleaseDummy;
    5580             : 
    5581             :                     /*
    5582             :                      * Test if user has permission to access all rows from the
    5583             :                      * table.
    5584             :                      *
    5585             :                      * For simplicity, we insist on the whole table being
    5586             :                      * selectable, rather than trying to identify which
    5587             :                      * column(s) the statistics object depends on.
    5588             :                      *
    5589             :                      * Note that for an inheritance child, permissions are
    5590             :                      * checked on the inheritance root parent, and whole-table
    5591             :                      * select privilege on the parent doesn't quite guarantee
    5592             :                      * that the user could read all columns of the child.  But
    5593             :                      * in practice it's unlikely that any interesting security
    5594             :                      * violation could result from allowing access to the
    5595             :                      * expression stats, so we allow it anyway.  See similar
    5596             :                      * code in examine_simple_variable() for additional
    5597             :                      * comments.
    5598             :                      */
    5599        1644 :                     vardata->acl_ok = all_rows_selectable(root,
    5600             :                                                           onerel->relid,
    5601             :                                                           NULL);
    5602             : 
    5603        1644 :                     break;
    5604             :                 }
    5605             : 
    5606        1302 :                 pos++;
    5607             :             }
    5608             :         }
    5609             :     }
    5610             : 
    5611      836444 :     bms_free(varnos);
    5612             : }
    5613             : 
    5614             : /*
    5615             :  * examine_simple_variable
    5616             :  *      Handle a simple Var for examine_variable
    5617             :  *
    5618             :  * This is split out as a subroutine so that we can recurse to deal with
    5619             :  * Vars referencing subqueries (either sub-SELECT-in-FROM or CTE style).
    5620             :  *
    5621             :  * We already filled in all the fields of *vardata except for the stats tuple.
    5622             :  */
    5623             : static void
    5624     2057684 : examine_simple_variable(PlannerInfo *root, Var *var,
    5625             :                         VariableStatData *vardata)
    5626             : {
    5627     2057684 :     RangeTblEntry *rte = root->simple_rte_array[var->varno];
    5628             : 
    5629             :     Assert(IsA(rte, RangeTblEntry));
    5630             : 
    5631     2057684 :     if (get_relation_stats_hook &&
    5632           0 :         (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
    5633             :     {
    5634             :         /*
    5635             :          * The hook took control of acquiring a stats tuple.  If it did supply
    5636             :          * a tuple, it'd better have supplied a freefunc.
    5637             :          */
    5638           0 :         if (HeapTupleIsValid(vardata->statsTuple) &&
    5639           0 :             !vardata->freefunc)
    5640           0 :             elog(ERROR, "no function provided to release variable stats with");
    5641             :     }
    5642     2057684 :     else if (rte->rtekind == RTE_RELATION)
    5643             :     {
    5644             :         /*
    5645             :          * Plain table or parent of an inheritance appendrel, so look up the
    5646             :          * column in pg_statistic
    5647             :          */
    5648     1942518 :         vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    5649             :                                               ObjectIdGetDatum(rte->relid),
    5650     1942518 :                                               Int16GetDatum(var->varattno),
    5651     1942518 :                                               BoolGetDatum(rte->inh));
    5652     1942518 :         vardata->freefunc = ReleaseSysCache;
    5653             : 
    5654     1942518 :         if (HeapTupleIsValid(vardata->statsTuple))
    5655             :         {
    5656             :             /*
    5657             :              * Test if user has permission to read all rows from this column.
    5658             :              *
    5659             :              * This requires that the user has the appropriate SELECT
    5660             :              * privileges and that there are no securityQuals from security
    5661             :              * barrier views or RLS policies.  If that's not the case, then we
    5662             :              * only permit leakproof functions to be passed pg_statistic data
    5663             :              * in vardata, otherwise the functions might reveal data that the
    5664             :              * user doesn't have permission to see --- see
    5665             :              * statistic_proc_security_check().
    5666             :              */
    5667     1466694 :             vardata->acl_ok =
    5668     1466694 :                 all_rows_selectable(root, var->varno,
    5669     1466694 :                                     bms_make_singleton(var->varattno - FirstLowInvalidHeapAttributeNumber));
    5670             :         }
    5671             :         else
    5672             :         {
    5673             :             /* suppress any possible leakproofness checks later */
    5674      475824 :             vardata->acl_ok = true;
    5675             :         }
    5676             :     }
    5677      115166 :     else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
    5678      105370 :              (rte->rtekind == RTE_CTE && !rte->self_reference))
    5679             :     {
    5680             :         /*
    5681             :          * Plain subquery (not one that was converted to an appendrel) or
    5682             :          * non-recursive CTE.  In either case, we can try to find out what the
    5683             :          * Var refers to within the subquery.  We skip this for appendrel and
    5684             :          * recursive-CTE cases because any column stats we did find would
    5685             :          * likely not be very relevant.
    5686             :          */
    5687             :         PlannerInfo *subroot;
    5688             :         Query      *subquery;
    5689             :         List       *subtlist;
    5690             :         TargetEntry *ste;
    5691             : 
    5692             :         /*
    5693             :          * Punt if it's a whole-row var rather than a plain column reference.
    5694             :          */
    5695       16762 :         if (var->varattno == InvalidAttrNumber)
    5696           0 :             return;
    5697             : 
    5698             :         /*
    5699             :          * Otherwise, find the subquery's planner subroot.
    5700             :          */
    5701       16762 :         if (rte->rtekind == RTE_SUBQUERY)
    5702             :         {
    5703             :             RelOptInfo *rel;
    5704             : 
    5705             :             /*
    5706             :              * Fetch RelOptInfo for subquery.  Note that we don't change the
    5707             :              * rel returned in vardata, since caller expects it to be a rel of
    5708             :              * the caller's query level.  Because we might already be
    5709             :              * recursing, we can't use that rel pointer either, but have to
    5710             :              * look up the Var's rel afresh.
    5711             :              */
    5712        9796 :             rel = find_base_rel(root, var->varno);
    5713             : 
    5714        9796 :             subroot = rel->subroot;
    5715             :         }
    5716             :         else
    5717             :         {
    5718             :             /* CTE case is more difficult */
    5719             :             PlannerInfo *cteroot;
    5720             :             Index       levelsup;
    5721             :             int         ndx;
    5722             :             int         plan_id;
    5723             :             ListCell   *lc;
    5724             : 
    5725             :             /*
    5726             :              * Find the referenced CTE, and locate the subroot previously made
    5727             :              * for it.
    5728             :              */
    5729        6966 :             levelsup = rte->ctelevelsup;
    5730        6966 :             cteroot = root;
    5731       13000 :             while (levelsup-- > 0)
    5732             :             {
    5733        6034 :                 cteroot = cteroot->parent_root;
    5734        6034 :                 if (!cteroot)   /* shouldn't happen */
    5735           0 :                     elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    5736             :             }
    5737             : 
    5738             :             /*
    5739             :              * Note: cte_plan_ids can be shorter than cteList, if we are still
    5740             :              * working on planning the CTEs (ie, this is a side-reference from
    5741             :              * another CTE).  So we mustn't use forboth here.
    5742             :              */
    5743        6966 :             ndx = 0;
    5744        9188 :             foreach(lc, cteroot->parse->cteList)
    5745             :             {
    5746        9188 :                 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
    5747             : 
    5748        9188 :                 if (strcmp(cte->ctename, rte->ctename) == 0)
    5749        6966 :                     break;
    5750        2222 :                 ndx++;
    5751             :             }
    5752        6966 :             if (lc == NULL)     /* shouldn't happen */
    5753           0 :                 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
    5754        6966 :             if (ndx >= list_length(cteroot->cte_plan_ids))
    5755           0 :                 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
    5756        6966 :             plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
    5757        6966 :             if (plan_id <= 0)
    5758           0 :                 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
    5759        6966 :             subroot = list_nth(root->glob->subroots, plan_id - 1);
    5760             :         }
    5761             : 
    5762             :         /* If the subquery hasn't been planned yet, we have to punt */
    5763       16762 :         if (subroot == NULL)
    5764           0 :             return;
    5765             :         Assert(IsA(subroot, PlannerInfo));
    5766             : 
    5767             :         /*
    5768             :          * We must use the subquery parsetree as mangled by the planner, not
    5769             :          * the raw version from the RTE, because we need a Var that will refer
    5770             :          * to the subroot's live RelOptInfos.  For instance, if any subquery
    5771             :          * pullup happened during planning, Vars in the targetlist might have
    5772             :          * gotten replaced, and we need to see the replacement expressions.
    5773             :          */
    5774       16762 :         subquery = subroot->parse;
    5775             :         Assert(IsA(subquery, Query));
    5776             : 
    5777             :         /*
    5778             :          * Punt if subquery uses set operations or grouping sets, as these
    5779             :          * will mash underlying columns' stats beyond recognition.  (Set ops
    5780             :          * are particularly nasty; if we forged ahead, we would return stats
    5781             :          * relevant to only the leftmost subselect...)  DISTINCT is also
    5782             :          * problematic, but we check that later because there is a possibility
    5783             :          * of learning something even with it.
    5784             :          */
    5785       16762 :         if (subquery->setOperations ||
    5786       14874 :             subquery->groupingSets)
    5787        1912 :             return;
    5788             : 
    5789             :         /* Get the subquery output expression referenced by the upper Var */
    5790       14850 :         if (subquery->returningList)
    5791         206 :             subtlist = subquery->returningList;
    5792             :         else
    5793       14644 :             subtlist = subquery->targetList;
    5794       14850 :         ste = get_tle_by_resno(subtlist, var->varattno);
    5795       14850 :         if (ste == NULL || ste->resjunk)
    5796           0 :             elog(ERROR, "subquery %s does not have attribute %d",
    5797             :                  rte->eref->aliasname, var->varattno);
    5798       14850 :         var = (Var *) ste->expr;
    5799             : 
    5800             :         /*
    5801             :          * If subquery uses DISTINCT, we can't make use of any stats for the
    5802             :          * variable ... but, if it's the only DISTINCT column, we are entitled
    5803             :          * to consider it unique.  We do the test this way so that it works
    5804             :          * for cases involving DISTINCT ON.
    5805             :          */
    5806       14850 :         if (subquery->distinctClause)
    5807             :         {
    5808        1838 :             if (list_length(subquery->distinctClause) == 1 &&
    5809         616 :                 targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
    5810         308 :                 vardata->isunique = true;
    5811             :             /* cannot go further */
    5812        1222 :             return;
    5813             :         }
    5814             : 
    5815             :         /* The same idea as with DISTINCT clause works for a GROUP-BY too */
    5816       13628 :         if (subquery->groupClause)
    5817             :         {
    5818        1040 :             if (list_length(subquery->groupClause) == 1 &&
    5819         430 :                 targetIsInSortList(ste, InvalidOid, subquery->groupClause))
    5820         334 :                 vardata->isunique = true;
    5821             :             /* cannot go further */
    5822         610 :             return;
    5823             :         }
    5824             : 
    5825             :         /*
    5826             :          * If the sub-query originated from a view with the security_barrier
    5827             :          * attribute, we must not look at the variable's statistics, though it
    5828             :          * seems all right to notice the existence of a DISTINCT clause. So
    5829             :          * stop here.
    5830             :          *
    5831             :          * This is probably a harsher restriction than necessary; it's
    5832             :          * certainly OK for the selectivity estimator (which is a C function,
    5833             :          * and therefore omnipotent anyway) to look at the statistics.  But
    5834             :          * many selectivity estimators will happily *invoke the operator
    5835             :          * function* to try to work out a good estimate - and that's not OK.
    5836             :          * So for now, don't dig down for stats.
    5837             :          */
    5838       13018 :         if (rte->security_barrier)
    5839        1350 :             return;
    5840             : 
    5841             :         /* Can only handle a simple Var of subquery's query level */
    5842       11668 :         if (var && IsA(var, Var) &&
    5843        6176 :             var->varlevelsup == 0)
    5844             :         {
    5845             :             /*
    5846             :              * OK, recurse into the subquery.  Note that the original setting
    5847             :              * of vardata->isunique (which will surely be false) is left
    5848             :              * unchanged in this situation.  That's what we want, since even
    5849             :              * if the underlying column is unique, the subquery may have
    5850             :              * joined to other tables in a way that creates duplicates.
    5851             :              */
    5852        6176 :             examine_simple_variable(subroot, var, vardata);
    5853             :         }
    5854             :     }
    5855             :     else
    5856             :     {
    5857             :         /*
    5858             :          * Otherwise, the Var comes from a FUNCTION or VALUES RTE.  (We won't
    5859             :          * see RTE_JOIN here because join alias Vars have already been
    5860             :          * flattened.)  There's not much we can do with function outputs, but
    5861             :          * maybe someday try to be smarter about VALUES.
    5862             :          */
    5863             :     }
    5864             : }
    5865             : 
    5866             : /*
    5867             :  * all_rows_selectable
    5868             :  *      Test whether the user has permission to select all rows from a given
    5869             :  *      relation.
    5870             :  *
    5871             :  * Inputs:
    5872             :  *  root: the planner info
    5873             :  *  varno: the index of the relation (assumed to be an RTE_RELATION)
    5874             :  *  varattnos: the attributes for which permission is required, or NULL if
    5875             :  *      whole-table access is required
    5876             :  *
    5877             :  * Returns true if the user has the required select permissions, and there are
    5878             :  * no securityQuals from security barrier views or RLS policies.
    5879             :  *
    5880             :  * Note that if the relation is an inheritance child relation, securityQuals
    5881             :  * and access permissions are checked against the inheritance root parent (the
    5882             :  * relation actually mentioned in the query) --- see the comments in
    5883             :  * expand_single_inheritance_child() for an explanation of why it has to be
    5884             :  * done this way.
    5885             :  *
    5886             :  * If varattnos is non-NULL, its attribute numbers should be offset by
    5887             :  * FirstLowInvalidHeapAttributeNumber so that system attributes can be
    5888             :  * checked.  If varattnos is NULL, only table-level SELECT privileges are
    5889             :  * checked, not any column-level privileges.
    5890             :  *
    5891             :  * Note: if the relation is accessed via a view, this function actually tests
    5892             :  * whether the view owner has permission to select from the relation.  To
    5893             :  * ensure that the current user has permission, it is also necessary to check
    5894             :  * that the current user has permission to select from the view, which we do
    5895             :  * at planner-startup --- see subquery_planner().
    5896             :  *
    5897             :  * This is exported so that other estimation functions can use it.
    5898             :  */
    5899             : bool
    5900     1471548 : all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
    5901             : {
    5902     1471548 :     RelOptInfo *rel = find_base_rel_noerr(root, varno);
    5903     1471548 :     RangeTblEntry *rte = planner_rt_fetch(varno, root);
    5904             :     Oid         userid;
    5905             :     int         varattno;
    5906             : 
    5907             :     Assert(rte->rtekind == RTE_RELATION);
    5908             : 
    5909             :     /*
    5910             :      * Determine the user ID to use for privilege checks (either the current
    5911             :      * user or the view owner, if we're accessing the table via a view).
    5912             :      *
    5913             :      * Normally the relation will have an associated RelOptInfo from which we
    5914             :      * can find the userid, but it might not if it's a RETURNING Var for an
    5915             :      * INSERT target relation.  In that case use the RTEPermissionInfo
    5916             :      * associated with the RTE.
    5917             :      *
    5918             :      * If we navigate up to a parent relation, we keep using the same userid,
    5919             :      * since it's the same in all relations of a given inheritance tree.
    5920             :      */
    5921     1471548 :     if (rel)
    5922     1471506 :         userid = rel->userid;
    5923             :     else
    5924             :     {
    5925             :         RTEPermissionInfo *perminfo;
    5926             : 
    5927          42 :         perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
    5928          42 :         userid = perminfo->checkAsUser;
    5929             :     }
    5930     1471548 :     if (!OidIsValid(userid))
    5931     1363224 :         userid = GetUserId();
    5932             : 
    5933             :     /*
    5934             :      * Permissions and securityQuals must be checked on the table actually
    5935             :      * mentioned in the query, so if this is an inheritance child, navigate up
    5936             :      * to the inheritance root parent.  If the user can read the whole table
    5937             :      * or the required columns there, then they can read from the child table
    5938             :      * too.  For per-column checks, we must find out which of the root
    5939             :      * parent's attributes the child relation's attributes correspond to.
    5940             :      */
    5941     1471548 :     if (root->append_rel_array != NULL)
    5942             :     {
    5943             :         AppendRelInfo *appinfo;
    5944             : 
    5945      141468 :         appinfo = root->append_rel_array[varno];
    5946             : 
    5947             :         /*
    5948             :          * Partitions are mapped to their immediate parent, not the root
    5949             :          * parent, so must be ready to walk up multiple AppendRelInfos.  But
    5950             :          * stop if we hit a parent that is not RTE_RELATION --- that's a
    5951             :          * flattened UNION ALL subquery, not an inheritance parent.
    5952             :          */
    5953      219996 :         while (appinfo &&
    5954       78900 :                planner_rt_fetch(appinfo->parent_relid,
    5955       78900 :                                 root)->rtekind == RTE_RELATION)
    5956             :         {
    5957       78528 :             Bitmapset  *parent_varattnos = NULL;
    5958             : 
    5959             :             /*
    5960             :              * For each child attribute, find the corresponding parent
    5961             :              * attribute.  In rare cases, the attribute may be local to the
    5962             :              * child table, in which case, we've got to live with having no
    5963             :              * access to this column.
    5964             :              */
    5965       78528 :             varattno = -1;
    5966      154206 :             while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
    5967             :             {
    5968             :                 AttrNumber  attno;
    5969             :                 AttrNumber  parent_attno;
    5970             : 
    5971       75678 :                 attno = varattno + FirstLowInvalidHeapAttributeNumber;
    5972             : 
    5973       75678 :                 if (attno == InvalidAttrNumber)
    5974             :                 {
    5975             :                     /*
    5976             :                      * Whole-row reference, so must map each column of the
    5977             :                      * child to the parent table.
    5978             :                      */
    5979          36 :                     for (attno = 1; attno <= appinfo->num_child_cols; attno++)
    5980             :                     {
    5981          24 :                         parent_attno = appinfo->parent_colnos[attno - 1];
    5982          24 :                         if (parent_attno == 0)
    5983           0 :                             return false;   /* attr is local to child */
    5984             :                         parent_varattnos =
    5985          24 :                             bms_add_member(parent_varattnos,
    5986             :                                            parent_attno - FirstLowInvalidHeapAttributeNumber);
    5987             :                     }
    5988             :                 }
    5989             :                 else
    5990             :                 {
    5991       75666 :                     if (attno < 0)
    5992             :                     {
    5993             :                         /* System attnos are the same in all tables */
    5994           0 :                         parent_attno = attno;
    5995             :                     }
    5996             :                     else
    5997             :                     {
    5998       75666 :                         if (attno > appinfo->num_child_cols)
    5999           0 :                             return false;   /* safety check */
    6000       75666 :                         parent_attno = appinfo->parent_colnos[attno - 1];
    6001       75666 :                         if (parent_attno == 0)
    6002           0 :                             return false;   /* attr is local to child */
    6003             :                     }
    6004             :                     parent_varattnos =
    6005       75666 :                         bms_add_member(parent_varattnos,
    6006             :                                        parent_attno - FirstLowInvalidHeapAttributeNumber);
    6007             :                 }
    6008             :             }
    6009             : 
    6010             :             /* If the parent is itself a child, continue up */
    6011       78528 :             varno = appinfo->parent_relid;
    6012       78528 :             varattnos = parent_varattnos;
    6013       78528 :             appinfo = root->append_rel_array[varno];
    6014             :         }
    6015             : 
    6016             :         /* Perform the access check on this parent rel */
    6017      141468 :         rte = planner_rt_fetch(varno, root);
    6018             :         Assert(rte->rtekind == RTE_RELATION);
    6019             :     }
    6020             : 
    6021             :     /*
    6022             :      * For all rows to be accessible, there must be no securityQuals from
    6023             :      * security barrier views or RLS policies.
    6024             :      */
    6025     1471548 :     if (rte->securityQuals != NIL)
    6026         828 :         return false;
    6027             : 
    6028             :     /*
    6029             :      * Test for table-level SELECT privilege.
    6030             :      *
    6031             :      * If varattnos is non-NULL, this is sufficient to give access to all
    6032             :      * requested attributes, even for a child table, since we have verified
    6033             :      * that all required child columns have matching parent columns.
    6034             :      *
    6035             :      * If varattnos is NULL (whole-table access requested), this doesn't
    6036             :      * necessarily guarantee that the user can read all columns of a child
    6037             :      * table, but we allow it anyway (see comments in examine_variable()) and
    6038             :      * don't bother checking any column privileges.
    6039             :      */
    6040     1470720 :     if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) == ACLCHECK_OK)
    6041     1470268 :         return true;
    6042             : 
    6043         452 :     if (varattnos == NULL)
    6044          12 :         return false;           /* whole-table access requested */
    6045             : 
    6046             :     /*
    6047             :      * Don't have table-level SELECT privilege, so check per-column
    6048             :      * privileges.
    6049             :      */
    6050         440 :     varattno = -1;
    6051         646 :     while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
    6052             :     {
    6053         440 :         AttrNumber  attno = varattno + FirstLowInvalidHeapAttributeNumber;
    6054             : 
    6055         440 :         if (attno == InvalidAttrNumber)
    6056             :         {
    6057             :             /* Whole-row reference, so must have access to all columns */
    6058           6 :             if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
    6059             :                                           ACLMASK_ALL) != ACLCHECK_OK)
    6060           6 :                 return false;
    6061             :         }
    6062             :         else
    6063             :         {
    6064         434 :             if (pg_attribute_aclcheck(rte->relid, attno, userid,
    6065             :                                       ACL_SELECT) != ACLCHECK_OK)
    6066         228 :                 return false;
    6067             :         }
    6068             :     }
    6069             : 
    6070             :     /* If we reach here, have all required column privileges */
    6071         206 :     return true;
    6072             : }
    6073             : 
    6074             : /*
    6075             :  * examine_indexcol_variable
    6076             :  *      Try to look up statistical data about an index column/expression.
    6077             :  *      Fill in a VariableStatData struct to describe the column.
    6078             :  *
    6079             :  * Inputs:
    6080             :  *  root: the planner info
    6081             :  *  index: the index whose column we're interested in
    6082             :  *  indexcol: 0-based index column number (subscripts index->indexkeys[])
    6083             :  *
    6084             :  * Outputs: *vardata is filled as follows:
    6085             :  *  var: the input expression (with any binary relabeling stripped, if
    6086             :  *      it is or contains a variable; but otherwise the type is preserved)
    6087             :  *  rel: RelOptInfo for table relation containing variable.
    6088             :  *  statsTuple: the pg_statistic entry for the variable, if one exists;
    6089             :  *      otherwise NULL.
    6090             :  *  freefunc: pointer to a function to release statsTuple with.
    6091             :  *
    6092             :  * Caller is responsible for doing ReleaseVariableStats() before exiting.
    6093             :  */
    6094             : static void
    6095      740648 : examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
    6096             :                           int indexcol, VariableStatData *vardata)
    6097             : {
    6098             :     AttrNumber  colnum;
    6099             :     Oid         relid;
    6100             : 
    6101      740648 :     if (index->indexkeys[indexcol] != 0)
    6102             :     {
    6103             :         /* Simple variable --- look to stats for the underlying table */
    6104      738458 :         RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
    6105             : 
    6106             :         Assert(rte->rtekind == RTE_RELATION);
    6107      738458 :         relid = rte->relid;
    6108             :         Assert(relid != InvalidOid);
    6109      738458 :         colnum = index->indexkeys[indexcol];
    6110      738458 :         vardata->rel = index->rel;
    6111             : 
    6112      738458 :         if (get_relation_stats_hook &&
    6113           0 :             (*get_relation_stats_hook) (root, rte, colnum, vardata))
    6114             :         {
    6115             :             /*
    6116             :              * The hook took control of acquiring a stats tuple.  If it did
    6117             :              * supply a tuple, it'd better have supplied a freefunc.
    6118             :              */
    6119           0 :             if (HeapTupleIsValid(vardata->statsTuple) &&
    6120           0 :                 !vardata->freefunc)
    6121           0 :                 elog(ERROR, "no function provided to release variable stats with");
    6122             :         }
    6123             :         else
    6124             :         {
    6125      738458 :             vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    6126             :                                                   ObjectIdGetDatum(relid),
    6127             :                                                   Int16GetDatum(colnum),
    6128      738458 :                                                   BoolGetDatum(rte->inh));
    6129      738458 :             vardata->freefunc = ReleaseSysCache;
    6130             :         }
    6131             :     }
    6132             :     else
    6133             :     {
    6134             :         /* Expression --- maybe there are stats for the index itself */
    6135        2190 :         relid = index->indexoid;
    6136        2190 :         colnum = indexcol + 1;
    6137             : 
    6138        2190 :         if (get_index_stats_hook &&
    6139           0 :             (*get_index_stats_hook) (root, relid, colnum, vardata))
    6140             :         {
    6141             :             /*
    6142             :              * The hook took control of acquiring a stats tuple.  If it did
    6143             :              * supply a tuple, it'd better have supplied a freefunc.
    6144             :              */
    6145           0 :             if (HeapTupleIsValid(vardata->statsTuple) &&
    6146           0 :                 !vardata->freefunc)
    6147           0 :                 elog(ERROR, "no function provided to release variable stats with");
    6148             :         }
    6149             :         else
    6150             :         {
    6151        2190 :             vardata->statsTuple = SearchSysCache3(STATRELATTINH,
    6152             :                                                   ObjectIdGetDatum(relid),
    6153             :                                                   Int16GetDatum(colnum),
    6154             :                                                   BoolGetDatum(false));
    6155        2190 :             vardata->freefunc = ReleaseSysCache;
    6156             :         }
    6157             :     }
    6158      740648 : }
    6159             : 
    6160             : /*
    6161             :  * Check whether it is permitted to call func_oid passing some of the
    6162             :  * pg_statistic data in vardata.  We allow this if either of the following
    6163             :  * conditions is met: (1) the user has SELECT privileges on the table or
    6164             :  * column underlying the pg_statistic data and there are no securityQuals from
    6165             :  * security barrier views or RLS policies, or (2) the function is marked
    6166             :  * leakproof.
    6167             :  */
    6168             : bool
    6169      962394 : statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
    6170             : {
    6171      962394 :     if (vardata->acl_ok)
    6172      960616 :         return true;            /* have SELECT privs and no securityQuals */
    6173             : 
    6174        1778 :     if (!OidIsValid(func_oid))
    6175           0 :         return false;
    6176             : 
    6177        1778 :     if (get_func_leakproof(func_oid))
    6178         880 :         return true;
    6179             : 
    6180         898 :     ereport(DEBUG2,
    6181             :             (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
    6182             :                              get_func_name(func_oid))));
    6183         898 :     return false;
    6184             : }
    6185             : 
    6186             : /*
    6187             :  * get_variable_numdistinct
    6188             :  *    Estimate the number of distinct values of a variable.
    6189             :  *
    6190             :  * vardata: results of examine_variable
    6191             :  * *isdefault: set to true if the result is a default rather than based on
    6192             :  * anything meaningful.
    6193             :  *
    6194             :  * NB: be careful to produce a positive integral result, since callers may
    6195             :  * compare the result to exact integer counts, or might divide by it.
    6196             :  */
    6197             : double
    6198     1437300 : get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
    6199             : {
    6200             :     double      stadistinct;
    6201     1437300 :     double      stanullfrac = 0.0;
    6202             :     double      ntuples;
    6203             : 
    6204     1437300 :     *isdefault = false;
    6205             : 
    6206             :     /*
    6207             :      * Determine the stadistinct value to use.  There are cases where we can
    6208             :      * get an estimate even without a pg_statistic entry, or can get a better
    6209             :      * value than is in pg_statistic.  Grab stanullfrac too if we can find it
    6210             :      * (otherwise, assume no nulls, for lack of any better idea).
    6211             :      */
    6212     1437300 :     if (HeapTupleIsValid(vardata->statsTuple))
    6213             :     {
    6214             :         /* Use the pg_statistic entry */
    6215             :         Form_pg_statistic stats;
    6216             : 
    6217     1036048 :         stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
    6218     1036048 :         stadistinct = stats->stadistinct;
    6219     1036048 :         stanullfrac = stats->stanullfrac;
    6220             :     }
    6221      401252 :     else if (vardata->vartype == BOOLOID)
    6222             :     {
    6223             :         /*
    6224             :          * Special-case boolean columns: presumably, two distinct values.
    6225             :          *
    6226             :          * Are there any other datatypes we should wire in special estimates
    6227             :          * for?
    6228             :          */
    6229         592 :         stadistinct = 2.0;
    6230             :     }
    6231      400660 :     else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
    6232             :     {
    6233             :         /*
    6234             :          * If the Var represents a column of a VALUES RTE, assume it's unique.
    6235             :          * This could of course be very wrong, but it should tend to be true
    6236             :          * in well-written queries.  We could consider examining the VALUES'
    6237             :          * contents to get some real statistics; but that only works if the
    6238             :          * entries are all constants, and it would be pretty expensive anyway.
    6239             :          */
    6240        3466 :         stadistinct = -1.0;     /* unique (and all non null) */
    6241             :     }
    6242             :     else
    6243             :     {
    6244             :         /*
    6245             :          * We don't keep statistics for system columns, but in some cases we
    6246             :          * can infer distinctness anyway.
    6247             :          */
    6248      397194 :         if (vardata->var && IsA(vardata->var, Var))
    6249             :         {
    6250      366436 :             switch (((Var *) vardata->var)->varattno)
    6251             :             {
    6252        1186 :                 case SelfItemPointerAttributeNumber:
    6253        1186 :                     stadistinct = -1.0; /* unique (and all non null) */
    6254        1186 :                     break;
    6255       10192 :                 case TableOidAttributeNumber:
    6256       10192 :                     stadistinct = 1.0;  /* only 1 value */
    6257       10192 :                     break;
    6258      355058 :                 default:
    6259      355058 :                     stadistinct = 0.0;  /* means "unknown" */
    6260      355058 :                     break;
    6261             :             }
    6262             :         }
    6263             :         else
    6264       30758 :             stadistinct = 0.0;  /* means "unknown" */
    6265             : 
    6266             :         /*
    6267             :          * XXX consider using estimate_num_groups on expressions?
    6268             :          */
    6269             :     }
    6270             : 
    6271             :     /*
    6272             :      * If there is a unique index, DISTINCT or GROUP-BY clause for the
    6273             :      * variable, assume it is unique no matter what pg_statistic says; the
    6274             :      * statistics could be out of date, or we might have found a partial
    6275             :      * unique index that proves the var is unique for this query.  However,
    6276             :      * we'd better still believe the null-fraction statistic.
    6277             :      */
    6278     1437300 :     if (vardata->isunique)
    6279      373056 :         stadistinct = -1.0 * (1.0 - stanullfrac);
    6280             : 
    6281             :     /*
    6282             :      * If we had an absolute estimate, use that.
    6283             :      */
    6284     1437300 :     if (stadistinct > 0.0)
    6285      334770 :         return clamp_row_est(stadistinct);
    6286             : 
    6287             :     /*
    6288             :      * Otherwise we need to get the relation size; punt if not available.
    6289             :      */
    6290     1102530 :     if (vardata->rel == NULL)
    6291             :     {
    6292         416 :         *isdefault = true;
    6293         416 :         return DEFAULT_NUM_DISTINCT;
    6294             :     }
    6295     1102114 :     ntuples = vardata->rel->tuples;
    6296     1102114 :     if (ntuples <= 0.0)
    6297             :     {
    6298       49864 :         *isdefault = true;
    6299       49864 :         return DEFAULT_NUM_DISTINCT;
    6300             :     }
    6301             : 
    6302             :     /*
    6303             :      * If we had a relative estimate, use that.
    6304             :      */
    6305     1052250 :     if (stadistinct < 0.0)
    6306      751458 :         return clamp_row_est(-stadistinct * ntuples);
    6307             : 
    6308             :     /*
    6309             :      * With no data, estimate ndistinct = ntuples if the table is small, else
    6310             :      * use default.  We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
    6311             :      * that the behavior isn't discontinuous.
    6312             :      */
    6313      300792 :     if (ntuples < DEFAULT_NUM_DISTINCT)
    6314      144308 :         return clamp_row_est(ntuples);
    6315             : 
    6316      156484 :     *isdefault = true;
    6317      156484 :     return DEFAULT_NUM_DISTINCT;
    6318             : }
    6319             : 
    6320             : /*
    6321             :  * get_variable_range
    6322             :  *      Estimate the minimum and maximum value of the specified variable.
    6323             :  *      If successful, store values in *min and *max, and return true.
    6324             :  *      If no data available, return false.
    6325             :  *
    6326             :  * sortop is the "<" comparison operator to use.  This should generally
    6327             :  * be "<" not ">", as only the former is likely to be found in pg_statistic.
    6328             :  * The collation must be specified too.
    6329             :  */
    6330             : static bool
    6331      204108 : get_variable_range(PlannerInfo *root, VariableStatData *vardata,
    6332             :                    Oid sortop, Oid collation,
    6333             :                    Datum *min, Datum *max)
    6334             : {
    6335      204108 :     Datum       tmin = 0;
    6336      204108 :     Datum       tmax = 0;
    6337      204108 :     bool        have_data = false;
    6338             :     int16       typLen;
    6339             :     bool        typByVal;
    6340             :     Oid         opfuncoid;
    6341             :     FmgrInfo    opproc;
    6342             :     AttStatsSlot sslot;
    6343             : 
    6344             :     /*
    6345             :      * XXX It's very tempting to try to use the actual column min and max, if
    6346             :      * we can get them relatively-cheaply with an index probe.  However, since
    6347             :      * this function is called many times during join planning, that could
    6348             :      * have unpleasant effects on planning speed.  Need more investigation
    6349             :      * before enabling this.
    6350             :      */
    6351             : #ifdef NOT_USED
    6352             :     if (get_actual_variable_range(root, vardata, sortop, collation, min, max))
    6353             :         return true;
    6354             : #endif
    6355             : 
    6356      204108 :     if (!HeapTupleIsValid(vardata->statsTuple))
    6357             :     {
    6358             :         /* no stats available, so default result */
    6359       44954 :         return false;
    6360             :     }
    6361             : 
    6362             :     /*
    6363             :      * If we can't apply the sortop to the stats data, just fail.  In
    6364             :      * principle, if there's a histogram and no MCVs, we could return the
    6365             :      * histogram endpoints without ever applying the sortop ... but it's
    6366             :      * probably not worth trying, because whatever the caller wants to do with
    6367             :      * the endpoints would likely fail the security check too.
    6368             :      */
    6369      159154 :     if (!statistic_proc_security_check(vardata,
    6370      159154 :                                        (opfuncoid = get_opcode(sortop))))
    6371           0 :         return false;
    6372             : 
    6373      159154 :     opproc.fn_oid = InvalidOid; /* mark this as not looked up yet */
    6374             : 
    6375      159154 :     get_typlenbyval(vardata->atttype, &typLen, &typByVal);
    6376             : 
    6377             :     /*
    6378             :      * If there is a histogram with the ordering we want, grab the first and
    6379             :      * last values.
    6380             :      */
    6381      159154 :     if (get_attstatsslot(&sslot, vardata->statsTuple,
    6382             :                          STATISTIC_KIND_HISTOGRAM, sortop,
    6383             :                          ATTSTATSSLOT_VALUES))
    6384             :     {
    6385      117210 :         if (sslot.stacoll == collation && sslot.nvalues > 0)
    6386             :         {
    6387      117210 :             tmin = datumCopy(sslot.values[0], typByVal, typLen);
    6388      117210 :             tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
    6389      117210 :             have_data = true;
    6390             :         }
    6391      117210 :         free_attstatsslot(&sslot);
    6392             :     }
    6393             : 
    6394             :     /*
    6395             :      * Otherwise, if there is a histogram with some other ordering, scan it
    6396             :      * and get the min and max values according to the ordering we want.  This
    6397             :      * of course may not find values that are really extremal according to our
    6398             :      * ordering, but it beats ignoring available data.
    6399             :      */
    6400      201098 :     if (!have_data &&
    6401       41944 :         get_attstatsslot(&sslot, vardata->statsTuple,
    6402             :                          STATISTIC_KIND_HISTOGRAM, InvalidOid,
    6403             :                          ATTSTATSSLOT_VALUES))
    6404             :     {
    6405           0 :         get_stats_slot_range(&sslot, opfuncoid, &opproc,
    6406             :                              collation, typLen, typByVal,
    6407             :                              &tmin, &tmax, &have_data);
    6408           0 :         free_attstatsslot(&sslot);
    6409             :     }
    6410             : 
    6411             :     /*
    6412             :      * If we have most-common-values info, look for extreme MCVs.  This is
    6413             :      * needed even if we also have a histogram, since the histogram excludes
    6414             :      * the MCVs.  However, if we *only* have MCVs and no histogram, we should
    6415             :      * be pretty wary of deciding that that is a full representation of the
    6416             :      * data.  Proceed only if the MCVs represent the whole table (to within
    6417             :      * roundoff error).
    6418             :      */
    6419      159154 :     if (get_attstatsslot(&sslot, vardata->statsTuple,
    6420             :                          STATISTIC_KIND_MCV, InvalidOid,
    6421      159154 :                          have_data ? ATTSTATSSLOT_VALUES :
    6422             :                          (ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)))
    6423             :     {
    6424       77350 :         bool        use_mcvs = have_data;
    6425             : 
    6426       77350 :         if (!have_data)
    6427             :         {
    6428       40550 :             double      sumcommon = 0.0;
    6429             :             double      nullfrac;
    6430             :             int         i;
    6431             : 
    6432      302236 :             for (i = 0; i < sslot.nnumbers; i++)
    6433      261686 :                 sumcommon += sslot.numbers[i];
    6434       40550 :             nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata->statsTuple))->stanullfrac;
    6435       40550 :             if (sumcommon + nullfrac > 0.99999)
    6436       38540 :                 use_mcvs = true;
    6437             :         }
    6438             : 
    6439       77350 :         if (use_mcvs)
    6440       75340 :             get_stats_slot_range(&sslot, opfuncoid, &opproc,
    6441             :                                  collation, typLen, typByVal,
    6442             :                                  &tmin, &tmax, &have_data);
    6443       77350 :         free_attstatsslot(&sslot);
    6444             :     }
    6445             : 
    6446      159154 :     *min = tmin;
    6447      159154 :     *max = tmax;
    6448      159154 :     return have_data;
    6449             : }
    6450             : 
    6451             : /*
    6452             :  * get_stats_slot_range: scan sslot for min/max values
    6453             :  *
    6454             :  * Subroutine for get_variable_range: update min/max/have_data according
    6455             :  * to what we find in the statistics array.
    6456             :  */
    6457             : static void
    6458       75340 : get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
    6459             :                      Oid collation, int16 typLen, bool typByVal,
    6460             :                      Datum *min, Datum *max, bool *p_have_data)
    6461             : {
    6462       75340 :     Datum       tmin = *min;
    6463       75340 :     Datum       tmax = *max;
    6464       75340 :     bool        have_data = *p_have_data;
    6465       75340 :     bool        found_tmin = false;
    6466       75340 :     bool        found_tmax = false;
    6467             : 
    6468             :     /* Look up the comparison function, if we didn't already do so */
    6469       75340 :     if (opproc->fn_oid != opfuncoid)
    6470       75340 :         fmgr_info(opfuncoid, opproc);
    6471             : 
    6472             :     /* Scan all the slot's values */
    6473     2249052 :     for (int i = 0; i < sslot->nvalues; i++)
    6474             :     {
    6475     2173712 :         if (!have_data)
    6476             :         {
    6477       38540 :             tmin = tmax = sslot->values[i];
    6478       38540 :             found_tmin = found_tmax = true;
    6479       38540 :             *p_have_data = have_data = true;
    6480       38540 :             continue;
    6481             :         }
    6482     2135172 :         if (DatumGetBool(FunctionCall2Coll(opproc,
    6483             :                                            collation,
    6484     2135172 :                                            sslot->values[i], tmin)))
    6485             :         {
    6486       52928 :             tmin = sslot->values[i];
    6487       52928 :             found_tmin = true;
    6488             :         }
    6489     2135172 :         if (DatumGetBool(FunctionCall2Coll(opproc,
    6490             :                                            collation,
    6491     2135172 :                                            tmax, sslot->values[i])))
    6492             :         {
    6493       99662 :             tmax = sslot->values[i];
    6494       99662 :             found_tmax = true;
    6495             :         }
    6496             :     }
    6497             : 
    6498             :     /*
    6499             :      * Copy the slot's values, if we found new extreme values.
    6500             :      */
    6501       75340 :     if (found_tmin)
    6502       60758 :         *min = datumCopy(tmin, typByVal, typLen);
    6503       75340 :     if (found_tmax)
    6504       42982 :         *max = datumCopy(tmax, typByVal, typLen);
    6505       75340 : }
    6506             : 
    6507             : 
    6508             : /*
    6509             :  * get_actual_variable_range
    6510             :  *      Attempt to identify the current *actual* minimum and/or maximum
    6511             :  *      of the specified variable, by looking for a suitable btree index
    6512             :  *      and fetching its low and/or high values.
    6513             :  *      If successful, store values in *min and *max, and return true.
    6514             :  *      (Either pointer can be NULL if that endpoint isn't needed.)
    6515             :  *      If unsuccessful, return false.
    6516             :  *
    6517             :  * sortop is the "<" comparison operator to use.
    6518             :  * collation is the required collation.
    6519             :  */
    6520             : static bool
    6521      180696 : get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
    6522             :                           Oid sortop, Oid collation,
    6523             :                           Datum *min, Datum *max)
    6524             : {
    6525      180696 :     bool        have_data = false;
    6526      180696 :     RelOptInfo *rel = vardata->rel;
    6527             :     RangeTblEntry *rte;
    6528             :     ListCell   *lc;
    6529             : 
    6530             :     /* No hope if no relation or it doesn't have indexes */
    6531      180696 :     if (rel == NULL || rel->indexlist == NIL)
    6532       13452 :         return false;
    6533             :     /* If it has indexes it must be a plain relation */
    6534      167244 :     rte = root->simple_rte_array[rel->relid];
    6535             :     Assert(rte->rtekind == RTE_RELATION);
    6536             : 
    6537             :     /* ignore partitioned tables.  Any indexes here are not real indexes */
    6538      167244 :     if (rte->relkind == RELKIND_PARTITIONED_TABLE)
    6539         876 :         return false;
    6540             : 
    6541             :     /* Search through the indexes to see if any match our problem */
    6542      324428 :     foreach(lc, rel->indexlist)
    6543             :     {
    6544      277202 :         IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
    6545             :         ScanDirection indexscandir;
    6546             :         StrategyNumber strategy;
    6547             : 
    6548             :         /* Ignore non-ordering indexes */
    6549      277202 :         if (index->sortopfamily == NULL)
    6550           0 :             continue;
    6551             : 
    6552             :         /*
    6553             :          * Ignore partial indexes --- we only want stats that cover the entire
    6554             :          * relation.
    6555             :          */
    6556      277202 :         if (index->indpred != NIL)
    6557         288 :             continue;
    6558             : 
    6559             :         /*
    6560             :          * The index list might include hypothetical indexes inserted by a
    6561             :          * get_relation_info hook --- don't try to access them.
    6562             :          */
    6563      276914 :         if (index->hypothetical)
    6564           0 :             continue;
    6565             : 
    6566             :         /*
    6567             :          * The first index column must match the desired variable, sortop, and
    6568             :          * collation --- but we can use a descending-order index.
    6569             :          */
    6570      276914 :         if (collation != index->indexcollations[0])
    6571       35866 :             continue;           /* test first 'cause it's cheapest */
    6572      241048 :         if (!match_index_to_operand(vardata->var, 0, index))
    6573      121906 :             continue;
    6574      119142 :         strategy = get_op_opfamily_strategy(sortop, index->sortopfamily[0]);
    6575      119142 :         switch (IndexAmTranslateStrategy(strategy, index->relam, index->sortopfamily[0], true))
    6576             :         {
    6577      119142 :             case COMPARE_LT:
    6578      119142 :                 if (index->reverse_sort[0])
    6579           0 :                     indexscandir = BackwardScanDirection;
    6580             :                 else
    6581      119142 :                     indexscandir = ForwardScanDirection;
    6582      119142 :                 break;
    6583           0 :             case COMPARE_GT:
    6584           0 :                 if (index->reverse_sort[0])
    6585           0 :                     indexscandir = ForwardScanDirection;
    6586             :                 else
    6587           0 :                     indexscandir = BackwardScanDirection;
    6588           0 :                 break;
    6589           0 :             default:
    6590             :                 /* index doesn't match the sortop */
    6591           0 :                 continue;
    6592             :         }
    6593             : 
    6594             :         /*
    6595             :          * Found a suitable index to extract data from.  Set up some data that
    6596             :          * can be used by both invocations of get_actual_variable_endpoint.
    6597             :          */
    6598             :         {
    6599             :             MemoryContext tmpcontext;
    6600             :             MemoryContext oldcontext;
    6601             :             Relation    heapRel;
    6602             :             Relation    indexRel;
    6603             :             TupleTableSlot *slot;
    6604             :             int16       typLen;
    6605             :             bool        typByVal;
    6606             :             ScanKeyData scankeys[1];
    6607             : 
    6608             :             /* Make sure any cruft gets recycled when we're done */
    6609      119142 :             tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
    6610             :                                                "get_actual_variable_range workspace",
    6611             :                                                ALLOCSET_DEFAULT_SIZES);
    6612      119142 :             oldcontext = MemoryContextSwitchTo(tmpcontext);
    6613             : 
    6614             :             /*
    6615             :              * Open the table and index so we can read from them.  We should
    6616             :              * already have some type of lock on each.
    6617             :              */
    6618      119142 :             heapRel = table_open(rte->relid, NoLock);
    6619      119142 :             indexRel = index_open(index->indexoid, NoLock);
    6620             : 
    6621             :             /* build some stuff needed for indexscan execution */
    6622      119142 :             slot = table_slot_create(heapRel, NULL);
    6623      119142 :             get_typlenbyval(vardata->atttype, &typLen, &typByVal);
    6624             : 
    6625             :             /* set up an IS NOT NULL scan key so that we ignore nulls */
    6626      119142 :             ScanKeyEntryInitialize(&scankeys[0],
    6627             :                                    SK_ISNULL | SK_SEARCHNOTNULL,
    6628             :                                    1,   /* index col to scan */
    6629             :                                    InvalidStrategy, /* no strategy */
    6630             :                                    InvalidOid,  /* no strategy subtype */
    6631             :                                    InvalidOid,  /* no collation */
    6632             :                                    InvalidOid,  /* no reg proc for this */
    6633             :                                    (Datum) 0);  /* constant */
    6634             : 
    6635             :             /* If min is requested ... */
    6636      119142 :             if (min)
    6637             :             {
    6638       67878 :                 have_data = get_actual_variable_endpoint(heapRel,
    6639             :                                                          indexRel,
    6640             :                                                          indexscandir,
    6641             :                                                          scankeys,
    6642             :                                                          typLen,
    6643             :                                                          typByVal,
    6644             :                                                          slot,
    6645             :                                                          oldcontext,
    6646             :                                                          min);
    6647             :             }
    6648             :             else
    6649             :             {
    6650             :                 /* If min not requested, still want to fetch max */
    6651       51264 :                 have_data = true;
    6652             :             }
    6653             : 
    6654             :             /* If max is requested, and we didn't already fail ... */
    6655      119142 :             if (max && have_data)
    6656             :             {
    6657             :                 /* scan in the opposite direction; all else is the same */
    6658       52904 :                 have_data = get_actual_variable_endpoint(heapRel,
    6659             :                                                          indexRel,
    6660       52904 :                                                          -indexscandir,
    6661             :                                                          scankeys,
    6662             :                                                          typLen,
    6663             :                                                          typByVal,
    6664             :                                                          slot,
    6665             :                                                          oldcontext,
    6666             :                                                          max);
    6667             :             }
    6668             : 
    6669             :             /* Clean everything up */
    6670      119142 :             ExecDropSingleTupleTableSlot(slot);
    6671             : 
    6672      119142 :             index_close(indexRel, NoLock);
    6673      119142 :             table_close(heapRel, NoLock);
    6674             : 
    6675      119142 :             MemoryContextSwitchTo(oldcontext);
    6676      119142 :             MemoryContextDelete(tmpcontext);
    6677             : 
    6678             :             /* And we're done */
    6679      119142 :             break;
    6680             :         }
    6681             :     }
    6682             : 
    6683      166368 :     return have_data;
    6684             : }
    6685             : 
    6686             : /*
    6687             :  * Get one endpoint datum (min or max depending on indexscandir) from the
    6688             :  * specified index.  Return true if successful, false if not.
    6689             :  * On success, endpoint value is stored to *endpointDatum (and copied into
    6690             :  * outercontext).
    6691             :  *
    6692             :  * scankeys is a 1-element scankey array set up to reject nulls.
    6693             :  * typLen/typByVal describe the datatype of the index's first column.
    6694             :  * tableslot is a slot suitable to hold table tuples, in case we need
    6695             :  * to probe the heap.
    6696             :  * (We could compute these values locally, but that would mean computing them
    6697             :  * twice when get_actual_variable_range needs both the min and the max.)
    6698             :  *
    6699             :  * Failure occurs either when the index is empty, or we decide that it's
    6700             :  * taking too long to find a suitable tuple.
    6701             :  */
    6702             : static bool
    6703      120782 : get_actual_variable_endpoint(Relation heapRel,
    6704             :                              Relation indexRel,
    6705             :                              ScanDirection indexscandir,
    6706             :                              ScanKey scankeys,
    6707             :                              int16 typLen,
    6708             :                              bool typByVal,
    6709             :                              TupleTableSlot *tableslot,
    6710             :                              MemoryContext outercontext,
    6711             :                              Datum *endpointDatum)
    6712             : {
    6713      120782 :     bool        have_data = false;
    6714             :     SnapshotData SnapshotNonVacuumable;
    6715             :     IndexScanDesc index_scan;
    6716      120782 :     Buffer      vmbuffer = InvalidBuffer;
    6717      120782 :     BlockNumber last_heap_block = InvalidBlockNumber;
    6718      120782 :     int         n_visited_heap_pages = 0;
    6719             :     ItemPointer tid;
    6720             :     Datum       values[INDEX_MAX_KEYS];
    6721             :     bool        isnull[INDEX_MAX_KEYS];
    6722             :     MemoryContext oldcontext;
    6723             : 
    6724             :     /*
    6725             :      * We use the index-only-scan machinery for this.  With mostly-static
    6726             :      * tables that's a win because it avoids a heap visit.  It's also a win
    6727             :      * for dynamic data, but the reason is less obvious; read on for details.
    6728             :      *
    6729             :      * In principle, we should scan the index with our current active
    6730             :      * snapshot, which is the best approximation we've got to what the query
    6731             :      * will see when executed.  But that won't be exact if a new snap is taken
    6732             :      * before running the query, and it can be very expensive if a lot of
    6733             :      * recently-dead or uncommitted rows exist at the beginning or end of the
    6734             :      * index (because we'll laboriously fetch each one and reject it).
    6735             :      * Instead, we use SnapshotNonVacuumable.  That will accept recently-dead
    6736             :      * and uncommitted rows as well as normal visible rows.  On the other
    6737             :      * hand, it will reject known-dead rows, and thus not give a bogus answer
    6738             :      * when the extreme value has been deleted (unless the deletion was quite
    6739             :      * recent); that case motivates not using SnapshotAny here.
    6740             :      *
    6741             :      * A crucial point here is that SnapshotNonVacuumable, with
    6742             :      * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
    6743             :      * condition that the indexscan will use to decide that index entries are
    6744             :      * killable (see heap_hot_search_buffer()).  Therefore, if the snapshot
    6745             :      * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
    6746             :      * have to continue scanning past it, we know that the indexscan will mark
    6747             :      * that index entry killed.  That means that the next
    6748             :      * get_actual_variable_endpoint() call will not have to re-consider that
    6749             :      * index entry.  In this way we avoid repetitive work when this function
    6750             :      * is used a lot during planning.
    6751             :      *
    6752             :      * But using SnapshotNonVacuumable creates a hazard of its own.  In a
    6753             :      * recently-created index, some index entries may point at "broken" HOT
    6754             :      * chains in which not all the tuple versions contain data matching the
    6755             :      * index entry.  The live tuple version(s) certainly do match the index,
    6756             :      * but SnapshotNonVacuumable can accept recently-dead tuple versions that
    6757             :      * don't match.  Hence, if we took data from the selected heap tuple, we
    6758             :      * might get a bogus answer that's not close to the index extremal value,
    6759             :      * or could even be NULL.  We avoid this hazard because we take the data
    6760             :      * from the index entry not the heap.
    6761             :      *
    6762             :      * Despite all this care, there are situations where we might find many
    6763             :      * non-visible tuples near the end of the index.  We don't want to expend
    6764             :      * a huge amount of time here, so we give up once we've read too many heap
    6765             :      * pages.  When we fail for that reason, the caller will end up using
    6766             :      * whatever extremal value is recorded in pg_statistic.
    6767             :      */
    6768      120782 :     InitNonVacuumableSnapshot(SnapshotNonVacuumable,
    6769             :                               GlobalVisTestFor(heapRel));
    6770             : 
    6771      120782 :     index_scan = index_beginscan(heapRel, indexRel,
    6772             :                                  &SnapshotNonVacuumable, NULL,
    6773             :                                  1, 0);
    6774             :     /* Set it up for index-only scan */
    6775      120782 :     index_scan->xs_want_itup = true;
    6776      120782 :     index_rescan(index_scan, scankeys, 1, NULL, 0);
    6777             : 
    6778             :     /* Fetch first/next tuple in specified direction */
    6779      154164 :     while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
    6780             :     {
    6781      154164 :         BlockNumber block = ItemPointerGetBlockNumber(tid);
    6782             : 
    6783      154164 :         if (!VM_ALL_VISIBLE(heapRel,
    6784             :                             block,
    6785             :                             &vmbuffer))
    6786             :         {
    6787             :             /* Rats, we have to visit the heap to check visibility */
    6788      112882 :             if (!index_fetch_heap(index_scan, tableslot))
    6789             :             {
    6790             :                 /*
    6791             :                  * No visible tuple for this index entry, so we need to
    6792             :                  * advance to the next entry.  Before doing so, count heap
    6793             :                  * page fetches and give up if we've done too many.
    6794             :                  *
    6795             :                  * We don't charge a page fetch if this is the same heap page
    6796             :                  * as the previous tuple.  This is on the conservative side,
    6797             :                  * since other recently-accessed pages are probably still in
    6798             :                  * buffers too; but it's good enough for this heuristic.
    6799             :                  */
    6800             : #define VISITED_PAGES_LIMIT 100
    6801             : 
    6802       33382 :                 if (block != last_heap_block)
    6803             :                 {
    6804        3472 :                     last_heap_block = block;
    6805        3472 :                     n_visited_heap_pages++;
    6806        3472 :                     if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
    6807           0 :                         break;
    6808             :                 }
    6809             : 
    6810       33382 :                 continue;       /* no visible tuple, try next index entry */
    6811             :             }
    6812             : 
    6813             :             /* We don't actually need the heap tuple for anything */
    6814       79500 :             ExecClearTuple(tableslot);
    6815             : 
    6816             :             /*
    6817             :              * We don't care whether there's more than one visible tuple in
    6818             :              * the HOT chain; if any are visible, that's good enough.
    6819             :              */
    6820             :         }
    6821             : 
    6822             :         /*
    6823             :          * We expect that the index will return data in IndexTuple not
    6824             :          * HeapTuple format.
    6825             :          */
    6826      120782 :         if (!index_scan->xs_itup)
    6827           0 :             elog(ERROR, "no data returned for index-only scan");
    6828             : 
    6829             :         /*
    6830             :          * We do not yet support recheck here.
    6831             :          */
    6832      120782 :         if (index_scan->xs_recheck)
    6833           0 :             break;
    6834             : 
    6835             :         /* OK to deconstruct the index tuple */
    6836      120782 :         index_deform_tuple(index_scan->xs_itup,
    6837             :                            index_scan->xs_itupdesc,
    6838             :                            values, isnull);
    6839             : 
    6840             :         /* Shouldn't have got a null, but be careful */
    6841      120782 :         if (isnull[0])
    6842           0 :             elog(ERROR, "found unexpected null value in index \"%s\"",
    6843             :                  RelationGetRelationName(indexRel));
    6844             : 
    6845             :         /* Copy the index column value out to caller's context */
    6846      120782 :         oldcontext = MemoryContextSwitchTo(outercontext);
    6847      120782 :         *endpointDatum = datumCopy(values[0], typByVal, typLen);
    6848      120782 :         MemoryContextSwitchTo(oldcontext);
    6849      120782 :         have_data = true;
    6850      120782 :         break;
    6851             :     }
    6852             : 
    6853      120782 :     if (vmbuffer != InvalidBuffer)
    6854      107734 :         ReleaseBuffer(vmbuffer);
    6855      120782 :     index_endscan(index_scan);
    6856             : 
    6857      120782 :     return have_data;
    6858             : }
    6859             : 
    6860             : /*
    6861             :  * find_join_input_rel
    6862             :  *      Look up the input relation for a join.
    6863             :  *
    6864             :  * We assume that the input relation's RelOptInfo must have been constructed
    6865             :  * already.
    6866             :  */
    6867             : static RelOptInfo *
    6868       10690 : find_join_input_rel(PlannerInfo *root, Relids relids)
    6869             : {
    6870       10690 :     RelOptInfo *rel = NULL;
    6871             : 
    6872       10690 :     if (!bms_is_empty(relids))
    6873             :     {
    6874             :         int         relid;
    6875             : 
    6876       10690 :         if (bms_get_singleton_member(relids, &relid))
    6877       10386 :             rel = find_base_rel(root, relid);
    6878             :         else
    6879         304 :             rel = find_join_rel(root, relids);
    6880             :     }
    6881             : 
    6882       10690 :     if (rel == NULL)
    6883           0 :         elog(ERROR, "could not find RelOptInfo for given relids");
    6884             : 
    6885       10690 :     return rel;
    6886             : }
    6887             : 
    6888             : 
    6889             : /*-------------------------------------------------------------------------
    6890             :  *
    6891             :  * Index cost estimation functions
    6892             :  *
    6893             :  *-------------------------------------------------------------------------
    6894             :  */
    6895             : 
    6896             : /*
    6897             :  * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
    6898             :  */
    6899             : List *
    6900      758182 : get_quals_from_indexclauses(List *indexclauses)
    6901             : {
    6902      758182 :     List       *result = NIL;
    6903             :     ListCell   *lc;
    6904             : 
    6905     1335150 :     foreach(lc, indexclauses)
    6906             :     {
    6907      576968 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    6908             :         ListCell   *lc2;
    6909             : 
    6910     1156848 :         foreach(lc2, iclause->indexquals)
    6911             :         {
    6912      579880 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    6913             : 
    6914      579880 :             result = lappend(result, rinfo);
    6915             :         }
    6916             :     }
    6917      758182 :     return result;
    6918             : }
    6919             : 
    6920             : /*
    6921             :  * Compute the total evaluation cost of the comparison operands in a list
    6922             :  * of index qual expressions.  Since we know these will be evaluated just
    6923             :  * once per scan, there's no need to distinguish startup from per-row cost.
    6924             :  *
    6925             :  * This can be used either on the result of get_quals_from_indexclauses(),
    6926             :  * or directly on an indexorderbys list.  In both cases, we expect that the
    6927             :  * index key expression is on the left side of binary clauses.
    6928             :  */
    6929             : Cost
    6930     1503370 : index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
    6931             : {
    6932     1503370 :     Cost        qual_arg_cost = 0;
    6933             :     ListCell   *lc;
    6934             : 
    6935     2083712 :     foreach(lc, indexquals)
    6936             :     {
    6937      580342 :         Expr       *clause = (Expr *) lfirst(lc);
    6938             :         Node       *other_operand;
    6939             :         QualCost    index_qual_cost;
    6940             : 
    6941             :         /*
    6942             :          * Index quals will have RestrictInfos, indexorderbys won't.  Look
    6943             :          * through RestrictInfo if present.
    6944             :          */
    6945      580342 :         if (IsA(clause, RestrictInfo))
    6946      579868 :             clause = ((RestrictInfo *) clause)->clause;
    6947             : 
    6948      580342 :         if (IsA(clause, OpExpr))
    6949             :         {
    6950      566180 :             OpExpr     *op = (OpExpr *) clause;
    6951             : 
    6952      566180 :             other_operand = (Node *) lsecond(op->args);
    6953             :         }
    6954       14162 :         else if (IsA(clause, RowCompareExpr))
    6955             :         {
    6956         396 :             RowCompareExpr *rc = (RowCompareExpr *) clause;
    6957             : 
    6958         396 :             other_operand = (Node *) rc->rargs;
    6959             :         }
    6960       13766 :         else if (IsA(clause, ScalarArrayOpExpr))
    6961             :         {
    6962       10840 :             ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    6963             : 
    6964       10840 :             other_operand = (Node *) lsecond(saop->args);
    6965             :         }
    6966        2926 :         else if (IsA(clause, NullTest))
    6967             :         {
    6968        2926 :             other_operand = NULL;
    6969             :         }
    6970             :         else
    6971             :         {
    6972           0 :             elog(ERROR, "unsupported indexqual type: %d",
    6973             :                  (int) nodeTag(clause));
    6974             :             other_operand = NULL;   /* keep compiler quiet */
    6975             :         }
    6976             : 
    6977      580342 :         cost_qual_eval_node(&index_qual_cost, other_operand, root);
    6978      580342 :         qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
    6979             :     }
    6980     1503370 :     return qual_arg_cost;
    6981             : }
    6982             : 
    6983             : void
    6984      745200 : genericcostestimate(PlannerInfo *root,
    6985             :                     IndexPath *path,
    6986             :                     double loop_count,
    6987             :                     GenericCosts *costs)
    6988             : {
    6989      745200 :     IndexOptInfo *index = path->indexinfo;
    6990      745200 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    6991      745200 :     List       *indexOrderBys = path->indexorderbys;
    6992             :     Cost        indexStartupCost;
    6993             :     Cost        indexTotalCost;
    6994             :     Selectivity indexSelectivity;
    6995             :     double      indexCorrelation;
    6996             :     double      numIndexPages;
    6997             :     double      numIndexTuples;
    6998             :     double      spc_random_page_cost;
    6999             :     double      num_sa_scans;
    7000             :     double      num_outer_scans;
    7001             :     double      num_scans;
    7002             :     double      qual_op_cost;
    7003             :     double      qual_arg_cost;
    7004             :     List       *selectivityQuals;
    7005             :     ListCell   *l;
    7006             : 
    7007             :     /*
    7008             :      * If the index is partial, AND the index predicate with the explicitly
    7009             :      * given indexquals to produce a more accurate idea of the index
    7010             :      * selectivity.
    7011             :      */
    7012      745200 :     selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
    7013             : 
    7014             :     /*
    7015             :      * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
    7016             :      * just assume that the number of index descents is the number of distinct
    7017             :      * combinations of array elements from all of the scan's SAOP clauses.
    7018             :      */
    7019      745200 :     num_sa_scans = costs->num_sa_scans;
    7020      745200 :     if (num_sa_scans < 1)
    7021             :     {
    7022        7804 :         num_sa_scans = 1;
    7023       16330 :         foreach(l, indexQuals)
    7024             :         {
    7025        8526 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
    7026             : 
    7027        8526 :             if (IsA(rinfo->clause, ScalarArrayOpExpr))
    7028             :             {
    7029          26 :                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
    7030          26 :                 double      alength = estimate_array_length(root, lsecond(saop->args));
    7031             : 
    7032          26 :                 if (alength > 1)
    7033          26 :                     num_sa_scans *= alength;
    7034             :             }
    7035             :         }
    7036             :     }
    7037             : 
    7038             :     /* Estimate the fraction of main-table tuples that will be visited */
    7039      745200 :     indexSelectivity = clauselist_selectivity(root, selectivityQuals,
    7040      745200 :                                               index->rel->relid,
    7041             :                                               JOIN_INNER,
    7042             :                                               NULL);
    7043             : 
    7044             :     /*
    7045             :      * If caller didn't give us an estimate, estimate the number of index
    7046             :      * tuples that will be visited.  We do it in this rather peculiar-looking
    7047             :      * way in order to get the right answer for partial indexes.
    7048             :      */
    7049      745200 :     numIndexTuples = costs->numIndexTuples;
    7050      745200 :     if (numIndexTuples <= 0.0)
    7051             :     {
    7052       75480 :         numIndexTuples = indexSelectivity * index->rel->tuples;
    7053             : 
    7054             :         /*
    7055             :          * The above calculation counts all the tuples visited across all
    7056             :          * scans induced by ScalarArrayOpExpr nodes.  We want to consider the
    7057             :          * average per-indexscan number, so adjust.  This is a handy place to
    7058             :          * round to integer, too.  (If caller supplied tuple estimate, it's
    7059             :          * responsible for handling these considerations.)
    7060             :          */
    7061       75480 :         numIndexTuples = rint(numIndexTuples / num_sa_scans);
    7062             :     }
    7063             : 
    7064             :     /*
    7065             :      * We can bound the number of tuples by the index size in any case. Also,
    7066             :      * always estimate at least one tuple is touched, even when
    7067             :      * indexSelectivity estimate is tiny.
    7068             :      */
    7069      745200 :     if (numIndexTuples > index->tuples)
    7070        5424 :         numIndexTuples = index->tuples;
    7071      745200 :     if (numIndexTuples < 1.0)
    7072       75088 :         numIndexTuples = 1.0;
    7073             : 
    7074             :     /*
    7075             :      * Estimate the number of index pages that will be retrieved.
    7076             :      *
    7077             :      * We use the simplistic method of taking a pro-rata fraction of the total
    7078             :      * number of index pages.  In effect, this counts only leaf pages and not
    7079             :      * any overhead such as index metapage or upper tree levels.
    7080             :      *
    7081             :      * In practice access to upper index levels is often nearly free because
    7082             :      * those tend to stay in cache under load; moreover, the cost involved is
    7083             :      * highly dependent on index type.  We therefore ignore such costs here
    7084             :      * and leave it to the caller to add a suitable charge if needed.
    7085             :      */
    7086      745200 :     if (index->pages > 1 && index->tuples > 1)
    7087      699214 :         numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
    7088             :     else
    7089       45986 :         numIndexPages = 1.0;
    7090             : 
    7091             :     /* fetch estimated page cost for tablespace containing index */
    7092      745200 :     get_tablespace_page_costs(index->reltablespace,
    7093             :                               &spc_random_page_cost,
    7094             :                               NULL);
    7095             : 
    7096             :     /*
    7097             :      * Now compute the disk access costs.
    7098             :      *
    7099             :      * The above calculations are all per-index-scan.  However, if we are in a
    7100             :      * nestloop inner scan, we can expect the scan to be repeated (with
    7101             :      * different search keys) for each row of the outer relation.  Likewise,
    7102             :      * ScalarArrayOpExpr quals result in multiple index scans.  This creates
    7103             :      * the potential for cache effects to reduce the number of disk page
    7104             :      * fetches needed.  We want to estimate the average per-scan I/O cost in
    7105             :      * the presence of caching.
    7106             :      *
    7107             :      * We use the Mackert-Lohman formula (see costsize.c for details) to
    7108             :      * estimate the total number of page fetches that occur.  While this
    7109             :      * wasn't what it was designed for, it seems a reasonable model anyway.
    7110             :      * Note that we are counting pages not tuples anymore, so we take N = T =
    7111             :      * index size, as if there were one "tuple" per page.
    7112             :      */
    7113      745200 :     num_outer_scans = loop_count;
    7114      745200 :     num_scans = num_sa_scans * num_outer_scans;
    7115             : 
    7116      745200 :     if (num_scans > 1)
    7117             :     {
    7118             :         double      pages_fetched;
    7119             : 
    7120             :         /* total page fetches ignoring cache effects */
    7121       83972 :         pages_fetched = numIndexPages * num_scans;
    7122             : 
    7123             :         /* use Mackert and Lohman formula to adjust for cache effects */
    7124       83972 :         pages_fetched = index_pages_fetched(pages_fetched,
    7125             :                                             index->pages,
    7126       83972 :                                             (double) index->pages,
    7127             :                                             root);
    7128             : 
    7129             :         /*
    7130             :          * Now compute the total disk access cost, and then report a pro-rated
    7131             :          * share for each outer scan.  (Don't pro-rate for ScalarArrayOpExpr,
    7132             :          * since that's internal to the indexscan.)
    7133             :          */
    7134       83972 :         indexTotalCost = (pages_fetched * spc_random_page_cost)
    7135             :             / num_outer_scans;
    7136             :     }
    7137             :     else
    7138             :     {
    7139             :         /*
    7140             :          * For a single index scan, we just charge spc_random_page_cost per
    7141             :          * page touched.
    7142             :          */
    7143      661228 :         indexTotalCost = numIndexPages * spc_random_page_cost;
    7144             :     }
    7145             : 
    7146             :     /*
    7147             :      * CPU cost: any complex expressions in the indexquals will need to be
    7148             :      * evaluated once at the start of the scan to reduce them to runtime keys
    7149             :      * to pass to the index AM (see nodeIndexscan.c).  We model the per-tuple
    7150             :      * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
    7151             :      * indexqual operator.  Because we have numIndexTuples as a per-scan
    7152             :      * number, we have to multiply by num_sa_scans to get the correct result
    7153             :      * for ScalarArrayOpExpr cases.  Similarly add in costs for any index
    7154             :      * ORDER BY expressions.
    7155             :      *
    7156             :      * Note: this neglects the possible costs of rechecking lossy operators.
    7157             :      * Detecting that that might be needed seems more expensive than it's
    7158             :      * worth, though, considering all the other inaccuracies here ...
    7159             :      */
    7160      745200 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
    7161      745200 :         index_other_operands_eval_cost(root, indexOrderBys);
    7162      745200 :     qual_op_cost = cpu_operator_cost *
    7163      745200 :         (list_length(indexQuals) + list_length(indexOrderBys));
    7164             : 
    7165      745200 :     indexStartupCost = qual_arg_cost;
    7166      745200 :     indexTotalCost += qual_arg_cost;
    7167      745200 :     indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
    7168             : 
    7169             :     /*
    7170             :      * Generic assumption about index correlation: there isn't any.
    7171             :      */
    7172      745200 :     indexCorrelation = 0.0;
    7173             : 
    7174             :     /*
    7175             :      * Return everything to caller.
    7176             :      */
    7177      745200 :     costs->indexStartupCost = indexStartupCost;
    7178      745200 :     costs->indexTotalCost = indexTotalCost;
    7179      745200 :     costs->indexSelectivity = indexSelectivity;
    7180      745200 :     costs->indexCorrelation = indexCorrelation;
    7181      745200 :     costs->numIndexPages = numIndexPages;
    7182      745200 :     costs->numIndexTuples = numIndexTuples;
    7183      745200 :     costs->spc_random_page_cost = spc_random_page_cost;
    7184      745200 :     costs->num_sa_scans = num_sa_scans;
    7185      745200 : }
    7186             : 
    7187             : /*
    7188             :  * If the index is partial, add its predicate to the given qual list.
    7189             :  *
    7190             :  * ANDing the index predicate with the explicitly given indexquals produces
    7191             :  * a more accurate idea of the index's selectivity.  However, we need to be
    7192             :  * careful not to insert redundant clauses, because clauselist_selectivity()
    7193             :  * is easily fooled into computing a too-low selectivity estimate.  Our
    7194             :  * approach is to add only the predicate clause(s) that cannot be proven to
    7195             :  * be implied by the given indexquals.  This successfully handles cases such
    7196             :  * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
    7197             :  * There are many other cases where we won't detect redundancy, leading to a
    7198             :  * too-low selectivity estimate, which will bias the system in favor of using
    7199             :  * partial indexes where possible.  That is not necessarily bad though.
    7200             :  *
    7201             :  * Note that indexQuals contains RestrictInfo nodes while the indpred
    7202             :  * does not, so the output list will be mixed.  This is OK for both
    7203             :  * predicate_implied_by() and clauselist_selectivity(), but might be
    7204             :  * problematic if the result were passed to other things.
    7205             :  */
    7206             : List *
    7207     1251412 : add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
    7208             : {
    7209     1251412 :     List       *predExtraQuals = NIL;
    7210             :     ListCell   *lc;
    7211             : 
    7212     1251412 :     if (index->indpred == NIL)
    7213     1249386 :         return indexQuals;
    7214             : 
    7215        4064 :     foreach(lc, index->indpred)
    7216             :     {
    7217        2038 :         Node       *predQual = (Node *) lfirst(lc);
    7218        2038 :         List       *oneQual = list_make1(predQual);
    7219             : 
    7220        2038 :         if (!predicate_implied_by(oneQual, indexQuals, false))
    7221        1836 :             predExtraQuals = list_concat(predExtraQuals, oneQual);
    7222             :     }
    7223        2026 :     return list_concat(predExtraQuals, indexQuals);
    7224             : }
    7225             : 
    7226             : /*
    7227             :  * Estimate correlation of btree index's first column.
    7228             :  *
    7229             :  * If we can get an estimate of the first column's ordering correlation C
    7230             :  * from pg_statistic, estimate the index correlation as C for a single-column
    7231             :  * index, or C * 0.75 for multiple columns.  The idea here is that multiple
    7232             :  * columns dilute the importance of the first column's ordering, but don't
    7233             :  * negate it entirely.
    7234             :  *
    7235             :  * We already filled in the stats tuple for *vardata when called.
    7236             :  */
    7237             : static double
    7238      562522 : btcost_correlation(IndexOptInfo *index, VariableStatData *vardata)
    7239             : {
    7240             :     Oid         sortop;
    7241             :     AttStatsSlot sslot;
    7242      562522 :     double      indexCorrelation = 0;
    7243             : 
    7244             :     Assert(HeapTupleIsValid(vardata->statsTuple));
    7245             : 
    7246      562522 :     sortop = get_opfamily_member(index->opfamily[0],
    7247      562522 :                                  index->opcintype[0],
    7248      562522 :                                  index->opcintype[0],
    7249             :                                  BTLessStrategyNumber);
    7250     1125044 :     if (OidIsValid(sortop) &&
    7251      562522 :         get_attstatsslot(&sslot, vardata->statsTuple,
    7252             :                          STATISTIC_KIND_CORRELATION, sortop,
    7253             :                          ATTSTATSSLOT_NUMBERS))
    7254             :     {
    7255             :         double      varCorrelation;
    7256             : 
    7257             :         Assert(sslot.nnumbers == 1);
    7258      555726 :         varCorrelation = sslot.numbers[0];
    7259             : 
    7260      555726 :         if (index->reverse_sort[0])
    7261           0 :             varCorrelation = -varCorrelation;
    7262             : 
    7263      555726 :         if (index->nkeycolumns > 1)
    7264      195524 :             indexCorrelation = varCorrelation * 0.75;
    7265             :         else
    7266      360202 :             indexCorrelation = varCorrelation;
    7267             : 
    7268      555726 :         free_attstatsslot(&sslot);
    7269             :     }
    7270             : 
    7271      562522 :     return indexCorrelation;
    7272             : }
    7273             : 
    7274             : void
    7275      737396 : btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7276             :                Cost *indexStartupCost, Cost *indexTotalCost,
    7277             :                Selectivity *indexSelectivity, double *indexCorrelation,
    7278             :                double *indexPages)
    7279             : {
    7280      737396 :     IndexOptInfo *index = path->indexinfo;
    7281      737396 :     GenericCosts costs = {0};
    7282      737396 :     VariableStatData vardata = {0};
    7283             :     double      numIndexTuples;
    7284             :     Cost        descentCost;
    7285             :     List       *indexBoundQuals;
    7286             :     List       *indexSkipQuals;
    7287             :     int         indexcol;
    7288             :     bool        eqQualHere;
    7289             :     bool        found_row_compare;
    7290             :     bool        found_array;
    7291             :     bool        found_is_null_op;
    7292      737396 :     bool        have_correlation = false;
    7293             :     double      num_sa_scans;
    7294      737396 :     double      correlation = 0.0;
    7295             :     ListCell   *lc;
    7296             : 
    7297             :     /*
    7298             :      * For a btree scan, only leading '=' quals plus inequality quals for the
    7299             :      * immediately next attribute contribute to index selectivity (these are
    7300             :      * the "boundary quals" that determine the starting and stopping points of
    7301             :      * the index scan).  Additional quals can suppress visits to the heap, so
    7302             :      * it's OK to count them in indexSelectivity, but they should not count
    7303             :      * for estimating numIndexTuples.  So we must examine the given indexquals
    7304             :      * to find out which ones count as boundary quals.  We rely on the
    7305             :      * knowledge that they are given in index column order.  Note that nbtree
    7306             :      * preprocessing can add skip arrays that act as leading '=' quals in the
    7307             :      * absence of ordinary input '=' quals, so in practice _most_ input quals
    7308             :      * are able to act as index bound quals (which we take into account here).
    7309             :      *
    7310             :      * For a RowCompareExpr, we consider only the first column, just as
    7311             :      * rowcomparesel() does.
    7312             :      *
    7313             :      * If there's a SAOP or skip array in the quals, we'll actually perform up
    7314             :      * to N index descents (not just one), but the underlying array key's
    7315             :      * operator can be considered to act the same as it normally does.
    7316             :      */
    7317      737396 :     indexBoundQuals = NIL;
    7318      737396 :     indexSkipQuals = NIL;
    7319      737396 :     indexcol = 0;
    7320      737396 :     eqQualHere = false;
    7321      737396 :     found_row_compare = false;
    7322      737396 :     found_array = false;
    7323      737396 :     found_is_null_op = false;
    7324      737396 :     num_sa_scans = 1;
    7325     1261946 :     foreach(lc, path->indexclauses)
    7326             :     {
    7327      552980 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    7328             :         ListCell   *lc2;
    7329             : 
    7330      552980 :         if (indexcol < iclause->indexcol)
    7331             :         {
    7332       98284 :             double      num_sa_scans_prev_cols = num_sa_scans;
    7333             : 
    7334             :             /*
    7335             :              * Beginning of a new column's quals.
    7336             :              *
    7337             :              * Skip scans use skip arrays, which are ScalarArrayOp style
    7338             :              * arrays that generate their elements procedurally and on demand.
    7339             :              * Given a multi-column index on "(a, b)", and an SQL WHERE clause
    7340             :              * "WHERE b = 42", a skip scan will effectively use an indexqual
    7341             :              * "WHERE a = ANY('{every col a value}') AND b = 42".  (Obviously,
    7342             :              * the array on "a" must also return "IS NULL" matches, since our
    7343             :              * WHERE clause used no strict operator on "a").
    7344             :              *
    7345             :              * Here we consider how nbtree will backfill skip arrays for any
    7346             :              * index columns that lacked an '=' qual.  This maintains our
    7347             :              * num_sa_scans estimate, and determines if this new column (the
    7348             :              * "iclause->indexcol" column, not the prior "indexcol" column)
    7349             :              * can have its RestrictInfos/quals added to indexBoundQuals.
    7350             :              *
    7351             :              * We'll need to handle columns that have inequality quals, where
    7352             :              * the skip array generates values from a range constrained by the
    7353             :              * quals (not every possible value).  We've been maintaining
    7354             :              * indexSkipQuals to help with this; it will now contain all of
    7355             :              * the prior column's quals (that is, indexcol's quals) when they
    7356             :              * might be used for this.
    7357             :              */
    7358       98284 :             if (found_row_compare)
    7359             :             {
    7360             :                 /*
    7361             :                  * Skip arrays can't be added after a RowCompare input qual
    7362             :                  * due to limitations in nbtree
    7363             :                  */
    7364          24 :                 break;
    7365             :             }
    7366       98260 :             if (eqQualHere)
    7367             :             {
    7368             :                 /*
    7369             :                  * Don't need to add a skip array for an indexcol that already
    7370             :                  * has an '=' qual/equality constraint
    7371             :                  */
    7372       70006 :                 indexcol++;
    7373       70006 :                 indexSkipQuals = NIL;
    7374             :             }
    7375       98260 :             eqQualHere = false;
    7376             : 
    7377      101348 :             while (indexcol < iclause->indexcol)
    7378             :             {
    7379             :                 double      ndistinct;
    7380       31494 :                 bool        isdefault = true;
    7381             : 
    7382       31494 :                 found_array = true;
    7383             : 
    7384             :                 /*
    7385             :                  * A skipped attribute's ndistinct forms the basis of our
    7386             :                  * estimate of the total number of "array elements" used by
    7387             :                  * its skip array at runtime.  Look that up first.
    7388             :                  */
    7389       31494 :                 examine_indexcol_variable(root, index, indexcol, &vardata);
    7390       31494 :                 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
    7391             : 
    7392       31494 :                 if (indexcol == 0)
    7393             :                 {
    7394             :                     /*
    7395             :                      * Get an estimate of the leading column's correlation in
    7396             :                      * passing (avoids rereading variable stats below)
    7397             :                      */
    7398       28242 :                     if (HeapTupleIsValid(vardata.statsTuple))
    7399       21698 :                         correlation = btcost_correlation(index, &vardata);
    7400       28242 :                     have_correlation = true;
    7401             :                 }
    7402             : 
    7403       31494 :                 ReleaseVariableStats(vardata);
    7404             : 
    7405             :                 /*
    7406             :                  * If ndistinct is a default estimate, conservatively assume
    7407             :                  * that no skipping will happen at runtime
    7408             :                  */
    7409       31494 :                 if (isdefault)
    7410             :                 {
    7411        5050 :                     num_sa_scans = num_sa_scans_prev_cols;
    7412       28406 :                     break;      /* done building indexBoundQuals */
    7413             :                 }
    7414             : 
    7415             :                 /*
    7416             :                  * Apply indexcol's indexSkipQuals selectivity to ndistinct
    7417             :                  */
    7418       26444 :                 if (indexSkipQuals != NIL)
    7419             :                 {
    7420             :                     List       *partialSkipQuals;
    7421             :                     Selectivity ndistinctfrac;
    7422             : 
    7423             :                     /*
    7424             :                      * If the index is partial, AND the index predicate with
    7425             :                      * the index-bound quals to produce a more accurate idea
    7426             :                      * of the number of distinct values for prior indexcol
    7427             :                      */
    7428         664 :                     partialSkipQuals = add_predicate_to_index_quals(index,
    7429             :                                                                     indexSkipQuals);
    7430             : 
    7431         664 :                     ndistinctfrac = clauselist_selectivity(root, partialSkipQuals,
    7432         664 :                                                            index->rel->relid,
    7433             :                                                            JOIN_INNER,
    7434             :                                                            NULL);
    7435             : 
    7436             :                     /*
    7437             :                      * If ndistinctfrac is selective (on its own), the scan is
    7438             :                      * unlikely to benefit from repositioning itself using
    7439             :                      * later quals.  Do not allow iclause->indexcol's quals to
    7440             :                      * be added to indexBoundQuals (it would increase descent
    7441             :                      * costs, without lowering numIndexTuples costs by much).
    7442             :                      */
    7443         664 :                     if (ndistinctfrac < DEFAULT_RANGE_INEQ_SEL)
    7444             :                     {
    7445         374 :                         num_sa_scans = num_sa_scans_prev_cols;
    7446         374 :                         break;  /* done building indexBoundQuals */
    7447             :                     }
    7448             : 
    7449             :                     /* Adjust ndistinct downward */
    7450         290 :                     ndistinct = rint(ndistinct * ndistinctfrac);
    7451         290 :                     ndistinct = Max(ndistinct, 1);
    7452             :                 }
    7453             : 
    7454             :                 /*
    7455             :                  * When there's no inequality quals, account for the need to
    7456             :                  * find an initial value by counting -inf/+inf as a value.
    7457             :                  *
    7458             :                  * We don't charge anything extra for possible next/prior key
    7459             :                  * index probes, which are sometimes used to find the next
    7460             :                  * valid skip array element (ahead of using the located
    7461             :                  * element value to relocate the scan to the next position
    7462             :                  * that might contain matching tuples).  It seems hard to do
    7463             :                  * better here.  Use of the skip support infrastructure often
    7464             :                  * avoids most next/prior key probes.  But even when it can't,
    7465             :                  * there's a decent chance that most individual next/prior key
    7466             :                  * probes will locate a leaf page whose key space overlaps all
    7467             :                  * of the scan's keys (even the lower-order keys) -- which
    7468             :                  * also avoids the need for a separate, extra index descent.
    7469             :                  * Note also that these probes are much cheaper than non-probe
    7470             :                  * primitive index scans: they're reliably very selective.
    7471             :                  */
    7472       26070 :                 if (indexSkipQuals == NIL)
    7473       25780 :                     ndistinct += 1;
    7474             : 
    7475             :                 /*
    7476             :                  * Update num_sa_scans estimate by multiplying by ndistinct.
    7477             :                  *
    7478             :                  * We make the pessimistic assumption that there is no
    7479             :                  * naturally occurring cross-column correlation.  This is
    7480             :                  * often wrong, but it seems best to err on the side of not
    7481             :                  * expecting skipping to be helpful...
    7482             :                  */
    7483       26070 :                 num_sa_scans *= ndistinct;
    7484             : 
    7485             :                 /*
    7486             :                  * ...but back out of adding this latest group of 1 or more
    7487             :                  * skip arrays when num_sa_scans exceeds the total number of
    7488             :                  * index pages (revert to num_sa_scans from before indexcol).
    7489             :                  * This causes a sharp discontinuity in cost (as a function of
    7490             :                  * the indexcol's ndistinct), but that is representative of
    7491             :                  * actual runtime costs.
    7492             :                  *
    7493             :                  * Note that skipping is helpful when each primitive index
    7494             :                  * scan only manages to skip over 1 or 2 irrelevant leaf pages
    7495             :                  * on average.  Skip arrays bring savings in CPU costs due to
    7496             :                  * the scan not needing to evaluate indexquals against every
    7497             :                  * tuple, which can greatly exceed any savings in I/O costs.
    7498             :                  * This test is a test of whether num_sa_scans implies that
    7499             :                  * we're past the point where the ability to skip ceases to
    7500             :                  * lower the scan's costs (even qual evaluation CPU costs).
    7501             :                  */
    7502       26070 :                 if (index->pages < num_sa_scans)
    7503             :                 {
    7504       22982 :                     num_sa_scans = num_sa_scans_prev_cols;
    7505       22982 :                     break;      /* done building indexBoundQuals */
    7506             :                 }
    7507             : 
    7508        3088 :                 indexcol++;
    7509        3088 :                 indexSkipQuals = NIL;
    7510             :             }
    7511             : 
    7512             :             /*
    7513             :              * Finished considering the need to add skip arrays to bridge an
    7514             :              * initial eqQualHere gap between the old and new index columns
    7515             :              * (or there was no initial eqQualHere gap in the first place).
    7516             :              *
    7517             :              * If an initial gap could not be bridged, then new column's quals
    7518             :              * (i.e. iclause->indexcol's quals) won't go into indexBoundQuals,
    7519             :              * and so won't affect our final numIndexTuples estimate.
    7520             :              */
    7521       98260 :             if (indexcol != iclause->indexcol)
    7522       28406 :                 break;          /* done building indexBoundQuals */
    7523             :         }
    7524             : 
    7525             :         Assert(indexcol == iclause->indexcol);
    7526             : 
    7527             :         /* Examine each indexqual associated with this index clause */
    7528     1051840 :         foreach(lc2, iclause->indexquals)
    7529             :         {
    7530      527290 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    7531      527290 :             Expr       *clause = rinfo->clause;
    7532      527290 :             Oid         clause_op = InvalidOid;
    7533             :             int         op_strategy;
    7534             : 
    7535      527290 :             if (IsA(clause, OpExpr))
    7536             :             {
    7537      514194 :                 OpExpr     *op = (OpExpr *) clause;
    7538             : 
    7539      514194 :                 clause_op = op->opno;
    7540             :             }
    7541       13096 :             else if (IsA(clause, RowCompareExpr))
    7542             :             {
    7543         396 :                 RowCompareExpr *rc = (RowCompareExpr *) clause;
    7544             : 
    7545         396 :                 clause_op = linitial_oid(rc->opnos);
    7546         396 :                 found_row_compare = true;
    7547             :             }
    7548       12700 :             else if (IsA(clause, ScalarArrayOpExpr))
    7549             :             {
    7550       10416 :                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    7551       10416 :                 Node       *other_operand = (Node *) lsecond(saop->args);
    7552       10416 :                 double      alength = estimate_array_length(root, other_operand);
    7553             : 
    7554       10416 :                 clause_op = saop->opno;
    7555       10416 :                 found_array = true;
    7556             :                 /* estimate SA descents by indexBoundQuals only */
    7557       10416 :                 if (alength > 1)
    7558       10216 :                     num_sa_scans *= alength;
    7559             :             }
    7560        2284 :             else if (IsA(clause, NullTest))
    7561             :             {
    7562        2284 :                 NullTest   *nt = (NullTest *) clause;
    7563             : 
    7564        2284 :                 if (nt->nulltesttype == IS_NULL)
    7565             :                 {
    7566         240 :                     found_is_null_op = true;
    7567             :                     /* IS NULL is like = for selectivity/skip scan purposes */
    7568         240 :                     eqQualHere = true;
    7569             :                 }
    7570             :             }
    7571             :             else
    7572           0 :                 elog(ERROR, "unsupported indexqual type: %d",
    7573             :                      (int) nodeTag(clause));
    7574             : 
    7575             :             /* check for equality operator */
    7576      527290 :             if (OidIsValid(clause_op))
    7577             :             {
    7578      525006 :                 op_strategy = get_op_opfamily_strategy(clause_op,
    7579      525006 :                                                        index->opfamily[indexcol]);
    7580             :                 Assert(op_strategy != 0);   /* not a member of opfamily?? */
    7581      525006 :                 if (op_strategy == BTEqualStrategyNumber)
    7582      498698 :                     eqQualHere = true;
    7583             :             }
    7584             : 
    7585      527290 :             indexBoundQuals = lappend(indexBoundQuals, rinfo);
    7586             : 
    7587             :             /*
    7588             :              * We apply inequality selectivities to estimate index descent
    7589             :              * costs with scans that use skip arrays.  Save this indexcol's
    7590             :              * RestrictInfos if it looks like they'll be needed for that.
    7591             :              */
    7592      527290 :             if (!eqQualHere && !found_row_compare &&
    7593       27254 :                 indexcol < index->nkeycolumns - 1)
    7594        5704 :                 indexSkipQuals = lappend(indexSkipQuals, rinfo);
    7595             :         }
    7596             :     }
    7597             : 
    7598             :     /*
    7599             :      * If index is unique and we found an '=' clause for each column, we can
    7600             :      * just assume numIndexTuples = 1 and skip the expensive
    7601             :      * clauselist_selectivity calculations.  However, an array or NullTest
    7602             :      * always invalidates that theory (even when eqQualHere has been set).
    7603             :      */
    7604      737396 :     if (index->unique &&
    7605      592988 :         indexcol == index->nkeycolumns - 1 &&
    7606      240114 :         eqQualHere &&
    7607      240114 :         !found_array &&
    7608      234148 :         !found_is_null_op)
    7609      234100 :         numIndexTuples = 1.0;
    7610             :     else
    7611             :     {
    7612             :         List       *selectivityQuals;
    7613             :         Selectivity btreeSelectivity;
    7614             : 
    7615             :         /*
    7616             :          * If the index is partial, AND the index predicate with the
    7617             :          * index-bound quals to produce a more accurate idea of the number of
    7618             :          * rows covered by the bound conditions.
    7619             :          */
    7620      503296 :         selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
    7621             : 
    7622      503296 :         btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
    7623      503296 :                                                   index->rel->relid,
    7624             :                                                   JOIN_INNER,
    7625             :                                                   NULL);
    7626      503296 :         numIndexTuples = btreeSelectivity * index->rel->tuples;
    7627             : 
    7628             :         /*
    7629             :          * btree automatically combines individual array element primitive
    7630             :          * index scans whenever the tuples covered by the next set of array
    7631             :          * keys are close to tuples covered by the current set.  That puts a
    7632             :          * natural ceiling on the worst case number of descents -- there
    7633             :          * cannot possibly be more than one descent per leaf page scanned.
    7634             :          *
    7635             :          * Clamp the number of descents to at most 1/3 the number of index
    7636             :          * pages.  This avoids implausibly high estimates with low selectivity
    7637             :          * paths, where scans usually require only one or two descents.  This
    7638             :          * is most likely to help when there are several SAOP clauses, where
    7639             :          * naively accepting the total number of distinct combinations of
    7640             :          * array elements as the number of descents would frequently lead to
    7641             :          * wild overestimates.
    7642             :          *
    7643             :          * We somewhat arbitrarily don't just make the cutoff the total number
    7644             :          * of leaf pages (we make it 1/3 the total number of pages instead) to
    7645             :          * give the btree code credit for its ability to continue on the leaf
    7646             :          * level with low selectivity scans.
    7647             :          *
    7648             :          * Note: num_sa_scans includes both ScalarArrayOp array elements and
    7649             :          * skip array elements whose qual affects our numIndexTuples estimate.
    7650             :          */
    7651      503296 :         num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
    7652      503296 :         num_sa_scans = Max(num_sa_scans, 1);
    7653             : 
    7654             :         /*
    7655             :          * As in genericcostestimate(), we have to adjust for any array quals
    7656             :          * included in indexBoundQuals, and then round to integer.
    7657             :          *
    7658             :          * It is tempting to make genericcostestimate behave as if array
    7659             :          * clauses work in almost the same way as scalar operators during
    7660             :          * btree scans, making the top-level scan look like a continuous scan
    7661             :          * (as opposed to num_sa_scans-many primitive index scans).  After
    7662             :          * all, btree scans mostly work like that at runtime.  However, such a
    7663             :          * scheme would badly bias genericcostestimate's simplistic approach
    7664             :          * to calculating numIndexPages through prorating.
    7665             :          *
    7666             :          * Stick with the approach taken by non-native SAOP scans for now.
    7667             :          * genericcostestimate will use the Mackert-Lohman formula to
    7668             :          * compensate for repeat page fetches, even though that definitely
    7669             :          * won't happen during btree scans (not for leaf pages, at least).
    7670             :          * We're usually very pessimistic about the number of primitive index
    7671             :          * scans that will be required, but it's not clear how to do better.
    7672             :          */
    7673      503296 :         numIndexTuples = rint(numIndexTuples / num_sa_scans);
    7674             :     }
    7675             : 
    7676             :     /*
    7677             :      * Now do generic index cost estimation.
    7678             :      */
    7679      737396 :     costs.numIndexTuples = numIndexTuples;
    7680      737396 :     costs.num_sa_scans = num_sa_scans;
    7681             : 
    7682      737396 :     genericcostestimate(root, path, loop_count, &costs);
    7683             : 
    7684             :     /*
    7685             :      * Add a CPU-cost component to represent the costs of initial btree
    7686             :      * descent.  We don't charge any I/O cost for touching upper btree levels,
    7687             :      * since they tend to stay in cache, but we still have to do about log2(N)
    7688             :      * comparisons to descend a btree of N leaf tuples.  We charge one
    7689             :      * cpu_operator_cost per comparison.
    7690             :      *
    7691             :      * If there are SAOP or skip array keys, charge this once per estimated
    7692             :      * index descent.  The ones after the first one are not startup cost so
    7693             :      * far as the overall plan goes, so just add them to "total" cost.
    7694             :      */
    7695      737396 :     if (index->tuples > 1)        /* avoid computing log(0) */
    7696             :     {
    7697      700060 :         descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
    7698      700060 :         costs.indexStartupCost += descentCost;
    7699      700060 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7700             :     }
    7701             : 
    7702             :     /*
    7703             :      * Even though we're not charging I/O cost for touching upper btree pages,
    7704             :      * it's still reasonable to charge some CPU cost per page descended
    7705             :      * through.  Moreover, if we had no such charge at all, bloated indexes
    7706             :      * would appear to have the same search cost as unbloated ones, at least
    7707             :      * in cases where only a single leaf page is expected to be visited.  This
    7708             :      * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
    7709             :      * touched.  The number of such pages is btree tree height plus one (ie,
    7710             :      * we charge for the leaf page too).  As above, charge once per estimated
    7711             :      * SAOP/skip array descent.
    7712             :      */
    7713      737396 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    7714      737396 :     costs.indexStartupCost += descentCost;
    7715      737396 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7716             : 
    7717      737396 :     if (!have_correlation)
    7718             :     {
    7719      709154 :         examine_indexcol_variable(root, index, 0, &vardata);
    7720      709154 :         if (HeapTupleIsValid(vardata.statsTuple))
    7721      540824 :             costs.indexCorrelation = btcost_correlation(index, &vardata);
    7722      709154 :         ReleaseVariableStats(vardata);
    7723             :     }
    7724             :     else
    7725             :     {
    7726             :         /* btcost_correlation already called earlier on */
    7727       28242 :         costs.indexCorrelation = correlation;
    7728             :     }
    7729             : 
    7730      737396 :     *indexStartupCost = costs.indexStartupCost;
    7731      737396 :     *indexTotalCost = costs.indexTotalCost;
    7732      737396 :     *indexSelectivity = costs.indexSelectivity;
    7733      737396 :     *indexCorrelation = costs.indexCorrelation;
    7734      737396 :     *indexPages = costs.numIndexPages;
    7735      737396 : }
    7736             : 
    7737             : void
    7738         418 : hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7739             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    7740             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    7741             :                  double *indexPages)
    7742             : {
    7743         418 :     GenericCosts costs = {0};
    7744             : 
    7745         418 :     genericcostestimate(root, path, loop_count, &costs);
    7746             : 
    7747             :     /*
    7748             :      * A hash index has no descent costs as such, since the index AM can go
    7749             :      * directly to the target bucket after computing the hash value.  There
    7750             :      * are a couple of other hash-specific costs that we could conceivably add
    7751             :      * here, though:
    7752             :      *
    7753             :      * Ideally we'd charge spc_random_page_cost for each page in the target
    7754             :      * bucket, not just the numIndexPages pages that genericcostestimate
    7755             :      * thought we'd visit.  However in most cases we don't know which bucket
    7756             :      * that will be.  There's no point in considering the average bucket size
    7757             :      * because the hash AM makes sure that's always one page.
    7758             :      *
    7759             :      * Likewise, we could consider charging some CPU for each index tuple in
    7760             :      * the bucket, if we knew how many there were.  But the per-tuple cost is
    7761             :      * just a hash value comparison, not a general datatype-dependent
    7762             :      * comparison, so any such charge ought to be quite a bit less than
    7763             :      * cpu_operator_cost; which makes it probably not worth worrying about.
    7764             :      *
    7765             :      * A bigger issue is that chance hash-value collisions will result in
    7766             :      * wasted probes into the heap.  We don't currently attempt to model this
    7767             :      * cost on the grounds that it's rare, but maybe it's not rare enough.
    7768             :      * (Any fix for this ought to consider the generic lossy-operator problem,
    7769             :      * though; it's not entirely hash-specific.)
    7770             :      */
    7771             : 
    7772         418 :     *indexStartupCost = costs.indexStartupCost;
    7773         418 :     *indexTotalCost = costs.indexTotalCost;
    7774         418 :     *indexSelectivity = costs.indexSelectivity;
    7775         418 :     *indexCorrelation = costs.indexCorrelation;
    7776         418 :     *indexPages = costs.numIndexPages;
    7777         418 : }
    7778             : 
    7779             : void
    7780        4790 : gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7781             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    7782             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    7783             :                  double *indexPages)
    7784             : {
    7785        4790 :     IndexOptInfo *index = path->indexinfo;
    7786        4790 :     GenericCosts costs = {0};
    7787             :     Cost        descentCost;
    7788             : 
    7789        4790 :     genericcostestimate(root, path, loop_count, &costs);
    7790             : 
    7791             :     /*
    7792             :      * We model index descent costs similarly to those for btree, but to do
    7793             :      * that we first need an idea of the tree height.  We somewhat arbitrarily
    7794             :      * assume that the fanout is 100, meaning the tree height is at most
    7795             :      * log100(index->pages).
    7796             :      *
    7797             :      * Although this computation isn't really expensive enough to require
    7798             :      * caching, we might as well use index->tree_height to cache it.
    7799             :      */
    7800        4790 :     if (index->tree_height < 0) /* unknown? */
    7801             :     {
    7802        4776 :         if (index->pages > 1) /* avoid computing log(0) */
    7803        2720 :             index->tree_height = (int) (log(index->pages) / log(100.0));
    7804             :         else
    7805        2056 :             index->tree_height = 0;
    7806             :     }
    7807             : 
    7808             :     /*
    7809             :      * Add a CPU-cost component to represent the costs of initial descent. We
    7810             :      * just use log(N) here not log2(N) since the branching factor isn't
    7811             :      * necessarily two anyway.  As for btree, charge once per SA scan.
    7812             :      */
    7813        4790 :     if (index->tuples > 1)        /* avoid computing log(0) */
    7814             :     {
    7815        4790 :         descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
    7816        4790 :         costs.indexStartupCost += descentCost;
    7817        4790 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7818             :     }
    7819             : 
    7820             :     /*
    7821             :      * Likewise add a per-page charge, calculated the same as for btrees.
    7822             :      */
    7823        4790 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    7824        4790 :     costs.indexStartupCost += descentCost;
    7825        4790 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7826             : 
    7827        4790 :     *indexStartupCost = costs.indexStartupCost;
    7828        4790 :     *indexTotalCost = costs.indexTotalCost;
    7829        4790 :     *indexSelectivity = costs.indexSelectivity;
    7830        4790 :     *indexCorrelation = costs.indexCorrelation;
    7831        4790 :     *indexPages = costs.numIndexPages;
    7832        4790 : }
    7833             : 
    7834             : void
    7835        1784 : spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    7836             :                 Cost *indexStartupCost, Cost *indexTotalCost,
    7837             :                 Selectivity *indexSelectivity, double *indexCorrelation,
    7838             :                 double *indexPages)
    7839             : {
    7840        1784 :     IndexOptInfo *index = path->indexinfo;
    7841        1784 :     GenericCosts costs = {0};
    7842             :     Cost        descentCost;
    7843             : 
    7844        1784 :     genericcostestimate(root, path, loop_count, &costs);
    7845             : 
    7846             :     /*
    7847             :      * We model index descent costs similarly to those for btree, but to do
    7848             :      * that we first need an idea of the tree height.  We somewhat arbitrarily
    7849             :      * assume that the fanout is 100, meaning the tree height is at most
    7850             :      * log100(index->pages).
    7851             :      *
    7852             :      * Although this computation isn't really expensive enough to require
    7853             :      * caching, we might as well use index->tree_height to cache it.
    7854             :      */
    7855        1784 :     if (index->tree_height < 0) /* unknown? */
    7856             :     {
    7857        1778 :         if (index->pages > 1) /* avoid computing log(0) */
    7858        1778 :             index->tree_height = (int) (log(index->pages) / log(100.0));
    7859             :         else
    7860           0 :             index->tree_height = 0;
    7861             :     }
    7862             : 
    7863             :     /*
    7864             :      * Add a CPU-cost component to represent the costs of initial descent. We
    7865             :      * just use log(N) here not log2(N) since the branching factor isn't
    7866             :      * necessarily two anyway.  As for btree, charge once per SA scan.
    7867             :      */
    7868        1784 :     if (index->tuples > 1)        /* avoid computing log(0) */
    7869             :     {
    7870        1784 :         descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
    7871        1784 :         costs.indexStartupCost += descentCost;
    7872        1784 :         costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7873             :     }
    7874             : 
    7875             :     /*
    7876             :      * Likewise add a per-page charge, calculated the same as for btrees.
    7877             :      */
    7878        1784 :     descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    7879        1784 :     costs.indexStartupCost += descentCost;
    7880        1784 :     costs.indexTotalCost += costs.num_sa_scans * descentCost;
    7881             : 
    7882        1784 :     *indexStartupCost = costs.indexStartupCost;
    7883        1784 :     *indexTotalCost = costs.indexTotalCost;
    7884        1784 :     *indexSelectivity = costs.indexSelectivity;
    7885        1784 :     *indexCorrelation = costs.indexCorrelation;
    7886        1784 :     *indexPages = costs.numIndexPages;
    7887        1784 : }
    7888             : 
    7889             : 
    7890             : /*
    7891             :  * Support routines for gincostestimate
    7892             :  */
    7893             : 
    7894             : typedef struct
    7895             : {
    7896             :     bool        attHasFullScan[INDEX_MAX_KEYS];
    7897             :     bool        attHasNormalScan[INDEX_MAX_KEYS];
    7898             :     double      partialEntries;
    7899             :     double      exactEntries;
    7900             :     double      searchEntries;
    7901             :     double      arrayScans;
    7902             : } GinQualCounts;
    7903             : 
    7904             : /*
    7905             :  * Estimate the number of index terms that need to be searched for while
    7906             :  * testing the given GIN query, and increment the counts in *counts
    7907             :  * appropriately.  If the query is unsatisfiable, return false.
    7908             :  */
    7909             : static bool
    7910        2456 : gincost_pattern(IndexOptInfo *index, int indexcol,
    7911             :                 Oid clause_op, Datum query,
    7912             :                 GinQualCounts *counts)
    7913             : {
    7914             :     FmgrInfo    flinfo;
    7915             :     Oid         extractProcOid;
    7916             :     Oid         collation;
    7917             :     int         strategy_op;
    7918             :     Oid         lefttype,
    7919             :                 righttype;
    7920        2456 :     int32       nentries = 0;
    7921        2456 :     bool       *partial_matches = NULL;
    7922        2456 :     Pointer    *extra_data = NULL;
    7923        2456 :     bool       *nullFlags = NULL;
    7924        2456 :     int32       searchMode = GIN_SEARCH_MODE_DEFAULT;
    7925             :     int32       i;
    7926             : 
    7927             :     Assert(indexcol < index->nkeycolumns);
    7928             : 
    7929             :     /*
    7930             :      * Get the operator's strategy number and declared input data types within
    7931             :      * the index opfamily.  (We don't need the latter, but we use
    7932             :      * get_op_opfamily_properties because it will throw error if it fails to
    7933             :      * find a matching pg_amop entry.)
    7934             :      */
    7935        2456 :     get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
    7936             :                                &strategy_op, &lefttype, &righttype);
    7937             : 
    7938             :     /*
    7939             :      * GIN always uses the "default" support functions, which are those with
    7940             :      * lefttype == righttype == the opclass' opcintype (see
    7941             :      * IndexSupportInitialize in relcache.c).
    7942             :      */
    7943        2456 :     extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
    7944        2456 :                                        index->opcintype[indexcol],
    7945        2456 :                                        index->opcintype[indexcol],
    7946             :                                        GIN_EXTRACTQUERY_PROC);
    7947             : 
    7948        2456 :     if (!OidIsValid(extractProcOid))
    7949             :     {
    7950             :         /* should not happen; throw same error as index_getprocinfo */
    7951           0 :         elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
    7952             :              GIN_EXTRACTQUERY_PROC, indexcol + 1,
    7953             :              get_rel_name(index->indexoid));
    7954             :     }
    7955             : 
    7956             :     /*
    7957             :      * Choose collation to pass to extractProc (should match initGinState).
    7958             :      */
    7959        2456 :     if (OidIsValid(index->indexcollations[indexcol]))
    7960         390 :         collation = index->indexcollations[indexcol];
    7961             :     else
    7962        2066 :         collation = DEFAULT_COLLATION_OID;
    7963             : 
    7964        2456 :     fmgr_info(extractProcOid, &flinfo);
    7965             : 
    7966        2456 :     set_fn_opclass_options(&flinfo, index->opclassoptions[indexcol]);
    7967             : 
    7968        2456 :     FunctionCall7Coll(&flinfo,
    7969             :                       collation,
    7970             :                       query,
    7971             :                       PointerGetDatum(&nentries),
    7972             :                       UInt16GetDatum(strategy_op),
    7973             :                       PointerGetDatum(&partial_matches),
    7974             :                       PointerGetDatum(&extra_data),
    7975             :                       PointerGetDatum(&nullFlags),
    7976             :                       PointerGetDatum(&searchMode));
    7977             : 
    7978        2456 :     if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
    7979             :     {
    7980             :         /* No match is possible */
    7981          12 :         return false;
    7982             :     }
    7983             : 
    7984        9568 :     for (i = 0; i < nentries; i++)
    7985             :     {
    7986             :         /*
    7987             :          * For partial match we haven't any information to estimate number of
    7988             :          * matched entries in index, so, we just estimate it as 100
    7989             :          */
    7990        7124 :         if (partial_matches && partial_matches[i])
    7991         694 :             counts->partialEntries += 100;
    7992             :         else
    7993        6430 :             counts->exactEntries++;
    7994             : 
    7995        7124 :         counts->searchEntries++;
    7996             :     }
    7997             : 
    7998        2444 :     if (searchMode == GIN_SEARCH_MODE_DEFAULT)
    7999             :     {
    8000        1972 :         counts->attHasNormalScan[indexcol] = true;
    8001             :     }
    8002         472 :     else if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
    8003             :     {
    8004             :         /* Treat "include empty" like an exact-match item */
    8005          44 :         counts->attHasNormalScan[indexcol] = true;
    8006          44 :         counts->exactEntries++;
    8007          44 :         counts->searchEntries++;
    8008             :     }
    8009             :     else
    8010             :     {
    8011             :         /* It's GIN_SEARCH_MODE_ALL */
    8012         428 :         counts->attHasFullScan[indexcol] = true;
    8013             :     }
    8014             : 
    8015        2444 :     return true;
    8016             : }
    8017             : 
    8018             : /*
    8019             :  * Estimate the number of index terms that need to be searched for while
    8020             :  * testing the given GIN index clause, and increment the counts in *counts
    8021             :  * appropriately.  If the query is unsatisfiable, return false.
    8022             :  */
    8023             : static bool
    8024        2444 : gincost_opexpr(PlannerInfo *root,
    8025             :                IndexOptInfo *index,
    8026             :                int indexcol,
    8027             :                OpExpr *clause,
    8028             :                GinQualCounts *counts)
    8029             : {
    8030        2444 :     Oid         clause_op = clause->opno;
    8031        2444 :     Node       *operand = (Node *) lsecond(clause->args);
    8032             : 
    8033             :     /* aggressively reduce to a constant, and look through relabeling */
    8034        2444 :     operand = estimate_expression_value(root, operand);
    8035             : 
    8036        2444 :     if (IsA(operand, RelabelType))
    8037           0 :         operand = (Node *) ((RelabelType *) operand)->arg;
    8038             : 
    8039             :     /*
    8040             :      * It's impossible to call extractQuery method for unknown operand. So
    8041             :      * unless operand is a Const we can't do much; just assume there will be
    8042             :      * one ordinary search entry from the operand at runtime.
    8043             :      */
    8044        2444 :     if (!IsA(operand, Const))
    8045             :     {
    8046           0 :         counts->exactEntries++;
    8047           0 :         counts->searchEntries++;
    8048           0 :         return true;
    8049             :     }
    8050             : 
    8051             :     /* If Const is null, there can be no matches */
    8052        2444 :     if (((Const *) operand)->constisnull)
    8053           0 :         return false;
    8054             : 
    8055             :     /* Otherwise, apply extractQuery and get the actual term counts */
    8056        2444 :     return gincost_pattern(index, indexcol, clause_op,
    8057             :                            ((Const *) operand)->constvalue,
    8058             :                            counts);
    8059             : }
    8060             : 
    8061             : /*
    8062             :  * Estimate the number of index terms that need to be searched for while
    8063             :  * testing the given GIN index clause, and increment the counts in *counts
    8064             :  * appropriately.  If the query is unsatisfiable, return false.
    8065             :  *
    8066             :  * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
    8067             :  * each of which involves one value from the RHS array, plus all the
    8068             :  * non-array quals (if any).  To model this, we average the counts across
    8069             :  * the RHS elements, and add the averages to the counts in *counts (which
    8070             :  * correspond to per-indexscan costs).  We also multiply counts->arrayScans
    8071             :  * by N, causing gincostestimate to scale up its estimates accordingly.
    8072             :  */
    8073             : static bool
    8074           6 : gincost_scalararrayopexpr(PlannerInfo *root,
    8075             :                           IndexOptInfo *index,
    8076             :                           int indexcol,
    8077             :                           ScalarArrayOpExpr *clause,
    8078             :                           double numIndexEntries,
    8079             :                           GinQualCounts *counts)
    8080             : {
    8081           6 :     Oid         clause_op = clause->opno;
    8082           6 :     Node       *rightop = (Node *) lsecond(clause->args);
    8083             :     ArrayType  *arrayval;
    8084             :     int16       elmlen;
    8085             :     bool        elmbyval;
    8086             :     char        elmalign;
    8087             :     int         numElems;
    8088             :     Datum      *elemValues;
    8089             :     bool       *elemNulls;
    8090             :     GinQualCounts arraycounts;
    8091           6 :     int         numPossible = 0;
    8092             :     int         i;
    8093             : 
    8094             :     Assert(clause->useOr);
    8095             : 
    8096             :     /* aggressively reduce to a constant, and look through relabeling */
    8097           6 :     rightop = estimate_expression_value(root, rightop);
    8098             : 
    8099           6 :     if (IsA(rightop, RelabelType))
    8100           0 :         rightop = (Node *) ((RelabelType *) rightop)->arg;
    8101             : 
    8102             :     /*
    8103             :      * It's impossible to call extractQuery method for unknown operand. So
    8104             :      * unless operand is a Const we can't do much; just assume there will be
    8105             :      * one ordinary search entry from each array entry at runtime, and fall
    8106             :      * back on a probably-bad estimate of the number of array entries.
    8107             :      */
    8108           6 :     if (!IsA(rightop, Const))
    8109             :     {
    8110           0 :         counts->exactEntries++;
    8111           0 :         counts->searchEntries++;
    8112           0 :         counts->arrayScans *= estimate_array_length(root, rightop);
    8113           0 :         return true;
    8114             :     }
    8115             : 
    8116             :     /* If Const is null, there can be no matches */
    8117           6 :     if (((Const *) rightop)->constisnull)
    8118           0 :         return false;
    8119             : 
    8120             :     /* Otherwise, extract the array elements and iterate over them */
    8121           6 :     arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
    8122           6 :     get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
    8123             :                          &elmlen, &elmbyval, &elmalign);
    8124           6 :     deconstruct_array(arrayval,
    8125             :                       ARR_ELEMTYPE(arrayval),
    8126             :                       elmlen, elmbyval, elmalign,
    8127             :                       &elemValues, &elemNulls, &numElems);
    8128             : 
    8129           6 :     memset(&arraycounts, 0, sizeof(arraycounts));
    8130             : 
    8131          18 :     for (i = 0; i < numElems; i++)
    8132             :     {
    8133             :         GinQualCounts elemcounts;
    8134             : 
    8135             :         /* NULL can't match anything, so ignore, as the executor will */
    8136          12 :         if (elemNulls[i])
    8137           0 :             continue;
    8138             : 
    8139             :         /* Otherwise, apply extractQuery and get the actual term counts */
    8140          12 :         memset(&elemcounts, 0, sizeof(elemcounts));
    8141             : 
    8142          12 :         if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
    8143             :                             &elemcounts))
    8144             :         {
    8145             :             /* We ignore array elements that are unsatisfiable patterns */
    8146          12 :             numPossible++;
    8147             : 
    8148          12 :             if (elemcounts.attHasFullScan[indexcol] &&
    8149           0 :                 !elemcounts.attHasNormalScan[indexcol])
    8150             :             {
    8151             :                 /*
    8152             :                  * Full index scan will be required.  We treat this as if
    8153             :                  * every key in the index had been listed in the query; is
    8154             :                  * that reasonable?
    8155             :                  */
    8156           0 :                 elemcounts.partialEntries = 0;
    8157           0 :                 elemcounts.exactEntries = numIndexEntries;
    8158           0 :                 elemcounts.searchEntries = numIndexEntries;
    8159             :             }
    8160          12 :             arraycounts.partialEntries += elemcounts.partialEntries;
    8161          12 :             arraycounts.exactEntries += elemcounts.exactEntries;
    8162          12 :             arraycounts.searchEntries += elemcounts.searchEntries;
    8163             :         }
    8164             :     }
    8165             : 
    8166           6 :     if (numPossible == 0)
    8167             :     {
    8168             :         /* No satisfiable patterns in the array */
    8169           0 :         return false;
    8170             :     }
    8171             : 
    8172             :     /*
    8173             :      * Now add the averages to the global counts.  This will give us an
    8174             :      * estimate of the average number of terms searched for in each indexscan,
    8175             :      * including contributions from both array and non-array quals.
    8176             :      */
    8177           6 :     counts->partialEntries += arraycounts.partialEntries / numPossible;
    8178           6 :     counts->exactEntries += arraycounts.exactEntries / numPossible;
    8179           6 :     counts->searchEntries += arraycounts.searchEntries / numPossible;
    8180             : 
    8181           6 :     counts->arrayScans *= numPossible;
    8182             : 
    8183           6 :     return true;
    8184             : }
    8185             : 
    8186             : /*
    8187             :  * GIN has search behavior completely different from other index types
    8188             :  */
    8189             : void
    8190        2252 : gincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8191             :                 Cost *indexStartupCost, Cost *indexTotalCost,
    8192             :                 Selectivity *indexSelectivity, double *indexCorrelation,
    8193             :                 double *indexPages)
    8194             : {
    8195        2252 :     IndexOptInfo *index = path->indexinfo;
    8196        2252 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    8197             :     List       *selectivityQuals;
    8198        2252 :     double      numPages = index->pages,
    8199        2252 :                 numTuples = index->tuples;
    8200             :     double      numEntryPages,
    8201             :                 numDataPages,
    8202             :                 numPendingPages,
    8203             :                 numEntries;
    8204             :     GinQualCounts counts;
    8205             :     bool        matchPossible;
    8206             :     bool        fullIndexScan;
    8207             :     double      partialScale;
    8208             :     double      entryPagesFetched,
    8209             :                 dataPagesFetched,
    8210             :                 dataPagesFetchedBySel;
    8211             :     double      qual_op_cost,
    8212             :                 qual_arg_cost,
    8213             :                 spc_random_page_cost,
    8214             :                 outer_scans;
    8215             :     Cost        descentCost;
    8216             :     Relation    indexRel;
    8217             :     GinStatsData ginStats;
    8218             :     ListCell   *lc;
    8219             :     int         i;
    8220             : 
    8221             :     /*
    8222             :      * Obtain statistical information from the meta page, if possible.  Else
    8223             :      * set ginStats to zeroes, and we'll cope below.
    8224             :      */
    8225        2252 :     if (!index->hypothetical)
    8226             :     {
    8227             :         /* Lock should have already been obtained in plancat.c */
    8228        2252 :         indexRel = index_open(index->indexoid, NoLock);
    8229        2252 :         ginGetStats(indexRel, &ginStats);
    8230        2252 :         index_close(indexRel, NoLock);
    8231             :     }
    8232             :     else
    8233             :     {
    8234           0 :         memset(&ginStats, 0, sizeof(ginStats));
    8235             :     }
    8236             : 
    8237             :     /*
    8238             :      * Assuming we got valid (nonzero) stats at all, nPendingPages can be
    8239             :      * trusted, but the other fields are data as of the last VACUUM.  We can
    8240             :      * scale them up to account for growth since then, but that method only
    8241             :      * goes so far; in the worst case, the stats might be for a completely
    8242             :      * empty index, and scaling them will produce pretty bogus numbers.
    8243             :      * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
    8244             :      * it's grown more than that, fall back to estimating things only from the
    8245             :      * assumed-accurate index size.  But we'll trust nPendingPages in any case
    8246             :      * so long as it's not clearly insane, ie, more than the index size.
    8247             :      */
    8248        2252 :     if (ginStats.nPendingPages < numPages)
    8249        2252 :         numPendingPages = ginStats.nPendingPages;
    8250             :     else
    8251           0 :         numPendingPages = 0;
    8252             : 
    8253        2252 :     if (numPages > 0 && ginStats.nTotalPages <= numPages &&
    8254        2252 :         ginStats.nTotalPages > numPages / 4 &&
    8255        2200 :         ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
    8256        1942 :     {
    8257             :         /*
    8258             :          * OK, the stats seem close enough to sane to be trusted.  But we
    8259             :          * still need to scale them by the ratio numPages / nTotalPages to
    8260             :          * account for growth since the last VACUUM.
    8261             :          */
    8262        1942 :         double      scale = numPages / ginStats.nTotalPages;
    8263             : 
    8264        1942 :         numEntryPages = ceil(ginStats.nEntryPages * scale);
    8265        1942 :         numDataPages = ceil(ginStats.nDataPages * scale);
    8266        1942 :         numEntries = ceil(ginStats.nEntries * scale);
    8267             :         /* ensure we didn't round up too much */
    8268        1942 :         numEntryPages = Min(numEntryPages, numPages - numPendingPages);
    8269        1942 :         numDataPages = Min(numDataPages,
    8270             :                            numPages - numPendingPages - numEntryPages);
    8271             :     }
    8272             :     else
    8273             :     {
    8274             :         /*
    8275             :          * We might get here because it's a hypothetical index, or an index
    8276             :          * created pre-9.1 and never vacuumed since upgrading (in which case
    8277             :          * its stats would read as zeroes), or just because it's grown too
    8278             :          * much since the last VACUUM for us to put our faith in scaling.
    8279             :          *
    8280             :          * Invent some plausible internal statistics based on the index page
    8281             :          * count (and clamp that to at least 10 pages, just in case).  We
    8282             :          * estimate that 90% of the index is entry pages, and the rest is data
    8283             :          * pages.  Estimate 100 entries per entry page; this is rather bogus
    8284             :          * since it'll depend on the size of the keys, but it's more robust
    8285             :          * than trying to predict the number of entries per heap tuple.
    8286             :          */
    8287         310 :         numPages = Max(numPages, 10);
    8288         310 :         numEntryPages = floor((numPages - numPendingPages) * 0.90);
    8289         310 :         numDataPages = numPages - numPendingPages - numEntryPages;
    8290         310 :         numEntries = floor(numEntryPages * 100);
    8291             :     }
    8292             : 
    8293             :     /* In an empty index, numEntries could be zero.  Avoid divide-by-zero */
    8294        2252 :     if (numEntries < 1)
    8295           0 :         numEntries = 1;
    8296             : 
    8297             :     /*
    8298             :      * If the index is partial, AND the index predicate with the index-bound
    8299             :      * quals to produce a more accurate idea of the number of rows covered by
    8300             :      * the bound conditions.
    8301             :      */
    8302        2252 :     selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
    8303             : 
    8304             :     /* Estimate the fraction of main-table tuples that will be visited */
    8305        4504 :     *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
    8306        2252 :                                                index->rel->relid,
    8307             :                                                JOIN_INNER,
    8308             :                                                NULL);
    8309             : 
    8310             :     /* fetch estimated page cost for tablespace containing index */
    8311        2252 :     get_tablespace_page_costs(index->reltablespace,
    8312             :                               &spc_random_page_cost,
    8313             :                               NULL);
    8314             : 
    8315             :     /*
    8316             :      * Generic assumption about index correlation: there isn't any.
    8317             :      */
    8318        2252 :     *indexCorrelation = 0.0;
    8319             : 
    8320             :     /*
    8321             :      * Examine quals to estimate number of search entries & partial matches
    8322             :      */
    8323        2252 :     memset(&counts, 0, sizeof(counts));
    8324        2252 :     counts.arrayScans = 1;
    8325        2252 :     matchPossible = true;
    8326             : 
    8327        4702 :     foreach(lc, path->indexclauses)
    8328             :     {
    8329        2450 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    8330             :         ListCell   *lc2;
    8331             : 
    8332        4888 :         foreach(lc2, iclause->indexquals)
    8333             :         {
    8334        2450 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    8335        2450 :             Expr       *clause = rinfo->clause;
    8336             : 
    8337        2450 :             if (IsA(clause, OpExpr))
    8338             :             {
    8339        2444 :                 matchPossible = gincost_opexpr(root,
    8340             :                                                index,
    8341        2444 :                                                iclause->indexcol,
    8342             :                                                (OpExpr *) clause,
    8343             :                                                &counts);
    8344        2444 :                 if (!matchPossible)
    8345          12 :                     break;
    8346             :             }
    8347           6 :             else if (IsA(clause, ScalarArrayOpExpr))
    8348             :             {
    8349           6 :                 matchPossible = gincost_scalararrayopexpr(root,
    8350             :                                                           index,
    8351           6 :                                                           iclause->indexcol,
    8352             :                                                           (ScalarArrayOpExpr *) clause,
    8353             :                                                           numEntries,
    8354             :                                                           &counts);
    8355           6 :                 if (!matchPossible)
    8356           0 :                     break;
    8357             :             }
    8358             :             else
    8359             :             {
    8360             :                 /* shouldn't be anything else for a GIN index */
    8361           0 :                 elog(ERROR, "unsupported GIN indexqual type: %d",
    8362             :                      (int) nodeTag(clause));
    8363             :             }
    8364             :         }
    8365             :     }
    8366             : 
    8367             :     /* Fall out if there were any provably-unsatisfiable quals */
    8368        2252 :     if (!matchPossible)
    8369             :     {
    8370          12 :         *indexStartupCost = 0;
    8371          12 :         *indexTotalCost = 0;
    8372          12 :         *indexSelectivity = 0;
    8373          12 :         return;
    8374             :     }
    8375             : 
    8376             :     /*
    8377             :      * If attribute has a full scan and at the same time doesn't have normal
    8378             :      * scan, then we'll have to scan all non-null entries of that attribute.
    8379             :      * Currently, we don't have per-attribute statistics for GIN.  Thus, we
    8380             :      * must assume the whole GIN index has to be scanned in this case.
    8381             :      */
    8382        2240 :     fullIndexScan = false;
    8383        4370 :     for (i = 0; i < index->nkeycolumns; i++)
    8384             :     {
    8385        2468 :         if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
    8386             :         {
    8387         338 :             fullIndexScan = true;
    8388         338 :             break;
    8389             :         }
    8390             :     }
    8391             : 
    8392        2240 :     if (fullIndexScan || indexQuals == NIL)
    8393             :     {
    8394             :         /*
    8395             :          * Full index scan will be required.  We treat this as if every key in
    8396             :          * the index had been listed in the query; is that reasonable?
    8397             :          */
    8398         338 :         counts.partialEntries = 0;
    8399         338 :         counts.exactEntries = numEntries;
    8400         338 :         counts.searchEntries = numEntries;
    8401             :     }
    8402             : 
    8403             :     /* Will we have more than one iteration of a nestloop scan? */
    8404        2240 :     outer_scans = loop_count;
    8405             : 
    8406             :     /*
    8407             :      * Compute cost to begin scan, first of all, pay attention to pending
    8408             :      * list.
    8409             :      */
    8410        2240 :     entryPagesFetched = numPendingPages;
    8411             : 
    8412             :     /*
    8413             :      * Estimate number of entry pages read.  We need to do
    8414             :      * counts.searchEntries searches.  Use a power function as it should be,
    8415             :      * but tuples on leaf pages usually is much greater. Here we include all
    8416             :      * searches in entry tree, including search of first entry in partial
    8417             :      * match algorithm
    8418             :      */
    8419        2240 :     entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
    8420             : 
    8421             :     /*
    8422             :      * Add an estimate of entry pages read by partial match algorithm. It's a
    8423             :      * scan over leaf pages in entry tree.  We haven't any useful stats here,
    8424             :      * so estimate it as proportion.  Because counts.partialEntries is really
    8425             :      * pretty bogus (see code above), it's possible that it is more than
    8426             :      * numEntries; clamp the proportion to ensure sanity.
    8427             :      */
    8428        2240 :     partialScale = counts.partialEntries / numEntries;
    8429        2240 :     partialScale = Min(partialScale, 1.0);
    8430             : 
    8431        2240 :     entryPagesFetched += ceil(numEntryPages * partialScale);
    8432             : 
    8433             :     /*
    8434             :      * Partial match algorithm reads all data pages before doing actual scan,
    8435             :      * so it's a startup cost.  Again, we haven't any useful stats here, so
    8436             :      * estimate it as proportion.
    8437             :      */
    8438        2240 :     dataPagesFetched = ceil(numDataPages * partialScale);
    8439             : 
    8440        2240 :     *indexStartupCost = 0;
    8441        2240 :     *indexTotalCost = 0;
    8442             : 
    8443             :     /*
    8444             :      * Add a CPU-cost component to represent the costs of initial entry btree
    8445             :      * descent.  We don't charge any I/O cost for touching upper btree levels,
    8446             :      * since they tend to stay in cache, but we still have to do about log2(N)
    8447             :      * comparisons to descend a btree of N leaf tuples.  We charge one
    8448             :      * cpu_operator_cost per comparison.
    8449             :      *
    8450             :      * If there are ScalarArrayOpExprs, charge this once per SA scan.  The
    8451             :      * ones after the first one are not startup cost so far as the overall
    8452             :      * plan is concerned, so add them only to "total" cost.
    8453             :      */
    8454        2240 :     if (numEntries > 1)          /* avoid computing log(0) */
    8455             :     {
    8456        2240 :         descentCost = ceil(log(numEntries) / log(2.0)) * cpu_operator_cost;
    8457        2240 :         *indexStartupCost += descentCost * counts.searchEntries;
    8458        2240 :         *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
    8459             :     }
    8460             : 
    8461             :     /*
    8462             :      * Add a cpu cost per entry-page fetched. This is not amortized over a
    8463             :      * loop.
    8464             :      */
    8465        2240 :     *indexStartupCost += entryPagesFetched * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8466        2240 :     *indexTotalCost += entryPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8467             : 
    8468             :     /*
    8469             :      * Add a cpu cost per data-page fetched. This is also not amortized over a
    8470             :      * loop. Since those are the data pages from the partial match algorithm,
    8471             :      * charge them as startup cost.
    8472             :      */
    8473        2240 :     *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * dataPagesFetched;
    8474             : 
    8475             :     /*
    8476             :      * Since we add the startup cost to the total cost later on, remove the
    8477             :      * initial arrayscan from the total.
    8478             :      */
    8479        2240 :     *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8480             : 
    8481             :     /*
    8482             :      * Calculate cache effects if more than one scan due to nestloops or array
    8483             :      * quals.  The result is pro-rated per nestloop scan, but the array qual
    8484             :      * factor shouldn't be pro-rated (compare genericcostestimate).
    8485             :      */
    8486        2240 :     if (outer_scans > 1 || counts.arrayScans > 1)
    8487             :     {
    8488           6 :         entryPagesFetched *= outer_scans * counts.arrayScans;
    8489           6 :         entryPagesFetched = index_pages_fetched(entryPagesFetched,
    8490             :                                                 (BlockNumber) numEntryPages,
    8491             :                                                 numEntryPages, root);
    8492           6 :         entryPagesFetched /= outer_scans;
    8493           6 :         dataPagesFetched *= outer_scans * counts.arrayScans;
    8494           6 :         dataPagesFetched = index_pages_fetched(dataPagesFetched,
    8495             :                                                (BlockNumber) numDataPages,
    8496             :                                                numDataPages, root);
    8497           6 :         dataPagesFetched /= outer_scans;
    8498             :     }
    8499             : 
    8500             :     /*
    8501             :      * Here we use random page cost because logically-close pages could be far
    8502             :      * apart on disk.
    8503             :      */
    8504        2240 :     *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
    8505             : 
    8506             :     /*
    8507             :      * Now compute the number of data pages fetched during the scan.
    8508             :      *
    8509             :      * We assume every entry to have the same number of items, and that there
    8510             :      * is no overlap between them. (XXX: tsvector and array opclasses collect
    8511             :      * statistics on the frequency of individual keys; it would be nice to use
    8512             :      * those here.)
    8513             :      */
    8514        2240 :     dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
    8515             : 
    8516             :     /*
    8517             :      * If there is a lot of overlap among the entries, in particular if one of
    8518             :      * the entries is very frequent, the above calculation can grossly
    8519             :      * under-estimate.  As a simple cross-check, calculate a lower bound based
    8520             :      * on the overall selectivity of the quals.  At a minimum, we must read
    8521             :      * one item pointer for each matching entry.
    8522             :      *
    8523             :      * The width of each item pointer varies, based on the level of
    8524             :      * compression.  We don't have statistics on that, but an average of
    8525             :      * around 3 bytes per item is fairly typical.
    8526             :      */
    8527        2240 :     dataPagesFetchedBySel = ceil(*indexSelectivity *
    8528        2240 :                                  (numTuples / (BLCKSZ / 3)));
    8529        2240 :     if (dataPagesFetchedBySel > dataPagesFetched)
    8530        1860 :         dataPagesFetched = dataPagesFetchedBySel;
    8531             : 
    8532             :     /* Add one page cpu-cost to the startup cost */
    8533        2240 :     *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
    8534             : 
    8535             :     /*
    8536             :      * Add once again a CPU-cost for those data pages, before amortizing for
    8537             :      * cache.
    8538             :      */
    8539        2240 :     *indexTotalCost += dataPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
    8540             : 
    8541             :     /* Account for cache effects, the same as above */
    8542        2240 :     if (outer_scans > 1 || counts.arrayScans > 1)
    8543             :     {
    8544           6 :         dataPagesFetched *= outer_scans * counts.arrayScans;
    8545           6 :         dataPagesFetched = index_pages_fetched(dataPagesFetched,
    8546             :                                                (BlockNumber) numDataPages,
    8547             :                                                numDataPages, root);
    8548           6 :         dataPagesFetched /= outer_scans;
    8549             :     }
    8550             : 
    8551             :     /* And apply random_page_cost as the cost per page */
    8552        2240 :     *indexTotalCost += *indexStartupCost +
    8553        2240 :         dataPagesFetched * spc_random_page_cost;
    8554             : 
    8555             :     /*
    8556             :      * Add on index qual eval costs, much as in genericcostestimate. We charge
    8557             :      * cpu but we can disregard indexorderbys, since GIN doesn't support
    8558             :      * those.
    8559             :      */
    8560        2240 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
    8561        2240 :     qual_op_cost = cpu_operator_cost * list_length(indexQuals);
    8562             : 
    8563        2240 :     *indexStartupCost += qual_arg_cost;
    8564        2240 :     *indexTotalCost += qual_arg_cost;
    8565             : 
    8566             :     /*
    8567             :      * Add a cpu cost per search entry, corresponding to the actual visited
    8568             :      * entries.
    8569             :      */
    8570        2240 :     *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
    8571             :     /* Now add a cpu cost per tuple in the posting lists / trees */
    8572        2240 :     *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
    8573        2240 :     *indexPages = dataPagesFetched;
    8574             : }
    8575             : 
    8576             : /*
    8577             :  * BRIN has search behavior completely different from other index types
    8578             :  */
    8579             : void
    8580       10730 : brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
    8581             :                  Cost *indexStartupCost, Cost *indexTotalCost,
    8582             :                  Selectivity *indexSelectivity, double *indexCorrelation,
    8583             :                  double *indexPages)
    8584             : {
    8585       10730 :     IndexOptInfo *index = path->indexinfo;
    8586       10730 :     List       *indexQuals = get_quals_from_indexclauses(path->indexclauses);
    8587       10730 :     double      numPages = index->pages;
    8588       10730 :     RelOptInfo *baserel = index->rel;
    8589       10730 :     RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
    8590             :     Cost        spc_seq_page_cost;
    8591             :     Cost        spc_random_page_cost;
    8592             :     double      qual_arg_cost;
    8593             :     double      qualSelectivity;
    8594             :     BrinStatsData statsData;
    8595             :     double      indexRanges;
    8596             :     double      minimalRanges;
    8597             :     double      estimatedRanges;
    8598             :     double      selec;
    8599             :     Relation    indexRel;
    8600             :     ListCell   *l;
    8601             :     VariableStatData vardata;
    8602             : 
    8603             :     Assert(rte->rtekind == RTE_RELATION);
    8604             : 
    8605             :     /* fetch estimated page cost for the tablespace containing the index */
    8606       10730 :     get_tablespace_page_costs(index->reltablespace,
    8607             :                               &spc_random_page_cost,
    8608             :                               &spc_seq_page_cost);
    8609             : 
    8610             :     /*
    8611             :      * Obtain some data from the index itself, if possible.  Otherwise invent
    8612             :      * some plausible internal statistics based on the relation page count.
    8613             :      */
    8614       10730 :     if (!index->hypothetical)
    8615             :     {
    8616             :         /*
    8617             :          * A lock should have already been obtained on the index in plancat.c.
    8618             :          */
    8619       10730 :         indexRel = index_open(index->indexoid, NoLock);
    8620       10730 :         brinGetStats(indexRel, &statsData);
    8621       10730 :         index_close(indexRel, NoLock);
    8622             : 
    8623             :         /* work out the actual number of ranges in the index */
    8624       10730 :         indexRanges = Max(ceil((double) baserel->pages /
    8625             :                                statsData.pagesPerRange), 1.0);
    8626             :     }
    8627             :     else
    8628             :     {
    8629             :         /*
    8630             :          * Assume default number of pages per range, and estimate the number
    8631             :          * of ranges based on that.
    8632             :          */
    8633           0 :         indexRanges = Max(ceil((double) baserel->pages /
    8634             :                                BRIN_DEFAULT_PAGES_PER_RANGE), 1.0);
    8635             : 
    8636           0 :         statsData.pagesPerRange = BRIN_DEFAULT_PAGES_PER_RANGE;
    8637           0 :         statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
    8638             :     }
    8639             : 
    8640             :     /*
    8641             :      * Compute index correlation
    8642             :      *
    8643             :      * Because we can use all index quals equally when scanning, we can use
    8644             :      * the largest correlation (in absolute value) among columns used by the
    8645             :      * query.  Start at zero, the worst possible case.  If we cannot find any
    8646             :      * correlation statistics, we will keep it as 0.
    8647             :      */
    8648       10730 :     *indexCorrelation = 0;
    8649             : 
    8650       21462 :     foreach(l, path->indexclauses)
    8651             :     {
    8652       10732 :         IndexClause *iclause = lfirst_node(IndexClause, l);
    8653       10732 :         AttrNumber  attnum = index->indexkeys[iclause->indexcol];
    8654             : 
    8655             :         /* attempt to lookup stats in relation for this index column */
    8656       10732 :         if (attnum != 0)
    8657             :         {
    8658             :             /* Simple variable -- look to stats for the underlying table */
    8659       10732 :             if (get_relation_stats_hook &&
    8660           0 :                 (*get_relation_stats_hook) (root, rte, attnum, &vardata))
    8661             :             {
    8662             :                 /*
    8663             :                  * The hook took control of acquiring a stats tuple.  If it
    8664             :                  * did supply a tuple, it'd better have supplied a freefunc.
    8665             :                  */
    8666           0 :                 if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
    8667           0 :                     elog(ERROR,
    8668             :                          "no function provided to release variable stats with");
    8669             :             }
    8670             :             else
    8671             :             {
    8672       10732 :                 vardata.statsTuple =
    8673       10732 :                     SearchSysCache3(STATRELATTINH,
    8674             :                                     ObjectIdGetDatum(rte->relid),
    8675             :                                     Int16GetDatum(attnum),
    8676             :                                     BoolGetDatum(false));
    8677       10732 :                 vardata.freefunc = ReleaseSysCache;
    8678             :             }
    8679             :         }
    8680             :         else
    8681             :         {
    8682             :             /*
    8683             :              * Looks like we've found an expression column in the index. Let's
    8684             :              * see if there's any stats for it.
    8685             :              */
    8686             : 
    8687             :             /* get the attnum from the 0-based index. */
    8688           0 :             attnum = iclause->indexcol + 1;
    8689             : 
    8690           0 :             if (get_index_stats_hook &&
    8691           0 :                 (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
    8692             :             {
    8693             :                 /*
    8694             :                  * The hook took control of acquiring a stats tuple.  If it
    8695             :                  * did supply a tuple, it'd better have supplied a freefunc.
    8696             :                  */
    8697           0 :                 if (HeapTupleIsValid(vardata.statsTuple) &&
    8698           0 :                     !vardata.freefunc)
    8699           0 :                     elog(ERROR, "no function provided to release variable stats with");
    8700             :             }
    8701             :             else
    8702             :             {
    8703           0 :                 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
    8704             :                                                      ObjectIdGetDatum(index->indexoid),
    8705             :                                                      Int16GetDatum(attnum),
    8706             :                                                      BoolGetDatum(false));
    8707           0 :                 vardata.freefunc = ReleaseSysCache;
    8708             :             }
    8709             :         }
    8710             : 
    8711       10732 :         if (HeapTupleIsValid(vardata.statsTuple))
    8712             :         {
    8713             :             AttStatsSlot sslot;
    8714             : 
    8715          36 :             if (get_attstatsslot(&sslot, vardata.statsTuple,
    8716             :                                  STATISTIC_KIND_CORRELATION, InvalidOid,
    8717             :                                  ATTSTATSSLOT_NUMBERS))
    8718             :             {
    8719          36 :                 double      varCorrelation = 0.0;
    8720             : 
    8721          36 :                 if (sslot.nnumbers > 0)
    8722          36 :                     varCorrelation = fabs(sslot.numbers[0]);
    8723             : 
    8724          36 :                 if (varCorrelation > *indexCorrelation)
    8725          36 :                     *indexCorrelation = varCorrelation;
    8726             : 
    8727          36 :                 free_attstatsslot(&sslot);
    8728             :             }
    8729             :         }
    8730             : 
    8731       10732 :         ReleaseVariableStats(vardata);
    8732             :     }
    8733             : 
    8734       10730 :     qualSelectivity = clauselist_selectivity(root, indexQuals,
    8735       10730 :                                              baserel->relid,
    8736             :                                              JOIN_INNER, NULL);
    8737             : 
    8738             :     /*
    8739             :      * Now calculate the minimum possible ranges we could match with if all of
    8740             :      * the rows were in the perfect order in the table's heap.
    8741             :      */
    8742       10730 :     minimalRanges = ceil(indexRanges * qualSelectivity);
    8743             : 
    8744             :     /*
    8745             :      * Now estimate the number of ranges that we'll touch by using the
    8746             :      * indexCorrelation from the stats. Careful not to divide by zero (note
    8747             :      * we're using the absolute value of the correlation).
    8748             :      */
    8749       10730 :     if (*indexCorrelation < 1.0e-10)
    8750       10694 :         estimatedRanges = indexRanges;
    8751             :     else
    8752          36 :         estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
    8753             : 
    8754             :     /* we expect to visit this portion of the table */
    8755       10730 :     selec = estimatedRanges / indexRanges;
    8756             : 
    8757       10730 :     CLAMP_PROBABILITY(selec);
    8758             : 
    8759       10730 :     *indexSelectivity = selec;
    8760             : 
    8761             :     /*
    8762             :      * Compute the index qual costs, much as in genericcostestimate, to add to
    8763             :      * the index costs.  We can disregard indexorderbys, since BRIN doesn't
    8764             :      * support those.
    8765             :      */
    8766       10730 :     qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
    8767             : 
    8768             :     /*
    8769             :      * Compute the startup cost as the cost to read the whole revmap
    8770             :      * sequentially, including the cost to execute the index quals.
    8771             :      */
    8772       10730 :     *indexStartupCost =
    8773       10730 :         spc_seq_page_cost * statsData.revmapNumPages * loop_count;
    8774       10730 :     *indexStartupCost += qual_arg_cost;
    8775             : 
    8776             :     /*
    8777             :      * To read a BRIN index there might be a bit of back and forth over
    8778             :      * regular pages, as revmap might point to them out of sequential order;
    8779             :      * calculate the total cost as reading the whole index in random order.
    8780             :      */
    8781       10730 :     *indexTotalCost = *indexStartupCost +
    8782       10730 :         spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
    8783             : 
    8784             :     /*
    8785             :      * Charge a small amount per range tuple which we expect to match to. This
    8786             :      * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
    8787             :      * will set a bit for each page in the range when we find a matching
    8788             :      * range, so we must multiply the charge by the number of pages in the
    8789             :      * range.
    8790             :      */
    8791       10730 :     *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
    8792       10730 :         statsData.pagesPerRange;
    8793             : 
    8794       10730 :     *indexPages = index->pages;
    8795       10730 : }

Generated by: LCOV version 1.16