PostgreSQL Source Code  git master
selfuncs.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * selfuncs.c
4  * Selectivity functions and index cost estimation functions for
5  * standard operators and index access methods.
6  *
7  * Selectivity routines are registered in the pg_operator catalog
8  * in the "oprrest" and "oprjoin" attributes.
9  *
10  * Index cost functions are located via the index AM's API struct,
11  * which is obtained from the handler function registered in pg_am.
12  *
13  * Portions Copyright (c) 1996-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  float8 result;
2771 
2772  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2773  {
2774  /*
2775  * For semi-joins, if there is more than one distinct value in the RHS
2776  * relation then every non-null LHS row must find a row to join since
2777  * it can only be equal to one of them. We'll assume that there is
2778  * always more than one distinct RHS value for the sake of stability,
2779  * though in theory we could have special cases for empty RHS
2780  * (selectivity = 0) and single-distinct-value RHS (selectivity =
2781  * fraction of LHS that has the same value as the single RHS value).
2782  *
2783  * For anti-joins, if we use the same assumption that there is more
2784  * than one distinct key in the RHS relation, then every non-null LHS
2785  * row must be suppressed by the anti-join.
2786  *
2787  * So either way, the selectivity estimate should be 1 - nullfrac.
2788  */
2789  VariableStatData leftvar;
2790  VariableStatData rightvar;
2791  bool reversed;
2792  HeapTuple statsTuple;
2793  double nullfrac;
2794 
2795  get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
2796  statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
2797  if (HeapTupleIsValid(statsTuple))
2798  nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
2799  else
2800  nullfrac = 0.0;
2801  ReleaseVariableStats(leftvar);
2802  ReleaseVariableStats(rightvar);
2803 
2804  result = 1.0 - nullfrac;
2805  }
2806  else
2807  {
2808  /*
2809  * We want 1 - eqjoinsel() where the equality operator is the one
2810  * associated with this != operator, that is, its negator.
2811  */
2812  Oid eqop = get_negator(operator);
2813 
2814  if (eqop)
2815  {
2817  PointerGetDatum(root),
2818  ObjectIdGetDatum(eqop),
2819  PointerGetDatum(args),
2820  Int16GetDatum(jointype),
2821  PointerGetDatum(sjinfo)));
2822  }
2823  else
2824  {
2825  /* Use default selectivity (should we raise an error instead?) */
2826  result = DEFAULT_EQ_SEL;
2827  }
2828  result = 1.0 - result;
2829  }
2830 
2831  PG_RETURN_FLOAT8(result);
2832 }
2833 
2834 /*
2835  * scalarltjoinsel - Join selectivity of "<" for scalars
2836  */
2837 Datum
2839 {
2841 }
2842 
2843 /*
2844  * scalarlejoinsel - Join selectivity of "<=" for scalars
2845  */
2846 Datum
2848 {
2850 }
2851 
2852 /*
2853  * scalargtjoinsel - Join selectivity of ">" for scalars
2854  */
2855 Datum
2857 {
2859 }
2860 
2861 /*
2862  * scalargejoinsel - Join selectivity of ">=" for scalars
2863  */
2864 Datum
2866 {
2868 }
2869 
2870 /*
2871  * patternjoinsel - Generic code for pattern-match join selectivity.
2872  */
2873 static double
2875 {
2876  /* For the moment we just punt. */
2877  return negate ? (1.0 - DEFAULT_MATCH_SEL) : DEFAULT_MATCH_SEL;
2878 }
2879 
2880 /*
2881  * regexeqjoinsel - Join selectivity of regular-expression pattern match.
2882  */
2883 Datum
2885 {
2887 }
2888 
2889 /*
2890  * icregexeqjoinsel - Join selectivity of case-insensitive regex match.
2891  */
2892 Datum
2894 {
2896 }
2897 
2898 /*
2899  * likejoinsel - Join selectivity of LIKE pattern match.
2900  */
2901 Datum
2903 {
2905 }
2906 
2907 /*
2908  * iclikejoinsel - Join selectivity of ILIKE pattern match.
2909  */
2910 Datum
2912 {
2914 }
2915 
2916 /*
2917  * regexnejoinsel - Join selectivity of regex non-match.
2918  */
2919 Datum
2921 {
2923 }
2924 
2925 /*
2926  * icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
2927  */
2928 Datum
2930 {
2932 }
2933 
2934 /*
2935  * nlikejoinsel - Join selectivity of LIKE pattern non-match.
2936  */
2937 Datum
2939 {
2941 }
2942 
2943 /*
2944  * icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
2945  */
2946 Datum
2948 {
2950 }
2951 
2952 /*
2953  * mergejoinscansel - Scan selectivity of merge join.
2954  *
2955  * A merge join will stop as soon as it exhausts either input stream.
2956  * Therefore, if we can estimate the ranges of both input variables,
2957  * we can estimate how much of the input will actually be read. This
2958  * can have a considerable impact on the cost when using indexscans.
2959  *
2960  * Also, we can estimate how much of each input has to be read before the
2961  * first join pair is found, which will affect the join's startup time.
2962  *
2963  * clause should be a clause already known to be mergejoinable. opfamily,
2964  * strategy, and nulls_first specify the sort ordering being used.
2965  *
2966  * The outputs are:
2967  * *leftstart is set to the fraction of the left-hand variable expected
2968  * to be scanned before the first join pair is found (0 to 1).
2969  * *leftend is set to the fraction of the left-hand variable expected
2970  * to be scanned before the join terminates (0 to 1).
2971  * *rightstart, *rightend similarly for the right-hand variable.
2972  */
2973 void
2975  Oid opfamily, int strategy, bool nulls_first,
2976  Selectivity *leftstart, Selectivity *leftend,
2977  Selectivity *rightstart, Selectivity *rightend)
2978 {
2979  Node *left,
2980  *right;
2981  VariableStatData leftvar,
2982  rightvar;
2983  int op_strategy;
2984  Oid op_lefttype;
2985  Oid op_righttype;
2986  Oid opno,
2987  lsortop,
2988  rsortop,
2989  lstatop,
2990  rstatop,
2991  ltop,
2992  leop,
2993  revltop,
2994  revleop;
2995  bool isgt;
2996  Datum leftmin,
2997  leftmax,
2998  rightmin,
2999  rightmax;
3000  double selec;
3001 
3002  /* Set default results if we can't figure anything out. */
3003  /* XXX should default "start" fraction be a bit more than 0? */
3004  *leftstart = *rightstart = 0.0;
3005  *leftend = *rightend = 1.0;
3006 
3007  /* Deconstruct the merge clause */
3008  if (!is_opclause(clause))
3009  return; /* shouldn't happen */
3010  opno = ((OpExpr *) clause)->opno;
3011  left = get_leftop((Expr *) clause);
3012  right = get_rightop((Expr *) clause);
3013  if (!right)
3014  return; /* shouldn't happen */
3015 
3016  /* Look for stats for the inputs */
3017  examine_variable(root, left, 0, &leftvar);
3018  examine_variable(root, right, 0, &rightvar);
3019 
3020  /* Extract the operator's declared left/right datatypes */
3021  get_op_opfamily_properties(opno, opfamily, false,
3022  &op_strategy,
3023  &op_lefttype,
3024  &op_righttype);
3025  Assert(op_strategy == BTEqualStrategyNumber);
3026 
3027  /*
3028  * Look up the various operators we need. If we don't find them all, it
3029  * probably means the opfamily is broken, but we just fail silently.
3030  *
3031  * Note: we expect that pg_statistic histograms will be sorted by the '<'
3032  * operator, regardless of which sort direction we are considering.
3033  */
3034  switch (strategy)
3035  {
3036  case BTLessStrategyNumber:
3037  isgt = false;
3038  if (op_lefttype == op_righttype)
3039  {
3040  /* easy case */
3041  ltop = get_opfamily_member(opfamily,
3042  op_lefttype, op_righttype,
3044  leop = get_opfamily_member(opfamily,
3045  op_lefttype, op_righttype,
3047  lsortop = ltop;
3048  rsortop = ltop;
3049  lstatop = lsortop;
3050  rstatop = rsortop;
3051  revltop = ltop;
3052  revleop = leop;
3053  }
3054  else
3055  {
3056  ltop = get_opfamily_member(opfamily,
3057  op_lefttype, op_righttype,
3059  leop = get_opfamily_member(opfamily,
3060  op_lefttype, op_righttype,
3062  lsortop = get_opfamily_member(opfamily,
3063  op_lefttype, op_lefttype,
3065  rsortop = get_opfamily_member(opfamily,
3066  op_righttype, op_righttype,
3068  lstatop = lsortop;
3069  rstatop = rsortop;
3070  revltop = get_opfamily_member(opfamily,
3071  op_righttype, op_lefttype,
3073  revleop = get_opfamily_member(opfamily,
3074  op_righttype, op_lefttype,
3076  }
3077  break;
3079  /* descending-order case */
3080  isgt = true;
3081  if (op_lefttype == op_righttype)
3082  {
3083  /* easy case */
3084  ltop = get_opfamily_member(opfamily,
3085  op_lefttype, op_righttype,
3087  leop = get_opfamily_member(opfamily,
3088  op_lefttype, op_righttype,
3090  lsortop = ltop;
3091  rsortop = ltop;
3092  lstatop = get_opfamily_member(opfamily,
3093  op_lefttype, op_lefttype,
3095  rstatop = lstatop;
3096  revltop = ltop;
3097  revleop = leop;
3098  }
3099  else
3100  {
3101  ltop = get_opfamily_member(opfamily,
3102  op_lefttype, op_righttype,
3104  leop = get_opfamily_member(opfamily,
3105  op_lefttype, op_righttype,
3107  lsortop = get_opfamily_member(opfamily,
3108  op_lefttype, op_lefttype,
3110  rsortop = get_opfamily_member(opfamily,
3111  op_righttype, op_righttype,
3113  lstatop = get_opfamily_member(opfamily,
3114  op_lefttype, op_lefttype,
3116  rstatop = get_opfamily_member(opfamily,
3117  op_righttype, op_righttype,
3119  revltop = get_opfamily_member(opfamily,
3120  op_righttype, op_lefttype,
3122  revleop = get_opfamily_member(opfamily,
3123  op_righttype, op_lefttype,
3125  }
3126  break;
3127  default:
3128  goto fail; /* shouldn't get here */
3129  }
3130 
3131  if (!OidIsValid(lsortop) ||
3132  !OidIsValid(rsortop) ||
3133  !OidIsValid(lstatop) ||
3134  !OidIsValid(rstatop) ||
3135  !OidIsValid(ltop) ||
3136  !OidIsValid(leop) ||
3137  !OidIsValid(revltop) ||
3138  !OidIsValid(revleop))
3139  goto fail; /* insufficient info in catalogs */
3140 
3141  /* Try to get ranges of both inputs */
3142  if (!isgt)
3143  {
3144  if (!get_variable_range(root, &leftvar, lstatop,
3145  &leftmin, &leftmax))
3146  goto fail; /* no range available from stats */
3147  if (!get_variable_range(root, &rightvar, rstatop,
3148  &rightmin, &rightmax))
3149  goto fail; /* no range available from stats */
3150  }
3151  else
3152  {
3153  /* need to swap the max and min */
3154  if (!get_variable_range(root, &leftvar, lstatop,
3155  &leftmax, &leftmin))
3156  goto fail; /* no range available from stats */
3157  if (!get_variable_range(root, &rightvar, rstatop,
3158  &rightmax, &rightmin))
3159  goto fail; /* no range available from stats */
3160  }
3161 
3162  /*
3163  * Now, the fraction of the left variable that will be scanned is the
3164  * fraction that's <= the right-side maximum value. But only believe
3165  * non-default estimates, else stick with our 1.0.
3166  */
3167  selec = scalarineqsel(root, leop, isgt, true, &leftvar,
3168  rightmax, op_righttype);
3169  if (selec != DEFAULT_INEQ_SEL)
3170  *leftend = selec;
3171 
3172  /* And similarly for the right variable. */
3173  selec = scalarineqsel(root, revleop, isgt, true, &rightvar,
3174  leftmax, op_lefttype);
3175  if (selec != DEFAULT_INEQ_SEL)
3176  *rightend = selec;
3177 
3178  /*
3179  * Only one of the two "end" fractions can really be less than 1.0;
3180  * believe the smaller estimate and reset the other one to exactly 1.0. If
3181  * we get exactly equal estimates (as can easily happen with self-joins),
3182  * believe neither.
3183  */
3184  if (*leftend > *rightend)
3185  *leftend = 1.0;
3186  else if (*leftend < *rightend)
3187  *rightend = 1.0;
3188  else
3189  *leftend = *rightend = 1.0;
3190 
3191  /*
3192  * Also, the fraction of the left variable that will be scanned before the
3193  * first join pair is found is the fraction that's < the right-side
3194  * minimum value. But only believe non-default estimates, else stick with
3195  * our own default.
3196  */
3197  selec = scalarineqsel(root, ltop, isgt, false, &leftvar,
3198  rightmin, op_righttype);
3199  if (selec != DEFAULT_INEQ_SEL)
3200  *leftstart = selec;
3201 
3202  /* And similarly for the right variable. */
3203  selec = scalarineqsel(root, revltop, isgt, false, &rightvar,
3204  leftmin, op_lefttype);
3205  if (selec != DEFAULT_INEQ_SEL)
3206  *rightstart = selec;
3207 
3208  /*
3209  * Only one of the two "start" fractions can really be more than zero;
3210  * believe the larger estimate and reset the other one to exactly 0.0. If
3211  * we get exactly equal estimates (as can easily happen with self-joins),
3212  * believe neither.
3213  */
3214  if (*leftstart < *rightstart)
3215  *leftstart = 0.0;
3216  else if (*leftstart > *rightstart)
3217  *rightstart = 0.0;
3218  else
3219  *leftstart = *rightstart = 0.0;
3220 
3221  /*
3222  * If the sort order is nulls-first, we're going to have to skip over any
3223  * nulls too. These would not have been counted by scalarineqsel, and we
3224  * can safely add in this fraction regardless of whether we believe
3225  * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3226  */
3227  if (nulls_first)
3228  {
3229  Form_pg_statistic stats;
3230 
3231  if (HeapTupleIsValid(leftvar.statsTuple))
3232  {
3233  stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3234  *leftstart += stats->stanullfrac;
3235  CLAMP_PROBABILITY(*leftstart);
3236  *leftend += stats->stanullfrac;
3237  CLAMP_PROBABILITY(*leftend);
3238  }
3239  if (HeapTupleIsValid(rightvar.statsTuple))
3240  {
3241  stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3242  *rightstart += stats->stanullfrac;
3243  CLAMP_PROBABILITY(*rightstart);
3244  *rightend += stats->stanullfrac;
3245  CLAMP_PROBABILITY(*rightend);
3246  }
3247  }
3248 
3249  /* Disbelieve start >= end, just in case that can happen */
3250  if (*leftstart >= *leftend)
3251  {
3252  *leftstart = 0.0;
3253  *leftend = 1.0;
3254  }
3255  if (*rightstart >= *rightend)
3256  {
3257  *rightstart = 0.0;
3258  *rightend = 1.0;
3259  }
3260 
3261 fail:
3262  ReleaseVariableStats(leftvar);
3263  ReleaseVariableStats(rightvar);
3264 }
3265 
3266 
3267 /*
3268  * Helper routine for estimate_num_groups: add an item to a list of
3269  * GroupVarInfos, but only if it's not known equal to any of the existing
3270  * entries.
3271  */
3272 typedef struct
3273 {
3274  Node *var; /* might be an expression, not just a Var */
3275  RelOptInfo *rel; /* relation it belongs to */
3276  double ndistinct; /* # distinct values */
3277 } GroupVarInfo;
3278 
3279 static List *
3281  Node *var, VariableStatData *vardata)
3282 {
3283  GroupVarInfo *varinfo;
3284  double ndistinct;
3285  bool isdefault;
3286  ListCell *lc;
3287 
3288  ndistinct = get_variable_numdistinct(vardata, &isdefault);
3289 
3290  /* cannot use foreach here because of possible list_delete */
3291  lc = list_head(varinfos);
3292  while (lc)
3293  {
3294  varinfo = (GroupVarInfo *) lfirst(lc);
3295 
3296  /* must advance lc before list_delete possibly pfree's it */
3297  lc = lnext(lc);
3298 
3299  /* Drop exact duplicates */
3300  if (equal(var, varinfo->var))
3301  return varinfos;
3302 
3303  /*
3304  * Drop known-equal vars, but only if they belong to different
3305  * relations (see comments for estimate_num_groups)
3306  */
3307  if (vardata->rel != varinfo->rel &&
3308  exprs_known_equal(root, var, varinfo->var))
3309  {
3310  if (varinfo->ndistinct <= ndistinct)
3311  {
3312  /* Keep older item, forget new one */
3313  return varinfos;
3314  }
3315  else
3316  {
3317  /* Delete the older item */
3318  varinfos = list_delete_ptr(varinfos, varinfo);
3319  }
3320  }
3321  }
3322 
3323  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3324 
3325  varinfo->var = var;
3326  varinfo->rel = vardata->rel;
3327  varinfo->ndistinct = ndistinct;
3328  varinfos = lappend(varinfos, varinfo);
3329  return varinfos;
3330 }
3331 
3332 /*
3333  * estimate_num_groups - Estimate number of groups in a grouped query
3334  *
3335  * Given a query having a GROUP BY clause, estimate how many groups there
3336  * will be --- ie, the number of distinct combinations of the GROUP BY
3337  * expressions.
3338  *
3339  * This routine is also used to estimate the number of rows emitted by
3340  * a DISTINCT filtering step; that is an isomorphic problem. (Note:
3341  * actually, we only use it for DISTINCT when there's no grouping or
3342  * aggregation ahead of the DISTINCT.)
3343  *
3344  * Inputs:
3345  * root - the query
3346  * groupExprs - list of expressions being grouped by
3347  * input_rows - number of rows estimated to arrive at the group/unique
3348  * filter step
3349  * pgset - NULL, or a List** pointing to a grouping set to filter the
3350  * groupExprs against
3351  *
3352  * Given the lack of any cross-correlation statistics in the system, it's
3353  * impossible to do anything really trustworthy with GROUP BY conditions
3354  * involving multiple Vars. We should however avoid assuming the worst
3355  * case (all possible cross-product terms actually appear as groups) since
3356  * very often the grouped-by Vars are highly correlated. Our current approach
3357  * is as follows:
3358  * 1. Expressions yielding boolean are assumed to contribute two groups,
3359  * independently of their content, and are ignored in the subsequent
3360  * steps. This is mainly because tests like "col IS NULL" break the
3361  * heuristic used in step 2 especially badly.
3362  * 2. Reduce the given expressions to a list of unique Vars used. For
3363  * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3364  * It is clearly correct not to count the same Var more than once.
3365  * It is also reasonable to treat f(x) the same as x: f() cannot
3366  * increase the number of distinct values (unless it is volatile,
3367  * which we consider unlikely for grouping), but it probably won't
3368  * reduce the number of distinct values much either.
3369  * As a special case, if a GROUP BY expression can be matched to an
3370  * expressional index for which we have statistics, then we treat the
3371  * whole expression as though it were just a Var.
3372  * 3. If the list contains Vars of different relations that are known equal
3373  * due to equivalence classes, then drop all but one of the Vars from each
3374  * known-equal set, keeping the one with smallest estimated # of values
3375  * (since the extra values of the others can't appear in joined rows).
3376  * Note the reason we only consider Vars of different relations is that
3377  * if we considered ones of the same rel, we'd be double-counting the
3378  * restriction selectivity of the equality in the next step.
3379  * 4. For Vars within a single source rel, we multiply together the numbers
3380  * of values, clamp to the number of rows in the rel (divided by 10 if
3381  * more than one Var), and then multiply by a factor based on the
3382  * selectivity of the restriction clauses for that rel. When there's
3383  * more than one Var, the initial product is probably too high (it's the
3384  * worst case) but clamping to a fraction of the rel's rows seems to be a
3385  * helpful heuristic for not letting the estimate get out of hand. (The
3386  * factor of 10 is derived from pre-Postgres-7.4 practice.) The factor
3387  * we multiply by to adjust for the restriction selectivity assumes that
3388  * the restriction clauses are independent of the grouping, which may not
3389  * be a valid assumption, but it's hard to do better.
3390  * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3391  * rel, and multiply the results together.
3392  * Note that rels not containing grouped Vars are ignored completely, as are
3393  * join clauses. Such rels cannot increase the number of groups, and we
3394  * assume such clauses do not reduce the number either (somewhat bogus,
3395  * but we don't have the info to do better).
3396  */
3397 double
3398 estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3399  List **pgset)
3400 {
3401  List *varinfos = NIL;
3402  double srf_multiplier = 1.0;
3403  double numdistinct;
3404  ListCell *l;
3405  int i;
3406 
3407  /*
3408  * We don't ever want to return an estimate of zero groups, as that tends
3409  * to lead to division-by-zero and other unpleasantness. The input_rows
3410  * estimate is usually already at least 1, but clamp it just in case it
3411  * isn't.
3412  */
3413  input_rows = clamp_row_est(input_rows);
3414 
3415  /*
3416  * If no grouping columns, there's exactly one group. (This can't happen
3417  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3418  * corner cases with set operations.)
3419  */
3420  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3421  return 1.0;
3422 
3423  /*
3424  * Count groups derived from boolean grouping expressions. For other
3425  * expressions, find the unique Vars used, treating an expression as a Var
3426  * if we can find stats for it. For each one, record the statistical
3427  * estimate of number of distinct values (total in its table, without
3428  * regard for filtering).
3429  */
3430  numdistinct = 1.0;
3431 
3432  i = 0;
3433  foreach(l, groupExprs)
3434  {
3435  Node *groupexpr = (Node *) lfirst(l);
3436  double this_srf_multiplier;
3437  VariableStatData vardata;
3438  List *varshere;
3439  ListCell *l2;
3440 
3441  /* is expression in this grouping set? */
3442  if (pgset && !list_member_int(*pgset, i++))
3443  continue;
3444 
3445  /*
3446  * Set-returning functions in grouping columns are a bit problematic.
3447  * The code below will effectively ignore their SRF nature and come up
3448  * with a numdistinct estimate as though they were scalar functions.
3449  * We compensate by scaling up the end result by the largest SRF
3450  * rowcount estimate. (This will be an overestimate if the SRF
3451  * produces multiple copies of any output value, but it seems best to
3452  * assume the SRF's outputs are distinct. In any case, it's probably
3453  * pointless to worry too much about this without much better
3454  * estimates for SRF output rowcounts than we have today.)
3455  */
3456  this_srf_multiplier = expression_returns_set_rows(groupexpr);
3457  if (srf_multiplier < this_srf_multiplier)
3458  srf_multiplier = this_srf_multiplier;
3459 
3460  /* Short-circuit for expressions returning boolean */
3461  if (exprType(groupexpr) == BOOLOID)
3462  {
3463  numdistinct *= 2.0;
3464  continue;
3465  }
3466 
3467  /*
3468  * If examine_variable is able to deduce anything about the GROUP BY
3469  * expression, treat it as a single variable even if it's really more
3470  * complicated.
3471  */
3472  examine_variable(root, groupexpr, 0, &vardata);
3473  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3474  {
3475  varinfos = add_unique_group_var(root, varinfos,
3476  groupexpr, &vardata);
3477  ReleaseVariableStats(vardata);
3478  continue;
3479  }
3480  ReleaseVariableStats(vardata);
3481 
3482  /*
3483  * Else pull out the component Vars. Handle PlaceHolderVars by
3484  * recursing into their arguments (effectively assuming that the
3485  * PlaceHolderVar doesn't change the number of groups, which boils
3486  * down to ignoring the possible addition of nulls to the result set).
3487  */
3488  varshere = pull_var_clause(groupexpr,
3492 
3493  /*
3494  * If we find any variable-free GROUP BY item, then either it is a
3495  * constant (and we can ignore it) or it contains a volatile function;
3496  * in the latter case we punt and assume that each input row will
3497  * yield a distinct group.
3498  */
3499  if (varshere == NIL)
3500  {
3501  if (contain_volatile_functions(groupexpr))
3502  return input_rows;
3503  continue;
3504  }
3505 
3506  /*
3507  * Else add variables to varinfos list
3508  */
3509  foreach(l2, varshere)
3510  {
3511  Node *var = (Node *) lfirst(l2);
3512 
3513  examine_variable(root, var, 0, &vardata);
3514  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3515  ReleaseVariableStats(vardata);
3516  }
3517  }
3518 
3519  /*
3520  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3521  * list.
3522  */
3523  if (varinfos == NIL)
3524  {
3525  /* Apply SRF multiplier as we would do in the long path */
3526  numdistinct *= srf_multiplier;
3527  /* Round off */
3528  numdistinct = ceil(numdistinct);
3529  /* Guard against out-of-range answers */
3530  if (numdistinct > input_rows)
3531  numdistinct = input_rows;
3532  if (numdistinct < 1.0)
3533  numdistinct = 1.0;
3534  return numdistinct;
3535  }
3536 
3537  /*
3538  * Group Vars by relation and estimate total numdistinct.
3539  *
3540  * For each iteration of the outer loop, we process the frontmost Var in
3541  * varinfos, plus all other Vars in the same relation. We remove these
3542  * Vars from the newvarinfos list for the next iteration. This is the
3543  * easiest way to group Vars of same rel together.
3544  */
3545  do
3546  {
3547  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3548  RelOptInfo *rel = varinfo1->rel;
3549  double reldistinct = 1;
3550  double relmaxndistinct = reldistinct;
3551  int relvarcount = 0;
3552  List *newvarinfos = NIL;
3553  List *relvarinfos = NIL;
3554 
3555  /*
3556  * Split the list of varinfos in two - one for the current rel, one
3557  * for remaining Vars on other rels.
3558  */
3559  relvarinfos = lcons(varinfo1, relvarinfos);
3560  for_each_cell(l, lnext(list_head(varinfos)))
3561  {
3562  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3563 
3564  if (varinfo2->rel == varinfo1->rel)
3565  {
3566  /* varinfos on current rel */
3567  relvarinfos = lcons(varinfo2, relvarinfos);
3568  }
3569  else
3570  {
3571  /* not time to process varinfo2 yet */
3572  newvarinfos = lcons(varinfo2, newvarinfos);
3573  }
3574  }
3575 
3576  /*
3577  * Get the numdistinct estimate for the Vars of this rel. We
3578  * iteratively search for multivariate n-distinct with maximum number
3579  * of vars; assuming that each var group is independent of the others,
3580  * we multiply them together. Any remaining relvarinfos after no more
3581  * multivariate matches are found are assumed independent too, so
3582  * their individual ndistinct estimates are multiplied also.
3583  *
3584  * While iterating, count how many separate numdistinct values we
3585  * apply. We apply a fudge factor below, but only if we multiplied
3586  * more than one such values.
3587  */
3588  while (relvarinfos)
3589  {
3590  double mvndistinct;
3591 
3592  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3593  &mvndistinct))
3594  {
3595  reldistinct *= mvndistinct;
3596  if (relmaxndistinct < mvndistinct)
3597  relmaxndistinct = mvndistinct;
3598  relvarcount++;
3599  }
3600  else
3601  {
3602  foreach(l, relvarinfos)
3603  {
3604  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3605 
3606  reldistinct *= varinfo2->ndistinct;
3607  if (relmaxndistinct < varinfo2->ndistinct)
3608  relmaxndistinct = varinfo2->ndistinct;
3609  relvarcount++;
3610  }
3611 
3612  /* we're done with this relation */
3613  relvarinfos = NIL;
3614  }
3615  }
3616 
3617  /*
3618  * Sanity check --- don't divide by zero if empty relation.
3619  */
3620  Assert(IS_SIMPLE_REL(rel));
3621  if (rel->tuples > 0)
3622  {
3623  /*
3624  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3625  * fudge factor is because the Vars are probably correlated but we
3626  * don't know by how much. We should never clamp to less than the
3627  * largest ndistinct value for any of the Vars, though, since
3628  * there will surely be at least that many groups.
3629  */
3630  double clamp = rel->tuples;
3631 
3632  if (relvarcount > 1)
3633  {
3634  clamp *= 0.1;
3635  if (clamp < relmaxndistinct)
3636  {
3637  clamp = relmaxndistinct;
3638  /* for sanity in case some ndistinct is too large: */
3639  if (clamp > rel->tuples)
3640  clamp = rel->tuples;
3641  }
3642  }
3643  if (reldistinct > clamp)
3644  reldistinct = clamp;
3645 
3646  /*
3647  * Update the estimate based on the restriction selectivity,
3648  * guarding against division by zero when reldistinct is zero.
3649  * Also skip this if we know that we are returning all rows.
3650  */
3651  if (reldistinct > 0 && rel->rows < rel->tuples)
3652  {
3653  /*
3654  * Given a table containing N rows with n distinct values in a
3655  * uniform distribution, if we select p rows at random then
3656  * the expected number of distinct values selected is
3657  *
3658  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3659  *
3660  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3661  *
3662  * See "Approximating block accesses in database
3663  * organizations", S. B. Yao, Communications of the ACM,
3664  * Volume 20 Issue 4, April 1977 Pages 260-261.
3665  *
3666  * Alternatively, re-arranging the terms from the factorials,
3667  * this may be written as
3668  *
3669  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3670  *
3671  * This form of the formula is more efficient to compute in
3672  * the common case where p is larger than N/n. Additionally,
3673  * as pointed out by Dell'Era, if i << N for all terms in the
3674  * product, it can be approximated by
3675  *
3676  * n * (1 - ((N-p)/N)^(N/n))
3677  *
3678  * See "Expected distinct values when selecting from a bag
3679  * without replacement", Alberto Dell'Era,
3680  * http://www.adellera.it/investigations/distinct_balls/.
3681  *
3682  * The condition i << N is equivalent to n >> 1, so this is a
3683  * good approximation when the number of distinct values in
3684  * the table is large. It turns out that this formula also
3685  * works well even when n is small.
3686  */
3687  reldistinct *=
3688  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3689  rel->tuples / reldistinct));
3690  }
3691  reldistinct = clamp_row_est(reldistinct);
3692 
3693  /*
3694  * Update estimate of total distinct groups.
3695  */
3696  numdistinct *= reldistinct;
3697  }
3698 
3699  varinfos = newvarinfos;
3700  } while (varinfos != NIL);
3701 
3702  /* Now we can account for the effects of any SRFs */
3703  numdistinct *= srf_multiplier;
3704 
3705  /* Round off */
3706  numdistinct = ceil(numdistinct);
3707 
3708  /* Guard against out-of-range answers */
3709  if (numdistinct > input_rows)
3710  numdistinct = input_rows;
3711  if (numdistinct < 1.0)
3712  numdistinct = 1.0;
3713 
3714  return numdistinct;
3715 }
3716 
3717 /*
3718  * Estimate hash bucket statistics when the specified expression is used
3719  * as a hash key for the given number of buckets.
3720  *
3721  * This attempts to determine two values:
3722  *
3723  * 1. The frequency of the most common value of the expression (returns
3724  * zero into *mcv_freq if we can't get that).
3725  *
3726  * 2. The "bucketsize fraction", ie, average number of entries in a bucket
3727  * divided by total tuples in relation.
3728  *
3729  * XXX This is really pretty bogus since we're effectively assuming that the
3730  * distribution of hash keys will be the same after applying restriction
3731  * clauses as it was in the underlying relation. However, we are not nearly
3732  * smart enough to figure out how the restrict clauses might change the
3733  * distribution, so this will have to do for now.
3734  *
3735  * We are passed the number of buckets the executor will use for the given
3736  * input relation. If the data were perfectly distributed, with the same
3737  * number of tuples going into each available bucket, then the bucketsize
3738  * fraction would be 1/nbuckets. But this happy state of affairs will occur
3739  * only if (a) there are at least nbuckets distinct data values, and (b)
3740  * we have a not-too-skewed data distribution. Otherwise the buckets will
3741  * be nonuniformly occupied. If the other relation in the join has a key
3742  * distribution similar to this one's, then the most-loaded buckets are
3743  * exactly those that will be probed most often. Therefore, the "average"
3744  * bucket size for costing purposes should really be taken as something close
3745  * to the "worst case" bucket size. We try to estimate this by adjusting the
3746  * fraction if there are too few distinct data values, and then scaling up
3747  * by the ratio of the most common value's frequency to the average frequency.
3748  *
3749  * If no statistics are available, use a default estimate of 0.1. This will
3750  * discourage use of a hash rather strongly if the inner relation is large,
3751  * which is what we want. We do not want to hash unless we know that the
3752  * inner rel is well-dispersed (or the alternatives seem much worse).
3753  *
3754  * The caller should also check that the mcv_freq is not so large that the
3755  * most common value would by itself require an impractically large bucket.
3756  * In a hash join, the executor can split buckets if they get too big, but
3757  * obviously that doesn't help for a bucket that contains many duplicates of
3758  * the same value.
3759  */
3760 void
3761 estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets,
3762  Selectivity *mcv_freq,
3763  Selectivity *bucketsize_frac)
3764 {
3765  VariableStatData vardata;
3766  double estfract,
3767  ndistinct,
3768  stanullfrac,
3769  avgfreq;
3770  bool isdefault;
3771  AttStatsSlot sslot;
3772 
3773  examine_variable(root, hashkey, 0, &vardata);
3774 
3775  /* Look up the frequency of the most common value, if available */
3776  *mcv_freq = 0.0;
3777 
3778  if (HeapTupleIsValid(vardata.statsTuple))
3779  {
3780  if (get_attstatsslot(&sslot, vardata.statsTuple,
3783  {
3784  /*
3785  * The first MCV stat is for the most common value.
3786  */
3787  if (sslot.nnumbers > 0)
3788  *mcv_freq = sslot.numbers[0];
3789  free_attstatsslot(&sslot);
3790  }
3791  }
3792 
3793  /* Get number of distinct values */
3794  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3795 
3796  /*
3797  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3798  * mcv_freq is known to be even higher than that, use it instead.
3799  */
3800  if (isdefault)
3801  {
3802  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3803  ReleaseVariableStats(vardata);
3804  return;
3805  }
3806 
3807  /* Get fraction that are null */
3808  if (HeapTupleIsValid(vardata.statsTuple))
3809  {
3810  Form_pg_statistic stats;
3811 
3812  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3813  stanullfrac = stats->stanullfrac;
3814  }
3815  else
3816  stanullfrac = 0.0;
3817 
3818  /* Compute avg freq of all distinct data values in raw relation */
3819  avgfreq = (1.0 - stanullfrac) / ndistinct;
3820 
3821  /*
3822  * Adjust ndistinct to account for restriction clauses. Observe we are
3823  * assuming that the data distribution is affected uniformly by the
3824  * restriction clauses!
3825  *
3826  * XXX Possibly better way, but much more expensive: multiply by
3827  * selectivity of rel's restriction clauses that mention the target Var.
3828  */
3829  if (vardata.rel && vardata.rel->tuples > 0)
3830  {
3831  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3832  ndistinct = clamp_row_est(ndistinct);
3833  }
3834 
3835  /*
3836  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3837  * number of buckets is less than the expected number of distinct values;
3838  * otherwise it is 1/ndistinct.
3839  */
3840  if (ndistinct > nbuckets)
3841  estfract = 1.0 / nbuckets;
3842  else
3843  estfract = 1.0 / ndistinct;
3844 
3845  /*
3846  * Adjust estimated bucketsize upward to account for skewed distribution.
3847  */
3848  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3849  estfract *= *mcv_freq / avgfreq;
3850 
3851  /*
3852  * Clamp bucketsize to sane range (the above adjustment could easily
3853  * produce an out-of-range result). We set the lower bound a little above
3854  * zero, since zero isn't a very sane result.
3855  */
3856  if (estfract < 1.0e-6)
3857  estfract = 1.0e-6;
3858  else if (estfract > 1.0)
3859  estfract = 1.0;
3860 
3861  *bucketsize_frac = (Selectivity) estfract;
3862 
3863  ReleaseVariableStats(vardata);
3864 }
3865 
3866 
3867 /*-------------------------------------------------------------------------
3868  *
3869  * Support routines
3870  *
3871  *-------------------------------------------------------------------------
3872  */
3873 
3874 /*
3875  * Find applicable ndistinct statistics for the given list of VarInfos (which
3876  * must all belong to the given rel), and update *ndistinct to the estimate of
3877  * the MVNDistinctItem that best matches. If a match it found, *varinfos is
3878  * updated to remove the list of matched varinfos.
3879  *
3880  * Varinfos that aren't for simple Vars are ignored.
3881  *
3882  * Return true if we're able to find a match, false otherwise.
3883  */
3884 static bool
3886  List **varinfos, double *ndistinct)
3887 {
3888  ListCell *lc;
3889  Bitmapset *attnums = NULL;
3890  int nmatches;
3891  Oid statOid = InvalidOid;
3892  MVNDistinct *stats;
3893  Bitmapset *matched = NULL;
3894 
3895  /* bail out immediately if the table has no extended statistics */
3896  if (!rel->statlist)
3897  return false;
3898 
3899  /* Determine the attnums we're looking for */
3900  foreach(lc, *varinfos)
3901  {
3902  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3903 
3904  Assert(varinfo->rel == rel);
3905 
3906  if (IsA(varinfo->var, Var))
3907  {
3908  attnums = bms_add_member(attnums,
3909  ((Var *) varinfo->var)->varattno);
3910  }
3911  }
3912 
3913  /* look for the ndistinct statistics matching the most vars */
3914  nmatches = 1; /* we require at least two matches */
3915  foreach(lc, rel->statlist)
3916  {
3917  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3918  Bitmapset *shared;
3919  int nshared;
3920 
3921  /* skip statistics of other kinds */
3922  if (info->kind != STATS_EXT_NDISTINCT)
3923  continue;
3924 
3925  /* compute attnums shared by the vars and the statistics object */
3926  shared = bms_intersect(info->keys, attnums);
3927  nshared = bms_num_members(shared);
3928 
3929  /*
3930  * Does this statistics object match more columns than the currently
3931  * best object? If so, use this one instead.
3932  *
3933  * XXX This should break ties using name of the object, or something
3934  * like that, to make the outcome stable.
3935  */
3936  if (nshared > nmatches)
3937  {
3938  statOid = info->statOid;
3939  nmatches = nshared;
3940  matched = shared;
3941  }
3942  }
3943 
3944  /* No match? */
3945  if (statOid == InvalidOid)
3946  return false;
3947  Assert(nmatches > 1 && matched != NULL);
3948 
3949  stats = statext_ndistinct_load(statOid);
3950 
3951  /*
3952  * If we have a match, search it for the specific item that matches (there
3953  * must be one), and construct the output values.
3954  */
3955  if (stats)
3956  {
3957  int i;
3958  List *newlist = NIL;
3959  MVNDistinctItem *item = NULL;
3960 
3961  /* Find the specific item that exactly matches the combination */
3962  for (i = 0; i < stats->nitems; i++)
3963  {
3964  MVNDistinctItem *tmpitem = &stats->items[i];
3965 
3966  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3967  {
3968  item = tmpitem;
3969  break;
3970  }
3971  }
3972 
3973  /* make sure we found an item */
3974  if (!item)
3975  elog(ERROR, "corrupt MVNDistinct entry");
3976 
3977  /* Form the output varinfo list, keeping only unmatched ones */
3978  foreach(lc, *varinfos)
3979  {
3980  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3981  AttrNumber attnum;
3982 
3983  if (!IsA(varinfo->var, Var))
3984  {
3985  newlist = lappend(newlist, varinfo);
3986  continue;
3987  }
3988 
3989  attnum = ((Var *) varinfo->var)->varattno;
3990  if (!bms_is_member(attnum, matched))
3991  newlist = lappend(newlist, varinfo);
3992  }
3993 
3994  *varinfos = newlist;
3995  *ndistinct = item->ndistinct;
3996  return true;
3997  }
3998 
3999  return false;
4000 }
4001 
4002 /*
4003  * convert_to_scalar
4004  * Convert non-NULL values of the indicated types to the comparison
4005  * scale needed by scalarineqsel().
4006  * Returns "true" if successful.
4007  *
4008  * XXX this routine is a hack: ideally we should look up the conversion
4009  * subroutines in pg_type.
4010  *
4011  * All numeric datatypes are simply converted to their equivalent
4012  * "double" values. (NUMERIC values that are outside the range of "double"
4013  * are clamped to +/- HUGE_VAL.)
4014  *
4015  * String datatypes are converted by convert_string_to_scalar(),
4016  * which is explained below. The reason why this routine deals with
4017  * three values at a time, not just one, is that we need it for strings.
4018  *
4019  * The bytea datatype is just enough different from strings that it has
4020  * to be treated separately.
4021  *
4022  * The several datatypes representing absolute times are all converted
4023  * to Timestamp, which is actually a double, and then we just use that
4024  * double value. Note this will give correct results even for the "special"
4025  * values of Timestamp, since those are chosen to compare correctly;
4026  * see timestamp_cmp.
4027  *
4028  * The several datatypes representing relative times (intervals) are all
4029  * converted to measurements expressed in seconds.
4030  */
4031 static bool
4032 convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
4033  Datum lobound, Datum hibound, Oid boundstypid,
4034  double *scaledlobound, double *scaledhibound)
4035 {
4036  /*
4037  * Both the valuetypid and the boundstypid should exactly match the
4038  * declared input type(s) of the operator we are invoked for, so we just
4039  * error out if either is not recognized.
4040  *
4041  * XXX The histogram we are interpolating between points of could belong
4042  * to a column that's only binary-compatible with the declared type. In
4043  * essence we are assuming that the semantics of binary-compatible types
4044  * are enough alike that we can use a histogram generated with one type's
4045  * operators to estimate selectivity for the other's. This is outright
4046  * wrong in some cases --- in particular signed versus unsigned
4047  * interpretation could trip us up. But it's useful enough in the
4048  * majority of cases that we do it anyway. Should think about more
4049  * rigorous ways to do it.
4050  */
4051  switch (valuetypid)
4052  {
4053  /*
4054  * Built-in numeric types
4055  */
4056  case BOOLOID:
4057  case INT2OID:
4058  case INT4OID:
4059  case INT8OID:
4060  case FLOAT4OID:
4061  case FLOAT8OID:
4062  case NUMERICOID:
4063  case OIDOID:
4064  case REGPROCOID:
4065  case REGPROCEDUREOID:
4066  case REGOPEROID:
4067  case REGOPERATOROID:
4068  case REGCLASSOID:
4069  case REGTYPEOID:
4070  case REGCONFIGOID:
4071  case REGDICTIONARYOID:
4072  case REGROLEOID:
4073  case REGNAMESPACEOID:
4074  *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
4075  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
4076  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
4077  return true;
4078 
4079  /*
4080  * Built-in string types
4081  */
4082  case CHAROID:
4083  case BPCHAROID:
4084  case VARCHAROID:
4085  case TEXTOID:
4086  case NAMEOID:
4087  {
4088  char *valstr = convert_string_datum(value, valuetypid);
4089  char *lostr = convert_string_datum(lobound, boundstypid);
4090  char *histr = convert_string_datum(hibound, boundstypid);
4091 
4092  convert_string_to_scalar(valstr, scaledvalue,
4093  lostr, scaledlobound,
4094  histr, scaledhibound);
4095  pfree(valstr);
4096  pfree(lostr);
4097  pfree(histr);
4098  return true;
4099  }
4100 
4101  /*
4102  * Built-in bytea type
4103  */
4104  case BYTEAOID:
4105  {
4106  convert_bytea_to_scalar(value, scaledvalue,
4107  lobound, scaledlobound,
4108  hibound, scaledhibound);
4109  return true;
4110  }
4111 
4112  /*
4113  * Built-in time types
4114  */
4115  case TIMESTAMPOID:
4116  case TIMESTAMPTZOID:
4117  case ABSTIMEOID:
4118  case DATEOID:
4119  case INTERVALOID:
4120  case RELTIMEOID:
4121  case TINTERVALOID:
4122  case TIMEOID:
4123  case TIMETZOID:
4124  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
4125  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
4126  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
4127  return true;
4128 
4129  /*
4130  * Built-in network types
4131  */
4132  case INETOID:
4133  case CIDROID:
4134  case MACADDROID:
4135  case MACADDR8OID:
4136  *scaledvalue = convert_network_to_scalar(value, valuetypid);
4137  *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
4138  *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
4139  return true;
4140  }
4141  /* Don't know how to convert */
4142  *scaledvalue = *scaledlobound = *scaledhibound = 0;
4143  return false;
4144 }
4145 
4146 /*
4147  * Do convert_to_scalar()'s work for any numeric data type.
4148  */
4149 static double
4151 {
4152  switch (typid)
4153  {
4154  case BOOLOID:
4155  return (double) DatumGetBool(value);
4156  case INT2OID:
4157  return (double) DatumGetInt16(value);
4158  case INT4OID:
4159  return (double) DatumGetInt32(value);
4160  case INT8OID:
4161  return (double) DatumGetInt64(value);
4162  case FLOAT4OID:
4163  return (double) DatumGetFloat4(value);
4164  case FLOAT8OID:
4165  return (double) DatumGetFloat8(value);
4166  case NUMERICOID:
4167  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4168  return (double)
4170  value));
4171  case OIDOID:
4172  case REGPROCOID:
4173  case REGPROCEDUREOID:
4174  case REGOPEROID:
4175  case REGOPERATOROID:
4176  case REGCLASSOID:
4177  case REGTYPEOID:
4178  case REGCONFIGOID:
4179  case REGDICTIONARYOID:
4180  case REGROLEOID:
4181  case REGNAMESPACEOID:
4182  /* we can treat OIDs as integers... */
4183  return (double) DatumGetObjectId(value);
4184  }
4185 
4186  /*
4187  * Can't get here unless someone tries to use scalarineqsel() on an
4188  * operator with one numeric and one non-numeric operand.
4189  */
4190  elog(ERROR, "unsupported type: %u", typid);
4191  return 0;
4192 }
4193 
4194 /*
4195  * Do convert_to_scalar()'s work for any character-string data type.
4196  *
4197  * String datatypes are converted to a scale that ranges from 0 to 1,
4198  * where we visualize the bytes of the string as fractional digits.
4199  *
4200  * We do not want the base to be 256, however, since that tends to
4201  * generate inflated selectivity estimates; few databases will have
4202  * occurrences of all 256 possible byte values at each position.
4203  * Instead, use the smallest and largest byte values seen in the bounds
4204  * as the estimated range for each byte, after some fudging to deal with
4205  * the fact that we probably aren't going to see the full range that way.
4206  *
4207  * An additional refinement is that we discard any common prefix of the
4208  * three strings before computing the scaled values. This allows us to
4209  * "zoom in" when we encounter a narrow data range. An example is a phone
4210  * number database where all the values begin with the same area code.
4211  * (Actually, the bounds will be adjacent histogram-bin-boundary values,
4212  * so this is more likely to happen than you might think.)
4213  */
4214 static void
4216  double *scaledvalue,
4217  char *lobound,
4218  double *scaledlobound,
4219  char *hibound,
4220  double *scaledhibound)
4221 {
4222  int rangelo,
4223  rangehi;
4224  char *sptr;
4225 
4226  rangelo = rangehi = (unsigned char) hibound[0];
4227  for (sptr = lobound; *sptr; sptr++)
4228  {
4229  if (rangelo > (unsigned char) *sptr)
4230  rangelo = (unsigned char) *sptr;
4231  if (rangehi < (unsigned char) *sptr)
4232  rangehi = (unsigned char) *sptr;
4233  }
4234  for (sptr = hibound; *sptr; sptr++)
4235  {
4236  if (rangelo > (unsigned char) *sptr)
4237  rangelo = (unsigned char) *sptr;
4238  if (rangehi < (unsigned char) *sptr)
4239  rangehi = (unsigned char) *sptr;
4240  }
4241  /* If range includes any upper-case ASCII chars, make it include all */
4242  if (rangelo <= 'Z' && rangehi >= 'A')
4243  {
4244  if (rangelo > 'A')
4245  rangelo = 'A';
4246  if (rangehi < 'Z')
4247  rangehi = 'Z';
4248  }
4249  /* Ditto lower-case */
4250  if (rangelo <= 'z' && rangehi >= 'a')
4251  {
4252  if (rangelo > 'a')
4253  rangelo = 'a';
4254  if (rangehi < 'z')
4255  rangehi = 'z';
4256  }
4257  /* Ditto digits */
4258  if (rangelo <= '9' && rangehi >= '0')
4259  {
4260  if (rangelo > '0')
4261  rangelo = '0';
4262  if (rangehi < '9')
4263  rangehi = '9';
4264  }
4265 
4266  /*
4267  * If range includes less than 10 chars, assume we have not got enough
4268  * data, and make it include regular ASCII set.
4269  */
4270  if (rangehi - rangelo < 9)
4271  {
4272  rangelo = ' ';
4273  rangehi = 127;
4274  }
4275 
4276  /*
4277  * Now strip any common prefix of the three strings.
4278  */
4279  while (*lobound)
4280  {
4281  if (*lobound != *hibound || *lobound != *value)
4282  break;
4283  lobound++, hibound++, value++;
4284  }
4285 
4286  /*
4287  * Now we can do the conversions.
4288  */
4289  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4290  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4291  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4292 }
4293 
4294 static double
4295 convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
4296 {
4297  int slen = strlen(value);
4298  double num,
4299  denom,
4300  base;
4301 
4302  if (slen <= 0)
4303  return 0.0; /* empty string has scalar value 0 */
4304 
4305  /*
4306  * There seems little point in considering more than a dozen bytes from
4307  * the string. Since base is at least 10, that will give us nominal
4308  * resolution of at least 12 decimal digits, which is surely far more
4309  * precision than this estimation technique has got anyway (especially in
4310  * non-C locales). Also, even with the maximum possible base of 256, this
4311  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4312  * overflow on any known machine.
4313  */
4314  if (slen > 12)
4315  slen = 12;
4316 
4317  /* Convert initial characters to fraction */
4318  base = rangehi - rangelo + 1;
4319  num = 0.0;
4320  denom = base;
4321  while (slen-- > 0)
4322  {
4323  int ch = (unsigned char) *value++;
4324 
4325  if (ch < rangelo)
4326  ch = rangelo - 1;
4327  else if (ch > rangehi)
4328  ch = rangehi + 1;
4329  num += ((double) (ch - rangelo)) / denom;
4330  denom *= base;
4331  }
4332 
4333  return num;
4334 }
4335 
4336 /*
4337  * Convert a string-type Datum into a palloc'd, null-terminated string.
4338  *
4339  * When using a non-C locale, we must pass the string through strxfrm()
4340  * before continuing, so as to generate correct locale-specific results.
4341  */
4342 static char *
4344 {
4345  char *val;
4346 
4347  switch (typid)
4348  {
4349  case CHAROID:
4350  val = (char *) palloc(2);
4351  val[0] = DatumGetChar(value);
4352  val[1] = '\0';
4353  break;
4354  case BPCHAROID:
4355  case VARCHAROID:
4356  case TEXTOID:
4357  val = TextDatumGetCString(value);
4358  break;
4359  case NAMEOID:
4360  {
4361  NameData *nm = (NameData *) DatumGetPointer(value);
4362 
4363  val = pstrdup(NameStr(*nm));
4364  break;
4365  }
4366  default:
4367 
4368  /*
4369  * Can't get here unless someone tries to use scalarineqsel() on
4370  * an operator with one string and one non-string operand.
4371  */
4372  elog(ERROR, "unsupported type: %u", typid);
4373  return NULL;
4374  }
4375 
4377  {
4378  char *xfrmstr;
4379  size_t xfrmlen;
4380  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4381 
4382  /*
4383  * XXX: We could guess at a suitable output buffer size and only call
4384  * strxfrm twice if our guess is too small.
4385  *
4386  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4387  * bogus data or set an error. This is not really a problem unless it
4388  * crashes since it will only give an estimation error and nothing
4389  * fatal.
4390  */
4391 #if _MSC_VER == 1400 /* VS.Net 2005 */
4392 
4393  /*
4394  *
4395  * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99694
4396  */
4397  {
4398  char x[1];
4399 
4400  xfrmlen = strxfrm(x, val, 0);
4401  }
4402 #else
4403  xfrmlen = strxfrm(NULL, val, 0);
4404 #endif
4405 #ifdef WIN32
4406 
4407  /*
4408  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4409  * of trying to allocate this much memory (and fail), just return the
4410  * original string unmodified as if we were in the C locale.
4411  */
4412  if (xfrmlen == INT_MAX)
4413  return val;
4414 #endif
4415  xfrmstr = (char *) palloc(xfrmlen + 1);
4416  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4417 
4418  /*
4419  * Some systems (e.g., glibc) can return a smaller value from the
4420  * second call than the first; thus the Assert must be <= not ==.
4421  */
4422  Assert(xfrmlen2 <= xfrmlen);
4423  pfree(val);
4424  val = xfrmstr;
4425  }
4426 
4427  return val;
4428 }
4429 
4430 /*
4431  * Do convert_to_scalar()'s work for any bytea data type.
4432  *
4433  * Very similar to convert_string_to_scalar except we can't assume
4434  * null-termination and therefore pass explicit lengths around.
4435  *
4436  * Also, assumptions about likely "normal" ranges of characters have been
4437  * removed - a data range of 0..255 is always used, for now. (Perhaps
4438  * someday we will add information about actual byte data range to
4439  * pg_statistic.)
4440  */
4441 static void
4443  double *scaledvalue,
4444  Datum lobound,
4445  double *scaledlobound,
4446  Datum hibound,
4447  double *scaledhibound)
4448 {
4449  int rangelo,
4450  rangehi,
4451  valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
4452  loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
4453  hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
4454  i,
4455  minlen;
4456  unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
4457  *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
4458  *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
4459 
4460  /*
4461  * Assume bytea data is uniformly distributed across all byte values.
4462  */
4463  rangelo = 0;
4464  rangehi = 255;
4465 
4466  /*
4467  * Now strip any common prefix of the three strings.
4468  */
4469  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4470  for (i = 0; i < minlen; i++)
4471  {
4472  if (*lostr != *histr || *lostr != *valstr)
4473  break;
4474  lostr++, histr++, valstr++;
4475  loboundlen--, hiboundlen--, valuelen--;
4476  }
4477 
4478  /*
4479  * Now we can do the conversions.
4480  */
4481  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4482  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4483  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4484 }
4485 
4486 static double
4487 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
4488  int rangelo, int rangehi)
4489 {
4490  double num,
4491  denom,
4492  base;
4493 
4494  if (valuelen <= 0)
4495  return 0.0; /* empty string has scalar value 0 */
4496 
4497  /*
4498  * Since base is 256, need not consider more than about 10 chars (even
4499  * this many seems like overkill)
4500  */
4501  if (valuelen > 10)
4502  valuelen = 10;
4503 
4504  /* Convert initial characters to fraction */
4505  base = rangehi - rangelo + 1;
4506  num = 0.0;
4507  denom = base;
4508  while (valuelen-- > 0)
4509  {
4510  int ch = *value++;
4511 
4512  if (ch < rangelo)
4513  ch = rangelo - 1;
4514  else if (ch > rangehi)
4515  ch = rangehi + 1;
4516  num += ((double) (ch - rangelo)) / denom;
4517  denom *= base;
4518  }
4519 
4520  return num;
4521 }
4522 
4523 /*
4524  * Do convert_to_scalar()'s work for any timevalue data type.
4525  */
4526 static double
4528 {
4529  switch (typid)
4530  {
4531  case TIMESTAMPOID:
4532  return DatumGetTimestamp(value);
4533  case TIMESTAMPTZOID:
4534  return DatumGetTimestampTz(value);
4535  case ABSTIMEOID:
4537  value));
4538  case DATEOID:
4540  case INTERVALOID:
4541  {
4543 
4544  /*
4545  * Convert the month part of Interval to days using assumed
4546  * average month length of 365.25/12.0 days. Not too
4547  * accurate, but plenty good enough for our purposes.
4548  */
4549  return interval->time + interval->day * (double) USECS_PER_DAY +
4550  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4551  }
4552  case RELTIMEOID:
4553  return (DatumGetRelativeTime(value) * 1000000.0);
4554  case TINTERVALOID:
4555  {
4556  TimeInterval tinterval = DatumGetTimeInterval(value);
4557 
4558  if (tinterval->status != 0)
4559  return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4560  return 0; /* for lack of a better idea */
4561  }
4562  case TIMEOID:
4563  return DatumGetTimeADT(value);
4564  case TIMETZOID:
4565  {
4566  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4567 
4568  /* use GMT-equivalent time */
4569  return (double) (timetz->time + (timetz->zone * 1000000.0));
4570  }
4571  }
4572 
4573  /*
4574  * Can't get here unless someone tries to use scalarineqsel() on an
4575  * operator with one timevalue and one non-timevalue operand.
4576  */
4577  elog(ERROR, "unsupported type: %u", typid);
4578  return 0;
4579 }
4580 
4581 
4582 /*
4583  * get_restriction_variable
4584  * Examine the args of a restriction clause to see if it's of the
4585  * form (variable op pseudoconstant) or (pseudoconstant op variable),
4586  * where "variable" could be either a Var or an expression in vars of a
4587  * single relation. If so, extract information about the variable,
4588  * and also indicate which side it was on and the other argument.
4589  *
4590  * Inputs:
4591  * root: the planner info
4592  * args: clause argument list
4593  * varRelid: see specs for restriction selectivity functions
4594  *
4595  * Outputs: (these are valid only if true is returned)
4596  * *vardata: gets information about variable (see examine_variable)
4597  * *other: gets other clause argument, aggressively reduced to a constant
4598  * *varonleft: set true if variable is on the left, false if on the right
4599  *
4600  * Returns true if a variable is identified, otherwise false.
4601  *
4602  * Note: if there are Vars on both sides of the clause, we must fail, because
4603  * callers are expecting that the other side will act like a pseudoconstant.
4604  */
4605 bool
4607  VariableStatData *vardata, Node **other,
4608  bool *varonleft)
4609 {
4610  Node *left,
4611  *right;
4612  VariableStatData rdata;
4613 
4614  /* Fail if not a binary opclause (probably shouldn't happen) */
4615  if (list_length(args) != 2)
4616  return false;
4617 
4618  left = (Node *) linitial(args);
4619  right = (Node *) lsecond(args);
4620 
4621  /*
4622  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4623  * relations will be treated as pseudoconstants.
4624  */
4625  examine_variable(root, left, varRelid, vardata);
4626  examine_variable(root, right, varRelid, &rdata);
4627 
4628  /*
4629  * If one side is a variable and the other not, we win.
4630  */
4631  if (vardata->rel && rdata.rel == NULL)
4632  {
4633  *varonleft = true;
4634  *other = estimate_expression_value(root, rdata.var);
4635  /* Assume we need no ReleaseVariableStats(rdata) here */
4636  return true;
4637  }
4638 
4639  if (vardata->rel == NULL && rdata.rel)
4640  {
4641  *varonleft = false;
4642  *other = estimate_expression_value(root, vardata->var);
4643  /* Assume we need no ReleaseVariableStats(*vardata) here */
4644  *vardata = rdata;
4645  return true;
4646  }
4647 
4648  /* Oops, clause has wrong structure (probably var op var) */
4649  ReleaseVariableStats(*vardata);
4650  ReleaseVariableStats(rdata);
4651 
4652  return false;
4653 }
4654 
4655 /*
4656  * get_join_variables
4657  * Apply examine_variable() to each side of a join clause.
4658  * Also, attempt to identify whether the join clause has the same
4659  * or reversed sense compared to the SpecialJoinInfo.
4660  *
4661  * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4662  * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4663  * where we can't tell for sure, we default to assuming it's normal.
4664  */
4665 void
4667  VariableStatData *vardata1, VariableStatData *vardata2,
4668  bool *join_is_reversed)
4669 {
4670  Node *left,
4671  *right;
4672 
4673  if (list_length(args) != 2)
4674  elog(ERROR, "join operator should take two arguments");
4675 
4676  left = (Node *) linitial(args);
4677  right = (Node *) lsecond(args);
4678 
4679  examine_variable(root, left, 0, vardata1);
4680  examine_variable(root, right, 0, vardata2);
4681 
4682  if (vardata1->rel &&
4683  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4684  *join_is_reversed = true; /* var1 is on RHS */
4685  else if (vardata2->rel &&
4686  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4687  *join_is_reversed = true; /* var2 is on LHS */
4688  else
4689  *join_is_reversed = false;
4690 }
4691 
4692 /*
4693  * examine_variable
4694  * Try to look up statistical data about an expression.
4695  * Fill in a VariableStatData struct to describe the expression.
4696  *
4697  * Inputs:
4698  * root: the planner info
4699  * node: the expression tree to examine
4700  * varRelid: see specs for restriction selectivity functions
4701  *
4702  * Outputs: *vardata is filled as follows:
4703  * var: the input expression (with any binary relabeling stripped, if
4704  * it is or contains a variable; but otherwise the type is preserved)
4705  * rel: RelOptInfo for relation containing variable; NULL if expression
4706  * contains no Vars (NOTE this could point to a RelOptInfo of a
4707  * subquery, not one in the current query).
4708  * statsTuple: the pg_statistic entry for the variable, if one exists;
4709  * otherwise NULL.
4710  * freefunc: pointer to a function to release statsTuple with.
4711  * vartype: exposed type of the expression; this should always match
4712  * the declared input type of the operator we are estimating for.
4713  * atttype, atttypmod: actual type/typmod of the "var" expression. This is
4714  * commonly the same as the exposed type of the variable argument,
4715  * but can be different in binary-compatible-type cases.
4716  * isunique: true if we were able to match the var to a unique index or a
4717  * single-column DISTINCT clause, implying its values are unique for
4718  * this query. (Caution: this should be trusted for statistical
4719  * purposes only, since we do not check indimmediate nor verify that
4720  * the exact same definition of equality applies.)
4721  * acl_ok: true if current user has permission to read the column(s)
4722  * underlying the pg_statistic entry. This is consulted by
4723  * statistic_proc_security_check().
4724  *
4725  * Caller is responsible for doing ReleaseVariableStats() before exiting.
4726  */
4727 void
4728 examine_variable(PlannerInfo *root, Node *node, int varRelid,
4729  VariableStatData *vardata)
4730 {
4731  Node *basenode;
4732  Relids varnos;
4733  RelOptInfo *onerel;
4734 
4735  /* Make sure we don't return dangling pointers in vardata */
4736  MemSet(vardata, 0, sizeof(VariableStatData));
4737 
4738  /* Save the exposed type of the expression */
4739  vardata->vartype = exprType(node);
4740 
4741  /* Look inside any binary-compatible relabeling */
4742 
4743  if (IsA(node, RelabelType))
4744  basenode = (Node *) ((RelabelType *) node)->arg;
4745  else
4746  basenode = node;
4747 
4748  /* Fast path for a simple Var */
4749 
4750  if (IsA(basenode, Var) &&
4751  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4752  {
4753  Var *var = (Var *) basenode;
4754 
4755  /* Set up result fields other than the stats tuple */
4756  vardata->var = basenode; /* return Var without relabeling */
4757  vardata->rel = find_base_rel(root, var->varno);
4758  vardata->atttype = var->vartype;
4759  vardata->atttypmod = var->vartypmod;
4760  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4761 
4762  /* Try to locate some stats */
4763  examine_simple_variable(root, var, vardata);
4764 
4765  return;
4766  }
4767 
4768  /*
4769  * Okay, it's a more complicated expression. Determine variable
4770  * membership. Note that when varRelid isn't zero, only vars of that
4771  * relation are considered "real" vars.
4772  */
4773  varnos = pull_varnos(basenode);
4774 
4775  onerel = NULL;
4776 
4777  switch (bms_membership(varnos))
4778  {
4779  case BMS_EMPTY_SET:
4780  /* No Vars at all ... must be pseudo-constant clause */
4781  break;
4782  case BMS_SINGLETON:
4783  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4784  {
4785  onerel = find_base_rel(root,
4786  (varRelid ? varRelid : bms_singleton_member(varnos)));
4787  vardata->rel = onerel;
4788  node = basenode; /* strip any relabeling */
4789  }
4790  /* else treat it as a constant */
4791  break;
4792  case BMS_MULTIPLE:
4793  if (varRelid == 0)
4794  {
4795  /* treat it as a variable of a join relation */
4796  vardata->rel = find_join_rel(root, varnos);
4797  node = basenode; /* strip any relabeling */
4798  }
4799  else if (bms_is_member(varRelid, varnos))
4800  {
4801  /* ignore the vars belonging to other relations */
4802  vardata->rel = find_base_rel(root, varRelid);
4803  node = basenode; /* strip any relabeling */
4804  /* note: no point in expressional-index search here */
4805  }
4806  /* else treat it as a constant */
4807  break;
4808  }
4809 
4810  bms_free(varnos);
4811 
4812  vardata->var = node;
4813  vardata->atttype = exprType(node);
4814  vardata->atttypmod = exprTypmod(node);
4815 
4816  if (onerel)
4817  {
4818  /*
4819  * We have an expression in vars of a single relation. Try to match
4820  * it to expressional index columns, in hopes of finding some
4821  * statistics.
4822  *
4823  * XXX it's conceivable that there are multiple matches with different
4824  * index opfamilies; if so, we need to pick one that matches the
4825  * operator we are estimating for. FIXME later.
4826  */
4827  ListCell *ilist;
4828 
4829  foreach(ilist, onerel->indexlist)
4830  {
4831  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4832  ListCell *indexpr_item;
4833  int pos;
4834 
4835  indexpr_item = list_head(index->indexprs);
4836  if (indexpr_item == NULL)
4837  continue; /* no expressions here... */
4838 
4839  for (pos = 0; pos < index->ncolumns; pos++)
4840  {
4841  if (index->indexkeys[pos] == 0)
4842  {
4843  Node *indexkey;
4844 
4845  if (indexpr_item == NULL)
4846  elog(ERROR, "too few entries in indexprs list");
4847  indexkey = (Node *) lfirst(indexpr_item);
4848  if (indexkey && IsA(indexkey, RelabelType))
4849  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4850  if (equal(node, indexkey))
4851  {
4852  /*
4853  * Found a match ... is it a unique index? Tests here
4854  * should match has_unique_index().
4855  */
4856  if (index->unique &&
4857  index->ncolumns == 1 &&
4858  (index->indpred == NIL || index->predOK))
4859  vardata->isunique = true;
4860 
4861  /*
4862  * Has it got stats? We only consider stats for
4863  * non-partial indexes, since partial indexes probably
4864  * don't reflect whole-relation statistics; the above
4865  * check for uniqueness is the only info we take from
4866  * a partial index.
4867  *
4868  * An index stats hook, however, must make its own
4869  * decisions about what to do with partial indexes.
4870  */
4871  if (get_index_stats_hook &&
4872  (*get_index_stats_hook) (root, index->indexoid,
4873  pos + 1, vardata))
4874  {
4875  /*
4876  * The hook took control of acquiring a stats
4877  * tuple. If it did supply a tuple, it'd better
4878  * have supplied a freefunc.
4879  */
4880  if (HeapTupleIsValid(vardata->statsTuple) &&
4881  !vardata->freefunc)
4882  elog(ERROR, "no function provided to release variable stats with");
4883  }
4884  else if (index->indpred == NIL)
4885  {
4886  vardata->statsTuple =
4888  ObjectIdGetDatum(index->indexoid),
4889  Int16GetDatum(pos + 1),
4890  BoolGetDatum(false));
4891  vardata->freefunc = ReleaseSysCache;
4892 
4893  if (HeapTupleIsValid(vardata->statsTuple))
4894  {
4895  /* Get index's table for permission check */
4896  RangeTblEntry *rte;
4897 
4898  rte = planner_rt_fetch(index->rel->relid, root);
4899  Assert(rte->rtekind == RTE_RELATION);
4900 
4901  /*
4902  * For simplicity, we insist on the whole
4903  * table being selectable, rather than trying
4904  * to identify which column(s) the index
4905  * depends on.
4906  */
4907  vardata->acl_ok =
4909  ACL_SELECT) == ACLCHECK_OK);
4910  }
4911  else
4912  {
4913  /* suppress leakproofness checks later */
4914  vardata->acl_ok = true;
4915  }
4916  }
4917  if (vardata->statsTuple)
4918  break;
4919  }
4920  indexpr_item = lnext(indexpr_item);
4921  }
4922  }
4923  if (vardata->statsTuple)
4924  break;
4925  }
4926  }
4927 }
4928 
4929 /*
4930  * examine_simple_variable
4931  * Handle a simple Var for examine_variable
4932  *
4933  * This is split out as a subroutine so that we can recurse to deal with
4934  * Vars referencing subqueries.
4935  *
4936  * We already filled in all the fields of *vardata except for the stats tuple.
4937  */
4938 static void
4940  VariableStatData *vardata)
4941 {
4942  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4943 
4944  Assert(IsA(rte, RangeTblEntry));
4945 
4947  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4948  {
4949  /*
4950  * The hook took control of acquiring a stats tuple. If it did supply
4951  * a tuple, it'd better have supplied a freefunc.
4952  */
4953  if (HeapTupleIsValid(vardata->statsTuple) &&
4954  !vardata->freefunc)
4955  elog(ERROR, "no function provided to release variable stats with");
4956  }
4957  else if (rte->rtekind == RTE_RELATION)
4958  {
4959  /*
4960  * Plain table or parent of an inheritance appendrel, so look up the
4961  * column in pg_statistic
4962  */
4964  ObjectIdGetDatum(rte->relid),
4965  Int16GetDatum(var->varattno),
4966  BoolGetDatum(rte->inh));
4967  vardata->freefunc = ReleaseSysCache;
4968 
4969  if (HeapTupleIsValid(vardata->statsTuple))
4970  {
4971  /* check if user has permission to read this column */
4972  vardata->acl_ok =
4974  ACL_SELECT) == ACLCHECK_OK) ||
4976  ACL_SELECT) == ACLCHECK_OK);
4977  }
4978  else
4979  {
4980  /* suppress any possible leakproofness checks later */
4981  vardata->acl_ok = true;
4982  }
4983  }
4984  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4985  {
4986  /*
4987  * Plain subquery (not one that was converted to an appendrel).
4988  */
4989  Query *subquery = rte->subquery;
4990  RelOptInfo *rel;
4991  TargetEntry *ste;
4992 
4993  /*
4994  * Punt if it's a whole-row var rather than a plain column reference.
4995  */
4996  if (var->varattno == InvalidAttrNumber)
4997  return;
4998 
4999  /*
5000  * Punt if subquery uses set operations or GROUP BY, as these will
5001  * mash underlying columns' stats beyond recognition. (Set ops are
5002  * particularly nasty; if we forged ahead, we would return stats
5003  * relevant to only the leftmost subselect...) DISTINCT is also
5004  * problematic, but we check that later because there is a possibility
5005  * of learning something even with it.
5006  */
5007  if (subquery->setOperations ||
5008  subquery->groupClause)
5009  return;
5010 
5011  /*
5012  * OK, fetch RelOptInfo for subquery. Note that we don't change the
5013  * rel returned in vardata, since caller expects it to be a rel of the
5014  * caller's query level. Because we might already be recursing, we
5015  * can't use that rel pointer either, but have to look up the Var's
5016  * rel afresh.
5017  */
5018  rel = find_base_rel(root, var->varno);
5019 
5020  /* If the subquery hasn't been planned yet, we have to punt */
5021  if (rel->subroot == NULL)
5022  return;
5023  Assert(IsA(rel->subroot, PlannerInfo));
5024 
5025  /*
5026  * Switch our attention to the subquery as mangled by the planner. It
5027  * was okay to look at the pre-planning version for the tests above,
5028  * but now we need a Var that will refer to the subroot's live
5029  * RelOptInfos. For instance, if any subquery pullup happened during
5030  * planning, Vars in the targetlist might have gotten replaced, and we
5031  * need to see the replacement expressions.
5032  */
5033  subquery = rel->subroot->parse;
5034  Assert(IsA(subquery, Query));
5035 
5036  /* Get the subquery output expression referenced by the upper Var */
5037  ste = get_tle_by_resno(subquery->targetList, var->varattno);
5038  if (ste == NULL || ste->resjunk)
5039  elog(ERROR, "subquery %s does not have attribute %d",
5040  rte->eref->aliasname, var->varattno);
5041  var = (Var *) ste->expr;
5042 
5043  /*
5044  * If subquery uses DISTINCT, we can't make use of any stats for the
5045  * variable ... but, if it's the only DISTINCT column, we are entitled
5046  * to consider it unique. We do the test this way so that it works
5047  * for cases involving DISTINCT ON.
5048  */
5049  if (subquery->distinctClause)
5050  {
5051  if (list_length(subquery->distinctClause) == 1 &&
5052  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5053  vardata->isunique = true;
5054  /* cannot go further */
5055  return;
5056  }
5057 
5058  /*
5059  * If the sub-query originated from a view with the security_barrier
5060  * attribute, we must not look at the variable's statistics, though it
5061  * seems all right to notice the existence of a DISTINCT clause. So
5062  * stop here.
5063  *
5064  * This is probably a harsher restriction than necessary; it's
5065  * certainly OK for the selectivity estimator (which is a C function,
5066  * and therefore omnipotent anyway) to look at the statistics. But
5067  * many selectivity estimators will happily *invoke the operator
5068  * function* to try to work out a good estimate - and that's not OK.
5069  * So for now, don't dig down for stats.
5070  */
5071  if (rte->security_barrier)
5072  return;
5073 
5074  /* Can only handle a simple Var of subquery's query level */
5075  if (var && IsA(var, Var) &&
5076  var->varlevelsup == 0)
5077  {
5078  /*
5079  * OK, recurse into the subquery. Note that the original setting
5080  * of vardata->isunique (which will surely be false) is left
5081  * unchanged in this situation. That's what we want, since even
5082  * if the underlying column is unique, the subquery may have
5083  * joined to other tables in a way that creates duplicates.
5084  */
5085  examine_simple_variable(rel->subroot, var, vardata);
5086  }
5087  }
5088  else
5089  {
5090  /*
5091  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
5092  * won't see RTE_JOIN here because join alias Vars have already been
5093  * flattened.) There's not much we can do with function outputs, but
5094  * maybe someday try to be smarter about VALUES and/or CTEs.
5095  */
5096  }
5097 }
5098 
5099 /*
5100  * Check whether it is permitted to call func_oid passing some of the
5101  * pg_statistic data in vardata. We allow this either if the user has SELECT
5102  * privileges on the table or column underlying the pg_statistic data or if
5103  * the function is marked leak-proof.
5104  */
5105 bool
5107 {
5108  if (vardata->acl_ok)
5109  return true;
5110 
5111  if (!OidIsValid(func_oid))
5112  return false;
5113 
5114  if (get_func_leakproof(func_oid))
5115  return true;
5116 
5117  ereport(DEBUG2,
5118  (errmsg_internal("not using statistics because function \"%s\" is not leak-proof",
5119  get_func_name(func_oid))));
5120  return false;
5121 }
5122 
5123 /*
5124  * get_variable_numdistinct
5125  * Estimate the number of distinct values of a variable.
5126  *
5127  * vardata: results of examine_variable
5128  * *isdefault: set to true if the result is a default rather than based on
5129  * anything meaningful.
5130  *
5131  * NB: be careful to produce a positive integral result, since callers may
5132  * compare the result to exact integer counts, or might divide by it.
5133  */
5134 double
5135 get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
5136 {
5137  double stadistinct;
5138  double stanullfrac = 0.0;
5139  double ntuples;
5140 
5141  *isdefault = false;
5142 
5143  /*
5144  * Determine the stadistinct value to use. There are cases where we can
5145  * get an estimate even without a pg_statistic entry, or can get a better
5146  * value than is in pg_statistic. Grab stanullfrac too if we can find it
5147  * (otherwise, assume no nulls, for lack of any better idea).
5148  */
5149  if (HeapTupleIsValid(vardata->statsTuple))
5150  {
5151  /* Use the pg_statistic entry */
5152  Form_pg_statistic stats;
5153 
5154  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
5155  stadistinct = stats->stadistinct;
5156  stanullfrac = stats->stanullfrac;
5157  }
5158  else if (vardata->vartype == BOOLOID)
5159  {
5160  /*
5161  * Special-case boolean columns: presumably, two distinct values.
5162  *
5163  * Are there any other datatypes we should wire in special estimates
5164  * for?
5165  */
5166  stadistinct = 2.0;
5167  }
5168  else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5169  {
5170  /*
5171  * If the Var represents a column of a VALUES RTE, assume it's unique.
5172  * This could of course be very wrong, but it should tend to be true
5173  * in well-written queries. We could consider examining the VALUES'
5174  * contents to get some real statistics; but that only works if the
5175  * entries are all constants, and it would be pretty expensive anyway.
5176  */
5177  stadistinct = -1.0; /* unique (and all non null) */
5178  }
5179  else
5180  {
5181  /*
5182  * We don't keep statistics for system columns, but in some cases we
5183  * can infer distinctness anyway.
5184  */
5185  if (vardata->var && IsA(vardata->var, Var))
5186  {
5187  switch (((Var *) vardata->var)->varattno)
5188  {
5191  stadistinct = -1.0; /* unique (and all non null) */
5192  break;
5194  stadistinct = 1.0; /* only 1 value */
5195  break;
5196  default:
5197  stadistinct = 0.0; /* means "unknown" */
5198  break;
5199  }
5200  }
5201  else
5202  stadistinct = 0.0; /* means "unknown" */
5203 
5204  /*
5205  * XXX consider using estimate_num_groups on expressions?
5206  */
5207  }
5208 
5209  /*
5210  * If there is a unique index or DISTINCT clause for the variable, assume
5211  * it is unique no matter what pg_statistic says; the statistics could be
5212  * out of date, or we might have found a partial unique index that proves
5213  * the var is unique for this query. However, we'd better still believe
5214  * the null-fraction statistic.
5215  */
5216  if (vardata->isunique)
5217  stadistinct = -1.0 * (1.0 - stanullfrac);
5218 
5219  /*
5220  * If we had an absolute estimate, use that.
5221  */
5222  if (stadistinct > 0.0)
5223  return clamp_row_est(stadistinct);
5224 
5225  /*
5226  * Otherwise we need to get the relation size; punt if not available.
5227  */
5228  if (vardata->rel == NULL)
5229  {
5230  *isdefault = true;
5231  return DEFAULT_NUM_DISTINCT;
5232  }
5233  ntuples = vardata->rel->tuples;
5234  if (ntuples <= 0.0)
5235  {
5236  *isdefault = true;
5237  return DEFAULT_NUM_DISTINCT;
5238  }
5239 
5240  /*
5241  * If we had a relative estimate, use that.
5242  */
5243  if (stadistinct < 0.0)
5244  return clamp_row_est(-stadistinct * ntuples);
5245 
5246  /*
5247  * With no data, estimate ndistinct = ntuples if the table is small, else
5248  * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
5249  * that the behavior isn't discontinuous.
5250  */
5251  if (ntuples < DEFAULT_NUM_DISTINCT)
5252  return clamp_row_est(ntuples);
5253 
5254  *isdefault = true;
5255  return DEFAULT_NUM_DISTINCT;
5256 }
5257 
5258 /*
5259  * get_variable_range
5260  * Estimate the minimum and maximum value of the specified variable.
5261  * If successful, store values in *min and *max, and return true.
5262  * If no data available, return false.
5263  *
5264  * sortop is the "<" comparison operator to use. This should generally
5265  * be "<" not ">", as only the former is likely to be found in pg_statistic.
5266  */
5267 static bool
5269  Datum *min, Datum *max)
5270 {
5271  Datum tmin = 0;
5272  Datum tmax = 0;
5273  bool have_data = false;
5274  int16 typLen;
5275  bool typByVal;
5276  Oid opfuncoid;
5277  AttStatsSlot sslot;
5278  int i;
5279 
5280  /*
5281  * XXX It's very tempting to try to use the actual column min and max, if
5282  * we can get them relatively-cheaply with an index probe. However, since
5283  * this function is called many times during join planning, that could
5284  * have unpleasant effects on planning speed. Need more investigation
5285  * before enabling this.
5286  */
5287 #ifdef NOT_USED
5288  if (get_actual_variable_range(root, vardata, sortop, min, max))
5289  return true;
5290 #endif
5291 
5292  if (!HeapTupleIsValid(vardata->statsTuple))
5293  {
5294  /* no stats available, so default result */
5295  return false;
5296  }
5297 
5298  /*
5299  * If we can't apply the sortop to the stats data, just fail. In
5300  * principle, if there's a histogram and no MCVs, we could return the
5301  * histogram endpoints without ever applying the sortop ... but it's
5302  * probably not worth trying, because whatever the caller wants to do with
5303  * the endpoints would likely fail the security check too.
5304  */
5305  if (!statistic_proc_security_check(vardata,
5306  (opfuncoid = get_opcode(sortop))))
5307  return false;
5308 
5309  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5310 
5311  /*
5312  * If there is a histogram, grab the first and last values.
5313  *
5314  * If there is a histogram that is sorted with some other operator than
5315  * the one we want, fail --- this suggests that there is data we can't
5316  * use.
5317  */
5318  if (get_attstatsslot(&sslot, vardata->statsTuple,
5319  STATISTIC_KIND_HISTOGRAM, sortop,
5321  {
5322  if (sslot.nvalues > 0)
5323  {
5324  tmin = datumCopy(sslot.values[0], typByVal, typLen);
5325  tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
5326  have_data = true;
5327  }
5328  free_attstatsslot(&sslot);
5329  }
5330  else if (get_attstatsslot(&sslot, vardata->statsTuple,
5332  0))
5333  {
5334  free_attstatsslot(&sslot);
5335  return false;
5336  }
5337 
5338  /*
5339  * If we have most-common-values info, look for extreme MCVs. This is
5340  * needed even if we also have a histogram, since the histogram excludes
5341  * the MCVs. However, usually the MCVs will not be the extreme values, so
5342  * avoid unnecessary data copying.
5343  */
5344  if (get_attstatsslot(&sslot, vardata->statsTuple,
5347  {
5348  bool tmin_is_mcv = false;
5349  bool tmax_is_mcv = false;
5350  FmgrInfo opproc;
5351 
5352  fmgr_info(opfuncoid, &opproc);
5353 
5354  for (i = 0; i < sslot.nvalues; i++)
5355  {
5356  if (!have_data)
5357  {
5358  tmin = tmax = sslot.values[i];
5359  tmin_is_mcv = tmax_is_mcv = have_data = true;
5360  continue;
5361  }
5362  if (DatumGetBool(FunctionCall2Coll(&opproc,
5364  sslot.values[i], tmin)))
5365  {
5366  tmin = sslot.values[i];
5367  tmin_is_mcv = true;
5368  }
5369  if (DatumGetBool(FunctionCall2Coll(&opproc,
5371  tmax, sslot.values[i])))
5372  {
5373  tmax = sslot.values[i];
5374  tmax_is_mcv = true;
5375  }
5376  }
5377  if (tmin_is_mcv)
5378  tmin = datumCopy(tmin, typByVal, typLen);
5379  if (tmax_is_mcv)
5380  tmax = datumCopy(tmax, typByVal, typLen);
5381  free_attstatsslot(&sslot);
5382  }
5383 
5384  *min = tmin;
5385  *max = tmax;
5386  return have_data;
5387 }
5388 
5389 
5390 /*
5391  * get_actual_variable_range
5392  * Attempt to identify the current *actual* minimum and/or maximum
5393  * of the specified variable, by looking for a suitable btree index
5394  * and fetching its low and/or high values.
5395  * If successful, store values in *min and *max, and return true.
5396  * (Either pointer can be NULL if that endpoint isn't needed.)
5397  * If no data available, return false.
5398  *
5399  * sortop is the "<" comparison operator to use.
5400  */
5401 static bool
5403  Oid sortop,
5404  Datum *min, Datum *max)
5405 {
5406  bool have_data = false;
5407  RelOptInfo *rel = vardata->rel;
5408  RangeTblEntry *rte;
5409  ListCell *lc;
5410 
5411  /* No hope if no relation or it doesn't have indexes */
5412  if (rel == NULL || rel->indexlist == NIL)
5413  return false;
5414  /* If it has indexes it must be a plain relation */
5415  rte = root->simple_rte_array[rel->relid];
5416  Assert(rte->rtekind == RTE_RELATION);
5417 
5418  /* Search through the indexes to see if any match our problem */
5419  foreach(lc, rel->indexlist)
5420  {
5422  ScanDirection indexscandir;
5423 
5424  /* Ignore non-btree indexes */
5425  if (index->relam != BTREE_AM_OID)
5426  continue;
5427 
5428  /*
5429  * Ignore partial indexes --- we only want stats that cover the entire
5430  * relation.
5431  */
5432  if (index->indpred != NIL)
5433  continue;
5434 
5435  /*
5436  * The index list might include hypothetical indexes inserted by a
5437  * get_relation_info hook --- don't try to access them.
5438  */
5439  if (index->hypothetical)
5440  continue;
5441 
5442  /*
5443  * The first index column must match the desired variable and sort
5444  * operator --- but we can use a descending-order index.
5445  */
5446  if (!match_index_to_operand(vardata->var, 0, index))
5447  continue;
5448  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5449  {
5450  case BTLessStrategyNumber:
5451  if (index->reverse_sort[0])
5452  indexscandir = BackwardScanDirection;
5453  else
5454  indexscandir = ForwardScanDirection;
5455  break;
5457  if (index->reverse_sort[0])
5458  indexscandir = ForwardScanDirection;
5459  else
5460  indexscandir = BackwardScanDirection;
5461  break;
5462  default:
5463  /* index doesn't match the sortop */
5464  continue;
5465  }
5466 
5467  /*
5468  * Found a suitable index to extract data from. We'll need an EState
5469  * and a bunch of other infrastructure.
5470  */
5471  {
5472  EState *estate;
5473  ExprContext *econtext;
5474  MemoryContext tmpcontext;
5475  MemoryContext oldcontext;
5476  Relation heapRel;
5477  Relation indexRel;
5478  IndexInfo *indexInfo;
5479  TupleTableSlot *slot;
5480  int16 typLen;
5481  bool typByVal;
5482  ScanKeyData scankeys[1];
5483  IndexScanDesc index_scan;
5484  HeapTuple tup;
5486  bool isnull[INDEX_MAX_KEYS];
5487  SnapshotData SnapshotNonVacuumable;
5488 
5489  estate = CreateExecutorState();
5490  econtext = GetPerTupleExprContext(estate);
5491  /* Make sure any cruft is generated in the econtext's memory */
5492  tmpcontext = econtext->ecxt_per_tuple_memory;
5493  oldcontext = MemoryContextSwitchTo(tmpcontext);
5494 
5495  /*
5496  * Open the table and index so we can read from them. We should
5497  * already have at least AccessShareLock on the table, but not
5498  * necessarily on the index.
5499  */
5500  heapRel = heap_open(rte->relid, NoLock);
5501  indexRel = index_open(index->indexoid, AccessShareLock);
5502 
5503  /* extract index key information from the index's pg_index info */
5504  indexInfo = BuildIndexInfo(indexRel);
5505 
5506  /* some other stuff */
5507  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
5508  econtext->ecxt_scantuple = slot;
5509  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5510  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5511 
5512  /* set up an IS NOT NULL scan key so that we ignore nulls */
5513  ScanKeyEntryInitialize(&scankeys[0],
5515  1, /* index col to scan */
5516  InvalidStrategy, /* no strategy */
5517  InvalidOid, /* no strategy subtype */
5518  InvalidOid, /* no collation */
5519  InvalidOid, /* no reg proc for this */
5520  (Datum) 0); /* constant */
5521 
5522  have_data = true;
5523 
5524  /* If min is requested ... */
5525  if (min)
5526  {
5527  /*
5528  * In principle, we should scan the index with our current
5529  * active snapshot, which is the best approximation we've got
5530  * to what the query will see when executed. But that won't
5531  * be exact if a new snap is taken before running the query,
5532  * and it can be very expensive if a lot of recently-dead or
5533  * uncommitted rows exist at the beginning or end of the index
5534  * (because we'll laboriously fetch each one and reject it).
5535  * Instead, we use SnapshotNonVacuumable. That will accept
5536  * recently-dead and uncommitted rows as well as normal
5537  * visible rows. On the other hand, it will reject known-dead
5538  * rows, and thus not give a bogus answer when the extreme
5539  * value has been deleted (unless the deletion was quite
5540  * recent); that case motivates not using SnapshotAny here.
5541  *
5542  * A crucial point here is that SnapshotNonVacuumable, with
5543  * RecentGlobalXmin as horizon, yields the inverse of the
5544  * condition that the indexscan will use to decide that index
5545  * entries are killable (see heap_hot_search_buffer()).
5546  * Therefore, if the snapshot rejects a tuple and we have to
5547  * continue scanning past it, we know that the indexscan will
5548  * mark that index entry killed. That means that the next
5549  * get_actual_variable_range() call will not have to visit
5550  * that heap entry. In this way we avoid repetitive work when
5551  * this function is used a lot during planning.
5552  */
5553  index_scan = index_beginscan(heapRel, indexRel,
5554  &SnapshotNonVacuumable,
5555  1, 0);
5556  index_rescan(index_scan, scankeys, 1, NULL, 0);
5557 
5558  /* Fetch first tuple in sortop's direction */
5559  if ((tup = index_getnext(index_scan,
5560  indexscandir)) != NULL)
5561  {
5562  /* Extract the index column values from the heap tuple */
5563  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5564  FormIndexDatum(indexInfo, slot, estate,
5565  values, isnull);
5566 
5567  /* Shouldn't have got a null, but be careful */
5568  if (isnull[0])
5569  elog(ERROR, "found unexpected null value in index \"%s\"",
5570  RelationGetRelationName(indexRel));
5571 
5572  /* Copy the index column value out to caller's context */
5573  MemoryContextSwitchTo(oldcontext);
5574  *min = datumCopy(values[0], typByVal, typLen);
5575  MemoryContextSwitchTo(tmpcontext);
5576  }
5577  else
5578  have_data = false;
5579 
5580  index_endscan(index_scan);
5581  }
5582 
5583  /* If max is requested, and we didn't find the index is empty */
5584  if (max && have_data)
5585  {
5586  index_scan = index_beginscan(heapRel, indexRel,
5587  &SnapshotNonVacuumable,
5588  1, 0);
5589  index_rescan(index_scan, scankeys, 1, NULL, 0);
5590 
5591  /* Fetch first tuple in reverse direction */
5592  if ((tup = index_getnext(index_scan,
5593  -indexscandir)) != NULL)
5594  {
5595  /* Extract the index column values from the heap tuple */
5596  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5597  FormIndexDatum(indexInfo, slot, estate,
5598  values, isnull);
5599 
5600  /* Shouldn't have got a null, but be careful */
5601  if (isnull[0])
5602  elog(ERROR, "found unexpected null value in index \"%s\"",
5603  RelationGetRelationName(indexRel));
5604 
5605  /* Copy the index column value out to caller's context */
5606  MemoryContextSwitchTo(oldcontext);
5607  *max = datumCopy(values[0], typByVal, typLen);
5608  MemoryContextSwitchTo(tmpcontext);
5609  }
5610  else
5611  have_data = false;
5612 
5613  index_endscan(index_scan);
5614  }
5615 
5616  /* Clean everything up */
5618 
5619  index_close(indexRel, AccessShareLock);
5620  heap_close(heapRel, NoLock);
5621 
5622  MemoryContextSwitchTo(oldcontext);
5623  FreeExecutorState(estate);
5624 
5625  /* And we're done */
5626  break;
5627  }
5628  }
5629 
5630  return have_data;
5631 }
5632 
5633 /*
5634  * find_join_input_rel
5635  * Look up the input relation for a join.
5636  *
5637  * We assume that the input relation's RelOptInfo must have been constructed
5638  * already.
5639  */
5640 static RelOptInfo *
5642 {
5643  RelOptInfo *rel = NULL;
5644 
5645  switch (bms_membership(relids))
5646  {
5647  case BMS_EMPTY_SET:
5648  /* should not happen */
5649  break;
5650  case BMS_SINGLETON:
5651  rel = find_base_rel(root, bms_singleton_member(relids));
5652  break;
5653  case BMS_MULTIPLE:
5654  rel = find_join_rel(root, relids);
5655  break;
5656  }
5657 
5658  if (rel == NULL)
5659  elog(ERROR, "could not find RelOptInfo for given relids");
5660 
5661  return rel;
5662 }
5663 
5664 
5665 /*-------------------------------------------------------------------------
5666  *
5667  * Pattern analysis functions
5668  *
5669  * These routines support analysis of LIKE and regular-expression patterns
5670  * by the planner/optimizer. It's important that they agree with the
5671  * regular-expression code in backend/regex/ and the LIKE code in
5672  * backend/utils/adt/like.c. Also, the computation of the fixed prefix
5673  * must be conservative: if we report a string longer than the true fixed
5674  * prefix, the query may produce actually wrong answers, rather than just
5675  * getting a bad selectivity estimate!
5676  *
5677  * Note that the prefix-analysis functions are called from
5678  * backend/optimizer/path/indxpath.c as well as from routines in this file.
5679  *
5680  *-------------------------------------------------------------------------
5681  */
5682 
5683 /*
5684  * Check whether char is a letter (and, hence, subject to case-folding)
5685  *
5686  * In multibyte character sets or with ICU, we can't use isalpha, and it does not seem
5687  * worth trying to convert to wchar_t to use iswalpha. Instead, just assume
5688  * any multibyte char is potentially case-varying.
5689  */
5690 static int
5691 pattern_char_isalpha(char c, bool is_multibyte,
5692  pg_locale_t locale, bool locale_is_c)
5693 {
5694  if (locale_is_c)
5695  return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
5696  else if (is_multibyte && IS_HIGHBIT_SET(c))
5697  return true;
5698  else if (locale && locale->provider == COLLPROVIDER_ICU)
5699  return IS_HIGHBIT_SET(c) ? true : false;
5700 #ifdef HAVE_LOCALE_T
5701  else if (locale && locale->provider == COLLPROVIDER_LIBC)
5702  return isalpha_l((unsigned char) c, locale->info.lt);
5703 #endif
5704  else
5705  return isalpha((unsigned char) c);
5706 }
5707 
5708 /*
5709  * Extract the fixed prefix, if any, for a pattern.
5710  *
5711  * *prefix is set to a palloc'd prefix string (in the form of a Const node),
5712  * or to NULL if no fixed prefix exists for the pattern.
5713  * If rest_selec is not NULL, *rest_selec is set to an estimate of the
5714  * selectivity of the remainder of the pattern (without any fixed prefix).
5715  * The prefix Const has the same type (TEXT or BYTEA) as the input pattern.
5716  *
5717  * The return value distinguishes no fixed prefix, a partial prefix,
5718  * or an exact-match-only pattern.
5719  */
5720 
5721 static Pattern_Prefix_Status
5722 like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
5723  Const **prefix_const, Selectivity *rest_selec)
5724 {
5725  char *match;
5726  char *patt;
5727  int pattlen;
5728  Oid typeid = patt_const->consttype;
5729  int pos,
5730  match_pos;
5731  bool is_multibyte = (pg_database_encoding_max_length() > 1);
5732  pg_locale_t locale = 0;
5733  bool locale_is_c = false;
5734 
5735  /* the right-hand const is type text or bytea */
5736  Assert(typeid == BYTEAOID || typeid == TEXTOID);
5737 
5738  if (case_insensitive)
5739  {
5740  if (typeid == BYTEAOID)
5741  ereport(ERROR,
5742  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5743  errmsg("case insensitive matching not supported on type bytea")));
5744 
5745  /* If case-insensitive, we need locale info */
5746  if (lc_ctype_is_c(collation))
5747  locale_is_c = true;
5748  else if (collation != DEFAULT_COLLATION_OID)
5749  {
5750  if (!OidIsValid(collation))
5751  {
5752  /*
5753  * This typically means that the parser could not resolve a
5754  * conflict of implicit collations, so report it that way.
5755  */
5756  ereport(ERROR,
5757  (errcode(ERRCODE_INDETERMINATE_COLLATION),
5758  errmsg("could not determine which collation to use for ILIKE"),
5759  errhint("Use the COLLATE clause to set the collation explicitly.")));
5760  }
5761  locale = pg_newlocale_from_collation(collation);
5762  }
5763  }
5764 
5765  if (typeid != BYTEAOID)
5766  {
5767  patt = TextDatumGetCString(patt_const->constvalue);
5768  pattlen = strlen(patt);
5769  }
5770  else
5771  {
5772  bytea *bstr = DatumGetByteaPP(patt_const->constvalue);
5773 
5774  pattlen = VARSIZE_ANY_EXHDR(bstr);
5775  patt = (char *) palloc(pattlen);
5776  memcpy(patt, VARDATA_ANY(bstr), pattlen);
5777  Assert((Pointer) bstr == DatumGetPointer(patt_const->constvalue));
5778  }
5779 
5780  match = palloc(pattlen + 1);
5781  match_pos = 0;
5782  for (pos = 0; pos < pattlen; pos++)
5783  {
5784  /* % and _ are wildcard characters in LIKE */
5785  if (patt[pos] == '%' ||
5786  patt[pos] == '_')
5787  break;
5788 
5789  /* Backslash escapes the next character */
5790  if (patt[pos] == '\\')
5791  {
5792  pos++;
5793  if (pos >= pattlen)
5794  break;
5795  }
5796 
5797  /* Stop if case-varying character (it's sort of a wildcard) */
5798  if (case_insensitive &&
5799  pattern_char_isalpha(patt[pos], is_multibyte, locale, locale_is_c))
5800  break;
5801 
5802  match[match_pos++] = patt[pos];
5803  }
5804 
5805  match[match_pos] = '\0';
5806 
5807  if (typeid != BYTEAOID)
5808  *prefix_const = string_to_const(match, typeid);
5809  else
5810  *prefix_const = string_to_bytea_const(match, match_pos);
5811 
5812  if (rest_selec != NULL)
5813  *rest_selec = like_selectivity(&patt[pos], pattlen - pos,
5814  case_insensitive);
5815 
5816  pfree(patt);
5817  pfree(match);
5818 
5819  /* in LIKE, an empty pattern is an exact match! */
5820  if (pos == pattlen)
5821  return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
5822 
5823  if (match_pos > 0)
5824  return Pattern_Prefix_Partial;
5825 
5826  return Pattern_Prefix_None;
5827 }
5828 
5829 static Pattern_Prefix_Status
5830 regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
5831  Const **prefix_const, Selectivity *rest_selec)
5832 {
5833  Oid typeid = patt_const->consttype;
5834  char *prefix;
5835  bool exact;
5836 
5837  /*
5838  * Should be unnecessary, there are no bytea regex operators defined. As
5839  * such, it should be noted that the rest of this function has *not* been
5840  * made safe for binary (possibly NULL containing) strings.
5841  */
5842  if (typeid == BYTEAOID)
5843  ereport(ERROR,
5844  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5845  errmsg("regular-expression matching not supported on type bytea")));
5846 
5847  /* Use the regexp machinery to extract the prefix, if any */
5848  prefix = regexp_fixed_prefix(DatumGetTextPP(patt_const->constvalue),
5849  case_insensitive, collation,
5850  &exact);
5851 
5852  if (prefix == NULL)
5853  {
5854  *prefix_const = NULL;
5855 
5856  if (rest_selec != NULL)
5857  {
5858  char *patt = TextDatumGetCString(patt_const->constvalue);
5859 
5860  *rest_selec = regex_selectivity(patt, strlen(patt),
5861  case_insensitive,
5862  0);
5863  pfree(patt);
5864  }
5865 
5866  return Pattern_Prefix_None;
5867  }
5868 
5869  *prefix_const = string_to_const(prefix, typeid);
5870 
5871  if (rest_selec != NULL)
5872  {
5873  if (exact)
5874  {
5875  /* Exact match, so there's no additional selectivity */
5876  *rest_selec = 1.0;
5877  }
5878  else
5879  {
5880  char *patt = TextDatumGetCString(patt_const->constvalue);
5881 
5882  *rest_selec = regex_selectivity(patt, strlen(patt),
5883  case_insensitive,
5884  strlen(prefix));
5885  pfree(patt);
5886  }
5887  }
5888 
5889  pfree(prefix);
5890 
5891  if (exact)
5892  return Pattern_Prefix_Exact; /* pattern specifies exact match */
5893  else
5894  return Pattern_Prefix_Partial;
5895 }
5896 
5898 pattern_fixed_prefix(Const *patt, Pattern_Type ptype, Oid collation,
5899  Const **prefix, Selectivity *rest_selec)
5900 {
5901  Pattern_Prefix_Status result;
5902 
5903  switch (ptype)
5904  {
5905  case Pattern_Type_Like:
5906  result = like_fixed_prefix(patt, false, collation,
5907  prefix, rest_selec);
5908  break;
5909  case Pattern_Type_Like_IC:
5910  result = like_fixed_prefix(patt, true, collation,
5911  prefix, rest_selec);
5912  break;
5913  case Pattern_Type_Regex:
5914  result = regex_fixed_prefix(patt, false, collation,
5915  prefix, rest_selec);
5916  break;
5917  case Pattern_Type_Regex_IC:
5918  result = regex_fixed_prefix(patt, true, collation,
5919  prefix, rest_selec);
5920  break;
5921  default:
5922  elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5923  result = Pattern_Prefix_None; /* keep compiler quiet */
5924  break;
5925  }
5926  return result;
5927 }
5928 
5929 /*
5930  * Estimate the selectivity of a fixed prefix for a pattern match.
5931  *
5932  * A fixed prefix "foo" is estimated as the selectivity of the expression
5933  * "variable >= 'foo' AND variable < 'fop'" (see also indxpath.c).
5934  *
5935  * The selectivity estimate is with respect to the portion of the column
5936  * population represented by the histogram --- the caller must fold this
5937  * together with info about MCVs and NULLs.
5938  *
5939  * We use the >= and < operators from the specified btree opfamily to do the
5940  * estimation. The given variable and Const must be of the associated
5941  * datatype.
5942  *
5943  * XXX Note: we make use of the upper bound to estimate operator selectivity
5944  * even if the locale is such that we cannot rely on the upper-bound string.
5945  * The selectivity only needs to be approximately right anyway, so it seems
5946  * more useful to use the upper-bound code than not.
5947  */
5948 static Selectivity
5950  Oid vartype, Oid opfamily, Const *prefixcon)
5951 {
5952  Selectivity prefixsel;
5953  Oid cmpopr;
5954  FmgrInfo opproc;
5955  Const *greaterstrcon;
5956  Selectivity eq_sel;
5957 
5958  cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5960  if (cmpopr == InvalidOid)
5961  elog(ERROR, "no >= operator for opfamily %u", opfamily);
5962  fmgr_info(get_opcode(cmpopr), &opproc);
5963 
5964  prefixsel = ineq_histogram_selectivity(root, vardata,
5965  &opproc, true, true,
5966  prefixcon->constvalue,
5967  prefixcon->consttype);
5968 
5969  if (prefixsel < 0.0)
5970  {
5971  /* No histogram is present ... return a suitable default estimate */
5972  return DEFAULT_MATCH_SEL;
5973  }
5974 
5975  /*-------
5976  * If we can create a string larger than the prefix, say
5977  * "x < greaterstr".
5978  *-------
5979  */
5980  cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5982  if (cmpopr == InvalidOid)
5983  elog(ERROR, "no < operator for opfamily %u", opfamily);
5984  fmgr_info(get_opcode(cmpopr), &opproc);
5985  greaterstrcon = make_greater_string(prefixcon, &opproc,
5987  if (greaterstrcon)
5988  {
5989  Selectivity topsel;
5990 
5991  topsel = ineq_histogram_selectivity(root, vardata,
5992  &opproc, false, false,
5993  greaterstrcon->constvalue,
5994  greaterstrcon->consttype);
5995 
5996  /* ineq_histogram_selectivity worked before, it shouldn't fail now */
5997  Assert(topsel >= 0.0);
5998 
5999  /*
6000  * Merge the two selectivities in the same way as for a range query
6001  * (see clauselist_selectivity()). Note that we don't need to worry
6002  * about double-exclusion of nulls, since ineq_histogram_selectivity
6003  * doesn't count those anyway.
6004  */
6005  prefixsel = topsel + prefixsel - 1.0;
6006  }
6007 
6008  /*
6009  * If the prefix is long then the two bounding values might be too close
6010  * together for the histogram to distinguish them usefully, resulting in a
6011  * zero estimate (plus or minus roundoff error). To avoid returning a
6012  * ridiculously small estimate, compute the estimated selectivity for
6013  * "variable = 'foo'", and clamp to that. (Obviously, the resultant
6014  * estimate should be at least that.)
6015  *
6016  * We apply this even if we couldn't make a greater string. That case
6017  * suggests that the prefix is near the maximum possible, and thus
6018  * probably off the end of the histogram, and thus we probably got a very
6019  * small estimate from the >= condition; so we still need to clamp.
6020  */
6021  cmpopr = get_opfamily_member(opfamily, vartype, vartype,
6023  if (cmpopr == InvalidOid)
6024  elog(ERROR, "no = operator for opfamily %u", opfamily);
6025  eq_sel = var_eq_const(vardata, cmpopr, prefixcon->constvalue,
6026  false, true, false);
6027 
6028  prefixsel = Max(prefixsel, eq_sel);
6029 
6030  return prefixsel;
6031 }
6032 
6033 
6034 /*
6035  * Estimate the selectivity of a pattern of the specified type.
6036  * Note that any fixed prefix of the pattern will have been removed already,
6037  * so actually we may be looking at just a fragment of the pattern.
6038  *
6039  * For now, we use a very simplistic approach: fixed characters reduce the
6040  * selectivity a good deal, character ranges reduce it a little,
6041  * wildcards (such as % for LIKE or .* for regex) increase it.
6042  */
6043 
6044 #define FIXED_CHAR_SEL 0.20 /* about 1/5 */
6045 #define CHAR_RANGE_SEL 0.25
6046 #define ANY_CHAR_SEL 0.9 /* not 1, since it won't match end-of-string */
6047 #define FULL_WILDCARD_SEL 5.0
6048 #define PARTIAL_WILDCARD_SEL 2.0
6049 
6050 static Selectivity
6051 like_selectivity(const char *patt, int pattlen, bool case_insensitive)
6052 {
6053  Selectivity sel = 1.0;
6054  int pos;
6055 
6056  /* Skip any leading wildcard; it's already factored into initial sel */
6057  for (pos = 0; pos < pattlen; pos++)
6058  {
6059  if (patt[pos] != '%' && patt[pos] != '_')
6060  break;
6061  }
6062 
6063  for (; pos < pattlen; pos++)
6064  {
6065  /* % and _ are wildcard characters in LIKE */
6066  if (patt[pos] == '%')
6067  sel *= FULL_WILDCARD_SEL;
6068  else if (patt[pos] == '_')
6069  sel *= ANY_CHAR_SEL;
6070  else if (patt[pos] == '\\')
6071  {
6072  /* Backslash quotes the next character */
6073  pos++;
6074  if (pos >= pattlen)
6075  break;
6076  sel *= FIXED_CHAR_SEL;
6077  }
6078  else
6079  sel *= FIXED_CHAR_SEL;
6080  }
6081  /* Could get sel > 1 if multiple wildcards */
6082  if (sel > 1.0)
6083  sel = 1.0;
6084  return sel;
6085 }
6086 
6087 static Selectivity
6088 regex_selectivity_sub(const char *patt, int pattlen, bool case_insensitive)
6089 {
6090  Selectivity sel = 1.0;
6091  int paren_depth = 0;
6092  int paren_pos = 0; /* dummy init to keep compiler quiet */
6093  int pos;
6094 
6095  for (pos = 0; pos < pattlen; pos++)
6096  {
6097  if (patt[pos] == '(')
6098  {
6099  if (paren_depth == 0)
6100  paren_pos = pos; /* remember start of parenthesized item */
6101  paren_depth++;
6102  }
6103  else if (patt[pos] == ')' && paren_depth > 0)
6104  {
6105  paren_depth--;
6106  if (paren_depth == 0)
6107  sel *= regex_selectivity_sub(patt + (paren_pos + 1),
6108  pos - (paren_pos + 1),
6109  case_insensitive);
6110  }
6111  else if (patt[pos] == '|' && paren_depth == 0)
6112  {
6113  /*
6114  * If unquoted | is present at paren level 0 in pattern, we have
6115  * multiple alternatives; sum their probabilities.
6116  */
6117  sel += regex_selectivity_sub(patt + (pos + 1),
6118  pattlen - (pos + 1),
6119  case_insensitive);