LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18beta1 Lines: 2187 2505 87.3 %
Date: 2025-05-09 02:15:25 Functions: 71 74 95.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14