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