LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - selfuncs.c (source / functions) Coverage Total Hit LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 86.8 % 2360 2049 51 188 72 55 1370 43 581 179 1399 5 18
Current Date: 2023-04-08 15:15:32 Functions: 95.8 % 71 68 3 66 2 3 68
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a