LCOV - code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 2239 2564 87.3 %
Date: 2025-11-21 08:18:19 Functions: 75 78 96.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16