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