PostgreSQL Source Code  git master
selfuncs.c
Go to the documentation of this file.
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-2019, 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. Thus, in most cases where we are looking at statistics, we
92  * should ignore the operator collation and use the stats entry's collation.
93  * We expect that the error induced by doing this is usually not large enough
94  * to justify complicating matters. In any case, doing otherwise would yield
95  * entirely garbage results for ordered stats data such as histograms.
96  *----------
97  */
98 
99 #include "postgres.h"
100 
101 #include <ctype.h>
102 #include <math.h>
103 
104 #include "access/brin.h"
105 #include "access/gin.h"
106 #include "access/table.h"
107 #include "access/tableam.h"
108 #include "access/visibilitymap.h"
109 #include "catalog/pg_am.h"
110 #include "catalog/pg_collation.h"
111 #include "catalog/pg_operator.h"
112 #include "catalog/pg_statistic.h"
114 #include "executor/nodeAgg.h"
115 #include "miscadmin.h"
116 #include "nodes/makefuncs.h"
117 #include "nodes/nodeFuncs.h"
118 #include "optimizer/clauses.h"
119 #include "optimizer/cost.h"
120 #include "optimizer/optimizer.h"
121 #include "optimizer/pathnode.h"
122 #include "optimizer/paths.h"
123 #include "optimizer/plancat.h"
124 #include "parser/parse_clause.h"
125 #include "parser/parsetree.h"
126 #include "statistics/statistics.h"
127 #include "storage/bufmgr.h"
128 #include "utils/builtins.h"
129 #include "utils/date.h"
130 #include "utils/datum.h"
131 #include "utils/fmgroids.h"
132 #include "utils/index_selfuncs.h"
133 #include "utils/lsyscache.h"
134 #include "utils/memutils.h"
135 #include "utils/pg_locale.h"
136 #include "utils/rel.h"
137 #include "utils/selfuncs.h"
138 #include "utils/snapmgr.h"
139 #include "utils/spccache.h"
140 #include "utils/syscache.h"
141 #include "utils/timestamp.h"
142 #include "utils/typcache.h"
143 
144 
145 /* Hooks for plugins to get control when we ask for stats */
148 
149 static double eqsel_internal(PG_FUNCTION_ARGS, bool negate);
150 static double eqjoinsel_inner(Oid opfuncoid,
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,
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);
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);
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, Datum *min, Datum *max);
196 static bool get_actual_variable_range(PlannerInfo *root,
197  VariableStatData *vardata,
198  Oid sortop,
199  Datum *min, Datum *max);
200 static bool get_actual_variable_endpoint(Relation heapRel,
201  Relation indexRel,
202  ScanDirection indexscandir,
203  ScanKey scankeys,
204  int16 typLen,
205  bool typByVal,
206  TupleTableSlot *tableslot,
207  MemoryContext outercontext,
208  Datum *endpointDatum);
209 static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
210 
211 
212 /*
213  * eqsel - Selectivity of "=" for any data types.
214  *
215  * Note: this routine is also used to estimate selectivity for some
216  * operators that are not "=" but have comparable selectivity behavior,
217  * such as "~=" (geometric approximate-match). Even for "=", we must
218  * keep in mind that the left and right datatypes may differ.
219  */
220 Datum
222 {
223  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
224 }
225 
226 /*
227  * Common code for eqsel() and neqsel()
228  */
229 static double
231 {
233  Oid operator = PG_GETARG_OID(1);
234  List *args = (List *) PG_GETARG_POINTER(2);
235  int varRelid = PG_GETARG_INT32(3);
236  VariableStatData vardata;
237  Node *other;
238  bool varonleft;
239  double selec;
240 
241  /*
242  * When asked about <>, we do the estimation using the corresponding =
243  * operator, then convert to <> via "1.0 - eq_selectivity - nullfrac".
244  */
245  if (negate)
246  {
247  operator = get_negator(operator);
248  if (!OidIsValid(operator))
249  {
250  /* Use default selectivity (should we raise an error instead?) */
251  return 1.0 - DEFAULT_EQ_SEL;
252  }
253  }
254 
255  /*
256  * If expression is not variable = something or something = variable, then
257  * punt and return a default estimate.
258  */
259  if (!get_restriction_variable(root, args, varRelid,
260  &vardata, &other, &varonleft))
261  return negate ? (1.0 - DEFAULT_EQ_SEL) : DEFAULT_EQ_SEL;
262 
263  /*
264  * We can do a lot better if the something is a constant. (Note: the
265  * Const might result from estimation rather than being a simple constant
266  * in the query.)
267  */
268  if (IsA(other, Const))
269  selec = var_eq_const(&vardata, operator,
270  ((Const *) other)->constvalue,
271  ((Const *) other)->constisnull,
272  varonleft, negate);
273  else
274  selec = var_eq_non_const(&vardata, operator, other,
275  varonleft, negate);
276 
277  ReleaseVariableStats(vardata);
278 
279  return selec;
280 }
281 
282 /*
283  * var_eq_const --- eqsel for var = const case
284  *
285  * This is exported so that some other estimation functions can use it.
286  */
287 double
288 var_eq_const(VariableStatData *vardata, Oid operator,
289  Datum constval, bool constisnull,
290  bool varonleft, bool negate)
291 {
292  double selec;
293  double nullfrac = 0.0;
294  bool isdefault;
295  Oid opfuncoid;
296 
297  /*
298  * If the constant is NULL, assume operator is strict and return zero, ie,
299  * operator will never return TRUE. (It's zero even for a negator op.)
300  */
301  if (constisnull)
302  return 0.0;
303 
304  /*
305  * Grab the nullfrac for use below. Note we allow use of nullfrac
306  * regardless of security check.
307  */
308  if (HeapTupleIsValid(vardata->statsTuple))
309  {
310  Form_pg_statistic stats;
311 
312  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
313  nullfrac = stats->stanullfrac;
314  }
315 
316  /*
317  * If we matched the var to a unique index or DISTINCT clause, assume
318  * there is exactly one match regardless of anything else. (This is
319  * slightly bogus, since the index or clause's equality operator might be
320  * different from ours, but it's much more likely to be right than
321  * ignoring the information.)
322  */
323  if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
324  {
325  selec = 1.0 / vardata->rel->tuples;
326  }
327  else if (HeapTupleIsValid(vardata->statsTuple) &&
329  (opfuncoid = get_opcode(operator))))
330  {
331  AttStatsSlot sslot;
332  bool match = false;
333  int i;
334 
335  /*
336  * Is the constant "=" to any of the column's most common values?
337  * (Although the given operator may not really be "=", we will assume
338  * that seeing whether it returns TRUE is an appropriate test. If you
339  * don't like this, maybe you shouldn't be using eqsel for your
340  * operator...)
341  */
342  if (get_attstatsslot(&sslot, vardata->statsTuple,
343  STATISTIC_KIND_MCV, InvalidOid,
345  {
346  FmgrInfo eqproc;
347 
348  fmgr_info(opfuncoid, &eqproc);
349 
350  for (i = 0; i < sslot.nvalues; i++)
351  {
352  /* be careful to apply operator right way 'round */
353  if (varonleft)
354  match = DatumGetBool(FunctionCall2Coll(&eqproc,
355  sslot.stacoll,
356  sslot.values[i],
357  constval));
358  else
359  match = DatumGetBool(FunctionCall2Coll(&eqproc,
360  sslot.stacoll,
361  constval,
362  sslot.values[i]));
363  if (match)
364  break;
365  }
366  }
367  else
368  {
369  /* no most-common-value info available */
370  i = 0; /* keep compiler quiet */
371  }
372 
373  if (match)
374  {
375  /*
376  * Constant is "=" to this common value. We know selectivity
377  * exactly (or as exactly as ANALYZE could calculate it, anyway).
378  */
379  selec = sslot.numbers[i];
380  }
381  else
382  {
383  /*
384  * Comparison is against a constant that is neither NULL nor any
385  * of the common values. Its selectivity cannot be more than
386  * this:
387  */
388  double sumcommon = 0.0;
389  double otherdistinct;
390 
391  for (i = 0; i < sslot.nnumbers; i++)
392  sumcommon += sslot.numbers[i];
393  selec = 1.0 - sumcommon - nullfrac;
394  CLAMP_PROBABILITY(selec);
395 
396  /*
397  * and in fact it's probably a good deal less. We approximate that
398  * all the not-common values share this remaining fraction
399  * equally, so we divide by the number of other distinct values.
400  */
401  otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
402  sslot.nnumbers;
403  if (otherdistinct > 1)
404  selec /= otherdistinct;
405 
406  /*
407  * Another cross-check: selectivity shouldn't be estimated as more
408  * than the least common "most common value".
409  */
410  if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
411  selec = sslot.numbers[sslot.nnumbers - 1];
412  }
413 
414  free_attstatsslot(&sslot);
415  }
416  else
417  {
418  /*
419  * No ANALYZE stats available, so make a guess using estimated number
420  * of distinct values and assuming they are equally common. (The guess
421  * is unlikely to be very good, but we do know a few special cases.)
422  */
423  selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
424  }
425 
426  /* now adjust if we wanted <> rather than = */
427  if (negate)
428  selec = 1.0 - selec - nullfrac;
429 
430  /* result should be in range, but make sure... */
431  CLAMP_PROBABILITY(selec);
432 
433  return selec;
434 }
435 
436 /*
437  * var_eq_non_const --- eqsel for var = something-other-than-const case
438  *
439  * This is exported so that some other estimation functions can use it.
440  */
441 double
443  Node *other,
444  bool varonleft, bool negate)
445 {
446  double selec;
447  double nullfrac = 0.0;
448  bool isdefault;
449 
450  /*
451  * Grab the nullfrac for use below.
452  */
453  if (HeapTupleIsValid(vardata->statsTuple))
454  {
455  Form_pg_statistic stats;
456 
457  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
458  nullfrac = stats->stanullfrac;
459  }
460 
461  /*
462  * If we matched the var to a unique index or DISTINCT clause, assume
463  * there is exactly one match regardless of anything else. (This is
464  * slightly bogus, since the index or clause's equality operator might be
465  * different from ours, but it's much more likely to be right than
466  * ignoring the information.)
467  */
468  if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
469  {
470  selec = 1.0 / vardata->rel->tuples;
471  }
472  else if (HeapTupleIsValid(vardata->statsTuple))
473  {
474  double ndistinct;
475  AttStatsSlot sslot;
476 
477  /*
478  * Search is for a value that we do not know a priori, but we will
479  * assume it is not NULL. Estimate the selectivity as non-null
480  * fraction divided by number of distinct values, so that we get a
481  * result averaged over all possible values whether common or
482  * uncommon. (Essentially, we are assuming that the not-yet-known
483  * comparison value is equally likely to be any of the possible
484  * values, regardless of their frequency in the table. Is that a good
485  * idea?)
486  */
487  selec = 1.0 - nullfrac;
488  ndistinct = get_variable_numdistinct(vardata, &isdefault);
489  if (ndistinct > 1)
490  selec /= ndistinct;
491 
492  /*
493  * Cross-check: selectivity should never be estimated as more than the
494  * most common value's.
495  */
496  if (get_attstatsslot(&sslot, vardata->statsTuple,
497  STATISTIC_KIND_MCV, InvalidOid,
499  {
500  if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
501  selec = sslot.numbers[0];
502  free_attstatsslot(&sslot);
503  }
504  }
505  else
506  {
507  /*
508  * No ANALYZE stats available, so make a guess using estimated number
509  * of distinct values and assuming they are equally common. (The guess
510  * is unlikely to be very good, but we do know a few special cases.)
511  */
512  selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
513  }
514 
515  /* now adjust if we wanted <> rather than = */
516  if (negate)
517  selec = 1.0 - selec - nullfrac;
518 
519  /* result should be in range, but make sure... */
520  CLAMP_PROBABILITY(selec);
521 
522  return selec;
523 }
524 
525 /*
526  * neqsel - Selectivity of "!=" for any data types.
527  *
528  * This routine is also used for some operators that are not "!="
529  * but have comparable selectivity behavior. See above comments
530  * for eqsel().
531  */
532 Datum
534 {
535  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, true));
536 }
537 
538 /*
539  * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
540  *
541  * This is the guts of scalarltsel/scalarlesel/scalargtsel/scalargesel.
542  * The isgt and iseq flags distinguish which of the four cases apply.
543  *
544  * The caller has commuted the clause, if necessary, so that we can treat
545  * the variable as being on the left. The caller must also make sure that
546  * the other side of the clause is a non-null Const, and dissect that into
547  * a value and datatype. (This definition simplifies some callers that
548  * want to estimate against a computed value instead of a Const node.)
549  *
550  * This routine works for any datatype (or pair of datatypes) known to
551  * convert_to_scalar(). If it is applied to some other datatype,
552  * it will return an approximate estimate based on assuming that the constant
553  * value falls in the middle of the bin identified by binary search.
554  */
555 static double
556 scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq,
557  VariableStatData *vardata, Datum constval, Oid consttype)
558 {
559  Form_pg_statistic stats;
560  FmgrInfo opproc;
561  double mcv_selec,
562  hist_selec,
563  sumcommon;
564  double selec;
565 
566  if (!HeapTupleIsValid(vardata->statsTuple))
567  {
568  /*
569  * No stats are available. Typically this means we have to fall back
570  * on the default estimate; but if the variable is CTID then we can
571  * make an estimate based on comparing the constant to the table size.
572  */
573  if (vardata->var && IsA(vardata->var, Var) &&
574  ((Var *) vardata->var)->varattno == SelfItemPointerAttributeNumber)
575  {
576  ItemPointer itemptr;
577  double block;
578  double density;
579 
580  /*
581  * If the relation's empty, we're going to include all of it.
582  * (This is mostly to avoid divide-by-zero below.)
583  */
584  if (vardata->rel->pages == 0)
585  return 1.0;
586 
587  itemptr = (ItemPointer) DatumGetPointer(constval);
588  block = ItemPointerGetBlockNumberNoCheck(itemptr);
589 
590  /*
591  * Determine the average number of tuples per page (density).
592  *
593  * Since the last page will, on average, be only half full, we can
594  * estimate it to have half as many tuples as earlier pages. So
595  * give it half the weight of a regular page.
596  */
597  density = vardata->rel->tuples / (vardata->rel->pages - 0.5);
598 
599  /* If target is the last page, use half the density. */
600  if (block >= vardata->rel->pages - 1)
601  density *= 0.5;
602 
603  /*
604  * Using the average tuples per page, calculate how far into the
605  * page the itemptr is likely to be and adjust block accordingly,
606  * by adding that fraction of a whole block (but never more than a
607  * whole block, no matter how high the itemptr's offset is). Here
608  * we are ignoring the possibility of dead-tuple line pointers,
609  * which is fairly bogus, but we lack the info to do better.
610  */
611  if (density > 0.0)
612  {
614 
615  block += Min(offset / density, 1.0);
616  }
617 
618  /*
619  * Convert relative block number to selectivity. Again, the last
620  * page has only half weight.
621  */
622  selec = block / (vardata->rel->pages - 0.5);
623 
624  /*
625  * The calculation so far gave us a selectivity for the "<=" case.
626  * We'll have one less tuple for "<" and one additional tuple for
627  * ">=", the latter of which we'll reverse the selectivity for
628  * below, so we can simply subtract one tuple for both cases. The
629  * cases that need this adjustment can be identified by iseq being
630  * equal to isgt.
631  */
632  if (iseq == isgt && vardata->rel->tuples >= 1.0)
633  selec -= (1.0 / vardata->rel->tuples);
634 
635  /* Finally, reverse the selectivity for the ">", ">=" cases. */
636  if (isgt)
637  selec = 1.0 - selec;
638 
639  CLAMP_PROBABILITY(selec);
640  return selec;
641  }
642 
643  /* no stats available, so default result */
644  return DEFAULT_INEQ_SEL;
645  }
646  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
647 
648  fmgr_info(get_opcode(operator), &opproc);
649 
650  /*
651  * If we have most-common-values info, add up the fractions of the MCV
652  * entries that satisfy MCV OP CONST. These fractions contribute directly
653  * to the result selectivity. Also add up the total fraction represented
654  * by MCV entries.
655  */
656  mcv_selec = mcv_selectivity(vardata, &opproc, constval, true,
657  &sumcommon);
658 
659  /*
660  * If there is a histogram, determine which bin the constant falls in, and
661  * compute the resulting contribution to selectivity.
662  */
663  hist_selec = ineq_histogram_selectivity(root, vardata,
664  &opproc, isgt, iseq,
665  constval, consttype);
666 
667  /*
668  * Now merge the results from the MCV and histogram calculations,
669  * realizing that the histogram covers only the non-null values that are
670  * not listed in MCV.
671  */
672  selec = 1.0 - stats->stanullfrac - sumcommon;
673 
674  if (hist_selec >= 0.0)
675  selec *= hist_selec;
676  else
677  {
678  /*
679  * If no histogram but there are values not accounted for by MCV,
680  * arbitrarily assume half of them will match.
681  */
682  selec *= 0.5;
683  }
684 
685  selec += mcv_selec;
686 
687  /* result should be in range, but make sure... */
688  CLAMP_PROBABILITY(selec);
689 
690  return selec;
691 }
692 
693 /*
694  * mcv_selectivity - Examine the MCV list for selectivity estimates
695  *
696  * Determine the fraction of the variable's MCV population that satisfies
697  * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
698  * compute the fraction of the total column population represented by the MCV
699  * list. This code will work for any boolean-returning predicate operator.
700  *
701  * The function result is the MCV selectivity, and the fraction of the
702  * total population is returned into *sumcommonp. Zeroes are returned
703  * if there is no MCV list.
704  */
705 double
707  Datum constval, bool varonleft,
708  double *sumcommonp)
709 {
710  double mcv_selec,
711  sumcommon;
712  AttStatsSlot sslot;
713  int i;
714 
715  mcv_selec = 0.0;
716  sumcommon = 0.0;
717 
718  if (HeapTupleIsValid(vardata->statsTuple) &&
719  statistic_proc_security_check(vardata, opproc->fn_oid) &&
720  get_attstatsslot(&sslot, vardata->statsTuple,
721  STATISTIC_KIND_MCV, InvalidOid,
723  {
724  for (i = 0; i < sslot.nvalues; i++)
725  {
726  if (varonleft ?
728  sslot.stacoll,
729  sslot.values[i],
730  constval)) :
732  sslot.stacoll,
733  constval,
734  sslot.values[i])))
735  mcv_selec += sslot.numbers[i];
736  sumcommon += sslot.numbers[i];
737  }
738  free_attstatsslot(&sslot);
739  }
740 
741  *sumcommonp = sumcommon;
742  return mcv_selec;
743 }
744 
745 /*
746  * histogram_selectivity - Examine the histogram for selectivity estimates
747  *
748  * Determine the fraction of the variable's histogram entries that satisfy
749  * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
750  *
751  * This code will work for any boolean-returning predicate operator, whether
752  * or not it has anything to do with the histogram sort operator. We are
753  * essentially using the histogram just as a representative sample. However,
754  * small histograms are unlikely to be all that representative, so the caller
755  * should be prepared to fall back on some other estimation approach when the
756  * histogram is missing or very small. It may also be prudent to combine this
757  * approach with another one when the histogram is small.
758  *
759  * If the actual histogram size is not at least min_hist_size, we won't bother
760  * to do the calculation at all. Also, if the n_skip parameter is > 0, we
761  * ignore the first and last n_skip histogram elements, on the grounds that
762  * they are outliers and hence not very representative. Typical values for
763  * these parameters are 10 and 1.
764  *
765  * The function result is the selectivity, or -1 if there is no histogram
766  * or it's smaller than min_hist_size.
767  *
768  * The output parameter *hist_size receives the actual histogram size,
769  * or zero if no histogram. Callers may use this number to decide how
770  * much faith to put in the function result.
771  *
772  * Note that the result disregards both the most-common-values (if any) and
773  * null entries. The caller is expected to combine this result with
774  * statistics for those portions of the column population. It may also be
775  * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
776  */
777 double
779  Datum constval, bool varonleft,
780  int min_hist_size, int n_skip,
781  int *hist_size)
782 {
783  double result;
784  AttStatsSlot sslot;
785 
786  /* check sanity of parameters */
787  Assert(n_skip >= 0);
788  Assert(min_hist_size > 2 * n_skip);
789 
790  if (HeapTupleIsValid(vardata->statsTuple) &&
791  statistic_proc_security_check(vardata, opproc->fn_oid) &&
792  get_attstatsslot(&sslot, vardata->statsTuple,
793  STATISTIC_KIND_HISTOGRAM, InvalidOid,
795  {
796  *hist_size = sslot.nvalues;
797  if (sslot.nvalues >= min_hist_size)
798  {
799  int nmatch = 0;
800  int i;
801 
802  for (i = n_skip; i < sslot.nvalues - n_skip; i++)
803  {
804  if (varonleft ?
806  sslot.stacoll,
807  sslot.values[i],
808  constval)) :
810  sslot.stacoll,
811  constval,
812  sslot.values[i])))
813  nmatch++;
814  }
815  result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
816  }
817  else
818  result = -1;
819  free_attstatsslot(&sslot);
820  }
821  else
822  {
823  *hist_size = 0;
824  result = -1;
825  }
826 
827  return result;
828 }
829 
830 /*
831  * ineq_histogram_selectivity - Examine the histogram for scalarineqsel
832  *
833  * Determine the fraction of the variable's histogram population that
834  * satisfies the inequality condition, ie, VAR < (or <=, >, >=) CONST.
835  * The isgt and iseq flags distinguish which of the four cases apply.
836  *
837  * Returns -1 if there is no histogram (valid results will always be >= 0).
838  *
839  * Note that the result disregards both the most-common-values (if any) and
840  * null entries. The caller is expected to combine this result with
841  * statistics for those portions of the column population.
842  *
843  * This is exported so that some other estimation functions can use it.
844  */
845 double
847  VariableStatData *vardata,
848  FmgrInfo *opproc, bool isgt, bool iseq,
849  Datum constval, Oid consttype)
850 {
851  double hist_selec;
852  AttStatsSlot sslot;
853 
854  hist_selec = -1.0;
855 
856  /*
857  * Someday, ANALYZE might store more than one histogram per rel/att,
858  * corresponding to more than one possible sort ordering defined for the
859  * column type. However, to make that work we will need to figure out
860  * which staop to search for --- it's not necessarily the one we have at
861  * hand! (For example, we might have a '<=' operator rather than the '<'
862  * operator that will appear in staop.) For now, assume that whatever
863  * appears in pg_statistic is sorted the same way our operator sorts, or
864  * the reverse way if isgt is true.
865  */
866  if (HeapTupleIsValid(vardata->statsTuple) &&
867  statistic_proc_security_check(vardata, opproc->fn_oid) &&
868  get_attstatsslot(&sslot, vardata->statsTuple,
869  STATISTIC_KIND_HISTOGRAM, InvalidOid,
871  {
872  if (sslot.nvalues > 1)
873  {
874  /*
875  * Use binary search to find the desired location, namely the
876  * right end of the histogram bin containing the comparison value,
877  * which is the leftmost entry for which the comparison operator
878  * succeeds (if isgt) or fails (if !isgt). (If the given operator
879  * isn't actually sort-compatible with the histogram, you'll get
880  * garbage results ... but probably not any more garbage-y than
881  * you would have from the old linear search.)
882  *
883  * In this loop, we pay no attention to whether the operator iseq
884  * or not; that detail will be mopped up below. (We cannot tell,
885  * anyway, whether the operator thinks the values are equal.)
886  *
887  * If the binary search accesses the first or last histogram
888  * entry, we try to replace that endpoint with the true column min
889  * or max as found by get_actual_variable_range(). This
890  * ameliorates misestimates when the min or max is moving as a
891  * result of changes since the last ANALYZE. Note that this could
892  * result in effectively including MCVs into the histogram that
893  * weren't there before, but we don't try to correct for that.
894  */
895  double histfrac;
896  int lobound = 0; /* first possible slot to search */
897  int hibound = sslot.nvalues; /* last+1 slot to search */
898  bool have_end = false;
899 
900  /*
901  * If there are only two histogram entries, we'll want up-to-date
902  * values for both. (If there are more than two, we need at most
903  * one of them to be updated, so we deal with that within the
904  * loop.)
905  */
906  if (sslot.nvalues == 2)
907  have_end = get_actual_variable_range(root,
908  vardata,
909  sslot.staop,
910  &sslot.values[0],
911  &sslot.values[1]);
912 
913  while (lobound < hibound)
914  {
915  int probe = (lobound + hibound) / 2;
916  bool ltcmp;
917 
918  /*
919  * If we find ourselves about to compare to the first or last
920  * histogram entry, first try to replace it with the actual
921  * current min or max (unless we already did so above).
922  */
923  if (probe == 0 && sslot.nvalues > 2)
924  have_end = get_actual_variable_range(root,
925  vardata,
926  sslot.staop,
927  &sslot.values[0],
928  NULL);
929  else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
930  have_end = get_actual_variable_range(root,
931  vardata,
932  sslot.staop,
933  NULL,
934  &sslot.values[probe]);
935 
936  ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
937  sslot.stacoll,
938  sslot.values[probe],
939  constval));
940  if (isgt)
941  ltcmp = !ltcmp;
942  if (ltcmp)
943  lobound = probe + 1;
944  else
945  hibound = probe;
946  }
947 
948  if (lobound <= 0)
949  {
950  /*
951  * Constant is below lower histogram boundary. More
952  * precisely, we have found that no entry in the histogram
953  * satisfies the inequality clause (if !isgt) or they all do
954  * (if isgt). We estimate that that's true of the entire
955  * table, so set histfrac to 0.0 (which we'll flip to 1.0
956  * below, if isgt).
957  */
958  histfrac = 0.0;
959  }
960  else if (lobound >= sslot.nvalues)
961  {
962  /*
963  * Inverse case: constant is above upper histogram boundary.
964  */
965  histfrac = 1.0;
966  }
967  else
968  {
969  /* We have values[i-1] <= constant <= values[i]. */
970  int i = lobound;
971  double eq_selec = 0;
972  double val,
973  high,
974  low;
975  double binfrac;
976 
977  /*
978  * In the cases where we'll need it below, obtain an estimate
979  * of the selectivity of "x = constval". We use a calculation
980  * similar to what var_eq_const() does for a non-MCV constant,
981  * ie, estimate that all distinct non-MCV values occur equally
982  * often. But multiplication by "1.0 - sumcommon - nullfrac"
983  * will be done by our caller, so we shouldn't do that here.
984  * Therefore we can't try to clamp the estimate by reference
985  * to the least common MCV; the result would be too small.
986  *
987  * Note: since this is effectively assuming that constval
988  * isn't an MCV, it's logically dubious if constval in fact is
989  * one. But we have to apply *some* correction for equality,
990  * and anyway we cannot tell if constval is an MCV, since we
991  * don't have a suitable equality operator at hand.
992  */
993  if (i == 1 || isgt == iseq)
994  {
995  double otherdistinct;
996  bool isdefault;
997  AttStatsSlot mcvslot;
998 
999  /* Get estimated number of distinct values */
1000  otherdistinct = get_variable_numdistinct(vardata,
1001  &isdefault);
1002 
1003  /* Subtract off the number of known MCVs */
1004  if (get_attstatsslot(&mcvslot, vardata->statsTuple,
1005  STATISTIC_KIND_MCV, InvalidOid,
1007  {
1008  otherdistinct -= mcvslot.nnumbers;
1009  free_attstatsslot(&mcvslot);
1010  }
1011 
1012  /* If result doesn't seem sane, leave eq_selec at 0 */
1013  if (otherdistinct > 1)
1014  eq_selec = 1.0 / otherdistinct;
1015  }
1016 
1017  /*
1018  * Convert the constant and the two nearest bin boundary
1019  * values to a uniform comparison scale, and do a linear
1020  * interpolation within this bin.
1021  */
1022  if (convert_to_scalar(constval, consttype, sslot.stacoll,
1023  &val,
1024  sslot.values[i - 1], sslot.values[i],
1025  vardata->vartype,
1026  &low, &high))
1027  {
1028  if (high <= low)
1029  {
1030  /* cope if bin boundaries appear identical */
1031  binfrac = 0.5;
1032  }
1033  else if (val <= low)
1034  binfrac = 0.0;
1035  else if (val >= high)
1036  binfrac = 1.0;
1037  else
1038  {
1039  binfrac = (val - low) / (high - low);
1040 
1041  /*
1042  * Watch out for the possibility that we got a NaN or
1043  * Infinity from the division. This can happen
1044  * despite the previous checks, if for example "low"
1045  * is -Infinity.
1046  */
1047  if (isnan(binfrac) ||
1048  binfrac < 0.0 || binfrac > 1.0)
1049  binfrac = 0.5;
1050  }
1051  }
1052  else
1053  {
1054  /*
1055  * Ideally we'd produce an error here, on the grounds that
1056  * the given operator shouldn't have scalarXXsel
1057  * registered as its selectivity func unless we can deal
1058  * with its operand types. But currently, all manner of
1059  * stuff is invoking scalarXXsel, so give a default
1060  * estimate until that can be fixed.
1061  */
1062  binfrac = 0.5;
1063  }
1064 
1065  /*
1066  * Now, compute the overall selectivity across the values
1067  * represented by the histogram. We have i-1 full bins and
1068  * binfrac partial bin below the constant.
1069  */
1070  histfrac = (double) (i - 1) + binfrac;
1071  histfrac /= (double) (sslot.nvalues - 1);
1072 
1073  /*
1074  * At this point, histfrac is an estimate of the fraction of
1075  * the population represented by the histogram that satisfies
1076  * "x <= constval". Somewhat remarkably, this statement is
1077  * true regardless of which operator we were doing the probes
1078  * with, so long as convert_to_scalar() delivers reasonable
1079  * results. If the probe constant is equal to some histogram
1080  * entry, we would have considered the bin to the left of that
1081  * entry if probing with "<" or ">=", or the bin to the right
1082  * if probing with "<=" or ">"; but binfrac would have come
1083  * out as 1.0 in the first case and 0.0 in the second, leading
1084  * to the same histfrac in either case. For probe constants
1085  * between histogram entries, we find the same bin and get the
1086  * same estimate with any operator.
1087  *
1088  * The fact that the estimate corresponds to "x <= constval"
1089  * and not "x < constval" is because of the way that ANALYZE
1090  * constructs the histogram: each entry is, effectively, the
1091  * rightmost value in its sample bucket. So selectivity
1092  * values that are exact multiples of 1/(histogram_size-1)
1093  * should be understood as estimates including a histogram
1094  * entry plus everything to its left.
1095  *
1096  * However, that breaks down for the first histogram entry,
1097  * which necessarily is the leftmost value in its sample
1098  * bucket. That means the first histogram bin is slightly
1099  * narrower than the rest, by an amount equal to eq_selec.
1100  * Another way to say that is that we want "x <= leftmost" to
1101  * be estimated as eq_selec not zero. So, if we're dealing
1102  * with the first bin (i==1), rescale to make that true while
1103  * adjusting the rest of that bin linearly.
1104  */
1105  if (i == 1)
1106  histfrac += eq_selec * (1.0 - binfrac);
1107 
1108  /*
1109  * "x <= constval" is good if we want an estimate for "<=" or
1110  * ">", but if we are estimating for "<" or ">=", we now need
1111  * to decrease the estimate by eq_selec.
1112  */
1113  if (isgt == iseq)
1114  histfrac -= eq_selec;
1115  }
1116 
1117  /*
1118  * Now the estimate is finished for "<" and "<=" cases. If we are
1119  * estimating for ">" or ">=", flip it.
1120  */
1121  hist_selec = isgt ? (1.0 - histfrac) : histfrac;
1122 
1123  /*
1124  * The histogram boundaries are only approximate to begin with,
1125  * and may well be out of date anyway. Therefore, don't believe
1126  * extremely small or large selectivity estimates --- unless we
1127  * got actual current endpoint values from the table, in which
1128  * case just do the usual sanity clamp. Somewhat arbitrarily, we
1129  * set the cutoff for other cases at a hundredth of the histogram
1130  * resolution.
1131  */
1132  if (have_end)
1133  CLAMP_PROBABILITY(hist_selec);
1134  else
1135  {
1136  double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1137 
1138  if (hist_selec < cutoff)
1139  hist_selec = cutoff;
1140  else if (hist_selec > 1.0 - cutoff)
1141  hist_selec = 1.0 - cutoff;
1142  }
1143  }
1144 
1145  free_attstatsslot(&sslot);
1146  }
1147 
1148  return hist_selec;
1149 }
1150 
1151 /*
1152  * Common wrapper function for the selectivity estimators that simply
1153  * invoke scalarineqsel().
1154  */
1155 static Datum
1157 {
1158  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1159  Oid operator = PG_GETARG_OID(1);
1160  List *args = (List *) PG_GETARG_POINTER(2);
1161  int varRelid = PG_GETARG_INT32(3);
1162  VariableStatData vardata;
1163  Node *other;
1164  bool varonleft;
1165  Datum constval;
1166  Oid consttype;
1167  double selec;
1168 
1169  /*
1170  * If expression is not variable op something or something op variable,
1171  * then punt and return a default estimate.
1172  */
1173  if (!get_restriction_variable(root, args, varRelid,
1174  &vardata, &other, &varonleft))
1176 
1177  /*
1178  * Can't do anything useful if the something is not a constant, either.
1179  */
1180  if (!IsA(other, Const))
1181  {
1182  ReleaseVariableStats(vardata);
1184  }
1185 
1186  /*
1187  * If the constant is NULL, assume operator is strict and return zero, ie,
1188  * operator will never return TRUE.
1189  */
1190  if (((Const *) other)->constisnull)
1191  {
1192  ReleaseVariableStats(vardata);
1193  PG_RETURN_FLOAT8(0.0);
1194  }
1195  constval = ((Const *) other)->constvalue;
1196  consttype = ((Const *) other)->consttype;
1197 
1198  /*
1199  * Force the var to be on the left to simplify logic in scalarineqsel.
1200  */
1201  if (!varonleft)
1202  {
1203  operator = get_commutator(operator);
1204  if (!operator)
1205  {
1206  /* Use default selectivity (should we raise an error instead?) */
1207  ReleaseVariableStats(vardata);
1209  }
1210  isgt = !isgt;
1211  }
1212 
1213  /* The rest of the work is done by scalarineqsel(). */
1214  selec = scalarineqsel(root, operator, isgt, iseq,
1215  &vardata, constval, consttype);
1216 
1217  ReleaseVariableStats(vardata);
1218 
1219  PG_RETURN_FLOAT8((float8) selec);
1220 }
1221 
1222 /*
1223  * scalarltsel - Selectivity of "<" for scalars.
1224  */
1225 Datum
1227 {
1228  return scalarineqsel_wrapper(fcinfo, false, false);
1229 }
1230 
1231 /*
1232  * scalarlesel - Selectivity of "<=" for scalars.
1233  */
1234 Datum
1236 {
1237  return scalarineqsel_wrapper(fcinfo, false, true);
1238 }
1239 
1240 /*
1241  * scalargtsel - Selectivity of ">" for scalars.
1242  */
1243 Datum
1245 {
1246  return scalarineqsel_wrapper(fcinfo, true, false);
1247 }
1248 
1249 /*
1250  * scalargesel - Selectivity of ">=" for scalars.
1251  */
1252 Datum
1254 {
1255  return scalarineqsel_wrapper(fcinfo, true, true);
1256 }
1257 
1258 /*
1259  * boolvarsel - Selectivity of Boolean variable.
1260  *
1261  * This can actually be called on any boolean-valued expression. If it
1262  * involves only Vars of the specified relation, and if there are statistics
1263  * about the Var or expression (the latter is possible if it's indexed) then
1264  * we'll produce a real estimate; otherwise it's just a default.
1265  */
1267 boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
1268 {
1269  VariableStatData vardata;
1270  double selec;
1271 
1272  examine_variable(root, arg, varRelid, &vardata);
1273  if (HeapTupleIsValid(vardata.statsTuple))
1274  {
1275  /*
1276  * A boolean variable V is equivalent to the clause V = 't', so we
1277  * compute the selectivity as if that is what we have.
1278  */
1279  selec = var_eq_const(&vardata, BooleanEqualOperator,
1280  BoolGetDatum(true), false, true, false);
1281  }
1282  else
1283  {
1284  /* Otherwise, the default estimate is 0.5 */
1285  selec = 0.5;
1286  }
1287  ReleaseVariableStats(vardata);
1288  return selec;
1289 }
1290 
1291 /*
1292  * booltestsel - Selectivity of BooleanTest Node.
1293  */
1296  int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1297 {
1298  VariableStatData vardata;
1299  double selec;
1300 
1301  examine_variable(root, arg, varRelid, &vardata);
1302 
1303  if (HeapTupleIsValid(vardata.statsTuple))
1304  {
1305  Form_pg_statistic stats;
1306  double freq_null;
1307  AttStatsSlot sslot;
1308 
1309  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1310  freq_null = stats->stanullfrac;
1311 
1312  if (get_attstatsslot(&sslot, vardata.statsTuple,
1313  STATISTIC_KIND_MCV, InvalidOid,
1315  && sslot.nnumbers > 0)
1316  {
1317  double freq_true;
1318  double freq_false;
1319 
1320  /*
1321  * Get first MCV frequency and derive frequency for true.
1322  */
1323  if (DatumGetBool(sslot.values[0]))
1324  freq_true = sslot.numbers[0];
1325  else
1326  freq_true = 1.0 - sslot.numbers[0] - freq_null;
1327 
1328  /*
1329  * Next derive frequency for false. Then use these as appropriate
1330  * to derive frequency for each case.
1331  */
1332  freq_false = 1.0 - freq_true - freq_null;
1333 
1334  switch (booltesttype)
1335  {
1336  case IS_UNKNOWN:
1337  /* select only NULL values */
1338  selec = freq_null;
1339  break;
1340  case IS_NOT_UNKNOWN:
1341  /* select non-NULL values */
1342  selec = 1.0 - freq_null;
1343  break;
1344  case IS_TRUE:
1345  /* select only TRUE values */
1346  selec = freq_true;
1347  break;
1348  case IS_NOT_TRUE:
1349  /* select non-TRUE values */
1350  selec = 1.0 - freq_true;
1351  break;
1352  case IS_FALSE:
1353  /* select only FALSE values */
1354  selec = freq_false;
1355  break;
1356  case IS_NOT_FALSE:
1357  /* select non-FALSE values */
1358  selec = 1.0 - freq_false;
1359  break;
1360  default:
1361  elog(ERROR, "unrecognized booltesttype: %d",
1362  (int) booltesttype);
1363  selec = 0.0; /* Keep compiler quiet */
1364  break;
1365  }
1366 
1367  free_attstatsslot(&sslot);
1368  }
1369  else
1370  {
1371  /*
1372  * No most-common-value info available. Still have null fraction
1373  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1374  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1375  */
1376  switch (booltesttype)
1377  {
1378  case IS_UNKNOWN:
1379  /* select only NULL values */
1380  selec = freq_null;
1381  break;
1382  case IS_NOT_UNKNOWN:
1383  /* select non-NULL values */
1384  selec = 1.0 - freq_null;
1385  break;
1386  case IS_TRUE:
1387  case IS_FALSE:
1388  /* Assume we select half of the non-NULL values */
1389  selec = (1.0 - freq_null) / 2.0;
1390  break;
1391  case IS_NOT_TRUE:
1392  case IS_NOT_FALSE:
1393  /* Assume we select NULLs plus half of the non-NULLs */
1394  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1395  selec = (freq_null + 1.0) / 2.0;
1396  break;
1397  default:
1398  elog(ERROR, "unrecognized booltesttype: %d",
1399  (int) booltesttype);
1400  selec = 0.0; /* Keep compiler quiet */
1401  break;
1402  }
1403  }
1404  }
1405  else
1406  {
1407  /*
1408  * If we can't get variable statistics for the argument, perhaps
1409  * clause_selectivity can do something with it. We ignore the
1410  * possibility of a NULL value when using clause_selectivity, and just
1411  * assume the value is either TRUE or FALSE.
1412  */
1413  switch (booltesttype)
1414  {
1415  case IS_UNKNOWN:
1416  selec = DEFAULT_UNK_SEL;
1417  break;
1418  case IS_NOT_UNKNOWN:
1419  selec = DEFAULT_NOT_UNK_SEL;
1420  break;
1421  case IS_TRUE:
1422  case IS_NOT_FALSE:
1423  selec = (double) clause_selectivity(root, arg,
1424  varRelid,
1425  jointype, sjinfo);
1426  break;
1427  case IS_FALSE:
1428  case IS_NOT_TRUE:
1429  selec = 1.0 - (double) clause_selectivity(root, arg,
1430  varRelid,
1431  jointype, sjinfo);
1432  break;
1433  default:
1434  elog(ERROR, "unrecognized booltesttype: %d",
1435  (int) booltesttype);
1436  selec = 0.0; /* Keep compiler quiet */
1437  break;
1438  }
1439  }
1440 
1441  ReleaseVariableStats(vardata);
1442 
1443  /* result should be in range, but make sure... */
1444  CLAMP_PROBABILITY(selec);
1445 
1446  return (Selectivity) selec;
1447 }
1448 
1449 /*
1450  * nulltestsel - Selectivity of NullTest Node.
1451  */
1454  int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1455 {
1456  VariableStatData vardata;
1457  double selec;
1458 
1459  examine_variable(root, arg, varRelid, &vardata);
1460 
1461  if (HeapTupleIsValid(vardata.statsTuple))
1462  {
1463  Form_pg_statistic stats;
1464  double freq_null;
1465 
1466  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1467  freq_null = stats->stanullfrac;
1468 
1469  switch (nulltesttype)
1470  {
1471  case IS_NULL:
1472 
1473  /*
1474  * Use freq_null directly.
1475  */
1476  selec = freq_null;
1477  break;
1478  case IS_NOT_NULL:
1479 
1480  /*
1481  * Select not unknown (not null) values. Calculate from
1482  * freq_null.
1483  */
1484  selec = 1.0 - freq_null;
1485  break;
1486  default:
1487  elog(ERROR, "unrecognized nulltesttype: %d",
1488  (int) nulltesttype);
1489  return (Selectivity) 0; /* keep compiler quiet */
1490  }
1491  }
1492  else if (vardata.var && IsA(vardata.var, Var) &&
1493  ((Var *) vardata.var)->varattno < 0)
1494  {
1495  /*
1496  * There are no stats for system columns, but we know they are never
1497  * NULL.
1498  */
1499  selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
1500  }
1501  else
1502  {
1503  /*
1504  * No ANALYZE stats available, so make a guess
1505  */
1506  switch (nulltesttype)
1507  {
1508  case IS_NULL:
1509  selec = DEFAULT_UNK_SEL;
1510  break;
1511  case IS_NOT_NULL:
1512  selec = DEFAULT_NOT_UNK_SEL;
1513  break;
1514  default:
1515  elog(ERROR, "unrecognized nulltesttype: %d",
1516  (int) nulltesttype);
1517  return (Selectivity) 0; /* keep compiler quiet */
1518  }
1519  }
1520 
1521  ReleaseVariableStats(vardata);
1522 
1523  /* result should be in range, but make sure... */
1524  CLAMP_PROBABILITY(selec);
1525 
1526  return (Selectivity) selec;
1527 }
1528 
1529 /*
1530  * strip_array_coercion - strip binary-compatible relabeling from an array expr
1531  *
1532  * For array values, the parser normally generates ArrayCoerceExpr conversions,
1533  * but it seems possible that RelabelType might show up. Also, the planner
1534  * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1535  * so we need to be ready to deal with more than one level.
1536  */
1537 static Node *
1539 {
1540  for (;;)
1541  {
1542  if (node && IsA(node, ArrayCoerceExpr))
1543  {
1544  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
1545 
1546  /*
1547  * If the per-element expression is just a RelabelType on top of
1548  * CaseTestExpr, then we know it's a binary-compatible relabeling.
1549  */
1550  if (IsA(acoerce->elemexpr, RelabelType) &&
1551  IsA(((RelabelType *) acoerce->elemexpr)->arg, CaseTestExpr))
1552  node = (Node *) acoerce->arg;
1553  else
1554  break;
1555  }
1556  else if (node && IsA(node, RelabelType))
1557  {
1558  /* We don't really expect this case, but may as well cope */
1559  node = (Node *) ((RelabelType *) node)->arg;
1560  }
1561  else
1562  break;
1563  }
1564  return node;
1565 }
1566 
1567 /*
1568  * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1569  */
1572  ScalarArrayOpExpr *clause,
1573  bool is_join_clause,
1574  int varRelid,
1575  JoinType jointype,
1576  SpecialJoinInfo *sjinfo)
1577 {
1578  Oid operator = clause->opno;
1579  bool useOr = clause->useOr;
1580  bool isEquality = false;
1581  bool isInequality = false;
1582  Node *leftop;
1583  Node *rightop;
1584  Oid nominal_element_type;
1585  Oid nominal_element_collation;
1586  TypeCacheEntry *typentry;
1587  RegProcedure oprsel;
1588  FmgrInfo oprselproc;
1589  Selectivity s1;
1590  Selectivity s1disjoint;
1591 
1592  /* First, deconstruct the expression */
1593  Assert(list_length(clause->args) == 2);
1594  leftop = (Node *) linitial(clause->args);
1595  rightop = (Node *) lsecond(clause->args);
1596 
1597  /* aggressively reduce both sides to constants */
1598  leftop = estimate_expression_value(root, leftop);
1599  rightop = estimate_expression_value(root, rightop);
1600 
1601  /* get nominal (after relabeling) element type of rightop */
1602  nominal_element_type = get_base_element_type(exprType(rightop));
1603  if (!OidIsValid(nominal_element_type))
1604  return (Selectivity) 0.5; /* probably shouldn't happen */
1605  /* get nominal collation, too, for generating constants */
1606  nominal_element_collation = exprCollation(rightop);
1607 
1608  /* look through any binary-compatible relabeling of rightop */
1609  rightop = strip_array_coercion(rightop);
1610 
1611  /*
1612  * Detect whether the operator is the default equality or inequality
1613  * operator of the array element type.
1614  */
1615  typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1616  if (OidIsValid(typentry->eq_opr))
1617  {
1618  if (operator == typentry->eq_opr)
1619  isEquality = true;
1620  else if (get_negator(operator) == typentry->eq_opr)
1621  isInequality = true;
1622  }
1623 
1624  /*
1625  * If it is equality or inequality, we might be able to estimate this as a
1626  * form of array containment; for instance "const = ANY(column)" can be
1627  * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1628  * that, and returns the selectivity estimate if successful, or -1 if not.
1629  */
1630  if ((isEquality || isInequality) && !is_join_clause)
1631  {
1632  s1 = scalararraysel_containment(root, leftop, rightop,
1633  nominal_element_type,
1634  isEquality, useOr, varRelid);
1635  if (s1 >= 0.0)
1636  return s1;
1637  }
1638 
1639  /*
1640  * Look up the underlying operator's selectivity estimator. Punt if it
1641  * hasn't got one.
1642  */
1643  if (is_join_clause)
1644  oprsel = get_oprjoin(operator);
1645  else
1646  oprsel = get_oprrest(operator);
1647  if (!oprsel)
1648  return (Selectivity) 0.5;
1649  fmgr_info(oprsel, &oprselproc);
1650 
1651  /*
1652  * In the array-containment check above, we must only believe that an
1653  * operator is equality or inequality if it is the default btree equality
1654  * operator (or its negator) for the element type, since those are the
1655  * operators that array containment will use. But in what follows, we can
1656  * be a little laxer, and also believe that any operators using eqsel() or
1657  * neqsel() as selectivity estimator act like equality or inequality.
1658  */
1659  if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1660  isEquality = true;
1661  else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1662  isInequality = true;
1663 
1664  /*
1665  * We consider three cases:
1666  *
1667  * 1. rightop is an Array constant: deconstruct the array, apply the
1668  * operator's selectivity function for each array element, and merge the
1669  * results in the same way that clausesel.c does for AND/OR combinations.
1670  *
1671  * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1672  * function for each element of the ARRAY[] construct, and merge.
1673  *
1674  * 3. otherwise, make a guess ...
1675  */
1676  if (rightop && IsA(rightop, Const))
1677  {
1678  Datum arraydatum = ((Const *) rightop)->constvalue;
1679  bool arrayisnull = ((Const *) rightop)->constisnull;
1680  ArrayType *arrayval;
1681  int16 elmlen;
1682  bool elmbyval;
1683  char elmalign;
1684  int num_elems;
1685  Datum *elem_values;
1686  bool *elem_nulls;
1687  int i;
1688 
1689  if (arrayisnull) /* qual can't succeed if null array */
1690  return (Selectivity) 0.0;
1691  arrayval = DatumGetArrayTypeP(arraydatum);
1693  &elmlen, &elmbyval, &elmalign);
1694  deconstruct_array(arrayval,
1695  ARR_ELEMTYPE(arrayval),
1696  elmlen, elmbyval, elmalign,
1697  &elem_values, &elem_nulls, &num_elems);
1698 
1699  /*
1700  * For generic operators, we assume the probability of success is
1701  * independent for each array element. But for "= ANY" or "<> ALL",
1702  * if the array elements are distinct (which'd typically be the case)
1703  * then the probabilities are disjoint, and we should just sum them.
1704  *
1705  * If we were being really tense we would try to confirm that the
1706  * elements are all distinct, but that would be expensive and it
1707  * doesn't seem to be worth the cycles; it would amount to penalizing
1708  * well-written queries in favor of poorly-written ones. However, we
1709  * do protect ourselves a little bit by checking whether the
1710  * disjointness assumption leads to an impossible (out of range)
1711  * probability; if so, we fall back to the normal calculation.
1712  */
1713  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1714 
1715  for (i = 0; i < num_elems; i++)
1716  {
1717  List *args;
1718  Selectivity s2;
1719 
1720  args = list_make2(leftop,
1721  makeConst(nominal_element_type,
1722  -1,
1723  nominal_element_collation,
1724  elmlen,
1725  elem_values[i],
1726  elem_nulls[i],
1727  elmbyval));
1728  if (is_join_clause)
1729  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1730  clause->inputcollid,
1731  PointerGetDatum(root),
1732  ObjectIdGetDatum(operator),
1733  PointerGetDatum(args),
1734  Int16GetDatum(jointype),
1735  PointerGetDatum(sjinfo)));
1736  else
1737  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1738  clause->inputcollid,
1739  PointerGetDatum(root),
1740  ObjectIdGetDatum(operator),
1741  PointerGetDatum(args),
1742  Int32GetDatum(varRelid)));
1743 
1744  if (useOr)
1745  {
1746  s1 = s1 + s2 - s1 * s2;
1747  if (isEquality)
1748  s1disjoint += s2;
1749  }
1750  else
1751  {
1752  s1 = s1 * s2;
1753  if (isInequality)
1754  s1disjoint += s2 - 1.0;
1755  }
1756  }
1757 
1758  /* accept disjoint-probability estimate if in range */
1759  if ((useOr ? isEquality : isInequality) &&
1760  s1disjoint >= 0.0 && s1disjoint <= 1.0)
1761  s1 = s1disjoint;
1762  }
1763  else if (rightop && IsA(rightop, ArrayExpr) &&
1764  !((ArrayExpr *) rightop)->multidims)
1765  {
1766  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1767  int16 elmlen;
1768  bool elmbyval;
1769  ListCell *l;
1770 
1771  get_typlenbyval(arrayexpr->element_typeid,
1772  &elmlen, &elmbyval);
1773 
1774  /*
1775  * We use the assumption of disjoint probabilities here too, although
1776  * the odds of equal array elements are rather higher if the elements
1777  * are not all constants (which they won't be, else constant folding
1778  * would have reduced the ArrayExpr to a Const). In this path it's
1779  * critical to have the sanity check on the s1disjoint estimate.
1780  */
1781  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1782 
1783  foreach(l, arrayexpr->elements)
1784  {
1785  Node *elem = (Node *) lfirst(l);
1786  List *args;
1787  Selectivity s2;
1788 
1789  /*
1790  * Theoretically, if elem isn't of nominal_element_type we should
1791  * insert a RelabelType, but it seems unlikely that any operator
1792  * estimation function would really care ...
1793  */
1794  args = list_make2(leftop, elem);
1795  if (is_join_clause)
1796  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1797  clause->inputcollid,
1798  PointerGetDatum(root),
1799  ObjectIdGetDatum(operator),
1800  PointerGetDatum(args),
1801  Int16GetDatum(jointype),
1802  PointerGetDatum(sjinfo)));
1803  else
1804  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1805  clause->inputcollid,
1806  PointerGetDatum(root),
1807  ObjectIdGetDatum(operator),
1808  PointerGetDatum(args),
1809  Int32GetDatum(varRelid)));
1810 
1811  if (useOr)
1812  {
1813  s1 = s1 + s2 - s1 * s2;
1814  if (isEquality)
1815  s1disjoint += s2;
1816  }
1817  else
1818  {
1819  s1 = s1 * s2;
1820  if (isInequality)
1821  s1disjoint += s2 - 1.0;
1822  }
1823  }
1824 
1825  /* accept disjoint-probability estimate if in range */
1826  if ((useOr ? isEquality : isInequality) &&
1827  s1disjoint >= 0.0 && s1disjoint <= 1.0)
1828  s1 = s1disjoint;
1829  }
1830  else
1831  {
1832  CaseTestExpr *dummyexpr;
1833  List *args;
1834  Selectivity s2;
1835  int i;
1836 
1837  /*
1838  * We need a dummy rightop to pass to the operator selectivity
1839  * routine. It can be pretty much anything that doesn't look like a
1840  * constant; CaseTestExpr is a convenient choice.
1841  */
1842  dummyexpr = makeNode(CaseTestExpr);
1843  dummyexpr->typeId = nominal_element_type;
1844  dummyexpr->typeMod = -1;
1845  dummyexpr->collation = clause->inputcollid;
1846  args = list_make2(leftop, dummyexpr);
1847  if (is_join_clause)
1848  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1849  clause->inputcollid,
1850  PointerGetDatum(root),
1851  ObjectIdGetDatum(operator),
1852  PointerGetDatum(args),
1853  Int16GetDatum(jointype),
1854  PointerGetDatum(sjinfo)));
1855  else
1856  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1857  clause->inputcollid,
1858  PointerGetDatum(root),
1859  ObjectIdGetDatum(operator),
1860  PointerGetDatum(args),
1861  Int32GetDatum(varRelid)));
1862  s1 = useOr ? 0.0 : 1.0;
1863 
1864  /*
1865  * Arbitrarily assume 10 elements in the eventual array value (see
1866  * also estimate_array_length). We don't risk an assumption of
1867  * disjoint probabilities here.
1868  */
1869  for (i = 0; i < 10; i++)
1870  {
1871  if (useOr)
1872  s1 = s1 + s2 - s1 * s2;
1873  else
1874  s1 = s1 * s2;
1875  }
1876  }
1877 
1878  /* result should be in range, but make sure... */
1879  CLAMP_PROBABILITY(s1);
1880 
1881  return s1;
1882 }
1883 
1884 /*
1885  * Estimate number of elements in the array yielded by an expression.
1886  *
1887  * It's important that this agree with scalararraysel.
1888  */
1889 int
1891 {
1892  /* look through any binary-compatible relabeling of arrayexpr */
1893  arrayexpr = strip_array_coercion(arrayexpr);
1894 
1895  if (arrayexpr && IsA(arrayexpr, Const))
1896  {
1897  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
1898  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
1899  ArrayType *arrayval;
1900 
1901  if (arrayisnull)
1902  return 0;
1903  arrayval = DatumGetArrayTypeP(arraydatum);
1904  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1905  }
1906  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
1907  !((ArrayExpr *) arrayexpr)->multidims)
1908  {
1909  return list_length(((ArrayExpr *) arrayexpr)->elements);
1910  }
1911  else
1912  {
1913  /* default guess --- see also scalararraysel */
1914  return 10;
1915  }
1916 }
1917 
1918 /*
1919  * rowcomparesel - Selectivity of RowCompareExpr Node.
1920  *
1921  * We estimate RowCompare selectivity by considering just the first (high
1922  * order) columns, which makes it equivalent to an ordinary OpExpr. While
1923  * this estimate could be refined by considering additional columns, it
1924  * seems unlikely that we could do a lot better without multi-column
1925  * statistics.
1926  */
1929  RowCompareExpr *clause,
1930  int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1931 {
1932  Selectivity s1;
1933  Oid opno = linitial_oid(clause->opnos);
1934  Oid inputcollid = linitial_oid(clause->inputcollids);
1935  List *opargs;
1936  bool is_join_clause;
1937 
1938  /* Build equivalent arg list for single operator */
1939  opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
1940 
1941  /*
1942  * Decide if it's a join clause. This should match clausesel.c's
1943  * treat_as_join_clause(), except that we intentionally consider only the
1944  * leading columns and not the rest of the clause.
1945  */
1946  if (varRelid != 0)
1947  {
1948  /*
1949  * Caller is forcing restriction mode (eg, because we are examining an
1950  * inner indexscan qual).
1951  */
1952  is_join_clause = false;
1953  }
1954  else if (sjinfo == NULL)
1955  {
1956  /*
1957  * It must be a restriction clause, since it's being evaluated at a
1958  * scan node.
1959  */
1960  is_join_clause = false;
1961  }
1962  else
1963  {
1964  /*
1965  * Otherwise, it's a join if there's more than one relation used.
1966  */
1967  is_join_clause = (NumRelids((Node *) opargs) > 1);
1968  }
1969 
1970  if (is_join_clause)
1971  {
1972  /* Estimate selectivity for a join clause. */
1973  s1 = join_selectivity(root, opno,
1974  opargs,
1975  inputcollid,
1976  jointype,
1977  sjinfo);
1978  }
1979  else
1980  {
1981  /* Estimate selectivity for a restriction clause. */
1982  s1 = restriction_selectivity(root, opno,
1983  opargs,
1984  inputcollid,
1985  varRelid);
1986  }
1987 
1988  return s1;
1989 }
1990 
1991 /*
1992  * eqjoinsel - Join selectivity of "="
1993  */
1994 Datum
1996 {
1997  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1998  Oid operator = PG_GETARG_OID(1);
1999  List *args = (List *) PG_GETARG_POINTER(2);
2000 
2001 #ifdef NOT_USED
2002  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2003 #endif
2005  double selec;
2006  double selec_inner;
2007  VariableStatData vardata1;
2008  VariableStatData vardata2;
2009  double nd1;
2010  double nd2;
2011  bool isdefault1;
2012  bool isdefault2;
2013  Oid opfuncoid;
2014  AttStatsSlot sslot1;
2015  AttStatsSlot sslot2;
2016  Form_pg_statistic stats1 = NULL;
2017  Form_pg_statistic stats2 = NULL;
2018  bool have_mcvs1 = false;
2019  bool have_mcvs2 = false;
2020  bool join_is_reversed;
2021  RelOptInfo *inner_rel;
2022 
2023  get_join_variables(root, args, sjinfo,
2024  &vardata1, &vardata2, &join_is_reversed);
2025 
2026  nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2027  nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2028 
2029  opfuncoid = get_opcode(operator);
2030 
2031  memset(&sslot1, 0, sizeof(sslot1));
2032  memset(&sslot2, 0, sizeof(sslot2));
2033 
2034  if (HeapTupleIsValid(vardata1.statsTuple))
2035  {
2036  /* note we allow use of nullfrac regardless of security check */
2037  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2038  if (statistic_proc_security_check(&vardata1, opfuncoid))
2039  have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2040  STATISTIC_KIND_MCV, InvalidOid,
2042  }
2043 
2044  if (HeapTupleIsValid(vardata2.statsTuple))
2045  {
2046  /* note we allow use of nullfrac regardless of security check */
2047  stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2048  if (statistic_proc_security_check(&vardata2, opfuncoid))
2049  have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2050  STATISTIC_KIND_MCV, InvalidOid,
2052  }
2053 
2054  /* We need to compute the inner-join selectivity in all cases */
2055  selec_inner = eqjoinsel_inner(opfuncoid,
2056  &vardata1, &vardata2,
2057  nd1, nd2,
2058  isdefault1, isdefault2,
2059  &sslot1, &sslot2,
2060  stats1, stats2,
2061  have_mcvs1, have_mcvs2);
2062 
2063  switch (sjinfo->jointype)
2064  {
2065  case JOIN_INNER:
2066  case JOIN_LEFT:
2067  case JOIN_FULL:
2068  selec = selec_inner;
2069  break;
2070  case JOIN_SEMI:
2071  case JOIN_ANTI:
2072 
2073  /*
2074  * Look up the join's inner relation. min_righthand is sufficient
2075  * information because neither SEMI nor ANTI joins permit any
2076  * reassociation into or out of their RHS, so the righthand will
2077  * always be exactly that set of rels.
2078  */
2079  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2080 
2081  if (!join_is_reversed)
2082  selec = eqjoinsel_semi(opfuncoid,
2083  &vardata1, &vardata2,
2084  nd1, nd2,
2085  isdefault1, isdefault2,
2086  &sslot1, &sslot2,
2087  stats1, stats2,
2088  have_mcvs1, have_mcvs2,
2089  inner_rel);
2090  else
2091  {
2092  Oid commop = get_commutator(operator);
2093  Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2094 
2095  selec = eqjoinsel_semi(commopfuncoid,
2096  &vardata2, &vardata1,
2097  nd2, nd1,
2098  isdefault2, isdefault1,
2099  &sslot2, &sslot1,
2100  stats2, stats1,
2101  have_mcvs2, have_mcvs1,
2102  inner_rel);
2103  }
2104 
2105  /*
2106  * We should never estimate the output of a semijoin to be more
2107  * rows than we estimate for an inner join with the same input
2108  * rels and join condition; it's obviously impossible for that to
2109  * happen. The former estimate is N1 * Ssemi while the latter is
2110  * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner. Doing
2111  * this is worthwhile because of the shakier estimation rules we
2112  * use in eqjoinsel_semi, particularly in cases where it has to
2113  * punt entirely.
2114  */
2115  selec = Min(selec, inner_rel->rows * selec_inner);
2116  break;
2117  default:
2118  /* other values not expected here */
2119  elog(ERROR, "unrecognized join type: %d",
2120  (int) sjinfo->jointype);
2121  selec = 0; /* keep compiler quiet */
2122  break;
2123  }
2124 
2125  free_attstatsslot(&sslot1);
2126  free_attstatsslot(&sslot2);
2127 
2128  ReleaseVariableStats(vardata1);
2129  ReleaseVariableStats(vardata2);
2130 
2131  CLAMP_PROBABILITY(selec);
2132 
2133  PG_RETURN_FLOAT8((float8) selec);
2134 }
2135 
2136 /*
2137  * eqjoinsel_inner --- eqjoinsel for normal inner join
2138  *
2139  * We also use this for LEFT/FULL outer joins; it's not presently clear
2140  * that it's worth trying to distinguish them here.
2141  */
2142 static double
2144  VariableStatData *vardata1, VariableStatData *vardata2,
2145  double nd1, double nd2,
2146  bool isdefault1, bool isdefault2,
2147  AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2148  Form_pg_statistic stats1, Form_pg_statistic stats2,
2149  bool have_mcvs1, bool have_mcvs2)
2150 {
2151  double selec;
2152 
2153  if (have_mcvs1 && have_mcvs2)
2154  {
2155  /*
2156  * We have most-common-value lists for both relations. Run through
2157  * the lists to see which MCVs actually join to each other with the
2158  * given operator. This allows us to determine the exact join
2159  * selectivity for the portion of the relations represented by the MCV
2160  * lists. We still have to estimate for the remaining population, but
2161  * in a skewed distribution this gives us a big leg up in accuracy.
2162  * For motivation see the analysis in Y. Ioannidis and S.
2163  * Christodoulakis, "On the propagation of errors in the size of join
2164  * results", Technical Report 1018, Computer Science Dept., University
2165  * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2166  */
2167  FmgrInfo eqproc;
2168  bool *hasmatch1;
2169  bool *hasmatch2;
2170  double nullfrac1 = stats1->stanullfrac;
2171  double nullfrac2 = stats2->stanullfrac;
2172  double matchprodfreq,
2173  matchfreq1,
2174  matchfreq2,
2175  unmatchfreq1,
2176  unmatchfreq2,
2177  otherfreq1,
2178  otherfreq2,
2179  totalsel1,
2180  totalsel2;
2181  int i,
2182  nmatches;
2183 
2184  fmgr_info(opfuncoid, &eqproc);
2185  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2186  hasmatch2 = (bool *) palloc0(sslot2->nvalues * sizeof(bool));
2187 
2188  /*
2189  * Note we assume that each MCV will match at most one member of the
2190  * other MCV list. If the operator isn't really equality, there could
2191  * be multiple matches --- but we don't look for them, both for speed
2192  * and because the math wouldn't add up...
2193  */
2194  matchprodfreq = 0.0;
2195  nmatches = 0;
2196  for (i = 0; i < sslot1->nvalues; i++)
2197  {
2198  int j;
2199 
2200  for (j = 0; j < sslot2->nvalues; j++)
2201  {
2202  if (hasmatch2[j])
2203  continue;
2204  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2205  sslot1->stacoll,
2206  sslot1->values[i],
2207  sslot2->values[j])))
2208  {
2209  hasmatch1[i] = hasmatch2[j] = true;
2210  matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2211  nmatches++;
2212  break;
2213  }
2214  }
2215  }
2216  CLAMP_PROBABILITY(matchprodfreq);
2217  /* Sum up frequencies of matched and unmatched MCVs */
2218  matchfreq1 = unmatchfreq1 = 0.0;
2219  for (i = 0; i < sslot1->nvalues; i++)
2220  {
2221  if (hasmatch1[i])
2222  matchfreq1 += sslot1->numbers[i];
2223  else
2224  unmatchfreq1 += sslot1->numbers[i];
2225  }
2226  CLAMP_PROBABILITY(matchfreq1);
2227  CLAMP_PROBABILITY(unmatchfreq1);
2228  matchfreq2 = unmatchfreq2 = 0.0;
2229  for (i = 0; i < sslot2->nvalues; i++)
2230  {
2231  if (hasmatch2[i])
2232  matchfreq2 += sslot2->numbers[i];
2233  else
2234  unmatchfreq2 += sslot2->numbers[i];
2235  }
2236  CLAMP_PROBABILITY(matchfreq2);
2237  CLAMP_PROBABILITY(unmatchfreq2);
2238  pfree(hasmatch1);
2239  pfree(hasmatch2);
2240 
2241  /*
2242  * Compute total frequency of non-null values that are not in the MCV
2243  * lists.
2244  */
2245  otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2246  otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2247  CLAMP_PROBABILITY(otherfreq1);
2248  CLAMP_PROBABILITY(otherfreq2);
2249 
2250  /*
2251  * We can estimate the total selectivity from the point of view of
2252  * relation 1 as: the known selectivity for matched MCVs, plus
2253  * unmatched MCVs that are assumed to match against random members of
2254  * relation 2's non-MCV population, plus non-MCV values that are
2255  * assumed to match against random members of relation 2's unmatched
2256  * MCVs plus non-MCV values.
2257  */
2258  totalsel1 = matchprodfreq;
2259  if (nd2 > sslot2->nvalues)
2260  totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2261  if (nd2 > nmatches)
2262  totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2263  (nd2 - nmatches);
2264  /* Same estimate from the point of view of relation 2. */
2265  totalsel2 = matchprodfreq;
2266  if (nd1 > sslot1->nvalues)
2267  totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2268  if (nd1 > nmatches)
2269  totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2270  (nd1 - nmatches);
2271 
2272  /*
2273  * Use the smaller of the two estimates. This can be justified in
2274  * essentially the same terms as given below for the no-stats case: to
2275  * a first approximation, we are estimating from the point of view of
2276  * the relation with smaller nd.
2277  */
2278  selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2279  }
2280  else
2281  {
2282  /*
2283  * We do not have MCV lists for both sides. Estimate the join
2284  * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2285  * is plausible if we assume that the join operator is strict and the
2286  * non-null values are about equally distributed: a given non-null
2287  * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2288  * of rel2, so total join rows are at most
2289  * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2290  * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2291  * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2292  * with MIN() is an upper bound. Using the MIN() means we estimate
2293  * from the point of view of the relation with smaller nd (since the
2294  * larger nd is determining the MIN). It is reasonable to assume that
2295  * most tuples in this rel will have join partners, so the bound is
2296  * probably reasonably tight and should be taken as-is.
2297  *
2298  * XXX Can we be smarter if we have an MCV list for just one side? It
2299  * seems that if we assume equal distribution for the other side, we
2300  * end up with the same answer anyway.
2301  */
2302  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2303  double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2304 
2305  selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2306  if (nd1 > nd2)
2307  selec /= nd1;
2308  else
2309  selec /= nd2;
2310  }
2311 
2312  return selec;
2313 }
2314 
2315 /*
2316  * eqjoinsel_semi --- eqjoinsel for semi join
2317  *
2318  * (Also used for anti join, which we are supposed to estimate the same way.)
2319  * Caller has ensured that vardata1 is the LHS variable.
2320  * Unlike eqjoinsel_inner, we have to cope with opfuncoid being InvalidOid.
2321  */
2322 static double
2324  VariableStatData *vardata1, VariableStatData *vardata2,
2325  double nd1, double nd2,
2326  bool isdefault1, bool isdefault2,
2327  AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2328  Form_pg_statistic stats1, Form_pg_statistic stats2,
2329  bool have_mcvs1, bool have_mcvs2,
2330  RelOptInfo *inner_rel)
2331 {
2332  double selec;
2333 
2334  /*
2335  * We clamp nd2 to be not more than what we estimate the inner relation's
2336  * size to be. This is intuitively somewhat reasonable since obviously
2337  * there can't be more than that many distinct values coming from the
2338  * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2339  * likewise) is that this is the only pathway by which restriction clauses
2340  * applied to the inner rel will affect the join result size estimate,
2341  * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2342  * only the outer rel's size. If we clamped nd1 we'd be double-counting
2343  * the selectivity of outer-rel restrictions.
2344  *
2345  * We can apply this clamping both with respect to the base relation from
2346  * which the join variable comes (if there is just one), and to the
2347  * immediate inner input relation of the current join.
2348  *
2349  * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2350  * great, maybe, but it didn't come out of nowhere either. This is most
2351  * helpful when the inner relation is empty and consequently has no stats.
2352  */
2353  if (vardata2->rel)
2354  {
2355  if (nd2 >= vardata2->rel->rows)
2356  {
2357  nd2 = vardata2->rel->rows;
2358  isdefault2 = false;
2359  }
2360  }
2361  if (nd2 >= inner_rel->rows)
2362  {
2363  nd2 = inner_rel->rows;
2364  isdefault2 = false;
2365  }
2366 
2367  if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2368  {
2369  /*
2370  * We have most-common-value lists for both relations. Run through
2371  * the lists to see which MCVs actually join to each other with the
2372  * given operator. This allows us to determine the exact join
2373  * selectivity for the portion of the relations represented by the MCV
2374  * lists. We still have to estimate for the remaining population, but
2375  * in a skewed distribution this gives us a big leg up in accuracy.
2376  */
2377  FmgrInfo eqproc;
2378  bool *hasmatch1;
2379  bool *hasmatch2;
2380  double nullfrac1 = stats1->stanullfrac;
2381  double matchfreq1,
2382  uncertainfrac,
2383  uncertain;
2384  int i,
2385  nmatches,
2386  clamped_nvalues2;
2387 
2388  /*
2389  * The clamping above could have resulted in nd2 being less than
2390  * sslot2->nvalues; in which case, we assume that precisely the nd2
2391  * most common values in the relation will appear in the join input,
2392  * and so compare to only the first nd2 members of the MCV list. Of
2393  * course this is frequently wrong, but it's the best bet we can make.
2394  */
2395  clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2396 
2397  fmgr_info(opfuncoid, &eqproc);
2398  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2399  hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2400 
2401  /*
2402  * Note we assume that each MCV will match at most one member of the
2403  * other MCV list. If the operator isn't really equality, there could
2404  * be multiple matches --- but we don't look for them, both for speed
2405  * and because the math wouldn't add up...
2406  */
2407  nmatches = 0;
2408  for (i = 0; i < sslot1->nvalues; i++)
2409  {
2410  int j;
2411 
2412  for (j = 0; j < clamped_nvalues2; j++)
2413  {
2414  if (hasmatch2[j])
2415  continue;
2416  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2417  sslot1->stacoll,
2418  sslot1->values[i],
2419  sslot2->values[j])))
2420  {
2421  hasmatch1[i] = hasmatch2[j] = true;
2422  nmatches++;
2423  break;
2424  }
2425  }
2426  }
2427  /* Sum up frequencies of matched MCVs */
2428  matchfreq1 = 0.0;
2429  for (i = 0; i < sslot1->nvalues; i++)
2430  {
2431  if (hasmatch1[i])
2432  matchfreq1 += sslot1->numbers[i];
2433  }
2434  CLAMP_PROBABILITY(matchfreq1);
2435  pfree(hasmatch1);
2436  pfree(hasmatch2);
2437 
2438  /*
2439  * Now we need to estimate the fraction of relation 1 that has at
2440  * least one join partner. We know for certain that the matched MCVs
2441  * do, so that gives us a lower bound, but we're really in the dark
2442  * about everything else. Our crude approach is: if nd1 <= nd2 then
2443  * assume all non-null rel1 rows have join partners, else assume for
2444  * the uncertain rows that a fraction nd2/nd1 have join partners. We
2445  * can discount the known-matched MCVs from the distinct-values counts
2446  * before doing the division.
2447  *
2448  * Crude as the above is, it's completely useless if we don't have
2449  * reliable ndistinct values for both sides. Hence, if either nd1 or
2450  * nd2 is default, punt and assume half of the uncertain rows have
2451  * join partners.
2452  */
2453  if (!isdefault1 && !isdefault2)
2454  {
2455  nd1 -= nmatches;
2456  nd2 -= nmatches;
2457  if (nd1 <= nd2 || nd2 < 0)
2458  uncertainfrac = 1.0;
2459  else
2460  uncertainfrac = nd2 / nd1;
2461  }
2462  else
2463  uncertainfrac = 0.5;
2464  uncertain = 1.0 - matchfreq1 - nullfrac1;
2465  CLAMP_PROBABILITY(uncertain);
2466  selec = matchfreq1 + uncertainfrac * uncertain;
2467  }
2468  else
2469  {
2470  /*
2471  * Without MCV lists for both sides, we can only use the heuristic
2472  * about nd1 vs nd2.
2473  */
2474  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2475 
2476  if (!isdefault1 && !isdefault2)
2477  {
2478  if (nd1 <= nd2 || nd2 < 0)
2479  selec = 1.0 - nullfrac1;
2480  else
2481  selec = (nd2 / nd1) * (1.0 - nullfrac1);
2482  }
2483  else
2484  selec = 0.5 * (1.0 - nullfrac1);
2485  }
2486 
2487  return selec;
2488 }
2489 
2490 /*
2491  * neqjoinsel - Join selectivity of "!="
2492  */
2493 Datum
2495 {
2496  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2497  Oid operator = PG_GETARG_OID(1);
2498  List *args = (List *) PG_GETARG_POINTER(2);
2499  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2501  float8 result;
2502 
2503  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2504  {
2505  /*
2506  * For semi-joins, if there is more than one distinct value in the RHS
2507  * relation then every non-null LHS row must find a row to join since
2508  * it can only be equal to one of them. We'll assume that there is
2509  * always more than one distinct RHS value for the sake of stability,
2510  * though in theory we could have special cases for empty RHS
2511  * (selectivity = 0) and single-distinct-value RHS (selectivity =
2512  * fraction of LHS that has the same value as the single RHS value).
2513  *
2514  * For anti-joins, if we use the same assumption that there is more
2515  * than one distinct key in the RHS relation, then every non-null LHS
2516  * row must be suppressed by the anti-join.
2517  *
2518  * So either way, the selectivity estimate should be 1 - nullfrac.
2519  */
2520  VariableStatData leftvar;
2521  VariableStatData rightvar;
2522  bool reversed;
2523  HeapTuple statsTuple;
2524  double nullfrac;
2525 
2526  get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
2527  statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
2528  if (HeapTupleIsValid(statsTuple))
2529  nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
2530  else
2531  nullfrac = 0.0;
2532  ReleaseVariableStats(leftvar);
2533  ReleaseVariableStats(rightvar);
2534 
2535  result = 1.0 - nullfrac;
2536  }
2537  else
2538  {
2539  /*
2540  * We want 1 - eqjoinsel() where the equality operator is the one
2541  * associated with this != operator, that is, its negator.
2542  */
2543  Oid eqop = get_negator(operator);
2544 
2545  if (eqop)
2546  {
2548  PointerGetDatum(root),
2549  ObjectIdGetDatum(eqop),
2550  PointerGetDatum(args),
2551  Int16GetDatum(jointype),
2552  PointerGetDatum(sjinfo)));
2553  }
2554  else
2555  {
2556  /* Use default selectivity (should we raise an error instead?) */
2557  result = DEFAULT_EQ_SEL;
2558  }
2559  result = 1.0 - result;
2560  }
2561 
2562  PG_RETURN_FLOAT8(result);
2563 }
2564 
2565 /*
2566  * scalarltjoinsel - Join selectivity of "<" for scalars
2567  */
2568 Datum
2570 {
2572 }
2573 
2574 /*
2575  * scalarlejoinsel - Join selectivity of "<=" for scalars
2576  */
2577 Datum
2579 {
2581 }
2582 
2583 /*
2584  * scalargtjoinsel - Join selectivity of ">" for scalars
2585  */
2586 Datum
2588 {
2590 }
2591 
2592 /*
2593  * scalargejoinsel - Join selectivity of ">=" for scalars
2594  */
2595 Datum
2597 {
2599 }
2600 
2601 
2602 /*
2603  * mergejoinscansel - Scan selectivity of merge join.
2604  *
2605  * A merge join will stop as soon as it exhausts either input stream.
2606  * Therefore, if we can estimate the ranges of both input variables,
2607  * we can estimate how much of the input will actually be read. This
2608  * can have a considerable impact on the cost when using indexscans.
2609  *
2610  * Also, we can estimate how much of each input has to be read before the
2611  * first join pair is found, which will affect the join's startup time.
2612  *
2613  * clause should be a clause already known to be mergejoinable. opfamily,
2614  * strategy, and nulls_first specify the sort ordering being used.
2615  *
2616  * The outputs are:
2617  * *leftstart is set to the fraction of the left-hand variable expected
2618  * to be scanned before the first join pair is found (0 to 1).
2619  * *leftend is set to the fraction of the left-hand variable expected
2620  * to be scanned before the join terminates (0 to 1).
2621  * *rightstart, *rightend similarly for the right-hand variable.
2622  */
2623 void
2625  Oid opfamily, int strategy, bool nulls_first,
2626  Selectivity *leftstart, Selectivity *leftend,
2627  Selectivity *rightstart, Selectivity *rightend)
2628 {
2629  Node *left,
2630  *right;
2631  VariableStatData leftvar,
2632  rightvar;
2633  int op_strategy;
2634  Oid op_lefttype;
2635  Oid op_righttype;
2636  Oid opno,
2637  lsortop,
2638  rsortop,
2639  lstatop,
2640  rstatop,
2641  ltop,
2642  leop,
2643  revltop,
2644  revleop;
2645  bool isgt;
2646  Datum leftmin,
2647  leftmax,
2648  rightmin,
2649  rightmax;
2650  double selec;
2651 
2652  /* Set default results if we can't figure anything out. */
2653  /* XXX should default "start" fraction be a bit more than 0? */
2654  *leftstart = *rightstart = 0.0;
2655  *leftend = *rightend = 1.0;
2656 
2657  /* Deconstruct the merge clause */
2658  if (!is_opclause(clause))
2659  return; /* shouldn't happen */
2660  opno = ((OpExpr *) clause)->opno;
2661  left = get_leftop((Expr *) clause);
2662  right = get_rightop((Expr *) clause);
2663  if (!right)
2664  return; /* shouldn't happen */
2665 
2666  /* Look for stats for the inputs */
2667  examine_variable(root, left, 0, &leftvar);
2668  examine_variable(root, right, 0, &rightvar);
2669 
2670  /* Extract the operator's declared left/right datatypes */
2671  get_op_opfamily_properties(opno, opfamily, false,
2672  &op_strategy,
2673  &op_lefttype,
2674  &op_righttype);
2675  Assert(op_strategy == BTEqualStrategyNumber);
2676 
2677  /*
2678  * Look up the various operators we need. If we don't find them all, it
2679  * probably means the opfamily is broken, but we just fail silently.
2680  *
2681  * Note: we expect that pg_statistic histograms will be sorted by the '<'
2682  * operator, regardless of which sort direction we are considering.
2683  */
2684  switch (strategy)
2685  {
2686  case BTLessStrategyNumber:
2687  isgt = false;
2688  if (op_lefttype == op_righttype)
2689  {
2690  /* easy case */
2691  ltop = get_opfamily_member(opfamily,
2692  op_lefttype, op_righttype,
2694  leop = get_opfamily_member(opfamily,
2695  op_lefttype, op_righttype,
2697  lsortop = ltop;
2698  rsortop = ltop;
2699  lstatop = lsortop;
2700  rstatop = rsortop;
2701  revltop = ltop;
2702  revleop = leop;
2703  }
2704  else
2705  {
2706  ltop = get_opfamily_member(opfamily,
2707  op_lefttype, op_righttype,
2709  leop = get_opfamily_member(opfamily,
2710  op_lefttype, op_righttype,
2712  lsortop = get_opfamily_member(opfamily,
2713  op_lefttype, op_lefttype,
2715  rsortop = get_opfamily_member(opfamily,
2716  op_righttype, op_righttype,
2718  lstatop = lsortop;
2719  rstatop = rsortop;
2720  revltop = get_opfamily_member(opfamily,
2721  op_righttype, op_lefttype,
2723  revleop = get_opfamily_member(opfamily,
2724  op_righttype, op_lefttype,
2726  }
2727  break;
2729  /* descending-order case */
2730  isgt = true;
2731  if (op_lefttype == op_righttype)
2732  {
2733  /* easy case */
2734  ltop = get_opfamily_member(opfamily,
2735  op_lefttype, op_righttype,
2737  leop = get_opfamily_member(opfamily,
2738  op_lefttype, op_righttype,
2740  lsortop = ltop;
2741  rsortop = ltop;
2742  lstatop = get_opfamily_member(opfamily,
2743  op_lefttype, op_lefttype,
2745  rstatop = lstatop;
2746  revltop = ltop;
2747  revleop = leop;
2748  }
2749  else
2750  {
2751  ltop = get_opfamily_member(opfamily,
2752  op_lefttype, op_righttype,
2754  leop = get_opfamily_member(opfamily,
2755  op_lefttype, op_righttype,
2757  lsortop = get_opfamily_member(opfamily,
2758  op_lefttype, op_lefttype,
2760  rsortop = get_opfamily_member(opfamily,
2761  op_righttype, op_righttype,
2763  lstatop = get_opfamily_member(opfamily,
2764  op_lefttype, op_lefttype,
2766  rstatop = get_opfamily_member(opfamily,
2767  op_righttype, op_righttype,
2769  revltop = get_opfamily_member(opfamily,
2770  op_righttype, op_lefttype,
2772  revleop = get_opfamily_member(opfamily,
2773  op_righttype, op_lefttype,
2775  }
2776  break;
2777  default:
2778  goto fail; /* shouldn't get here */
2779  }
2780 
2781  if (!OidIsValid(lsortop) ||
2782  !OidIsValid(rsortop) ||
2783  !OidIsValid(lstatop) ||
2784  !OidIsValid(rstatop) ||
2785  !OidIsValid(ltop) ||
2786  !OidIsValid(leop) ||
2787  !OidIsValid(revltop) ||
2788  !OidIsValid(revleop))
2789  goto fail; /* insufficient info in catalogs */
2790 
2791  /* Try to get ranges of both inputs */
2792  if (!isgt)
2793  {
2794  if (!get_variable_range(root, &leftvar, lstatop,
2795  &leftmin, &leftmax))
2796  goto fail; /* no range available from stats */
2797  if (!get_variable_range(root, &rightvar, rstatop,
2798  &rightmin, &rightmax))
2799  goto fail; /* no range available from stats */
2800  }
2801  else
2802  {
2803  /* need to swap the max and min */
2804  if (!get_variable_range(root, &leftvar, lstatop,
2805  &leftmax, &leftmin))
2806  goto fail; /* no range available from stats */
2807  if (!get_variable_range(root, &rightvar, rstatop,
2808  &rightmax, &rightmin))
2809  goto fail; /* no range available from stats */
2810  }
2811 
2812  /*
2813  * Now, the fraction of the left variable that will be scanned is the
2814  * fraction that's <= the right-side maximum value. But only believe
2815  * non-default estimates, else stick with our 1.0.
2816  */
2817  selec = scalarineqsel(root, leop, isgt, true, &leftvar,
2818  rightmax, op_righttype);
2819  if (selec != DEFAULT_INEQ_SEL)
2820  *leftend = selec;
2821 
2822  /* And similarly for the right variable. */
2823  selec = scalarineqsel(root, revleop, isgt, true, &rightvar,
2824  leftmax, op_lefttype);
2825  if (selec != DEFAULT_INEQ_SEL)
2826  *rightend = selec;
2827 
2828  /*
2829  * Only one of the two "end" fractions can really be less than 1.0;
2830  * believe the smaller estimate and reset the other one to exactly 1.0. If
2831  * we get exactly equal estimates (as can easily happen with self-joins),
2832  * believe neither.
2833  */
2834  if (*leftend > *rightend)
2835  *leftend = 1.0;
2836  else if (*leftend < *rightend)
2837  *rightend = 1.0;
2838  else
2839  *leftend = *rightend = 1.0;
2840 
2841  /*
2842  * Also, the fraction of the left variable that will be scanned before the
2843  * first join pair is found is the fraction that's < the right-side
2844  * minimum value. But only believe non-default estimates, else stick with
2845  * our own default.
2846  */
2847  selec = scalarineqsel(root, ltop, isgt, false, &leftvar,
2848  rightmin, op_righttype);
2849  if (selec != DEFAULT_INEQ_SEL)
2850  *leftstart = selec;
2851 
2852  /* And similarly for the right variable. */
2853  selec = scalarineqsel(root, revltop, isgt, false, &rightvar,
2854  leftmin, op_lefttype);
2855  if (selec != DEFAULT_INEQ_SEL)
2856  *rightstart = selec;
2857 
2858  /*
2859  * Only one of the two "start" fractions can really be more than zero;
2860  * believe the larger estimate and reset the other one to exactly 0.0. If
2861  * we get exactly equal estimates (as can easily happen with self-joins),
2862  * believe neither.
2863  */
2864  if (*leftstart < *rightstart)
2865  *leftstart = 0.0;
2866  else if (*leftstart > *rightstart)
2867  *rightstart = 0.0;
2868  else
2869  *leftstart = *rightstart = 0.0;
2870 
2871  /*
2872  * If the sort order is nulls-first, we're going to have to skip over any
2873  * nulls too. These would not have been counted by scalarineqsel, and we
2874  * can safely add in this fraction regardless of whether we believe
2875  * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
2876  */
2877  if (nulls_first)
2878  {
2879  Form_pg_statistic stats;
2880 
2881  if (HeapTupleIsValid(leftvar.statsTuple))
2882  {
2883  stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
2884  *leftstart += stats->stanullfrac;
2885  CLAMP_PROBABILITY(*leftstart);
2886  *leftend += stats->stanullfrac;
2887  CLAMP_PROBABILITY(*leftend);
2888  }
2889  if (HeapTupleIsValid(rightvar.statsTuple))
2890  {
2891  stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
2892  *rightstart += stats->stanullfrac;
2893  CLAMP_PROBABILITY(*rightstart);
2894  *rightend += stats->stanullfrac;
2895  CLAMP_PROBABILITY(*rightend);
2896  }
2897  }
2898 
2899  /* Disbelieve start >= end, just in case that can happen */
2900  if (*leftstart >= *leftend)
2901  {
2902  *leftstart = 0.0;
2903  *leftend = 1.0;
2904  }
2905  if (*rightstart >= *rightend)
2906  {
2907  *rightstart = 0.0;
2908  *rightend = 1.0;
2909  }
2910 
2911 fail:
2912  ReleaseVariableStats(leftvar);
2913  ReleaseVariableStats(rightvar);
2914 }
2915 
2916 
2917 /*
2918  * Helper routine for estimate_num_groups: add an item to a list of
2919  * GroupVarInfos, but only if it's not known equal to any of the existing
2920  * entries.
2921  */
2922 typedef struct
2923 {
2924  Node *var; /* might be an expression, not just a Var */
2925  RelOptInfo *rel; /* relation it belongs to */
2926  double ndistinct; /* # distinct values */
2927 } GroupVarInfo;
2928 
2929 static List *
2931  Node *var, VariableStatData *vardata)
2932 {
2933  GroupVarInfo *varinfo;
2934  double ndistinct;
2935  bool isdefault;
2936  ListCell *lc;
2937 
2938  ndistinct = get_variable_numdistinct(vardata, &isdefault);
2939 
2940  foreach(lc, varinfos)
2941  {
2942  varinfo = (GroupVarInfo *) lfirst(lc);
2943 
2944  /* Drop exact duplicates */
2945  if (equal(var, varinfo->var))
2946  return varinfos;
2947 
2948  /*
2949  * Drop known-equal vars, but only if they belong to different
2950  * relations (see comments for estimate_num_groups)
2951  */
2952  if (vardata->rel != varinfo->rel &&
2953  exprs_known_equal(root, var, varinfo->var))
2954  {
2955  if (varinfo->ndistinct <= ndistinct)
2956  {
2957  /* Keep older item, forget new one */
2958  return varinfos;
2959  }
2960  else
2961  {
2962  /* Delete the older item */
2963  varinfos = foreach_delete_current(varinfos, lc);
2964  }
2965  }
2966  }
2967 
2968  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
2969 
2970  varinfo->var = var;
2971  varinfo->rel = vardata->rel;
2972  varinfo->ndistinct = ndistinct;
2973  varinfos = lappend(varinfos, varinfo);
2974  return varinfos;
2975 }
2976 
2977 /*
2978  * estimate_num_groups - Estimate number of groups in a grouped query
2979  *
2980  * Given a query having a GROUP BY clause, estimate how many groups there
2981  * will be --- ie, the number of distinct combinations of the GROUP BY
2982  * expressions.
2983  *
2984  * This routine is also used to estimate the number of rows emitted by
2985  * a DISTINCT filtering step; that is an isomorphic problem. (Note:
2986  * actually, we only use it for DISTINCT when there's no grouping or
2987  * aggregation ahead of the DISTINCT.)
2988  *
2989  * Inputs:
2990  * root - the query
2991  * groupExprs - list of expressions being grouped by
2992  * input_rows - number of rows estimated to arrive at the group/unique
2993  * filter step
2994  * pgset - NULL, or a List** pointing to a grouping set to filter the
2995  * groupExprs against
2996  *
2997  * Given the lack of any cross-correlation statistics in the system, it's
2998  * impossible to do anything really trustworthy with GROUP BY conditions
2999  * involving multiple Vars. We should however avoid assuming the worst
3000  * case (all possible cross-product terms actually appear as groups) since
3001  * very often the grouped-by Vars are highly correlated. Our current approach
3002  * is as follows:
3003  * 1. Expressions yielding boolean are assumed to contribute two groups,
3004  * independently of their content, and are ignored in the subsequent
3005  * steps. This is mainly because tests like "col IS NULL" break the
3006  * heuristic used in step 2 especially badly.
3007  * 2. Reduce the given expressions to a list of unique Vars used. For
3008  * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3009  * It is clearly correct not to count the same Var more than once.
3010  * It is also reasonable to treat f(x) the same as x: f() cannot
3011  * increase the number of distinct values (unless it is volatile,
3012  * which we consider unlikely for grouping), but it probably won't
3013  * reduce the number of distinct values much either.
3014  * As a special case, if a GROUP BY expression can be matched to an
3015  * expressional index for which we have statistics, then we treat the
3016  * whole expression as though it were just a Var.
3017  * 3. If the list contains Vars of different relations that are known equal
3018  * due to equivalence classes, then drop all but one of the Vars from each
3019  * known-equal set, keeping the one with smallest estimated # of values
3020  * (since the extra values of the others can't appear in joined rows).
3021  * Note the reason we only consider Vars of different relations is that
3022  * if we considered ones of the same rel, we'd be double-counting the
3023  * restriction selectivity of the equality in the next step.
3024  * 4. For Vars within a single source rel, we multiply together the numbers
3025  * of values, clamp to the number of rows in the rel (divided by 10 if
3026  * more than one Var), and then multiply by a factor based on the
3027  * selectivity of the restriction clauses for that rel. When there's
3028  * more than one Var, the initial product is probably too high (it's the
3029  * worst case) but clamping to a fraction of the rel's rows seems to be a
3030  * helpful heuristic for not letting the estimate get out of hand. (The
3031  * factor of 10 is derived from pre-Postgres-7.4 practice.) The factor
3032  * we multiply by to adjust for the restriction selectivity assumes that
3033  * the restriction clauses are independent of the grouping, which may not
3034  * be a valid assumption, but it's hard to do better.
3035  * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3036  * rel, and multiply the results together.
3037  * Note that rels not containing grouped Vars are ignored completely, as are
3038  * join clauses. Such rels cannot increase the number of groups, and we
3039  * assume such clauses do not reduce the number either (somewhat bogus,
3040  * but we don't have the info to do better).
3041  */
3042 double
3043 estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3044  List **pgset)
3045 {
3046  List *varinfos = NIL;
3047  double srf_multiplier = 1.0;
3048  double numdistinct;
3049  ListCell *l;
3050  int i;
3051 
3052  /*
3053  * We don't ever want to return an estimate of zero groups, as that tends
3054  * to lead to division-by-zero and other unpleasantness. The input_rows
3055  * estimate is usually already at least 1, but clamp it just in case it
3056  * isn't.
3057  */
3058  input_rows = clamp_row_est(input_rows);
3059 
3060  /*
3061  * If no grouping columns, there's exactly one group. (This can't happen
3062  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3063  * corner cases with set operations.)
3064  */
3065  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3066  return 1.0;
3067 
3068  /*
3069  * Count groups derived from boolean grouping expressions. For other
3070  * expressions, find the unique Vars used, treating an expression as a Var
3071  * if we can find stats for it. For each one, record the statistical
3072  * estimate of number of distinct values (total in its table, without
3073  * regard for filtering).
3074  */
3075  numdistinct = 1.0;
3076 
3077  i = 0;
3078  foreach(l, groupExprs)
3079  {
3080  Node *groupexpr = (Node *) lfirst(l);
3081  double this_srf_multiplier;
3082  VariableStatData vardata;
3083  List *varshere;
3084  ListCell *l2;
3085 
3086  /* is expression in this grouping set? */
3087  if (pgset && !list_member_int(*pgset, i++))
3088  continue;
3089 
3090  /*
3091  * Set-returning functions in grouping columns are a bit problematic.
3092  * The code below will effectively ignore their SRF nature and come up
3093  * with a numdistinct estimate as though they were scalar functions.
3094  * We compensate by scaling up the end result by the largest SRF
3095  * rowcount estimate. (This will be an overestimate if the SRF
3096  * produces multiple copies of any output value, but it seems best to
3097  * assume the SRF's outputs are distinct. In any case, it's probably
3098  * pointless to worry too much about this without much better
3099  * estimates for SRF output rowcounts than we have today.)
3100  */
3101  this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3102  if (srf_multiplier < this_srf_multiplier)
3103  srf_multiplier = this_srf_multiplier;
3104 
3105  /* Short-circuit for expressions returning boolean */
3106  if (exprType(groupexpr) == BOOLOID)
3107  {
3108  numdistinct *= 2.0;
3109  continue;
3110  }
3111 
3112  /*
3113  * If examine_variable is able to deduce anything about the GROUP BY
3114  * expression, treat it as a single variable even if it's really more
3115  * complicated.
3116  */
3117  examine_variable(root, groupexpr, 0, &vardata);
3118  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3119  {
3120  varinfos = add_unique_group_var(root, varinfos,
3121  groupexpr, &vardata);
3122  ReleaseVariableStats(vardata);
3123  continue;
3124  }
3125  ReleaseVariableStats(vardata);
3126 
3127  /*
3128  * Else pull out the component Vars. Handle PlaceHolderVars by
3129  * recursing into their arguments (effectively assuming that the
3130  * PlaceHolderVar doesn't change the number of groups, which boils
3131  * down to ignoring the possible addition of nulls to the result set).
3132  */
3133  varshere = pull_var_clause(groupexpr,
3137 
3138  /*
3139  * If we find any variable-free GROUP BY item, then either it is a
3140  * constant (and we can ignore it) or it contains a volatile function;
3141  * in the latter case we punt and assume that each input row will
3142  * yield a distinct group.
3143  */
3144  if (varshere == NIL)
3145  {
3146  if (contain_volatile_functions(groupexpr))
3147  return input_rows;
3148  continue;
3149  }
3150 
3151  /*
3152  * Else add variables to varinfos list
3153  */
3154  foreach(l2, varshere)
3155  {
3156  Node *var = (Node *) lfirst(l2);
3157 
3158  examine_variable(root, var, 0, &vardata);
3159  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3160  ReleaseVariableStats(vardata);
3161  }
3162  }
3163 
3164  /*
3165  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3166  * list.
3167  */
3168  if (varinfos == NIL)
3169  {
3170  /* Apply SRF multiplier as we would do in the long path */
3171  numdistinct *= srf_multiplier;
3172  /* Round off */
3173  numdistinct = ceil(numdistinct);
3174  /* Guard against out-of-range answers */
3175  if (numdistinct > input_rows)
3176  numdistinct = input_rows;
3177  if (numdistinct < 1.0)
3178  numdistinct = 1.0;
3179  return numdistinct;
3180  }
3181 
3182  /*
3183  * Group Vars by relation and estimate total numdistinct.
3184  *
3185  * For each iteration of the outer loop, we process the frontmost Var in
3186  * varinfos, plus all other Vars in the same relation. We remove these
3187  * Vars from the newvarinfos list for the next iteration. This is the
3188  * easiest way to group Vars of same rel together.
3189  */
3190  do
3191  {
3192  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3193  RelOptInfo *rel = varinfo1->rel;
3194  double reldistinct = 1;
3195  double relmaxndistinct = reldistinct;
3196  int relvarcount = 0;
3197  List *newvarinfos = NIL;
3198  List *relvarinfos = NIL;
3199 
3200  /*
3201  * Split the list of varinfos in two - one for the current rel, one
3202  * for remaining Vars on other rels.
3203  */
3204  relvarinfos = lappend(relvarinfos, varinfo1);
3205  for_each_cell(l, varinfos, list_second_cell(varinfos))
3206  {
3207  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3208 
3209  if (varinfo2->rel == varinfo1->rel)
3210  {
3211  /* varinfos on current rel */
3212  relvarinfos = lappend(relvarinfos, varinfo2);
3213  }
3214  else
3215  {
3216  /* not time to process varinfo2 yet */
3217  newvarinfos = lappend(newvarinfos, varinfo2);
3218  }
3219  }
3220 
3221  /*
3222  * Get the numdistinct estimate for the Vars of this rel. We
3223  * iteratively search for multivariate n-distinct with maximum number
3224  * of vars; assuming that each var group is independent of the others,
3225  * we multiply them together. Any remaining relvarinfos after no more
3226  * multivariate matches are found are assumed independent too, so
3227  * their individual ndistinct estimates are multiplied also.
3228  *
3229  * While iterating, count how many separate numdistinct values we
3230  * apply. We apply a fudge factor below, but only if we multiplied
3231  * more than one such values.
3232  */
3233  while (relvarinfos)
3234  {
3235  double mvndistinct;
3236 
3237  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3238  &mvndistinct))
3239  {
3240  reldistinct *= mvndistinct;
3241  if (relmaxndistinct < mvndistinct)
3242  relmaxndistinct = mvndistinct;
3243  relvarcount++;
3244  }
3245  else
3246  {
3247  foreach(l, relvarinfos)
3248  {
3249  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3250 
3251  reldistinct *= varinfo2->ndistinct;
3252  if (relmaxndistinct < varinfo2->ndistinct)
3253  relmaxndistinct = varinfo2->ndistinct;
3254  relvarcount++;
3255  }
3256 
3257  /* we're done with this relation */
3258  relvarinfos = NIL;
3259  }
3260  }
3261 
3262  /*
3263  * Sanity check --- don't divide by zero if empty relation.
3264  */
3265  Assert(IS_SIMPLE_REL(rel));
3266  if (rel->tuples > 0)
3267  {
3268  /*
3269  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3270  * fudge factor is because the Vars are probably correlated but we
3271  * don't know by how much. We should never clamp to less than the
3272  * largest ndistinct value for any of the Vars, though, since
3273  * there will surely be at least that many groups.
3274  */
3275  double clamp = rel->tuples;
3276 
3277  if (relvarcount > 1)
3278  {
3279  clamp *= 0.1;
3280  if (clamp < relmaxndistinct)
3281  {
3282  clamp = relmaxndistinct;
3283  /* for sanity in case some ndistinct is too large: */
3284  if (clamp > rel->tuples)
3285  clamp = rel->tuples;
3286  }
3287  }
3288  if (reldistinct > clamp)
3289  reldistinct = clamp;
3290 
3291  /*
3292  * Update the estimate based on the restriction selectivity,
3293  * guarding against division by zero when reldistinct is zero.
3294  * Also skip this if we know that we are returning all rows.
3295  */
3296  if (reldistinct > 0 && rel->rows < rel->tuples)
3297  {
3298  /*
3299  * Given a table containing N rows with n distinct values in a
3300  * uniform distribution, if we select p rows at random then
3301  * the expected number of distinct values selected is
3302  *
3303  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3304  *
3305  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3306  *
3307  * See "Approximating block accesses in database
3308  * organizations", S. B. Yao, Communications of the ACM,
3309  * Volume 20 Issue 4, April 1977 Pages 260-261.
3310  *
3311  * Alternatively, re-arranging the terms from the factorials,
3312  * this may be written as
3313  *
3314  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3315  *
3316  * This form of the formula is more efficient to compute in
3317  * the common case where p is larger than N/n. Additionally,
3318  * as pointed out by Dell'Era, if i << N for all terms in the
3319  * product, it can be approximated by
3320  *
3321  * n * (1 - ((N-p)/N)^(N/n))
3322  *
3323  * See "Expected distinct values when selecting from a bag
3324  * without replacement", Alberto Dell'Era,
3325  * http://www.adellera.it/investigations/distinct_balls/.
3326  *
3327  * The condition i << N is equivalent to n >> 1, so this is a
3328  * good approximation when the number of distinct values in
3329  * the table is large. It turns out that this formula also
3330  * works well even when n is small.
3331  */
3332  reldistinct *=
3333  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3334  rel->tuples / reldistinct));
3335  }
3336  reldistinct = clamp_row_est(reldistinct);
3337 
3338  /*
3339  * Update estimate of total distinct groups.
3340  */
3341  numdistinct *= reldistinct;
3342  }
3343 
3344  varinfos = newvarinfos;
3345  } while (varinfos != NIL);
3346 
3347  /* Now we can account for the effects of any SRFs */
3348  numdistinct *= srf_multiplier;
3349 
3350  /* Round off */
3351  numdistinct = ceil(numdistinct);
3352 
3353  /* Guard against out-of-range answers */
3354  if (numdistinct > input_rows)
3355  numdistinct = input_rows;
3356  if (numdistinct < 1.0)
3357  numdistinct = 1.0;
3358 
3359  return numdistinct;
3360 }
3361 
3362 /*
3363  * Estimate hash bucket statistics when the specified expression is used
3364  * as a hash key for the given number of buckets.
3365  *
3366  * This attempts to determine two values:
3367  *
3368  * 1. The frequency of the most common value of the expression (returns
3369  * zero into *mcv_freq if we can't get that).
3370  *
3371  * 2. The "bucketsize fraction", ie, average number of entries in a bucket
3372  * divided by total tuples in relation.
3373  *
3374  * XXX This is really pretty bogus since we're effectively assuming that the
3375  * distribution of hash keys will be the same after applying restriction
3376  * clauses as it was in the underlying relation. However, we are not nearly
3377  * smart enough to figure out how the restrict clauses might change the
3378  * distribution, so this will have to do for now.
3379  *
3380  * We are passed the number of buckets the executor will use for the given
3381  * input relation. If the data were perfectly distributed, with the same
3382  * number of tuples going into each available bucket, then the bucketsize
3383  * fraction would be 1/nbuckets. But this happy state of affairs will occur
3384  * only if (a) there are at least nbuckets distinct data values, and (b)
3385  * we have a not-too-skewed data distribution. Otherwise the buckets will
3386  * be nonuniformly occupied. If the other relation in the join has a key
3387  * distribution similar to this one's, then the most-loaded buckets are
3388  * exactly those that will be probed most often. Therefore, the "average"
3389  * bucket size for costing purposes should really be taken as something close
3390  * to the "worst case" bucket size. We try to estimate this by adjusting the
3391  * fraction if there are too few distinct data values, and then scaling up
3392  * by the ratio of the most common value's frequency to the average frequency.
3393  *
3394  * If no statistics are available, use a default estimate of 0.1. This will
3395  * discourage use of a hash rather strongly if the inner relation is large,
3396  * which is what we want. We do not want to hash unless we know that the
3397  * inner rel is well-dispersed (or the alternatives seem much worse).
3398  *
3399  * The caller should also check that the mcv_freq is not so large that the
3400  * most common value would by itself require an impractically large bucket.
3401  * In a hash join, the executor can split buckets if they get too big, but
3402  * obviously that doesn't help for a bucket that contains many duplicates of
3403  * the same value.
3404  */
3405 void
3406 estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets,
3407  Selectivity *mcv_freq,
3408  Selectivity *bucketsize_frac)
3409 {
3410  VariableStatData vardata;
3411  double estfract,
3412  ndistinct,
3413  stanullfrac,
3414  avgfreq;
3415  bool isdefault;
3416  AttStatsSlot sslot;
3417 
3418  examine_variable(root, hashkey, 0, &vardata);
3419 
3420  /* Look up the frequency of the most common value, if available */
3421  *mcv_freq = 0.0;
3422 
3423  if (HeapTupleIsValid(vardata.statsTuple))
3424  {
3425  if (get_attstatsslot(&sslot, vardata.statsTuple,
3426  STATISTIC_KIND_MCV, InvalidOid,
3428  {
3429  /*
3430  * The first MCV stat is for the most common value.
3431  */
3432  if (sslot.nnumbers > 0)
3433  *mcv_freq = sslot.numbers[0];
3434  free_attstatsslot(&sslot);
3435  }
3436  }
3437 
3438  /* Get number of distinct values */
3439  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3440 
3441  /*
3442  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3443  * mcv_freq is known to be even higher than that, use it instead.
3444  */
3445  if (isdefault)
3446  {
3447  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3448  ReleaseVariableStats(vardata);
3449  return;
3450  }
3451 
3452  /* Get fraction that are null */
3453  if (HeapTupleIsValid(vardata.statsTuple))
3454  {
3455  Form_pg_statistic stats;
3456 
3457  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3458  stanullfrac = stats->stanullfrac;
3459  }
3460  else
3461  stanullfrac = 0.0;
3462 
3463  /* Compute avg freq of all distinct data values in raw relation */
3464  avgfreq = (1.0 - stanullfrac) / ndistinct;
3465 
3466  /*
3467  * Adjust ndistinct to account for restriction clauses. Observe we are
3468  * assuming that the data distribution is affected uniformly by the
3469  * restriction clauses!
3470  *
3471  * XXX Possibly better way, but much more expensive: multiply by
3472  * selectivity of rel's restriction clauses that mention the target Var.
3473  */
3474  if (vardata.rel && vardata.rel->tuples > 0)
3475  {
3476  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3477  ndistinct = clamp_row_est(ndistinct);
3478  }
3479 
3480  /*
3481  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3482  * number of buckets is less than the expected number of distinct values;
3483  * otherwise it is 1/ndistinct.
3484  */
3485  if (ndistinct > nbuckets)
3486  estfract = 1.0 / nbuckets;
3487  else
3488  estfract = 1.0 / ndistinct;
3489 
3490  /*
3491  * Adjust estimated bucketsize upward to account for skewed distribution.
3492  */
3493  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3494  estfract *= *mcv_freq / avgfreq;
3495 
3496  /*
3497  * Clamp bucketsize to sane range (the above adjustment could easily
3498  * produce an out-of-range result). We set the lower bound a little above
3499  * zero, since zero isn't a very sane result.
3500  */
3501  if (estfract < 1.0e-6)
3502  estfract = 1.0e-6;
3503  else if (estfract > 1.0)
3504  estfract = 1.0;
3505 
3506  *bucketsize_frac = (Selectivity) estfract;
3507 
3508  ReleaseVariableStats(vardata);
3509 }
3510 
3511 /*
3512  * estimate_hashagg_tablesize
3513  * estimate the number of bytes that a hash aggregate hashtable will
3514  * require based on the agg_costs, path width and number of groups.
3515  *
3516  * We return the result as "double" to forestall any possible overflow
3517  * problem in the multiplication by dNumGroups.
3518  *
3519  * XXX this may be over-estimating the size now that hashagg knows to omit
3520  * unneeded columns from the hashtable. Also for mixed-mode grouping sets,
3521  * grouping columns not in the hashed set are counted here even though hashagg
3522  * won't store them. Is this a problem?
3523  */
3524 double
3526  double dNumGroups)
3527 {
3528  Size hashentrysize;
3529 
3530  /* Estimate per-hash-entry space at tuple width... */
3531  hashentrysize = MAXALIGN(path->pathtarget->width) +
3533 
3534  /* plus space for pass-by-ref transition values... */
3535  hashentrysize += agg_costs->transitionSpace;
3536  /* plus the per-hash-entry overhead */
3537  hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
3538 
3539  /*
3540  * Note that this disregards the effect of fill-factor and growth policy
3541  * of the hash table. That's probably ok, given that the default
3542  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3543  * "double-in-size" growth policies here.
3544  */
3545  return hashentrysize * dNumGroups;
3546 }
3547 
3548 
3549 /*-------------------------------------------------------------------------
3550  *
3551  * Support routines
3552  *
3553  *-------------------------------------------------------------------------
3554  */
3555 
3556 /*
3557  * Find applicable ndistinct statistics for the given list of VarInfos (which
3558  * must all belong to the given rel), and update *ndistinct to the estimate of
3559  * the MVNDistinctItem that best matches. If a match it found, *varinfos is
3560  * updated to remove the list of matched varinfos.
3561  *
3562  * Varinfos that aren't for simple Vars are ignored.
3563  *
3564  * Return true if we're able to find a match, false otherwise.
3565  */
3566 static bool
3568  List **varinfos, double *ndistinct)
3569 {
3570  ListCell *lc;
3571  Bitmapset *attnums = NULL;
3572  int nmatches;
3573  Oid statOid = InvalidOid;
3574  MVNDistinct *stats;
3575  Bitmapset *matched = NULL;
3576 
3577  /* bail out immediately if the table has no extended statistics */
3578  if (!rel->statlist)
3579  return false;
3580 
3581  /* Determine the attnums we're looking for */
3582  foreach(lc, *varinfos)
3583  {
3584  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3585 
3586  Assert(varinfo->rel == rel);
3587 
3588  if (IsA(varinfo->var, Var))
3589  {
3590  attnums = bms_add_member(attnums,
3591  ((Var *) varinfo->var)->varattno);
3592  }
3593  }
3594 
3595  /* look for the ndistinct statistics matching the most vars */
3596  nmatches = 1; /* we require at least two matches */
3597  foreach(lc, rel->statlist)
3598  {
3599  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3600  Bitmapset *shared;
3601  int nshared;
3602 
3603  /* skip statistics of other kinds */
3604  if (info->kind != STATS_EXT_NDISTINCT)
3605  continue;
3606 
3607  /* compute attnums shared by the vars and the statistics object */
3608  shared = bms_intersect(info->keys, attnums);
3609  nshared = bms_num_members(shared);
3610 
3611  /*
3612  * Does this statistics object match more columns than the currently
3613  * best object? If so, use this one instead.
3614  *
3615  * XXX This should break ties using name of the object, or something
3616  * like that, to make the outcome stable.
3617  */
3618  if (nshared > nmatches)
3619  {
3620  statOid = info->statOid;
3621  nmatches = nshared;
3622  matched = shared;
3623  }
3624  }
3625 
3626  /* No match? */
3627  if (statOid == InvalidOid)
3628  return false;
3629  Assert(nmatches > 1 && matched != NULL);
3630 
3631  stats = statext_ndistinct_load(statOid);
3632 
3633  /*
3634  * If we have a match, search it for the specific item that matches (there
3635  * must be one), and construct the output values.
3636  */
3637  if (stats)
3638  {
3639  int i;
3640  List *newlist = NIL;
3641  MVNDistinctItem *item = NULL;
3642 
3643  /* Find the specific item that exactly matches the combination */
3644  for (i = 0; i < stats->nitems; i++)
3645  {
3646  MVNDistinctItem *tmpitem = &stats->items[i];
3647 
3648  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3649  {
3650  item = tmpitem;
3651  break;
3652  }
3653  }
3654 
3655  /* make sure we found an item */
3656  if (!item)
3657  elog(ERROR, "corrupt MVNDistinct entry");
3658 
3659  /* Form the output varinfo list, keeping only unmatched ones */
3660  foreach(lc, *varinfos)
3661  {
3662  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3664 
3665  if (!IsA(varinfo->var, Var))
3666  {
3667  newlist = lappend(newlist, varinfo);
3668  continue;
3669  }
3670 
3671  attnum = ((Var *) varinfo->var)->varattno;
3672  if (!bms_is_member(attnum, matched))
3673  newlist = lappend(newlist, varinfo);
3674  }
3675 
3676  *varinfos = newlist;
3677  *ndistinct = item->ndistinct;
3678  return true;
3679  }
3680 
3681  return false;
3682 }
3683 
3684 /*
3685  * convert_to_scalar
3686  * Convert non-NULL values of the indicated types to the comparison
3687  * scale needed by scalarineqsel().
3688  * Returns "true" if successful.
3689  *
3690  * XXX this routine is a hack: ideally we should look up the conversion
3691  * subroutines in pg_type.
3692  *
3693  * All numeric datatypes are simply converted to their equivalent
3694  * "double" values. (NUMERIC values that are outside the range of "double"
3695  * are clamped to +/- HUGE_VAL.)
3696  *
3697  * String datatypes are converted by convert_string_to_scalar(),
3698  * which is explained below. The reason why this routine deals with
3699  * three values at a time, not just one, is that we need it for strings.
3700  *
3701  * The bytea datatype is just enough different from strings that it has
3702  * to be treated separately.
3703  *
3704  * The several datatypes representing absolute times are all converted
3705  * to Timestamp, which is actually a double, and then we just use that
3706  * double value. Note this will give correct results even for the "special"
3707  * values of Timestamp, since those are chosen to compare correctly;
3708  * see timestamp_cmp.
3709  *
3710  * The several datatypes representing relative times (intervals) are all
3711  * converted to measurements expressed in seconds.
3712  */
3713 static bool
3714 convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue,
3715  Datum lobound, Datum hibound, Oid boundstypid,
3716  double *scaledlobound, double *scaledhibound)
3717 {
3718  bool failure = false;
3719 
3720  /*
3721  * Both the valuetypid and the boundstypid should exactly match the
3722  * declared input type(s) of the operator we are invoked for. However,
3723  * extensions might try to use scalarineqsel as estimator for operators
3724  * with input type(s) we don't handle here; in such cases, we want to
3725  * return false, not fail. In any case, we mustn't assume that valuetypid
3726  * and boundstypid are identical.
3727  *
3728  * XXX The histogram we are interpolating between points of could belong
3729  * to a column that's only binary-compatible with the declared type. In
3730  * essence we are assuming that the semantics of binary-compatible types
3731  * are enough alike that we can use a histogram generated with one type's
3732  * operators to estimate selectivity for the other's. This is outright
3733  * wrong in some cases --- in particular signed versus unsigned
3734  * interpretation could trip us up. But it's useful enough in the
3735  * majority of cases that we do it anyway. Should think about more
3736  * rigorous ways to do it.
3737  */
3738  switch (valuetypid)
3739  {
3740  /*
3741  * Built-in numeric types
3742  */
3743  case BOOLOID:
3744  case INT2OID:
3745  case INT4OID:
3746  case INT8OID:
3747  case FLOAT4OID:
3748  case FLOAT8OID:
3749  case NUMERICOID:
3750  case OIDOID:
3751  case REGPROCOID:
3752  case REGPROCEDUREOID:
3753  case REGOPEROID:
3754  case REGOPERATOROID:
3755  case REGCLASSOID:
3756  case REGTYPEOID:
3757  case REGCONFIGOID:
3758  case REGDICTIONARYOID:
3759  case REGROLEOID:
3760  case REGNAMESPACEOID:
3761  *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
3762  &failure);
3763  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
3764  &failure);
3765  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
3766  &failure);
3767  return !failure;
3768 
3769  /*
3770  * Built-in string types
3771  */
3772  case CHAROID:
3773  case BPCHAROID:
3774  case VARCHAROID:
3775  case TEXTOID:
3776  case NAMEOID:
3777  {
3778  char *valstr = convert_string_datum(value, valuetypid,
3779  collid, &failure);
3780  char *lostr = convert_string_datum(lobound, boundstypid,
3781  collid, &failure);
3782  char *histr = convert_string_datum(hibound, boundstypid,
3783  collid, &failure);
3784 
3785  /*
3786  * Bail out if any of the values is not of string type. We
3787  * might leak converted strings for the other value(s), but
3788  * that's not worth troubling over.
3789  */
3790  if (failure)
3791  return false;
3792 
3793  convert_string_to_scalar(valstr, scaledvalue,
3794  lostr, scaledlobound,
3795  histr, scaledhibound);
3796  pfree(valstr);
3797  pfree(lostr);
3798  pfree(histr);
3799  return true;
3800  }
3801 
3802  /*
3803  * Built-in bytea type
3804  */
3805  case BYTEAOID:
3806  {
3807  /* We only support bytea vs bytea comparison */
3808  if (boundstypid != BYTEAOID)
3809  return false;
3810  convert_bytea_to_scalar(value, scaledvalue,
3811  lobound, scaledlobound,
3812  hibound, scaledhibound);
3813  return true;
3814  }
3815 
3816  /*
3817  * Built-in time types
3818  */
3819  case TIMESTAMPOID:
3820  case TIMESTAMPTZOID:
3821  case DATEOID:
3822  case INTERVALOID:
3823  case TIMEOID:
3824  case TIMETZOID:
3825  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
3826  &failure);
3827  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
3828  &failure);
3829  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
3830  &failure);
3831  return !failure;
3832 
3833  /*
3834  * Built-in network types
3835  */
3836  case INETOID:
3837  case CIDROID:
3838  case MACADDROID:
3839  case MACADDR8OID:
3840  *scaledvalue = convert_network_to_scalar(value, valuetypid,
3841  &failure);
3842  *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
3843  &failure);
3844  *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
3845  &failure);
3846  return !failure;
3847  }
3848  /* Don't know how to convert */
3849  *scaledvalue = *scaledlobound = *scaledhibound = 0;
3850  return false;
3851 }
3852 
3853 /*
3854  * Do convert_to_scalar()'s work for any numeric data type.
3855  *
3856  * On failure (e.g., unsupported typid), set *failure to true;
3857  * otherwise, that variable is not changed.
3858  */
3859 static double
3861 {
3862  switch (typid)
3863  {
3864  case BOOLOID:
3865  return (double) DatumGetBool(value);
3866  case INT2OID:
3867  return (double) DatumGetInt16(value);
3868  case INT4OID:
3869  return (double) DatumGetInt32(value);
3870  case INT8OID:
3871  return (double) DatumGetInt64(value);
3872  case FLOAT4OID:
3873  return (double) DatumGetFloat4(value);
3874  case FLOAT8OID:
3875  return (double) DatumGetFloat8(value);
3876  case NUMERICOID:
3877  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3878  return (double)
3880  value));
3881  case OIDOID:
3882  case REGPROCOID:
3883  case REGPROCEDUREOID:
3884  case REGOPEROID:
3885  case REGOPERATOROID:
3886  case REGCLASSOID:
3887  case REGTYPEOID:
3888  case REGCONFIGOID:
3889  case REGDICTIONARYOID:
3890  case REGROLEOID:
3891  case REGNAMESPACEOID:
3892  /* we can treat OIDs as integers... */
3893  return (double) DatumGetObjectId(value);
3894  }
3895 
3896  *failure = true;
3897  return 0;
3898 }
3899 
3900 /*
3901  * Do convert_to_scalar()'s work for any character-string data type.
3902  *
3903  * String datatypes are converted to a scale that ranges from 0 to 1,
3904  * where we visualize the bytes of the string as fractional digits.
3905  *
3906  * We do not want the base to be 256, however, since that tends to
3907  * generate inflated selectivity estimates; few databases will have
3908  * occurrences of all 256 possible byte values at each position.
3909  * Instead, use the smallest and largest byte values seen in the bounds
3910  * as the estimated range for each byte, after some fudging to deal with
3911  * the fact that we probably aren't going to see the full range that way.
3912  *
3913  * An additional refinement is that we discard any common prefix of the
3914  * three strings before computing the scaled values. This allows us to
3915  * "zoom in" when we encounter a narrow data range. An example is a phone
3916  * number database where all the values begin with the same area code.
3917  * (Actually, the bounds will be adjacent histogram-bin-boundary values,
3918  * so this is more likely to happen than you might think.)
3919  */
3920 static void
3922  double *scaledvalue,
3923  char *lobound,
3924  double *scaledlobound,
3925  char *hibound,
3926  double *scaledhibound)
3927 {
3928  int rangelo,
3929  rangehi;
3930  char *sptr;
3931 
3932  rangelo = rangehi = (unsigned char) hibound[0];
3933  for (sptr = lobound; *sptr; sptr++)
3934  {
3935  if (rangelo > (unsigned char) *sptr)
3936  rangelo = (unsigned char) *sptr;
3937  if (rangehi < (unsigned char) *sptr)
3938  rangehi = (unsigned char) *sptr;
3939  }
3940  for (sptr = hibound; *sptr; sptr++)
3941  {
3942  if (rangelo > (unsigned char) *sptr)
3943  rangelo = (unsigned char) *sptr;
3944  if (rangehi < (unsigned char) *sptr)
3945  rangehi = (unsigned char) *sptr;
3946  }
3947  /* If range includes any upper-case ASCII chars, make it include all */
3948  if (rangelo <= 'Z' && rangehi >= 'A')
3949  {
3950  if (rangelo > 'A')
3951  rangelo = 'A';
3952  if (rangehi < 'Z')
3953  rangehi = 'Z';
3954  }
3955  /* Ditto lower-case */
3956  if (rangelo <= 'z' && rangehi >= 'a')
3957  {
3958  if (rangelo > 'a')
3959  rangelo = 'a';
3960  if (rangehi < 'z')
3961  rangehi = 'z';
3962  }
3963  /* Ditto digits */
3964  if (rangelo <= '9' && rangehi >= '0')
3965  {
3966  if (rangelo > '0')
3967  rangelo = '0';
3968  if (rangehi < '9')
3969  rangehi = '9';
3970  }
3971 
3972  /*
3973  * If range includes less than 10 chars, assume we have not got enough
3974  * data, and make it include regular ASCII set.
3975  */
3976  if (rangehi - rangelo < 9)
3977  {
3978  rangelo = ' ';
3979  rangehi = 127;
3980  }
3981 
3982  /*
3983  * Now strip any common prefix of the three strings.
3984  */
3985  while (*lobound)
3986  {
3987  if (*lobound != *hibound || *lobound != *value)
3988  break;
3989  lobound++, hibound++, value++;
3990  }
3991 
3992  /*
3993  * Now we can do the conversions.
3994  */
3995  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
3996  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
3997  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
3998 }
3999 
4000 static double
4001 convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
4002 {
4003  int slen = strlen(value);
4004  double num,
4005  denom,
4006  base;
4007 
4008  if (slen <= 0)
4009  return 0.0; /* empty string has scalar value 0 */
4010 
4011  /*
4012  * There seems little point in considering more than a dozen bytes from
4013  * the string. Since base is at least 10, that will give us nominal
4014  * resolution of at least 12 decimal digits, which is surely far more
4015  * precision than this estimation technique has got anyway (especially in
4016  * non-C locales). Also, even with the maximum possible base of 256, this
4017  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4018  * overflow on any known machine.
4019  */
4020  if (slen > 12)
4021  slen = 12;
4022 
4023  /* Convert initial characters to fraction */
4024  base = rangehi - rangelo + 1;
4025  num = 0.0;
4026  denom = base;
4027  while (slen-- > 0)
4028  {
4029  int ch = (unsigned char) *value++;
4030 
4031  if (ch < rangelo)
4032  ch = rangelo - 1;
4033  else if (ch > rangehi)
4034  ch = rangehi + 1;
4035  num += ((double) (ch - rangelo)) / denom;
4036  denom *= base;
4037  }
4038 
4039  return num;
4040 }
4041 
4042 /*
4043  * Convert a string-type Datum into a palloc'd, null-terminated string.
4044  *
4045  * On failure (e.g., unsupported typid), set *failure to true;
4046  * otherwise, that variable is not changed. (We'll return NULL on failure.)
4047  *
4048  * When using a non-C locale, we must pass the string through strxfrm()
4049  * before continuing, so as to generate correct locale-specific results.
4050  */
4051 static char *
4052 convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
4053 {
4054  char *val;
4055 
4056  switch (typid)
4057  {
4058  case CHAROID:
4059  val = (char *) palloc(2);
4060  val[0] = DatumGetChar(value);
4061  val[1] = '\0';
4062  break;
4063  case BPCHAROID:
4064  case VARCHAROID:
4065  case TEXTOID:
4066  val = TextDatumGetCString(value);
4067  break;
4068  case NAMEOID:
4069  {
4070  NameData *nm = (NameData *) DatumGetPointer(value);
4071 
4072  val = pstrdup(NameStr(*nm));
4073  break;
4074  }
4075  default:
4076  *failure = true;
4077  return NULL;
4078  }
4079 
4080  if (!lc_collate_is_c(collid))
4081  {
4082  char *xfrmstr;
4083  size_t xfrmlen;
4084  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4085 
4086  /*
4087  * XXX: We could guess at a suitable output buffer size and only call
4088  * strxfrm twice if our guess is too small.
4089  *
4090  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4091  * bogus data or set an error. This is not really a problem unless it
4092  * crashes since it will only give an estimation error and nothing
4093  * fatal.
4094  */
4095  xfrmlen = strxfrm(NULL, val, 0);
4096 #ifdef WIN32
4097 
4098  /*
4099  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4100  * of trying to allocate this much memory (and fail), just return the
4101  * original string unmodified as if we were in the C locale.
4102  */
4103  if (xfrmlen == INT_MAX)
4104  return val;
4105 #endif
4106  xfrmstr = (char *) palloc(xfrmlen + 1);
4107  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4108 
4109  /*
4110  * Some systems (e.g., glibc) can return a smaller value from the
4111  * second call than the first; thus the Assert must be <= not ==.
4112  */
4113  Assert(xfrmlen2 <= xfrmlen);
4114  pfree(val);
4115  val = xfrmstr;
4116  }
4117 
4118  return val;
4119 }
4120 
4121 /*
4122  * Do convert_to_scalar()'s work for any bytea data type.
4123  *
4124  * Very similar to convert_string_to_scalar except we can't assume
4125  * null-termination and therefore pass explicit lengths around.
4126  *
4127  * Also, assumptions about likely "normal" ranges of characters have been
4128  * removed - a data range of 0..255 is always used, for now. (Perhaps
4129  * someday we will add information about actual byte data range to
4130  * pg_statistic.)
4131  */
4132 static void
4134  double *scaledvalue,
4135  Datum lobound,
4136  double *scaledlobound,
4137  Datum hibound,
4138  double *scaledhibound)
4139 {
4140  bytea *valuep = DatumGetByteaPP(value);
4141  bytea *loboundp = DatumGetByteaPP(lobound);
4142  bytea *hiboundp = DatumGetByteaPP(hibound);
4143  int rangelo,
4144  rangehi,
4145  valuelen = VARSIZE_ANY_EXHDR(valuep),
4146  loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4147  hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4148  i,
4149  minlen;
4150  unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4151  unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4152  unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4153 
4154  /*
4155  * Assume bytea data is uniformly distributed across all byte values.
4156  */
4157  rangelo = 0;
4158  rangehi = 255;
4159 
4160  /*
4161  * Now strip any common prefix of the three strings.
4162  */
4163  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4164  for (i = 0; i < minlen; i++)
4165  {
4166  if (*lostr != *histr || *lostr != *valstr)
4167  break;
4168  lostr++, histr++, valstr++;
4169  loboundlen--, hiboundlen--, valuelen--;
4170  }
4171 
4172  /*
4173  * Now we can do the conversions.
4174  */
4175  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4176  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4177  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4178 }
4179 
4180 static double
4181 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
4182  int rangelo, int rangehi)
4183 {
4184  double num,
4185  denom,
4186  base;
4187 
4188  if (valuelen <= 0)
4189  return 0.0; /* empty string has scalar value 0 */
4190 
4191  /*
4192  * Since base is 256, need not consider more than about 10 chars (even
4193  * this many seems like overkill)
4194  */
4195  if (valuelen > 10)
4196  valuelen = 10;
4197 
4198  /* Convert initial characters to fraction */
4199  base = rangehi - rangelo + 1;
4200  num = 0.0;
4201  denom = base;
4202  while (valuelen-- > 0)
4203  {
4204  int ch = *value++;
4205 
4206  if (ch < rangelo)
4207  ch = rangelo - 1;
4208  else if (ch > rangehi)
4209  ch = rangehi + 1;
4210  num += ((double) (ch - rangelo)) / denom;
4211  denom *= base;
4212  }
4213 
4214  return num;
4215 }
4216 
4217 /*
4218  * Do convert_to_scalar()'s work for any timevalue data type.
4219  *
4220  * On failure (e.g., unsupported typid), set *failure to true;
4221  * otherwise, that variable is not changed.
4222  */
4223 static double
4225 {
4226  switch (typid)
4227  {
4228  case TIMESTAMPOID:
4229  return DatumGetTimestamp(value);
4230  case TIMESTAMPTZOID:
4231  return DatumGetTimestampTz(value);
4232  case DATEOID:
4234  case INTERVALOID:
4235  {
4237 
4238  /*
4239  * Convert the month part of Interval to days using assumed
4240  * average month length of 365.25/12.0 days. Not too
4241  * accurate, but plenty good enough for our purposes.
4242  */
4243  return interval->time + interval->day * (double) USECS_PER_DAY +
4244  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4245  }
4246  case TIMEOID:
4247  return DatumGetTimeADT(value);
4248  case TIMETZOID:
4249  {
4250  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4251 
4252  /* use GMT-equivalent time */
4253  return (double) (timetz->time + (timetz->zone * 1000000.0));
4254  }
4255  }
4256 
4257  *failure = true;
4258  return 0;
4259 }
4260 
4261 
4262 /*
4263  * get_restriction_variable
4264  * Examine the args of a restriction clause to see if it's of the
4265  * form (variable op pseudoconstant) or (pseudoconstant op variable),
4266  * where "variable" could be either a Var or an expression in vars of a
4267  * single relation. If so, extract information about the variable,
4268  * and also indicate which side it was on and the other argument.
4269  *
4270  * Inputs:
4271  * root: the planner info
4272  * args: clause argument list
4273  * varRelid: see specs for restriction selectivity functions
4274  *
4275  * Outputs: (these are valid only if true is returned)
4276  * *vardata: gets information about variable (see examine_variable)
4277  * *other: gets other clause argument, aggressively reduced to a constant
4278  * *varonleft: set true if variable is on the left, false if on the right
4279  *
4280  * Returns true if a variable is identified, otherwise false.
4281  *
4282  * Note: if there are Vars on both sides of the clause, we must fail, because
4283  * callers are expecting that the other side will act like a pseudoconstant.
4284  */
4285 bool
4287  VariableStatData *vardata, Node **other,
4288  bool *varonleft)
4289 {
4290  Node *left,
4291  *right;
4292  VariableStatData rdata;
4293 
4294  /* Fail if not a binary opclause (probably shouldn't happen) */
4295  if (list_length(args) != 2)
4296  return false;
4297 
4298  left = (Node *) linitial(args);
4299  right = (Node *) lsecond(args);
4300 
4301  /*
4302  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4303  * relations will be treated as pseudoconstants.
4304  */
4305  examine_variable(root, left, varRelid, vardata);
4306  examine_variable(root, right, varRelid, &rdata);
4307 
4308  /*
4309  * If one side is a variable and the other not, we win.
4310  */
4311  if (vardata->rel && rdata.rel == NULL)
4312  {
4313  *varonleft = true;
4314  *other = estimate_expression_value(root, rdata.var);
4315  /* Assume we need no ReleaseVariableStats(rdata) here */
4316  return true;
4317  }
4318 
4319  if (vardata->rel == NULL && rdata.rel)
4320  {
4321  *varonleft = false;
4322  *other = estimate_expression_value(root, vardata->var);
4323  /* Assume we need no ReleaseVariableStats(*vardata) here */
4324  *vardata = rdata;
4325  return true;
4326  }
4327 
4328  /* Oops, clause has wrong structure (probably var op var) */
4329  ReleaseVariableStats(*vardata);
4330  ReleaseVariableStats(rdata);
4331 
4332  return false;
4333 }
4334 
4335 /*
4336  * get_join_variables
4337  * Apply examine_variable() to each side of a join clause.
4338  * Also, attempt to identify whether the join clause has the same
4339  * or reversed sense compared to the SpecialJoinInfo.
4340  *
4341  * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4342  * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4343  * where we can't tell for sure, we default to assuming it's normal.
4344  */
4345 void
4347  VariableStatData *vardata1, VariableStatData *vardata2,
4348  bool *join_is_reversed)
4349 {
4350  Node *left,
4351  *right;
4352 
4353  if (list_length(args) != 2)
4354  elog(ERROR, "join operator should take two arguments");
4355 
4356  left = (Node *) linitial(args);
4357  right = (Node *) lsecond(args);
4358 
4359  examine_variable(root, left, 0, vardata1);
4360  examine_variable(root, right, 0, vardata2);
4361 
4362  if (vardata1->rel &&
4363  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4364  *join_is_reversed = true; /* var1 is on RHS */
4365  else if (vardata2->rel &&
4366  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4367  *join_is_reversed = true; /* var2 is on LHS */
4368  else
4369  *join_is_reversed = false;
4370 }
4371 
4372 /*
4373  * examine_variable
4374  * Try to look up statistical data about an expression.
4375  * Fill in a VariableStatData struct to describe the expression.
4376  *
4377  * Inputs:
4378  * root: the planner info
4379  * node: the expression tree to examine
4380  * varRelid: see specs for restriction selectivity functions
4381  *
4382  * Outputs: *vardata is filled as follows:
4383  * var: the input expression (with any binary relabeling stripped, if
4384  * it is or contains a variable; but otherwise the type is preserved)
4385  * rel: RelOptInfo for relation containing variable; NULL if expression
4386  * contains no Vars (NOTE this could point to a RelOptInfo of a
4387  * subquery, not one in the current query).
4388  * statsTuple: the pg_statistic entry for the variable, if one exists;
4389  * otherwise NULL.
4390  * freefunc: pointer to a function to release statsTuple with.
4391  * vartype: exposed type of the expression; this should always match
4392  * the declared input type of the operator we are estimating for.
4393  * atttype, atttypmod: actual type/typmod of the "var" expression. This is
4394  * commonly the same as the exposed type of the variable argument,
4395  * but can be different in binary-compatible-type cases.
4396  * isunique: true if we were able to match the var to a unique index or a
4397  * single-column DISTINCT clause, implying its values are unique for
4398  * this query. (Caution: this should be trusted for statistical
4399  * purposes only, since we do not check indimmediate nor verify that
4400  * the exact same definition of equality applies.)
4401  * acl_ok: true if current user has permission to read the column(s)
4402  * underlying the pg_statistic entry. This is consulted by
4403  * statistic_proc_security_check().
4404  *
4405  * Caller is responsible for doing ReleaseVariableStats() before exiting.
4406  */
4407 void
4408 examine_variable(PlannerInfo *root, Node *node, int varRelid,
4409  VariableStatData *vardata)
4410 {
4411  Node *basenode;
4412  Relids varnos;
4413  RelOptInfo *onerel;
4414 
4415  /* Make sure we don't return dangling pointers in vardata */
4416  MemSet(vardata, 0, sizeof(VariableStatData));
4417 
4418  /* Save the exposed type of the expression */
4419  vardata->vartype = exprType(node);
4420 
4421  /* Look inside any binary-compatible relabeling */
4422 
4423  if (IsA(node, RelabelType))
4424  basenode = (Node *) ((RelabelType *) node)->arg;
4425  else
4426  basenode = node;
4427 
4428  /* Fast path for a simple Var */
4429 
4430  if (IsA(basenode, Var) &&
4431  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4432  {
4433  Var *var = (Var *) basenode;
4434 
4435  /* Set up result fields other than the stats tuple */
4436  vardata->var = basenode; /* return Var without relabeling */
4437  vardata->rel = find_base_rel(root, var->varno);
4438  vardata->atttype = var->vartype;
4439  vardata->atttypmod = var->vartypmod;
4440  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4441 
4442  /* Try to locate some stats */
4443  examine_simple_variable(root, var, vardata);
4444 
4445  return;
4446  }
4447 
4448  /*
4449  * Okay, it's a more complicated expression. Determine variable
4450  * membership. Note that when varRelid isn't zero, only vars of that
4451  * relation are considered "real" vars.
4452  */
4453  varnos = pull_varnos(basenode);
4454 
4455  onerel = NULL;
4456 
4457  switch (bms_membership(varnos))
4458  {
4459  case BMS_EMPTY_SET:
4460  /* No Vars at all ... must be pseudo-constant clause */
4461  break;
4462  case BMS_SINGLETON:
4463  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4464  {
4465  onerel = find_base_rel(root,
4466  (varRelid ? varRelid : bms_singleton_member(varnos)));
4467  vardata->rel = onerel;
4468  node = basenode; /* strip any relabeling */
4469  }
4470  /* else treat it as a constant */
4471  break;
4472  case BMS_MULTIPLE:
4473  if (varRelid == 0)
4474  {
4475  /* treat it as a variable of a join relation */
4476  vardata->rel = find_join_rel(root, varnos);
4477  node = basenode; /* strip any relabeling */
4478  }
4479  else if (bms_is_member(varRelid, varnos))
4480  {
4481  /* ignore the vars belonging to other relations */
4482  vardata->rel = find_base_rel(root, varRelid);
4483  node = basenode; /* strip any relabeling */
4484  /* note: no point in expressional-index search here */
4485  }
4486  /* else treat it as a constant */
4487  break;
4488  }
4489 
4490  bms_free(varnos);
4491 
4492  vardata->var = node;
4493  vardata->atttype = exprType(node);
4494  vardata->atttypmod = exprTypmod(node);
4495 
4496  if (onerel)
4497  {
4498  /*
4499  * We have an expression in vars of a single relation. Try to match
4500  * it to expressional index columns, in hopes of finding some
4501  * statistics.
4502  *
4503  * Note that we consider all index columns including INCLUDE columns,
4504  * since there could be stats for such columns. But the test for
4505  * uniqueness needs to be warier.
4506  *
4507  * XXX it's conceivable that there are multiple matches with different
4508  * index opfamilies; if so, we need to pick one that matches the
4509  * operator we are estimating for. FIXME later.
4510  */
4511  ListCell *ilist;
4512 
4513  foreach(ilist, onerel->indexlist)
4514  {
4515  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4516  ListCell *indexpr_item;
4517  int pos;
4518 
4519  indexpr_item = list_head(index->indexprs);
4520  if (indexpr_item == NULL)
4521  continue; /* no expressions here... */
4522 
4523  for (pos = 0; pos < index->ncolumns; pos++)
4524  {
4525  if (index->indexkeys[pos] == 0)
4526  {
4527  Node *indexkey;
4528 
4529  if (indexpr_item == NULL)
4530  elog(ERROR, "too few entries in indexprs list");
4531  indexkey = (Node *) lfirst(indexpr_item);
4532  if (indexkey && IsA(indexkey, RelabelType))
4533  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4534  if (equal(node, indexkey))
4535  {
4536  /*
4537  * Found a match ... is it a unique index? Tests here
4538  * should match has_unique_index().
4539  */
4540  if (index->unique &&
4541  index->nkeycolumns == 1 &&
4542  pos == 0 &&
4543  (index->indpred == NIL || index->predOK))
4544  vardata->isunique = true;
4545 
4546  /*
4547  * Has it got stats? We only consider stats for
4548  * non-partial indexes, since partial indexes probably
4549  * don't reflect whole-relation statistics; the above
4550  * check for uniqueness is the only info we take from
4551  * a partial index.
4552  *
4553  * An index stats hook, however, must make its own
4554  * decisions about what to do with partial indexes.
4555  */
4556  if (get_index_stats_hook &&
4557  (*get_index_stats_hook) (root, index->indexoid,
4558  pos + 1, vardata))
4559  {
4560  /*
4561  * The hook took control of acquiring a stats
4562  * tuple. If it did supply a tuple, it'd better
4563  * have supplied a freefunc.
4564  */
4565  if (HeapTupleIsValid(vardata->statsTuple) &&
4566  !vardata->freefunc)
4567  elog(ERROR, "no function provided to release variable stats with");
4568  }
4569  else if (index->indpred == NIL)
4570  {
4571  vardata->statsTuple =
4573  ObjectIdGetDatum(index->indexoid),
4574  Int16GetDatum(pos + 1),
4575  BoolGetDatum(false));
4576  vardata->freefunc = ReleaseSysCache;
4577 
4578  if (HeapTupleIsValid(vardata->statsTuple))
4579  {
4580  /* Get index's table for permission check */
4581  RangeTblEntry *rte;
4582  Oid userid;
4583 
4584  rte = planner_rt_fetch(index->rel->relid, root);
4585  Assert(rte->rtekind == RTE_RELATION);
4586 
4587  /*
4588  * Use checkAsUser if it's set, in case we're
4589  * accessing the table via a view.
4590  */
4591  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4592 
4593  /*
4594  * For simplicity, we insist on the whole
4595  * table being selectable, rather than trying
4596  * to identify which column(s) the index
4597  * depends on. Also require all rows to be
4598  * selectable --- there must be no
4599  * securityQuals from security barrier views
4600  * or RLS policies.
4601  */
4602  vardata->acl_ok =
4603  rte->securityQuals == NIL &&
4604  (pg_class_aclcheck(rte->relid, userid,
4605  ACL_SELECT) == ACLCHECK_OK);
4606  }
4607  else
4608  {
4609  /* suppress leakproofness checks later */
4610  vardata->acl_ok = true;
4611  }
4612  }
4613  if (vardata->statsTuple)
4614  break;
4615  }
4616  indexpr_item = lnext(index->indexprs, indexpr_item);
4617  }
4618  }
4619  if (vardata->statsTuple)
4620  break;
4621  }
4622  }
4623 }
4624 
4625 /*
4626  * examine_simple_variable
4627  * Handle a simple Var for examine_variable
4628  *
4629  * This is split out as a subroutine so that we can recurse to deal with
4630  * Vars referencing subqueries.
4631  *
4632  * We already filled in all the fields of *vardata except for the stats tuple.
4633  */
4634 static void
4636  VariableStatData *vardata)
4637 {
4638  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4639 
4640  Assert(IsA(rte, RangeTblEntry));
4641 
4643  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4644  {
4645  /*
4646  * The hook took control of acquiring a stats tuple. If it did supply
4647  * a tuple, it'd better have supplied a freefunc.
4648  */
4649  if (HeapTupleIsValid(vardata->statsTuple) &&
4650  !vardata->freefunc)
4651  elog(ERROR, "no function provided to release variable stats with");
4652  }
4653  else if (rte->rtekind == RTE_RELATION)
4654  {
4655  /*
4656  * Plain table or parent of an inheritance appendrel, so look up the
4657  * column in pg_statistic
4658  */
4660  ObjectIdGetDatum(rte->relid),
4661  Int16GetDatum(var->varattno),
4662  BoolGetDatum(rte->inh));
4663  vardata->freefunc = ReleaseSysCache;
4664 
4665  if (HeapTupleIsValid(vardata->statsTuple))
4666  {
4667  Oid userid;
4668 
4669  /*
4670  * Check if user has permission to read this column. We require
4671  * all rows to be accessible, so there must be no securityQuals
4672  * from security barrier views or RLS policies. Use checkAsUser
4673  * if it's set, in case we're accessing the table via a view.
4674  */
4675  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4676 
4677  vardata->acl_ok =
4678  rte->securityQuals == NIL &&
4679  ((pg_class_aclcheck(rte->relid, userid,
4680  ACL_SELECT) == ACLCHECK_OK) ||
4681  (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
4682  ACL_SELECT) == ACLCHECK_OK));
4683  }
4684  else
4685  {
4686  /* suppress any possible leakproofness checks later */
4687  vardata->acl_ok = true;
4688  }
4689  }
4690  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4691  {
4692  /*
4693  * Plain subquery (not one that was converted to an appendrel).
4694  */
4695  Query *subquery = rte->subquery;
4696  RelOptInfo *rel;
4697  TargetEntry *ste;
4698 
4699  /*
4700  * Punt if it's a whole-row var rather than a plain column reference.
4701  */
4702  if (var->varattno == InvalidAttrNumber)
4703  return;
4704 
4705  /*
4706  * Punt if subquery uses set operations or GROUP BY, as these will
4707  * mash underlying columns' stats beyond recognition. (Set ops are
4708  * particularly nasty; if we forged ahead, we would return stats
4709  * relevant to only the leftmost subselect...) DISTINCT is also
4710  * problematic, but we check that later because there is a possibility
4711  * of learning something even with it.
4712  */
4713  if (subquery->setOperations ||
4714  subquery->groupClause)
4715  return;
4716 
4717  /*
4718  * OK, fetch RelOptInfo for subquery. Note that we don't change the
4719  * rel returned in vardata, since caller expects it to be a rel of the
4720  * caller's query level. Because we might already be recursing, we
4721  * can't use that rel pointer either, but have to look up the Var's
4722  * rel afresh.
4723  */
4724  rel = find_base_rel(root, var->varno);
4725 
4726  /* If the subquery hasn't been planned yet, we have to punt */
4727  if (rel->subroot == NULL)
4728  return;
4729  Assert(IsA(rel->subroot, PlannerInfo));
4730 
4731  /*
4732  * Switch our attention to the subquery as mangled by the planner. It
4733  * was okay to look at the pre-planning version for the tests above,
4734  * but now we need a Var that will refer to the subroot's live
4735  * RelOptInfos. For instance, if any subquery pullup happened during
4736  * planning, Vars in the targetlist might have gotten replaced, and we
4737  * need to see the replacement expressions.
4738  */
4739  subquery = rel->subroot->parse;
4740  Assert(IsA(subquery, Query));
4741 
4742  /* Get the subquery output expression referenced by the upper Var */
4743  ste = get_tle_by_resno(subquery->targetList, var->varattno);
4744  if (ste == NULL || ste->resjunk)
4745  elog(ERROR, "subquery %s does not have attribute %d",
4746  rte->eref->aliasname, var->varattno);
4747  var = (Var *) ste->expr;
4748 
4749  /*
4750  * If subquery uses DISTINCT, we can't make use of any stats for the
4751  * variable ... but, if it's the only DISTINCT column, we are entitled
4752  * to consider it unique. We do the test this way so that it works
4753  * for cases involving DISTINCT ON.
4754  */
4755  if (subquery->distinctClause)
4756  {
4757  if (list_length(subquery->distinctClause) == 1 &&
4758  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4759  vardata->isunique = true;
4760  /* cannot go further */
4761  return;
4762  }
4763 
4764  /*
4765  * If the sub-query originated from a view with the security_barrier
4766  * attribute, we must not look at the variable's statistics, though it
4767  * seems all right to notice the existence of a DISTINCT clause. So
4768  * stop here.
4769  *
4770  * This is probably a harsher restriction than necessary; it's
4771  * certainly OK for the selectivity estimator (which is a C function,
4772  * and therefore omnipotent anyway) to look at the statistics. But
4773  * many selectivity estimators will happily *invoke the operator
4774  * function* to try to work out a good estimate - and that's not OK.
4775  * So for now, don't dig down for stats.
4776  */
4777  if (rte->security_barrier)
4778  return;
4779 
4780  /* Can only handle a simple Var of subquery's query level */
4781  if (var && IsA(var, Var) &&
4782  var->varlevelsup == 0)
4783  {
4784  /*
4785  * OK, recurse into the subquery. Note that the original setting
4786  * of vardata->isunique (which will surely be false) is left
4787  * unchanged in this situation. That's what we want, since even
4788  * if the underlying column is unique, the subquery may have
4789  * joined to other tables in a way that creates duplicates.
4790  */
4791  examine_simple_variable(rel->subroot, var, vardata);
4792  }
4793  }
4794  else
4795  {
4796  /*
4797  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
4798  * won't see RTE_JOIN here because join alias Vars have already been
4799  * flattened.) There's not much we can do with function outputs, but
4800  * maybe someday try to be smarter about VALUES and/or CTEs.
4801  */
4802  }
4803 }
4804 
4805 /*
4806  * Check whether it is permitted to call func_oid passing some of the
4807  * pg_statistic data in vardata. We allow this either if the user has SELECT
4808  * privileges on the table or column underlying the pg_statistic data or if
4809  * the function is marked leak-proof.
4810  */
4811 bool
4813 {
4814  if (vardata->acl_ok)
4815  return true;
4816 
4817  if (!OidIsValid(func_oid))
4818  return false;
4819 
4820  if (get_func_leakproof(func_oid))
4821  return true;
4822 
4823  ereport(DEBUG2,
4824  (errmsg_internal("not using statistics because function \"%s\" is not leak-proof",
4825  get_func_name(func_oid))));
4826  return false;
4827 }
4828 
4829 /*
4830  * get_variable_numdistinct
4831  * Estimate the number of distinct values of a variable.
4832  *
4833  * vardata: results of examine_variable
4834  * *isdefault: set to true if the result is a default rather than based on
4835  * anything meaningful.
4836  *
4837  * NB: be careful to produce a positive integral result, since callers may
4838  * compare the result to exact integer counts, or might divide by it.
4839  */
4840 double
4841 get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
4842 {
4843  double stadistinct;
4844  double stanullfrac = 0.0;
4845  double ntuples;
4846 
4847  *isdefault = false;
4848 
4849  /*
4850  * Determine the stadistinct value to use. There are cases where we can
4851  * get an estimate even without a pg_statistic entry, or can get a better
4852  * value than is in pg_statistic. Grab stanullfrac too if we can find it
4853  * (otherwise, assume no nulls, for lack of any better idea).
4854  */
4855  if (HeapTupleIsValid(vardata->statsTuple))
4856  {
4857  /* Use the pg_statistic entry */
4858  Form_pg_statistic stats;
4859 
4860  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4861  stadistinct = stats->stadistinct;
4862  stanullfrac = stats->stanullfrac;
4863  }
4864  else if (vardata->vartype == BOOLOID)
4865  {
4866  /*
4867  * Special-case boolean columns: presumably, two distinct values.
4868  *
4869  * Are there any other datatypes we should wire in special estimates
4870  * for?
4871  */
4872  stadistinct = 2.0;
4873  }
4874  else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
4875  {
4876  /*
4877  * If the Var represents a column of a VALUES RTE, assume it's unique.
4878  * This could of course be very wrong, but it should tend to be true
4879  * in well-written queries. We could consider examining the VALUES'
4880  * contents to get some real statistics; but that only works if the
4881  * entries are all constants, and it would be pretty expensive anyway.
4882  */
4883  stadistinct = -1.0; /* unique (and all non null) */
4884  }
4885  else
4886  {
4887  /*
4888  * We don't keep statistics for system columns, but in some cases we
4889  * can infer distinctness anyway.
4890  */
4891  if (vardata->var && IsA(vardata->var, Var))
4892  {
4893  switch (((Var *) vardata->var)->varattno)
4894  {
4896  stadistinct = -1.0; /* unique (and all non null) */
4897  break;
4899  stadistinct = 1.0; /* only 1 value */
4900  break;
4901  default:
4902  stadistinct = 0.0; /* means "unknown" */
4903  break;
4904  }
4905  }
4906  else
4907  stadistinct = 0.0; /* means "unknown" */
4908 
4909  /*
4910  * XXX consider using estimate_num_groups on expressions?
4911  */
4912  }
4913 
4914  /*
4915  * If there is a unique index or DISTINCT clause for the variable, assume
4916  * it is unique no matter what pg_statistic says; the statistics could be
4917  * out of date, or we might have found a partial unique index that proves
4918  * the var is unique for this query. However, we'd better still believe
4919  * the null-fraction statistic.
4920  */
4921  if (vardata->isunique)
4922  stadistinct = -1.0 * (1.0 - stanullfrac);
4923 
4924  /*
4925  * If we had an absolute estimate, use that.
4926  */
4927  if (stadistinct > 0.0)
4928  return clamp_row_est(stadistinct);
4929 
4930  /*
4931  * Otherwise we need to get the relation size; punt if not available.
4932  */
4933  if (vardata->rel == NULL)
4934  {
4935  *isdefault = true;
4936  return DEFAULT_NUM_DISTINCT;
4937  }
4938  ntuples = vardata->rel->tuples;
4939  if (ntuples <= 0.0)
4940  {
4941  *isdefault = true;
4942  return DEFAULT_NUM_DISTINCT;
4943  }
4944 
4945  /*
4946  * If we had a relative estimate, use that.
4947  */
4948  if (stadistinct < 0.0)
4949  return clamp_row_est(-stadistinct * ntuples);
4950 
4951  /*
4952  * With no data, estimate ndistinct = ntuples if the table is small, else
4953  * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
4954  * that the behavior isn't discontinuous.
4955  */
4956  if (ntuples < DEFAULT_NUM_DISTINCT)
4957  return clamp_row_est(ntuples);
4958 
4959  *isdefault = true;
4960  return DEFAULT_NUM_DISTINCT;
4961 }
4962 
4963 /*
4964  * get_variable_range
4965  * Estimate the minimum and maximum value of the specified variable.
4966  * If successful, store values in *min and *max, and return true.
4967  * If no data available, return false.
4968  *
4969  * sortop is the "<" comparison operator to use. This should generally
4970  * be "<" not ">", as only the former is likely to be found in pg_statistic.
4971  */
4972 static bool
4974  Datum *min, Datum *max)
4975 {
4976  Datum tmin = 0;
4977  Datum tmax = 0;
4978  bool have_data = false;
4979  int16 typLen;
4980  bool typByVal;
4981  Oid opfuncoid;
4982  AttStatsSlot sslot;
4983  int i;
4984 
4985  /*
4986  * XXX It's very tempting to try to use the actual column min and max, if
4987  * we can get them relatively-cheaply with an index probe. However, since
4988  * this function is called many times during join planning, that could
4989  * have unpleasant effects on planning speed. Need more investigation
4990  * before enabling this.
4991  */
4992 #ifdef NOT_USED
4993  if (get_actual_variable_range(root, vardata, sortop, min, max))
4994  return true;
4995 #endif
4996 
4997  if (!HeapTupleIsValid(vardata->statsTuple))
4998  {
4999  /* no stats available, so default result */
5000  return false;
5001  }
5002 
5003  /*
5004  * If we can't apply the sortop to the stats data, just fail. In
5005  * principle, if there's a histogram and no MCVs, we could return the
5006  * histogram endpoints without ever applying the sortop ... but it's
5007  * probably not worth trying, because whatever the caller wants to do with
5008  * the endpoints would likely fail the security check too.
5009  */
5010  if (!statistic_proc_security_check(vardata,
5011  (opfuncoid = get_opcode(sortop))))
5012  return false;
5013 
5014  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5015 
5016  /*
5017  * If there is a histogram, grab the first and last values.
5018  *
5019  * If there is a histogram that is sorted with some other operator than
5020  * the one we want, fail --- this suggests that there is data we can't
5021  * use.
5022  */
5023  if (get_attstatsslot(&sslot, vardata->statsTuple,
5024  STATISTIC_KIND_HISTOGRAM, sortop,
5026  {
5027  if (sslot.nvalues > 0)
5028  {
5029  tmin = datumCopy(sslot.values[0], typByVal, typLen);
5030  tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
5031  have_data = true;
5032  }
5033  free_attstatsslot(&sslot);
5034  }
5035  else if (get_attstatsslot(&sslot, vardata->statsTuple,
5036  STATISTIC_KIND_HISTOGRAM, InvalidOid,
5037  0))
5038  {
5039  free_attstatsslot(&sslot);
5040  return false;
5041  }
5042 
5043  /*
5044  * If we have most-common-values info, look for extreme MCVs. This is
5045  * needed even if we also have a histogram, since the histogram excludes
5046  * the MCVs. However, usually the MCVs will not be the extreme values, so
5047  * avoid unnecessary data copying.
5048  */
5049  if (get_attstatsslot(&sslot, vardata->statsTuple,
5050  STATISTIC_KIND_MCV, InvalidOid,
5052  {
5053  bool tmin_is_mcv = false;
5054  bool tmax_is_mcv = false;
5055  FmgrInfo opproc;
5056 
5057  fmgr_info(opfuncoid, &opproc);
5058 
5059  for (i = 0; i < sslot.nvalues; i++)
5060  {
5061  if (!have_data)
5062  {
5063  tmin = tmax = sslot.values[i];
5064  tmin_is_mcv = tmax_is_mcv = have_data = true;
5065  continue;
5066  }
5067  if (DatumGetBool(FunctionCall2Coll(&opproc,
5068  sslot.stacoll,
5069  sslot.values[i], tmin)))
5070  {
5071  tmin = sslot.values[i];
5072  tmin_is_mcv = true;
5073  }
5074  if (DatumGetBool(FunctionCall2Coll(&opproc,
5075  sslot.stacoll,
5076  tmax, sslot.values[i])))
5077  {
5078  tmax = sslot.values[i];
5079  tmax_is_mcv = true;
5080  }
5081  }
5082  if (tmin_is_mcv)
5083  tmin = datumCopy(tmin, typByVal, typLen);
5084  if (tmax_is_mcv)
5085  tmax = datumCopy(tmax, typByVal, typLen);
5086  free_attstatsslot(&sslot);
5087  }
5088 
5089  *min = tmin;
5090  *max = tmax;
5091  return have_data;
5092 }
5093 
5094 
5095 /*
5096  * get_actual_variable_range
5097  * Attempt to identify the current *actual* minimum and/or maximum
5098  * of the specified variable, by looking for a suitable btree index
5099  * and fetching its low and/or high values.
5100  * If successful, store values in *min and *max, and return true.
5101  * (Either pointer can be NULL if that endpoint isn't needed.)
5102  * If no data available, return false.
5103  *
5104  * sortop is the "<" comparison operator to use.
5105  */
5106 static bool
5108  Oid sortop,
5109  Datum *min, Datum *max)
5110 {
5111  bool have_data = false;
5112  RelOptInfo *rel = vardata->rel;
5113  RangeTblEntry *rte;
5114  ListCell *lc;
5115 
5116  /* No hope if no relation or it doesn't have indexes */
5117  if (rel == NULL || rel->indexlist == NIL)
5118  return false;
5119  /* If it has indexes it must be a plain relation */
5120  rte = root->simple_rte_array[rel->relid];
5121  Assert(rte->rtekind == RTE_RELATION);
5122 
5123  /* Search through the indexes to see if any match our problem */
5124  foreach(lc, rel->indexlist)
5125  {
5127  ScanDirection indexscandir;
5128 
5129  /* Ignore non-btree indexes */
5130  if (index->relam != BTREE_AM_OID)
5131  continue;
5132 
5133  /*
5134  * Ignore partial indexes --- we only want stats that cover the entire
5135  * relation.
5136  */
5137  if (index->indpred != NIL)
5138  continue;
5139 
5140  /*
5141  * The index list might include hypothetical indexes inserted by a
5142  * get_relation_info hook --- don't try to access them.
5143  */
5144  if (index->hypothetical)
5145  continue;
5146 
5147  /*
5148  * The first index column must match the desired variable and sort
5149  * operator --- but we can use a descending-order index.
5150  */
5151  if (!match_index_to_operand(vardata->var, 0, index))
5152  continue;
5153  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5154  {
5155  case BTLessStrategyNumber:
5156  if (index->reverse_sort[0])
5157  indexscandir = BackwardScanDirection;
5158  else
5159  indexscandir = ForwardScanDirection;
5160  break;
5162  if (index->reverse_sort[0])
5163  indexscandir = ForwardScanDirection;
5164  else
5165  indexscandir = BackwardScanDirection;
5166  break;
5167  default:
5168  /* index doesn't match the sortop */
5169  continue;
5170  }
5171 
5172  /*
5173  * Found a suitable index to extract data from. Set up some data that
5174  * can be used by both invocations of get_actual_variable_endpoint.
5175  */
5176  {
5177  MemoryContext tmpcontext;
5178  MemoryContext oldcontext;
5179  Relation heapRel;
5180  Relation indexRel;
5181  TupleTableSlot *slot;
5182  int16 typLen;
5183  bool typByVal;
5184  ScanKeyData scankeys[1];
5185 
5186  /* Make sure any cruft gets recycled when we're done */
5188  "get_actual_variable_range workspace",
5190  oldcontext = MemoryContextSwitchTo(tmpcontext);
5191 
5192  /*
5193  * Open the table and index so we can read from them. We should
5194  * already have some type of lock on each.
5195  */
5196  heapRel = table_open(rte->relid, NoLock);
5197  indexRel = index_open(index->indexoid, NoLock);
5198 
5199  /* build some stuff needed for indexscan execution */
5200  slot = table_slot_create(heapRel, NULL);
5201  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5202 
5203  /* set up an IS NOT NULL scan key so that we ignore nulls */
5204  ScanKeyEntryInitialize(&scankeys[0],
5206  1, /* index col to scan */
5207  InvalidStrategy, /* no strategy */
5208  InvalidOid, /* no strategy subtype */
5209  InvalidOid, /* no collation */
5210  InvalidOid, /* no reg proc for this */
5211  (Datum) 0); /* constant */
5212 
5213  /* If min is requested ... */
5214  if (min)
5215  {
5216  have_data = get_actual_variable_endpoint(heapRel,
5217  indexRel,
5218  indexscandir,
5219  scankeys,
5220  typLen,
5221  typByVal,
5222  slot,
5223  oldcontext,
5224  min);
5225  }
5226  else
5227  {
5228  /* If min not requested, assume index is nonempty */
5229  have_data = true;
5230  }
5231 
5232  /* If max is requested, and we didn't find the index is empty */
5233  if (max && have_data)
5234  {
5235  /* scan in the opposite direction; all else is the same */
5236  have_data = get_actual_variable_endpoint(heapRel,
5237  indexRel,
5238  -indexscandir,
5239  scankeys,
5240  typLen,
5241  typByVal,
5242  slot,
5243  oldcontext,
5244  max);
5245  }
5246 
5247  /* Clean everything up */
5249 
5250  index_close(indexRel, NoLock);
5251  table_close(heapRel, NoLock);
5252 
5253  MemoryContextSwitchTo(oldcontext);
5254  MemoryContextDelete(tmpcontext);
5255 
5256  /* And we're done */
5257  break;
5258  }
5259  }
5260 
5261  return have_data;
5262 }
5263 
5264 /*
5265  * Get one endpoint datum (min or max depending on indexscandir) from the
5266  * specified index. Return true if successful, false if index is empty.
5267  * On success, endpoint value is stored to *endpointDatum (and copied into
5268  * outercontext).
5269  *
5270  * scankeys is a 1-element scankey array set up to reject nulls.
5271  * typLen/typByVal describe the datatype of the index's first column.
5272  * tableslot is a slot suitable to hold table tuples, in case we need
5273  * to probe the heap.
5274  * (We could compute these values locally, but that would mean computing them
5275  * twice when get_actual_variable_range needs both the min and the max.)
5276  */
5277 static bool
5279  Relation indexRel,
5280  ScanDirection indexscandir,
5281  ScanKey scankeys,
5282  int16 typLen,
5283  bool typByVal,
5284  TupleTableSlot *tableslot,
5285  MemoryContext outercontext,
5286  Datum *endpointDatum)
5287 {
5288  bool have_data = false;
5289  SnapshotData SnapshotNonVacuumable;
5290  IndexScanDesc index_scan;
5291  Buffer vmbuffer = InvalidBuffer;
5292  ItemPointer tid;
5294  bool isnull[INDEX_MAX_KEYS];
5295  MemoryContext oldcontext;
5296 
5297  /*
5298  * We use the index-only-scan machinery for this. With mostly-static
5299  * tables that's a win because it avoids a heap visit. It's also a win
5300  * for dynamic data, but the reason is less obvious; read on for details.
5301  *
5302  * In principle, we should scan the index with our current active
5303  * snapshot, which is the best approximation we've got to what the query
5304  * will see when executed. But that won't be exact if a new snap is taken
5305  * before running the query, and it can be very expensive if a lot of
5306  * recently-dead or uncommitted rows exist at the beginning or end of the
5307  * index (because we'll laboriously fetch each one and reject it).
5308  * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
5309  * and uncommitted rows as well as normal visible rows. On the other
5310  * hand, it will reject known-dead rows, and thus not give a bogus answer
5311  * when the extreme value has been deleted (unless the deletion was quite
5312  * recent); that case motivates not using SnapshotAny here.
5313  *
5314  * A crucial point here is that SnapshotNonVacuumable, with
5315  * RecentGlobalXmin as horizon, yields the inverse of the condition that
5316  * the indexscan will use to decide that index entries are killable (see
5317  * heap_hot_search_buffer()). Therefore, if the snapshot rejects a tuple
5318  * (or more precisely, all tuples of a HOT chain) and we have to continue
5319  * scanning past it, we know that the indexscan will mark that index entry
5320  * killed. That means that the next get_actual_variable_endpoint() call
5321  * will not have to re-consider that index entry. In this way we avoid
5322  * repetitive work when this function is used a lot during planning.
5323  *
5324  * But using SnapshotNonVacuumable creates a hazard of its own. In a
5325  * recently-created index, some index entries may point at "broken" HOT
5326  * chains in which not all the tuple versions contain data matching the
5327  * index entry. The live tuple version(s) certainly do match the index,
5328  * but SnapshotNonVacuumable can accept recently-dead tuple versions that
5329  * don't match. Hence, if we took data from the selected heap tuple, we
5330  * might get a bogus answer that's not close to the index extremal value,
5331  * or could even be NULL. We avoid this hazard because we take the data
5332  * from the index entry not the heap.
5333  */
5334  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5335 
5336  index_scan = index_beginscan(heapRel, indexRel,
5337  &SnapshotNonVacuumable,
5338  1, 0);
5339  /* Set it up for index-only scan */
5340  index_scan->xs_want_itup = true;
5341  index_rescan(index_scan, scankeys, 1, NULL, 0);
5342 
5343  /* Fetch first/next tuple in specified direction */
5344  while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
5345  {
5346  if (!VM_ALL_VISIBLE(heapRel,
5348  &vmbuffer))
5349  {
5350  /* Rats, we have to visit the heap to check visibility */
5351  if (!index_fetch_heap(index_scan, tableslot))
5352  continue; /* no visible tuple, try next index entry */
5353 
5354  /* We don't actually need the heap tuple for anything */
5355  ExecClearTuple(tableslot);
5356 
5357  /*
5358  * We don't care whether there's more than one visible tuple in
5359  * the HOT chain; if any are visible, that's good enough.
5360  */
5361  }
5362 
5363  /*
5364  * We expect that btree will return data in IndexTuple not HeapTuple
5365  * format. It's not lossy either.
5366  */
5367  if (!index_scan->xs_itup)
5368  elog(ERROR, "no data returned for index-only scan");
5369  if (index_scan->xs_recheck)
5370  elog(ERROR, "unexpected recheck indication from btree");
5371 
5372  /* OK to deconstruct the index tuple */
5373  index_deform_tuple(index_scan->xs_itup,
5374  index_scan->xs_itupdesc,
5375  values, isnull);
5376 
5377  /* Shouldn't have got a null, but be careful */
5378  if (isnull[0])
5379  elog(ERROR, "found unexpected null value in index \"%s\"",
5380  RelationGetRelationName(indexRel));
5381 
5382  /* Copy the index column value out to caller's context */
5383  oldcontext = MemoryContextSwitchTo(outercontext);
5384  *endpointDatum = datumCopy(values[0], typByVal, typLen);
5385  MemoryContextSwitchTo(oldcontext);
5386  have_data = true;
5387  break;
5388  }
5389 
5390  if (vmbuffer != InvalidBuffer)
5391  ReleaseBuffer(vmbuffer);
5392  index_endscan(index_scan);
5393 
5394  return have_data;
5395 }
5396 
5397 /*
5398  * find_join_input_rel
5399  * Look up the input relation for a join.
5400  *
5401  * We assume that the input relation's RelOptInfo must have been constructed
5402  * already.
5403  */
5404 static RelOptInfo *
5406 {
5407  RelOptInfo *rel = NULL;
5408 
5409  switch (bms_membership(relids))
5410  {
5411  case BMS_EMPTY_SET:
5412  /* should not happen */
5413  break;
5414  case BMS_SINGLETON:
5415  rel = find_base_rel(root, bms_singleton_member(relids));
5416  break;
5417  case BMS_MULTIPLE:
5418  rel = find_join_rel(root, relids);
5419  break;
5420  }
5421 
5422  if (rel == NULL)
5423  elog(ERROR, "could not find RelOptInfo for given relids");
5424 
5425  return rel;
5426 }
5427 
5428 
5429 /*-------------------------------------------------------------------------
5430  *
5431  * Index cost estimation functions
5432  *
5433  *-------------------------------------------------------------------------
5434  */
5435 
5436 /*
5437  * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
5438  */
5439 List *
5441 {
5442  List *result = NIL;
5443  ListCell *lc;
5444 
5445  foreach(lc, indexclauses)
5446  {
5447  IndexClause *iclause = lfirst_node(IndexClause, lc);
5448  ListCell *lc2;
5449 
5450  foreach(lc2, iclause->indexquals)
5451  {
5452  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5453 
5454  result = lappend(result, rinfo);
5455  }
5456  }
5457  return result;
5458 }
5459 
5460 /*
5461  * Compute the total evaluation cost of the comparison operands in a list
5462  * of index qual expressions. Since we know these will be evaluated just
5463  * once per scan, there's no need to distinguish startup from per-row cost.
5464  *
5465  * This can be used either on the result of get_quals_from_indexclauses(),
5466  * or directly on an indexorderbys list. In both cases, we expect that the
5467  * index key expression is on the left side of binary clauses.
5468  */
5469 Cost
5471 {
5472  Cost qual_arg_cost = 0;
5473  ListCell *lc;
5474 
5475  foreach(lc, indexquals)
5476  {
5477  Expr *clause = (Expr *) lfirst(lc);
5478  Node *other_operand;
5479  QualCost index_qual_cost;
5480 
5481  /*
5482  * Index quals will have RestrictInfos, indexorderbys won't. Look
5483  * through RestrictInfo if present.
5484  */
5485  if (IsA(clause, RestrictInfo))
5486  clause = ((RestrictInfo *) clause)->clause;
5487 
5488  if (IsA(clause, OpExpr))
5489  {
5490  OpExpr *op = (OpExpr *) clause;
5491 
5492  other_operand = (Node *) lsecond(op->args);
5493  }
5494  else if (IsA(clause, RowCompareExpr))
5495  {
5496  RowCompareExpr *rc = (RowCompareExpr *) clause;
5497 
5498  other_operand = (Node *) rc->rargs;
5499  }
5500  else if (IsA(clause, ScalarArrayOpExpr))
5501  {
5502  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
5503 
5504  other_operand = (Node *) lsecond(saop->args);
5505  }
5506  else if (IsA(clause, NullTest))
5507  {
5508  other_operand = NULL;
5509  }
5510  else
5511  {
5512  elog(ERROR, "unsupported indexqual type: %d",
5513  (int) nodeTag(clause));
5514  other_operand = NULL; /* keep compiler quiet */
5515  }
5516 
5517  cost_qual_eval_node(&index_qual_cost, other_operand, root);
5518  qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
5519  }
5520  return qual_arg_cost;
5521 }
5522 
5523 void
5525  IndexPath *path,
5526  double loop_count,
5527  GenericCosts *costs)
5528 {
5529  IndexOptInfo *index = path->indexinfo;
5530  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
5531  List *indexOrderBys = path->indexorderbys;
5532  Cost indexStartupCost;
5533  Cost indexTotalCost;
5534  Selectivity indexSelectivity;
5535  double indexCorrelation;
5536  double numIndexPages;
5537  double numIndexTuples;
5538  double spc_random_page_cost;
5539  double num_sa_scans;
5540  double num_outer_scans;
5541  double num_scans;
5542  double qual_op_cost;
5543  double qual_arg_cost;
5544  List *selectivityQuals;
5545  ListCell *l;
5546 
5547  /*
5548  * If the index is partial, AND the index predicate with the explicitly
5549  * given indexquals to produce a more accurate idea of the index
5550  * selectivity.
5551  */
5552  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
5553 
5554  /*
5555  * Check for ScalarArrayOpExpr index quals, and estimate the number of
5556  * index scans that will be performed.
5557  */
5558  num_sa_scans = 1;
5559  foreach(l, indexQuals)
5560  {
5561  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
5562 
5563  if (IsA(rinfo->clause, ScalarArrayOpExpr))
5564  {
5565  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
5566  int alength = estimate_array_length(lsecond(saop->args));
5567 
5568  if (alength > 1)
5569  num_sa_scans *= alength;
5570  }
5571  }
5572 
5573  /* Estimate the fraction of main-table tuples that will be visited */
5574  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
5575  index->rel->relid,
5576  JOIN_INNER,
5577  NULL);
5578 
5579  /*
5580  * If caller didn't give us an estimate, estimate the number of index
5581  * tuples that will be visited. We do it in this rather peculiar-looking
5582  * way in order to get the right answer for partial indexes.
5583  */
5584  numIndexTuples = costs->numIndexTuples;
5585  if (numIndexTuples <= 0.0)
5586  {
5587  numIndexTuples = indexSelectivity * index->rel->tuples;
5588 
5589  /*
5590  * The above calculation counts all the tuples visited across all
5591  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
5592  * average per-indexscan number, so adjust. This is a handy place to
5593  * round to integer, too. (If caller supplied tuple estimate, it's
5594  * responsible for handling these considerations.)
5595  */
5596  numIndexTuples = rint(numIndexTuples / num_sa_scans);
5597  }
5598 
5599  /*
5600  * We can bound the number of tuples by the index size in any case. Also,
5601  * always estimate at least one tuple is touched, even when
5602  * indexSelectivity estimate is tiny.
5603  */
5604  if (numIndexTuples > index->tuples)
5605  numIndexTuples = index->tuples;
5606  if (numIndexTuples < 1.0)
5607  numIndexTuples = 1.0;
5608 
5609  /*
5610  * Estimate the number of index pages that will be retrieved.
5611  *
5612  * We use the simplistic method of taking a pro-rata fraction of the total
5613  * number of index pages. In effect, this counts only leaf pages and not
5614  * any overhead such as index metapage or upper tree levels.
5615  *
5616  * In practice access to upper index levels is often nearly free because
5617  * those tend to stay in cache under load; moreover, the cost involved is
5618  * highly dependent on index type. We therefore ignore such costs here
5619  * and leave it to the caller to add a suitable charge if needed.
5620  */
5621  if (index->pages > 1 && index->tuples > 1)
5622  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
5623  else
5624  numIndexPages = 1.0;
5625 
5626  /* fetch estimated page cost for tablespace containing index */
5628  &spc_random_page_cost,
5629  NULL);
5630 
5631  /*
5632  * Now compute the disk access costs.
5633  *
5634  * The above calculations are all per-index-scan. However, if we are in a
5635  * nestloop inner scan, we can expect the scan to be repeated (with
5636  * different search keys) for each row of the outer relation. Likewise,
5637  * ScalarArrayOpExpr quals result in multiple index scans. This creates
5638  * the potential for cache effects to reduce the number of disk page
5639  * fetches needed. We want to estimate the average per-scan I/O cost in
5640  * the presence of caching.
5641  *
5642  * We use the Mackert-Lohman formula (see costsize.c for details) to
5643  * estimate the total number of page fetches that occur. While this
5644  * wasn't what it was designed for, it seems a reasonable model anyway.
5645  * Note that we are counting pages not tuples anymore, so we take N = T =
5646  * index size, as if there were one "tuple" per page.
5647  */
5648  num_outer_scans = loop_count;
5649  num_scans = num_sa_scans * num_outer_scans;
5650 
5651  if (num_scans > 1)
5652  {
5653  double pages_fetched;
5654 
5655  /* total page fetches ignoring cache effects */
5656  pages_fetched = numIndexPages * num_scans;
5657 
5658  /* use Mackert and Lohman formula to adjust for cache effects */
5659  pages_fetched = index_pages_fetched(pages_fetched,
5660  index->pages,
5661  (double) index->pages,
5662  root);
5663 
5664  /*
5665  * Now compute the total disk access cost, and then report a pro-rated
5666  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
5667  * since that's internal to the indexscan.)
5668  */
5669  indexTotalCost = (pages_fetched * spc_random_page_cost)
5670  / num_outer_scans;
5671  }
5672  else
5673  {
5674  /*
5675  * For a single index scan, we just charge spc_random_page_cost per
5676  * page touched.
5677  */
5678  indexTotalCost = numIndexPages * spc_random_page_cost;
5679  }
5680 
5681  /*
5682  * CPU cost: any complex expressions in the indexquals will need to be
5683  * evaluated once at the start of the scan to reduce them to runtime keys
5684  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
5685  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
5686  * indexqual operator. Because we have numIndexTuples as a per-scan
5687  * number, we have to multiply by num_sa_scans to get the correct result
5688  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
5689  * ORDER BY expressions.
5690  *
5691  * Note: this neglects the possible costs of rechecking lossy operators.
5692  * Detecting that that might be needed seems more expensive than it's
5693  * worth, though, considering all the other inaccuracies here ...
5694  */
5695  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
5696  index_other_operands_eval_cost(root, indexOrderBys);
5697  qual_op_cost = cpu_operator_cost *
5698  (list_length(indexQuals) + list_length(indexOrderBys));
5699 
5700  indexStartupCost = qual_arg_cost;
5701  indexTotalCost += qual_arg_cost;
5702  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
5703 
5704  /*
5705  * Generic assumption about index correlation: there isn't any.
5706  */
5707  indexCorrelation = 0.0;
5708 
5709  /*
5710  * Return everything to caller.
5711  */
5712  costs->indexStartupCost = indexStartupCost;
5713  costs->indexTotalCost = indexTotalCost;
5714  costs->indexSelectivity = indexSelectivity;
5715  costs->indexCorrelation = indexCorrelation;
5716  costs->numIndexPages = numIndexPages;
5717  costs->numIndexTuples = numIndexTuples;
5718  costs->spc_random_page_cost = spc_random_page_cost;
5719  costs->num_sa_scans = num_sa_scans;
5720 }
5721 
5722 /*
5723  * If the index is partial, add its predicate to the given qual list.
5724  *
5725  * ANDing the index predicate with the explicitly given indexquals produces
5726  * a more accurate idea of the index's selectivity. However, we need to be
5727  * careful not to insert redundant clauses, because clauselist_selectivity()
5728  * is easily fooled into computing a too-low selectivity estimate. Our
5729  * approach is to add only the predicate clause(s) that cannot be proven to
5730  * be implied by the given indexquals. This successfully handles cases such
5731  * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
5732  * There are many other cases where we won't detect redundancy, leading to a
5733  * too-low selectivity estimate, which will bias the system in favor of using
5734  * partial indexes where possible. That is not necessarily bad though.
5735  *
5736  * Note that indexQuals contains RestrictInfo nodes while the indpred
5737  * does not, so the output list will be mixed. This is OK for both
5738  * predicate_implied_by() and clauselist_selectivity(), but might be
5739  * problematic if the result were passed to other things.
5740  */
5741 List *
5743 {
5744  List *predExtraQuals = NIL;
5745  ListCell *lc;
5746 
5747  if (index->indpred == NIL)
5748  return indexQuals;
5749 
5750  foreach(lc, index->indpred)
5751  {
5752  Node *predQual = (Node *) lfirst(lc);
5753  List *oneQual = list_make1(predQual);
5754 
5755  if (!predicate_implied_by(oneQual, indexQuals, false))
5756  predExtraQuals = list_concat(predExtraQuals, oneQual);
5757  }
5758  return list_concat(predExtraQuals, indexQuals);
5759 }
5760 
5761 
5762 void
5763 btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
5764  Cost *indexStartupCost, Cost *indexTotalCost,
5765  Selectivity *indexSelectivity, double *indexCorrelation,
5766  double *indexPages)
5767 {
5768  IndexOptInfo *index = path->indexinfo;
5769  GenericCosts costs;
5770  Oid relid;
5771  AttrNumber colnum;
5772  VariableStatData vardata;
5773  double numIndexTuples;
5774  Cost descentCost;
5775  List *indexBoundQuals;
5776  int indexcol;
5777  bool eqQualHere;
5778  bool found_saop;
5779  bool found_is_null_op;
5780  double num_sa_scans;
5781  ListCell *lc;
5782 
5783  /*
5784  * For a btree scan, only leading '=' quals plus inequality quals for the
5785  * immediately next attribute contribute to index selectivity (these are
5786  * the "boundary quals" that determine the starting and stopping points of
5787  * the index scan). Additional quals can suppress visits to the heap, so
5788  * it's OK to count them in indexSelectivity, but they should not count
5789  * for estimating numIndexTuples. So we must examine the given indexquals
5790  * to find out which ones count as boundary quals. We rely on the
5791  * knowledge that they are given in index column order.
5792  *
5793  * For a RowCompareExpr, we consider only the first column, just as
5794  * rowcomparesel() does.
5795  *
5796  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
5797  * index scans not one, but the ScalarArrayOpExpr's operator can be
5798  * considered to act the same as it normally does.
5799  */
5800  indexBoundQuals = NIL;
5801  indexcol = 0;
5802  eqQualHere = false;
5803  found_saop = false;
5804  found_is_null_op = false;
5805  num_sa_scans = 1;
5806  foreach(lc, path->indexclauses)
5807  {
5808  IndexClause *iclause = lfirst_node(IndexClause, lc);
5809  ListCell *lc2;
5810 
5811  if (indexcol != iclause->indexcol)
5812  {
5813  /* Beginning of a new column's quals */
5814  if (!eqQualHere)
5815  break; /* done if no '=' qual for indexcol */
5816  eqQualHere = false;
5817  indexcol++;
5818  if (indexcol != iclause->indexcol)
5819  break; /* no quals at all for indexcol */
5820  }
5821 
5822  /* Examine each indexqual associated with this index clause */
5823  foreach(lc2, iclause->indexquals)
5824  {
5825  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5826  Expr *clause = rinfo->clause;
5827  Oid clause_op = InvalidOid;
5828  int op_strategy;
5829 
5830  if (IsA(clause, OpExpr))
5831  {
5832  OpExpr *op = (OpExpr *) clause;
5833 
5834  clause_op = op->opno;
5835  }
5836  else if (IsA(clause, RowCompareExpr))
5837  {
5838  RowCompareExpr *rc = (RowCompareExpr *) clause;
5839 
5840  clause_op = linitial_oid(rc->opnos);
5841  }
5842  else if (IsA(clause, ScalarArrayOpExpr))
5843  {
5844  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
5845  Node *other_operand = (Node *) lsecond(saop->args);
5846  int alength = estimate_array_length(other_operand);
5847 
5848  clause_op = saop->opno;
5849  found_saop = true;
5850  /* count number of SA scans induced by indexBoundQuals only */
5851  if (alength > 1)
5852  num_sa_scans *= alength;
5853  }
5854  else if (IsA(clause, NullTest))
5855  {
5856  NullTest *nt = (NullTest *) clause;
5857 
5858  if (nt->nulltesttype == IS_NULL)
5859  {
5860  found_is_null_op = true;
5861  /* IS NULL is like = for selectivity purposes */
5862  eqQualHere = true;
5863  }
5864  }
5865  else
5866  elog(ERROR, "unsupported indexqual type: %d",
5867  (int) nodeTag(clause));
5868 
5869  /* check for equality operator */
5870  if (OidIsValid(clause_op))
5871  {
5872  op_strategy = get_op_opfamily_strategy(clause_op,
5873  index->opfamily[indexcol]);
5874  Assert(op_strategy != 0); /* not a member of opfamily?? */
5875  if (op_strategy == BTEqualStrategyNumber)
5876  eqQualHere = true;
5877  }
5878 
5879  indexBoundQuals = lappend(indexBoundQuals, rinfo);
5880  }
5881  }
5882 
5883  /*
5884  * If index is unique and we found an '=' clause for each column, we can
5885  * just assume numIndexTuples = 1 and skip the expensive
5886  * clauselist_selectivity calculations. However, a ScalarArrayOp or
5887  * NullTest invalidates that theory, even though it sets eqQualHere.
5888  */
5889  if (index->unique &&
5890  indexcol == index->nkeycolumns - 1 &&
5891  eqQualHere &&
5892  !found_saop &&
5893  !found_is_null_op)
5894  numIndexTuples = 1.0;
5895  else
5896  {
5897  List *selectivityQuals;
5898  Selectivity btreeSelectivity;
5899 
5900  /*
5901  * If the index is partial, AND the index predicate with the
5902  * index-bound quals to produce a more accurate idea of the number of
5903  * rows covered by the bound conditions.
5904  */
5905  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
5906 
5907  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
5908  index->rel->relid,
5909  JOIN_INNER,
5910  NULL);
5911  numIndexTuples = btreeSelectivity * index->rel->tuples;
5912 
5913  /*
5914  * As in genericcostestimate(), we have to adjust for any
5915  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
5916  * to integer.
5917  */
5918  numIndexTuples = rint(numIndexTuples / num_sa_scans);
5919  }
5920 
5921  /*
5922  * Now do generic index cost estimation.
5923  */
5924  MemSet(&costs, 0, sizeof(costs));
5925  costs.numIndexTuples = numIndexTuples;
5926 
5927  genericcostestimate(root, path, loop_count, &costs);
5928 
5929  /*
5930  * Add a CPU-cost component to represent the costs of initial btree
5931  * descent. We don't charge any I/O cost for touching upper btree levels,
5932  * since they tend to stay in cache, but we still have to do about log2(N)
5933  * comparisons to descend a btree of N leaf tuples. We charge one
5934  * cpu_operator_cost per comparison.
5935  *
5936  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
5937  * ones after the first one are not startup cost so far as the overall
5938  * plan is concerned, so add them only to "total" cost.
5939  */
5940  if (index->tuples > 1) /* avoid computing log(0) */
5941  {
5942  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
5943  costs.indexStartupCost += descentCost;
5944  costs.indexTotalCost += costs.num_sa_scans * descentCost;
5945  }
5946 
5947  /*
5948  * Even though we're not charging I/O cost for touching upper btree pages,
5949  * it's still reasonable to charge some CPU cost per page descended
5950  * through. Moreover, if we had no such charge at all, bloated indexes
5951  * would appear to have the same search cost as unbloated ones, at least
5952  * in cases where only a single leaf page is expected to be visited. This
5953  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
5954  * touched. The number of such pages is btree tree height plus one (ie,
5955  * we charge for the leaf page too). As above, charge once per SA scan.
5956  */
5957  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
5958  costs.indexStartupCost += descentCost;
5959  costs.indexTotalCost += costs.num_sa_scans * descentCost;
5960 
5961  /*
5962  * If we can get an estimate of the first column's ordering correlation C
5963  * from pg_statistic, estimate the index correlation as C for a
5964  * single-column index, or C * 0.75 for multiple columns. (The idea here
5965  * is that multiple columns dilute the importance of the first column's
5966  * ordering, but don't negate it entirely. Before 8.0 we divided the
5967  * correlation by the number of columns, but that seems too strong.)
5968  */
5969  MemSet(&vardata, 0, sizeof(vardata));
5970 
5971  if (index->indexkeys[0] != 0)
5972  {
5973  /* Simple variable --- look to stats for the underlying table */
5974  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
5975 
5976  Assert(rte->rtekind == RTE_RELATION);
5977  relid = rte->relid;
5978  Assert(relid != InvalidOid);
5979  colnum = index->indexkeys[0];
5980 
5982  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
5983  {
5984  /*
5985  * The hook took control of acquiring a stats tuple. If it did
5986  * supply a tuple, it'd better have supplied a freefunc.
5987  */
5988  if (HeapTupleIsValid(vardata.statsTuple) &&
5989  !vardata.freefunc)
5990  elog(ERROR, "no function provided to release variable stats with");
5991  }
5992  else
5993  {
5995  ObjectIdGetDatum(relid),
5996  Int16GetDatum(colnum),
5997  BoolGetDatum(rte->inh));
5998  vardata.freefunc = ReleaseSysCache;
5999  }
6000  }
6001  else
6002  {
6003  /* Expression --- maybe there are stats for the index itself */
6004  relid = index->indexoid;
6005  colnum = 1;
6006 
6007  if (get_index_stats_hook &&
6008  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6009  {
6010  /*
6011  * The hook took control of acquiring a stats tuple. If it did
6012  * supply a tuple, it'd better have supplied a freefunc.
6013  */
6014  if (HeapTupleIsValid(vardata.statsTuple) &&
6015  !vardata.freefunc)
6016  elog(ERROR, "no function provided to release variable stats with");
6017  }
6018  else
6019  {
6021  ObjectIdGetDatum(relid),
6022  Int16GetDatum(colnum),
6023  BoolGetDatum(false));
6024  vardata.freefunc = ReleaseSysCache;
6025  }
6026  }
6027 
6028  if (HeapTupleIsValid(vardata.statsTuple))
6029  {
6030  Oid sortop;
6031  AttStatsSlot sslot;
6032 
6033  sortop = get_opfamily_member(index->opfamily[0],
6034  index->opcintype[0],
6035  index->opcintype[0],
6037  if (OidIsValid(sortop) &&
6038  get_attstatsslot(&sslot, vardata.statsTuple,
6039  STATISTIC_KIND_CORRELATION, sortop,
6041  {
6042  double varCorrelation;
6043 
6044  Assert(sslot.nnumbers == 1);
6045  varCorrelation = sslot.numbers[0];
6046 
6047  if (index->reverse_sort[0])
6048  varCorrelation = -varCorrelation;
6049 
6050  if (index->nkeycolumns > 1)
6051  costs.indexCorrelation = varCorrelation * 0.75;
6052  else
6053  costs.indexCorrelation = varCorrelation;
6054 
6055  free_attstatsslot(&sslot);
6056  }
6057  }
6058 
6059  ReleaseVariableStats(vardata);
6060 
6061  *indexStartupCost = costs.indexStartupCost;
6062  *indexTotalCost = costs.indexTotalCost;
6063  *indexSelectivity = costs.indexSelectivity;
6064  *indexCorrelation = costs.indexCorrelation;
6065  *indexPages = costs.numIndexPages;
6066 }
6067 
6068 void
6069 hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
6070  Cost *indexStartupCost, Cost *indexTotalCost,
6071  Selectivity *indexSelectivity, double *indexCorrelation,
6072  double *indexPages)
6073 {
6074  GenericCosts costs;
6075 
6076  MemSet(&costs, 0, sizeof(costs));
6077 
6078  genericcostestimate(root, path, loop_count, &costs);
6079 
6080  /*
6081  * A hash index has no descent costs as such, since the index AM can go
6082  * directly to the target bucket after computing the hash value. There
6083  * are a couple of other hash-specific costs that we could conceivably add
6084  * here, though:
6085  *
6086  * Ideally we'd charge spc_random_page_cost for each page in the target
6087  * bucket, not just the numIndexPages pages that genericcostestimate
6088  * thought we'd visit. However in most cases we don't know which bucket
6089  * that will be. There's no point in considering the average bucket size
6090  * because the hash AM makes sure that's always one page.
6091  *
6092  * Likewise, we could consider charging some CPU for each index tuple in
6093  * the bucket, if we knew how many there were. But the per-tuple cost is
6094  * just a hash value comparison, not a general datatype-dependent
6095  * comparison, so any such charge ought to be quite a bit less than
6096  * cpu_operator_cost; which makes it probably not worth worrying about.
6097  *
6098  * A bigger issue is that chance hash-value collisions will result in
6099  * wasted probes into the heap. We don't currently attempt to model this
6100  * cost on the grounds that it's rare, but maybe it's not rare enough.
6101  * (Any fix for this ought to consider the generic lossy-operator problem,
6102  * though; it's not entirely hash-specific.)
6103  */
6104 
6105  *indexStartupCost = costs.indexStartupCost;
6106  *indexTotalCost = costs.indexTotalCost;
6107  *indexSelectivity = costs.indexSelectivity;
6108  *indexCorrelation = costs.indexCorrelation;
6109  *indexPages = costs.numIndexPages;
6110 }
6111 
6112 void
6113 gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
6114  Cost *indexStartupCost, Cost *indexTotalCost,
6115  Selectivity *indexSelectivity, double *indexCorrelation,
6116  double *indexPages)
6117 {
6118  IndexOptInfo *index = path->indexinfo;
6119  GenericCosts costs;
6120  Cost descentCost;
6121 
6122  MemSet(&costs, 0, sizeof(costs));
6123 
6124  genericcostestimate(root, path, loop_count, &costs);
6125 
6126  /*
6127  * We model index descent costs similarly to those for btree, but to do
6128  * that we first need an idea of the tree height. We somewhat arbitrarily
6129  * assume that the fanout is 100, meaning the tree height is at most
6130  * log100(index->pages).
6131  *
6132  * Although this computation isn't really expensive enough to require
6133  * caching, we might as well use index->tree_height to cache it.
6134  */
6135  if (index->tree_height < 0) /* unknown? */
6136  {
6137  if (index->pages > 1) /* avoid computing log(0) */
6138  index->tree_height = (int) (log(index->pages) / log(100.0));
6139  else
6140  index->tree_height = 0;
6141  }
6142 
6143  /*
6144  * Add a CPU-cost component to represent the costs of initial descent. We
6145  * just use log(N) here not log2(N) since the branching factor isn't
6146  * necessarily two anyway. As for btree, charge once per SA scan.
6147  */
6148  if (index->tuples > 1) /* avoid computing log(0) */
6149  {
6150  descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6151  costs.indexStartupCost += descentCost;
6152  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6153  }
6154 
6155  /*
6156  * Likewise add a per-page charge, calculated the same as for btrees.
6157  */
6158  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6159  costs.indexStartupCost += descentCost;
6160  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6161 
6162  *indexStartupCost = costs.indexStartupCost;
6163  *indexTotalCost = costs.indexTotalCost;
6164  *indexSelectivity = costs.indexSelectivity;
6165  *indexCorrelation = costs.indexCorrelation;
6166  *indexPages = costs.numIndexPages;
6167 }
6168 
6169 void
6170 spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
6171  Cost *indexStartupCost, Cost *indexTotalCost,
6172  Selectivity *indexSelectivity, double *indexCorrelation,
6173  double *indexPages)
6174 {
6175  IndexOptI