1 /*-------------------------------------------------------------------------
4 * Selectivity functions and index cost estimation functions for
5 * standard operators and index access methods.
7 * Selectivity routines are registered in the pg_operator catalog
8 * in the "oprrest" and "oprjoin" attributes.
10 * Index cost functions are registered in the pg_am catalog
11 * in the "amcostestimate" attribute.
13 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
18 * src/backend/utils/adt/selfuncs.c
20 *-------------------------------------------------------------------------
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
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.
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.
39 * The call convention for a restriction estimator (oprrest function) is
41 * Selectivity oprrest (PlannerInfo *root,
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.
54 * This is represented at the SQL level (in pg_proc) as
56 * float8 oprrest (internal, oid, internal, int4);
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
62 * The call convention for a join estimator (oprjoin function) is similar
63 * except that varRelid is not needed, and instead join information is
66 * Selectivity oprjoin (PlannerInfo *root,
70 * SpecialJoinInfo *sjinfo);
72 * float8 oprjoin (internal, oid, internal, int2, internal);
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.
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.
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.
103 #include "access/gin.h"
104 #include "access/htup_details.h"
105 #include "access/sysattr.h"
106 #include "catalog/index.h"
107 #include "catalog/pg_collation.h"
108 #include "catalog/pg_opfamily.h"
109 #include "catalog/pg_statistic.h"
110 #include "catalog/pg_type.h"
111 #include "executor/executor.h"
112 #include "mb/pg_wchar.h"
113 #include "nodes/makefuncs.h"
114 #include "nodes/nodeFuncs.h"
115 #include "optimizer/clauses.h"
116 #include "optimizer/cost.h"
117 #include "optimizer/pathnode.h"
118 #include "optimizer/paths.h"
119 #include "optimizer/plancat.h"
120 #include "optimizer/predtest.h"
121 #include "optimizer/restrictinfo.h"
122 #include "optimizer/var.h"
123 #include "parser/parse_clause.h"
124 #include "parser/parse_coerce.h"
125 #include "parser/parsetree.h"
126 #include "utils/builtins.h"
127 #include "utils/bytea.h"
128 #include "utils/date.h"
129 #include "utils/datum.h"
130 #include "utils/fmgroids.h"
131 #include "utils/lsyscache.h"
132 #include "utils/nabstime.h"
133 #include "utils/pg_locale.h"
134 #include "utils/rel.h"
135 #include "utils/selfuncs.h"
136 #include "utils/spccache.h"
137 #include "utils/syscache.h"
138 #include "utils/timestamp.h"
139 #include "utils/tqual.h"
140 #include "utils/typcache.h"
143 /* Hooks for plugins to get control when we ask for stats */
144 get_relation_stats_hook_type get_relation_stats_hook = NULL;
145 get_index_stats_hook_type get_index_stats_hook = NULL;
147 static double var_eq_const(VariableStatData *vardata, Oid operator,
148 Datum constval, bool constisnull,
150 static double var_eq_non_const(VariableStatData *vardata, Oid operator,
153 static double ineq_histogram_selectivity(PlannerInfo *root,
154 VariableStatData *vardata,
155 FmgrInfo *opproc, bool isgt,
156 Datum constval, Oid consttype);
157 static double eqjoinsel_inner(Oid operator,
158 VariableStatData *vardata1, VariableStatData *vardata2);
159 static double eqjoinsel_semi(Oid operator,
160 VariableStatData *vardata1, VariableStatData *vardata2,
161 RelOptInfo *inner_rel);
162 static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
163 Datum lobound, Datum hibound, Oid boundstypid,
164 double *scaledlobound, double *scaledhibound);
165 static double convert_numeric_to_scalar(Datum value, Oid typid);
166 static void convert_string_to_scalar(char *value,
169 double *scaledlobound,
171 double *scaledhibound);
172 static void convert_bytea_to_scalar(Datum value,
175 double *scaledlobound,
177 double *scaledhibound);
178 static double convert_one_string_to_scalar(char *value,
179 int rangelo, int rangehi);
180 static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
181 int rangelo, int rangehi);
182 static char *convert_string_datum(Datum value, Oid typid);
183 static double convert_timevalue_to_scalar(Datum value, Oid typid);
184 static void examine_simple_variable(PlannerInfo *root, Var *var,
185 VariableStatData *vardata);
186 static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
187 Oid sortop, Datum *min, Datum *max);
188 static bool get_actual_variable_range(PlannerInfo *root,
189 VariableStatData *vardata,
191 Datum *min, Datum *max);
192 static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
193 static Selectivity prefix_selectivity(PlannerInfo *root,
194 VariableStatData *vardata,
195 Oid vartype, Oid opfamily, Const *prefixcon);
196 static Selectivity like_selectivity(const char *patt, int pattlen,
197 bool case_insensitive);
198 static Selectivity regex_selectivity(const char *patt, int pattlen,
199 bool case_insensitive,
200 int fixed_prefix_len);
201 static Datum string_to_datum(const char *str, Oid datatype);
202 static Const *string_to_const(const char *str, Oid datatype);
203 static Const *string_to_bytea_const(const char *str, size_t str_len);
204 static List *add_predicate_to_quals(IndexOptInfo *index, List *indexQuals);
208 * eqsel - Selectivity of "=" for any data types.
210 * Note: this routine is also used to estimate selectivity for some
211 * operators that are not "=" but have comparable selectivity behavior,
212 * such as "~=" (geometric approximate-match). Even for "=", we must
213 * keep in mind that the left and right datatypes may differ.
216 eqsel(PG_FUNCTION_ARGS)
218 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
219 Oid operator = PG_GETARG_OID(1);
220 List *args = (List *) PG_GETARG_POINTER(2);
221 int varRelid = PG_GETARG_INT32(3);
222 VariableStatData vardata;
228 * If expression is not variable = something or something = variable, then
229 * punt and return a default estimate.
231 if (!get_restriction_variable(root, args, varRelid,
232 &vardata, &other, &varonleft))
233 PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
236 * We can do a lot better if the something is a constant. (Note: the
237 * Const might result from estimation rather than being a simple constant
240 if (IsA(other, Const))
241 selec = var_eq_const(&vardata, operator,
242 ((Const *) other)->constvalue,
243 ((Const *) other)->constisnull,
246 selec = var_eq_non_const(&vardata, operator, other,
249 ReleaseVariableStats(vardata);
251 PG_RETURN_FLOAT8((float8) selec);
255 * var_eq_const --- eqsel for var = const case
257 * This is split out so that some other estimation functions can use it.
260 var_eq_const(VariableStatData *vardata, Oid operator,
261 Datum constval, bool constisnull,
268 * If the constant is NULL, assume operator is strict and return zero, ie,
269 * operator will never return TRUE.
275 * If we matched the var to a unique index or DISTINCT clause, assume
276 * there is exactly one match regardless of anything else. (This is
277 * slightly bogus, since the index or clause's equality operator might be
278 * different from ours, but it's much more likely to be right than
279 * ignoring the information.)
281 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
282 return 1.0 / vardata->rel->tuples;
284 if (HeapTupleIsValid(vardata->statsTuple))
286 Form_pg_statistic stats;
294 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
297 * Is the constant "=" to any of the column's most common values?
298 * (Although the given operator may not really be "=", we will assume
299 * that seeing whether it returns TRUE is an appropriate test. If you
300 * don't like this, maybe you shouldn't be using eqsel for your
303 if (get_attstatsslot(vardata->statsTuple,
304 vardata->atttype, vardata->atttypmod,
305 STATISTIC_KIND_MCV, InvalidOid,
308 &numbers, &nnumbers))
312 fmgr_info(get_opcode(operator), &eqproc);
314 for (i = 0; i < nvalues; i++)
316 /* be careful to apply operator right way 'round */
318 match = DatumGetBool(FunctionCall2Coll(&eqproc,
319 DEFAULT_COLLATION_OID,
323 match = DatumGetBool(FunctionCall2Coll(&eqproc,
324 DEFAULT_COLLATION_OID,
333 /* no most-common-value info available */
336 i = nvalues = nnumbers = 0;
342 * Constant is "=" to this common value. We know selectivity
343 * exactly (or as exactly as ANALYZE could calculate it, anyway).
350 * Comparison is against a constant that is neither NULL nor any
351 * of the common values. Its selectivity cannot be more than
354 double sumcommon = 0.0;
355 double otherdistinct;
357 for (i = 0; i < nnumbers; i++)
358 sumcommon += numbers[i];
359 selec = 1.0 - sumcommon - stats->stanullfrac;
360 CLAMP_PROBABILITY(selec);
363 * and in fact it's probably a good deal less. We approximate that
364 * all the not-common values share this remaining fraction
365 * equally, so we divide by the number of other distinct values.
367 otherdistinct = get_variable_numdistinct(vardata, &isdefault) - nnumbers;
368 if (otherdistinct > 1)
369 selec /= otherdistinct;
372 * Another cross-check: selectivity shouldn't be estimated as more
373 * than the least common "most common value".
375 if (nnumbers > 0 && selec > numbers[nnumbers - 1])
376 selec = numbers[nnumbers - 1];
379 free_attstatsslot(vardata->atttype, values, nvalues,
385 * No ANALYZE stats available, so make a guess using estimated number
386 * of distinct values and assuming they are equally common. (The guess
387 * is unlikely to be very good, but we do know a few special cases.)
389 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
392 /* result should be in range, but make sure... */
393 CLAMP_PROBABILITY(selec);
399 * var_eq_non_const --- eqsel for var = something-other-than-const case
402 var_eq_non_const(VariableStatData *vardata, Oid operator,
410 * If we matched the var to a unique index or DISTINCT clause, assume
411 * there is exactly one match regardless of anything else. (This is
412 * slightly bogus, since the index or clause's equality operator might be
413 * different from ours, but it's much more likely to be right than
414 * ignoring the information.)
416 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
417 return 1.0 / vardata->rel->tuples;
419 if (HeapTupleIsValid(vardata->statsTuple))
421 Form_pg_statistic stats;
426 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
429 * Search is for a value that we do not know a priori, but we will
430 * assume it is not NULL. Estimate the selectivity as non-null
431 * fraction divided by number of distinct values, so that we get a
432 * result averaged over all possible values whether common or
433 * uncommon. (Essentially, we are assuming that the not-yet-known
434 * comparison value is equally likely to be any of the possible
435 * values, regardless of their frequency in the table. Is that a good
438 selec = 1.0 - stats->stanullfrac;
439 ndistinct = get_variable_numdistinct(vardata, &isdefault);
444 * Cross-check: selectivity should never be estimated as more than the
445 * most common value's.
447 if (get_attstatsslot(vardata->statsTuple,
448 vardata->atttype, vardata->atttypmod,
449 STATISTIC_KIND_MCV, InvalidOid,
452 &numbers, &nnumbers))
454 if (nnumbers > 0 && selec > numbers[0])
456 free_attstatsslot(vardata->atttype, NULL, 0, numbers, nnumbers);
462 * No ANALYZE stats available, so make a guess using estimated number
463 * of distinct values and assuming they are equally common. (The guess
464 * is unlikely to be very good, but we do know a few special cases.)
466 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
469 /* result should be in range, but make sure... */
470 CLAMP_PROBABILITY(selec);
476 * neqsel - Selectivity of "!=" for any data types.
478 * This routine is also used for some operators that are not "!="
479 * but have comparable selectivity behavior. See above comments
483 neqsel(PG_FUNCTION_ARGS)
485 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
486 Oid operator = PG_GETARG_OID(1);
487 List *args = (List *) PG_GETARG_POINTER(2);
488 int varRelid = PG_GETARG_INT32(3);
493 * We want 1 - eqsel() where the equality operator is the one associated
494 * with this != operator, that is, its negator.
496 eqop = get_negator(operator);
499 result = DatumGetFloat8(DirectFunctionCall4(eqsel,
500 PointerGetDatum(root),
501 ObjectIdGetDatum(eqop),
502 PointerGetDatum(args),
503 Int32GetDatum(varRelid)));
507 /* Use default selectivity (should we raise an error instead?) */
508 result = DEFAULT_EQ_SEL;
510 result = 1.0 - result;
511 PG_RETURN_FLOAT8(result);
515 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
517 * This is the guts of both scalarltsel and scalargtsel. The caller has
518 * commuted the clause, if necessary, so that we can treat the variable as
519 * being on the left. The caller must also make sure that the other side
520 * of the clause is a non-null Const, and dissect same into a value and
523 * This routine works for any datatype (or pair of datatypes) known to
524 * convert_to_scalar(). If it is applied to some other datatype,
525 * it will return a default estimate.
528 scalarineqsel(PlannerInfo *root, Oid operator, bool isgt,
529 VariableStatData *vardata, Datum constval, Oid consttype)
531 Form_pg_statistic stats;
538 if (!HeapTupleIsValid(vardata->statsTuple))
540 /* no stats available, so default result */
541 return DEFAULT_INEQ_SEL;
543 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
545 fmgr_info(get_opcode(operator), &opproc);
548 * If we have most-common-values info, add up the fractions of the MCV
549 * entries that satisfy MCV OP CONST. These fractions contribute directly
550 * to the result selectivity. Also add up the total fraction represented
553 mcv_selec = mcv_selectivity(vardata, &opproc, constval, true,
557 * If there is a histogram, determine which bin the constant falls in, and
558 * compute the resulting contribution to selectivity.
560 hist_selec = ineq_histogram_selectivity(root, vardata, &opproc, isgt,
561 constval, consttype);
564 * Now merge the results from the MCV and histogram calculations,
565 * realizing that the histogram covers only the non-null values that are
568 selec = 1.0 - stats->stanullfrac - sumcommon;
570 if (hist_selec >= 0.0)
575 * If no histogram but there are values not accounted for by MCV,
576 * arbitrarily assume half of them will match.
583 /* result should be in range, but make sure... */
584 CLAMP_PROBABILITY(selec);
590 * mcv_selectivity - Examine the MCV list for selectivity estimates
592 * Determine the fraction of the variable's MCV population that satisfies
593 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
594 * compute the fraction of the total column population represented by the MCV
595 * list. This code will work for any boolean-returning predicate operator.
597 * The function result is the MCV selectivity, and the fraction of the
598 * total population is returned into *sumcommonp. Zeroes are returned
599 * if there is no MCV list.
602 mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
603 Datum constval, bool varonleft,
617 if (HeapTupleIsValid(vardata->statsTuple) &&
618 get_attstatsslot(vardata->statsTuple,
619 vardata->atttype, vardata->atttypmod,
620 STATISTIC_KIND_MCV, InvalidOid,
623 &numbers, &nnumbers))
625 for (i = 0; i < nvalues; i++)
628 DatumGetBool(FunctionCall2Coll(opproc,
629 DEFAULT_COLLATION_OID,
632 DatumGetBool(FunctionCall2Coll(opproc,
633 DEFAULT_COLLATION_OID,
636 mcv_selec += numbers[i];
637 sumcommon += numbers[i];
639 free_attstatsslot(vardata->atttype, values, nvalues,
643 *sumcommonp = sumcommon;
648 * histogram_selectivity - Examine the histogram for selectivity estimates
650 * Determine the fraction of the variable's histogram entries that satisfy
651 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
653 * This code will work for any boolean-returning predicate operator, whether
654 * or not it has anything to do with the histogram sort operator. We are
655 * essentially using the histogram just as a representative sample. However,
656 * small histograms are unlikely to be all that representative, so the caller
657 * should be prepared to fall back on some other estimation approach when the
658 * histogram is missing or very small. It may also be prudent to combine this
659 * approach with another one when the histogram is small.
661 * If the actual histogram size is not at least min_hist_size, we won't bother
662 * to do the calculation at all. Also, if the n_skip parameter is > 0, we
663 * ignore the first and last n_skip histogram elements, on the grounds that
664 * they are outliers and hence not very representative. Typical values for
665 * these parameters are 10 and 1.
667 * The function result is the selectivity, or -1 if there is no histogram
668 * or it's smaller than min_hist_size.
670 * The output parameter *hist_size receives the actual histogram size,
671 * or zero if no histogram. Callers may use this number to decide how
672 * much faith to put in the function result.
674 * Note that the result disregards both the most-common-values (if any) and
675 * null entries. The caller is expected to combine this result with
676 * statistics for those portions of the column population. It may also be
677 * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
680 histogram_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
681 Datum constval, bool varonleft,
682 int min_hist_size, int n_skip,
689 /* check sanity of parameters */
691 Assert(min_hist_size > 2 * n_skip);
693 if (HeapTupleIsValid(vardata->statsTuple) &&
694 get_attstatsslot(vardata->statsTuple,
695 vardata->atttype, vardata->atttypmod,
696 STATISTIC_KIND_HISTOGRAM, InvalidOid,
701 *hist_size = nvalues;
702 if (nvalues >= min_hist_size)
707 for (i = n_skip; i < nvalues - n_skip; i++)
710 DatumGetBool(FunctionCall2Coll(opproc,
711 DEFAULT_COLLATION_OID,
714 DatumGetBool(FunctionCall2Coll(opproc,
715 DEFAULT_COLLATION_OID,
720 result = ((double) nmatch) / ((double) (nvalues - 2 * n_skip));
724 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
736 * ineq_histogram_selectivity - Examine the histogram for scalarineqsel
738 * Determine the fraction of the variable's histogram population that
739 * satisfies the inequality condition, ie, VAR < CONST or VAR > CONST.
741 * Returns -1 if there is no histogram (valid results will always be >= 0).
743 * Note that the result disregards both the most-common-values (if any) and
744 * null entries. The caller is expected to combine this result with
745 * statistics for those portions of the column population.
748 ineq_histogram_selectivity(PlannerInfo *root,
749 VariableStatData *vardata,
750 FmgrInfo *opproc, bool isgt,
751 Datum constval, Oid consttype)
761 * Someday, ANALYZE might store more than one histogram per rel/att,
762 * corresponding to more than one possible sort ordering defined for the
763 * column type. However, to make that work we will need to figure out
764 * which staop to search for --- it's not necessarily the one we have at
765 * hand! (For example, we might have a '<=' operator rather than the '<'
766 * operator that will appear in staop.) For now, assume that whatever
767 * appears in pg_statistic is sorted the same way our operator sorts, or
768 * the reverse way if isgt is TRUE.
770 if (HeapTupleIsValid(vardata->statsTuple) &&
771 get_attstatsslot(vardata->statsTuple,
772 vardata->atttype, vardata->atttypmod,
773 STATISTIC_KIND_HISTOGRAM, InvalidOid,
781 * Use binary search to find proper location, ie, the first slot
782 * at which the comparison fails. (If the given operator isn't
783 * actually sort-compatible with the histogram, you'll get garbage
784 * results ... but probably not any more garbage-y than you would
785 * from the old linear search.)
787 * If the binary search accesses the first or last histogram
788 * entry, we try to replace that endpoint with the true column min
789 * or max as found by get_actual_variable_range(). This
790 * ameliorates misestimates when the min or max is moving as a
791 * result of changes since the last ANALYZE. Note that this could
792 * result in effectively including MCVs into the histogram that
793 * weren't there before, but we don't try to correct for that.
796 int lobound = 0; /* first possible slot to search */
797 int hibound = nvalues; /* last+1 slot to search */
798 bool have_end = false;
801 * If there are only two histogram entries, we'll want up-to-date
802 * values for both. (If there are more than two, we need at most
803 * one of them to be updated, so we deal with that within the
807 have_end = get_actual_variable_range(root,
813 while (lobound < hibound)
815 int probe = (lobound + hibound) / 2;
819 * If we find ourselves about to compare to the first or last
820 * histogram entry, first try to replace it with the actual
821 * current min or max (unless we already did so above).
823 if (probe == 0 && nvalues > 2)
824 have_end = get_actual_variable_range(root,
829 else if (probe == nvalues - 1 && nvalues > 2)
830 have_end = get_actual_variable_range(root,
836 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
837 DEFAULT_COLLATION_OID,
850 /* Constant is below lower histogram boundary. */
853 else if (lobound >= nvalues)
855 /* Constant is above upper histogram boundary. */
867 * We have values[i-1] <= constant <= values[i].
869 * Convert the constant and the two nearest bin boundary
870 * values to a uniform comparison scale, and do a linear
871 * interpolation within this bin.
873 if (convert_to_scalar(constval, consttype, &val,
874 values[i - 1], values[i],
880 /* cope if bin boundaries appear identical */
885 else if (val >= high)
889 binfrac = (val - low) / (high - low);
892 * Watch out for the possibility that we got a NaN or
893 * Infinity from the division. This can happen
894 * despite the previous checks, if for example "low"
897 if (isnan(binfrac) ||
898 binfrac < 0.0 || binfrac > 1.0)
905 * Ideally we'd produce an error here, on the grounds that
906 * the given operator shouldn't have scalarXXsel
907 * registered as its selectivity func unless we can deal
908 * with its operand types. But currently, all manner of
909 * stuff is invoking scalarXXsel, so give a default
910 * estimate until that can be fixed.
916 * Now, compute the overall selectivity across the values
917 * represented by the histogram. We have i-1 full bins and
918 * binfrac partial bin below the constant.
920 histfrac = (double) (i - 1) + binfrac;
921 histfrac /= (double) (nvalues - 1);
925 * Now histfrac = fraction of histogram entries below the
928 * Account for "<" vs ">"
930 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
933 * The histogram boundaries are only approximate to begin with,
934 * and may well be out of date anyway. Therefore, don't believe
935 * extremely small or large selectivity estimates --- unless we
936 * got actual current endpoint values from the table.
939 CLAMP_PROBABILITY(hist_selec);
942 if (hist_selec < 0.0001)
944 else if (hist_selec > 0.9999)
949 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
956 * scalarltsel - Selectivity of "<" (also "<=") for scalars.
959 scalarltsel(PG_FUNCTION_ARGS)
961 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
962 Oid operator = PG_GETARG_OID(1);
963 List *args = (List *) PG_GETARG_POINTER(2);
964 int varRelid = PG_GETARG_INT32(3);
965 VariableStatData vardata;
974 * If expression is not variable op something or something op variable,
975 * then punt and return a default estimate.
977 if (!get_restriction_variable(root, args, varRelid,
978 &vardata, &other, &varonleft))
979 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
982 * Can't do anything useful if the something is not a constant, either.
984 if (!IsA(other, Const))
986 ReleaseVariableStats(vardata);
987 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
991 * If the constant is NULL, assume operator is strict and return zero, ie,
992 * operator will never return TRUE.
994 if (((Const *) other)->constisnull)
996 ReleaseVariableStats(vardata);
997 PG_RETURN_FLOAT8(0.0);
999 constval = ((Const *) other)->constvalue;
1000 consttype = ((Const *) other)->consttype;
1003 * Force the var to be on the left to simplify logic in scalarineqsel.
1007 /* we have var < other */
1012 /* we have other < var, commute to make var > other */
1013 operator = get_commutator(operator);
1016 /* Use default selectivity (should we raise an error instead?) */
1017 ReleaseVariableStats(vardata);
1018 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1023 selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
1025 ReleaseVariableStats(vardata);
1027 PG_RETURN_FLOAT8((float8) selec);
1031 * scalargtsel - Selectivity of ">" (also ">=") for integers.
1034 scalargtsel(PG_FUNCTION_ARGS)
1036 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1037 Oid operator = PG_GETARG_OID(1);
1038 List *args = (List *) PG_GETARG_POINTER(2);
1039 int varRelid = PG_GETARG_INT32(3);
1040 VariableStatData vardata;
1049 * If expression is not variable op something or something op variable,
1050 * then punt and return a default estimate.
1052 if (!get_restriction_variable(root, args, varRelid,
1053 &vardata, &other, &varonleft))
1054 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1057 * Can't do anything useful if the something is not a constant, either.
1059 if (!IsA(other, Const))
1061 ReleaseVariableStats(vardata);
1062 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1066 * If the constant is NULL, assume operator is strict and return zero, ie,
1067 * operator will never return TRUE.
1069 if (((Const *) other)->constisnull)
1071 ReleaseVariableStats(vardata);
1072 PG_RETURN_FLOAT8(0.0);
1074 constval = ((Const *) other)->constvalue;
1075 consttype = ((Const *) other)->consttype;
1078 * Force the var to be on the left to simplify logic in scalarineqsel.
1082 /* we have var > other */
1087 /* we have other > var, commute to make var < other */
1088 operator = get_commutator(operator);
1091 /* Use default selectivity (should we raise an error instead?) */
1092 ReleaseVariableStats(vardata);
1093 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1098 selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
1100 ReleaseVariableStats(vardata);
1102 PG_RETURN_FLOAT8((float8) selec);
1106 * patternsel - Generic code for pattern-match selectivity.
1109 patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
1111 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1112 Oid operator = PG_GETARG_OID(1);
1113 List *args = (List *) PG_GETARG_POINTER(2);
1114 int varRelid = PG_GETARG_INT32(3);
1115 Oid collation = PG_GET_COLLATION();
1116 VariableStatData vardata;
1123 Pattern_Prefix_Status pstatus;
1125 Const *prefix = NULL;
1126 Selectivity rest_selec = 0;
1130 * If this is for a NOT LIKE or similar operator, get the corresponding
1131 * positive-match operator and work with that. Set result to the correct
1132 * default estimate, too.
1136 operator = get_negator(operator);
1137 if (!OidIsValid(operator))
1138 elog(ERROR, "patternsel called for operator without a negator");
1139 result = 1.0 - DEFAULT_MATCH_SEL;
1143 result = DEFAULT_MATCH_SEL;
1147 * If expression is not variable op constant, then punt and return a
1150 if (!get_restriction_variable(root, args, varRelid,
1151 &vardata, &other, &varonleft))
1153 if (!varonleft || !IsA(other, Const))
1155 ReleaseVariableStats(vardata);
1160 * If the constant is NULL, assume operator is strict and return zero, ie,
1161 * operator will never return TRUE. (It's zero even for a negator op.)
1163 if (((Const *) other)->constisnull)
1165 ReleaseVariableStats(vardata);
1168 constval = ((Const *) other)->constvalue;
1169 consttype = ((Const *) other)->consttype;
1172 * The right-hand const is type text or bytea for all supported operators.
1173 * We do not expect to see binary-compatible types here, since
1174 * const-folding should have relabeled the const to exactly match the
1175 * operator's declared type.
1177 if (consttype != TEXTOID && consttype != BYTEAOID)
1179 ReleaseVariableStats(vardata);
1184 * Similarly, the exposed type of the left-hand side should be one of
1185 * those we know. (Do not look at vardata.atttype, which might be
1186 * something binary-compatible but different.) We can use it to choose
1187 * the index opfamily from which we must draw the comparison operators.
1189 * NOTE: It would be more correct to use the PATTERN opfamilies than the
1190 * simple ones, but at the moment ANALYZE will not generate statistics for
1191 * the PATTERN operators. But our results are so approximate anyway that
1192 * it probably hardly matters.
1194 vartype = vardata.vartype;
1199 opfamily = TEXT_BTREE_FAM_OID;
1202 opfamily = BPCHAR_BTREE_FAM_OID;
1205 opfamily = NAME_BTREE_FAM_OID;
1208 opfamily = BYTEA_BTREE_FAM_OID;
1211 ReleaseVariableStats(vardata);
1216 * Pull out any fixed prefix implied by the pattern, and estimate the
1217 * fractional selectivity of the remainder of the pattern. Unlike many of
1218 * the other functions in this file, we use the pattern operator's actual
1219 * collation for this step. This is not because we expect the collation
1220 * to make a big difference in the selectivity estimate (it seldom would),
1221 * but because we want to be sure we cache compiled regexps under the
1222 * right cache key, so that they can be re-used at runtime.
1224 patt = (Const *) other;
1225 pstatus = pattern_fixed_prefix(patt, ptype, collation,
1226 &prefix, &rest_selec);
1229 * If necessary, coerce the prefix constant to the right type.
1231 if (prefix && prefix->consttype != vartype)
1235 switch (prefix->consttype)
1238 prefixstr = TextDatumGetCString(prefix->constvalue);
1241 prefixstr = DatumGetCString(DirectFunctionCall1(byteaout,
1242 prefix->constvalue));
1245 elog(ERROR, "unrecognized consttype: %u",
1247 ReleaseVariableStats(vardata);
1250 prefix = string_to_const(prefixstr, vartype);
1254 if (pstatus == Pattern_Prefix_Exact)
1257 * Pattern specifies an exact match, so pretend operator is '='
1259 Oid eqopr = get_opfamily_member(opfamily, vartype, vartype,
1260 BTEqualStrategyNumber);
1262 if (eqopr == InvalidOid)
1263 elog(ERROR, "no = operator for opfamily %u", opfamily);
1264 result = var_eq_const(&vardata, eqopr, prefix->constvalue,
1270 * Not exact-match pattern. If we have a sufficiently large
1271 * histogram, estimate selectivity for the histogram part of the
1272 * population by counting matches in the histogram. If not, estimate
1273 * selectivity of the fixed prefix and remainder of pattern
1274 * separately, then combine the two to get an estimate of the
1275 * selectivity for the part of the column population represented by
1276 * the histogram. (For small histograms, we combine these
1279 * We then add up data for any most-common-values values; these are
1280 * not in the histogram population, and we can get exact answers for
1281 * them by applying the pattern operator, so there's no reason to
1282 * approximate. (If the MCVs cover a significant part of the total
1283 * population, this gives us a big leg up in accuracy.)
1292 /* Try to use the histogram entries to get selectivity */
1293 fmgr_info(get_opcode(operator), &opproc);
1295 selec = histogram_selectivity(&vardata, &opproc, constval, true,
1298 /* If not at least 100 entries, use the heuristic method */
1299 if (hist_size < 100)
1301 Selectivity heursel;
1302 Selectivity prefixsel;
1304 if (pstatus == Pattern_Prefix_Partial)
1305 prefixsel = prefix_selectivity(root, &vardata, vartype,
1309 heursel = prefixsel * rest_selec;
1311 if (selec < 0) /* fewer than 10 histogram entries? */
1316 * For histogram sizes from 10 to 100, we combine the
1317 * histogram and heuristic selectivities, putting increasingly
1318 * more trust in the histogram for larger sizes.
1320 double hist_weight = hist_size / 100.0;
1322 selec = selec * hist_weight + heursel * (1.0 - hist_weight);
1326 /* In any case, don't believe extremely small or large estimates. */
1329 else if (selec > 0.9999)
1333 * If we have most-common-values info, add up the fractions of the MCV
1334 * entries that satisfy MCV OP PATTERN. These fractions contribute
1335 * directly to the result selectivity. Also add up the total fraction
1336 * represented by MCV entries.
1338 mcv_selec = mcv_selectivity(&vardata, &opproc, constval, true,
1341 if (HeapTupleIsValid(vardata.statsTuple))
1342 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
1347 * Now merge the results from the MCV and histogram calculations,
1348 * realizing that the histogram covers only the non-null values that
1349 * are not listed in MCV.
1351 selec *= 1.0 - nullfrac - sumcommon;
1354 /* result should be in range, but make sure... */
1355 CLAMP_PROBABILITY(selec);
1361 pfree(DatumGetPointer(prefix->constvalue));
1365 ReleaseVariableStats(vardata);
1367 return negate ? (1.0 - result) : result;
1371 * regexeqsel - Selectivity of regular-expression pattern match.
1374 regexeqsel(PG_FUNCTION_ARGS)
1376 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, false));
1380 * icregexeqsel - Selectivity of case-insensitive regex match.
1383 icregexeqsel(PG_FUNCTION_ARGS)
1385 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, false));
1389 * likesel - Selectivity of LIKE pattern match.
1392 likesel(PG_FUNCTION_ARGS)
1394 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, false));
1398 * iclikesel - Selectivity of ILIKE pattern match.
1401 iclikesel(PG_FUNCTION_ARGS)
1403 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, false));
1407 * regexnesel - Selectivity of regular-expression pattern non-match.
1410 regexnesel(PG_FUNCTION_ARGS)
1412 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, true));
1416 * icregexnesel - Selectivity of case-insensitive regex non-match.
1419 icregexnesel(PG_FUNCTION_ARGS)
1421 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, true));
1425 * nlikesel - Selectivity of LIKE pattern non-match.
1428 nlikesel(PG_FUNCTION_ARGS)
1430 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, true));
1434 * icnlikesel - Selectivity of ILIKE pattern non-match.
1437 icnlikesel(PG_FUNCTION_ARGS)
1439 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, true));
1443 * booltestsel - Selectivity of BooleanTest Node.
1446 booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
1447 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1449 VariableStatData vardata;
1452 examine_variable(root, arg, varRelid, &vardata);
1454 if (HeapTupleIsValid(vardata.statsTuple))
1456 Form_pg_statistic stats;
1463 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1464 freq_null = stats->stanullfrac;
1466 if (get_attstatsslot(vardata.statsTuple,
1467 vardata.atttype, vardata.atttypmod,
1468 STATISTIC_KIND_MCV, InvalidOid,
1471 &numbers, &nnumbers)
1478 * Get first MCV frequency and derive frequency for true.
1480 if (DatumGetBool(values[0]))
1481 freq_true = numbers[0];
1483 freq_true = 1.0 - numbers[0] - freq_null;
1486 * Next derive frequency for false. Then use these as appropriate
1487 * to derive frequency for each case.
1489 freq_false = 1.0 - freq_true - freq_null;
1491 switch (booltesttype)
1494 /* select only NULL values */
1497 case IS_NOT_UNKNOWN:
1498 /* select non-NULL values */
1499 selec = 1.0 - freq_null;
1502 /* select only TRUE values */
1506 /* select non-TRUE values */
1507 selec = 1.0 - freq_true;
1510 /* select only FALSE values */
1514 /* select non-FALSE values */
1515 selec = 1.0 - freq_false;
1518 elog(ERROR, "unrecognized booltesttype: %d",
1519 (int) booltesttype);
1520 selec = 0.0; /* Keep compiler quiet */
1524 free_attstatsslot(vardata.atttype, values, nvalues,
1530 * No most-common-value info available. Still have null fraction
1531 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1532 * for null fraction and assume a 50-50 split of TRUE and FALSE.
1534 switch (booltesttype)
1537 /* select only NULL values */
1540 case IS_NOT_UNKNOWN:
1541 /* select non-NULL values */
1542 selec = 1.0 - freq_null;
1546 /* Assume we select half of the non-NULL values */
1547 selec = (1.0 - freq_null) / 2.0;
1551 /* Assume we select NULLs plus half of the non-NULLs */
1552 /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1553 selec = (freq_null + 1.0) / 2.0;
1556 elog(ERROR, "unrecognized booltesttype: %d",
1557 (int) booltesttype);
1558 selec = 0.0; /* Keep compiler quiet */
1566 * If we can't get variable statistics for the argument, perhaps
1567 * clause_selectivity can do something with it. We ignore the
1568 * possibility of a NULL value when using clause_selectivity, and just
1569 * assume the value is either TRUE or FALSE.
1571 switch (booltesttype)
1574 selec = DEFAULT_UNK_SEL;
1576 case IS_NOT_UNKNOWN:
1577 selec = DEFAULT_NOT_UNK_SEL;
1581 selec = (double) clause_selectivity(root, arg,
1587 selec = 1.0 - (double) clause_selectivity(root, arg,
1592 elog(ERROR, "unrecognized booltesttype: %d",
1593 (int) booltesttype);
1594 selec = 0.0; /* Keep compiler quiet */
1599 ReleaseVariableStats(vardata);
1601 /* result should be in range, but make sure... */
1602 CLAMP_PROBABILITY(selec);
1604 return (Selectivity) selec;
1608 * nulltestsel - Selectivity of NullTest Node.
1611 nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1612 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1614 VariableStatData vardata;
1617 examine_variable(root, arg, varRelid, &vardata);
1619 if (HeapTupleIsValid(vardata.statsTuple))
1621 Form_pg_statistic stats;
1624 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1625 freq_null = stats->stanullfrac;
1627 switch (nulltesttype)
1632 * Use freq_null directly.
1639 * Select not unknown (not null) values. Calculate from
1642 selec = 1.0 - freq_null;
1645 elog(ERROR, "unrecognized nulltesttype: %d",
1646 (int) nulltesttype);
1647 return (Selectivity) 0; /* keep compiler quiet */
1653 * No ANALYZE stats available, so make a guess
1655 switch (nulltesttype)
1658 selec = DEFAULT_UNK_SEL;
1661 selec = DEFAULT_NOT_UNK_SEL;
1664 elog(ERROR, "unrecognized nulltesttype: %d",
1665 (int) nulltesttype);
1666 return (Selectivity) 0; /* keep compiler quiet */
1670 ReleaseVariableStats(vardata);
1672 /* result should be in range, but make sure... */
1673 CLAMP_PROBABILITY(selec);
1675 return (Selectivity) selec;
1679 * strip_array_coercion - strip binary-compatible relabeling from an array expr
1681 * For array values, the parser normally generates ArrayCoerceExpr conversions,
1682 * but it seems possible that RelabelType might show up. Also, the planner
1683 * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1684 * so we need to be ready to deal with more than one level.
1687 strip_array_coercion(Node *node)
1691 if (node && IsA(node, ArrayCoerceExpr) &&
1692 ((ArrayCoerceExpr *) node)->elemfuncid == InvalidOid)
1694 node = (Node *) ((ArrayCoerceExpr *) node)->arg;
1696 else if (node && IsA(node, RelabelType))
1698 /* We don't really expect this case, but may as well cope */
1699 node = (Node *) ((RelabelType *) node)->arg;
1708 * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1711 scalararraysel(PlannerInfo *root,
1712 ScalarArrayOpExpr *clause,
1713 bool is_join_clause,
1716 SpecialJoinInfo *sjinfo)
1718 Oid operator = clause->opno;
1719 bool useOr = clause->useOr;
1720 bool isEquality = false;
1721 bool isInequality = false;
1724 Oid nominal_element_type;
1725 Oid nominal_element_collation;
1726 TypeCacheEntry *typentry;
1727 RegProcedure oprsel;
1728 FmgrInfo oprselproc;
1730 Selectivity s1disjoint;
1732 /* First, deconstruct the expression */
1733 Assert(list_length(clause->args) == 2);
1734 leftop = (Node *) linitial(clause->args);
1735 rightop = (Node *) lsecond(clause->args);
1737 /* aggressively reduce both sides to constants */
1738 leftop = estimate_expression_value(root, leftop);
1739 rightop = estimate_expression_value(root, rightop);
1741 /* get nominal (after relabeling) element type of rightop */
1742 nominal_element_type = get_base_element_type(exprType(rightop));
1743 if (!OidIsValid(nominal_element_type))
1744 return (Selectivity) 0.5; /* probably shouldn't happen */
1745 /* get nominal collation, too, for generating constants */
1746 nominal_element_collation = exprCollation(rightop);
1748 /* look through any binary-compatible relabeling of rightop */
1749 rightop = strip_array_coercion(rightop);
1752 * Detect whether the operator is the default equality or inequality
1753 * operator of the array element type.
1755 typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1756 if (OidIsValid(typentry->eq_opr))
1758 if (operator == typentry->eq_opr)
1760 else if (get_negator(operator) == typentry->eq_opr)
1761 isInequality = true;
1765 * If it is equality or inequality, we might be able to estimate this as a
1766 * form of array containment; for instance "const = ANY(column)" can be
1767 * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1768 * that, and returns the selectivity estimate if successful, or -1 if not.
1770 if ((isEquality || isInequality) && !is_join_clause)
1772 s1 = scalararraysel_containment(root, leftop, rightop,
1773 nominal_element_type,
1774 isEquality, useOr, varRelid);
1780 * Look up the underlying operator's selectivity estimator. Punt if it
1784 oprsel = get_oprjoin(operator);
1786 oprsel = get_oprrest(operator);
1788 return (Selectivity) 0.5;
1789 fmgr_info(oprsel, &oprselproc);
1792 * In the array-containment check above, we must only believe that an
1793 * operator is equality or inequality if it is the default btree equality
1794 * operator (or its negator) for the element type, since those are the
1795 * operators that array containment will use. But in what follows, we can
1796 * be a little laxer, and also believe that any operators using eqsel() or
1797 * neqsel() as selectivity estimator act like equality or inequality.
1799 if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1801 else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1802 isInequality = true;
1805 * We consider three cases:
1807 * 1. rightop is an Array constant: deconstruct the array, apply the
1808 * operator's selectivity function for each array element, and merge the
1809 * results in the same way that clausesel.c does for AND/OR combinations.
1811 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1812 * function for each element of the ARRAY[] construct, and merge.
1814 * 3. otherwise, make a guess ...
1816 if (rightop && IsA(rightop, Const))
1818 Datum arraydatum = ((Const *) rightop)->constvalue;
1819 bool arrayisnull = ((Const *) rightop)->constisnull;
1820 ArrayType *arrayval;
1829 if (arrayisnull) /* qual can't succeed if null array */
1830 return (Selectivity) 0.0;
1831 arrayval = DatumGetArrayTypeP(arraydatum);
1832 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1833 &elmlen, &elmbyval, &elmalign);
1834 deconstruct_array(arrayval,
1835 ARR_ELEMTYPE(arrayval),
1836 elmlen, elmbyval, elmalign,
1837 &elem_values, &elem_nulls, &num_elems);
1840 * For generic operators, we assume the probability of success is
1841 * independent for each array element. But for "= ANY" or "<> ALL",
1842 * if the array elements are distinct (which'd typically be the case)
1843 * then the probabilities are disjoint, and we should just sum them.
1845 * If we were being really tense we would try to confirm that the
1846 * elements are all distinct, but that would be expensive and it
1847 * doesn't seem to be worth the cycles; it would amount to penalizing
1848 * well-written queries in favor of poorly-written ones. However, we
1849 * do protect ourselves a little bit by checking whether the
1850 * disjointness assumption leads to an impossible (out of range)
1851 * probability; if so, we fall back to the normal calculation.
1853 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1855 for (i = 0; i < num_elems; i++)
1860 args = list_make2(leftop,
1861 makeConst(nominal_element_type,
1863 nominal_element_collation,
1869 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1870 clause->inputcollid,
1871 PointerGetDatum(root),
1872 ObjectIdGetDatum(operator),
1873 PointerGetDatum(args),
1874 Int16GetDatum(jointype),
1875 PointerGetDatum(sjinfo)));
1877 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1878 clause->inputcollid,
1879 PointerGetDatum(root),
1880 ObjectIdGetDatum(operator),
1881 PointerGetDatum(args),
1882 Int32GetDatum(varRelid)));
1886 s1 = s1 + s2 - s1 * s2;
1894 s1disjoint += s2 - 1.0;
1898 /* accept disjoint-probability estimate if in range */
1899 if ((useOr ? isEquality : isInequality) &&
1900 s1disjoint >= 0.0 && s1disjoint <= 1.0)
1903 else if (rightop && IsA(rightop, ArrayExpr) &&
1904 !((ArrayExpr *) rightop)->multidims)
1906 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1911 get_typlenbyval(arrayexpr->element_typeid,
1912 &elmlen, &elmbyval);
1915 * We use the assumption of disjoint probabilities here too, although
1916 * the odds of equal array elements are rather higher if the elements
1917 * are not all constants (which they won't be, else constant folding
1918 * would have reduced the ArrayExpr to a Const). In this path it's
1919 * critical to have the sanity check on the s1disjoint estimate.
1921 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1923 foreach(l, arrayexpr->elements)
1925 Node *elem = (Node *) lfirst(l);
1930 * Theoretically, if elem isn't of nominal_element_type we should
1931 * insert a RelabelType, but it seems unlikely that any operator
1932 * estimation function would really care ...
1934 args = list_make2(leftop, elem);
1936 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1937 clause->inputcollid,
1938 PointerGetDatum(root),
1939 ObjectIdGetDatum(operator),
1940 PointerGetDatum(args),
1941 Int16GetDatum(jointype),
1942 PointerGetDatum(sjinfo)));
1944 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1945 clause->inputcollid,
1946 PointerGetDatum(root),
1947 ObjectIdGetDatum(operator),
1948 PointerGetDatum(args),
1949 Int32GetDatum(varRelid)));
1953 s1 = s1 + s2 - s1 * s2;
1961 s1disjoint += s2 - 1.0;
1965 /* accept disjoint-probability estimate if in range */
1966 if ((useOr ? isEquality : isInequality) &&
1967 s1disjoint >= 0.0 && s1disjoint <= 1.0)
1972 CaseTestExpr *dummyexpr;
1978 * We need a dummy rightop to pass to the operator selectivity
1979 * routine. It can be pretty much anything that doesn't look like a
1980 * constant; CaseTestExpr is a convenient choice.
1982 dummyexpr = makeNode(CaseTestExpr);
1983 dummyexpr->typeId = nominal_element_type;
1984 dummyexpr->typeMod = -1;
1985 dummyexpr->collation = clause->inputcollid;
1986 args = list_make2(leftop, dummyexpr);
1988 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1989 clause->inputcollid,
1990 PointerGetDatum(root),
1991 ObjectIdGetDatum(operator),
1992 PointerGetDatum(args),
1993 Int16GetDatum(jointype),
1994 PointerGetDatum(sjinfo)));
1996 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1997 clause->inputcollid,
1998 PointerGetDatum(root),
1999 ObjectIdGetDatum(operator),
2000 PointerGetDatum(args),
2001 Int32GetDatum(varRelid)));
2002 s1 = useOr ? 0.0 : 1.0;
2005 * Arbitrarily assume 10 elements in the eventual array value (see
2006 * also estimate_array_length). We don't risk an assumption of
2007 * disjoint probabilities here.
2009 for (i = 0; i < 10; i++)
2012 s1 = s1 + s2 - s1 * s2;
2018 /* result should be in range, but make sure... */
2019 CLAMP_PROBABILITY(s1);
2025 * Estimate number of elements in the array yielded by an expression.
2027 * It's important that this agree with scalararraysel.
2030 estimate_array_length(Node *arrayexpr)
2032 /* look through any binary-compatible relabeling of arrayexpr */
2033 arrayexpr = strip_array_coercion(arrayexpr);
2035 if (arrayexpr && IsA(arrayexpr, Const))
2037 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2038 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2039 ArrayType *arrayval;
2043 arrayval = DatumGetArrayTypeP(arraydatum);
2044 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2046 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2047 !((ArrayExpr *) arrayexpr)->multidims)
2049 return list_length(((ArrayExpr *) arrayexpr)->elements);
2053 /* default guess --- see also scalararraysel */
2059 * rowcomparesel - Selectivity of RowCompareExpr Node.
2061 * We estimate RowCompare selectivity by considering just the first (high
2062 * order) columns, which makes it equivalent to an ordinary OpExpr. While
2063 * this estimate could be refined by considering additional columns, it
2064 * seems unlikely that we could do a lot better without multi-column
2068 rowcomparesel(PlannerInfo *root,
2069 RowCompareExpr *clause,
2070 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
2073 Oid opno = linitial_oid(clause->opnos);
2074 Oid inputcollid = linitial_oid(clause->inputcollids);
2076 bool is_join_clause;
2078 /* Build equivalent arg list for single operator */
2079 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2082 * Decide if it's a join clause. This should match clausesel.c's
2083 * treat_as_join_clause(), except that we intentionally consider only the
2084 * leading columns and not the rest of the clause.
2089 * Caller is forcing restriction mode (eg, because we are examining an
2090 * inner indexscan qual).
2092 is_join_clause = false;
2094 else if (sjinfo == NULL)
2097 * It must be a restriction clause, since it's being evaluated at a
2100 is_join_clause = false;
2105 * Otherwise, it's a join if there's more than one relation used.
2107 is_join_clause = (NumRelids((Node *) opargs) > 1);
2112 /* Estimate selectivity for a join clause. */
2113 s1 = join_selectivity(root, opno,
2121 /* Estimate selectivity for a restriction clause. */
2122 s1 = restriction_selectivity(root, opno,
2132 * eqjoinsel - Join selectivity of "="
2135 eqjoinsel(PG_FUNCTION_ARGS)
2137 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2138 Oid operator = PG_GETARG_OID(1);
2139 List *args = (List *) PG_GETARG_POINTER(2);
2142 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2144 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2146 VariableStatData vardata1;
2147 VariableStatData vardata2;
2148 bool join_is_reversed;
2149 RelOptInfo *inner_rel;
2151 get_join_variables(root, args, sjinfo,
2152 &vardata1, &vardata2, &join_is_reversed);
2154 switch (sjinfo->jointype)
2159 selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2165 * Look up the join's inner relation. min_righthand is sufficient
2166 * information because neither SEMI nor ANTI joins permit any
2167 * reassociation into or out of their RHS, so the righthand will
2168 * always be exactly that set of rels.
2170 inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2172 if (!join_is_reversed)
2173 selec = eqjoinsel_semi(operator, &vardata1, &vardata2,
2176 selec = eqjoinsel_semi(get_commutator(operator),
2177 &vardata2, &vardata1,
2181 /* other values not expected here */
2182 elog(ERROR, "unrecognized join type: %d",
2183 (int) sjinfo->jointype);
2184 selec = 0; /* keep compiler quiet */
2188 ReleaseVariableStats(vardata1);
2189 ReleaseVariableStats(vardata2);
2191 CLAMP_PROBABILITY(selec);
2193 PG_RETURN_FLOAT8((float8) selec);
2197 * eqjoinsel_inner --- eqjoinsel for normal inner join
2199 * We also use this for LEFT/FULL outer joins; it's not presently clear
2200 * that it's worth trying to distinguish them here.
2203 eqjoinsel_inner(Oid operator,
2204 VariableStatData *vardata1, VariableStatData *vardata2)
2211 Form_pg_statistic stats1 = NULL;
2212 Form_pg_statistic stats2 = NULL;
2213 bool have_mcvs1 = false;
2214 Datum *values1 = NULL;
2216 float4 *numbers1 = NULL;
2218 bool have_mcvs2 = false;
2219 Datum *values2 = NULL;
2221 float4 *numbers2 = NULL;
2224 nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2225 nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2227 if (HeapTupleIsValid(vardata1->statsTuple))
2229 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2230 have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2232 vardata1->atttypmod,
2236 &values1, &nvalues1,
2237 &numbers1, &nnumbers1);
2240 if (HeapTupleIsValid(vardata2->statsTuple))
2242 stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2243 have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2245 vardata2->atttypmod,
2249 &values2, &nvalues2,
2250 &numbers2, &nnumbers2);
2253 if (have_mcvs1 && have_mcvs2)
2256 * We have most-common-value lists for both relations. Run through
2257 * the lists to see which MCVs actually join to each other with the
2258 * given operator. This allows us to determine the exact join
2259 * selectivity for the portion of the relations represented by the MCV
2260 * lists. We still have to estimate for the remaining population, but
2261 * in a skewed distribution this gives us a big leg up in accuracy.
2262 * For motivation see the analysis in Y. Ioannidis and S.
2263 * Christodoulakis, "On the propagation of errors in the size of join
2264 * results", Technical Report 1018, Computer Science Dept., University
2265 * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2270 double nullfrac1 = stats1->stanullfrac;
2271 double nullfrac2 = stats2->stanullfrac;
2272 double matchprodfreq,
2284 fmgr_info(get_opcode(operator), &eqproc);
2285 hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2286 hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
2289 * Note we assume that each MCV will match at most one member of the
2290 * other MCV list. If the operator isn't really equality, there could
2291 * be multiple matches --- but we don't look for them, both for speed
2292 * and because the math wouldn't add up...
2294 matchprodfreq = 0.0;
2296 for (i = 0; i < nvalues1; i++)
2300 for (j = 0; j < nvalues2; j++)
2304 if (DatumGetBool(FunctionCall2Coll(&eqproc,
2305 DEFAULT_COLLATION_OID,
2309 hasmatch1[i] = hasmatch2[j] = true;
2310 matchprodfreq += numbers1[i] * numbers2[j];
2316 CLAMP_PROBABILITY(matchprodfreq);
2317 /* Sum up frequencies of matched and unmatched MCVs */
2318 matchfreq1 = unmatchfreq1 = 0.0;
2319 for (i = 0; i < nvalues1; i++)
2322 matchfreq1 += numbers1[i];
2324 unmatchfreq1 += numbers1[i];
2326 CLAMP_PROBABILITY(matchfreq1);
2327 CLAMP_PROBABILITY(unmatchfreq1);
2328 matchfreq2 = unmatchfreq2 = 0.0;
2329 for (i = 0; i < nvalues2; i++)
2332 matchfreq2 += numbers2[i];
2334 unmatchfreq2 += numbers2[i];
2336 CLAMP_PROBABILITY(matchfreq2);
2337 CLAMP_PROBABILITY(unmatchfreq2);
2342 * Compute total frequency of non-null values that are not in the MCV
2345 otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2346 otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2347 CLAMP_PROBABILITY(otherfreq1);
2348 CLAMP_PROBABILITY(otherfreq2);
2351 * We can estimate the total selectivity from the point of view of
2352 * relation 1 as: the known selectivity for matched MCVs, plus
2353 * unmatched MCVs that are assumed to match against random members of
2354 * relation 2's non-MCV population, plus non-MCV values that are
2355 * assumed to match against random members of relation 2's unmatched
2356 * MCVs plus non-MCV values.
2358 totalsel1 = matchprodfreq;
2360 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
2362 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2364 /* Same estimate from the point of view of relation 2. */
2365 totalsel2 = matchprodfreq;
2367 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
2369 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2373 * Use the smaller of the two estimates. This can be justified in
2374 * essentially the same terms as given below for the no-stats case: to
2375 * a first approximation, we are estimating from the point of view of
2376 * the relation with smaller nd.
2378 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2383 * We do not have MCV lists for both sides. Estimate the join
2384 * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2385 * is plausible if we assume that the join operator is strict and the
2386 * non-null values are about equally distributed: a given non-null
2387 * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2388 * of rel2, so total join rows are at most
2389 * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2390 * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2391 * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2392 * with MIN() is an upper bound. Using the MIN() means we estimate
2393 * from the point of view of the relation with smaller nd (since the
2394 * larger nd is determining the MIN). It is reasonable to assume that
2395 * most tuples in this rel will have join partners, so the bound is
2396 * probably reasonably tight and should be taken as-is.
2398 * XXX Can we be smarter if we have an MCV list for just one side? It
2399 * seems that if we assume equal distribution for the other side, we
2400 * end up with the same answer anyway.
2402 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2403 double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2405 selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2413 free_attstatsslot(vardata1->atttype, values1, nvalues1,
2414 numbers1, nnumbers1);
2416 free_attstatsslot(vardata2->atttype, values2, nvalues2,
2417 numbers2, nnumbers2);
2423 * eqjoinsel_semi --- eqjoinsel for semi join
2425 * (Also used for anti join, which we are supposed to estimate the same way.)
2426 * Caller has ensured that vardata1 is the LHS variable.
2429 eqjoinsel_semi(Oid operator,
2430 VariableStatData *vardata1, VariableStatData *vardata2,
2431 RelOptInfo *inner_rel)
2438 Form_pg_statistic stats1 = NULL;
2439 bool have_mcvs1 = false;
2440 Datum *values1 = NULL;
2442 float4 *numbers1 = NULL;
2444 bool have_mcvs2 = false;
2445 Datum *values2 = NULL;
2447 float4 *numbers2 = NULL;
2450 nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2451 nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2454 * We clamp nd2 to be not more than what we estimate the inner relation's
2455 * size to be. This is intuitively somewhat reasonable since obviously
2456 * there can't be more than that many distinct values coming from the
2457 * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2458 * likewise) is that this is the only pathway by which restriction clauses
2459 * applied to the inner rel will affect the join result size estimate,
2460 * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2461 * only the outer rel's size. If we clamped nd1 we'd be double-counting
2462 * the selectivity of outer-rel restrictions.
2464 * We can apply this clamping both with respect to the base relation from
2465 * which the join variable comes (if there is just one), and to the
2466 * immediate inner input relation of the current join.
2469 nd2 = Min(nd2, vardata2->rel->rows);
2470 nd2 = Min(nd2, inner_rel->rows);
2472 if (HeapTupleIsValid(vardata1->statsTuple))
2474 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2475 have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2477 vardata1->atttypmod,
2481 &values1, &nvalues1,
2482 &numbers1, &nnumbers1);
2485 if (HeapTupleIsValid(vardata2->statsTuple))
2487 have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2489 vardata2->atttypmod,
2493 &values2, &nvalues2,
2494 &numbers2, &nnumbers2);
2497 if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
2500 * We have most-common-value lists for both relations. Run through
2501 * the lists to see which MCVs actually join to each other with the
2502 * given operator. This allows us to determine the exact join
2503 * selectivity for the portion of the relations represented by the MCV
2504 * lists. We still have to estimate for the remaining population, but
2505 * in a skewed distribution this gives us a big leg up in accuracy.
2510 double nullfrac1 = stats1->stanullfrac;
2519 * The clamping above could have resulted in nd2 being less than
2520 * nvalues2; in which case, we assume that precisely the nd2 most
2521 * common values in the relation will appear in the join input, and so
2522 * compare to only the first nd2 members of the MCV list. Of course
2523 * this is frequently wrong, but it's the best bet we can make.
2525 clamped_nvalues2 = Min(nvalues2, nd2);
2527 fmgr_info(get_opcode(operator), &eqproc);
2528 hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2529 hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2532 * Note we assume that each MCV will match at most one member of the
2533 * other MCV list. If the operator isn't really equality, there could
2534 * be multiple matches --- but we don't look for them, both for speed
2535 * and because the math wouldn't add up...
2538 for (i = 0; i < nvalues1; i++)
2542 for (j = 0; j < clamped_nvalues2; j++)
2546 if (DatumGetBool(FunctionCall2Coll(&eqproc,
2547 DEFAULT_COLLATION_OID,
2551 hasmatch1[i] = hasmatch2[j] = true;
2557 /* Sum up frequencies of matched MCVs */
2559 for (i = 0; i < nvalues1; i++)
2562 matchfreq1 += numbers1[i];
2564 CLAMP_PROBABILITY(matchfreq1);
2569 * Now we need to estimate the fraction of relation 1 that has at
2570 * least one join partner. We know for certain that the matched MCVs
2571 * do, so that gives us a lower bound, but we're really in the dark
2572 * about everything else. Our crude approach is: if nd1 <= nd2 then
2573 * assume all non-null rel1 rows have join partners, else assume for
2574 * the uncertain rows that a fraction nd2/nd1 have join partners. We
2575 * can discount the known-matched MCVs from the distinct-values counts
2576 * before doing the division.
2578 * Crude as the above is, it's completely useless if we don't have
2579 * reliable ndistinct values for both sides. Hence, if either nd1 or
2580 * nd2 is default, punt and assume half of the uncertain rows have
2583 if (!isdefault1 && !isdefault2)
2587 if (nd1 <= nd2 || nd2 < 0)
2588 uncertainfrac = 1.0;
2590 uncertainfrac = nd2 / nd1;
2593 uncertainfrac = 0.5;
2594 uncertain = 1.0 - matchfreq1 - nullfrac1;
2595 CLAMP_PROBABILITY(uncertain);
2596 selec = matchfreq1 + uncertainfrac * uncertain;
2601 * Without MCV lists for both sides, we can only use the heuristic
2604 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2606 if (!isdefault1 && !isdefault2)
2608 if (nd1 <= nd2 || nd2 < 0)
2609 selec = 1.0 - nullfrac1;
2611 selec = (nd2 / nd1) * (1.0 - nullfrac1);
2614 selec = 0.5 * (1.0 - nullfrac1);
2618 free_attstatsslot(vardata1->atttype, values1, nvalues1,
2619 numbers1, nnumbers1);
2621 free_attstatsslot(vardata2->atttype, values2, nvalues2,
2622 numbers2, nnumbers2);
2628 * neqjoinsel - Join selectivity of "!="
2631 neqjoinsel(PG_FUNCTION_ARGS)
2633 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2634 Oid operator = PG_GETARG_OID(1);
2635 List *args = (List *) PG_GETARG_POINTER(2);
2636 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2637 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2642 * We want 1 - eqjoinsel() where the equality operator is the one
2643 * associated with this != operator, that is, its negator.
2645 eqop = get_negator(operator);
2648 result = DatumGetFloat8(DirectFunctionCall5(eqjoinsel,
2649 PointerGetDatum(root),
2650 ObjectIdGetDatum(eqop),
2651 PointerGetDatum(args),
2652 Int16GetDatum(jointype),
2653 PointerGetDatum(sjinfo)));
2657 /* Use default selectivity (should we raise an error instead?) */
2658 result = DEFAULT_EQ_SEL;
2660 result = 1.0 - result;
2661 PG_RETURN_FLOAT8(result);
2665 * scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
2668 scalarltjoinsel(PG_FUNCTION_ARGS)
2670 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2674 * scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
2677 scalargtjoinsel(PG_FUNCTION_ARGS)
2679 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2683 * patternjoinsel - Generic code for pattern-match join selectivity.
2686 patternjoinsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
2688 /* For the moment we just punt. */
2689 return negate ? (1.0 - DEFAULT_MATCH_SEL) : DEFAULT_MATCH_SEL;
2693 * regexeqjoinsel - Join selectivity of regular-expression pattern match.
2696 regexeqjoinsel(PG_FUNCTION_ARGS)
2698 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, false));
2702 * icregexeqjoinsel - Join selectivity of case-insensitive regex match.
2705 icregexeqjoinsel(PG_FUNCTION_ARGS)
2707 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, false));
2711 * likejoinsel - Join selectivity of LIKE pattern match.
2714 likejoinsel(PG_FUNCTION_ARGS)
2716 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, false));
2720 * iclikejoinsel - Join selectivity of ILIKE pattern match.
2723 iclikejoinsel(PG_FUNCTION_ARGS)
2725 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, false));
2729 * regexnejoinsel - Join selectivity of regex non-match.
2732 regexnejoinsel(PG_FUNCTION_ARGS)
2734 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, true));
2738 * icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
2741 icregexnejoinsel(PG_FUNCTION_ARGS)
2743 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, true));
2747 * nlikejoinsel - Join selectivity of LIKE pattern non-match.
2750 nlikejoinsel(PG_FUNCTION_ARGS)
2752 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, true));
2756 * icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
2759 icnlikejoinsel(PG_FUNCTION_ARGS)
2761 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, true));
2765 * mergejoinscansel - Scan selectivity of merge join.
2767 * A merge join will stop as soon as it exhausts either input stream.
2768 * Therefore, if we can estimate the ranges of both input variables,
2769 * we can estimate how much of the input will actually be read. This
2770 * can have a considerable impact on the cost when using indexscans.
2772 * Also, we can estimate how much of each input has to be read before the
2773 * first join pair is found, which will affect the join's startup time.
2775 * clause should be a clause already known to be mergejoinable. opfamily,
2776 * strategy, and nulls_first specify the sort ordering being used.
2779 * *leftstart is set to the fraction of the left-hand variable expected
2780 * to be scanned before the first join pair is found (0 to 1).
2781 * *leftend is set to the fraction of the left-hand variable expected
2782 * to be scanned before the join terminates (0 to 1).
2783 * *rightstart, *rightend similarly for the right-hand variable.
2786 mergejoinscansel(PlannerInfo *root, Node *clause,
2787 Oid opfamily, int strategy, bool nulls_first,
2788 Selectivity *leftstart, Selectivity *leftend,
2789 Selectivity *rightstart, Selectivity *rightend)
2793 VariableStatData leftvar,
2814 /* Set default results if we can't figure anything out. */
2815 /* XXX should default "start" fraction be a bit more than 0? */
2816 *leftstart = *rightstart = 0.0;
2817 *leftend = *rightend = 1.0;
2819 /* Deconstruct the merge clause */
2820 if (!is_opclause(clause))
2821 return; /* shouldn't happen */
2822 opno = ((OpExpr *) clause)->opno;
2823 left = get_leftop((Expr *) clause);
2824 right = get_rightop((Expr *) clause);
2826 return; /* shouldn't happen */
2828 /* Look for stats for the inputs */
2829 examine_variable(root, left, 0, &leftvar);
2830 examine_variable(root, right, 0, &rightvar);
2832 /* Extract the operator's declared left/right datatypes */
2833 get_op_opfamily_properties(opno, opfamily, false,
2837 Assert(op_strategy == BTEqualStrategyNumber);
2840 * Look up the various operators we need. If we don't find them all, it
2841 * probably means the opfamily is broken, but we just fail silently.
2843 * Note: we expect that pg_statistic histograms will be sorted by the '<'
2844 * operator, regardless of which sort direction we are considering.
2848 case BTLessStrategyNumber:
2850 if (op_lefttype == op_righttype)
2853 ltop = get_opfamily_member(opfamily,
2854 op_lefttype, op_righttype,
2855 BTLessStrategyNumber);
2856 leop = get_opfamily_member(opfamily,
2857 op_lefttype, op_righttype,
2858 BTLessEqualStrategyNumber);
2868 ltop = get_opfamily_member(opfamily,
2869 op_lefttype, op_righttype,
2870 BTLessStrategyNumber);
2871 leop = get_opfamily_member(opfamily,
2872 op_lefttype, op_righttype,
2873 BTLessEqualStrategyNumber);
2874 lsortop = get_opfamily_member(opfamily,
2875 op_lefttype, op_lefttype,
2876 BTLessStrategyNumber);
2877 rsortop = get_opfamily_member(opfamily,
2878 op_righttype, op_righttype,
2879 BTLessStrategyNumber);
2882 revltop = get_opfamily_member(opfamily,
2883 op_righttype, op_lefttype,
2884 BTLessStrategyNumber);
2885 revleop = get_opfamily_member(opfamily,
2886 op_righttype, op_lefttype,
2887 BTLessEqualStrategyNumber);
2890 case BTGreaterStrategyNumber:
2891 /* descending-order case */
2893 if (op_lefttype == op_righttype)
2896 ltop = get_opfamily_member(opfamily,
2897 op_lefttype, op_righttype,
2898 BTGreaterStrategyNumber);
2899 leop = get_opfamily_member(opfamily,
2900 op_lefttype, op_righttype,
2901 BTGreaterEqualStrategyNumber);
2904 lstatop = get_opfamily_member(opfamily,
2905 op_lefttype, op_lefttype,
2906 BTLessStrategyNumber);
2913 ltop = get_opfamily_member(opfamily,
2914 op_lefttype, op_righttype,
2915 BTGreaterStrategyNumber);
2916 leop = get_opfamily_member(opfamily,
2917 op_lefttype, op_righttype,
2918 BTGreaterEqualStrategyNumber);
2919 lsortop = get_opfamily_member(opfamily,
2920 op_lefttype, op_lefttype,
2921 BTGreaterStrategyNumber);
2922 rsortop = get_opfamily_member(opfamily,
2923 op_righttype, op_righttype,
2924 BTGreaterStrategyNumber);
2925 lstatop = get_opfamily_member(opfamily,
2926 op_lefttype, op_lefttype,
2927 BTLessStrategyNumber);
2928 rstatop = get_opfamily_member(opfamily,
2929 op_righttype, op_righttype,
2930 BTLessStrategyNumber);
2931 revltop = get_opfamily_member(opfamily,
2932 op_righttype, op_lefttype,
2933 BTGreaterStrategyNumber);
2934 revleop = get_opfamily_member(opfamily,
2935 op_righttype, op_lefttype,
2936 BTGreaterEqualStrategyNumber);
2940 goto fail; /* shouldn't get here */
2943 if (!OidIsValid(lsortop) ||
2944 !OidIsValid(rsortop) ||
2945 !OidIsValid(lstatop) ||
2946 !OidIsValid(rstatop) ||
2947 !OidIsValid(ltop) ||
2948 !OidIsValid(leop) ||
2949 !OidIsValid(revltop) ||
2950 !OidIsValid(revleop))
2951 goto fail; /* insufficient info in catalogs */
2953 /* Try to get ranges of both inputs */
2956 if (!get_variable_range(root, &leftvar, lstatop,
2957 &leftmin, &leftmax))
2958 goto fail; /* no range available from stats */
2959 if (!get_variable_range(root, &rightvar, rstatop,
2960 &rightmin, &rightmax))
2961 goto fail; /* no range available from stats */
2965 /* need to swap the max and min */
2966 if (!get_variable_range(root, &leftvar, lstatop,
2967 &leftmax, &leftmin))
2968 goto fail; /* no range available from stats */
2969 if (!get_variable_range(root, &rightvar, rstatop,
2970 &rightmax, &rightmin))
2971 goto fail; /* no range available from stats */
2975 * Now, the fraction of the left variable that will be scanned is the
2976 * fraction that's <= the right-side maximum value. But only believe
2977 * non-default estimates, else stick with our 1.0.
2979 selec = scalarineqsel(root, leop, isgt, &leftvar,
2980 rightmax, op_righttype);
2981 if (selec != DEFAULT_INEQ_SEL)
2984 /* And similarly for the right variable. */
2985 selec = scalarineqsel(root, revleop, isgt, &rightvar,
2986 leftmax, op_lefttype);
2987 if (selec != DEFAULT_INEQ_SEL)
2991 * Only one of the two "end" fractions can really be less than 1.0;
2992 * believe the smaller estimate and reset the other one to exactly 1.0. If
2993 * we get exactly equal estimates (as can easily happen with self-joins),
2996 if (*leftend > *rightend)
2998 else if (*leftend < *rightend)
3001 *leftend = *rightend = 1.0;
3004 * Also, the fraction of the left variable that will be scanned before the
3005 * first join pair is found is the fraction that's < the right-side
3006 * minimum value. But only believe non-default estimates, else stick with
3009 selec = scalarineqsel(root, ltop, isgt, &leftvar,
3010 rightmin, op_righttype);
3011 if (selec != DEFAULT_INEQ_SEL)
3014 /* And similarly for the right variable. */
3015 selec = scalarineqsel(root, revltop, isgt, &rightvar,
3016 leftmin, op_lefttype);
3017 if (selec != DEFAULT_INEQ_SEL)
3018 *rightstart = selec;
3021 * Only one of the two "start" fractions can really be more than zero;
3022 * believe the larger estimate and reset the other one to exactly 0.0. If
3023 * we get exactly equal estimates (as can easily happen with self-joins),
3026 if (*leftstart < *rightstart)
3028 else if (*leftstart > *rightstart)
3031 *leftstart = *rightstart = 0.0;
3034 * If the sort order is nulls-first, we're going to have to skip over any
3035 * nulls too. These would not have been counted by scalarineqsel, and we
3036 * can safely add in this fraction regardless of whether we believe
3037 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3041 Form_pg_statistic stats;
3043 if (HeapTupleIsValid(leftvar.statsTuple))
3045 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3046 *leftstart += stats->stanullfrac;
3047 CLAMP_PROBABILITY(*leftstart);
3048 *leftend += stats->stanullfrac;
3049 CLAMP_PROBABILITY(*leftend);
3051 if (HeapTupleIsValid(rightvar.statsTuple))
3053 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3054 *rightstart += stats->stanullfrac;
3055 CLAMP_PROBABILITY(*rightstart);
3056 *rightend += stats->stanullfrac;
3057 CLAMP_PROBABILITY(*rightend);
3061 /* Disbelieve start >= end, just in case that can happen */
3062 if (*leftstart >= *leftend)
3067 if (*rightstart >= *rightend)
3074 ReleaseVariableStats(leftvar);
3075 ReleaseVariableStats(rightvar);
3080 * Helper routine for estimate_num_groups: add an item to a list of
3081 * GroupVarInfos, but only if it's not known equal to any of the existing
3086 Node *var; /* might be an expression, not just a Var */
3087 RelOptInfo *rel; /* relation it belongs to */
3088 double ndistinct; /* # distinct values */
3092 add_unique_group_var(PlannerInfo *root, List *varinfos,
3093 Node *var, VariableStatData *vardata)
3095 GroupVarInfo *varinfo;
3100 ndistinct = get_variable_numdistinct(vardata, &isdefault);
3102 /* cannot use foreach here because of possible list_delete */
3103 lc = list_head(varinfos);
3106 varinfo = (GroupVarInfo *) lfirst(lc);
3108 /* must advance lc before list_delete possibly pfree's it */
3111 /* Drop exact duplicates */
3112 if (equal(var, varinfo->var))
3116 * Drop known-equal vars, but only if they belong to different
3117 * relations (see comments for estimate_num_groups)
3119 if (vardata->rel != varinfo->rel &&
3120 exprs_known_equal(root, var, varinfo->var))
3122 if (varinfo->ndistinct <= ndistinct)
3124 /* Keep older item, forget new one */
3129 /* Delete the older item */
3130 varinfos = list_delete_ptr(varinfos, varinfo);
3135 varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3138 varinfo->rel = vardata->rel;
3139 varinfo->ndistinct = ndistinct;
3140 varinfos = lappend(varinfos, varinfo);
3145 * estimate_num_groups - Estimate number of groups in a grouped query
3147 * Given a query having a GROUP BY clause, estimate how many groups there
3148 * will be --- ie, the number of distinct combinations of the GROUP BY
3151 * This routine is also used to estimate the number of rows emitted by
3152 * a DISTINCT filtering step; that is an isomorphic problem. (Note:
3153 * actually, we only use it for DISTINCT when there's no grouping or
3154 * aggregation ahead of the DISTINCT.)
3158 * groupExprs - list of expressions being grouped by
3159 * input_rows - number of rows estimated to arrive at the group/unique
3161 * pgset - NULL, or a List** pointing to a grouping set to filter the
3162 * groupExprs against
3164 * Given the lack of any cross-correlation statistics in the system, it's
3165 * impossible to do anything really trustworthy with GROUP BY conditions
3166 * involving multiple Vars. We should however avoid assuming the worst
3167 * case (all possible cross-product terms actually appear as groups) since
3168 * very often the grouped-by Vars are highly correlated. Our current approach
3170 * 1. Expressions yielding boolean are assumed to contribute two groups,
3171 * independently of their content, and are ignored in the subsequent
3172 * steps. This is mainly because tests like "col IS NULL" break the
3173 * heuristic used in step 2 especially badly.
3174 * 2. Reduce the given expressions to a list of unique Vars used. For
3175 * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3176 * It is clearly correct not to count the same Var more than once.
3177 * It is also reasonable to treat f(x) the same as x: f() cannot
3178 * increase the number of distinct values (unless it is volatile,
3179 * which we consider unlikely for grouping), but it probably won't
3180 * reduce the number of distinct values much either.
3181 * As a special case, if a GROUP BY expression can be matched to an
3182 * expressional index for which we have statistics, then we treat the
3183 * whole expression as though it were just a Var.
3184 * 3. If the list contains Vars of different relations that are known equal
3185 * due to equivalence classes, then drop all but one of the Vars from each
3186 * known-equal set, keeping the one with smallest estimated # of values
3187 * (since the extra values of the others can't appear in joined rows).
3188 * Note the reason we only consider Vars of different relations is that
3189 * if we considered ones of the same rel, we'd be double-counting the
3190 * restriction selectivity of the equality in the next step.
3191 * 4. For Vars within a single source rel, we multiply together the numbers
3192 * of values, clamp to the number of rows in the rel (divided by 10 if
3193 * more than one Var), and then multiply by the selectivity of the
3194 * restriction clauses for that rel. When there's more than one Var,
3195 * the initial product is probably too high (it's the worst case) but
3196 * clamping to a fraction of the rel's rows seems to be a helpful
3197 * heuristic for not letting the estimate get out of hand. (The factor
3198 * of 10 is derived from pre-Postgres-7.4 practice.) Multiplying
3199 * by the restriction selectivity is effectively assuming that the
3200 * restriction clauses are independent of the grouping, which is a crummy
3201 * assumption, but it's hard to do better.
3202 * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3203 * rel, and multiply the results together.
3204 * Note that rels not containing grouped Vars are ignored completely, as are
3205 * join clauses. Such rels cannot increase the number of groups, and we
3206 * assume such clauses do not reduce the number either (somewhat bogus,
3207 * but we don't have the info to do better).
3210 estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3213 List *varinfos = NIL;
3219 * We don't ever want to return an estimate of zero groups, as that tends
3220 * to lead to division-by-zero and other unpleasantness. The input_rows
3221 * estimate is usually already at least 1, but clamp it just in case it
3224 input_rows = clamp_row_est(input_rows);
3227 * If no grouping columns, there's exactly one group. (This can't happen
3228 * for normal cases with GROUP BY or DISTINCT, but it is possible for
3229 * corner cases with set operations.)
3231 if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3235 * Count groups derived from boolean grouping expressions. For other
3236 * expressions, find the unique Vars used, treating an expression as a Var
3237 * if we can find stats for it. For each one, record the statistical
3238 * estimate of number of distinct values (total in its table, without
3239 * regard for filtering).
3244 foreach(l, groupExprs)
3246 Node *groupexpr = (Node *) lfirst(l);
3247 VariableStatData vardata;
3251 /* is expression in this grouping set? */
3252 if (pgset && !list_member_int(*pgset, i++))
3255 /* Short-circuit for expressions returning boolean */
3256 if (exprType(groupexpr) == BOOLOID)
3263 * If examine_variable is able to deduce anything about the GROUP BY
3264 * expression, treat it as a single variable even if it's really more
3267 examine_variable(root, groupexpr, 0, &vardata);
3268 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3270 varinfos = add_unique_group_var(root, varinfos,
3271 groupexpr, &vardata);
3272 ReleaseVariableStats(vardata);
3275 ReleaseVariableStats(vardata);
3278 * Else pull out the component Vars. Handle PlaceHolderVars by
3279 * recursing into their arguments (effectively assuming that the
3280 * PlaceHolderVar doesn't change the number of groups, which boils
3281 * down to ignoring the possible addition of nulls to the result set).
3283 varshere = pull_var_clause(groupexpr,
3284 PVC_RECURSE_AGGREGATES,
3285 PVC_RECURSE_PLACEHOLDERS);
3288 * If we find any variable-free GROUP BY item, then either it is a
3289 * constant (and we can ignore it) or it contains a volatile function;
3290 * in the latter case we punt and assume that each input row will
3291 * yield a distinct group.
3293 if (varshere == NIL)
3295 if (contain_volatile_functions(groupexpr))
3301 * Else add variables to varinfos list
3303 foreach(l2, varshere)
3305 Node *var = (Node *) lfirst(l2);
3307 examine_variable(root, var, 0, &vardata);
3308 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3309 ReleaseVariableStats(vardata);
3314 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3317 if (varinfos == NIL)
3319 /* Guard against out-of-range answers */
3320 if (numdistinct > input_rows)
3321 numdistinct = input_rows;
3326 * Group Vars by relation and estimate total numdistinct.
3328 * For each iteration of the outer loop, we process the frontmost Var in
3329 * varinfos, plus all other Vars in the same relation. We remove these
3330 * Vars from the newvarinfos list for the next iteration. This is the
3331 * easiest way to group Vars of same rel together.
3335 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3336 RelOptInfo *rel = varinfo1->rel;
3337 double reldistinct = varinfo1->ndistinct;
3338 double relmaxndistinct = reldistinct;
3339 int relvarcount = 1;
3340 List *newvarinfos = NIL;
3343 * Get the product of numdistinct estimates of the Vars for this rel.
3344 * Also, construct new varinfos list of remaining Vars.
3346 for_each_cell(l, lnext(list_head(varinfos)))
3348 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3350 if (varinfo2->rel == varinfo1->rel)
3352 reldistinct *= varinfo2->ndistinct;
3353 if (relmaxndistinct < varinfo2->ndistinct)
3354 relmaxndistinct = varinfo2->ndistinct;
3359 /* not time to process varinfo2 yet */
3360 newvarinfos = lcons(varinfo2, newvarinfos);
3365 * Sanity check --- don't divide by zero if empty relation.
3367 Assert(rel->reloptkind == RELOPT_BASEREL);
3368 if (rel->tuples > 0)
3371 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3372 * fudge factor is because the Vars are probably correlated but we
3373 * don't know by how much. We should never clamp to less than the
3374 * largest ndistinct value for any of the Vars, though, since
3375 * there will surely be at least that many groups.
3377 double clamp = rel->tuples;
3379 if (relvarcount > 1)
3382 if (clamp < relmaxndistinct)
3384 clamp = relmaxndistinct;
3385 /* for sanity in case some ndistinct is too large: */
3386 if (clamp > rel->tuples)
3387 clamp = rel->tuples;
3390 if (reldistinct > clamp)
3391 reldistinct = clamp;
3394 * Multiply by restriction selectivity.
3396 reldistinct *= rel->rows / rel->tuples;
3399 * Update estimate of total distinct groups.
3401 numdistinct *= reldistinct;
3404 varinfos = newvarinfos;
3405 } while (varinfos != NIL);
3407 numdistinct = ceil(numdistinct);
3409 /* Guard against out-of-range answers */
3410 if (numdistinct > input_rows)
3411 numdistinct = input_rows;
3412 if (numdistinct < 1.0)
3419 * Estimate hash bucketsize fraction (ie, number of entries in a bucket
3420 * divided by total tuples in relation) if the specified expression is used
3423 * XXX This is really pretty bogus since we're effectively assuming that the
3424 * distribution of hash keys will be the same after applying restriction
3425 * clauses as it was in the underlying relation. However, we are not nearly
3426 * smart enough to figure out how the restrict clauses might change the
3427 * distribution, so this will have to do for now.
3429 * We are passed the number of buckets the executor will use for the given
3430 * input relation. If the data were perfectly distributed, with the same
3431 * number of tuples going into each available bucket, then the bucketsize
3432 * fraction would be 1/nbuckets. But this happy state of affairs will occur
3433 * only if (a) there are at least nbuckets distinct data values, and (b)
3434 * we have a not-too-skewed data distribution. Otherwise the buckets will
3435 * be nonuniformly occupied. If the other relation in the join has a key
3436 * distribution similar to this one's, then the most-loaded buckets are
3437 * exactly those that will be probed most often. Therefore, the "average"
3438 * bucket size for costing purposes should really be taken as something close
3439 * to the "worst case" bucket size. We try to estimate this by adjusting the
3440 * fraction if there are too few distinct data values, and then scaling up
3441 * by the ratio of the most common value's frequency to the average frequency.
3443 * If no statistics are available, use a default estimate of 0.1. This will
3444 * discourage use of a hash rather strongly if the inner relation is large,
3445 * which is what we want. We do not want to hash unless we know that the
3446 * inner rel is well-dispersed (or the alternatives seem much worse).
3449 estimate_hash_bucketsize(PlannerInfo *root, Node *hashkey, double nbuckets)
3451 VariableStatData vardata;
3461 examine_variable(root, hashkey, 0, &vardata);
3463 /* Get number of distinct values */
3464 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3466 /* If ndistinct isn't real, punt and return 0.1, per comments above */
3469 ReleaseVariableStats(vardata);
3470 return (Selectivity) 0.1;
3473 /* Get fraction that are null */
3474 if (HeapTupleIsValid(vardata.statsTuple))
3476 Form_pg_statistic stats;
3478 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3479 stanullfrac = stats->stanullfrac;
3484 /* Compute avg freq of all distinct data values in raw relation */
3485 avgfreq = (1.0 - stanullfrac) / ndistinct;
3488 * Adjust ndistinct to account for restriction clauses. Observe we are
3489 * assuming that the data distribution is affected uniformly by the
3490 * restriction clauses!
3492 * XXX Possibly better way, but much more expensive: multiply by
3493 * selectivity of rel's restriction clauses that mention the target Var.
3496 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3499 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3500 * number of buckets is less than the expected number of distinct values;
3501 * otherwise it is 1/ndistinct.
3503 if (ndistinct > nbuckets)
3504 estfract = 1.0 / nbuckets;
3506 estfract = 1.0 / ndistinct;
3509 * Look up the frequency of the most common value, if available.
3513 if (HeapTupleIsValid(vardata.statsTuple))
3515 if (get_attstatsslot(vardata.statsTuple,
3516 vardata.atttype, vardata.atttypmod,
3517 STATISTIC_KIND_MCV, InvalidOid,
3520 &numbers, &nnumbers))
3523 * The first MCV stat is for the most common value.
3526 mcvfreq = numbers[0];
3527 free_attstatsslot(vardata.atttype, NULL, 0,
3533 * Adjust estimated bucketsize upward to account for skewed distribution.
3535 if (avgfreq > 0.0 && mcvfreq > avgfreq)
3536 estfract *= mcvfreq / avgfreq;
3539 * Clamp bucketsize to sane range (the above adjustment could easily
3540 * produce an out-of-range result). We set the lower bound a little above
3541 * zero, since zero isn't a very sane result.
3543 if (estfract < 1.0e-6)
3545 else if (estfract > 1.0)
3548 ReleaseVariableStats(vardata);
3550 return (Selectivity) estfract;
3554 /*-------------------------------------------------------------------------
3558 *-------------------------------------------------------------------------
3563 * Convert non-NULL values of the indicated types to the comparison
3564 * scale needed by scalarineqsel().
3565 * Returns "true" if successful.
3567 * XXX this routine is a hack: ideally we should look up the conversion
3568 * subroutines in pg_type.
3570 * All numeric datatypes are simply converted to their equivalent
3571 * "double" values. (NUMERIC values that are outside the range of "double"
3572 * are clamped to +/- HUGE_VAL.)
3574 * String datatypes are converted by convert_string_to_scalar(),
3575 * which is explained below. The reason why this routine deals with
3576 * three values at a time, not just one, is that we need it for strings.
3578 * The bytea datatype is just enough different from strings that it has
3579 * to be treated separately.
3581 * The several datatypes representing absolute times are all converted
3582 * to Timestamp, which is actually a double, and then we just use that
3583 * double value. Note this will give correct results even for the "special"
3584 * values of Timestamp, since those are chosen to compare correctly;
3585 * see timestamp_cmp.
3587 * The several datatypes representing relative times (intervals) are all
3588 * converted to measurements expressed in seconds.
3591 convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
3592 Datum lobound, Datum hibound, Oid boundstypid,
3593 double *scaledlobound, double *scaledhibound)
3596 * Both the valuetypid and the boundstypid should exactly match the
3597 * declared input type(s) of the operator we are invoked for, so we just
3598 * error out if either is not recognized.
3600 * XXX The histogram we are interpolating between points of could belong
3601 * to a column that's only binary-compatible with the declared type. In
3602 * essence we are assuming that the semantics of binary-compatible types
3603 * are enough alike that we can use a histogram generated with one type's
3604 * operators to estimate selectivity for the other's. This is outright
3605 * wrong in some cases --- in particular signed versus unsigned
3606 * interpretation could trip us up. But it's useful enough in the
3607 * majority of cases that we do it anyway. Should think about more
3608 * rigorous ways to do it.
3613 * Built-in numeric types
3624 case REGPROCEDUREOID:
3626 case REGOPERATOROID:
3630 case REGDICTIONARYOID:
3632 case REGNAMESPACEOID:
3633 *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
3634 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
3635 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
3639 * Built-in string types
3647 char *valstr = convert_string_datum(value, valuetypid);
3648 char *lostr = convert_string_datum(lobound, boundstypid);
3649 char *histr = convert_string_datum(hibound, boundstypid);
3651 convert_string_to_scalar(valstr, scaledvalue,
3652 lostr, scaledlobound,
3653 histr, scaledhibound);
3661 * Built-in bytea type
3665 convert_bytea_to_scalar(value, scaledvalue,
3666 lobound, scaledlobound,
3667 hibound, scaledhibound);
3672 * Built-in time types
3675 case TIMESTAMPTZOID:
3683 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
3684 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
3685 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
3689 * Built-in network types
3694 *scaledvalue = convert_network_to_scalar(value, valuetypid);
3695 *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
3696 *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
3699 /* Don't know how to convert */
3700 *scaledvalue = *scaledlobound = *scaledhibound = 0;
3705 * Do convert_to_scalar()'s work for any numeric data type.
3708 convert_numeric_to_scalar(Datum value, Oid typid)
3713 return (double) DatumGetBool(value);
3715 return (double) DatumGetInt16(value);
3717 return (double) DatumGetInt32(value);
3719 return (double) DatumGetInt64(value);
3721 return (double) DatumGetFloat4(value);
3723 return (double) DatumGetFloat8(value);
3725 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3727 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
3731 case REGPROCEDUREOID:
3733 case REGOPERATOROID:
3737 case REGDICTIONARYOID:
3739 case REGNAMESPACEOID:
3740 /* we can treat OIDs as integers... */
3741 return (double) DatumGetObjectId(value);
3745 * Can't get here unless someone tries to use scalarltsel/scalargtsel on
3746 * an operator with one numeric and one non-numeric operand.
3748 elog(ERROR, "unsupported type: %u", typid);
3753 * Do convert_to_scalar()'s work for any character-string data type.
3755 * String datatypes are converted to a scale that ranges from 0 to 1,
3756 * where we visualize the bytes of the string as fractional digits.
3758 * We do not want the base to be 256, however, since that tends to
3759 * generate inflated selectivity estimates; few databases will have
3760 * occurrences of all 256 possible byte values at each position.
3761 * Instead, use the smallest and largest byte values seen in the bounds
3762 * as the estimated range for each byte, after some fudging to deal with
3763 * the fact that we probably aren't going to see the full range that way.
3765 * An additional refinement is that we discard any common prefix of the
3766 * three strings before computing the scaled values. This allows us to
3767 * "zoom in" when we encounter a narrow data range. An example is a phone
3768 * number database where all the values begin with the same area code.
3769 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
3770 * so this is more likely to happen than you might think.)
3773 convert_string_to_scalar(char *value,
3774 double *scaledvalue,
3776 double *scaledlobound,
3778 double *scaledhibound)
3784 rangelo = rangehi = (unsigned char) hibound[0];
3785 for (sptr = lobound; *sptr; sptr++)
3787 if (rangelo > (unsigned char) *sptr)
3788 rangelo = (unsigned char) *sptr;
3789 if (rangehi < (unsigned char) *sptr)
3790 rangehi = (unsigned char) *sptr;
3792 for (sptr = hibound; *sptr; sptr++)
3794 if (rangelo > (unsigned char) *sptr)
3795 rangelo = (unsigned char) *sptr;
3796 if (rangehi < (unsigned char) *sptr)
3797 rangehi = (unsigned char) *sptr;
3799 /* If range includes any upper-case ASCII chars, make it include all */
3800 if (rangelo <= 'Z' && rangehi >= 'A')
3807 /* Ditto lower-case */
3808 if (rangelo <= 'z' && rangehi >= 'a')
3816 if (rangelo <= '9' && rangehi >= '0')
3825 * If range includes less than 10 chars, assume we have not got enough
3826 * data, and make it include regular ASCII set.
3828 if (rangehi - rangelo < 9)
3835 * Now strip any common prefix of the three strings.
3839 if (*lobound != *hibound || *lobound != *value)
3841 lobound++, hibound++, value++;
3845 * Now we can do the conversions.
3847 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
3848 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
3849 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
3853 convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
3855 int slen = strlen(value);
3861 return 0.0; /* empty string has scalar value 0 */
3864 * Since base is at least 10, need not consider more than about 20 chars
3869 /* Convert initial characters to fraction */
3870 base = rangehi - rangelo + 1;
3875 int ch = (unsigned char) *value++;
3879 else if (ch > rangehi)
3881 num += ((double) (ch - rangelo)) / denom;
3889 * Convert a string-type Datum into a palloc'd, null-terminated string.
3891 * When using a non-C locale, we must pass the string through strxfrm()
3892 * before continuing, so as to generate correct locale-specific results.
3895 convert_string_datum(Datum value, Oid typid)
3902 val = (char *) palloc(2);
3903 val[0] = DatumGetChar(value);
3909 val = TextDatumGetCString(value);
3913 NameData *nm = (NameData *) DatumGetPointer(value);
3915 val = pstrdup(NameStr(*nm));
3921 * Can't get here unless someone tries to use scalarltsel on an
3922 * operator with one string and one non-string operand.
3924 elog(ERROR, "unsupported type: %u", typid);
3928 if (!lc_collate_is_c(DEFAULT_COLLATION_OID))
3932 size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
3935 * Note: originally we guessed at a suitable output buffer size, and
3936 * only needed to call strxfrm twice if our guess was too small.
3937 * However, it seems that some versions of Solaris have buggy strxfrm
3938 * that can write past the specified buffer length in that scenario.
3939 * So, do it the dumb way for portability.
3941 * Yet other systems (e.g., glibc) sometimes return a smaller value
3942 * from the second call than the first; thus the Assert must be <= not
3943 * == as you'd expect. Can't any of these people program their way
3944 * out of a paper bag?
3946 * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
3947 * bogus data or set an error. This is not really a problem unless it
3948 * crashes since it will only give an estimation error and nothing
3951 #if _MSC_VER == 1400 /* VS.Net 2005 */
3955 * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?
3956 * FeedbackID=99694 */
3960 xfrmlen = strxfrm(x, val, 0);
3963 xfrmlen = strxfrm(NULL, val, 0);
3968 * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
3969 * of trying to allocate this much memory (and fail), just return the
3970 * original string unmodified as if we were in the C locale.
3972 if (xfrmlen == INT_MAX)
3975 xfrmstr = (char *) palloc(xfrmlen + 1);
3976 xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
3977 Assert(xfrmlen2 <= xfrmlen);
3986 * Do convert_to_scalar()'s work for any bytea data type.
3988 * Very similar to convert_string_to_scalar except we can't assume
3989 * null-termination and therefore pass explicit lengths around.
3991 * Also, assumptions about likely "normal" ranges of characters have been
3992 * removed - a data range of 0..255 is always used, for now. (Perhaps
3993 * someday we will add information about actual byte data range to
3997 convert_bytea_to_scalar(Datum value,
3998 double *scaledvalue,
4000 double *scaledlobound,
4002 double *scaledhibound)
4006 valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
4007 loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
4008 hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
4011 unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
4012 *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
4013 *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
4016 * Assume bytea data is uniformly distributed across all byte values.
4022 * Now strip any common prefix of the three strings.
4024 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4025 for (i = 0; i < minlen; i++)
4027 if (*lostr != *histr || *lostr != *valstr)
4029 lostr++, histr++, valstr++;
4030 loboundlen--, hiboundlen--, valuelen--;
4034 * Now we can do the conversions.
4036 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4037 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4038 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4042 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
4043 int rangelo, int rangehi)
4050 return 0.0; /* empty string has scalar value 0 */
4053 * Since base is 256, need not consider more than about 10 chars (even
4054 * this many seems like overkill)
4059 /* Convert initial characters to fraction */
4060 base = rangehi - rangelo + 1;
4063 while (valuelen-- > 0)
4069 else if (ch > rangehi)
4071 num += ((double) (ch - rangelo)) / denom;
4079 * Do convert_to_scalar()'s work for any timevalue data type.
4082 convert_timevalue_to_scalar(Datum value, Oid typid)
4087 return DatumGetTimestamp(value);
4088 case TIMESTAMPTZOID:
4089 return DatumGetTimestampTz(value);
4091 return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
4094 return date2timestamp_no_overflow(DatumGetDateADT(value));
4097 Interval *interval = DatumGetIntervalP(value);
4100 * Convert the month part of Interval to days using assumed
4101 * average month length of 365.25/12.0 days. Not too
4102 * accurate, but plenty good enough for our purposes.
4104 #ifdef HAVE_INT64_TIMESTAMP
4105 return interval->time + interval->day * (double) USECS_PER_DAY +
4106 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4108 return interval->time + interval->day * SECS_PER_DAY +
4109 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * (double) SECS_PER_DAY);
4113 #ifdef HAVE_INT64_TIMESTAMP
4114 return (DatumGetRelativeTime(value) * 1000000.0);
4116 return DatumGetRelativeTime(value);
4120 TimeInterval tinterval = DatumGetTimeInterval(value);
4122 #ifdef HAVE_INT64_TIMESTAMP
4123 if (tinterval->status != 0)
4124 return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4126 if (tinterval->status != 0)
4127 return tinterval->data[1] - tinterval->data[0];
4129 return 0; /* for lack of a better idea */
4132 return DatumGetTimeADT(value);
4135 TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4137 /* use GMT-equivalent time */
4138 #ifdef HAVE_INT64_TIMESTAMP
4139 return (double) (timetz->time + (timetz->zone * 1000000.0));
4141 return (double) (timetz->time + timetz->zone);
4147 * Can't get here unless someone tries to use scalarltsel/scalargtsel on
4148 * an operator with one timevalue and one non-timevalue operand.
4150 elog(ERROR, "unsupported type: %u", typid);
4156 * get_restriction_variable
4157 * Examine the args of a restriction clause to see if it's of the
4158 * form (variable op pseudoconstant) or (pseudoconstant op variable),
4159 * where "variable" could be either a Var or an expression in vars of a
4160 * single relation. If so, extract information about the variable,
4161 * and also indicate which side it was on and the other argument.
4164 * root: the planner info
4165 * args: clause argument list
4166 * varRelid: see specs for restriction selectivity functions
4168 * Outputs: (these are valid only if TRUE is returned)
4169 * *vardata: gets information about variable (see examine_variable)
4170 * *other: gets other clause argument, aggressively reduced to a constant
4171 * *varonleft: set TRUE if variable is on the left, FALSE if on the right
4173 * Returns TRUE if a variable is identified, otherwise FALSE.
4175 * Note: if there are Vars on both sides of the clause, we must fail, because
4176 * callers are expecting that the other side will act like a pseudoconstant.
4179 get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
4180 VariableStatData *vardata, Node **other,
4185 VariableStatData rdata;
4187 /* Fail if not a binary opclause (probably shouldn't happen) */
4188 if (list_length(args) != 2)
4191 left = (Node *) linitial(args);
4192 right = (Node *) lsecond(args);
4195 * Examine both sides. Note that when varRelid is nonzero, Vars of other
4196 * relations will be treated as pseudoconstants.
4198 examine_variable(root, left, varRelid, vardata);
4199 examine_variable(root, right, varRelid, &rdata);
4202 * If one side is a variable and the other not, we win.
4204 if (vardata->rel && rdata.rel == NULL)
4207 *other = estimate_expression_value(root, rdata.var);
4208 /* Assume we need no ReleaseVariableStats(rdata) here */
4212 if (vardata->rel == NULL && rdata.rel)
4215 *other = estimate_expression_value(root, vardata->var);
4216 /* Assume we need no ReleaseVariableStats(*vardata) here */
4221 /* Ooops, clause has wrong structure (probably var op var) */
4222 ReleaseVariableStats(*vardata);
4223 ReleaseVariableStats(rdata);
4229 * get_join_variables
4230 * Apply examine_variable() to each side of a join clause.
4231 * Also, attempt to identify whether the join clause has the same
4232 * or reversed sense compared to the SpecialJoinInfo.
4234 * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4235 * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4236 * where we can't tell for sure, we default to assuming it's normal.
4239 get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
4240 VariableStatData *vardata1, VariableStatData *vardata2,
4241 bool *join_is_reversed)
4246 if (list_length(args) != 2)
4247 elog(ERROR, "join operator should take two arguments");
4249 left = (Node *) linitial(args);
4250 right = (Node *) lsecond(args);
4252 examine_variable(root, left, 0, vardata1);
4253 examine_variable(root, right, 0, vardata2);
4255 if (vardata1->rel &&
4256 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4257 *join_is_reversed = true; /* var1 is on RHS */
4258 else if (vardata2->rel &&
4259 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4260 *join_is_reversed = true; /* var2 is on LHS */
4262 *join_is_reversed = false;
4267 * Try to look up statistical data about an expression.
4268 * Fill in a VariableStatData struct to describe the expression.
4271 * root: the planner info
4272 * node: the expression tree to examine
4273 * varRelid: see specs for restriction selectivity functions
4275 * Outputs: *vardata is filled as follows:
4276 * var: the input expression (with any binary relabeling stripped, if
4277 * it is or contains a variable; but otherwise the type is preserved)
4278 * rel: RelOptInfo for relation containing variable; NULL if expression
4279 * contains no Vars (NOTE this could point to a RelOptInfo of a
4280 * subquery, not one in the current query).
4281 * statsTuple: the pg_statistic entry for the variable, if one exists;
4283 * freefunc: pointer to a function to release statsTuple with.
4284 * vartype: exposed type of the expression; this should always match
4285 * the declared input type of the operator we are estimating for.
4286 * atttype, atttypmod: type data to pass to get_attstatsslot(). This is
4287 * commonly the same as the exposed type of the variable argument,
4288 * but can be different in binary-compatible-type cases.
4289 * isunique: TRUE if we were able to match the var to a unique index or a
4290 * single-column DISTINCT clause, implying its values are unique for
4291 * this query. (Caution: this should be trusted for statistical
4292 * purposes only, since we do not check indimmediate nor verify that
4293 * the exact same definition of equality applies.)
4295 * Caller is responsible for doing ReleaseVariableStats() before exiting.
4298 examine_variable(PlannerInfo *root, Node *node, int varRelid,
4299 VariableStatData *vardata)
4305 /* Make sure we don't return dangling pointers in vardata */
4306 MemSet(vardata, 0, sizeof(VariableStatData));
4308 /* Save the exposed type of the expression */
4309 vardata->vartype = exprType(node);
4311 /* Look inside any binary-compatible relabeling */
4313 if (IsA(node, RelabelType))
4314 basenode = (Node *) ((RelabelType *) node)->arg;
4318 /* Fast path for a simple Var */
4320 if (IsA(basenode, Var) &&
4321 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4323 Var *var = (Var *) basenode;
4325 /* Set up result fields other than the stats tuple */
4326 vardata->var = basenode; /* return Var without relabeling */
4327 vardata->rel = find_base_rel(root, var->varno);
4328 vardata->atttype = var->vartype;
4329 vardata->atttypmod = var->vartypmod;
4330 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4332 /* Try to locate some stats */
4333 examine_simple_variable(root, var, vardata);
4339 * Okay, it's a more complicated expression. Determine variable
4340 * membership. Note that when varRelid isn't zero, only vars of that
4341 * relation are considered "real" vars.
4343 varnos = pull_varnos(basenode);
4347 switch (bms_membership(varnos))
4350 /* No Vars at all ... must be pseudo-constant clause */
4353 if (varRelid == 0 || bms_is_member(varRelid, varnos))
4355 onerel = find_base_rel(root,
4356 (varRelid ? varRelid : bms_singleton_member(varnos)));
4357 vardata->rel = onerel;
4358 node = basenode; /* strip any relabeling */
4360 /* else treat it as a constant */
4365 /* treat it as a variable of a join relation */
4366 vardata->rel = find_join_rel(root, varnos);
4367 node = basenode; /* strip any relabeling */
4369 else if (bms_is_member(varRelid, varnos))
4371 /* ignore the vars belonging to other relations */
4372 vardata->rel = find_base_rel(root, varRelid);
4373 node = basenode; /* strip any relabeling */
4374 /* note: no point in expressional-index search here */
4376 /* else treat it as a constant */
4382 vardata->var = node;
4383 vardata->atttype = exprType(node);
4384 vardata->atttypmod = exprTypmod(node);
4389 * We have an expression in vars of a single relation. Try to match
4390 * it to expressional index columns, in hopes of finding some
4393 * XXX it's conceivable that there are multiple matches with different
4394 * index opfamilies; if so, we need to pick one that matches the
4395 * operator we are estimating for. FIXME later.
4399 foreach(ilist, onerel->indexlist)
4401 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4402 ListCell *indexpr_item;
4405 indexpr_item = list_head(index->indexprs);
4406 if (indexpr_item == NULL)
4407 continue; /* no expressions here... */
4409 for (pos = 0; pos < index->ncolumns; pos++)
4411 if (index->indexkeys[pos] == 0)
4415 if (indexpr_item == NULL)
4416 elog(ERROR, "too few entries in indexprs list");
4417 indexkey = (Node *) lfirst(indexpr_item);
4418 if (indexkey && IsA(indexkey, RelabelType))
4419 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4420 if (equal(node, indexkey))
4423 * Found a match ... is it a unique index? Tests here
4424 * should match has_unique_index().
4426 if (index->unique &&
4427 index->ncolumns == 1 &&
4428 (index->indpred == NIL || index->predOK))
4429 vardata->isunique = true;
4432 * Has it got stats? We only consider stats for
4433 * non-partial indexes, since partial indexes probably
4434 * don't reflect whole-relation statistics; the above
4435 * check for uniqueness is the only info we take from
4438 * An index stats hook, however, must make its own
4439 * decisions about what to do with partial indexes.
4441 if (get_index_stats_hook &&
4442 (*get_index_stats_hook) (root, index->indexoid,
4446 * The hook took control of acquiring a stats
4447 * tuple. If it did supply a tuple, it'd better
4448 * have supplied a freefunc.
4450 if (HeapTupleIsValid(vardata->statsTuple) &&
4452 elog(ERROR, "no function provided to release variable stats with");
4454 else if (index->indpred == NIL)
4456 vardata->statsTuple =
4457 SearchSysCache3(STATRELATTINH,
4458 ObjectIdGetDatum(index->indexoid),
4459 Int16GetDatum(pos + 1),
4460 BoolGetDatum(false));
4461 vardata->freefunc = ReleaseSysCache;
4463 if (vardata->statsTuple)
4466 indexpr_item = lnext(indexpr_item);
4469 if (vardata->statsTuple)
4476 * examine_simple_variable
4477 * Handle a simple Var for examine_variable
4479 * This is split out as a subroutine so that we can recurse to deal with
4480 * Vars referencing subqueries.
4482 * We already filled in all the fields of *vardata except for the stats tuple.
4485 examine_simple_variable(PlannerInfo *root, Var *var,
4486 VariableStatData *vardata)
4488 RangeTblEntry *rte = root->simple_rte_array[var->varno];
4490 Assert(IsA(rte, RangeTblEntry));
4492 if (get_relation_stats_hook &&
4493 (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4496 * The hook took control of acquiring a stats tuple. If it did supply
4497 * a tuple, it'd better have supplied a freefunc.
4499 if (HeapTupleIsValid(vardata->statsTuple) &&
4501 elog(ERROR, "no function provided to release variable stats with");
4503 else if (rte->rtekind == RTE_RELATION)
4506 * Plain table or parent of an inheritance appendrel, so look up the
4507 * column in pg_statistic
4509 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
4510 ObjectIdGetDatum(rte->relid),
4511 Int16GetDatum(var->varattno),
4512 BoolGetDatum(rte->inh));
4513 vardata->freefunc = ReleaseSysCache;
4515 else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4518 * Plain subquery (not one that was converted to an appendrel).
4520 Query *subquery = rte->subquery;
4525 * Punt if it's a whole-row var rather than a plain column reference.
4527 if (var->varattno == InvalidAttrNumber)
4531 * Punt if subquery uses set operations or GROUP BY, as these will
4532 * mash underlying columns' stats beyond recognition. (Set ops are
4533 * particularly nasty; if we forged ahead, we would return stats
4534 * relevant to only the leftmost subselect...) DISTINCT is also
4535 * problematic, but we check that later because there is a possibility
4536 * of learning something even with it.
4538 if (subquery->setOperations ||
4539 subquery->groupClause)
4543 * OK, fetch RelOptInfo for subquery. Note that we don't change the
4544 * rel returned in vardata, since caller expects it to be a rel of the
4545 * caller's query level. Because we might already be recursing, we
4546 * can't use that rel pointer either, but have to look up the Var's
4549 rel = find_base_rel(root, var->varno);
4551 /* If the subquery hasn't been planned yet, we have to punt */
4552 if (rel->subroot == NULL)
4554 Assert(IsA(rel->subroot, PlannerInfo));
4557 * Switch our attention to the subquery as mangled by the planner. It
4558 * was okay to look at the pre-planning version for the tests above,
4559 * but now we need a Var that will refer to the subroot's live
4560 * RelOptInfos. For instance, if any subquery pullup happened during
4561 * planning, Vars in the targetlist might have gotten replaced, and we
4562 * need to see the replacement expressions.
4564 subquery = rel->subroot->parse;
4565 Assert(IsA(subquery, Query));
4567 /* Get the subquery output expression referenced by the upper Var */
4568 ste = get_tle_by_resno(subquery->targetList, var->varattno);
4569 if (ste == NULL || ste->resjunk)
4570 elog(ERROR, "subquery %s does not have attribute %d",
4571 rte->eref->aliasname, var->varattno);
4572 var = (Var *) ste->expr;
4575 * If subquery uses DISTINCT, we can't make use of any stats for the
4576 * variable ... but, if it's the only DISTINCT column, we are entitled
4577 * to consider it unique. We do the test this way so that it works
4578 * for cases involving DISTINCT ON.
4580 if (subquery->distinctClause)
4582 if (list_length(subquery->distinctClause) == 1 &&
4583 targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4584 vardata->isunique = true;
4585 /* cannot go further */
4590 * If the sub-query originated from a view with the security_barrier
4591 * attribute, we must not look at the variable's statistics, though it
4592 * seems all right to notice the existence of a DISTINCT clause. So
4595 * This is probably a harsher restriction than necessary; it's
4596 * certainly OK for the selectivity estimator (which is a C function,
4597 * and therefore omnipotent anyway) to look at the statistics. But
4598 * many selectivity estimators will happily *invoke the operator
4599 * function* to try to work out a good estimate - and that's not OK.
4600 * So for now, don't dig down for stats.
4602 if (rte->security_barrier)
4605 /* Can only handle a simple Var of subquery's query level */
4606 if (var && IsA(var, Var) &&
4607 var->varlevelsup == 0)
4610 * OK, recurse into the subquery. Note that the original setting
4611 * of vardata->isunique (which will surely be false) is left
4612 * unchanged in this situation. That's what we want, since even
4613 * if the underlying column is unique, the subquery may have
4614 * joined to other tables in a way that creates duplicates.
4616 examine_simple_variable(rel->subroot, var, vardata);
4622 * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
4623 * won't see RTE_JOIN here because join alias Vars have already been
4624 * flattened.) There's not much we can do with function outputs, but
4625 * maybe someday try to be smarter about VALUES and/or CTEs.
4631 * get_variable_numdistinct
4632 * Estimate the number of distinct values of a variable.
4634 * vardata: results of examine_variable
4635 * *isdefault: set to TRUE if the result is a default rather than based on
4636 * anything meaningful.
4638 * NB: be careful to produce an integral result, since callers may compare
4639 * the result to exact integer counts.
4642 get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
4650 * Determine the stadistinct value to use. There are cases where we can
4651 * get an estimate even without a pg_statistic entry, or can get a better
4652 * value than is in pg_statistic.
4654 if (HeapTupleIsValid(vardata->statsTuple))
4656 /* Use the pg_statistic entry */
4657 Form_pg_statistic stats;
4659 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4660 stadistinct = stats->stadistinct;
4662 else if (vardata->vartype == BOOLOID)
4665 * Special-case boolean columns: presumably, two distinct values.
4667 * Are there any other datatypes we should wire in special estimates
4675 * We don't keep statistics for system columns, but in some cases we
4676 * can infer distinctness anyway.
4678 if (vardata->var && IsA(vardata->var, Var))
4680 switch (((Var *) vardata->var)->varattno)
4682 case ObjectIdAttributeNumber:
4683 case SelfItemPointerAttributeNumber:
4684 stadistinct = -1.0; /* unique */
4686 case TableOidAttributeNumber:
4687 stadistinct = 1.0; /* only 1 value */
4690 stadistinct = 0.0; /* means "unknown" */
4695 stadistinct = 0.0; /* means "unknown" */
4698 * XXX consider using estimate_num_groups on expressions?
4703 * If there is a unique index or DISTINCT clause for the variable, assume
4704 * it is unique no matter what pg_statistic says; the statistics could be
4705 * out of date, or we might have found a partial unique index that proves
4706 * the var is unique for this query.
4708 if (vardata->isunique)
4712 * If we had an absolute estimate, use that.
4714 if (stadistinct > 0.0)
4718 * Otherwise we need to get the relation size; punt if not available.
4720 if (vardata->rel == NULL)
4723 return DEFAULT_NUM_DISTINCT;
4725 ntuples = vardata->rel->tuples;
4729 return DEFAULT_NUM_DISTINCT;
4733 * If we had a relative estimate, use that.
4735 if (stadistinct < 0.0)
4736 return floor((-stadistinct * ntuples) + 0.5);
4739 * With no data, estimate ndistinct = ntuples if the table is small, else
4740 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
4741 * that the behavior isn't discontinuous.
4743 if (ntuples < DEFAULT_NUM_DISTINCT)
4747 return DEFAULT_NUM_DISTINCT;
4751 * get_variable_range
4752 * Estimate the minimum and maximum value of the specified variable.
4753 * If successful, store values in *min and *max, and return TRUE.
4754 * If no data available, return FALSE.
4756 * sortop is the "<" comparison operator to use. This should generally
4757 * be "<" not ">", as only the former is likely to be found in pg_statistic.
4760 get_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop,
4761 Datum *min, Datum *max)
4765 bool have_data = false;
4773 * XXX It's very tempting to try to use the actual column min and max, if
4774 * we can get them relatively-cheaply with an index probe. However, since
4775 * this function is called many times during join planning, that could
4776 * have unpleasant effects on planning speed. Need more investigation
4777 * before enabling this.
4780 if (get_actual_variable_range(root, vardata, sortop, min, max))
4784 if (!HeapTupleIsValid(vardata->statsTuple))
4786 /* no stats available, so default result */
4790 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
4793 * If there is a histogram, grab the first and last values.
4795 * If there is a histogram that is sorted with some other operator than
4796 * the one we want, fail --- this suggests that there is data we can't
4799 if (get_attstatsslot(vardata->statsTuple,
4800 vardata->atttype, vardata->atttypmod,
4801 STATISTIC_KIND_HISTOGRAM, sortop,
4808 tmin = datumCopy(values[0], typByVal, typLen);
4809 tmax = datumCopy(values[nvalues - 1], typByVal, typLen);
4812 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4814 else if (get_attstatsslot(vardata->statsTuple,
4815 vardata->atttype, vardata->atttypmod,
4816 STATISTIC_KIND_HISTOGRAM, InvalidOid,
4821 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4826 * If we have most-common-values info, look for extreme MCVs. This is
4827 * needed even if we also have a histogram, since the histogram excludes
4828 * the MCVs. However, usually the MCVs will not be the extreme values, so
4829 * avoid unnecessary data copying.
4831 if (get_attstatsslot(vardata->statsTuple,
4832 vardata->atttype, vardata->atttypmod,
4833 STATISTIC_KIND_MCV, InvalidOid,
4838 bool tmin_is_mcv = false;
4839 bool tmax_is_mcv = false;
4842 fmgr_info(get_opcode(sortop), &opproc);
4844 for (i = 0; i < nvalues; i++)
4848 tmin = tmax = values[i];
4849 tmin_is_mcv = tmax_is_mcv = have_data = true;
4852 if (DatumGetBool(FunctionCall2Coll(&opproc,
4853 DEFAULT_COLLATION_OID,
4859 if (DatumGetBool(FunctionCall2Coll(&opproc,
4860 DEFAULT_COLLATION_OID,
4868 tmin = datumCopy(tmin, typByVal, typLen);
4870 tmax = datumCopy(tmax, typByVal, typLen);
4871 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4881 * get_actual_variable_range
4882 * Attempt to identify the current *actual* minimum and/or maximum
4883 * of the specified variable, by looking for a suitable btree index
4884 * and fetching its low and/or high values.
4885 * If successful, store values in *min and *max, and return TRUE.
4886 * (Either pointer can be NULL if that endpoint isn't needed.)
4887 * If no data available, return FALSE.
4889 * sortop is the "<" comparison operator to use.
4892 get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
4894 Datum *min, Datum *max)
4896 bool have_data = false;
4897 RelOptInfo *rel = vardata->rel;
4901 /* No hope if no relation or it doesn't have indexes */
4902 if (rel == NULL || rel->indexlist == NIL)
4904 /* If it has indexes it must be a plain relation */
4905 rte = root->simple_rte_array[rel->relid];
4906 Assert(rte->rtekind == RTE_RELATION);
4908 /* Search through the indexes to see if any match our problem */
4909 foreach(lc, rel->indexlist)
4911 IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
4912 ScanDirection indexscandir;
4914 /* Ignore non-btree indexes */
4915 if (index->relam != BTREE_AM_OID)
4919 * Ignore partial indexes --- we only want stats that cover the entire
4922 if (index->indpred != NIL)
4926 * The index list might include hypothetical indexes inserted by a
4927 * get_relation_info hook --- don't try to access them.
4929 if (index->hypothetical)
4933 * The first index column must match the desired variable and sort
4934 * operator --- but we can use a descending-order index.
4936 if (!match_index_to_operand(vardata->var, 0, index))
4938 switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
4940 case BTLessStrategyNumber:
4941 if (index->reverse_sort[0])
4942 indexscandir = BackwardScanDirection;
4944 indexscandir = ForwardScanDirection;
4946 case BTGreaterStrategyNumber:
4947 if (index->reverse_sort[0])
4948 indexscandir = ForwardScanDirection;
4950 indexscandir = BackwardScanDirection;
4953 /* index doesn't match the sortop */
4958 * Found a suitable index to extract data from. We'll need an EState
4959 * and a bunch of other infrastructure.
4963 ExprContext *econtext;
4964 MemoryContext tmpcontext;
4965 MemoryContext oldcontext;
4968 IndexInfo *indexInfo;
4969 TupleTableSlot *slot;
4972 ScanKeyData scankeys[1];
4973 IndexScanDesc index_scan;
4975 Datum values[INDEX_MAX_KEYS];
4976 bool isnull[INDEX_MAX_KEYS];
4977 SnapshotData SnapshotDirty;
4979 estate = CreateExecutorState();
4980 econtext = GetPerTupleExprContext(estate);
4981 /* Make sure any cruft is generated in the econtext's memory */
4982 tmpcontext = econtext->ecxt_per_tuple_memory;
4983 oldcontext = MemoryContextSwitchTo(tmpcontext);
4986 * Open the table and index so we can read from them. We should
4987 * already have at least AccessShareLock on the table, but not
4988 * necessarily on the index.
4990 heapRel = heap_open(rte->relid, NoLock);
4991 indexRel = index_open(index->indexoid, AccessShareLock);
4993 /* extract index key information from the index's pg_index info */
4994 indexInfo = BuildIndexInfo(indexRel);
4996 /* some other stuff */
4997 slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
4998 econtext->ecxt_scantuple = slot;
4999 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5000 InitDirtySnapshot(SnapshotDirty);
5002 /* set up an IS NOT NULL scan key so that we ignore nulls */
5003 ScanKeyEntryInitialize(&scankeys[0],
5004 SK_ISNULL | SK_SEARCHNOTNULL,
5005 1, /* index col to scan */
5006 InvalidStrategy, /* no strategy */
5007 InvalidOid, /* no strategy subtype */
5008 InvalidOid, /* no collation */
5009 InvalidOid, /* no reg proc for this */
5010 (Datum) 0); /* constant */
5014 /* If min is requested ... */
5018 * In principle, we should scan the index with our current
5019 * active snapshot, which is the best approximation we've got
5020 * to what the query will see when executed. But that won't
5021 * be exact if a new snap is taken before running the query,
5022 * and it can be very expensive if a lot of uncommitted rows
5023 * exist at the end of the index (because we'll laboriously
5024 * fetch each one and reject it). What seems like a good
5025 * compromise is to use SnapshotDirty. That will accept
5026 * uncommitted rows, and thus avoid fetching multiple heap
5027 * tuples in this scenario. On the other hand, it will reject
5028 * known-dead rows, and thus not give a bogus answer when the
5029 * extreme value has been deleted; that case motivates not
5030 * using SnapshotAny here.
5032 index_scan = index_beginscan(heapRel, indexRel, &SnapshotDirty,
5034 index_rescan(index_scan, scankeys, 1, NULL, 0);
5036 /* Fetch first tuple in sortop's direction */
5037 if ((tup = index_getnext(index_scan,
5038 indexscandir)) != NULL)
5040 /* Extract the index column values from the heap tuple */
5041 ExecStoreTuple(tup, slot, InvalidBuffer, false);
5042 FormIndexDatum(indexInfo, slot, estate,
5045 /* Shouldn't have got a null, but be careful */
5047 elog(ERROR, "found unexpected null value in index \"%s\"",
5048 RelationGetRelationName(indexRel));
5050 /* Copy the index column value out to caller's context */
5051 MemoryContextSwitchTo(oldcontext);
5052 *min = datumCopy(values[0], typByVal, typLen);
5053 MemoryContextSwitchTo(tmpcontext);
5058 index_endscan(index_scan);
5061 /* If max is requested, and we didn't find the index is empty */
5062 if (max && have_data)
5064 index_scan = index_beginscan(heapRel, indexRel, &SnapshotDirty,
5066 index_rescan(index_scan, scankeys, 1, NULL, 0);
5068 /* Fetch first tuple in reverse direction */
5069 if ((tup = index_getnext(index_scan,
5070 -indexscandir)) != NULL)
5072 /* Extract the index column values from the heap tuple */
5073 ExecStoreTuple(tup, slot, InvalidBuffer, false);
5074 FormIndexDatum(indexInfo, slot, estate,
5077 /* Shouldn't have got a null, but be careful */
5079 elog(ERROR, "found unexpected null value in index \"%s\"",
5080 RelationGetRelationName(indexRel));
5082 /* Copy the index column value out to caller's context */
5083 MemoryContextSwitchTo(oldcontext);
5084 *max = datumCopy(values[0], typByVal, typLen);
5085 MemoryContextSwitchTo(tmpcontext);
5090 index_endscan(index_scan);
5093 /* Clean everything up */
5094 ExecDropSingleTupleTableSlot(slot);
5096 index_close(indexRel, AccessShareLock);
5097 heap_close(heapRel, NoLock);
5099 MemoryContextSwitchTo(oldcontext);
5100 FreeExecutorState(estate);
5102 /* And we're done */
5111 * find_join_input_rel
5112 * Look up the input relation for a join.
5114 * We assume that the input relation's RelOptInfo must have been constructed
5118 find_join_input_rel(PlannerInfo *root, Relids relids)
5120 RelOptInfo *rel = NULL;
5122 switch (bms_membership(relids))
5125 /* should not happen */
5128 rel = find_base_rel(root, bms_singleton_member(relids));
5131 rel = find_join_rel(root, relids);
5136 elog(ERROR, "could not find RelOptInfo for given relids");
5142 /*-------------------------------------------------------------------------
5144 * Pattern analysis functions
5146 * These routines support analysis of LIKE and regular-expression patterns
5147 * by the planner/optimizer. It's important that they agree with the
5148 * regular-expression code in backend/regex/ and the LIKE code in
5149 * backend/utils/adt/like.c. Also, the computation of the fixed prefix
5150 * must be conservative: if we report a string longer than the true fixed
5151 * prefix, the query may produce actually wrong answers, rather than just
5152 * getting a bad selectivity estimate!
5154 * Note that the prefix-analysis functions are called from
5155 * backend/optimizer/path/indxpath.c as well as from routines in this file.
5157 *-------------------------------------------------------------------------
5161 * Check whether char is a letter (and, hence, subject to case-folding)
5163 * In multibyte character sets, we can't use isalpha, and it does not seem
5164 * worth trying to convert to wchar_t to use iswalpha. Instead, just assume
5165 * any multibyte char is potentially case-varying.
5168 pattern_char_isalpha(char c, bool is_multibyte,
5169 pg_locale_t locale, bool locale_is_c)
5172 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
5173 else if (is_multibyte && IS_HIGHBIT_SET(c))
5175 #ifdef HAVE_LOCALE_T
5177 return isalpha_l((unsigned char) c, locale);
5180 return isalpha((unsigned char) c);
5184 * Extract the fixed prefix, if any, for a pattern.
5186 * *prefix is set to a palloc'd prefix string (in the form of a Const node),
5187 * or to NULL if no fixed prefix exists for the pattern.
5188 * If rest_selec is not NULL, *rest_selec is set to an estimate of the
5189 * selectivity of the remainder of the pattern (without any fixed prefix).
5190 * The prefix Const has the same type (TEXT or BYTEA) as the input pattern.
5192 * The return value distinguishes no fixed prefix, a partial prefix,
5193 * or an exact-match-only pattern.
5196 static Pattern_Prefix_Status
5197 like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
5198 Const **prefix_const, Selectivity *rest_selec)
5203 Oid typeid = patt_const->consttype;
5206 bool is_multibyte = (pg_database_encoding_max_length() > 1);
5207 pg_locale_t locale = 0;
5208 bool locale_is_c = false;
5210 /* the right-hand const is type text or bytea */
5211 Assert(typeid == BYTEAOID || typeid == TEXTOID);
5213 if (case_insensitive)
5215 if (typeid == BYTEAOID)
5217 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5218 errmsg("case insensitive matching not supported on type bytea")));
5220 /* If case-insensitive, we need locale info */
5221 if (lc_ctype_is_c(collation))
5223 else if (collation != DEFAULT_COLLATION_OID)
5225 if (!OidIsValid(collation))
5228 * This typically means that the parser could not resolve a
5229 * conflict of implicit collations, so report it that way.
5232 (errcode(ERRCODE_INDETERMINATE_COLLATION),
5233 errmsg("could not determine which collation to use for ILIKE"),
5234 errhint("Use the COLLATE clause to set the collation explicitly.")));
5236 locale = pg_newlocale_from_collation(collation);
5240 if (typeid != BYTEAOID)
5242 patt = TextDatumGetCString(patt_const->constvalue);
5243 pattlen = strlen(patt);
5247 bytea *bstr = DatumGetByteaP(patt_const->constvalue);
5249 pattlen = VARSIZE(bstr) - VARHDRSZ;
5250 patt = (char *) palloc(pattlen);
5251 memcpy(patt, VARDATA(bstr), pattlen);
5252 if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
5256 match = palloc(pattlen + 1);
5258 for (pos = 0; pos < pattlen; pos++)
5260 /* % and _ are wildcard characters in LIKE */
5261 if (patt[pos] == '%' ||
5265 /* Backslash escapes the next character */
5266 if (patt[pos] == '\\')
5273 /* Stop if case-varying character (it's sort of a wildcard) */
5274 if (case_insensitive &&
5275 pattern_char_isalpha(patt[pos], is_multibyte, locale, locale_is_c))
5278 match[match_pos++] = patt[pos];
5281 match[match_pos] = '\0';
5283 if (typeid != BYTEAOID)
5284 *prefix_const = string_to_const(match, typeid);
5286 *prefix_const = string_to_bytea_const(match, match_pos);
5288 if (rest_selec != NULL)
5289 *rest_selec = like_selectivity(&patt[pos], pattlen - pos,
5295 /* in LIKE, an empty pattern is an exact match! */
5297 return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
5300 return Pattern_Prefix_Partial;
5302 return Pattern_Prefix_None;
5305 static Pattern_Prefix_Status
5306 regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
5307 Const **prefix_const, Selectivity *rest_selec)
5309 Oid typeid = patt_const->consttype;
5314 * Should be unnecessary, there are no bytea regex operators defined. As
5315 * such, it should be noted that the rest of this function has *not* been
5316 * made safe for binary (possibly NULL containing) strings.
5318 if (typeid == BYTEAOID)
5320 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5321 errmsg("regular-expression matching not supported on type bytea")));
5323 /* Use the regexp machinery to extract the prefix, if any */
5324 prefix = regexp_fixed_prefix(DatumGetTextPP(patt_const->constvalue),
5325 case_insensitive, collation,
5330 *prefix_const = NULL;
5332 if (rest_selec != NULL)
5334 char *patt = TextDatumGetCString(patt_const->constvalue);
5336 *rest_selec = regex_selectivity(patt, strlen(patt),
5342 return Pattern_Prefix_None;
5345 *prefix_const = string_to_const(prefix, typeid);
5347 if (rest_selec != NULL)
5351 /* Exact match, so there's no additional selectivity */
5356 char *patt = TextDatumGetCString(patt_const->constvalue);
5358 *rest_selec = regex_selectivity(patt, strlen(patt),
5368 return Pattern_Prefix_Exact; /* pattern specifies exact match */
5370 return Pattern_Prefix_Partial;
5373 Pattern_Prefix_Status
5374 pattern_fixed_prefix(Const *patt, Pattern_Type ptype, Oid collation,
5375 Const **prefix, Selectivity *rest_selec)
5377 Pattern_Prefix_Status result;
5381 case Pattern_Type_Like:
5382 result = like_fixed_prefix(patt, false, collation,
5383 prefix, rest_selec);
5385 case Pattern_Type_Like_IC:
5386 result = like_fixed_prefix(patt, true, collation,
5387 prefix, rest_selec);
5389 case Pattern_Type_Regex:
5390 result = regex_fixed_prefix(patt, false, collation,
5391 prefix, rest_selec);
5393 case Pattern_Type_Regex_IC:
5394 result = regex_fixed_prefix(patt, true, collation,
5395 prefix, rest_selec);
5398 elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5399 result = Pattern_Prefix_None; /* keep compiler quiet */
5406 * Estimate the selectivity of a fixed prefix for a pattern match.
5408 * A fixed prefix "foo" is estimated as the selectivity of the expression
5409 * "variable >= 'foo' AND variable < 'fop'" (see also indxpath.c).
5411 * The selectivity estimate is with respect to the portion of the column
5412 * population represented by the histogram --- the caller must fold this
5413 * together with info about MCVs and NULLs.
5415 * We use the >= and < operators from the specified btree opfamily to do the
5416 * estimation. The given variable and Const must be of the associated
5419 * XXX Note: we make use of the upper bound to estimate operator selectivity
5420 * even if the locale is such that we cannot rely on the upper-bound string.
5421 * The selectivity only needs to be approximately right anyway, so it seems
5422 * more useful to use the upper-bound code than not.
5425 prefix_selectivity(PlannerInfo *root, VariableStatData *vardata,
5426 Oid vartype, Oid opfamily, Const *prefixcon)
5428 Selectivity prefixsel;
5431 Const *greaterstrcon;
5434 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5435 BTGreaterEqualStrategyNumber);
5436 if (cmpopr == InvalidOid)
5437 elog(ERROR, "no >= operator for opfamily %u", opfamily);
5438 fmgr_info(get_opcode(cmpopr), &opproc);
5440 prefixsel = ineq_histogram_selectivity(root, vardata, &opproc, true,
5441 prefixcon->constvalue,
5442 prefixcon->consttype);
5444 if (prefixsel < 0.0)
5446 /* No histogram is present ... return a suitable default estimate */
5447 return DEFAULT_MATCH_SEL;
5451 * If we can create a string larger than the prefix, say
5455 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5456 BTLessStrategyNumber);
5457 if (cmpopr == InvalidOid)
5458 elog(ERROR, "no < operator for opfamily %u", opfamily);
5459 fmgr_info(get_opcode(cmpopr), &opproc);
5460 greaterstrcon = make_greater_string(prefixcon, &opproc,
5461 DEFAULT_COLLATION_OID);
5466 topsel = ineq_histogram_selectivity(root, vardata, &opproc, false,
5467 greaterstrcon->constvalue,
5468 greaterstrcon->consttype);
5470 /* ineq_histogram_selectivity worked before, it shouldn't fail now */
5471 Assert(topsel >= 0.0);
5474 * Merge the two selectivities in the same way as for a range query
5475 * (see clauselist_selectivity()). Note that we don't need to worry
5476 * about double-exclusion of nulls, since ineq_histogram_selectivity
5477 * doesn't count those anyway.
5479 prefixsel = topsel + prefixsel - 1.0;
5483 * If the prefix is long then the two bounding values might be too close
5484 * together for the histogram to distinguish them usefully, resulting in a
5485 * zero estimate (plus or minus roundoff error). To avoid returning a
5486 * ridiculously small estimate, compute the estimated selectivity for
5487 * "variable = 'foo'", and clamp to that. (Obviously, the resultant
5488 * estimate should be at least that.)
5490 * We apply this even if we couldn't make a greater string. That case
5491 * suggests that the prefix is near the maximum possible, and thus
5492 * probably off the end of the histogram, and thus we probably got a very
5493 * small estimate from the >= condition; so we still need to clamp.
5495 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5496 BTEqualStrategyNumber);
5497 if (cmpopr == InvalidOid)
5498 elog(ERROR, "no = operator for opfamily %u", opfamily);
5499 eq_sel = var_eq_const(vardata, cmpopr, prefixcon->constvalue,
5502 prefixsel = Max(prefixsel, eq_sel);
5509 * Estimate the selectivity of a pattern of the specified type.
5510 * Note that any fixed prefix of the pattern will have been removed already,
5511 * so actually we may be looking at just a fragment of the pattern.
5513 * For now, we use a very simplistic approach: fixed characters reduce the
5514 * selectivity a good deal, character ranges reduce it a little,
5515 * wildcards (such as % for LIKE or .* for regex) increase it.
5518 #define FIXED_CHAR_SEL 0.20 /* about 1/5 */
5519 #define CHAR_RANGE_SEL 0.25
5520 #define ANY_CHAR_SEL 0.9 /* not 1, since it won't match end-of-string */
5521 #define FULL_WILDCARD_SEL 5.0
5522 #define PARTIAL_WILDCARD_SEL 2.0
5525 like_selectivity(const char *patt, int pattlen, bool case_insensitive)
5527 Selectivity sel = 1.0;
5530 /* Skip any leading wildcard; it's already factored into initial sel */
5531 for (pos = 0; pos < pattlen; pos++)
5533 if (patt[pos] != '%' && patt[pos] != '_')
5537 for (; pos < pattlen; pos++)
5539 /* % and _ are wildcard characters in LIKE */
5540 if (patt[pos] == '%')
5541 sel *= FULL_WILDCARD_SEL;
5542 else if (patt[pos] == '_')
5543 sel *= ANY_CHAR_SEL;
5544 else if (patt[pos] == '\\')
5546 /* Backslash quotes the next character */
5550 sel *= FIXED_CHAR_SEL;
5553 sel *= FIXED_CHAR_SEL;
5555 /* Could get sel > 1 if multiple wildcards */
5562 regex_selectivity_sub(const char *patt, int pattlen, bool case_insensitive)
5564 Selectivity sel = 1.0;
5565 int paren_depth = 0;
5566 int paren_pos = 0; /* dummy init to keep compiler quiet */
5569 for (pos = 0; pos < pattlen; pos++)
5571 if (patt[pos] == '(')
5573 if (paren_depth == 0)
5574 paren_pos = pos; /* remember start of parenthesized item */
5577 else if (patt[pos] == ')' && paren_depth > 0)
5580 if (paren_depth == 0)
5581 sel *= regex_selectivity_sub(patt + (paren_pos + 1),
5582 pos - (paren_pos + 1),
5585 else if (patt[pos] == '|' && paren_depth == 0)
5588 * If unquoted | is present at paren level 0 in pattern, we have
5589 * multiple alternatives; sum their probabilities.
5591 sel += regex_selectivity_sub(patt + (pos + 1),
5592 pattlen - (pos + 1),
5594 break; /* rest of pattern is now processed */
5596 else if (patt[pos] == '[')
5598 bool negclass = false;
5600 if (patt[++pos] == '^')
5605 if (patt[pos] == ']') /* ']' at start of class is not
5608 while (pos < pattlen && patt[pos] != ']')
5610 if (paren_depth == 0)
5611 sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
5613 else if (patt[pos] == '.')
5615 if (paren_depth == 0)
5616 sel *= ANY_CHAR_SEL;
5618 else if (patt[pos] == '*' ||
5622 /* Ought to be smarter about quantifiers... */
5623 if (paren_depth == 0)
5624 sel *= PARTIAL_WILDCARD_SEL;
5626 else if (patt[pos] == '{')
5628 while (pos < pattlen && patt[pos] != '}')
5630 if (paren_depth == 0)
5631 sel *= PARTIAL_WILDCARD_SEL;
5633 else if (patt[pos] == '\\')
5635 /* backslash quotes the next character */
5639 if (paren_depth == 0)
5640 sel *= FIXED_CHAR_SEL;
5644 if (paren_depth == 0)
5645 sel *= FIXED_CHAR_SEL;
5648 /* Could get sel > 1 if multiple wildcards */
5655 regex_selectivity(const char *patt, int pattlen, bool case_insensitive,
5656 int fixed_prefix_len)
5660 /* If patt doesn't end with $, consider it to have a trailing wildcard */
5661 if (pattlen > 0 && patt[pattlen - 1] == '$' &&
5662 (pattlen == 1 || patt[pattlen - 2] != '\\'))
5664 /* has trailing $ */
5665 sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
5670 sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
5671 sel *= FULL_WILDCARD_SEL;
5674 /* If there's a fixed prefix, discount its selectivity */
5675 if (fixed_prefix_len > 0)
5676 sel /= pow(FIXED_CHAR_SEL, fixed_prefix_len);
5678 /* Make sure result stays in range */
5679 CLAMP_PROBABILITY(sel);
5685 * For bytea, the increment function need only increment the current byte
5686 * (there are no multibyte characters to worry about).
5689 byte_increment(unsigned char *ptr, int len)
5698 * Try to generate a string greater than the given string or any
5699 * string it is a prefix of. If successful, return a palloc'd string
5700 * in the form of a Const node; else return NULL.
5702 * The caller must provide the appropriate "less than" comparison function
5703 * for testing the strings, along with the collation to use.
5705 * The key requirement here is that given a prefix string, say "foo",
5706 * we must be able to generate another string "fop" that is greater than
5707 * all strings "foobar" starting with "foo". We can test that we have
5708 * generated a string greater than the prefix string, but in non-C collations
5709 * that is not a bulletproof guarantee that an extension of the string might
5710 * not sort after it; an example is that "foo " is less than "foo!", but it
5711 * is not clear that a "dictionary" sort ordering will consider "foo!" less
5712 * than "foo bar". CAUTION: Therefore, this function should be used only for
5713 * estimation purposes when working in a non-C collation.
5715 * To try to catch most cases where an extended string might otherwise sort
5716 * before the result value, we determine which of the strings "Z", "z", "y",
5717 * and "9" is seen as largest by the collation, and append that to the given
5718 * prefix before trying to find a string that compares as larger.
5720 * To search for a greater string, we repeatedly "increment" the rightmost
5721 * character, using an encoding-specific character incrementer function.
5722 * When it's no longer possible to increment the last character, we truncate
5723 * off that character and start incrementing the next-to-rightmost.
5724 * For example, if "z" were the last character in the sort order, then we
5725 * could produce "foo" as a string greater than "fonz".
5727 * This could be rather slow in the worst case, but in most cases we
5728 * won't have to try more than one or two strings before succeeding.
5730 * Note that it's important for the character incrementer not to be too anal
5731 * about producing every possible character code, since in some cases the only
5732 * way to get a larger string is to increment a previous character position.
5733 * So we don't want to spend too much time trying every possible character
5734 * code at the last position. A good rule of thumb is to be sure that we
5735 * don't try more than 256*K values for a K-byte character (and definitely
5736 * not 256^K, which is what an exhaustive search would approach).
5739 make_greater_string(const Const *str_const, FmgrInfo *ltproc, Oid collation)
5741 Oid datatype = str_const->consttype;
5745 text *cmptxt = NULL;
5746 mbcharacter_incrementer charinc;
5749 * Get a modifiable copy of the prefix string in C-string format, and set
5750 * up the string we will compare to as a Datum. In C locale this can just
5751 * be the given prefix string, otherwise we need to add a suffix. Types
5752 * NAME and BYTEA sort bytewise so they don't need a suffix either.
5754 if (datatype == NAMEOID)
5756 workstr = DatumGetCString(DirectFunctionCall1(nameout,
5757 str_const->constvalue));
5758 len = strlen(workstr);
5759 cmpstr = str_const->constvalue;
5761 else if (datatype == BYTEAOID)
5763 bytea *bstr = DatumGetByteaP(str_const->constvalue);
5765 len = VARSIZE(bstr) - VARHDRSZ;
5766 workstr = (char *) palloc(len);
5767 memcpy(workstr, VARDATA(bstr), len);
5768 if ((Pointer) bstr != DatumGetPointer(str_const->constvalue))
5770 cmpstr = str_const->constvalue;
5774 workstr = TextDatumGetCString(str_const->constvalue);
5775 len = strlen(workstr);
5776 if (lc_collate_is_c(collation) || len == 0)
5777 cmpstr = str_const->constvalue;
5780 /* If first time through, determine the suffix to use */
5781 static char suffixchar = 0;
5782 static Oid suffixcollation = 0;
5784 if (!suffixchar || suffixcollation != collation)
5789 if (varstr_cmp(best, 1, "z", 1, collation) < 0)
5791 if (varstr_cmp(best, 1, "y", 1, collation) < 0)
5793 if (varstr_cmp(best, 1, "9", 1, collation) < 0)
5796 suffixcollation = collation;
5799 /* And build the string to compare to */
5800 cmptxt = (text *) palloc(VARHDRSZ + len + 1);
5801 SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
5802 memcpy(VARDATA(cmptxt), workstr, len);
5803 *(VARDATA(cmptxt) + len) = suffixchar;
5804 cmpstr = PointerGetDatum(cmptxt);
5808 /* Select appropriate character-incrementer function */
5809 if (datatype == BYTEAOID)
5810 charinc = byte_increment;
5812 charinc = pg_database_encoding_character_incrementer();
5814 /* And search ... */
5818 unsigned char *lastchar;
5820 /* Identify the last character --- for bytea, just the last byte */
5821 if (datatype == BYTEAOID)
5824 charlen = len - pg_mbcliplen(workstr, len, len - 1);
5825 lastchar = (unsigned char *) (workstr + len - charlen);
5828 * Try to generate a larger string by incrementing the last character
5829 * (for BYTEA, we treat each byte as a character).
5831 * Note: the incrementer function is expected to return true if it's
5832 * generated a valid-per-the-encoding new character, otherwise false.
5833 * The contents of the character on false return are unspecified.
5835 while (charinc(lastchar, charlen))
5837 Const *workstr_const;
5839 if (datatype == BYTEAOID)
5840 workstr_const = string_to_bytea_const(workstr, len);
5842 workstr_const = string_to_const(workstr, datatype);
5844 if (DatumGetBool(FunctionCall2Coll(ltproc,
5847 workstr_const->constvalue)))
5849 /* Successfully made a string larger than cmpstr */
5853 return workstr_const;
5856 /* No good, release unusable value and try again */
5857 pfree(DatumGetPointer(workstr_const->constvalue));
5858 pfree(workstr_const);
5862 * No luck here, so truncate off the last character and try to
5863 * increment the next one.
5866 workstr[len] = '\0';
5878 * Generate a Datum of the appropriate type from a C string.
5879 * Note that all of the supported types are pass-by-ref, so the
5880 * returned value should be pfree'd if no longer needed.
5883 string_to_datum(const char *str, Oid datatype)
5885 Assert(str != NULL);
5888 * We cheat a little by assuming that CStringGetTextDatum() will do for
5889 * bpchar and varchar constants too...
5891 if (datatype == NAMEOID)
5892 return DirectFunctionCall1(namein, CStringGetDatum(str));
5893 else if (datatype == BYTEAOID)
5894 return DirectFunctionCall1(byteain, CStringGetDatum(str));
5896 return CStringGetTextDatum(str);
5900 * Generate a Const node of the appropriate type from a C string.
5903 string_to_const(const char *str, Oid datatype)
5905 Datum conval = string_to_datum(str, datatype);
5910 * We only need to support a few datatypes here, so hard-wire properties
5911 * instead of incurring the expense of catalog lookups.
5918 collation = DEFAULT_COLLATION_OID;
5923 collation = InvalidOid;
5924 constlen = NAMEDATALEN;
5928 collation = InvalidOid;
5933 elog(ERROR, "unexpected datatype in string_to_const: %u",
5938 return makeConst(datatype, -1, collation, constlen,
5939 conval, false, false);
5943 * Generate a Const node of bytea type from a binary C string and a length.
5946 string_to_bytea_const(const char *str, size_t str_len)
5948 bytea *bstr = palloc(VARHDRSZ + str_len);
5951 memcpy(VARDATA(bstr), str, str_len);
5952 SET_VARSIZE(bstr, VARHDRSZ + str_len);
5953 conval = PointerGetDatum(bstr);
5955 return makeConst(BYTEAOID, -1, InvalidOid, -1, conval, false, false);
5958 /*-------------------------------------------------------------------------
5960 * Index cost estimation functions
5962 *-------------------------------------------------------------------------
5966 * deconstruct_indexquals is a simple function to examine the indexquals
5967 * attached to a proposed IndexPath. It returns a list of IndexQualInfo
5968 * structs, one per qual expression.
5972 RestrictInfo *rinfo; /* the indexqual itself */
5973 int indexcol; /* zero-based index column number */
5974 bool varonleft; /* true if index column is on left of qual */
5975 Oid clause_op; /* qual's operator OID, if relevant */
5976 Node *other_operand; /* non-index operand of qual's operator */
5980 deconstruct_indexquals(IndexPath *path)
5983 IndexOptInfo *index = path->indexinfo;
5987 forboth(lcc, path->indexquals, lci, path->indexqualcols)
5989 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
5990 int indexcol = lfirst_int(lci);
5994 IndexQualInfo *qinfo;
5996 Assert(IsA(rinfo, RestrictInfo));
5997 clause = rinfo->clause;
5999 qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6000 qinfo->rinfo = rinfo;
6001 qinfo->indexcol = indexcol;
6003 if (IsA(clause, OpExpr))
6005 qinfo->clause_op = ((OpExpr *) clause)->opno;
6006 leftop = get_leftop(clause);
6007 rightop = get_rightop(clause);
6008 if (match_index_to_operand(leftop, indexcol, index))
6010 qinfo->varonleft = true;
6011 qinfo->other_operand = rightop;
6015 Assert(match_index_to_operand(rightop, indexcol, index));
6016 qinfo->varonleft = false;
6017 qinfo->other_operand = leftop;
6020 else if (IsA(clause, RowCompareExpr))
6022 RowCompareExpr *rc = (RowCompareExpr *) clause;
6024 qinfo->clause_op = linitial_oid(rc->opnos);
6025 /* Examine only first columns to determine left/right sides */
6026 if (match_index_to_operand((Node *) linitial(rc->largs),
6029 qinfo->varonleft = true;
6030 qinfo->other_operand = (Node *) rc->rargs;
6034 Assert(match_index_to_operand((Node *) linitial(rc->rargs),
6036 qinfo->varonleft = false;
6037 qinfo->other_operand = (Node *) rc->largs;
6040 else if (IsA(clause, ScalarArrayOpExpr))
6042 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6044 qinfo->clause_op = saop->opno;
6045 /* index column is always on the left in this case */
6046 Assert(match_index_to_operand((Node *) linitial(saop->args),
6048 qinfo->varonleft = true;
6049 qinfo->other_operand = (Node *) lsecond(saop->args);
6051 else if (IsA(clause, NullTest))
6053 qinfo->clause_op = InvalidOid;
6054 Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6056 qinfo->varonleft = true;
6057 qinfo->other_operand = NULL;
6061 elog(ERROR, "unsupported indexqual type: %d",
6062 (int) nodeTag(clause));
6065 result = lappend(result, qinfo);
6071 * Simple function to compute the total eval cost of the "other operands"
6072 * in an IndexQualInfo list. Since we know these will be evaluated just
6073 * once per scan, there's no need to distinguish startup from per-row cost.
6076 other_operands_eval_cost(PlannerInfo *root, List *qinfos)
6078 Cost qual_arg_cost = 0;
6083 IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(lc);
6084 QualCost index_qual_cost;
6086 cost_qual_eval_node(&index_qual_cost, qinfo->other_operand, root);
6087 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6089 return qual_arg_cost;
6093 * Get other-operand eval cost for an index orderby list.
6095 * Index orderby expressions aren't represented as RestrictInfos (since they
6096 * aren't boolean, usually). So we can't apply deconstruct_indexquals to
6097 * them. However, they are much simpler to deal with since they are always
6098 * OpExprs and the index column is always on the left.
6101 orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
6103 Cost qual_arg_cost = 0;
6106 foreach(lc, path->indexorderbys)
6108 Expr *clause = (Expr *) lfirst(lc);
6109 Node *other_operand;
6110 QualCost index_qual_cost;
6112 if (IsA(clause, OpExpr))
6114 other_operand = get_rightop(clause);
6118 elog(ERROR, "unsupported indexorderby type: %d",
6119 (int) nodeTag(clause));
6120 other_operand = NULL; /* keep compiler quiet */
6123 cost_qual_eval_node(&index_qual_cost, other_operand, root);
6124 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6126 return qual_arg_cost;
6130 * genericcostestimate is a general-purpose estimator that can be used for
6131 * most index types. In some cases we use genericcostestimate as the base
6132 * code and then incorporate additional index-type-specific knowledge in
6133 * the type-specific calling function. To avoid code duplication, we make
6134 * genericcostestimate return a number of intermediate values as well as
6135 * its preliminary estimates of the output cost values. The GenericCosts
6136 * struct includes all these values.
6138 * Callers should initialize all fields of GenericCosts to zero. In addition,
6139 * they can set numIndexTuples to some positive value if they have a better
6140 * than default way of estimating the number of leaf index tuples visited.
6144 /* These are the values the cost estimator must return to the planner */
6145 Cost indexStartupCost; /* index-related startup cost */
6146 Cost indexTotalCost; /* total index-related scan cost */
6147 Selectivity indexSelectivity; /* selectivity of index */
6148 double indexCorrelation; /* order correlation of index */
6150 /* Intermediate values we obtain along the way */
6151 double numIndexPages; /* number of leaf pages visited */
6152 double numIndexTuples; /* number of leaf tuples visited */
6153 double spc_random_page_cost; /* relevant random_page_cost value */
6154 double num_sa_scans; /* # indexscans from ScalarArrayOps */
6158 genericcostestimate(PlannerInfo *root,
6162 GenericCosts *costs)
6164 IndexOptInfo *index = path->indexinfo;
6165 List *indexQuals = path->indexquals;
6166 List *indexOrderBys = path->indexorderbys;
6167 Cost indexStartupCost;
6168 Cost indexTotalCost;
6169 Selectivity indexSelectivity;
6170 double indexCorrelation;
6171 double numIndexPages;
6172 double numIndexTuples;
6173 double spc_random_page_cost;
6174 double num_sa_scans;
6175 double num_outer_scans;
6177 double qual_op_cost;
6178 double qual_arg_cost;
6179 List *selectivityQuals;
6183 * If the index is partial, AND the index predicate with the explicitly
6184 * given indexquals to produce a more accurate idea of the index
6187 selectivityQuals = add_predicate_to_quals(index, indexQuals);
6190 * Check for ScalarArrayOpExpr index quals, and estimate the number of
6191 * index scans that will be performed.
6194 foreach(l, indexQuals)
6196 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6198 if (IsA(rinfo->clause, ScalarArrayOpExpr))
6200 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6201 int alength = estimate_array_length(lsecond(saop->args));
6204 num_sa_scans *= alength;
6208 /* Estimate the fraction of main-table tuples that will be visited */
6209 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6215 * If caller didn't give us an estimate, estimate the number of index
6216 * tuples that will be visited. We do it in this rather peculiar-looking
6217 * way in order to get the right answer for partial indexes.
6219 numIndexTuples = costs->numIndexTuples;
6220 if (numIndexTuples <= 0.0)
6222 numIndexTuples = indexSelectivity * index->rel->tuples;
6225 * The above calculation counts all the tuples visited across all
6226 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6227 * average per-indexscan number, so adjust. This is a handy place to
6228 * round to integer, too. (If caller supplied tuple estimate, it's
6229 * responsible for handling these considerations.)
6231 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6235 * We can bound the number of tuples by the index size in any case. Also,
6236 * always estimate at least one tuple is touched, even when
6237 * indexSelectivity estimate is tiny.
6239 if (numIndexTuples > index->tuples)
6240 numIndexTuples = index->tuples;
6241 if (numIndexTuples < 1.0)
6242 numIndexTuples = 1.0;
6245 * Estimate the number of index pages that will be retrieved.
6247 * We use the simplistic method of taking a pro-rata fraction of the total
6248 * number of index pages. In effect, this counts only leaf pages and not
6249 * any overhead such as index metapage or upper tree levels.
6251 * In practice access to upper index levels is often nearly free because
6252 * those tend to stay in cache under load; moreover, the cost involved is
6253 * highly dependent on index type. We therefore ignore such costs here
6254 * and leave it to the caller to add a suitable charge if needed.
6256 if (index->pages > 1 && index->tuples > 1)
6257 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6259 numIndexPages = 1.0;
6261 /* fetch estimated page cost for tablespace containing index */
6262 get_tablespace_page_costs(index->reltablespace,
6263 &spc_random_page_cost,
6267 * Now compute the disk access costs.
6269 * The above calculations are all per-index-scan. However, if we are in a
6270 * nestloop inner scan, we can expect the scan to be repeated (with
6271 * different search keys) for each row of the outer relation. Likewise,
6272 * ScalarArrayOpExpr quals result in multiple index scans. This creates
6273 * the potential for cache effects to reduce the number of disk page
6274 * fetches needed. We want to estimate the average per-scan I/O cost in
6275 * the presence of caching.
6277 * We use the Mackert-Lohman formula (see costsize.c for details) to
6278 * estimate the total number of page fetches that occur. While this
6279 * wasn't what it was designed for, it seems a reasonable model anyway.
6280 * Note that we are counting pages not tuples anymore, so we take N = T =
6281 * index size, as if there were one "tuple" per page.
6283 num_outer_scans = loop_count;
6284 num_scans = num_sa_scans * num_outer_scans;
6288 double pages_fetched;
6290 /* total page fetches ignoring cache effects */
6291 pages_fetched = numIndexPages * num_scans;
6293 /* use Mackert and Lohman formula to adjust for cache effects */
6294 pages_fetched = index_pages_fetched(pages_fetched,
6296 (double) index->pages,
6300 * Now compute the total disk access cost, and then report a pro-rated
6301 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6302 * since that's internal to the indexscan.)
6304 indexTotalCost = (pages_fetched * spc_random_page_cost)
6310 * For a single index scan, we just charge spc_random_page_cost per
6313 indexTotalCost = numIndexPages * spc_random_page_cost;
6317 * CPU cost: any complex expressions in the indexquals will need to be
6318 * evaluated once at the start of the scan to reduce them to runtime keys
6319 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6320 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6321 * indexqual operator. Because we have numIndexTuples as a per-scan
6322 * number, we have to multiply by num_sa_scans to get the correct result
6323 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6324 * ORDER BY expressions.
6326 * Note: this neglects the possible costs of rechecking lossy operators.
6327 * Detecting that that might be needed seems more expensive than it's
6328 * worth, though, considering all the other inaccuracies here ...
6330 qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6331 orderby_operands_eval_cost(root, path);
6332 qual_op_cost = cpu_operator_cost *
6333 (list_length(indexQuals) + list_length(indexOrderBys));
6335 indexStartupCost = qual_arg_cost;
6336 indexTotalCost += qual_arg_cost;
6337 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6340 * Generic assumption about index correlation: there isn't any.
6342 indexCorrelation = 0.0;
6345 * Return everything to caller.
6347 costs->indexStartupCost = indexStartupCost;
6348 costs->indexTotalCost = indexTotalCost;
6349 costs->indexSelectivity = indexSelectivity;
6350 costs->indexCorrelation = indexCorrelation;
6351 costs->numIndexPages = numIndexPages;
6352 costs->numIndexTuples = numIndexTuples;
6353 costs->spc_random_page_cost = spc_random_page_cost;
6354 costs->num_sa_scans = num_sa_scans;
6358 * If the index is partial, add its predicate to the given qual list.
6360 * ANDing the index predicate with the explicitly given indexquals produces
6361 * a more accurate idea of the index's selectivity. However, we need to be
6362 * careful not to insert redundant clauses, because clauselist_selectivity()
6363 * is easily fooled into computing a too-low selectivity estimate. Our
6364 * approach is to add only the predicate clause(s) that cannot be proven to
6365 * be implied by the given indexquals. This successfully handles cases such
6366 * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
6367 * There are many other cases where we won't detect redundancy, leading to a
6368 * too-low selectivity estimate, which will bias the system in favor of using
6369 * partial indexes where possible. That is not necessarily bad though.
6371 * Note that indexQuals contains RestrictInfo nodes while the indpred
6372 * does not, so the output list will be mixed. This is OK for both
6373 * predicate_implied_by() and clauselist_selectivity(), but might be
6374 * problematic if the result were passed to other things.
6377 add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
6379 List *predExtraQuals = NIL;
6382 if (index->indpred == NIL)
6385 foreach(lc, index->indpred)
6387 Node *predQual = (Node *) lfirst(lc);
6388 List *oneQual = list_make1(predQual);
6390 if (!predicate_implied_by(oneQual, indexQuals))
6391 predExtraQuals = list_concat(predExtraQuals, oneQual);
6393 /* list_concat avoids modifying the passed-in indexQuals list */
6394 return list_concat(predExtraQuals, indexQuals);
6399 btcostestimate(PG_FUNCTION_ARGS)
6401 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6402 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6403 double loop_count = PG_GETARG_FLOAT8(2);
6404 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6405 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6406 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6407 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6408 IndexOptInfo *index = path->indexinfo;
6413 VariableStatData vardata;
6414 double numIndexTuples;
6416 List *indexBoundQuals;
6420 bool found_is_null_op;
6421 double num_sa_scans;
6424 /* Do preliminary analysis of indexquals */
6425 qinfos = deconstruct_indexquals(path);
6428 * For a btree scan, only leading '=' quals plus inequality quals for the
6429 * immediately next attribute contribute to index selectivity (these are
6430 * the "boundary quals" that determine the starting and stopping points of
6431 * the index scan). Additional quals can suppress visits to the heap, so
6432 * it's OK to count them in indexSelectivity, but they should not count
6433 * for estimating numIndexTuples. So we must examine the given indexquals
6434 * to find out which ones count as boundary quals. We rely on the
6435 * knowledge that they are given in index column order.
6437 * For a RowCompareExpr, we consider only the first column, just as
6438 * rowcomparesel() does.
6440 * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6441 * index scans not one, but the ScalarArrayOpExpr's operator can be
6442 * considered to act the same as it normally does.
6444 indexBoundQuals = NIL;
6448 found_is_null_op = false;
6452 IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(lc);
6453 RestrictInfo *rinfo = qinfo->rinfo;
6454 Expr *clause = rinfo->clause;
6458 if (indexcol != qinfo->indexcol)
6460 /* Beginning of a new column's quals */
6462 break; /* done if no '=' qual for indexcol */
6465 if (indexcol != qinfo->indexcol)
6466 break; /* no quals at all for indexcol */
6469 if (IsA(clause, ScalarArrayOpExpr))
6471 int alength = estimate_array_length(qinfo->other_operand);
6474 /* count up number of SA scans induced by indexBoundQuals only */
6476 num_sa_scans *= alength;
6478 else if (IsA(clause, NullTest))
6480 NullTest *nt = (NullTest *) clause;
6482 if (nt->nulltesttype == IS_NULL)
6484 found_is_null_op = true;
6485 /* IS NULL is like = for selectivity determination purposes */
6491 * We would need to commute the clause_op if not varonleft, except
6492 * that we only care if it's equality or not, so that refinement is
6495 clause_op = qinfo->clause_op;
6497 /* check for equality operator */
6498 if (OidIsValid(clause_op))
6500 op_strategy = get_op_opfamily_strategy(clause_op,
6501 index->opfamily[indexcol]);
6502 Assert(op_strategy != 0); /* not a member of opfamily?? */
6503 if (op_strategy == BTEqualStrategyNumber)
6507 indexBoundQuals = lappend(indexBoundQuals, rinfo);
6511 * If index is unique and we found an '=' clause for each column, we can
6512 * just assume numIndexTuples = 1 and skip the expensive
6513 * clauselist_selectivity calculations. However, a ScalarArrayOp or
6514 * NullTest invalidates that theory, even though it sets eqQualHere.
6516 if (index->unique &&
6517 indexcol == index->ncolumns - 1 &&
6521 numIndexTuples = 1.0;
6524 List *selectivityQuals;
6525 Selectivity btreeSelectivity;
6528 * If the index is partial, AND the index predicate with the
6529 * index-bound quals to produce a more accurate idea of the number of
6530 * rows covered by the bound conditions.
6532 selectivityQuals = add_predicate_to_quals(index, indexBoundQuals);
6534 btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6538 numIndexTuples = btreeSelectivity * index->rel->tuples;
6541 * As in genericcostestimate(), we have to adjust for any
6542 * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6545 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6549 * Now do generic index cost estimation.
6551 MemSet(&costs, 0, sizeof(costs));
6552 costs.numIndexTuples = numIndexTuples;
6554 genericcostestimate(root, path, loop_count, qinfos, &costs);
6557 * Add a CPU-cost component to represent the costs of initial btree
6558 * descent. We don't charge any I/O cost for touching upper btree levels,
6559 * since they tend to stay in cache, but we still have to do about log2(N)
6560 * comparisons to descend a btree of N leaf tuples. We charge one
6561 * cpu_operator_cost per comparison.
6563 * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6564 * ones after the first one are not startup cost so far as the overall
6565 * plan is concerned, so add them only to "total" cost.
6567 if (index->tuples > 1) /* avoid computing log(0) */
6569 descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6570 costs.indexStartupCost += descentCost;
6571 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6575 * Even though we're not charging I/O cost for touching upper btree pages,
6576 * it's still reasonable to charge some CPU cost per page descended
6577 * through. Moreover, if we had no such charge at all, bloated indexes
6578 * would appear to have the same search cost as unbloated ones, at least
6579 * in cases where only a single leaf page is expected to be visited. This
6580 * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6581 * touched. The number of such pages is btree tree height plus one (ie,
6582 * we charge for the leaf page too). As above, charge once per SA scan.
6584 descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6585 costs.indexStartupCost += descentCost;
6586 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6589 * If we can get an estimate of the first column's ordering correlation C
6590 * from pg_statistic, estimate the index correlation as C for a
6591 * single-column index, or C * 0.75 for multiple columns. (The idea here
6592 * is that multiple columns dilute the importance of the first column's
6593 * ordering, but don't negate it entirely. Before 8.0 we divided the
6594 * correlation by the number of columns, but that seems too strong.)
6596 MemSet(&vardata, 0, sizeof(vardata));
6598 if (index->indexkeys[0] != 0)
6600 /* Simple variable --- look to stats for the underlying table */
6601 RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6603 Assert(rte->rtekind == RTE_RELATION);
6605 Assert(relid != InvalidOid);
6606 colnum = index->indexkeys[0];
6608 if (get_relation_stats_hook &&
6609 (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6612 * The hook took control of acquiring a stats tuple. If it did
6613 * supply a tuple, it'd better have supplied a freefunc.
6615 if (HeapTupleIsValid(vardata.statsTuple) &&
6617 elog(ERROR, "no function provided to release variable stats with");
6621 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6622 ObjectIdGetDatum(relid),
6623 Int16GetDatum(colnum),
6624 BoolGetDatum(rte->inh));
6625 vardata.freefunc = ReleaseSysCache;
6630 /* Expression --- maybe there are stats for the index itself */
6631 relid = index->indexoid;
6634 if (get_index_stats_hook &&
6635 (*get_index_stats_hook) (root, relid, colnum, &vardata))
6638 * The hook took control of acquiring a stats tuple. If it did
6639 * supply a tuple, it'd better have supplied a freefunc.
6641 if (HeapTupleIsValid(vardata.statsTuple) &&
6643 elog(ERROR, "no function provided to release variable stats with");
6647 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6648 ObjectIdGetDatum(relid),
6649 Int16GetDatum(colnum),
6650 BoolGetDatum(false));
6651 vardata.freefunc = ReleaseSysCache;
6655 if (HeapTupleIsValid(vardata.statsTuple))
6661 sortop = get_opfamily_member(index->opfamily[0],
6662 index->opcintype[0],
6663 index->opcintype[0],
6664 BTLessStrategyNumber);
6665 if (OidIsValid(sortop) &&
6666 get_attstatsslot(vardata.statsTuple, InvalidOid, 0,
6667 STATISTIC_KIND_CORRELATION,
6671 &numbers, &nnumbers))
6673 double varCorrelation;
6675 Assert(nnumbers == 1);
6676 varCorrelation = numbers[0];
6678 if (index->reverse_sort[0])
6679 varCorrelation = -varCorrelation;
6681 if (index->ncolumns > 1)
6682 costs.indexCorrelation = varCorrelation * 0.75;
6684 costs.indexCorrelation = varCorrelation;
6686 free_attstatsslot(InvalidOid, NULL, 0, numbers, nnumbers);
6690 ReleaseVariableStats(vardata);
6692 *indexStartupCost = costs.indexStartupCost;
6693 *indexTotalCost = costs.indexTotalCost;
6694 *indexSelectivity = costs.indexSelectivity;
6695 *indexCorrelation = costs.indexCorrelation;
6701 hashcostestimate(PG_FUNCTION_ARGS)
6703 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6704 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6705 double loop_count = PG_GETARG_FLOAT8(2);
6706 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6707 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6708 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6709 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6713 /* Do preliminary analysis of indexquals */
6714 qinfos = deconstruct_indexquals(path);
6716 MemSet(&costs, 0, sizeof(costs));
6718 genericcostestimate(root, path, loop_count, qinfos, &costs);
6721 * A hash index has no descent costs as such, since the index AM can go
6722 * directly to the target bucket after computing the hash value. There
6723 * are a couple of other hash-specific costs that we could conceivably add
6726 * Ideally we'd charge spc_random_page_cost for each page in the target
6727 * bucket, not just the numIndexPages pages that genericcostestimate
6728 * thought we'd visit. However in most cases we don't know which bucket
6729 * that will be. There's no point in considering the average bucket size
6730 * because the hash AM makes sure that's always one page.
6732 * Likewise, we could consider charging some CPU for each index tuple in
6733 * the bucket, if we knew how many there were. But the per-tuple cost is
6734 * just a hash value comparison, not a general datatype-dependent
6735 * comparison, so any such charge ought to be quite a bit less than
6736 * cpu_operator_cost; which makes it probably not worth worrying about.
6738 * A bigger issue is that chance hash-value collisions will result in
6739 * wasted probes into the heap. We don't currently attempt to model this
6740 * cost on the grounds that it's rare, but maybe it's not rare enough.
6741 * (Any fix for this ought to consider the generic lossy-operator problem,
6742 * though; it's not entirely hash-specific.)
6745 *indexStartupCost = costs.indexStartupCost;
6746 *indexTotalCost = costs.indexTotalCost;
6747 *indexSelectivity = costs.indexSelectivity;
6748 *indexCorrelation = costs.indexCorrelation;
6754 gistcostestimate(PG_FUNCTION_ARGS)
6756 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6757 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6758 double loop_count = PG_GETARG_FLOAT8(2);
6759 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6760 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6761 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6762 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6763 IndexOptInfo *index = path->indexinfo;
6768 /* Do preliminary analysis of indexquals */
6769 qinfos = deconstruct_indexquals(path);
6771 MemSet(&costs, 0, sizeof(costs));
6773 genericcostestimate(root, path, loop_count, qinfos, &costs);
6776 * We model index descent costs similarly to those for btree, but to do
6777 * that we first need an idea of the tree height. We somewhat arbitrarily
6778 * assume that the fanout is 100, meaning the tree height is at most
6779 * log100(index->pages).
6781 * Although this computation isn't really expensive enough to require
6782 * caching, we might as well use index->tree_height to cache it.
6784 if (index->tree_height < 0) /* unknown? */
6786 if (index->pages > 1) /* avoid computing log(0) */
6787 index->tree_height = (int) (log(index->pages) / log(100.0));
6789 index->tree_height = 0;
6793 * Add a CPU-cost component to represent the costs of initial descent. We
6794 * just use log(N) here not log2(N) since the branching factor isn't
6795 * necessarily two anyway. As for btree, charge once per SA scan.
6797 if (index->tuples > 1) /* avoid computing log(0) */
6799 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6800 costs.indexStartupCost += descentCost;
6801 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6805 * Likewise add a per-page charge, calculated the same as for btrees.
6807 descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6808 costs.indexStartupCost += descentCost;
6809 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6811 *indexStartupCost = costs.indexStartupCost;
6812 *indexTotalCost = costs.indexTotalCost;
6813 *indexSelectivity = costs.indexSelectivity;
6814 *indexCorrelation = costs.indexCorrelation;
6820 spgcostestimate(PG_FUNCTION_ARGS)
6822 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6823 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6824 double loop_count = PG_GETARG_FLOAT8(2);
6825 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6826 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6827 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6828 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6829 IndexOptInfo *index = path->indexinfo;
6834 /* Do preliminary analysis of indexquals */
6835 qinfos = deconstruct_indexquals(path);
6837 MemSet(&costs, 0, sizeof(costs));
6839 genericcostestimate(root, path, loop_count, qinfos, &costs);
6842 * We model index descent costs similarly to those for btree, but to do
6843 * that we first need an idea of the tree height. We somewhat arbitrarily
6844 * assume that the fanout is 100, meaning the tree height is at most
6845 * log100(index->pages).
6847 * Although this computation isn't really expensive enough to require
6848 * caching, we might as well use index->tree_height to cache it.
6850 if (index->tree_height < 0) /* unknown? */
6852 if (index->pages > 1) /* avoid computing log(0) */
6853 index->tree_height = (int) (log(index->pages) / log(100.0));
6855 index->tree_height = 0;
6859 * Add a CPU-cost component to represent the costs of initial descent. We
6860 * just use log(N) here not log2(N) since the branching factor isn't
6861 * necessarily two anyway. As for btree, charge once per SA scan.
6863 if (index->tuples > 1) /* avoid computing log(0) */
6865 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6866 costs.indexStartupCost += descentCost;
6867 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6871 * Likewise add a per-page charge, calculated the same as for btrees.
6873 descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6874 costs.indexStartupCost += descentCost;
6875 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6877 *indexStartupCost = costs.indexStartupCost;
6878 *indexTotalCost = costs.indexTotalCost;
6879 *indexSelectivity = costs.indexSelectivity;
6880 *indexCorrelation = costs.indexCorrelation;
6887 * Support routines for gincostestimate
6893 double partialEntries;
6894 double exactEntries;
6895 double searchEntries;
6900 * Estimate the number of index terms that need to be searched for while
6901 * testing the given GIN query, and increment the counts in *counts
6902 * appropriately. If the query is unsatisfiable, return false.
6905 gincost_pattern(IndexOptInfo *index, int indexcol,
6906 Oid clause_op, Datum query,
6907 GinQualCounts *counts)
6915 bool *partial_matches = NULL;
6916 Pointer *extra_data = NULL;
6917 bool *nullFlags = NULL;
6918 int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
6922 * Get the operator's strategy number and declared input data types within
6923 * the index opfamily. (We don't need the latter, but we use
6924 * get_op_opfamily_properties because it will throw error if it fails to
6925 * find a matching pg_amop entry.)
6927 get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
6928 &strategy_op, &lefttype, &righttype);
6931 * GIN always uses the "default" support functions, which are those with
6932 * lefttype == righttype == the opclass' opcintype (see
6933 * IndexSupportInitialize in relcache.c).
6935 extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
6936 index->opcintype[indexcol],
6937 index->opcintype[indexcol],
6938 GIN_EXTRACTQUERY_PROC);
6940 if (!OidIsValid(extractProcOid))
6942 /* should not happen; throw same error as index_getprocinfo */
6943 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
6944 GIN_EXTRACTQUERY_PROC, indexcol + 1,
6945 get_rel_name(index->indexoid));
6949 * Choose collation to pass to extractProc (should match initGinState).
6951 if (OidIsValid(index->indexcollations[indexcol]))
6952 collation = index->indexcollations[indexcol];
6954 collation = DEFAULT_COLLATION_OID;
6956 OidFunctionCall7Coll(extractProcOid,
6959 PointerGetDatum(&nentries),
6960 UInt16GetDatum(strategy_op),
6961 PointerGetDatum(&partial_matches),
6962 PointerGetDatum(&extra_data),
6963 PointerGetDatum(&nullFlags),
6964 PointerGetDatum(&searchMode));
6966 if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
6968 /* No match is possible */
6972 for (i = 0; i < nentries; i++)
6975 * For partial match we haven't any information to estimate number of
6976 * matched entries in index, so, we just estimate it as 100
6978 if (partial_matches && partial_matches[i])
6979 counts->partialEntries += 100;
6981 counts->exactEntries++;
6983 counts->searchEntries++;
6986 if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
6988 /* Treat "include empty" like an exact-match item */
6989 counts->exactEntries++;
6990 counts->searchEntries++;
6992 else if (searchMode != GIN_SEARCH_MODE_DEFAULT)
6994 /* It's GIN_SEARCH_MODE_ALL */
6995 counts->haveFullScan = true;
7002 * Estimate the number of index terms that need to be searched for while
7003 * testing the given GIN index clause, and increment the counts in *counts
7004 * appropriately. If the query is unsatisfiable, return false.
7007 gincost_opexpr(PlannerInfo *root,
7008 IndexOptInfo *index,
7009 IndexQualInfo *qinfo,
7010 GinQualCounts *counts)
7012 int indexcol = qinfo->indexcol;
7013 Oid clause_op = qinfo->clause_op;
7014 Node *operand = qinfo->other_operand;
7016 if (!qinfo->varonleft)
7018 /* must commute the operator */
7019 clause_op = get_commutator(clause_op);
7022 /* aggressively reduce to a constant, and look through relabeling */
7023 operand = estimate_expression_value(root, operand);
7025 if (IsA(operand, RelabelType))
7026 operand = (Node *) ((RelabelType *) operand)->arg;
7029 * It's impossible to call extractQuery method for unknown operand. So
7030 * unless operand is a Const we can't do much; just assume there will be
7031 * one ordinary search entry from the operand at runtime.
7033 if (!IsA(operand, Const))
7035 counts->exactEntries++;
7036 counts->searchEntries++;
7040 /* If Const is null, there can be no matches */
7041 if (((Const *) operand)->constisnull)
7044 /* Otherwise, apply extractQuery and get the actual term counts */
7045 return gincost_pattern(index, indexcol, clause_op,
7046 ((Const *) operand)->constvalue,
7051 * Estimate the number of index terms that need to be searched for while
7052 * testing the given GIN index clause, and increment the counts in *counts
7053 * appropriately. If the query is unsatisfiable, return false.
7055 * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
7056 * each of which involves one value from the RHS array, plus all the
7057 * non-array quals (if any). To model this, we average the counts across
7058 * the RHS elements, and add the averages to the counts in *counts (which
7059 * correspond to per-indexscan costs). We also multiply counts->arrayScans
7060 * by N, causing gincostestimate to scale up its estimates accordingly.
7063 gincost_scalararrayopexpr(PlannerInfo *root,
7064 IndexOptInfo *index,
7065 IndexQualInfo *qinfo,
7066 double numIndexEntries,
7067 GinQualCounts *counts)
7069 int indexcol = qinfo->indexcol;
7070 Oid clause_op = qinfo->clause_op;
7071 Node *rightop = qinfo->other_operand;
7072 ArrayType *arrayval;
7079 GinQualCounts arraycounts;
7080 int numPossible = 0;
7083 Assert(((ScalarArrayOpExpr *) qinfo->rinfo->clause)->useOr);
7085 /* aggressively reduce to a constant, and look through relabeling */
7086 rightop = estimate_expression_value(root, rightop);
7088 if (IsA(rightop, RelabelType))
7089 rightop = (Node *) ((RelabelType *) rightop)->arg;
7092 * It's impossible to call extractQuery method for unknown operand. So
7093 * unless operand is a Const we can't do much; just assume there will be
7094 * one ordinary search entry from each array entry at runtime, and fall
7095 * back on a probably-bad estimate of the number of array entries.
7097 if (!IsA(rightop, Const))
7099 counts->exactEntries++;
7100 counts->searchEntries++;
7101 counts->arrayScans *= estimate_array_length(rightop);
7105 /* If Const is null, there can be no matches */
7106 if (((Const *) rightop)->constisnull)
7109 /* Otherwise, extract the array elements and iterate over them */
7110 arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
7111 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
7112 &elmlen, &elmbyval, &elmalign);
7113 deconstruct_array(arrayval,
7114 ARR_ELEMTYPE(arrayval),
7115 elmlen, elmbyval, elmalign,
7116 &elemValues, &elemNulls, &numElems);
7118 memset(&arraycounts, 0, sizeof(arraycounts));
7120 for (i = 0; i < numElems; i++)
7122 GinQualCounts elemcounts;
7124 /* NULL can't match anything, so ignore, as the executor will */
7128 /* Otherwise, apply extractQuery and get the actual term counts */
7129 memset(&elemcounts, 0, sizeof(elemcounts));
7131 if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
7134 /* We ignore array elements that are unsatisfiable patterns */
7137 if (elemcounts.haveFullScan)
7140 * Full index scan will be required. We treat this as if
7141 * every key in the index had been listed in the query; is
7144 elemcounts.partialEntries = 0;
7145 elemcounts.exactEntries = numIndexEntries;
7146 elemcounts.searchEntries = numIndexEntries;
7148 arraycounts.partialEntries += elemcounts.partialEntries;
7149 arraycounts.exactEntries += elemcounts.exactEntries;
7150 arraycounts.searchEntries += elemcounts.searchEntries;
7154 if (numPossible == 0)
7156 /* No satisfiable patterns in the array */
7161 * Now add the averages to the global counts. This will give us an
7162 * estimate of the average number of terms searched for in each indexscan,
7163 * including contributions from both array and non-array quals.
7165 counts->partialEntries += arraycounts.partialEntries / numPossible;
7166 counts->exactEntries += arraycounts.exactEntries / numPossible;
7167 counts->searchEntries += arraycounts.searchEntries / numPossible;
7169 counts->arrayScans *= numPossible;
7175 * GIN has search behavior completely different from other index types
7178 gincostestimate(PG_FUNCTION_ARGS)
7180 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
7181 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
7182 double loop_count = PG_GETARG_FLOAT8(2);
7183 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
7184 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
7185 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
7186 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
7187 IndexOptInfo *index = path->indexinfo;
7188 List *indexQuals = path->indexquals;
7189 List *indexOrderBys = path->indexorderbys;
7192 List *selectivityQuals;
7193 double numPages = index->pages,
7194 numTuples = index->tuples;
7195 double numEntryPages,
7199 GinQualCounts counts;
7201 double entryPagesFetched,
7203 dataPagesFetchedBySel;
7204 double qual_op_cost,
7206 spc_random_page_cost,
7209 GinStatsData ginStats;
7211 /* Do preliminary analysis of indexquals */
7212 qinfos = deconstruct_indexquals(path);
7215 * Obtain statistic information from the meta page
7217 indexRel = index_open(index->indexoid, AccessShareLock);
7218 ginGetStats(indexRel, &ginStats);
7219 index_close(indexRel, AccessShareLock);
7221 numEntryPages = ginStats.nEntryPages;
7222 numDataPages = ginStats.nDataPages;
7223 numPendingPages = ginStats.nPendingPages;
7224 numEntries = ginStats.nEntries;
7227 * nPendingPages can be trusted, but the other fields are as of the last
7228 * VACUUM. Scale them by the ratio numPages / nTotalPages to account for
7229 * growth since then. If the fields are zero (implying no VACUUM at all,
7230 * and an index created pre-9.1), assume all pages are entry pages.
7232 if (ginStats.nTotalPages == 0 || ginStats.nEntryPages == 0)
7234 numEntryPages = numPages;
7236 numEntries = numTuples; /* bogus, but no other info available */
7240 double scale = numPages / ginStats.nTotalPages;
7242 numEntryPages = ceil(numEntryPages * scale);
7243 numDataPages = ceil(numDataPages * scale);
7244 numEntries = ceil(numEntries * scale);
7245 /* ensure we didn't round up too much */
7246 numEntryPages = Min(numEntryPages, numPages);
7247 numDataPages = Min(numDataPages, numPages - numEntryPages);
7250 /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
7255 * Include predicate in selectivityQuals (should match
7256 * genericcostestimate)
7258 if (index->indpred != NIL)
7260 List *predExtraQuals = NIL;
7262 foreach(l, index->indpred)
7264 Node *predQual = (Node *) lfirst(l);
7265 List *oneQual = list_make1(predQual);
7267 if (!predicate_implied_by(oneQual, indexQuals))
7268 predExtraQuals = list_concat(predExtraQuals, oneQual);
7270 /* list_concat avoids modifying the passed-in indexQuals list */
7271 selectivityQuals = list_concat(predExtraQuals, indexQuals);
7274 selectivityQuals = indexQuals;
7276 /* Estimate the fraction of main-table tuples that will be visited */
7277 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7282 /* fetch estimated page cost for tablespace containing index */
7283 get_tablespace_page_costs(index->reltablespace,
7284 &spc_random_page_cost,
7288 * Generic assumption about index correlation: there isn't any.
7290 *indexCorrelation = 0.0;
7293 * Examine quals to estimate number of search entries & partial matches
7295 memset(&counts, 0, sizeof(counts));
7296 counts.arrayScans = 1;
7297 matchPossible = true;
7301 IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(l);
7302 Expr *clause = qinfo->rinfo->clause;
7304 if (IsA(clause, OpExpr))
7306 matchPossible = gincost_opexpr(root,
7313 else if (IsA(clause, ScalarArrayOpExpr))
7315 matchPossible = gincost_scalararrayopexpr(root,
7325 /* shouldn't be anything else for a GIN index */
7326 elog(ERROR, "unsupported GIN indexqual type: %d",
7327 (int) nodeTag(clause));
7331 /* Fall out if there were any provably-unsatisfiable quals */
7334 *indexStartupCost = 0;
7335 *indexTotalCost = 0;
7336 *indexSelectivity = 0;
7340 if (counts.haveFullScan || indexQuals == NIL)
7343 * Full index scan will be required. We treat this as if every key in
7344 * the index had been listed in the query; is that reasonable?
7346 counts.partialEntries = 0;
7347 counts.exactEntries = numEntries;
7348 counts.searchEntries = numEntries;
7351 /* Will we have more than one iteration of a nestloop scan? */
7352 outer_scans = loop_count;
7355 * Compute cost to begin scan, first of all, pay attention to pending
7358 entryPagesFetched = numPendingPages;
7361 * Estimate number of entry pages read. We need to do
7362 * counts.searchEntries searches. Use a power function as it should be,
7363 * but tuples on leaf pages usually is much greater. Here we include all
7364 * searches in entry tree, including search of first entry in partial
7367 entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
7370 * Add an estimate of entry pages read by partial match algorithm. It's a
7371 * scan over leaf pages in entry tree. We haven't any useful stats here,
7372 * so estimate it as proportion.
7374 entryPagesFetched += ceil(numEntryPages * counts.partialEntries / numEntries);
7377 * Partial match algorithm reads all data pages before doing actual scan,
7378 * so it's a startup cost. Again, we haven't any useful stats here, so,
7379 * estimate it as proportion
7381 dataPagesFetched = ceil(numDataPages * counts.partialEntries / numEntries);
7384 * Calculate cache effects if more than one scan due to nestloops or array
7385 * quals. The result is pro-rated per nestloop scan, but the array qual
7386 * factor shouldn't be pro-rated (compare genericcostestimate).
7388 if (outer_scans > 1 || counts.arrayScans > 1)
7390 entryPagesFetched *= outer_scans * counts.arrayScans;
7391 entryPagesFetched = index_pages_fetched(entryPagesFetched,
7392 (BlockNumber) numEntryPages,
7393 numEntryPages, root);
7394 entryPagesFetched /= outer_scans;
7395 dataPagesFetched *= outer_scans * counts.arrayScans;
7396 dataPagesFetched = index_pages_fetched(dataPagesFetched,
7397 (BlockNumber) numDataPages,
7398 numDataPages, root);
7399 dataPagesFetched /= outer_scans;
7403 * Here we use random page cost because logically-close pages could be far
7406 *indexStartupCost = (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
7409 * Now compute the number of data pages fetched during the scan.
7411 * We assume every entry to have the same number of items, and that there
7412 * is no overlap between them. (XXX: tsvector and array opclasses collect
7413 * statistics on the frequency of individual keys; it would be nice to use
7416 dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
7419 * If there is a lot of overlap among the entries, in particular if one of
7420 * the entries is very frequent, the above calculation can grossly
7421 * under-estimate. As a simple cross-check, calculate a lower bound based
7422 * on the overall selectivity of the quals. At a minimum, we must read
7423 * one item pointer for each matching entry.
7425 * The width of each item pointer varies, based on the level of
7426 * compression. We don't have statistics on that, but an average of
7427 * around 3 bytes per item is fairly typical.
7429 dataPagesFetchedBySel = ceil(*indexSelectivity *
7430 (numTuples / (BLCKSZ / 3)));
7431 if (dataPagesFetchedBySel > dataPagesFetched)
7432 dataPagesFetched = dataPagesFetchedBySel;
7434 /* Account for cache effects, the same as above */
7435 if (outer_scans > 1 || counts.arrayScans > 1)
7437 dataPagesFetched *= outer_scans * counts.arrayScans;
7438 dataPagesFetched = index_pages_fetched(dataPagesFetched,
7439 (BlockNumber) numDataPages,
7440 numDataPages, root);
7441 dataPagesFetched /= outer_scans;
7444 /* And apply random_page_cost as the cost per page */
7445 *indexTotalCost = *indexStartupCost +
7446 dataPagesFetched * spc_random_page_cost;
7449 * Add on index qual eval costs, much as in genericcostestimate
7451 qual_arg_cost = other_operands_eval_cost(root, qinfos) +
7452 orderby_operands_eval_cost(root, path);
7453 qual_op_cost = cpu_operator_cost *
7454 (list_length(indexQuals) + list_length(indexOrderBys));
7456 *indexStartupCost += qual_arg_cost;
7457 *indexTotalCost += qual_arg_cost;
7458 *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost + qual_op_cost);
7464 * BRIN has search behavior completely different from other index types
7467 brincostestimate(PG_FUNCTION_ARGS)
7469 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
7470 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
7471 double loop_count = PG_GETARG_FLOAT8(2);
7472 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
7473 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
7474 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
7475 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
7476 IndexOptInfo *index = path->indexinfo;
7477 List *indexQuals = path->indexquals;
7478 List *indexOrderBys = path->indexorderbys;
7479 double numPages = index->pages;
7480 double numTuples = index->tuples;
7482 Cost spc_seq_page_cost;
7483 Cost spc_random_page_cost;
7484 double qual_op_cost;
7485 double qual_arg_cost;
7487 /* Do preliminary analysis of indexquals */
7488 qinfos = deconstruct_indexquals(path);
7490 /* fetch estimated page cost for tablespace containing index */
7491 get_tablespace_page_costs(index->reltablespace,
7492 &spc_random_page_cost,
7493 &spc_seq_page_cost);
7496 * BRIN indexes are always read in full; use that as startup cost.
7498 * XXX maybe only include revmap pages here?
7500 *indexStartupCost = spc_seq_page_cost * numPages * loop_count;
7503 * To read a BRIN index there might be a bit of back and forth over
7504 * regular pages, as revmap might point to them out of sequential order;
7505 * calculate this as reading the whole index in random order.
7507 *indexTotalCost = spc_random_page_cost * numPages * loop_count;
7510 clauselist_selectivity(root, indexQuals,
7511 path->indexinfo->rel->relid,
7513 *indexCorrelation = 1;
7516 * Add on index qual eval costs, much as in genericcostestimate.
7518 qual_arg_cost = other_operands_eval_cost(root, qinfos) +
7519 orderby_operands_eval_cost(root, path);
7520 qual_op_cost = cpu_operator_cost *
7521 (list_length(indexQuals) + list_length(indexOrderBys));
7523 *indexStartupCost += qual_arg_cost;
7524 *indexTotalCost += qual_arg_cost;
7525 *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost + qual_op_cost);
7527 /* XXX what about pages_per_range? */