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