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