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