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