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-2011, 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.
94 #include "access/gin.h"
95 #include "access/sysattr.h"
96 #include "catalog/index.h"
97 #include "catalog/pg_collation.h"
98 #include "catalog/pg_opfamily.h"
99 #include "catalog/pg_statistic.h"
100 #include "catalog/pg_type.h"
101 #include "executor/executor.h"
102 #include "mb/pg_wchar.h"
103 #include "nodes/makefuncs.h"
104 #include "nodes/nodeFuncs.h"
105 #include "optimizer/clauses.h"
106 #include "optimizer/cost.h"
107 #include "optimizer/pathnode.h"
108 #include "optimizer/paths.h"
109 #include "optimizer/plancat.h"
110 #include "optimizer/predtest.h"
111 #include "optimizer/restrictinfo.h"
112 #include "optimizer/var.h"
113 #include "parser/parse_coerce.h"
114 #include "parser/parsetree.h"
115 #include "utils/builtins.h"
116 #include "utils/bytea.h"
117 #include "utils/date.h"
118 #include "utils/datum.h"
119 #include "utils/fmgroids.h"
120 #include "utils/lsyscache.h"
121 #include "utils/nabstime.h"
122 #include "utils/pg_locale.h"
123 #include "utils/selfuncs.h"
124 #include "utils/spccache.h"
125 #include "utils/syscache.h"
126 #include "utils/tqual.h"
129 /* Hooks for plugins to get control when we ask for stats */
130 get_relation_stats_hook_type get_relation_stats_hook = NULL;
131 get_index_stats_hook_type get_index_stats_hook = NULL;
133 static double var_eq_const(VariableStatData *vardata, Oid operator,
134 Datum constval, bool constisnull,
136 static double var_eq_non_const(VariableStatData *vardata, Oid operator,
139 static double ineq_histogram_selectivity(PlannerInfo *root,
140 VariableStatData *vardata,
141 FmgrInfo *opproc, bool isgt,
142 Datum constval, Oid consttype);
143 static double eqjoinsel_inner(Oid operator,
144 VariableStatData *vardata1, VariableStatData *vardata2);
145 static double eqjoinsel_semi(Oid operator,
146 VariableStatData *vardata1, VariableStatData *vardata2);
147 static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
148 Datum lobound, Datum hibound, Oid boundstypid,
149 double *scaledlobound, double *scaledhibound);
150 static double convert_numeric_to_scalar(Datum value, Oid typid);
151 static void convert_string_to_scalar(char *value,
154 double *scaledlobound,
156 double *scaledhibound);
157 static void convert_bytea_to_scalar(Datum value,
160 double *scaledlobound,
162 double *scaledhibound);
163 static double convert_one_string_to_scalar(char *value,
164 int rangelo, int rangehi);
165 static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
166 int rangelo, int rangehi);
167 static char *convert_string_datum(Datum value, Oid typid);
168 static double convert_timevalue_to_scalar(Datum value, Oid typid);
169 static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
170 Oid sortop, Datum *min, Datum *max);
171 static bool get_actual_variable_range(PlannerInfo *root,
172 VariableStatData *vardata,
174 Datum *min, Datum *max);
175 static Selectivity prefix_selectivity(PlannerInfo *root,
176 VariableStatData *vardata,
177 Oid vartype, Oid opfamily, Const *prefixcon);
178 static Selectivity pattern_selectivity(Const *patt, Pattern_Type ptype);
179 static Datum string_to_datum(const char *str, Oid datatype);
180 static Const *string_to_const(const char *str, Oid datatype);
181 static Const *string_to_bytea_const(const char *str, size_t str_len);
185 * eqsel - Selectivity of "=" for any data types.
187 * Note: this routine is also used to estimate selectivity for some
188 * operators that are not "=" but have comparable selectivity behavior,
189 * such as "~=" (geometric approximate-match). Even for "=", we must
190 * keep in mind that the left and right datatypes may differ.
193 eqsel(PG_FUNCTION_ARGS)
195 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
196 Oid operator = PG_GETARG_OID(1);
197 List *args = (List *) PG_GETARG_POINTER(2);
198 int varRelid = PG_GETARG_INT32(3);
199 VariableStatData vardata;
205 * If expression is not variable = something or something = variable, then
206 * punt and return a default estimate.
208 if (!get_restriction_variable(root, args, varRelid,
209 &vardata, &other, &varonleft))
210 PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
213 * We can do a lot better if the something is a constant. (Note: the
214 * Const might result from estimation rather than being a simple constant
217 if (IsA(other, Const))
218 selec = var_eq_const(&vardata, operator,
219 ((Const *) other)->constvalue,
220 ((Const *) other)->constisnull,
223 selec = var_eq_non_const(&vardata, operator, other,
226 ReleaseVariableStats(vardata);
228 PG_RETURN_FLOAT8((float8) selec);
232 * var_eq_const --- eqsel for var = const case
234 * This is split out so that some other estimation functions can use it.
237 var_eq_const(VariableStatData *vardata, Oid operator,
238 Datum constval, bool constisnull,
244 * If the constant is NULL, assume operator is strict and return zero, ie,
245 * operator will never return TRUE.
251 * If we matched the var to a unique index, assume there is exactly one
252 * match regardless of anything else. (This is slightly bogus, since the
253 * index's equality operator might be different from ours, but it's more
254 * likely to be right than ignoring the information.)
256 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
257 return 1.0 / vardata->rel->tuples;
259 if (HeapTupleIsValid(vardata->statsTuple))
261 Form_pg_statistic stats;
269 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
272 * Is the constant "=" to any of the column's most common values?
273 * (Although the given operator may not really be "=", we will assume
274 * that seeing whether it returns TRUE is an appropriate test. If you
275 * don't like this, maybe you shouldn't be using eqsel for your
278 if (get_attstatsslot(vardata->statsTuple,
279 vardata->atttype, vardata->atttypmod,
280 STATISTIC_KIND_MCV, InvalidOid,
283 &numbers, &nnumbers))
287 fmgr_info(get_opcode(operator), &eqproc);
288 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &eqproc);
290 for (i = 0; i < nvalues; i++)
292 /* be careful to apply operator right way 'round */
294 match = DatumGetBool(FunctionCall2(&eqproc,
298 match = DatumGetBool(FunctionCall2(&eqproc,
307 /* no most-common-value info available */
310 i = nvalues = nnumbers = 0;
316 * Constant is "=" to this common value. We know selectivity
317 * exactly (or as exactly as ANALYZE could calculate it, anyway).
324 * Comparison is against a constant that is neither NULL nor any
325 * of the common values. Its selectivity cannot be more than
328 double sumcommon = 0.0;
329 double otherdistinct;
331 for (i = 0; i < nnumbers; i++)
332 sumcommon += numbers[i];
333 selec = 1.0 - sumcommon - stats->stanullfrac;
334 CLAMP_PROBABILITY(selec);
337 * and in fact it's probably a good deal less. We approximate that
338 * all the not-common values share this remaining fraction
339 * equally, so we divide by the number of other distinct values.
341 otherdistinct = get_variable_numdistinct(vardata) - nnumbers;
342 if (otherdistinct > 1)
343 selec /= otherdistinct;
346 * Another cross-check: selectivity shouldn't be estimated as more
347 * than the least common "most common value".
349 if (nnumbers > 0 && selec > numbers[nnumbers - 1])
350 selec = numbers[nnumbers - 1];
353 free_attstatsslot(vardata->atttype, values, nvalues,
359 * No ANALYZE stats available, so make a guess using estimated number
360 * of distinct values and assuming they are equally common. (The guess
361 * is unlikely to be very good, but we do know a few special cases.)
363 selec = 1.0 / get_variable_numdistinct(vardata);
366 /* result should be in range, but make sure... */
367 CLAMP_PROBABILITY(selec);
373 * var_eq_non_const --- eqsel for var = something-other-than-const case
376 var_eq_non_const(VariableStatData *vardata, Oid operator,
383 * If we matched the var to a unique index, assume there is exactly one
384 * match regardless of anything else. (This is slightly bogus, since the
385 * index's equality operator might be different from ours, but it's more
386 * likely to be right than ignoring the information.)
388 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
389 return 1.0 / vardata->rel->tuples;
391 if (HeapTupleIsValid(vardata->statsTuple))
393 Form_pg_statistic stats;
398 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
401 * Search is for a value that we do not know a priori, but we will
402 * assume it is not NULL. Estimate the selectivity as non-null
403 * fraction divided by number of distinct values, so that we get a
404 * result averaged over all possible values whether common or
405 * uncommon. (Essentially, we are assuming that the not-yet-known
406 * comparison value is equally likely to be any of the possible
407 * values, regardless of their frequency in the table. Is that a good
410 selec = 1.0 - stats->stanullfrac;
411 ndistinct = get_variable_numdistinct(vardata);
416 * Cross-check: selectivity should never be estimated as more than the
417 * most common value's.
419 if (get_attstatsslot(vardata->statsTuple,
420 vardata->atttype, vardata->atttypmod,
421 STATISTIC_KIND_MCV, InvalidOid,
424 &numbers, &nnumbers))
426 if (nnumbers > 0 && selec > numbers[0])
428 free_attstatsslot(vardata->atttype, NULL, 0, numbers, nnumbers);
434 * No ANALYZE stats available, so make a guess using estimated number
435 * of distinct values and assuming they are equally common. (The guess
436 * is unlikely to be very good, but we do know a few special cases.)
438 selec = 1.0 / get_variable_numdistinct(vardata);
441 /* result should be in range, but make sure... */
442 CLAMP_PROBABILITY(selec);
448 * neqsel - Selectivity of "!=" for any data types.
450 * This routine is also used for some operators that are not "!="
451 * but have comparable selectivity behavior. See above comments
455 neqsel(PG_FUNCTION_ARGS)
457 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
458 Oid operator = PG_GETARG_OID(1);
459 List *args = (List *) PG_GETARG_POINTER(2);
460 int varRelid = PG_GETARG_INT32(3);
465 * We want 1 - eqsel() where the equality operator is the one associated
466 * with this != operator, that is, its negator.
468 eqop = get_negator(operator);
471 result = DatumGetFloat8(DirectFunctionCall4(eqsel,
472 PointerGetDatum(root),
473 ObjectIdGetDatum(eqop),
474 PointerGetDatum(args),
475 Int32GetDatum(varRelid)));
479 /* Use default selectivity (should we raise an error instead?) */
480 result = DEFAULT_EQ_SEL;
482 result = 1.0 - result;
483 PG_RETURN_FLOAT8(result);
487 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
489 * This is the guts of both scalarltsel and scalargtsel. The caller has
490 * commuted the clause, if necessary, so that we can treat the variable as
491 * being on the left. The caller must also make sure that the other side
492 * of the clause is a non-null Const, and dissect same into a value and
495 * This routine works for any datatype (or pair of datatypes) known to
496 * convert_to_scalar(). If it is applied to some other datatype,
497 * it will return a default estimate.
500 scalarineqsel(PlannerInfo *root, Oid operator, bool isgt,
501 VariableStatData *vardata, Datum constval, Oid consttype)
503 Form_pg_statistic stats;
510 if (!HeapTupleIsValid(vardata->statsTuple))
512 /* no stats available, so default result */
513 return DEFAULT_INEQ_SEL;
515 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
517 fmgr_info(get_opcode(operator), &opproc);
518 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &opproc);
521 * If we have most-common-values info, add up the fractions of the MCV
522 * entries that satisfy MCV OP CONST. These fractions contribute directly
523 * to the result selectivity. Also add up the total fraction represented
526 mcv_selec = mcv_selectivity(vardata, &opproc, constval, true,
530 * If there is a histogram, determine which bin the constant falls in, and
531 * compute the resulting contribution to selectivity.
533 hist_selec = ineq_histogram_selectivity(root, vardata, &opproc, isgt,
534 constval, consttype);
537 * Now merge the results from the MCV and histogram calculations,
538 * realizing that the histogram covers only the non-null values that are
541 selec = 1.0 - stats->stanullfrac - sumcommon;
543 if (hist_selec >= 0.0)
548 * If no histogram but there are values not accounted for by MCV,
549 * arbitrarily assume half of them will match.
556 /* result should be in range, but make sure... */
557 CLAMP_PROBABILITY(selec);
563 * mcv_selectivity - Examine the MCV list for selectivity estimates
565 * Determine the fraction of the variable's MCV population that satisfies
566 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
567 * compute the fraction of the total column population represented by the MCV
568 * list. This code will work for any boolean-returning predicate operator.
570 * The function result is the MCV selectivity, and the fraction of the
571 * total population is returned into *sumcommonp. Zeroes are returned
572 * if there is no MCV list.
575 mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
576 Datum constval, bool varonleft,
590 if (HeapTupleIsValid(vardata->statsTuple) &&
591 get_attstatsslot(vardata->statsTuple,
592 vardata->atttype, vardata->atttypmod,
593 STATISTIC_KIND_MCV, InvalidOid,
596 &numbers, &nnumbers))
598 for (i = 0; i < nvalues; i++)
601 DatumGetBool(FunctionCall2(opproc,
604 DatumGetBool(FunctionCall2(opproc,
607 mcv_selec += numbers[i];
608 sumcommon += numbers[i];
610 free_attstatsslot(vardata->atttype, values, nvalues,
614 *sumcommonp = sumcommon;
619 * histogram_selectivity - Examine the histogram for selectivity estimates
621 * Determine the fraction of the variable's histogram entries that satisfy
622 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
624 * This code will work for any boolean-returning predicate operator, whether
625 * or not it has anything to do with the histogram sort operator. We are
626 * essentially using the histogram just as a representative sample. However,
627 * small histograms are unlikely to be all that representative, so the caller
628 * should be prepared to fall back on some other estimation approach when the
629 * histogram is missing or very small. It may also be prudent to combine this
630 * approach with another one when the histogram is small.
632 * If the actual histogram size is not at least min_hist_size, we won't bother
633 * to do the calculation at all. Also, if the n_skip parameter is > 0, we
634 * ignore the first and last n_skip histogram elements, on the grounds that
635 * they are outliers and hence not very representative. Typical values for
636 * these parameters are 10 and 1.
638 * The function result is the selectivity, or -1 if there is no histogram
639 * or it's smaller than min_hist_size.
641 * The output parameter *hist_size receives the actual histogram size,
642 * or zero if no histogram. Callers may use this number to decide how
643 * much faith to put in the function result.
645 * Note that the result disregards both the most-common-values (if any) and
646 * null entries. The caller is expected to combine this result with
647 * statistics for those portions of the column population. It may also be
648 * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
651 histogram_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
652 Datum constval, bool varonleft,
653 int min_hist_size, int n_skip,
660 /* check sanity of parameters */
662 Assert(min_hist_size > 2 * n_skip);
664 if (HeapTupleIsValid(vardata->statsTuple) &&
665 get_attstatsslot(vardata->statsTuple,
666 vardata->atttype, vardata->atttypmod,
667 STATISTIC_KIND_HISTOGRAM, InvalidOid,
672 *hist_size = nvalues;
673 if (nvalues >= min_hist_size)
678 for (i = n_skip; i < nvalues - n_skip; i++)
681 DatumGetBool(FunctionCall2(opproc,
684 DatumGetBool(FunctionCall2(opproc,
689 result = ((double) nmatch) / ((double) (nvalues - 2 * n_skip));
693 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
705 * ineq_histogram_selectivity - Examine the histogram for scalarineqsel
707 * Determine the fraction of the variable's histogram population that
708 * satisfies the inequality condition, ie, VAR < CONST or VAR > CONST.
710 * Returns -1 if there is no histogram (valid results will always be >= 0).
712 * Note that the result disregards both the most-common-values (if any) and
713 * null entries. The caller is expected to combine this result with
714 * statistics for those portions of the column population.
717 ineq_histogram_selectivity(PlannerInfo *root,
718 VariableStatData *vardata,
719 FmgrInfo *opproc, bool isgt,
720 Datum constval, Oid consttype)
730 * Someday, ANALYZE might store more than one histogram per rel/att,
731 * corresponding to more than one possible sort ordering defined for the
732 * column type. However, to make that work we will need to figure out
733 * which staop to search for --- it's not necessarily the one we have at
734 * hand! (For example, we might have a '<=' operator rather than the '<'
735 * operator that will appear in staop.) For now, assume that whatever
736 * appears in pg_statistic is sorted the same way our operator sorts, or
737 * the reverse way if isgt is TRUE.
739 if (HeapTupleIsValid(vardata->statsTuple) &&
740 get_attstatsslot(vardata->statsTuple,
741 vardata->atttype, vardata->atttypmod,
742 STATISTIC_KIND_HISTOGRAM, InvalidOid,
750 * Use binary search to find proper location, ie, the first slot
751 * at which the comparison fails. (If the given operator isn't
752 * actually sort-compatible with the histogram, you'll get garbage
753 * results ... but probably not any more garbage-y than you would
754 * from the old linear search.)
756 * If the binary search accesses the first or last histogram
757 * entry, we try to replace that endpoint with the true column min
758 * or max as found by get_actual_variable_range(). This
759 * ameliorates misestimates when the min or max is moving as a
760 * result of changes since the last ANALYZE. Note that this could
761 * result in effectively including MCVs into the histogram that
762 * weren't there before, but we don't try to correct for that.
765 int lobound = 0; /* first possible slot to search */
766 int hibound = nvalues; /* last+1 slot to search */
767 bool have_end = false;
770 * If there are only two histogram entries, we'll want up-to-date
771 * values for both. (If there are more than two, we need at most
772 * one of them to be updated, so we deal with that within the
776 have_end = get_actual_variable_range(root,
782 while (lobound < hibound)
784 int probe = (lobound + hibound) / 2;
788 * If we find ourselves about to compare to the first or last
789 * histogram entry, first try to replace it with the actual
790 * current min or max (unless we already did so above).
792 if (probe == 0 && nvalues > 2)
793 have_end = get_actual_variable_range(root,
798 else if (probe == nvalues - 1 && nvalues > 2)
799 have_end = get_actual_variable_range(root,
805 ltcmp = DatumGetBool(FunctionCall2(opproc,
818 /* Constant is below lower histogram boundary. */
821 else if (lobound >= nvalues)
823 /* Constant is above upper histogram boundary. */
835 * We have values[i-1] <= constant <= values[i].
837 * Convert the constant and the two nearest bin boundary
838 * values to a uniform comparison scale, and do a linear
839 * interpolation within this bin.
841 if (convert_to_scalar(constval, consttype, &val,
842 values[i - 1], values[i],
848 /* cope if bin boundaries appear identical */
853 else if (val >= high)
857 binfrac = (val - low) / (high - low);
860 * Watch out for the possibility that we got a NaN or
861 * Infinity from the division. This can happen
862 * despite the previous checks, if for example "low"
865 if (isnan(binfrac) ||
866 binfrac < 0.0 || binfrac > 1.0)
873 * Ideally we'd produce an error here, on the grounds that
874 * the given operator shouldn't have scalarXXsel
875 * registered as its selectivity func unless we can deal
876 * with its operand types. But currently, all manner of
877 * stuff is invoking scalarXXsel, so give a default
878 * estimate until that can be fixed.
884 * Now, compute the overall selectivity across the values
885 * represented by the histogram. We have i-1 full bins and
886 * binfrac partial bin below the constant.
888 histfrac = (double) (i - 1) + binfrac;
889 histfrac /= (double) (nvalues - 1);
893 * Now histfrac = fraction of histogram entries below the
896 * Account for "<" vs ">"
898 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
901 * The histogram boundaries are only approximate to begin with,
902 * and may well be out of date anyway. Therefore, don't believe
903 * extremely small or large selectivity estimates --- unless we
904 * got actual current endpoint values from the table.
907 CLAMP_PROBABILITY(hist_selec);
910 if (hist_selec < 0.0001)
912 else if (hist_selec > 0.9999)
917 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
924 * scalarltsel - Selectivity of "<" (also "<=") for scalars.
927 scalarltsel(PG_FUNCTION_ARGS)
929 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
930 Oid operator = PG_GETARG_OID(1);
931 List *args = (List *) PG_GETARG_POINTER(2);
932 int varRelid = PG_GETARG_INT32(3);
933 VariableStatData vardata;
942 * If expression is not variable op something or something op variable,
943 * then punt and return a default estimate.
945 if (!get_restriction_variable(root, args, varRelid,
946 &vardata, &other, &varonleft))
947 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
950 * Can't do anything useful if the something is not a constant, either.
952 if (!IsA(other, Const))
954 ReleaseVariableStats(vardata);
955 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
959 * If the constant is NULL, assume operator is strict and return zero, ie,
960 * operator will never return TRUE.
962 if (((Const *) other)->constisnull)
964 ReleaseVariableStats(vardata);
965 PG_RETURN_FLOAT8(0.0);
967 constval = ((Const *) other)->constvalue;
968 consttype = ((Const *) other)->consttype;
971 * Force the var to be on the left to simplify logic in scalarineqsel.
975 /* we have var < other */
980 /* we have other < var, commute to make var > other */
981 operator = get_commutator(operator);
984 /* Use default selectivity (should we raise an error instead?) */
985 ReleaseVariableStats(vardata);
986 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
991 selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
993 ReleaseVariableStats(vardata);
995 PG_RETURN_FLOAT8((float8) selec);
999 * scalargtsel - Selectivity of ">" (also ">=") for integers.
1002 scalargtsel(PG_FUNCTION_ARGS)
1004 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1005 Oid operator = PG_GETARG_OID(1);
1006 List *args = (List *) PG_GETARG_POINTER(2);
1007 int varRelid = PG_GETARG_INT32(3);
1008 VariableStatData vardata;
1017 * If expression is not variable op something or something op variable,
1018 * then punt and return a default estimate.
1020 if (!get_restriction_variable(root, args, varRelid,
1021 &vardata, &other, &varonleft))
1022 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1025 * Can't do anything useful if the something is not a constant, either.
1027 if (!IsA(other, Const))
1029 ReleaseVariableStats(vardata);
1030 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1034 * If the constant is NULL, assume operator is strict and return zero, ie,
1035 * operator will never return TRUE.
1037 if (((Const *) other)->constisnull)
1039 ReleaseVariableStats(vardata);
1040 PG_RETURN_FLOAT8(0.0);
1042 constval = ((Const *) other)->constvalue;
1043 consttype = ((Const *) other)->consttype;
1046 * Force the var to be on the left to simplify logic in scalarineqsel.
1050 /* we have var > other */
1055 /* we have other > var, commute to make var < other */
1056 operator = get_commutator(operator);
1059 /* Use default selectivity (should we raise an error instead?) */
1060 ReleaseVariableStats(vardata);
1061 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1066 selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
1068 ReleaseVariableStats(vardata);
1070 PG_RETURN_FLOAT8((float8) selec);
1074 * patternsel - Generic code for pattern-match selectivity.
1077 patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
1079 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1080 Oid operator = PG_GETARG_OID(1);
1081 List *args = (List *) PG_GETARG_POINTER(2);
1082 int varRelid = PG_GETARG_INT32(3);
1083 VariableStatData vardata;
1091 Pattern_Prefix_Status pstatus;
1093 Const *prefix = NULL;
1098 * If this is for a NOT LIKE or similar operator, get the corresponding
1099 * positive-match operator and work with that. Set result to the correct
1100 * default estimate, too.
1104 operator = get_negator(operator);
1105 if (!OidIsValid(operator))
1106 elog(ERROR, "patternsel called for operator without a negator");
1107 result = 1.0 - DEFAULT_MATCH_SEL;
1111 result = DEFAULT_MATCH_SEL;
1115 * If expression is not variable op constant, then punt and return a
1118 if (!get_restriction_variable(root, args, varRelid,
1119 &vardata, &other, &varonleft))
1121 if (!varonleft || !IsA(other, Const))
1123 ReleaseVariableStats(vardata);
1126 variable = (Node *) linitial(args);
1129 * If the constant is NULL, assume operator is strict and return zero, ie,
1130 * operator will never return TRUE. (It's zero even for a negator op.)
1132 if (((Const *) other)->constisnull)
1134 ReleaseVariableStats(vardata);
1137 constval = ((Const *) other)->constvalue;
1138 consttype = ((Const *) other)->consttype;
1141 * The right-hand const is type text or bytea for all supported operators.
1142 * We do not expect to see binary-compatible types here, since
1143 * const-folding should have relabeled the const to exactly match the
1144 * operator's declared type.
1146 if (consttype != TEXTOID && consttype != BYTEAOID)
1148 ReleaseVariableStats(vardata);
1153 * Similarly, the exposed type of the left-hand side should be one of
1154 * those we know. (Do not look at vardata.atttype, which might be
1155 * something binary-compatible but different.) We can use it to choose
1156 * the index opfamily from which we must draw the comparison operators.
1158 * NOTE: It would be more correct to use the PATTERN opfamilies than the
1159 * simple ones, but at the moment ANALYZE will not generate statistics for
1160 * the PATTERN operators. But our results are so approximate anyway that
1161 * it probably hardly matters.
1163 vartype = vardata.vartype;
1168 opfamily = TEXT_BTREE_FAM_OID;
1171 opfamily = BPCHAR_BTREE_FAM_OID;
1174 opfamily = NAME_BTREE_FAM_OID;
1177 opfamily = BYTEA_BTREE_FAM_OID;
1180 ReleaseVariableStats(vardata);
1184 /* divide pattern into fixed prefix and remainder */
1185 patt = (Const *) other;
1186 pstatus = pattern_fixed_prefix(patt, ptype, &prefix, &rest);
1189 * If necessary, coerce the prefix constant to the right type. (The "rest"
1190 * constant need not be changed.)
1192 if (prefix && prefix->consttype != vartype)
1196 switch (prefix->consttype)
1199 prefixstr = TextDatumGetCString(prefix->constvalue);
1202 prefixstr = DatumGetCString(DirectFunctionCall1(byteaout,
1203 prefix->constvalue));
1206 elog(ERROR, "unrecognized consttype: %u",
1208 ReleaseVariableStats(vardata);
1211 prefix = string_to_const(prefixstr, vartype);
1215 if (pstatus == Pattern_Prefix_Exact)
1218 * Pattern specifies an exact match, so pretend operator is '='
1220 Oid eqopr = get_opfamily_member(opfamily, vartype, vartype,
1221 BTEqualStrategyNumber);
1223 if (eqopr == InvalidOid)
1224 elog(ERROR, "no = operator for opfamily %u", opfamily);
1225 result = var_eq_const(&vardata, eqopr, prefix->constvalue,
1231 * Not exact-match pattern. If we have a sufficiently large
1232 * histogram, estimate selectivity for the histogram part of the
1233 * population by counting matches in the histogram. If not, estimate
1234 * selectivity of the fixed prefix and remainder of pattern
1235 * separately, then combine the two to get an estimate of the
1236 * selectivity for the part of the column population represented by
1237 * the histogram. (For small histograms, we combine these
1240 * We then add up data for any most-common-values values; these are
1241 * not in the histogram population, and we can get exact answers for
1242 * them by applying the pattern operator, so there's no reason to
1243 * approximate. (If the MCVs cover a significant part of the total
1244 * population, this gives us a big leg up in accuracy.)
1253 /* Try to use the histogram entries to get selectivity */
1254 fmgr_info(get_opcode(operator), &opproc);
1255 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &opproc);
1257 selec = histogram_selectivity(&vardata, &opproc, constval, true,
1260 /* If not at least 100 entries, use the heuristic method */
1261 if (hist_size < 100)
1263 Selectivity heursel;
1264 Selectivity prefixsel;
1265 Selectivity restsel;
1267 if (pstatus == Pattern_Prefix_Partial)
1268 prefixsel = prefix_selectivity(root, &vardata, vartype,
1272 restsel = pattern_selectivity(rest, ptype);
1273 heursel = prefixsel * restsel;
1275 if (selec < 0) /* fewer than 10 histogram entries? */
1280 * For histogram sizes from 10 to 100, we combine the
1281 * histogram and heuristic selectivities, putting increasingly
1282 * more trust in the histogram for larger sizes.
1284 double hist_weight = hist_size / 100.0;
1286 selec = selec * hist_weight + heursel * (1.0 - hist_weight);
1290 /* In any case, don't believe extremely small or large estimates. */
1293 else if (selec > 0.9999)
1297 * If we have most-common-values info, add up the fractions of the MCV
1298 * entries that satisfy MCV OP PATTERN. These fractions contribute
1299 * directly to the result selectivity. Also add up the total fraction
1300 * represented by MCV entries.
1302 mcv_selec = mcv_selectivity(&vardata, &opproc, constval, true,
1305 if (HeapTupleIsValid(vardata.statsTuple))
1306 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
1311 * Now merge the results from the MCV and histogram calculations,
1312 * realizing that the histogram covers only the non-null values that
1313 * are not listed in MCV.
1315 selec *= 1.0 - nullfrac - sumcommon;
1318 /* result should be in range, but make sure... */
1319 CLAMP_PROBABILITY(selec);
1325 pfree(DatumGetPointer(prefix->constvalue));
1329 ReleaseVariableStats(vardata);
1331 return negate ? (1.0 - result) : result;
1335 * regexeqsel - Selectivity of regular-expression pattern match.
1338 regexeqsel(PG_FUNCTION_ARGS)
1340 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, false));
1344 * icregexeqsel - Selectivity of case-insensitive regex match.
1347 icregexeqsel(PG_FUNCTION_ARGS)
1349 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, false));
1353 * likesel - Selectivity of LIKE pattern match.
1356 likesel(PG_FUNCTION_ARGS)
1358 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, false));
1362 * iclikesel - Selectivity of ILIKE pattern match.
1365 iclikesel(PG_FUNCTION_ARGS)
1367 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, false));
1371 * regexnesel - Selectivity of regular-expression pattern non-match.
1374 regexnesel(PG_FUNCTION_ARGS)
1376 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, true));
1380 * icregexnesel - Selectivity of case-insensitive regex non-match.
1383 icregexnesel(PG_FUNCTION_ARGS)
1385 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, true));
1389 * nlikesel - Selectivity of LIKE pattern non-match.
1392 nlikesel(PG_FUNCTION_ARGS)
1394 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, true));
1398 * icnlikesel - Selectivity of ILIKE pattern non-match.
1401 icnlikesel(PG_FUNCTION_ARGS)
1403 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, true));
1407 * booltestsel - Selectivity of BooleanTest Node.
1410 booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
1411 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1413 VariableStatData vardata;
1416 examine_variable(root, arg, varRelid, &vardata);
1418 if (HeapTupleIsValid(vardata.statsTuple))
1420 Form_pg_statistic stats;
1427 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1428 freq_null = stats->stanullfrac;
1430 if (get_attstatsslot(vardata.statsTuple,
1431 vardata.atttype, vardata.atttypmod,
1432 STATISTIC_KIND_MCV, InvalidOid,
1435 &numbers, &nnumbers)
1442 * Get first MCV frequency and derive frequency for true.
1444 if (DatumGetBool(values[0]))
1445 freq_true = numbers[0];
1447 freq_true = 1.0 - numbers[0] - freq_null;
1450 * Next derive frequency for false. Then use these as appropriate
1451 * to derive frequency for each case.
1453 freq_false = 1.0 - freq_true - freq_null;
1455 switch (booltesttype)
1458 /* select only NULL values */
1461 case IS_NOT_UNKNOWN:
1462 /* select non-NULL values */
1463 selec = 1.0 - freq_null;
1466 /* select only TRUE values */
1470 /* select non-TRUE values */
1471 selec = 1.0 - freq_true;
1474 /* select only FALSE values */
1478 /* select non-FALSE values */
1479 selec = 1.0 - freq_false;
1482 elog(ERROR, "unrecognized booltesttype: %d",
1483 (int) booltesttype);
1484 selec = 0.0; /* Keep compiler quiet */
1488 free_attstatsslot(vardata.atttype, values, nvalues,
1494 * No most-common-value info available. Still have null fraction
1495 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1496 * for null fraction and assume an even split for boolean tests.
1498 switch (booltesttype)
1503 * Use freq_null directly.
1507 case IS_NOT_UNKNOWN:
1510 * Select not unknown (not null) values. Calculate from
1513 selec = 1.0 - freq_null;
1519 selec = (1.0 - freq_null) / 2.0;
1522 elog(ERROR, "unrecognized booltesttype: %d",
1523 (int) booltesttype);
1524 selec = 0.0; /* Keep compiler quiet */
1532 * If we can't get variable statistics for the argument, perhaps
1533 * clause_selectivity can do something with it. We ignore the
1534 * possibility of a NULL value when using clause_selectivity, and just
1535 * assume the value is either TRUE or FALSE.
1537 switch (booltesttype)
1540 selec = DEFAULT_UNK_SEL;
1542 case IS_NOT_UNKNOWN:
1543 selec = DEFAULT_NOT_UNK_SEL;
1547 selec = (double) clause_selectivity(root, arg,
1553 selec = 1.0 - (double) clause_selectivity(root, arg,
1558 elog(ERROR, "unrecognized booltesttype: %d",
1559 (int) booltesttype);
1560 selec = 0.0; /* Keep compiler quiet */
1565 ReleaseVariableStats(vardata);
1567 /* result should be in range, but make sure... */
1568 CLAMP_PROBABILITY(selec);
1570 return (Selectivity) selec;
1574 * nulltestsel - Selectivity of NullTest Node.
1577 nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1578 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1580 VariableStatData vardata;
1583 examine_variable(root, arg, varRelid, &vardata);
1585 if (HeapTupleIsValid(vardata.statsTuple))
1587 Form_pg_statistic stats;
1590 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1591 freq_null = stats->stanullfrac;
1593 switch (nulltesttype)
1598 * Use freq_null directly.
1605 * Select not unknown (not null) values. Calculate from
1608 selec = 1.0 - freq_null;
1611 elog(ERROR, "unrecognized nulltesttype: %d",
1612 (int) nulltesttype);
1613 return (Selectivity) 0; /* keep compiler quiet */
1619 * No ANALYZE stats available, so make a guess
1621 switch (nulltesttype)
1624 selec = DEFAULT_UNK_SEL;
1627 selec = DEFAULT_NOT_UNK_SEL;
1630 elog(ERROR, "unrecognized nulltesttype: %d",
1631 (int) nulltesttype);
1632 return (Selectivity) 0; /* keep compiler quiet */
1636 ReleaseVariableStats(vardata);
1638 /* result should be in range, but make sure... */
1639 CLAMP_PROBABILITY(selec);
1641 return (Selectivity) selec;
1645 * strip_array_coercion - strip binary-compatible relabeling from an array expr
1647 * For array values, the parser normally generates ArrayCoerceExpr conversions,
1648 * but it seems possible that RelabelType might show up. Also, the planner
1649 * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1650 * so we need to be ready to deal with more than one level.
1653 strip_array_coercion(Node *node)
1657 if (node && IsA(node, ArrayCoerceExpr) &&
1658 ((ArrayCoerceExpr *) node)->elemfuncid == InvalidOid)
1660 node = (Node *) ((ArrayCoerceExpr *) node)->arg;
1662 else if (node && IsA(node, RelabelType))
1664 /* We don't really expect this case, but may as well cope */
1665 node = (Node *) ((RelabelType *) node)->arg;
1674 * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1677 scalararraysel(PlannerInfo *root,
1678 ScalarArrayOpExpr *clause,
1679 bool is_join_clause,
1682 SpecialJoinInfo *sjinfo)
1684 Oid operator = clause->opno;
1685 bool useOr = clause->useOr;
1688 Oid nominal_element_type;
1689 Oid nominal_element_collation;
1690 RegProcedure oprsel;
1691 FmgrInfo oprselproc;
1695 * First, look up the underlying operator's selectivity estimator. Punt if
1696 * it hasn't got one.
1699 oprsel = get_oprjoin(operator);
1701 oprsel = get_oprrest(operator);
1703 return (Selectivity) 0.5;
1704 fmgr_info(oprsel, &oprselproc);
1705 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &oprselproc);
1707 /* deconstruct the expression */
1708 Assert(list_length(clause->args) == 2);
1709 leftop = (Node *) linitial(clause->args);
1710 rightop = (Node *) lsecond(clause->args);
1712 /* get nominal (after relabeling) element type of rightop */
1713 nominal_element_type = get_base_element_type(exprType(rightop));
1714 if (!OidIsValid(nominal_element_type))
1715 return (Selectivity) 0.5; /* probably shouldn't happen */
1716 /* get nominal collation, too, for generating constants */
1717 nominal_element_collation = exprCollation(rightop);
1719 /* look through any binary-compatible relabeling of rightop */
1720 rightop = strip_array_coercion(rightop);
1723 * We consider three cases:
1725 * 1. rightop is an Array constant: deconstruct the array, apply the
1726 * operator's selectivity function for each array element, and merge the
1727 * results in the same way that clausesel.c does for AND/OR combinations.
1729 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1730 * function for each element of the ARRAY[] construct, and merge.
1732 * 3. otherwise, make a guess ...
1734 if (rightop && IsA(rightop, Const))
1736 Datum arraydatum = ((Const *) rightop)->constvalue;
1737 bool arrayisnull = ((Const *) rightop)->constisnull;
1738 ArrayType *arrayval;
1747 if (arrayisnull) /* qual can't succeed if null array */
1748 return (Selectivity) 0.0;
1749 arrayval = DatumGetArrayTypeP(arraydatum);
1750 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1751 &elmlen, &elmbyval, &elmalign);
1752 deconstruct_array(arrayval,
1753 ARR_ELEMTYPE(arrayval),
1754 elmlen, elmbyval, elmalign,
1755 &elem_values, &elem_nulls, &num_elems);
1756 s1 = useOr ? 0.0 : 1.0;
1757 for (i = 0; i < num_elems; i++)
1762 args = list_make2(leftop,
1763 makeConst(nominal_element_type,
1765 nominal_element_collation,
1771 s2 = DatumGetFloat8(FunctionCall5(&oprselproc,
1772 PointerGetDatum(root),
1773 ObjectIdGetDatum(operator),
1774 PointerGetDatum(args),
1775 Int16GetDatum(jointype),
1776 PointerGetDatum(sjinfo)));
1778 s2 = DatumGetFloat8(FunctionCall4(&oprselproc,
1779 PointerGetDatum(root),
1780 ObjectIdGetDatum(operator),
1781 PointerGetDatum(args),
1782 Int32GetDatum(varRelid)));
1784 s1 = s1 + s2 - s1 * s2;
1789 else if (rightop && IsA(rightop, ArrayExpr) &&
1790 !((ArrayExpr *) rightop)->multidims)
1792 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1797 get_typlenbyval(arrayexpr->element_typeid,
1798 &elmlen, &elmbyval);
1799 s1 = useOr ? 0.0 : 1.0;
1800 foreach(l, arrayexpr->elements)
1802 Node *elem = (Node *) lfirst(l);
1807 * Theoretically, if elem isn't of nominal_element_type we should
1808 * insert a RelabelType, but it seems unlikely that any operator
1809 * estimation function would really care ...
1811 args = list_make2(leftop, elem);
1813 s2 = DatumGetFloat8(FunctionCall5(&oprselproc,
1814 PointerGetDatum(root),
1815 ObjectIdGetDatum(operator),
1816 PointerGetDatum(args),
1817 Int16GetDatum(jointype),
1818 PointerGetDatum(sjinfo)));
1820 s2 = DatumGetFloat8(FunctionCall4(&oprselproc,
1821 PointerGetDatum(root),
1822 ObjectIdGetDatum(operator),
1823 PointerGetDatum(args),
1824 Int32GetDatum(varRelid)));
1826 s1 = s1 + s2 - s1 * s2;
1833 CaseTestExpr *dummyexpr;
1839 * We need a dummy rightop to pass to the operator selectivity
1840 * routine. It can be pretty much anything that doesn't look like a
1841 * constant; CaseTestExpr is a convenient choice.
1843 dummyexpr = makeNode(CaseTestExpr);
1844 dummyexpr->typeId = nominal_element_type;
1845 dummyexpr->typeMod = -1;
1846 dummyexpr->collation = clause->inputcollid;
1847 args = list_make2(leftop, dummyexpr);
1849 s2 = DatumGetFloat8(FunctionCall5(&oprselproc,
1850 PointerGetDatum(root),
1851 ObjectIdGetDatum(operator),
1852 PointerGetDatum(args),
1853 Int16GetDatum(jointype),
1854 PointerGetDatum(sjinfo)));
1856 s2 = DatumGetFloat8(FunctionCall4(&oprselproc,
1857 PointerGetDatum(root),
1858 ObjectIdGetDatum(operator),
1859 PointerGetDatum(args),
1860 Int32GetDatum(varRelid)));
1861 s1 = useOr ? 0.0 : 1.0;
1864 * Arbitrarily assume 10 elements in the eventual array value (see
1865 * also estimate_array_length)
1867 for (i = 0; i < 10; i++)
1870 s1 = s1 + s2 - s1 * s2;
1876 /* result should be in range, but make sure... */
1877 CLAMP_PROBABILITY(s1);
1883 * Estimate number of elements in the array yielded by an expression.
1885 * It's important that this agree with scalararraysel.
1888 estimate_array_length(Node *arrayexpr)
1890 /* look through any binary-compatible relabeling of arrayexpr */
1891 arrayexpr = strip_array_coercion(arrayexpr);
1893 if (arrayexpr && IsA(arrayexpr, Const))
1895 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
1896 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
1897 ArrayType *arrayval;
1901 arrayval = DatumGetArrayTypeP(arraydatum);
1902 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1904 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
1905 !((ArrayExpr *) arrayexpr)->multidims)
1907 return list_length(((ArrayExpr *) arrayexpr)->elements);
1911 /* default guess --- see also scalararraysel */
1917 * rowcomparesel - Selectivity of RowCompareExpr Node.
1919 * We estimate RowCompare selectivity by considering just the first (high
1920 * order) columns, which makes it equivalent to an ordinary OpExpr. While
1921 * this estimate could be refined by considering additional columns, it
1922 * seems unlikely that we could do a lot better without multi-column
1926 rowcomparesel(PlannerInfo *root,
1927 RowCompareExpr *clause,
1928 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1931 Oid opno = linitial_oid(clause->opnos);
1933 bool is_join_clause;
1935 /* Build equivalent arg list for single operator */
1936 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
1939 * Decide if it's a join clause. This should match clausesel.c's
1940 * treat_as_join_clause(), except that we intentionally consider only the
1941 * leading columns and not the rest of the clause.
1946 * Caller is forcing restriction mode (eg, because we are examining an
1947 * inner indexscan qual).
1949 is_join_clause = false;
1951 else if (sjinfo == NULL)
1954 * It must be a restriction clause, since it's being evaluated at a
1957 is_join_clause = false;
1962 * Otherwise, it's a join if there's more than one relation used.
1964 is_join_clause = (NumRelids((Node *) opargs) > 1);
1969 /* Estimate selectivity for a join clause. */
1970 s1 = join_selectivity(root, opno,
1977 /* Estimate selectivity for a restriction clause. */
1978 s1 = restriction_selectivity(root, opno,
1987 * eqjoinsel - Join selectivity of "="
1990 eqjoinsel(PG_FUNCTION_ARGS)
1992 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1993 Oid operator = PG_GETARG_OID(1);
1994 List *args = (List *) PG_GETARG_POINTER(2);
1997 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
1999 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2001 VariableStatData vardata1;
2002 VariableStatData vardata2;
2003 bool join_is_reversed;
2005 get_join_variables(root, args, sjinfo,
2006 &vardata1, &vardata2, &join_is_reversed);
2008 switch (sjinfo->jointype)
2013 selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2017 if (!join_is_reversed)
2018 selec = eqjoinsel_semi(operator, &vardata1, &vardata2);
2020 selec = eqjoinsel_semi(get_commutator(operator),
2021 &vardata2, &vardata1);
2024 /* other values not expected here */
2025 elog(ERROR, "unrecognized join type: %d",
2026 (int) sjinfo->jointype);
2027 selec = 0; /* keep compiler quiet */
2031 ReleaseVariableStats(vardata1);
2032 ReleaseVariableStats(vardata2);
2034 CLAMP_PROBABILITY(selec);
2036 PG_RETURN_FLOAT8((float8) selec);
2040 * eqjoinsel_inner --- eqjoinsel for normal inner join
2042 * We also use this for LEFT/FULL outer joins; it's not presently clear
2043 * that it's worth trying to distinguish them here.
2046 eqjoinsel_inner(Oid operator,
2047 VariableStatData *vardata1, VariableStatData *vardata2)
2052 Form_pg_statistic stats1 = NULL;
2053 Form_pg_statistic stats2 = NULL;
2054 bool have_mcvs1 = false;
2055 Datum *values1 = NULL;
2057 float4 *numbers1 = NULL;
2059 bool have_mcvs2 = false;
2060 Datum *values2 = NULL;
2062 float4 *numbers2 = NULL;
2065 nd1 = get_variable_numdistinct(vardata1);
2066 nd2 = get_variable_numdistinct(vardata2);
2068 if (HeapTupleIsValid(vardata1->statsTuple))
2070 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2071 have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2073 vardata1->atttypmod,
2077 &values1, &nvalues1,
2078 &numbers1, &nnumbers1);
2081 if (HeapTupleIsValid(vardata2->statsTuple))
2083 stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2084 have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2086 vardata2->atttypmod,
2090 &values2, &nvalues2,
2091 &numbers2, &nnumbers2);
2094 if (have_mcvs1 && have_mcvs2)
2097 * We have most-common-value lists for both relations. Run through
2098 * the lists to see which MCVs actually join to each other with the
2099 * given operator. This allows us to determine the exact join
2100 * selectivity for the portion of the relations represented by the MCV
2101 * lists. We still have to estimate for the remaining population, but
2102 * in a skewed distribution this gives us a big leg up in accuracy.
2103 * For motivation see the analysis in Y. Ioannidis and S.
2104 * Christodoulakis, "On the propagation of errors in the size of join
2105 * results", Technical Report 1018, Computer Science Dept., University
2106 * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2111 double nullfrac1 = stats1->stanullfrac;
2112 double nullfrac2 = stats2->stanullfrac;
2113 double matchprodfreq,
2125 fmgr_info(get_opcode(operator), &eqproc);
2126 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &eqproc);
2127 hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2128 hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
2131 * Note we assume that each MCV will match at most one member of the
2132 * other MCV list. If the operator isn't really equality, there could
2133 * be multiple matches --- but we don't look for them, both for speed
2134 * and because the math wouldn't add up...
2136 matchprodfreq = 0.0;
2138 for (i = 0; i < nvalues1; i++)
2142 for (j = 0; j < nvalues2; j++)
2146 if (DatumGetBool(FunctionCall2(&eqproc,
2150 hasmatch1[i] = hasmatch2[j] = true;
2151 matchprodfreq += numbers1[i] * numbers2[j];
2157 CLAMP_PROBABILITY(matchprodfreq);
2158 /* Sum up frequencies of matched and unmatched MCVs */
2159 matchfreq1 = unmatchfreq1 = 0.0;
2160 for (i = 0; i < nvalues1; i++)
2163 matchfreq1 += numbers1[i];
2165 unmatchfreq1 += numbers1[i];
2167 CLAMP_PROBABILITY(matchfreq1);
2168 CLAMP_PROBABILITY(unmatchfreq1);
2169 matchfreq2 = unmatchfreq2 = 0.0;
2170 for (i = 0; i < nvalues2; i++)
2173 matchfreq2 += numbers2[i];
2175 unmatchfreq2 += numbers2[i];
2177 CLAMP_PROBABILITY(matchfreq2);
2178 CLAMP_PROBABILITY(unmatchfreq2);
2183 * Compute total frequency of non-null values that are not in the MCV
2186 otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2187 otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2188 CLAMP_PROBABILITY(otherfreq1);
2189 CLAMP_PROBABILITY(otherfreq2);
2192 * We can estimate the total selectivity from the point of view of
2193 * relation 1 as: the known selectivity for matched MCVs, plus
2194 * unmatched MCVs that are assumed to match against random members of
2195 * relation 2's non-MCV population, plus non-MCV values that are
2196 * assumed to match against random members of relation 2's unmatched
2197 * MCVs plus non-MCV values.
2199 totalsel1 = matchprodfreq;
2201 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
2203 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2205 /* Same estimate from the point of view of relation 2. */
2206 totalsel2 = matchprodfreq;
2208 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
2210 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2214 * Use the smaller of the two estimates. This can be justified in
2215 * essentially the same terms as given below for the no-stats case: to
2216 * a first approximation, we are estimating from the point of view of
2217 * the relation with smaller nd.
2219 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2224 * We do not have MCV lists for both sides. Estimate the join
2225 * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2226 * is plausible if we assume that the join operator is strict and the
2227 * non-null values are about equally distributed: a given non-null
2228 * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2229 * of rel2, so total join rows are at most
2230 * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2231 * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2232 * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2233 * with MIN() is an upper bound. Using the MIN() means we estimate
2234 * from the point of view of the relation with smaller nd (since the
2235 * larger nd is determining the MIN). It is reasonable to assume that
2236 * most tuples in this rel will have join partners, so the bound is
2237 * probably reasonably tight and should be taken as-is.
2239 * XXX Can we be smarter if we have an MCV list for just one side? It
2240 * seems that if we assume equal distribution for the other side, we
2241 * end up with the same answer anyway.
2243 * An additional hack we use here is to clamp the nd1 and nd2 values
2244 * to not more than what we are estimating the input relation sizes to
2245 * be, providing a crude correction for the selectivity of restriction
2246 * clauses on those relations. (We don't do that in the other path
2247 * since there we are comparing the nd values to stats for the whole
2250 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2251 double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2254 nd1 = Min(nd1, vardata1->rel->rows);
2256 nd2 = Min(nd2, vardata2->rel->rows);
2258 selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2266 free_attstatsslot(vardata1->atttype, values1, nvalues1,
2267 numbers1, nnumbers1);
2269 free_attstatsslot(vardata2->atttype, values2, nvalues2,
2270 numbers2, nnumbers2);
2276 * eqjoinsel_semi --- eqjoinsel for semi join
2278 * (Also used for anti join, which we are supposed to estimate the same way.)
2279 * Caller has ensured that vardata1 is the LHS variable.
2282 eqjoinsel_semi(Oid operator,
2283 VariableStatData *vardata1, VariableStatData *vardata2)
2288 Form_pg_statistic stats1 = NULL;
2289 Form_pg_statistic stats2 = NULL;
2290 bool have_mcvs1 = false;
2291 Datum *values1 = NULL;
2293 float4 *numbers1 = NULL;
2295 bool have_mcvs2 = false;
2296 Datum *values2 = NULL;
2298 float4 *numbers2 = NULL;
2301 nd1 = get_variable_numdistinct(vardata1);
2302 nd2 = get_variable_numdistinct(vardata2);
2304 if (HeapTupleIsValid(vardata1->statsTuple))
2306 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2307 have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2309 vardata1->atttypmod,
2313 &values1, &nvalues1,
2314 &numbers1, &nnumbers1);
2317 if (HeapTupleIsValid(vardata2->statsTuple))
2319 stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2320 have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2322 vardata2->atttypmod,
2326 &values2, &nvalues2,
2327 &numbers2, &nnumbers2);
2330 if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
2333 * We have most-common-value lists for both relations. Run through
2334 * the lists to see which MCVs actually join to each other with the
2335 * given operator. This allows us to determine the exact join
2336 * selectivity for the portion of the relations represented by the MCV
2337 * lists. We still have to estimate for the remaining population, but
2338 * in a skewed distribution this gives us a big leg up in accuracy.
2343 double nullfrac1 = stats1->stanullfrac;
2348 fmgr_info(get_opcode(operator), &eqproc);
2349 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &eqproc);
2350 hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2351 hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
2354 * Note we assume that each MCV will match at most one member of the
2355 * other MCV list. If the operator isn't really equality, there could
2356 * be multiple matches --- but we don't look for them, both for speed
2357 * and because the math wouldn't add up...
2360 for (i = 0; i < nvalues1; i++)
2364 for (j = 0; j < nvalues2; j++)
2368 if (DatumGetBool(FunctionCall2(&eqproc,
2372 hasmatch1[i] = hasmatch2[j] = true;
2378 /* Sum up frequencies of matched MCVs */
2380 for (i = 0; i < nvalues1; i++)
2383 matchfreq1 += numbers1[i];
2385 CLAMP_PROBABILITY(matchfreq1);
2390 * Now we need to estimate the fraction of relation 1 that has at
2391 * least one join partner. We know for certain that the matched MCVs
2392 * do, so that gives us a lower bound, but we're really in the dark
2393 * about everything else. Our crude approach is: if nd1 <= nd2 then
2394 * assume all non-null rel1 rows have join partners, else assume for
2395 * the uncertain rows that a fraction nd2/nd1 have join partners. We
2396 * can discount the known-matched MCVs from the distinct-values counts
2397 * before doing the division.
2401 if (nd1 <= nd2 || nd2 <= 0)
2402 selec = Max(matchfreq1, 1.0 - nullfrac1);
2405 double uncertain = 1.0 - matchfreq1 - nullfrac1;
2407 CLAMP_PROBABILITY(uncertain);
2408 selec = matchfreq1 + (nd2 / nd1) * uncertain;
2414 * Without MCV lists for both sides, we can only use the heuristic
2417 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2420 nd1 = Min(nd1, vardata1->rel->rows);
2422 nd2 = Min(nd2, vardata2->rel->rows);
2424 if (nd1 <= nd2 || nd2 <= 0)
2425 selec = 1.0 - nullfrac1;
2427 selec = (nd2 / nd1) * (1.0 - nullfrac1);
2431 free_attstatsslot(vardata1->atttype, values1, nvalues1,
2432 numbers1, nnumbers1);
2434 free_attstatsslot(vardata2->atttype, values2, nvalues2,
2435 numbers2, nnumbers2);
2441 * neqjoinsel - Join selectivity of "!="
2444 neqjoinsel(PG_FUNCTION_ARGS)
2446 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2447 Oid operator = PG_GETARG_OID(1);
2448 List *args = (List *) PG_GETARG_POINTER(2);
2449 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2450 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2455 * We want 1 - eqjoinsel() where the equality operator is the one
2456 * associated with this != operator, that is, its negator.
2458 eqop = get_negator(operator);
2461 result = DatumGetFloat8(DirectFunctionCall5(eqjoinsel,
2462 PointerGetDatum(root),
2463 ObjectIdGetDatum(eqop),
2464 PointerGetDatum(args),
2465 Int16GetDatum(jointype),
2466 PointerGetDatum(sjinfo)));
2470 /* Use default selectivity (should we raise an error instead?) */
2471 result = DEFAULT_EQ_SEL;
2473 result = 1.0 - result;
2474 PG_RETURN_FLOAT8(result);
2478 * scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
2481 scalarltjoinsel(PG_FUNCTION_ARGS)
2483 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2487 * scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
2490 scalargtjoinsel(PG_FUNCTION_ARGS)
2492 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2496 * patternjoinsel - Generic code for pattern-match join selectivity.
2499 patternjoinsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
2501 /* For the moment we just punt. */
2502 return negate ? (1.0 - DEFAULT_MATCH_SEL) : DEFAULT_MATCH_SEL;
2506 * regexeqjoinsel - Join selectivity of regular-expression pattern match.
2509 regexeqjoinsel(PG_FUNCTION_ARGS)
2511 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, false));
2515 * icregexeqjoinsel - Join selectivity of case-insensitive regex match.
2518 icregexeqjoinsel(PG_FUNCTION_ARGS)
2520 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, false));
2524 * likejoinsel - Join selectivity of LIKE pattern match.
2527 likejoinsel(PG_FUNCTION_ARGS)
2529 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, false));
2533 * iclikejoinsel - Join selectivity of ILIKE pattern match.
2536 iclikejoinsel(PG_FUNCTION_ARGS)
2538 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, false));
2542 * regexnejoinsel - Join selectivity of regex non-match.
2545 regexnejoinsel(PG_FUNCTION_ARGS)
2547 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, true));
2551 * icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
2554 icregexnejoinsel(PG_FUNCTION_ARGS)
2556 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, true));
2560 * nlikejoinsel - Join selectivity of LIKE pattern non-match.
2563 nlikejoinsel(PG_FUNCTION_ARGS)
2565 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, true));
2569 * icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
2572 icnlikejoinsel(PG_FUNCTION_ARGS)
2574 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, true));
2578 * mergejoinscansel - Scan selectivity of merge join.
2580 * A merge join will stop as soon as it exhausts either input stream.
2581 * Therefore, if we can estimate the ranges of both input variables,
2582 * we can estimate how much of the input will actually be read. This
2583 * can have a considerable impact on the cost when using indexscans.
2585 * Also, we can estimate how much of each input has to be read before the
2586 * first join pair is found, which will affect the join's startup time.
2588 * clause should be a clause already known to be mergejoinable. opfamily,
2589 * strategy, and nulls_first specify the sort ordering being used.
2592 * *leftstart is set to the fraction of the left-hand variable expected
2593 * to be scanned before the first join pair is found (0 to 1).
2594 * *leftend is set to the fraction of the left-hand variable expected
2595 * to be scanned before the join terminates (0 to 1).
2596 * *rightstart, *rightend similarly for the right-hand variable.
2599 mergejoinscansel(PlannerInfo *root, Node *clause,
2600 Oid opfamily, int strategy, bool nulls_first,
2601 Selectivity *leftstart, Selectivity *leftend,
2602 Selectivity *rightstart, Selectivity *rightend)
2606 VariableStatData leftvar,
2627 /* Set default results if we can't figure anything out. */
2628 /* XXX should default "start" fraction be a bit more than 0? */
2629 *leftstart = *rightstart = 0.0;
2630 *leftend = *rightend = 1.0;
2632 /* Deconstruct the merge clause */
2633 if (!is_opclause(clause))
2634 return; /* shouldn't happen */
2635 opno = ((OpExpr *) clause)->opno;
2636 left = get_leftop((Expr *) clause);
2637 right = get_rightop((Expr *) clause);
2639 return; /* shouldn't happen */
2641 /* Look for stats for the inputs */
2642 examine_variable(root, left, 0, &leftvar);
2643 examine_variable(root, right, 0, &rightvar);
2645 /* Extract the operator's declared left/right datatypes */
2646 get_op_opfamily_properties(opno, opfamily, false,
2650 Assert(op_strategy == BTEqualStrategyNumber);
2653 * Look up the various operators we need. If we don't find them all, it
2654 * probably means the opfamily is broken, but we just fail silently.
2656 * Note: we expect that pg_statistic histograms will be sorted by the '<'
2657 * operator, regardless of which sort direction we are considering.
2661 case BTLessStrategyNumber:
2663 if (op_lefttype == op_righttype)
2666 ltop = get_opfamily_member(opfamily,
2667 op_lefttype, op_righttype,
2668 BTLessStrategyNumber);
2669 leop = get_opfamily_member(opfamily,
2670 op_lefttype, op_righttype,
2671 BTLessEqualStrategyNumber);
2681 ltop = get_opfamily_member(opfamily,
2682 op_lefttype, op_righttype,
2683 BTLessStrategyNumber);
2684 leop = get_opfamily_member(opfamily,
2685 op_lefttype, op_righttype,
2686 BTLessEqualStrategyNumber);
2687 lsortop = get_opfamily_member(opfamily,
2688 op_lefttype, op_lefttype,
2689 BTLessStrategyNumber);
2690 rsortop = get_opfamily_member(opfamily,
2691 op_righttype, op_righttype,
2692 BTLessStrategyNumber);
2695 revltop = get_opfamily_member(opfamily,
2696 op_righttype, op_lefttype,
2697 BTLessStrategyNumber);
2698 revleop = get_opfamily_member(opfamily,
2699 op_righttype, op_lefttype,
2700 BTLessEqualStrategyNumber);
2703 case BTGreaterStrategyNumber:
2704 /* descending-order case */
2706 if (op_lefttype == op_righttype)
2709 ltop = get_opfamily_member(opfamily,
2710 op_lefttype, op_righttype,
2711 BTGreaterStrategyNumber);
2712 leop = get_opfamily_member(opfamily,
2713 op_lefttype, op_righttype,
2714 BTGreaterEqualStrategyNumber);
2717 lstatop = get_opfamily_member(opfamily,
2718 op_lefttype, op_lefttype,
2719 BTLessStrategyNumber);
2726 ltop = get_opfamily_member(opfamily,
2727 op_lefttype, op_righttype,
2728 BTGreaterStrategyNumber);
2729 leop = get_opfamily_member(opfamily,
2730 op_lefttype, op_righttype,
2731 BTGreaterEqualStrategyNumber);
2732 lsortop = get_opfamily_member(opfamily,
2733 op_lefttype, op_lefttype,
2734 BTGreaterStrategyNumber);
2735 rsortop = get_opfamily_member(opfamily,
2736 op_righttype, op_righttype,
2737 BTGreaterStrategyNumber);
2738 lstatop = get_opfamily_member(opfamily,
2739 op_lefttype, op_lefttype,
2740 BTLessStrategyNumber);
2741 rstatop = get_opfamily_member(opfamily,
2742 op_righttype, op_righttype,
2743 BTLessStrategyNumber);
2744 revltop = get_opfamily_member(opfamily,
2745 op_righttype, op_lefttype,
2746 BTGreaterStrategyNumber);
2747 revleop = get_opfamily_member(opfamily,
2748 op_righttype, op_lefttype,
2749 BTGreaterEqualStrategyNumber);
2753 goto fail; /* shouldn't get here */
2756 if (!OidIsValid(lsortop) ||
2757 !OidIsValid(rsortop) ||
2758 !OidIsValid(lstatop) ||
2759 !OidIsValid(rstatop) ||
2760 !OidIsValid(ltop) ||
2761 !OidIsValid(leop) ||
2762 !OidIsValid(revltop) ||
2763 !OidIsValid(revleop))
2764 goto fail; /* insufficient info in catalogs */
2766 /* Try to get ranges of both inputs */
2769 if (!get_variable_range(root, &leftvar, lstatop,
2770 &leftmin, &leftmax))
2771 goto fail; /* no range available from stats */
2772 if (!get_variable_range(root, &rightvar, rstatop,
2773 &rightmin, &rightmax))
2774 goto fail; /* no range available from stats */
2778 /* need to swap the max and min */
2779 if (!get_variable_range(root, &leftvar, lstatop,
2780 &leftmax, &leftmin))
2781 goto fail; /* no range available from stats */
2782 if (!get_variable_range(root, &rightvar, rstatop,
2783 &rightmax, &rightmin))
2784 goto fail; /* no range available from stats */
2788 * Now, the fraction of the left variable that will be scanned is the
2789 * fraction that's <= the right-side maximum value. But only believe
2790 * non-default estimates, else stick with our 1.0.
2792 selec = scalarineqsel(root, leop, isgt, &leftvar,
2793 rightmax, op_righttype);
2794 if (selec != DEFAULT_INEQ_SEL)
2797 /* And similarly for the right variable. */
2798 selec = scalarineqsel(root, revleop, isgt, &rightvar,
2799 leftmax, op_lefttype);
2800 if (selec != DEFAULT_INEQ_SEL)
2804 * Only one of the two "end" fractions can really be less than 1.0;
2805 * believe the smaller estimate and reset the other one to exactly 1.0. If
2806 * we get exactly equal estimates (as can easily happen with self-joins),
2809 if (*leftend > *rightend)
2811 else if (*leftend < *rightend)
2814 *leftend = *rightend = 1.0;
2817 * Also, the fraction of the left variable that will be scanned before the
2818 * first join pair is found is the fraction that's < the right-side
2819 * minimum value. But only believe non-default estimates, else stick with
2822 selec = scalarineqsel(root, ltop, isgt, &leftvar,
2823 rightmin, op_righttype);
2824 if (selec != DEFAULT_INEQ_SEL)
2827 /* And similarly for the right variable. */
2828 selec = scalarineqsel(root, revltop, isgt, &rightvar,
2829 leftmin, op_lefttype);
2830 if (selec != DEFAULT_INEQ_SEL)
2831 *rightstart = selec;
2834 * Only one of the two "start" fractions can really be more than zero;
2835 * believe the larger estimate and reset the other one to exactly 0.0. If
2836 * we get exactly equal estimates (as can easily happen with self-joins),
2839 if (*leftstart < *rightstart)
2841 else if (*leftstart > *rightstart)
2844 *leftstart = *rightstart = 0.0;
2847 * If the sort order is nulls-first, we're going to have to skip over any
2848 * nulls too. These would not have been counted by scalarineqsel, and we
2849 * can safely add in this fraction regardless of whether we believe
2850 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
2854 Form_pg_statistic stats;
2856 if (HeapTupleIsValid(leftvar.statsTuple))
2858 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
2859 *leftstart += stats->stanullfrac;
2860 CLAMP_PROBABILITY(*leftstart);
2861 *leftend += stats->stanullfrac;
2862 CLAMP_PROBABILITY(*leftend);
2864 if (HeapTupleIsValid(rightvar.statsTuple))
2866 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
2867 *rightstart += stats->stanullfrac;
2868 CLAMP_PROBABILITY(*rightstart);
2869 *rightend += stats->stanullfrac;
2870 CLAMP_PROBABILITY(*rightend);
2874 /* Disbelieve start >= end, just in case that can happen */
2875 if (*leftstart >= *leftend)
2880 if (*rightstart >= *rightend)
2887 ReleaseVariableStats(leftvar);
2888 ReleaseVariableStats(rightvar);
2893 * Helper routine for estimate_num_groups: add an item to a list of
2894 * GroupVarInfos, but only if it's not known equal to any of the existing
2899 Node *var; /* might be an expression, not just a Var */
2900 RelOptInfo *rel; /* relation it belongs to */
2901 double ndistinct; /* # distinct values */
2905 add_unique_group_var(PlannerInfo *root, List *varinfos,
2906 Node *var, VariableStatData *vardata)
2908 GroupVarInfo *varinfo;
2912 ndistinct = get_variable_numdistinct(vardata);
2914 /* cannot use foreach here because of possible list_delete */
2915 lc = list_head(varinfos);
2918 varinfo = (GroupVarInfo *) lfirst(lc);
2920 /* must advance lc before list_delete possibly pfree's it */
2923 /* Drop exact duplicates */
2924 if (equal(var, varinfo->var))
2928 * Drop known-equal vars, but only if they belong to different
2929 * relations (see comments for estimate_num_groups)
2931 if (vardata->rel != varinfo->rel &&
2932 exprs_known_equal(root, var, varinfo->var))
2934 if (varinfo->ndistinct <= ndistinct)
2936 /* Keep older item, forget new one */
2941 /* Delete the older item */
2942 varinfos = list_delete_ptr(varinfos, varinfo);
2947 varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
2950 varinfo->rel = vardata->rel;
2951 varinfo->ndistinct = ndistinct;
2952 varinfos = lappend(varinfos, varinfo);
2957 * estimate_num_groups - Estimate number of groups in a grouped query
2959 * Given a query having a GROUP BY clause, estimate how many groups there
2960 * will be --- ie, the number of distinct combinations of the GROUP BY
2963 * This routine is also used to estimate the number of rows emitted by
2964 * a DISTINCT filtering step; that is an isomorphic problem. (Note:
2965 * actually, we only use it for DISTINCT when there's no grouping or
2966 * aggregation ahead of the DISTINCT.)
2970 * groupExprs - list of expressions being grouped by
2971 * input_rows - number of rows estimated to arrive at the group/unique
2974 * Given the lack of any cross-correlation statistics in the system, it's
2975 * impossible to do anything really trustworthy with GROUP BY conditions
2976 * involving multiple Vars. We should however avoid assuming the worst
2977 * case (all possible cross-product terms actually appear as groups) since
2978 * very often the grouped-by Vars are highly correlated. Our current approach
2980 * 1. Expressions yielding boolean are assumed to contribute two groups,
2981 * independently of their content, and are ignored in the subsequent
2982 * steps. This is mainly because tests like "col IS NULL" break the
2983 * heuristic used in step 2 especially badly.
2984 * 2. Reduce the given expressions to a list of unique Vars used. For
2985 * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
2986 * It is clearly correct not to count the same Var more than once.
2987 * It is also reasonable to treat f(x) the same as x: f() cannot
2988 * increase the number of distinct values (unless it is volatile,
2989 * which we consider unlikely for grouping), but it probably won't
2990 * reduce the number of distinct values much either.
2991 * As a special case, if a GROUP BY expression can be matched to an
2992 * expressional index for which we have statistics, then we treat the
2993 * whole expression as though it were just a Var.
2994 * 3. If the list contains Vars of different relations that are known equal
2995 * due to equivalence classes, then drop all but one of the Vars from each
2996 * known-equal set, keeping the one with smallest estimated # of values
2997 * (since the extra values of the others can't appear in joined rows).
2998 * Note the reason we only consider Vars of different relations is that
2999 * if we considered ones of the same rel, we'd be double-counting the
3000 * restriction selectivity of the equality in the next step.
3001 * 4. For Vars within a single source rel, we multiply together the numbers
3002 * of values, clamp to the number of rows in the rel (divided by 10 if
3003 * more than one Var), and then multiply by the selectivity of the
3004 * restriction clauses for that rel. When there's more than one Var,
3005 * the initial product is probably too high (it's the worst case) but
3006 * clamping to a fraction of the rel's rows seems to be a helpful
3007 * heuristic for not letting the estimate get out of hand. (The factor
3008 * of 10 is derived from pre-Postgres-7.4 practice.) Multiplying
3009 * by the restriction selectivity is effectively assuming that the
3010 * restriction clauses are independent of the grouping, which is a crummy
3011 * assumption, but it's hard to do better.
3012 * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3013 * rel, and multiply the results together.
3014 * Note that rels not containing grouped Vars are ignored completely, as are
3015 * join clauses. Such rels cannot increase the number of groups, and we
3016 * assume such clauses do not reduce the number either (somewhat bogus,
3017 * but we don't have the info to do better).
3020 estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows)
3022 List *varinfos = NIL;
3026 /* We should not be called unless query has GROUP BY (or DISTINCT) */
3027 Assert(groupExprs != NIL);
3030 * Count groups derived from boolean grouping expressions. For other
3031 * expressions, find the unique Vars used, treating an expression as a Var
3032 * if we can find stats for it. For each one, record the statistical
3033 * estimate of number of distinct values (total in its table, without
3034 * regard for filtering).
3038 foreach(l, groupExprs)
3040 Node *groupexpr = (Node *) lfirst(l);
3041 VariableStatData vardata;
3045 /* Short-circuit for expressions returning boolean */
3046 if (exprType(groupexpr) == BOOLOID)
3053 * If examine_variable is able to deduce anything about the GROUP BY
3054 * expression, treat it as a single variable even if it's really more
3057 examine_variable(root, groupexpr, 0, &vardata);
3058 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3060 varinfos = add_unique_group_var(root, varinfos,
3061 groupexpr, &vardata);
3062 ReleaseVariableStats(vardata);
3065 ReleaseVariableStats(vardata);
3068 * Else pull out the component Vars. Handle PlaceHolderVars by
3069 * recursing into their arguments (effectively assuming that the
3070 * PlaceHolderVar doesn't change the number of groups, which boils
3071 * down to ignoring the possible addition of nulls to the result set).
3073 varshere = pull_var_clause(groupexpr, PVC_RECURSE_PLACEHOLDERS);
3076 * If we find any variable-free GROUP BY item, then either it is a
3077 * constant (and we can ignore it) or it contains a volatile function;
3078 * in the latter case we punt and assume that each input row will
3079 * yield a distinct group.
3081 if (varshere == NIL)
3083 if (contain_volatile_functions(groupexpr))
3089 * Else add variables to varinfos list
3091 foreach(l2, varshere)
3093 Node *var = (Node *) lfirst(l2);
3095 examine_variable(root, var, 0, &vardata);
3096 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3097 ReleaseVariableStats(vardata);
3102 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3105 if (varinfos == NIL)
3107 /* Guard against out-of-range answers */
3108 if (numdistinct > input_rows)
3109 numdistinct = input_rows;
3114 * Group Vars by relation and estimate total numdistinct.
3116 * For each iteration of the outer loop, we process the frontmost Var in
3117 * varinfos, plus all other Vars in the same relation. We remove these
3118 * Vars from the newvarinfos list for the next iteration. This is the
3119 * easiest way to group Vars of same rel together.
3123 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3124 RelOptInfo *rel = varinfo1->rel;
3125 double reldistinct = varinfo1->ndistinct;
3126 double relmaxndistinct = reldistinct;
3127 int relvarcount = 1;
3128 List *newvarinfos = NIL;
3131 * Get the product of numdistinct estimates of the Vars for this rel.
3132 * Also, construct new varinfos list of remaining Vars.
3134 for_each_cell(l, lnext(list_head(varinfos)))
3136 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3138 if (varinfo2->rel == varinfo1->rel)
3140 reldistinct *= varinfo2->ndistinct;
3141 if (relmaxndistinct < varinfo2->ndistinct)
3142 relmaxndistinct = varinfo2->ndistinct;
3147 /* not time to process varinfo2 yet */
3148 newvarinfos = lcons(varinfo2, newvarinfos);
3153 * Sanity check --- don't divide by zero if empty relation.
3155 Assert(rel->reloptkind == RELOPT_BASEREL);
3156 if (rel->tuples > 0)
3159 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3160 * fudge factor is because the Vars are probably correlated but we
3161 * don't know by how much. We should never clamp to less than the
3162 * largest ndistinct value for any of the Vars, though, since
3163 * there will surely be at least that many groups.
3165 double clamp = rel->tuples;
3167 if (relvarcount > 1)
3170 if (clamp < relmaxndistinct)
3172 clamp = relmaxndistinct;
3173 /* for sanity in case some ndistinct is too large: */
3174 if (clamp > rel->tuples)
3175 clamp = rel->tuples;
3178 if (reldistinct > clamp)
3179 reldistinct = clamp;
3182 * Multiply by restriction selectivity.
3184 reldistinct *= rel->rows / rel->tuples;
3187 * Update estimate of total distinct groups.
3189 numdistinct *= reldistinct;
3192 varinfos = newvarinfos;
3193 } while (varinfos != NIL);
3195 numdistinct = ceil(numdistinct);
3197 /* Guard against out-of-range answers */
3198 if (numdistinct > input_rows)
3199 numdistinct = input_rows;
3200 if (numdistinct < 1.0)
3207 * Estimate hash bucketsize fraction (ie, number of entries in a bucket
3208 * divided by total tuples in relation) if the specified expression is used
3211 * XXX This is really pretty bogus since we're effectively assuming that the
3212 * distribution of hash keys will be the same after applying restriction
3213 * clauses as it was in the underlying relation. However, we are not nearly
3214 * smart enough to figure out how the restrict clauses might change the
3215 * distribution, so this will have to do for now.
3217 * We are passed the number of buckets the executor will use for the given
3218 * input relation. If the data were perfectly distributed, with the same
3219 * number of tuples going into each available bucket, then the bucketsize
3220 * fraction would be 1/nbuckets. But this happy state of affairs will occur
3221 * only if (a) there are at least nbuckets distinct data values, and (b)
3222 * we have a not-too-skewed data distribution. Otherwise the buckets will
3223 * be nonuniformly occupied. If the other relation in the join has a key
3224 * distribution similar to this one's, then the most-loaded buckets are
3225 * exactly those that will be probed most often. Therefore, the "average"
3226 * bucket size for costing purposes should really be taken as something close
3227 * to the "worst case" bucket size. We try to estimate this by adjusting the
3228 * fraction if there are too few distinct data values, and then scaling up
3229 * by the ratio of the most common value's frequency to the average frequency.
3231 * If no statistics are available, use a default estimate of 0.1. This will
3232 * discourage use of a hash rather strongly if the inner relation is large,
3233 * which is what we want. We do not want to hash unless we know that the
3234 * inner rel is well-dispersed (or the alternatives seem much worse).
3237 estimate_hash_bucketsize(PlannerInfo *root, Node *hashkey, double nbuckets)
3239 VariableStatData vardata;
3248 examine_variable(root, hashkey, 0, &vardata);
3250 /* Get number of distinct values and fraction that are null */
3251 ndistinct = get_variable_numdistinct(&vardata);
3253 if (HeapTupleIsValid(vardata.statsTuple))
3255 Form_pg_statistic stats;
3257 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3258 stanullfrac = stats->stanullfrac;
3263 * Believe a default ndistinct only if it came from stats. Otherwise
3264 * punt and return 0.1, per comments above.
3266 if (ndistinct == DEFAULT_NUM_DISTINCT)
3268 ReleaseVariableStats(vardata);
3269 return (Selectivity) 0.1;
3275 /* Compute avg freq of all distinct data values in raw relation */
3276 avgfreq = (1.0 - stanullfrac) / ndistinct;
3279 * Adjust ndistinct to account for restriction clauses. Observe we are
3280 * assuming that the data distribution is affected uniformly by the
3281 * restriction clauses!
3283 * XXX Possibly better way, but much more expensive: multiply by
3284 * selectivity of rel's restriction clauses that mention the target Var.
3287 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3290 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3291 * number of buckets is less than the expected number of distinct values;
3292 * otherwise it is 1/ndistinct.
3294 if (ndistinct > nbuckets)
3295 estfract = 1.0 / nbuckets;
3297 estfract = 1.0 / ndistinct;
3300 * Look up the frequency of the most common value, if available.
3304 if (HeapTupleIsValid(vardata.statsTuple))
3306 if (get_attstatsslot(vardata.statsTuple,
3307 vardata.atttype, vardata.atttypmod,
3308 STATISTIC_KIND_MCV, InvalidOid,
3311 &numbers, &nnumbers))
3314 * The first MCV stat is for the most common value.
3317 mcvfreq = numbers[0];
3318 free_attstatsslot(vardata.atttype, NULL, 0,
3324 * Adjust estimated bucketsize upward to account for skewed distribution.
3326 if (avgfreq > 0.0 && mcvfreq > avgfreq)
3327 estfract *= mcvfreq / avgfreq;
3330 * Clamp bucketsize to sane range (the above adjustment could easily
3331 * produce an out-of-range result). We set the lower bound a little above
3332 * zero, since zero isn't a very sane result.
3334 if (estfract < 1.0e-6)
3336 else if (estfract > 1.0)
3339 ReleaseVariableStats(vardata);
3341 return (Selectivity) estfract;
3345 /*-------------------------------------------------------------------------
3349 *-------------------------------------------------------------------------
3354 * Convert non-NULL values of the indicated types to the comparison
3355 * scale needed by scalarineqsel().
3356 * Returns "true" if successful.
3358 * XXX this routine is a hack: ideally we should look up the conversion
3359 * subroutines in pg_type.
3361 * All numeric datatypes are simply converted to their equivalent
3362 * "double" values. (NUMERIC values that are outside the range of "double"
3363 * are clamped to +/- HUGE_VAL.)
3365 * String datatypes are converted by convert_string_to_scalar(),
3366 * which is explained below. The reason why this routine deals with
3367 * three values at a time, not just one, is that we need it for strings.
3369 * The bytea datatype is just enough different from strings that it has
3370 * to be treated separately.
3372 * The several datatypes representing absolute times are all converted
3373 * to Timestamp, which is actually a double, and then we just use that
3374 * double value. Note this will give correct results even for the "special"
3375 * values of Timestamp, since those are chosen to compare correctly;
3376 * see timestamp_cmp.
3378 * The several datatypes representing relative times (intervals) are all
3379 * converted to measurements expressed in seconds.
3382 convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
3383 Datum lobound, Datum hibound, Oid boundstypid,
3384 double *scaledlobound, double *scaledhibound)
3387 * Both the valuetypid and the boundstypid should exactly match the
3388 * declared input type(s) of the operator we are invoked for, so we just
3389 * error out if either is not recognized.
3391 * XXX The histogram we are interpolating between points of could belong
3392 * to a column that's only binary-compatible with the declared type. In
3393 * essence we are assuming that the semantics of binary-compatible types
3394 * are enough alike that we can use a histogram generated with one type's
3395 * operators to estimate selectivity for the other's. This is outright
3396 * wrong in some cases --- in particular signed versus unsigned
3397 * interpretation could trip us up. But it's useful enough in the
3398 * majority of cases that we do it anyway. Should think about more
3399 * rigorous ways to do it.
3404 * Built-in numeric types
3415 case REGPROCEDUREOID:
3417 case REGOPERATOROID:
3421 case REGDICTIONARYOID:
3422 *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
3423 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
3424 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
3428 * Built-in string types
3436 char *valstr = convert_string_datum(value, valuetypid);
3437 char *lostr = convert_string_datum(lobound, boundstypid);
3438 char *histr = convert_string_datum(hibound, boundstypid);
3440 convert_string_to_scalar(valstr, scaledvalue,
3441 lostr, scaledlobound,
3442 histr, scaledhibound);
3450 * Built-in bytea type
3454 convert_bytea_to_scalar(value, scaledvalue,
3455 lobound, scaledlobound,
3456 hibound, scaledhibound);
3461 * Built-in time types
3464 case TIMESTAMPTZOID:
3472 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
3473 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
3474 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
3478 * Built-in network types
3483 *scaledvalue = convert_network_to_scalar(value, valuetypid);
3484 *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
3485 *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
3488 /* Don't know how to convert */
3489 *scaledvalue = *scaledlobound = *scaledhibound = 0;
3494 * Do convert_to_scalar()'s work for any numeric data type.
3497 convert_numeric_to_scalar(Datum value, Oid typid)
3502 return (double) DatumGetBool(value);
3504 return (double) DatumGetInt16(value);
3506 return (double) DatumGetInt32(value);
3508 return (double) DatumGetInt64(value);
3510 return (double) DatumGetFloat4(value);
3512 return (double) DatumGetFloat8(value);
3514 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3516 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
3520 case REGPROCEDUREOID:
3522 case REGOPERATOROID:
3526 case REGDICTIONARYOID:
3527 /* we can treat OIDs as integers... */
3528 return (double) DatumGetObjectId(value);
3532 * Can't get here unless someone tries to use scalarltsel/scalargtsel on
3533 * an operator with one numeric and one non-numeric operand.
3535 elog(ERROR, "unsupported type: %u", typid);
3540 * Do convert_to_scalar()'s work for any character-string data type.
3542 * String datatypes are converted to a scale that ranges from 0 to 1,
3543 * where we visualize the bytes of the string as fractional digits.
3545 * We do not want the base to be 256, however, since that tends to
3546 * generate inflated selectivity estimates; few databases will have
3547 * occurrences of all 256 possible byte values at each position.
3548 * Instead, use the smallest and largest byte values seen in the bounds
3549 * as the estimated range for each byte, after some fudging to deal with
3550 * the fact that we probably aren't going to see the full range that way.
3552 * An additional refinement is that we discard any common prefix of the
3553 * three strings before computing the scaled values. This allows us to
3554 * "zoom in" when we encounter a narrow data range. An example is a phone
3555 * number database where all the values begin with the same area code.
3556 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
3557 * so this is more likely to happen than you might think.)
3560 convert_string_to_scalar(char *value,
3561 double *scaledvalue,
3563 double *scaledlobound,
3565 double *scaledhibound)
3571 rangelo = rangehi = (unsigned char) hibound[0];
3572 for (sptr = lobound; *sptr; sptr++)
3574 if (rangelo > (unsigned char) *sptr)
3575 rangelo = (unsigned char) *sptr;
3576 if (rangehi < (unsigned char) *sptr)
3577 rangehi = (unsigned char) *sptr;
3579 for (sptr = hibound; *sptr; sptr++)
3581 if (rangelo > (unsigned char) *sptr)
3582 rangelo = (unsigned char) *sptr;
3583 if (rangehi < (unsigned char) *sptr)
3584 rangehi = (unsigned char) *sptr;
3586 /* If range includes any upper-case ASCII chars, make it include all */
3587 if (rangelo <= 'Z' && rangehi >= 'A')
3594 /* Ditto lower-case */
3595 if (rangelo <= 'z' && rangehi >= 'a')
3603 if (rangelo <= '9' && rangehi >= '0')
3612 * If range includes less than 10 chars, assume we have not got enough
3613 * data, and make it include regular ASCII set.
3615 if (rangehi - rangelo < 9)
3622 * Now strip any common prefix of the three strings.
3626 if (*lobound != *hibound || *lobound != *value)
3628 lobound++, hibound++, value++;
3632 * Now we can do the conversions.
3634 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
3635 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
3636 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
3640 convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
3642 int slen = strlen(value);
3648 return 0.0; /* empty string has scalar value 0 */
3651 * Since base is at least 10, need not consider more than about 20 chars
3656 /* Convert initial characters to fraction */
3657 base = rangehi - rangelo + 1;
3662 int ch = (unsigned char) *value++;
3666 else if (ch > rangehi)
3668 num += ((double) (ch - rangelo)) / denom;
3676 * Convert a string-type Datum into a palloc'd, null-terminated string.
3678 * When using a non-C locale, we must pass the string through strxfrm()
3679 * before continuing, so as to generate correct locale-specific results.
3682 convert_string_datum(Datum value, Oid typid)
3689 val = (char *) palloc(2);
3690 val[0] = DatumGetChar(value);
3696 val = TextDatumGetCString(value);
3700 NameData *nm = (NameData *) DatumGetPointer(value);
3702 val = pstrdup(NameStr(*nm));
3708 * Can't get here unless someone tries to use scalarltsel on an
3709 * operator with one string and one non-string operand.
3711 elog(ERROR, "unsupported type: %u", typid);
3715 if (!lc_collate_is_c(DEFAULT_COLLATION_OID))
3722 * Note: originally we guessed at a suitable output buffer size, and
3723 * only needed to call strxfrm twice if our guess was too small.
3724 * However, it seems that some versions of Solaris have buggy strxfrm
3725 * that can write past the specified buffer length in that scenario.
3726 * So, do it the dumb way for portability.
3728 * Yet other systems (e.g., glibc) sometimes return a smaller value
3729 * from the second call than the first; thus the Assert must be <= not
3730 * == as you'd expect. Can't any of these people program their way
3731 * out of a paper bag?
3733 * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
3734 * bogus data or set an error. This is not really a problem unless it
3735 * crashes since it will only give an estimation error and nothing
3738 #if _MSC_VER == 1400 /* VS.Net 2005 */
3742 * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?
3743 * FeedbackID=99694 */
3747 xfrmlen = strxfrm(x, val, 0);
3750 xfrmlen = strxfrm(NULL, val, 0);
3755 * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
3756 * of trying to allocate this much memory (and fail), just return the
3757 * original string unmodified as if we were in the C locale.
3759 if (xfrmlen == INT_MAX)
3762 xfrmstr = (char *) palloc(xfrmlen + 1);
3763 xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
3764 Assert(xfrmlen2 <= xfrmlen);
3773 * Do convert_to_scalar()'s work for any bytea data type.
3775 * Very similar to convert_string_to_scalar except we can't assume
3776 * null-termination and therefore pass explicit lengths around.
3778 * Also, assumptions about likely "normal" ranges of characters have been
3779 * removed - a data range of 0..255 is always used, for now. (Perhaps
3780 * someday we will add information about actual byte data range to
3784 convert_bytea_to_scalar(Datum value,
3785 double *scaledvalue,
3787 double *scaledlobound,
3789 double *scaledhibound)
3793 valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
3794 loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
3795 hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
3798 unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
3799 *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
3800 *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
3803 * Assume bytea data is uniformly distributed across all byte values.
3809 * Now strip any common prefix of the three strings.
3811 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
3812 for (i = 0; i < minlen; i++)
3814 if (*lostr != *histr || *lostr != *valstr)
3816 lostr++, histr++, valstr++;
3817 loboundlen--, hiboundlen--, valuelen--;
3821 * Now we can do the conversions.
3823 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
3824 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
3825 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
3829 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
3830 int rangelo, int rangehi)
3837 return 0.0; /* empty string has scalar value 0 */
3840 * Since base is 256, need not consider more than about 10 chars (even
3841 * this many seems like overkill)
3846 /* Convert initial characters to fraction */
3847 base = rangehi - rangelo + 1;
3850 while (valuelen-- > 0)
3856 else if (ch > rangehi)
3858 num += ((double) (ch - rangelo)) / denom;
3866 * Do convert_to_scalar()'s work for any timevalue data type.
3869 convert_timevalue_to_scalar(Datum value, Oid typid)
3874 return DatumGetTimestamp(value);
3875 case TIMESTAMPTZOID:
3876 return DatumGetTimestampTz(value);
3878 return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
3881 return date2timestamp_no_overflow(DatumGetDateADT(value));
3884 Interval *interval = DatumGetIntervalP(value);
3887 * Convert the month part of Interval to days using assumed
3888 * average month length of 365.25/12.0 days. Not too
3889 * accurate, but plenty good enough for our purposes.
3891 #ifdef HAVE_INT64_TIMESTAMP
3892 return interval->time + interval->day * (double) USECS_PER_DAY +
3893 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
3895 return interval->time + interval->day * SECS_PER_DAY +
3896 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * (double) SECS_PER_DAY);
3900 #ifdef HAVE_INT64_TIMESTAMP
3901 return (DatumGetRelativeTime(value) * 1000000.0);
3903 return DatumGetRelativeTime(value);
3907 TimeInterval tinterval = DatumGetTimeInterval(value);
3909 #ifdef HAVE_INT64_TIMESTAMP
3910 if (tinterval->status != 0)
3911 return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
3913 if (tinterval->status != 0)
3914 return tinterval->data[1] - tinterval->data[0];
3916 return 0; /* for lack of a better idea */
3919 return DatumGetTimeADT(value);
3922 TimeTzADT *timetz = DatumGetTimeTzADTP(value);
3924 /* use GMT-equivalent time */
3925 #ifdef HAVE_INT64_TIMESTAMP
3926 return (double) (timetz->time + (timetz->zone * 1000000.0));
3928 return (double) (timetz->time + timetz->zone);
3934 * Can't get here unless someone tries to use scalarltsel/scalargtsel on
3935 * an operator with one timevalue and one non-timevalue operand.
3937 elog(ERROR, "unsupported type: %u", typid);
3943 * get_restriction_variable
3944 * Examine the args of a restriction clause to see if it's of the
3945 * form (variable op pseudoconstant) or (pseudoconstant op variable),
3946 * where "variable" could be either a Var or an expression in vars of a
3947 * single relation. If so, extract information about the variable,
3948 * and also indicate which side it was on and the other argument.
3951 * root: the planner info
3952 * args: clause argument list
3953 * varRelid: see specs for restriction selectivity functions
3955 * Outputs: (these are valid only if TRUE is returned)
3956 * *vardata: gets information about variable (see examine_variable)
3957 * *other: gets other clause argument, aggressively reduced to a constant
3958 * *varonleft: set TRUE if variable is on the left, FALSE if on the right
3960 * Returns TRUE if a variable is identified, otherwise FALSE.
3962 * Note: if there are Vars on both sides of the clause, we must fail, because
3963 * callers are expecting that the other side will act like a pseudoconstant.
3966 get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
3967 VariableStatData *vardata, Node **other,
3972 VariableStatData rdata;
3974 /* Fail if not a binary opclause (probably shouldn't happen) */
3975 if (list_length(args) != 2)
3978 left = (Node *) linitial(args);
3979 right = (Node *) lsecond(args);
3982 * Examine both sides. Note that when varRelid is nonzero, Vars of other
3983 * relations will be treated as pseudoconstants.
3985 examine_variable(root, left, varRelid, vardata);
3986 examine_variable(root, right, varRelid, &rdata);
3989 * If one side is a variable and the other not, we win.
3991 if (vardata->rel && rdata.rel == NULL)
3994 *other = estimate_expression_value(root, rdata.var);
3995 /* Assume we need no ReleaseVariableStats(rdata) here */
3999 if (vardata->rel == NULL && rdata.rel)
4002 *other = estimate_expression_value(root, vardata->var);
4003 /* Assume we need no ReleaseVariableStats(*vardata) here */
4008 /* Ooops, clause has wrong structure (probably var op var) */
4009 ReleaseVariableStats(*vardata);
4010 ReleaseVariableStats(rdata);
4016 * get_join_variables
4017 * Apply examine_variable() to each side of a join clause.
4018 * Also, attempt to identify whether the join clause has the same
4019 * or reversed sense compared to the SpecialJoinInfo.
4021 * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4022 * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4023 * where we can't tell for sure, we default to assuming it's normal.
4026 get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
4027 VariableStatData *vardata1, VariableStatData *vardata2,
4028 bool *join_is_reversed)
4033 if (list_length(args) != 2)
4034 elog(ERROR, "join operator should take two arguments");
4036 left = (Node *) linitial(args);
4037 right = (Node *) lsecond(args);
4039 examine_variable(root, left, 0, vardata1);
4040 examine_variable(root, right, 0, vardata2);
4042 if (vardata1->rel &&
4043 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4044 *join_is_reversed = true; /* var1 is on RHS */
4045 else if (vardata2->rel &&
4046 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4047 *join_is_reversed = true; /* var2 is on LHS */
4049 *join_is_reversed = false;
4054 * Try to look up statistical data about an expression.
4055 * Fill in a VariableStatData struct to describe the expression.
4058 * root: the planner info
4059 * node: the expression tree to examine
4060 * varRelid: see specs for restriction selectivity functions
4062 * Outputs: *vardata is filled as follows:
4063 * var: the input expression (with any binary relabeling stripped, if
4064 * it is or contains a variable; but otherwise the type is preserved)
4065 * rel: RelOptInfo for relation containing variable; NULL if expression
4066 * contains no Vars (NOTE this could point to a RelOptInfo of a
4067 * subquery, not one in the current query).
4068 * statsTuple: the pg_statistic entry for the variable, if one exists;
4070 * freefunc: pointer to a function to release statsTuple with.
4071 * vartype: exposed type of the expression; this should always match
4072 * the declared input type of the operator we are estimating for.
4073 * atttype, atttypmod: type data to pass to get_attstatsslot(). This is
4074 * commonly the same as the exposed type of the variable argument,
4075 * but can be different in binary-compatible-type cases.
4076 * isunique: TRUE if we were able to match the var to a unique index,
4077 * implying its values are unique for this query.
4079 * Caller is responsible for doing ReleaseVariableStats() before exiting.
4082 examine_variable(PlannerInfo *root, Node *node, int varRelid,
4083 VariableStatData *vardata)
4089 /* Make sure we don't return dangling pointers in vardata */
4090 MemSet(vardata, 0, sizeof(VariableStatData));
4092 /* Save the exposed type of the expression */
4093 vardata->vartype = exprType(node);
4095 /* Look inside any binary-compatible relabeling */
4097 if (IsA(node, RelabelType))
4098 basenode = (Node *) ((RelabelType *) node)->arg;
4102 /* Fast path for a simple Var */
4104 if (IsA(basenode, Var) &&
4105 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4107 Var *var = (Var *) basenode;
4110 vardata->var = basenode; /* return Var without relabeling */
4111 vardata->rel = find_base_rel(root, var->varno);
4112 vardata->atttype = var->vartype;
4113 vardata->atttypmod = var->vartypmod;
4114 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4116 rte = root->simple_rte_array[var->varno];
4118 if (get_relation_stats_hook &&
4119 (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4122 * The hook took control of acquiring a stats tuple. If it did
4123 * supply a tuple, it'd better have supplied a freefunc.
4125 if (HeapTupleIsValid(vardata->statsTuple) &&
4127 elog(ERROR, "no function provided to release variable stats with");
4129 else if (rte->rtekind == RTE_RELATION)
4131 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
4132 ObjectIdGetDatum(rte->relid),
4133 Int16GetDatum(var->varattno),
4134 BoolGetDatum(rte->inh));
4135 vardata->freefunc = ReleaseSysCache;
4140 * XXX This means the Var comes from a JOIN or sub-SELECT. Later
4141 * add code to dig down into the join etc and see if we can trace
4142 * the variable to something with stats. (But beware of
4143 * sub-SELECTs with DISTINCT/GROUP BY/etc. Perhaps there are no
4144 * cases where this would really be useful, because we'd have
4145 * flattened the subselect if it is??)
4153 * Okay, it's a more complicated expression. Determine variable
4154 * membership. Note that when varRelid isn't zero, only vars of that
4155 * relation are considered "real" vars.
4157 varnos = pull_varnos(basenode);
4161 switch (bms_membership(varnos))
4164 /* No Vars at all ... must be pseudo-constant clause */
4167 if (varRelid == 0 || bms_is_member(varRelid, varnos))
4169 onerel = find_base_rel(root,
4170 (varRelid ? varRelid : bms_singleton_member(varnos)));
4171 vardata->rel = onerel;
4172 node = basenode; /* strip any relabeling */
4174 /* else treat it as a constant */
4179 /* treat it as a variable of a join relation */
4180 vardata->rel = find_join_rel(root, varnos);
4181 node = basenode; /* strip any relabeling */
4183 else if (bms_is_member(varRelid, varnos))
4185 /* ignore the vars belonging to other relations */
4186 vardata->rel = find_base_rel(root, varRelid);
4187 node = basenode; /* strip any relabeling */
4188 /* note: no point in expressional-index search here */
4190 /* else treat it as a constant */
4196 vardata->var = node;
4197 vardata->atttype = exprType(node);
4198 vardata->atttypmod = exprTypmod(node);
4203 * We have an expression in vars of a single relation. Try to match
4204 * it to expressional index columns, in hopes of finding some
4207 * XXX it's conceivable that there are multiple matches with different
4208 * index opfamilies; if so, we need to pick one that matches the
4209 * operator we are estimating for. FIXME later.
4213 foreach(ilist, onerel->indexlist)
4215 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4216 ListCell *indexpr_item;
4219 indexpr_item = list_head(index->indexprs);
4220 if (indexpr_item == NULL)
4221 continue; /* no expressions here... */
4223 for (pos = 0; pos < index->ncolumns; pos++)
4225 if (index->indexkeys[pos] == 0)
4229 if (indexpr_item == NULL)
4230 elog(ERROR, "too few entries in indexprs list");
4231 indexkey = (Node *) lfirst(indexpr_item);
4232 if (indexkey && IsA(indexkey, RelabelType))
4233 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4234 if (equal(node, indexkey))
4237 * Found a match ... is it a unique index? Tests here
4238 * should match has_unique_index().
4240 if (index->unique &&
4241 index->ncolumns == 1 &&
4242 (index->indpred == NIL || index->predOK))
4243 vardata->isunique = true;
4246 * Has it got stats? We only consider stats for
4247 * non-partial indexes, since partial indexes probably
4248 * don't reflect whole-relation statistics; the above
4249 * check for uniqueness is the only info we take from
4252 * An index stats hook, however, must make its own
4253 * decisions about what to do with partial indexes.
4255 if (get_index_stats_hook &&
4256 (*get_index_stats_hook) (root, index->indexoid,
4260 * The hook took control of acquiring a stats
4261 * tuple. If it did supply a tuple, it'd better
4262 * have supplied a freefunc.
4264 if (HeapTupleIsValid(vardata->statsTuple) &&
4266 elog(ERROR, "no function provided to release variable stats with");
4268 else if (index->indpred == NIL)
4270 vardata->statsTuple =
4271 SearchSysCache3(STATRELATTINH,
4272 ObjectIdGetDatum(index->indexoid),
4273 Int16GetDatum(pos + 1),
4274 BoolGetDatum(false));
4275 vardata->freefunc = ReleaseSysCache;
4277 if (vardata->statsTuple)
4280 indexpr_item = lnext(indexpr_item);
4283 if (vardata->statsTuple)
4290 * get_variable_numdistinct
4291 * Estimate the number of distinct values of a variable.
4293 * vardata: results of examine_variable
4295 * NB: be careful to produce an integral result, since callers may compare
4296 * the result to exact integer counts.
4299 get_variable_numdistinct(VariableStatData *vardata)
4305 * Determine the stadistinct value to use. There are cases where we can
4306 * get an estimate even without a pg_statistic entry, or can get a better
4307 * value than is in pg_statistic.
4309 if (HeapTupleIsValid(vardata->statsTuple))
4311 /* Use the pg_statistic entry */
4312 Form_pg_statistic stats;
4314 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4315 stadistinct = stats->stadistinct;
4317 else if (vardata->vartype == BOOLOID)
4320 * Special-case boolean columns: presumably, two distinct values.
4322 * Are there any other datatypes we should wire in special estimates
4330 * We don't keep statistics for system columns, but in some cases we
4331 * can infer distinctness anyway.
4333 if (vardata->var && IsA(vardata->var, Var))
4335 switch (((Var *) vardata->var)->varattno)
4337 case ObjectIdAttributeNumber:
4338 case SelfItemPointerAttributeNumber:
4339 stadistinct = -1.0; /* unique */
4341 case TableOidAttributeNumber:
4342 stadistinct = 1.0; /* only 1 value */
4345 stadistinct = 0.0; /* means "unknown" */
4350 stadistinct = 0.0; /* means "unknown" */
4353 * XXX consider using estimate_num_groups on expressions?
4358 * If there is a unique index for the variable, assume it is unique no
4359 * matter what pg_statistic says; the statistics could be out of date, or
4360 * we might have found a partial unique index that proves the var is
4361 * unique for this query.
4363 if (vardata->isunique)
4367 * If we had an absolute estimate, use that.
4369 if (stadistinct > 0.0)
4373 * Otherwise we need to get the relation size; punt if not available.
4375 if (vardata->rel == NULL)
4376 return DEFAULT_NUM_DISTINCT;
4377 ntuples = vardata->rel->tuples;
4379 return DEFAULT_NUM_DISTINCT;
4382 * If we had a relative estimate, use that.
4384 if (stadistinct < 0.0)
4385 return floor((-stadistinct * ntuples) + 0.5);
4388 * With no data, estimate ndistinct = ntuples if the table is small, else
4391 if (ntuples < DEFAULT_NUM_DISTINCT)
4394 return DEFAULT_NUM_DISTINCT;
4398 * get_variable_range
4399 * Estimate the minimum and maximum value of the specified variable.
4400 * If successful, store values in *min and *max, and return TRUE.
4401 * If no data available, return FALSE.
4403 * sortop is the "<" comparison operator to use. This should generally
4404 * be "<" not ">", as only the former is likely to be found in pg_statistic.
4407 get_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop,
4408 Datum *min, Datum *max)
4412 bool have_data = false;
4413 Form_pg_statistic stats;
4421 * XXX It's very tempting to try to use the actual column min and max, if
4422 * we can get them relatively-cheaply with an index probe. However, since
4423 * this function is called many times during join planning, that could
4424 * have unpleasant effects on planning speed. Need more investigation
4425 * before enabling this.
4428 if (get_actual_variable_range(root, vardata, sortop, min, max))
4432 if (!HeapTupleIsValid(vardata->statsTuple))
4434 /* no stats available, so default result */
4437 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4439 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
4442 * If there is a histogram, grab the first and last values.
4444 * If there is a histogram that is sorted with some other operator than
4445 * the one we want, fail --- this suggests that there is data we can't
4448 if (get_attstatsslot(vardata->statsTuple,
4449 vardata->atttype, vardata->atttypmod,
4450 STATISTIC_KIND_HISTOGRAM, sortop,
4457 tmin = datumCopy(values[0], typByVal, typLen);
4458 tmax = datumCopy(values[nvalues - 1], typByVal, typLen);
4461 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4463 else if (get_attstatsslot(vardata->statsTuple,
4464 vardata->atttype, vardata->atttypmod,
4465 STATISTIC_KIND_HISTOGRAM, InvalidOid,
4470 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4475 * If we have most-common-values info, look for extreme MCVs. This is
4476 * needed even if we also have a histogram, since the histogram excludes
4477 * the MCVs. However, usually the MCVs will not be the extreme values, so
4478 * avoid unnecessary data copying.
4480 if (get_attstatsslot(vardata->statsTuple,
4481 vardata->atttype, vardata->atttypmod,
4482 STATISTIC_KIND_MCV, InvalidOid,
4487 bool tmin_is_mcv = false;
4488 bool tmax_is_mcv = false;
4491 fmgr_info(get_opcode(sortop), &opproc);
4492 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &opproc);
4494 for (i = 0; i < nvalues; i++)
4498 tmin = tmax = values[i];
4499 tmin_is_mcv = tmax_is_mcv = have_data = true;
4502 if (DatumGetBool(FunctionCall2(&opproc, values[i], tmin)))
4507 if (DatumGetBool(FunctionCall2(&opproc, tmax, values[i])))
4514 tmin = datumCopy(tmin, typByVal, typLen);
4516 tmax = datumCopy(tmax, typByVal, typLen);
4517 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4527 * get_actual_variable_range
4528 * Attempt to identify the current *actual* minimum and/or maximum
4529 * of the specified variable, by looking for a suitable btree index
4530 * and fetching its low and/or high values.
4531 * If successful, store values in *min and *max, and return TRUE.
4532 * (Either pointer can be NULL if that endpoint isn't needed.)
4533 * If no data available, return FALSE.
4535 * sortop is the "<" comparison operator to use.
4538 get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
4540 Datum *min, Datum *max)
4542 bool have_data = false;
4543 RelOptInfo *rel = vardata->rel;
4547 /* No hope if no relation or it doesn't have indexes */
4548 if (rel == NULL || rel->indexlist == NIL)
4550 /* If it has indexes it must be a plain relation */
4551 rte = root->simple_rte_array[rel->relid];
4552 Assert(rte->rtekind == RTE_RELATION);
4554 /* Search through the indexes to see if any match our problem */
4555 foreach(lc, rel->indexlist)
4557 IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
4558 ScanDirection indexscandir;
4560 /* Ignore non-btree indexes */
4561 if (index->relam != BTREE_AM_OID)
4565 * Ignore partial indexes --- we only want stats that cover the entire
4568 if (index->indpred != NIL)
4572 * The index list might include hypothetical indexes inserted by a
4573 * get_relation_info hook --- don't try to access them.
4575 if (index->hypothetical)
4579 * The first index column must match the desired variable and sort
4580 * operator --- but we can use a descending-order index.
4582 if (!match_index_to_operand(vardata->var, 0, index))
4584 switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
4586 case BTLessStrategyNumber:
4587 if (index->reverse_sort[0])
4588 indexscandir = BackwardScanDirection;
4590 indexscandir = ForwardScanDirection;
4592 case BTGreaterStrategyNumber:
4593 if (index->reverse_sort[0])
4594 indexscandir = ForwardScanDirection;
4596 indexscandir = BackwardScanDirection;
4599 /* index doesn't match the sortop */
4604 * Found a suitable index to extract data from. We'll need an EState
4605 * and a bunch of other infrastructure.
4609 ExprContext *econtext;
4610 MemoryContext tmpcontext;
4611 MemoryContext oldcontext;
4614 IndexInfo *indexInfo;
4615 TupleTableSlot *slot;
4618 ScanKeyData scankeys[1];
4619 IndexScanDesc index_scan;
4621 Datum values[INDEX_MAX_KEYS];
4622 bool isnull[INDEX_MAX_KEYS];
4624 estate = CreateExecutorState();
4625 econtext = GetPerTupleExprContext(estate);
4626 /* Make sure any cruft is generated in the econtext's memory */
4627 tmpcontext = econtext->ecxt_per_tuple_memory;
4628 oldcontext = MemoryContextSwitchTo(tmpcontext);
4631 * Open the table and index so we can read from them. We should
4632 * already have at least AccessShareLock on the table, but not
4633 * necessarily on the index.
4635 heapRel = heap_open(rte->relid, NoLock);
4636 indexRel = index_open(index->indexoid, AccessShareLock);
4638 /* extract index key information from the index's pg_index info */
4639 indexInfo = BuildIndexInfo(indexRel);
4641 /* some other stuff */
4642 slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
4643 econtext->ecxt_scantuple = slot;
4644 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
4646 /* set up an IS NOT NULL scan key so that we ignore nulls */
4647 ScanKeyEntryInitialize(&scankeys[0],
4648 SK_ISNULL | SK_SEARCHNOTNULL,
4649 1, /* index col to scan */
4650 InvalidStrategy, /* no strategy */
4651 InvalidOid, /* no strategy subtype */
4652 InvalidOid, /* no collation */
4653 InvalidOid, /* no reg proc for this */
4654 (Datum) 0); /* constant */
4658 /* If min is requested ... */
4661 index_scan = index_beginscan(heapRel, indexRel, SnapshotNow,
4663 index_rescan(index_scan, scankeys, 1, NULL, 0);
4665 /* Fetch first tuple in sortop's direction */
4666 if ((tup = index_getnext(index_scan,
4667 indexscandir)) != NULL)
4669 /* Extract the index column values from the heap tuple */
4670 ExecStoreTuple(tup, slot, InvalidBuffer, false);
4671 FormIndexDatum(indexInfo, slot, estate,
4674 /* Shouldn't have got a null, but be careful */
4676 elog(ERROR, "found unexpected null value in index \"%s\"",
4677 RelationGetRelationName(indexRel));
4679 /* Copy the index column value out to caller's context */
4680 MemoryContextSwitchTo(oldcontext);
4681 *min = datumCopy(values[0], typByVal, typLen);
4682 MemoryContextSwitchTo(tmpcontext);
4687 index_endscan(index_scan);
4690 /* If max is requested, and we didn't find the index is empty */
4691 if (max && have_data)
4693 index_scan = index_beginscan(heapRel, indexRel, SnapshotNow,
4695 index_rescan(index_scan, scankeys, 1, NULL, 0);
4697 /* Fetch first tuple in reverse direction */
4698 if ((tup = index_getnext(index_scan,
4699 -indexscandir)) != NULL)
4701 /* Extract the index column values from the heap tuple */
4702 ExecStoreTuple(tup, slot, InvalidBuffer, false);
4703 FormIndexDatum(indexInfo, slot, estate,
4706 /* Shouldn't have got a null, but be careful */
4708 elog(ERROR, "found unexpected null value in index \"%s\"",
4709 RelationGetRelationName(indexRel));
4711 /* Copy the index column value out to caller's context */
4712 MemoryContextSwitchTo(oldcontext);
4713 *max = datumCopy(values[0], typByVal, typLen);
4714 MemoryContextSwitchTo(tmpcontext);
4719 index_endscan(index_scan);
4722 /* Clean everything up */
4723 ExecDropSingleTupleTableSlot(slot);
4725 index_close(indexRel, AccessShareLock);
4726 heap_close(heapRel, NoLock);
4728 MemoryContextSwitchTo(oldcontext);
4729 FreeExecutorState(estate);
4731 /* And we're done */
4740 /*-------------------------------------------------------------------------
4742 * Pattern analysis functions
4744 * These routines support analysis of LIKE and regular-expression patterns
4745 * by the planner/optimizer. It's important that they agree with the
4746 * regular-expression code in backend/regex/ and the LIKE code in
4747 * backend/utils/adt/like.c. Also, the computation of the fixed prefix
4748 * must be conservative: if we report a string longer than the true fixed
4749 * prefix, the query may produce actually wrong answers, rather than just
4750 * getting a bad selectivity estimate!
4752 * Note that the prefix-analysis functions are called from
4753 * backend/optimizer/path/indxpath.c as well as from routines in this file.
4755 *-------------------------------------------------------------------------
4759 * Extract the fixed prefix, if any, for a pattern.
4761 * *prefix is set to a palloc'd prefix string (in the form of a Const node),
4762 * or to NULL if no fixed prefix exists for the pattern.
4763 * *rest is set to a palloc'd Const representing the remainder of the pattern
4764 * after the portion describing the fixed prefix.
4765 * Each of these has the same type (TEXT or BYTEA) as the given pattern Const.
4767 * The return value distinguishes no fixed prefix, a partial prefix,
4768 * or an exact-match-only pattern.
4771 static Pattern_Prefix_Status
4772 like_fixed_prefix(Const *patt_const, bool case_insensitive,
4773 Const **prefix_const, Const **rest_const)
4779 Oid typeid = patt_const->consttype;
4782 bool is_multibyte = (pg_database_encoding_max_length() > 1);
4784 /* the right-hand const is type text or bytea */
4785 Assert(typeid == BYTEAOID || typeid == TEXTOID);
4787 if (typeid == BYTEAOID && case_insensitive)
4789 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4790 errmsg("case insensitive matching not supported on type bytea")));
4792 if (typeid != BYTEAOID)
4794 patt = TextDatumGetCString(patt_const->constvalue);
4795 pattlen = strlen(patt);
4799 bytea *bstr = DatumGetByteaP(patt_const->constvalue);
4801 pattlen = VARSIZE(bstr) - VARHDRSZ;
4802 patt = (char *) palloc(pattlen);
4803 memcpy(patt, VARDATA(bstr), pattlen);
4804 if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
4808 match = palloc(pattlen + 1);
4810 for (pos = 0; pos < pattlen; pos++)
4812 /* % and _ are wildcard characters in LIKE */
4813 if (patt[pos] == '%' ||
4817 /* Backslash escapes the next character */
4818 if (patt[pos] == '\\')
4826 * XXX In multibyte character sets, we can't trust isalpha, so assume
4827 * any multibyte char is potentially case-varying.
4829 if (case_insensitive)
4831 if (is_multibyte && (unsigned char) patt[pos] >= 0x80)
4833 if (isalpha((unsigned char) patt[pos]))
4838 * NOTE: this code used to think that %% meant a literal %, but
4839 * textlike() itself does not think that, and the SQL92 spec doesn't
4840 * say any such thing either.
4842 match[match_pos++] = patt[pos];
4845 match[match_pos] = '\0';
4848 if (typeid != BYTEAOID)
4850 *prefix_const = string_to_const(match, typeid);
4851 *rest_const = string_to_const(rest, typeid);
4855 *prefix_const = string_to_bytea_const(match, match_pos);
4856 *rest_const = string_to_bytea_const(rest, pattlen - pos);
4862 /* in LIKE, an empty pattern is an exact match! */
4864 return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
4867 return Pattern_Prefix_Partial;
4869 return Pattern_Prefix_None;
4872 static Pattern_Prefix_Status
4873 regex_fixed_prefix(Const *patt_const, bool case_insensitive,
4874 Const **prefix_const, Const **rest_const)
4881 bool have_leading_paren;
4884 Oid typeid = patt_const->consttype;
4885 bool is_multibyte = (pg_database_encoding_max_length() > 1);
4888 * Should be unnecessary, there are no bytea regex operators defined. As
4889 * such, it should be noted that the rest of this function has *not* been
4890 * made safe for binary (possibly NULL containing) strings.
4892 if (typeid == BYTEAOID)
4894 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4895 errmsg("regular-expression matching not supported on type bytea")));
4897 /* the right-hand const is type text for all of these */
4898 patt = TextDatumGetCString(patt_const->constvalue);
4901 * Check for ARE director prefix. It's worth our trouble to recognize
4902 * this because similar_escape() used to use it, and some other code might
4903 * still use it, to force ARE mode.
4906 if (strncmp(patt, "***:", 4) == 0)
4909 /* Pattern must be anchored left */
4910 if (patt[pos] != '^')
4914 *prefix_const = NULL;
4915 *rest_const = string_to_const(rest, typeid);
4917 return Pattern_Prefix_None;
4922 * If '|' is present in pattern, then there may be multiple alternatives
4923 * for the start of the string. (There are cases where this isn't so, for
4924 * instance if the '|' is inside parens, but detecting that reliably is
4927 if (strchr(patt + pos, '|') != NULL)
4931 *prefix_const = NULL;
4932 *rest_const = string_to_const(rest, typeid);
4934 return Pattern_Prefix_None;
4937 /* OK, allocate space for pattern */
4938 match = palloc(strlen(patt) + 1);
4939 prev_match_pos = match_pos = 0;
4942 * We special-case the syntax '^(...)$' because psql uses it. But beware:
4943 * sequences beginning "(?" are not what they seem, unless they're "(?:".
4944 * (We must recognize that because of similar_escape().)
4946 have_leading_paren = false;
4947 if (patt[pos] == '(' &&
4948 (patt[pos + 1] != '?' || patt[pos + 2] == ':'))
4950 have_leading_paren = true;
4951 pos += (patt[pos + 1] != '?' ? 1 : 3);
4954 /* Scan remainder of pattern */
4961 * Check for characters that indicate multiple possible matches here.
4962 * Also, drop out at ')' or '$' so the termination test works right.
4964 if (patt[pos] == '.' ||
4973 * XXX In multibyte character sets, we can't trust isalpha, so assume
4974 * any multibyte char is potentially case-varying.
4976 if (case_insensitive)
4978 if (is_multibyte && (unsigned char) patt[pos] >= 0x80)
4980 if (isalpha((unsigned char) patt[pos]))
4985 * Check for quantifiers. Except for +, this means the preceding
4986 * character is optional, so we must remove it from the prefix too!
4988 if (patt[pos] == '*' ||
4992 match_pos = prev_match_pos;
4996 if (patt[pos] == '+')
5003 * Normally, backslash quotes the next character. But in AREs,
5004 * backslash followed by alphanumeric is an escape, not a quoted
5005 * character. Must treat it as having multiple possible matches.
5006 * Note: since only ASCII alphanumerics are escapes, we don't have to
5007 * be paranoid about multibyte here.
5009 if (patt[pos] == '\\')
5011 if (isalnum((unsigned char) patt[pos + 1]))
5014 if (patt[pos] == '\0')
5017 /* save position in case we need to back up on next loop cycle */
5018 prev_match_pos = match_pos;
5020 /* must use encoding-aware processing here */
5021 len = pg_mblen(&patt[pos]);
5022 memcpy(&match[match_pos], &patt[pos], len);
5027 match[match_pos] = '\0';
5030 if (have_leading_paren && patt[pos] == ')')
5033 if (patt[pos] == '$' && patt[pos + 1] == '\0')
5035 rest = &patt[pos + 1];
5037 *prefix_const = string_to_const(match, typeid);
5038 *rest_const = string_to_const(rest, typeid);
5043 return Pattern_Prefix_Exact; /* pattern specifies exact match */
5046 *prefix_const = string_to_const(match, typeid);
5047 *rest_const = string_to_const(rest, typeid);
5053 return Pattern_Prefix_Partial;
5055 return Pattern_Prefix_None;
5058 Pattern_Prefix_Status
5059 pattern_fixed_prefix(Const *patt, Pattern_Type ptype,
5060 Const **prefix, Const **rest)
5062 Pattern_Prefix_Status result;
5066 case Pattern_Type_Like:
5067 result = like_fixed_prefix(patt, false, prefix, rest);
5069 case Pattern_Type_Like_IC:
5070 result = like_fixed_prefix(patt, true, prefix, rest);
5072 case Pattern_Type_Regex:
5073 result = regex_fixed_prefix(patt, false, prefix, rest);
5075 case Pattern_Type_Regex_IC:
5076 result = regex_fixed_prefix(patt, true, prefix, rest);
5079 elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5080 result = Pattern_Prefix_None; /* keep compiler quiet */
5087 * Estimate the selectivity of a fixed prefix for a pattern match.
5089 * A fixed prefix "foo" is estimated as the selectivity of the expression
5090 * "variable >= 'foo' AND variable < 'fop'" (see also indxpath.c).
5092 * The selectivity estimate is with respect to the portion of the column
5093 * population represented by the histogram --- the caller must fold this
5094 * together with info about MCVs and NULLs.
5096 * We use the >= and < operators from the specified btree opfamily to do the
5097 * estimation. The given variable and Const must be of the associated
5100 * XXX Note: we make use of the upper bound to estimate operator selectivity
5101 * even if the locale is such that we cannot rely on the upper-bound string.
5102 * The selectivity only needs to be approximately right anyway, so it seems
5103 * more useful to use the upper-bound code than not.
5106 prefix_selectivity(PlannerInfo *root, VariableStatData *vardata,
5107 Oid vartype, Oid opfamily, Const *prefixcon)
5109 Selectivity prefixsel;
5112 Const *greaterstrcon;
5115 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5116 BTGreaterEqualStrategyNumber);
5117 if (cmpopr == InvalidOid)
5118 elog(ERROR, "no >= operator for opfamily %u", opfamily);
5119 fmgr_info(get_opcode(cmpopr), &opproc);
5120 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &opproc);
5122 prefixsel = ineq_histogram_selectivity(root, vardata, &opproc, true,
5123 prefixcon->constvalue,
5124 prefixcon->consttype);
5126 if (prefixsel < 0.0)
5128 /* No histogram is present ... return a suitable default estimate */
5129 return DEFAULT_MATCH_SEL;
5133 * If we can create a string larger than the prefix, say
5137 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5138 BTLessStrategyNumber);
5139 if (cmpopr == InvalidOid)
5140 elog(ERROR, "no < operator for opfamily %u", opfamily);
5141 fmgr_info(get_opcode(cmpopr), &opproc);
5142 fmgr_info_set_collation(DEFAULT_COLLATION_OID, &opproc);
5144 greaterstrcon = make_greater_string(prefixcon, &opproc);
5149 topsel = ineq_histogram_selectivity(root, vardata, &opproc, false,
5150 greaterstrcon->constvalue,
5151 greaterstrcon->consttype);
5153 /* ineq_histogram_selectivity worked before, it shouldn't fail now */
5154 Assert(topsel >= 0.0);
5157 * Merge the two selectivities in the same way as for a range query
5158 * (see clauselist_selectivity()). Note that we don't need to worry
5159 * about double-exclusion of nulls, since ineq_histogram_selectivity
5160 * doesn't count those anyway.
5162 prefixsel = topsel + prefixsel - 1.0;
5166 * If the prefix is long then the two bounding values might be too close
5167 * together for the histogram to distinguish them usefully, resulting in a
5168 * zero estimate (plus or minus roundoff error). To avoid returning a
5169 * ridiculously small estimate, compute the estimated selectivity for
5170 * "variable = 'foo'", and clamp to that. (Obviously, the resultant
5171 * estimate should be at least that.)
5173 * We apply this even if we couldn't make a greater string. That case
5174 * suggests that the prefix is near the maximum possible, and thus
5175 * probably off the end of the histogram, and thus we probably got a very
5176 * small estimate from the >= condition; so we still need to clamp.
5178 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5179 BTEqualStrategyNumber);
5180 if (cmpopr == InvalidOid)
5181 elog(ERROR, "no = operator for opfamily %u", opfamily);
5182 eq_sel = var_eq_const(vardata, cmpopr, prefixcon->constvalue,
5185 prefixsel = Max(prefixsel, eq_sel);
5192 * Estimate the selectivity of a pattern of the specified type.
5193 * Note that any fixed prefix of the pattern will have been removed already.
5195 * For now, we use a very simplistic approach: fixed characters reduce the
5196 * selectivity a good deal, character ranges reduce it a little,
5197 * wildcards (such as % for LIKE or .* for regex) increase it.
5200 #define FIXED_CHAR_SEL 0.20 /* about 1/5 */
5201 #define CHAR_RANGE_SEL 0.25
5202 #define ANY_CHAR_SEL 0.9 /* not 1, since it won't match end-of-string */
5203 #define FULL_WILDCARD_SEL 5.0
5204 #define PARTIAL_WILDCARD_SEL 2.0
5207 like_selectivity(Const *patt_const, bool case_insensitive)
5209 Selectivity sel = 1.0;
5211 Oid typeid = patt_const->consttype;
5215 /* the right-hand const is type text or bytea */
5216 Assert(typeid == BYTEAOID || typeid == TEXTOID);
5218 if (typeid == BYTEAOID && case_insensitive)
5220 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5221 errmsg("case insensitive matching not supported on type bytea")));
5223 if (typeid != BYTEAOID)
5225 patt = TextDatumGetCString(patt_const->constvalue);
5226 pattlen = strlen(patt);
5230 bytea *bstr = DatumGetByteaP(patt_const->constvalue);
5232 pattlen = VARSIZE(bstr) - VARHDRSZ;
5233 patt = (char *) palloc(pattlen);
5234 memcpy(patt, VARDATA(bstr), pattlen);
5235 if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
5239 /* Skip any leading wildcard; it's already factored into initial sel */
5240 for (pos = 0; pos < pattlen; pos++)
5242 if (patt[pos] != '%' && patt[pos] != '_')
5246 for (; pos < pattlen; pos++)
5248 /* % and _ are wildcard characters in LIKE */
5249 if (patt[pos] == '%')
5250 sel *= FULL_WILDCARD_SEL;
5251 else if (patt[pos] == '_')
5252 sel *= ANY_CHAR_SEL;
5253 else if (patt[pos] == '\\')
5255 /* Backslash quotes the next character */
5259 sel *= FIXED_CHAR_SEL;
5262 sel *= FIXED_CHAR_SEL;
5264 /* Could get sel > 1 if multiple wildcards */
5273 regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive)
5275 Selectivity sel = 1.0;
5276 int paren_depth = 0;
5277 int paren_pos = 0; /* dummy init to keep compiler quiet */
5280 for (pos = 0; pos < pattlen; pos++)
5282 if (patt[pos] == '(')
5284 if (paren_depth == 0)
5285 paren_pos = pos; /* remember start of parenthesized item */
5288 else if (patt[pos] == ')' && paren_depth > 0)
5291 if (paren_depth == 0)
5292 sel *= regex_selectivity_sub(patt + (paren_pos + 1),
5293 pos - (paren_pos + 1),
5296 else if (patt[pos] == '|' && paren_depth == 0)
5299 * If unquoted | is present at paren level 0 in pattern, we have
5300 * multiple alternatives; sum their probabilities.
5302 sel += regex_selectivity_sub(patt + (pos + 1),
5303 pattlen - (pos + 1),
5305 break; /* rest of pattern is now processed */
5307 else if (patt[pos] == '[')
5309 bool negclass = false;
5311 if (patt[++pos] == '^')
5316 if (patt[pos] == ']') /* ']' at start of class is not
5319 while (pos < pattlen && patt[pos] != ']')
5321 if (paren_depth == 0)
5322 sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
5324 else if (patt[pos] == '.')
5326 if (paren_depth == 0)
5327 sel *= ANY_CHAR_SEL;
5329 else if (patt[pos] == '*' ||
5333 /* Ought to be smarter about quantifiers... */
5334 if (paren_depth == 0)
5335 sel *= PARTIAL_WILDCARD_SEL;
5337 else if (patt[pos] == '{')
5339 while (pos < pattlen && patt[pos] != '}')
5341 if (paren_depth == 0)
5342 sel *= PARTIAL_WILDCARD_SEL;
5344 else if (patt[pos] == '\\')
5346 /* backslash quotes the next character */
5350 if (paren_depth == 0)
5351 sel *= FIXED_CHAR_SEL;
5355 if (paren_depth == 0)
5356 sel *= FIXED_CHAR_SEL;
5359 /* Could get sel > 1 if multiple wildcards */
5366 regex_selectivity(Const *patt_const, bool case_insensitive)
5371 Oid typeid = patt_const->consttype;
5374 * Should be unnecessary, there are no bytea regex operators defined. As
5375 * such, it should be noted that the rest of this function has *not* been
5376 * made safe for binary (possibly NULL containing) strings.
5378 if (typeid == BYTEAOID)
5380 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5381 errmsg("regular-expression matching not supported on type bytea")));
5383 /* the right-hand const is type text for all of these */
5384 patt = TextDatumGetCString(patt_const->constvalue);
5385 pattlen = strlen(patt);
5387 /* If patt doesn't end with $, consider it to have a trailing wildcard */
5388 if (pattlen > 0 && patt[pattlen - 1] == '$' &&
5389 (pattlen == 1 || patt[pattlen - 2] != '\\'))
5391 /* has trailing $ */
5392 sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
5397 sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
5398 sel *= FULL_WILDCARD_SEL;
5406 pattern_selectivity(Const *patt, Pattern_Type ptype)
5412 case Pattern_Type_Like:
5413 result = like_selectivity(patt, false);
5415 case Pattern_Type_Like_IC:
5416 result = like_selectivity(patt, true);
5418 case Pattern_Type_Regex:
5419 result = regex_selectivity(patt, false);
5421 case Pattern_Type_Regex_IC:
5422 result = regex_selectivity(patt, true);
5425 elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5426 result = 1.0; /* keep compiler quiet */
5434 * Try to generate a string greater than the given string or any
5435 * string it is a prefix of. If successful, return a palloc'd string
5436 * in the form of a Const node; else return NULL.
5438 * The caller must provide the appropriate "less than" comparison function
5439 * for testing the strings. In particular, ltproc->fn_collation specifies
5440 * the locale for comparisons.
5442 * The key requirement here is that given a prefix string, say "foo",
5443 * we must be able to generate another string "fop" that is greater than
5444 * all strings "foobar" starting with "foo". We can test that we have
5445 * generated a string greater than the prefix string, but in non-C locales
5446 * that is not a bulletproof guarantee that an extension of the string might
5447 * not sort after it; an example is that "foo " is less than "foo!", but it
5448 * is not clear that a "dictionary" sort ordering will consider "foo!" less
5449 * than "foo bar". CAUTION: Therefore, this function should be used only for
5450 * estimation purposes when working in a non-C locale.
5452 * To try to catch most cases where an extended string might otherwise sort
5453 * before the result value, we determine which of the strings "Z", "z", "y",
5454 * and "9" is seen as largest by the locale, and append that to the given
5455 * prefix before trying to find a string that compares as larger.
5457 * If we max out the righthand byte, truncate off the last character
5458 * and start incrementing the next. For example, if "z" were the last
5459 * character in the sort order, then we could produce "foo" as a
5460 * string greater than "fonz".
5462 * This could be rather slow in the worst case, but in most cases we
5463 * won't have to try more than one or two strings before succeeding.
5466 make_greater_string(const Const *str_const, FmgrInfo *ltproc)
5468 Oid datatype = str_const->consttype;
5472 text *cmptxt = NULL;
5475 * Get a modifiable copy of the prefix string in C-string format, and set
5476 * up the string we will compare to as a Datum. In C locale this can just
5477 * be the given prefix string, otherwise we need to add a suffix. Types
5478 * NAME and BYTEA sort bytewise so they don't need a suffix either.
5480 if (datatype == NAMEOID)
5482 workstr = DatumGetCString(DirectFunctionCall1(nameout,
5483 str_const->constvalue));
5484 len = strlen(workstr);
5485 cmpstr = str_const->constvalue;
5487 else if (datatype == BYTEAOID)
5489 bytea *bstr = DatumGetByteaP(str_const->constvalue);
5491 len = VARSIZE(bstr) - VARHDRSZ;
5492 workstr = (char *) palloc(len);
5493 memcpy(workstr, VARDATA(bstr), len);
5494 if ((Pointer) bstr != DatumGetPointer(str_const->constvalue))
5496 cmpstr = str_const->constvalue;
5500 workstr = TextDatumGetCString(str_const->constvalue);
5501 len = strlen(workstr);
5502 if (lc_collate_is_c(ltproc->fn_collation) || len == 0)
5503 cmpstr = str_const->constvalue;
5506 /* If first time through, determine the suffix to use */
5507 static char suffixchar = 0;
5508 static Oid suffixcollation = 0;
5510 if (!suffixchar || suffixcollation != ltproc->fn_collation)
5515 if (varstr_cmp(best, 1, "z", 1, ltproc->fn_collation) < 0)
5517 if (varstr_cmp(best, 1, "y", 1, ltproc->fn_collation) < 0)
5519 if (varstr_cmp(best, 1, "9", 1, ltproc->fn_collation) < 0)
5522 suffixcollation = ltproc->fn_collation;
5525 /* And build the string to compare to */
5526 cmptxt = (text *) palloc(VARHDRSZ + len + 1);
5527 SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
5528 memcpy(VARDATA(cmptxt), workstr, len);
5529 *(VARDATA(cmptxt) + len) = suffixchar;
5530 cmpstr = PointerGetDatum(cmptxt);
5536 unsigned char *lastchar = (unsigned char *) (workstr + len - 1);
5537 unsigned char savelastchar = *lastchar;
5540 * Try to generate a larger string by incrementing the last byte.
5542 while (*lastchar < (unsigned char) 255)
5544 Const *workstr_const;
5548 if (datatype != BYTEAOID)
5550 /* do not generate invalid encoding sequences */
5551 if (!pg_verifymbstr(workstr, len, true))
5553 workstr_const = string_to_const(workstr, datatype);
5556 workstr_const = string_to_bytea_const(workstr, len);
5558 if (DatumGetBool(FunctionCall2(ltproc,
5560 workstr_const->constvalue)))
5562 /* Successfully made a string larger than cmpstr */
5566 return workstr_const;
5569 /* No good, release unusable value and try again */
5570 pfree(DatumGetPointer(workstr_const->constvalue));
5571 pfree(workstr_const);
5574 /* restore last byte so we don't confuse pg_mbcliplen */
5575 *lastchar = savelastchar;
5578 * Truncate off the last character, which might be more than 1 byte,
5579 * depending on the character encoding.
5581 if (datatype != BYTEAOID && pg_database_encoding_max_length() > 1)
5582 len = pg_mbcliplen(workstr, len, len - 1);
5586 if (datatype != BYTEAOID)
5587 workstr[len] = '\0';
5599 * Generate a Datum of the appropriate type from a C string.
5600 * Note that all of the supported types are pass-by-ref, so the
5601 * returned value should be pfree'd if no longer needed.
5604 string_to_datum(const char *str, Oid datatype)
5606 Assert(str != NULL);
5609 * We cheat a little by assuming that CStringGetTextDatum() will do for
5610 * bpchar and varchar constants too...
5612 if (datatype == NAMEOID)
5613 return DirectFunctionCall1(namein, CStringGetDatum(str));
5614 else if (datatype == BYTEAOID)
5615 return DirectFunctionCall1(byteain, CStringGetDatum(str));
5617 return CStringGetTextDatum(str);
5621 * Generate a Const node of the appropriate type from a C string.
5624 string_to_const(const char *str, Oid datatype)
5626 Datum conval = string_to_datum(str, datatype);
5631 * We only need to support a few datatypes here, so hard-wire properties
5632 * instead of incurring the expense of catalog lookups.
5639 collation = DEFAULT_COLLATION_OID;
5644 collation = InvalidOid;
5645 constlen = NAMEDATALEN;
5649 collation = InvalidOid;
5654 elog(ERROR, "unexpected datatype in string_to_const: %u",
5659 return makeConst(datatype, -1, collation, constlen,
5660 conval, false, false);
5664 * Generate a Const node of bytea type from a binary C string and a length.
5667 string_to_bytea_const(const char *str, size_t str_len)
5669 bytea *bstr = palloc(VARHDRSZ + str_len);
5672 memcpy(VARDATA(bstr), str, str_len);
5673 SET_VARSIZE(bstr, VARHDRSZ + str_len);
5674 conval = PointerGetDatum(bstr);
5676 return makeConst(BYTEAOID, -1, InvalidOid, -1, conval, false, false);
5679 /*-------------------------------------------------------------------------
5681 * Index cost estimation functions
5683 * genericcostestimate is a general-purpose estimator for use when we
5684 * don't have any better idea about how to estimate. Index-type-specific
5685 * knowledge can be incorporated in the type-specific routines.
5687 * One bit of index-type-specific knowledge we can relatively easily use
5688 * in genericcostestimate is the estimate of the number of index tuples
5689 * visited. If numIndexTuples is not 0 then it is used as the estimate,
5690 * otherwise we compute a generic estimate.
5692 *-------------------------------------------------------------------------
5696 genericcostestimate(PlannerInfo *root,
5697 IndexOptInfo *index,
5699 List *indexOrderBys,
5700 RelOptInfo *outer_rel,
5701 double numIndexTuples,
5702 Cost *indexStartupCost,
5703 Cost *indexTotalCost,
5704 Selectivity *indexSelectivity,
5705 double *indexCorrelation)
5707 double numIndexPages;
5708 double num_sa_scans;
5709 double num_outer_scans;
5711 QualCost index_qual_cost;
5712 double qual_op_cost;
5713 double qual_arg_cost;
5714 double spc_random_page_cost;
5715 List *selectivityQuals;
5719 * If the index is partial, AND the index predicate with the explicitly
5720 * given indexquals to produce a more accurate idea of the index
5721 * selectivity. However, we need to be careful not to insert redundant
5722 * clauses, because clauselist_selectivity() is easily fooled into
5723 * computing a too-low selectivity estimate. Our approach is to add
5724 * only the index predicate clause(s) that cannot be proven to be implied
5725 * by the given indexquals. This successfully handles cases such as a
5726 * qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
5727 * There are many other cases where we won't detect redundancy, leading
5728 * to a too-low selectivity estimate, which will bias the system in favor
5729 * of using partial indexes where possible. That is not necessarily bad
5732 * Note that indexQuals contains RestrictInfo nodes while the indpred
5733 * does not. This is OK for both predicate_implied_by() and
5734 * clauselist_selectivity().
5737 if (index->indpred != NIL)
5739 List *predExtraQuals = NIL;
5741 foreach(l, index->indpred)
5743 Node *predQual = (Node *) lfirst(l);
5744 List *oneQual = list_make1(predQual);
5746 if (!predicate_implied_by(oneQual, indexQuals))
5747 predExtraQuals = list_concat(predExtraQuals, oneQual);
5749 /* list_concat avoids modifying the passed-in indexQuals list */
5750 selectivityQuals = list_concat(predExtraQuals, indexQuals);
5753 selectivityQuals = indexQuals;
5756 * Check for ScalarArrayOpExpr index quals, and estimate the number of
5757 * index scans that will be performed.
5760 foreach(l, indexQuals)
5762 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
5764 if (IsA(rinfo->clause, ScalarArrayOpExpr))
5766 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
5767 int alength = estimate_array_length(lsecond(saop->args));
5770 num_sa_scans *= alength;
5774 /* Estimate the fraction of main-table tuples that will be visited */
5775 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
5781 * If caller didn't give us an estimate, estimate the number of index
5782 * tuples that will be visited. We do it in this rather peculiar-looking
5783 * way in order to get the right answer for partial indexes.
5785 if (numIndexTuples <= 0.0)
5787 numIndexTuples = *indexSelectivity * index->rel->tuples;
5790 * The above calculation counts all the tuples visited across all
5791 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
5792 * average per-indexscan number, so adjust. This is a handy place to
5793 * round to integer, too. (If caller supplied tuple estimate, it's
5794 * responsible for handling these considerations.)
5796 numIndexTuples = rint(numIndexTuples / num_sa_scans);
5800 * We can bound the number of tuples by the index size in any case. Also,
5801 * always estimate at least one tuple is touched, even when
5802 * indexSelectivity estimate is tiny.
5804 if (numIndexTuples > index->tuples)
5805 numIndexTuples = index->tuples;
5806 if (numIndexTuples < 1.0)
5807 numIndexTuples = 1.0;
5810 * Estimate the number of index pages that will be retrieved.
5812 * We use the simplistic method of taking a pro-rata fraction of the total
5813 * number of index pages. In effect, this counts only leaf pages and not
5814 * any overhead such as index metapage or upper tree levels. In practice
5815 * this seems a better approximation than charging for access to the upper
5816 * levels, perhaps because those tend to stay in cache under load.
5818 if (index->pages > 1 && index->tuples > 1)
5819 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
5821 numIndexPages = 1.0;
5823 /* fetch estimated page cost for schema containing index */
5824 get_tablespace_page_costs(index->reltablespace,
5825 &spc_random_page_cost,
5829 * Now compute the disk access costs.
5831 * The above calculations are all per-index-scan. However, if we are in a
5832 * nestloop inner scan, we can expect the scan to be repeated (with
5833 * different search keys) for each row of the outer relation. Likewise,
5834 * ScalarArrayOpExpr quals result in multiple index scans. This creates
5835 * the potential for cache effects to reduce the number of disk page
5836 * fetches needed. We want to estimate the average per-scan I/O cost in
5837 * the presence of caching.
5839 * We use the Mackert-Lohman formula (see costsize.c for details) to
5840 * estimate the total number of page fetches that occur. While this
5841 * wasn't what it was designed for, it seems a reasonable model anyway.
5842 * Note that we are counting pages not tuples anymore, so we take N = T =
5843 * index size, as if there were one "tuple" per page.
5845 if (outer_rel != NULL && outer_rel->rows > 1)
5847 num_outer_scans = outer_rel->rows;
5848 num_scans = num_sa_scans * num_outer_scans;
5852 num_outer_scans = 1;
5853 num_scans = num_sa_scans;
5858 double pages_fetched;
5860 /* total page fetches ignoring cache effects */
5861 pages_fetched = numIndexPages * num_scans;
5863 /* use Mackert and Lohman formula to adjust for cache effects */
5864 pages_fetched = index_pages_fetched(pages_fetched,
5866 (double) index->pages,
5870 * Now compute the total disk access cost, and then report a pro-rated
5871 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
5872 * since that's internal to the indexscan.)
5874 *indexTotalCost = (pages_fetched * spc_random_page_cost)
5880 * For a single index scan, we just charge spc_random_page_cost per
5883 *indexTotalCost = numIndexPages * spc_random_page_cost;
5887 * A difficulty with the leaf-pages-only cost approach is that for small
5888 * selectivities (eg, single index tuple fetched) all indexes will look
5889 * equally attractive because we will estimate exactly 1 leaf page to be
5890 * fetched. All else being equal, we should prefer physically smaller
5891 * indexes over larger ones. (An index might be smaller because it is
5892 * partial or because it contains fewer columns; presumably the other
5893 * columns in the larger index aren't useful to the query, or the larger
5894 * index would have better selectivity.)
5896 * We can deal with this by adding a very small "fudge factor" that
5897 * depends on the index size. The fudge factor used here is one
5898 * spc_random_page_cost per 100000 index pages, which should be small
5899 * enough to not alter index-vs-seqscan decisions, but will prevent
5900 * indexes of different sizes from looking exactly equally attractive.
5902 *indexTotalCost += index->pages * spc_random_page_cost / 100000.0;
5905 * CPU cost: any complex expressions in the indexquals will need to be
5906 * evaluated once at the start of the scan to reduce them to runtime keys
5907 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
5908 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
5909 * indexqual operator. Because we have numIndexTuples as a per-scan
5910 * number, we have to multiply by num_sa_scans to get the correct result
5911 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
5912 * ORDER BY expressions.
5914 * Note: this neglects the possible costs of rechecking lossy operators
5915 * and OR-clause expressions. Detecting that that might be needed seems
5916 * more expensive than it's worth, though, considering all the other
5917 * inaccuracies here ...
5919 cost_qual_eval(&index_qual_cost, indexQuals, root);
5920 qual_arg_cost = index_qual_cost.startup + index_qual_cost.per_tuple;
5921 cost_qual_eval(&index_qual_cost, indexOrderBys, root);
5922 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
5923 qual_op_cost = cpu_operator_cost *
5924 (list_length(indexQuals) + list_length(indexOrderBys));
5925 qual_arg_cost -= qual_op_cost;
5926 if (qual_arg_cost < 0) /* just in case... */
5929 *indexStartupCost = qual_arg_cost;
5930 *indexTotalCost += qual_arg_cost;
5931 *indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
5934 * We also add a CPU-cost component to represent the general costs of
5935 * starting an indexscan, such as analysis of btree index keys and initial
5936 * tree descent. This is estimated at 100x cpu_operator_cost, which is a
5937 * bit arbitrary but seems the right order of magnitude. (As noted above,
5938 * we don't charge any I/O for touching upper tree levels, but charging
5939 * nothing at all has been found too optimistic.)
5941 * Although this is startup cost with respect to any one scan, we add it
5942 * to the "total" cost component because it's only very interesting in the
5943 * many-ScalarArrayOpExpr-scan case, and there it will be paid over the
5944 * life of the scan node.
5946 *indexTotalCost += num_sa_scans * 100.0 * cpu_operator_cost;
5949 * Generic assumption about index correlation: there isn't any.
5951 *indexCorrelation = 0.0;
5956 btcostestimate(PG_FUNCTION_ARGS)
5958 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
5959 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
5960 List *indexQuals = (List *) PG_GETARG_POINTER(2);
5961 List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
5962 RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
5963 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
5964 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
5965 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
5966 double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
5969 VariableStatData vardata;
5970 double numIndexTuples;
5971 List *indexBoundQuals;
5975 bool found_is_null_op;
5976 double num_sa_scans;
5980 * For a btree scan, only leading '=' quals plus inequality quals for the
5981 * immediately next attribute contribute to index selectivity (these are
5982 * the "boundary quals" that determine the starting and stopping points of
5983 * the index scan). Additional quals can suppress visits to the heap, so
5984 * it's OK to count them in indexSelectivity, but they should not count
5985 * for estimating numIndexTuples. So we must examine the given indexQuals
5986 * to find out which ones count as boundary quals. We rely on the
5987 * knowledge that they are given in index column order.
5989 * For a RowCompareExpr, we consider only the first column, just as
5990 * rowcomparesel() does.
5992 * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
5993 * index scans not one, but the ScalarArrayOpExpr's operator can be
5994 * considered to act the same as it normally does.
5996 indexBoundQuals = NIL;
6000 found_is_null_op = false;
6002 foreach(l, indexQuals)
6004 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6010 bool is_null_op = false;
6012 Assert(IsA(rinfo, RestrictInfo));
6013 clause = rinfo->clause;
6014 if (IsA(clause, OpExpr))
6016 leftop = get_leftop(clause);
6017 rightop = get_rightop(clause);
6018 clause_op = ((OpExpr *) clause)->opno;
6020 else if (IsA(clause, RowCompareExpr))
6022 RowCompareExpr *rc = (RowCompareExpr *) clause;
6024 leftop = (Node *) linitial(rc->largs);
6025 rightop = (Node *) linitial(rc->rargs);
6026 clause_op = linitial_oid(rc->opnos);
6028 else if (IsA(clause, ScalarArrayOpExpr))
6030 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6032 leftop = (Node *) linitial(saop->args);
6033 rightop = (Node *) lsecond(saop->args);
6034 clause_op = saop->opno;
6037 else if (IsA(clause, NullTest))
6039 NullTest *nt = (NullTest *) clause;
6041 leftop = (Node *) nt->arg;
6043 clause_op = InvalidOid;
6044 if (nt->nulltesttype == IS_NULL)
6046 found_is_null_op = true;
6052 elog(ERROR, "unsupported indexqual type: %d",
6053 (int) nodeTag(clause));
6054 continue; /* keep compiler quiet */
6056 if (match_index_to_operand(leftop, indexcol, index))
6058 /* clause_op is correct */
6060 else if (match_index_to_operand(rightop, indexcol, index))
6062 /* Must flip operator to get the opfamily member */
6063 clause_op = get_commutator(clause_op);
6067 /* Must be past the end of quals for indexcol, try next */
6069 break; /* done if no '=' qual for indexcol */
6072 if (match_index_to_operand(leftop, indexcol, index))
6074 /* clause_op is correct */
6076 else if (match_index_to_operand(rightop, indexcol, index))
6078 /* Must flip operator to get the opfamily member */
6079 clause_op = get_commutator(clause_op);
6083 /* No quals for new indexcol, so we are done */
6087 /* check for equality operator */
6088 if (OidIsValid(clause_op))
6090 op_strategy = get_op_opfamily_strategy(clause_op,
6091 index->opfamily[indexcol]);
6092 Assert(op_strategy != 0); /* not a member of opfamily?? */
6093 if (op_strategy == BTEqualStrategyNumber)
6096 else if (is_null_op)
6098 /* IS NULL is like = for purposes of selectivity determination */
6101 /* count up number of SA scans induced by indexBoundQuals only */
6102 if (IsA(clause, ScalarArrayOpExpr))
6104 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6105 int alength = estimate_array_length(lsecond(saop->args));
6108 num_sa_scans *= alength;
6110 indexBoundQuals = lappend(indexBoundQuals, rinfo);
6114 * If index is unique and we found an '=' clause for each column, we can
6115 * just assume numIndexTuples = 1 and skip the expensive
6116 * clauselist_selectivity calculations. However, a ScalarArrayOp or
6117 * NullTest invalidates that theory, even though it sets eqQualHere.
6119 if (index->unique &&
6120 indexcol == index->ncolumns - 1 &&
6124 numIndexTuples = 1.0;
6127 Selectivity btreeSelectivity;
6129 btreeSelectivity = clauselist_selectivity(root, indexBoundQuals,
6133 numIndexTuples = btreeSelectivity * index->rel->tuples;
6136 * As in genericcostestimate(), we have to adjust for any
6137 * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6140 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6143 genericcostestimate(root, index, indexQuals, indexOrderBys,
6144 outer_rel, numIndexTuples,
6145 indexStartupCost, indexTotalCost,
6146 indexSelectivity, indexCorrelation);
6149 * If we can get an estimate of the first column's ordering correlation C
6150 * from pg_statistic, estimate the index correlation as C for a
6151 * single-column index, or C * 0.75 for multiple columns. (The idea here
6152 * is that multiple columns dilute the importance of the first column's
6153 * ordering, but don't negate it entirely. Before 8.0 we divided the
6154 * correlation by the number of columns, but that seems too strong.)
6156 * We can skip all this if we found a ScalarArrayOpExpr, because then the
6157 * call must be for a bitmap index scan, and the caller isn't going to
6158 * care what the index correlation is.
6163 MemSet(&vardata, 0, sizeof(vardata));
6165 if (index->indexkeys[0] != 0)
6167 /* Simple variable --- look to stats for the underlying table */
6168 RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6170 Assert(rte->rtekind == RTE_RELATION);
6172 Assert(relid != InvalidOid);
6173 colnum = index->indexkeys[0];
6175 if (get_relation_stats_hook &&
6176 (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6179 * The hook took control of acquiring a stats tuple. If it did
6180 * supply a tuple, it'd better have supplied a freefunc.
6182 if (HeapTupleIsValid(vardata.statsTuple) &&
6184 elog(ERROR, "no function provided to release variable stats with");
6188 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6189 ObjectIdGetDatum(relid),
6190 Int16GetDatum(colnum),
6191 BoolGetDatum(rte->inh));
6192 vardata.freefunc = ReleaseSysCache;
6197 /* Expression --- maybe there are stats for the index itself */
6198 relid = index->indexoid;
6201 if (get_index_stats_hook &&
6202 (*get_index_stats_hook) (root, relid, colnum, &vardata))
6205 * The hook took control of acquiring a stats tuple. If it did
6206 * supply a tuple, it'd better have supplied a freefunc.
6208 if (HeapTupleIsValid(vardata.statsTuple) &&
6210 elog(ERROR, "no function provided to release variable stats with");
6214 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6215 ObjectIdGetDatum(relid),
6216 Int16GetDatum(colnum),
6217 BoolGetDatum(false));
6218 vardata.freefunc = ReleaseSysCache;
6222 if (HeapTupleIsValid(vardata.statsTuple))
6228 sortop = get_opfamily_member(index->opfamily[0],
6229 index->opcintype[0],
6230 index->opcintype[0],
6231 BTLessStrategyNumber);
6232 if (OidIsValid(sortop) &&
6233 get_attstatsslot(vardata.statsTuple, InvalidOid, 0,
6234 STATISTIC_KIND_CORRELATION,
6238 &numbers, &nnumbers))
6240 double varCorrelation;
6242 Assert(nnumbers == 1);
6243 varCorrelation = numbers[0];
6245 if (index->reverse_sort[0])
6246 varCorrelation = -varCorrelation;
6248 if (index->ncolumns > 1)
6249 *indexCorrelation = varCorrelation * 0.75;
6251 *indexCorrelation = varCorrelation;
6253 free_attstatsslot(InvalidOid, NULL, 0, numbers, nnumbers);
6257 ReleaseVariableStats(vardata);
6263 hashcostestimate(PG_FUNCTION_ARGS)
6265 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6266 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
6267 List *indexQuals = (List *) PG_GETARG_POINTER(2);
6268 List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
6269 RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
6270 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
6271 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
6272 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
6273 double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
6275 genericcostestimate(root, index, indexQuals, indexOrderBys, outer_rel, 0.0,
6276 indexStartupCost, indexTotalCost,
6277 indexSelectivity, indexCorrelation);
6283 gistcostestimate(PG_FUNCTION_ARGS)
6285 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6286 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
6287 List *indexQuals = (List *) PG_GETARG_POINTER(2);
6288 List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
6289 RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
6290 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
6291 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
6292 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
6293 double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
6295 genericcostestimate(root, index, indexQuals, indexOrderBys, outer_rel, 0.0,
6296 indexStartupCost, indexTotalCost,
6297 indexSelectivity, indexCorrelation);
6302 /* Find the index column matching "op"; return its index, or -1 if no match */
6304 find_index_column(Node *op, IndexOptInfo *index)
6308 for (i = 0; i < index->ncolumns; i++)
6310 if (match_index_to_operand(op, i, index))
6318 * GIN has search behavior completely different from other index types
6321 gincostestimate(PG_FUNCTION_ARGS)
6323 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6324 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
6325 List *indexQuals = (List *) PG_GETARG_POINTER(2);
6326 List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
6327 RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
6328 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
6329 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
6330 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
6331 double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
6333 List *selectivityQuals;
6334 double numPages = index->pages,
6335 numTuples = index->tuples;
6336 double numEntryPages,
6340 bool haveFullScan = false;
6341 double partialEntriesInQuals = 0.0;
6342 double searchEntriesInQuals = 0.0;
6343 double exactEntriesInQuals = 0.0;
6344 double entryPagesFetched,
6346 dataPagesFetchedBySel;
6347 double qual_op_cost,
6349 spc_random_page_cost,
6351 QualCost index_qual_cost;
6353 GinStatsData ginStats;
6356 * Obtain statistic information from the meta page
6358 indexRel = index_open(index->indexoid, AccessShareLock);
6359 ginGetStats(indexRel, &ginStats);
6360 index_close(indexRel, AccessShareLock);
6362 numEntryPages = ginStats.nEntryPages;
6363 numDataPages = ginStats.nDataPages;
6364 numPendingPages = ginStats.nPendingPages;
6365 numEntries = ginStats.nEntries;
6368 * nPendingPages can be trusted, but the other fields are as of the last
6369 * VACUUM. Scale them by the ratio numPages / nTotalPages to account for
6370 * growth since then. If the fields are zero (implying no VACUUM at all,
6371 * and an index created pre-9.1), assume all pages are entry pages.
6373 if (ginStats.nTotalPages == 0 || ginStats.nEntryPages == 0)
6375 numEntryPages = numPages;
6377 numEntries = numTuples; /* bogus, but no other info available */
6381 double scale = numPages / ginStats.nTotalPages;
6383 numEntryPages = ceil(numEntryPages * scale);
6384 numDataPages = ceil(numDataPages * scale);
6385 numEntries = ceil(numEntries * scale);
6386 /* ensure we didn't round up too much */
6387 numEntryPages = Min(numEntryPages, numPages);
6388 numDataPages = Min(numDataPages, numPages - numEntryPages);
6392 * Include predicate in selectivityQuals (should match
6393 * genericcostestimate)
6395 if (index->indpred != NIL)
6397 List *predExtraQuals = NIL;
6399 foreach(l, index->indpred)
6401 Node *predQual = (Node *) lfirst(l);
6402 List *oneQual = list_make1(predQual);
6404 if (!predicate_implied_by(oneQual, indexQuals))
6405 predExtraQuals = list_concat(predExtraQuals, oneQual);
6407 /* list_concat avoids modifying the passed-in indexQuals list */
6408 selectivityQuals = list_concat(predExtraQuals, indexQuals);
6411 selectivityQuals = indexQuals;
6413 /* Estimate the fraction of main-table tuples that will be visited */
6414 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6419 /* fetch estimated page cost for schema containing index */
6420 get_tablespace_page_costs(index->reltablespace,
6421 &spc_random_page_cost,
6425 * Generic assumption about index correlation: there isn't any.
6427 *indexCorrelation = 0.0;
6430 * Examine quals to estimate number of search entries & partial matches
6432 foreach(l, indexQuals)
6434 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6445 bool *partial_matches = NULL;
6446 Pointer *extra_data = NULL;
6447 bool *nullFlags = NULL;
6448 int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
6451 Assert(IsA(rinfo, RestrictInfo));
6452 clause = rinfo->clause;
6453 Assert(IsA(clause, OpExpr));
6454 leftop = get_leftop(clause);
6455 rightop = get_rightop(clause);
6456 clause_op = ((OpExpr *) clause)->opno;
6458 if ((indexcol = find_index_column(leftop, index)) >= 0)
6462 else if ((indexcol = find_index_column(rightop, index)) >= 0)
6465 clause_op = get_commutator(clause_op);
6469 elog(ERROR, "could not match index to operand");
6470 operand = NULL; /* keep compiler quiet */
6473 if (IsA(operand, RelabelType))
6474 operand = (Node *) ((RelabelType *) operand)->arg;
6477 * It's impossible to call extractQuery method for unknown operand. So
6478 * unless operand is a Const we can't do much; just assume there will
6479 * be one ordinary search entry from the operand at runtime.
6481 if (!IsA(operand, Const))
6483 searchEntriesInQuals++;
6487 /* If Const is null, there can be no matches */
6488 if (((Const *) operand)->constisnull)
6490 *indexStartupCost = 0;
6491 *indexTotalCost = 0;
6492 *indexSelectivity = 0;
6497 * Get the operator's strategy number and declared input data types
6498 * within the index opfamily. (We don't need the latter, but we use
6499 * get_op_opfamily_properties because it will throw error if it fails
6500 * to find a matching pg_amop entry.)
6502 get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
6503 &strategy_op, &lefttype, &righttype);
6506 * GIN always uses the "default" support functions, which are those
6507 * with lefttype == righttype == the opclass' opcintype (see
6508 * IndexSupportInitialize in relcache.c).
6510 extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
6511 index->opcintype[indexcol],
6512 index->opcintype[indexcol],
6513 GIN_EXTRACTQUERY_PROC);
6515 if (!OidIsValid(extractProcOid))
6517 /* should not happen; throw same error as index_getprocinfo */
6518 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
6519 GIN_EXTRACTQUERY_PROC, indexcol + 1,
6520 get_rel_name(index->indexoid));
6523 OidFunctionCall7(extractProcOid,
6524 ((Const *) operand)->constvalue,
6525 PointerGetDatum(&nentries),
6526 UInt16GetDatum(strategy_op),
6527 PointerGetDatum(&partial_matches),
6528 PointerGetDatum(&extra_data),
6529 PointerGetDatum(&nullFlags),
6530 PointerGetDatum(&searchMode));
6532 if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
6534 /* No match is possible */
6535 *indexStartupCost = 0;
6536 *indexTotalCost = 0;
6537 *indexSelectivity = 0;
6544 for (i = 0; i < nentries; i++)
6547 * For partial match we haven't any information to estimate
6548 * number of matched entries in index, so, we just estimate it
6551 if (partial_matches && partial_matches[i])
6552 partialEntriesInQuals += 100;
6554 exactEntriesInQuals++;
6556 searchEntriesInQuals++;
6560 if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
6562 /* Treat "include empty" like an exact-match item */
6563 exactEntriesInQuals++;
6564 searchEntriesInQuals++;
6566 else if (searchMode != GIN_SEARCH_MODE_DEFAULT)
6568 /* It's GIN_SEARCH_MODE_ALL */
6569 haveFullScan = true;
6573 if (haveFullScan || indexQuals == NIL)
6576 * Full index scan will be required. We treat this as if every key in
6577 * the index had been listed in the query; is that reasonable?
6579 searchEntriesInQuals = numEntries;
6582 /* Will we have more than one iteration of a nestloop scan? */
6583 if (outer_rel != NULL && outer_rel->rows > 1)
6584 num_scans = outer_rel->rows;
6589 * cost to begin scan, first of all, pay attention to pending list.
6591 entryPagesFetched = numPendingPages;
6594 * Estimate number of entry pages read. We need to do
6595 * searchEntriesInQuals searches. Use a power function as it should be,
6596 * but tuples on leaf pages usually is much greater. Here we include all
6597 * searches in entry tree, including search of first entry in partial
6600 entryPagesFetched += ceil(searchEntriesInQuals * rint(pow(numEntryPages, 0.15)));
6603 * Add an estimate of entry pages read by partial match algorithm. It's a
6604 * scan over leaf pages in entry tree. We haven't any useful stats here,
6605 * so estimate it as proportion.
6607 entryPagesFetched += ceil(numEntryPages * partialEntriesInQuals / numEntries);
6610 * Partial match algorithm reads all data pages before doing actual scan,
6611 * so it's a startup cost. Again, we havn't any useful stats here, so,
6612 * estimate it as proportion
6614 dataPagesFetched = ceil(numDataPages * partialEntriesInQuals / numEntries);
6616 /* calculate cache effects */
6617 if (num_scans > 1 || searchEntriesInQuals > 1)
6619 entryPagesFetched = index_pages_fetched(entryPagesFetched,
6620 (BlockNumber) numEntryPages,
6621 numEntryPages, root);
6622 dataPagesFetched = index_pages_fetched(dataPagesFetched,
6623 (BlockNumber) numDataPages,
6624 numDataPages, root);
6628 * Here we use random page cost because logically-close pages could be far
6631 *indexStartupCost = (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
6633 /* cost to scan data pages for each exact (non-partial) matched entry */
6634 dataPagesFetched = ceil(numDataPages * exactEntriesInQuals / numEntries);
6637 * Estimate number of data pages read, using selectivity estimation and
6638 * capacity of data page.
6640 dataPagesFetchedBySel = ceil(*indexSelectivity *
6641 (numTuples / (BLCKSZ / SizeOfIptrData)));
6643 if (dataPagesFetchedBySel > dataPagesFetched)
6646 * At least one of entries is very frequent and, unfortunately, we
6647 * couldn't get statistic about entries (only tsvector has such
6648 * statistics). So, we obviously have too small estimation of pages
6649 * fetched from data tree. Re-estimate it from known capacity of data
6652 dataPagesFetched = dataPagesFetchedBySel;
6656 dataPagesFetched = index_pages_fetched(dataPagesFetched,
6657 (BlockNumber) numDataPages,
6658 numDataPages, root);
6659 *indexTotalCost = *indexStartupCost +
6660 dataPagesFetched * spc_random_page_cost;
6663 * Add on index qual eval costs, much as in genericcostestimate
6665 cost_qual_eval(&index_qual_cost, indexQuals, root);
6666 qual_arg_cost = index_qual_cost.startup + index_qual_cost.per_tuple;
6667 cost_qual_eval(&index_qual_cost, indexOrderBys, root);
6668 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6669 qual_op_cost = cpu_operator_cost *
6670 (list_length(indexQuals) + list_length(indexOrderBys));
6671 qual_arg_cost -= qual_op_cost;
6672 if (qual_arg_cost < 0) /* just in case... */
6675 *indexStartupCost += qual_arg_cost;
6676 *indexTotalCost += qual_arg_cost;
6677 *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost + qual_op_cost);