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-2013, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
18 * src/backend/utils/adt/selfuncs.c
20 *-------------------------------------------------------------------------
24 * Operator selectivity estimation functions are called to estimate the
25 * selectivity of WHERE clauses whose top-level operator is their operator.
26 * We divide the problem into two cases:
27 * Restriction clause estimation: the clause involves vars of just
29 * Join clause estimation: the clause involves vars of multiple rels.
30 * Join selectivity estimation is far more difficult and usually less accurate
31 * than restriction estimation.
33 * When dealing with the inner scan of a nestloop join, we consider the
34 * join's joinclauses as restriction clauses for the inner relation, and
35 * treat vars of the outer relation as parameters (a/k/a constants of unknown
36 * values). So, restriction estimators need to be able to accept an argument
37 * telling which relation is to be treated as the variable.
39 * The call convention for a restriction estimator (oprrest function) is
41 * Selectivity oprrest (PlannerInfo *root,
46 * root: general information about the query (rtable and RelOptInfo lists
47 * are particularly important for the estimator).
48 * operator: OID of the specific operator in question.
49 * args: argument list from the operator clause.
50 * varRelid: if not zero, the relid (rtable index) of the relation to
51 * be treated as the variable relation. May be zero if the args list
52 * is known to contain vars of only one relation.
54 * This is represented at the SQL level (in pg_proc) as
56 * float8 oprrest (internal, oid, internal, int4);
58 * The result is a selectivity, that is, a fraction (0 to 1) of the rows
59 * of the relation that are expected to produce a TRUE result for the
62 * The call convention for a join estimator (oprjoin function) is similar
63 * except that varRelid is not needed, and instead join information is
66 * Selectivity oprjoin (PlannerInfo *root,
70 * SpecialJoinInfo *sjinfo);
72 * float8 oprjoin (internal, oid, internal, int2, internal);
74 * (Before Postgres 8.4, join estimators had only the first four of these
75 * parameters. That signature is still allowed, but deprecated.) The
76 * relationship between jointype and sjinfo is explained in the comments for
77 * clause_selectivity() --- the short version is that jointype is usually
78 * best ignored in favor of examining sjinfo.
80 * Join selectivity for regular inner and outer joins is defined as the
81 * fraction (0 to 1) of the cross product of the relations that is expected
82 * to produce a TRUE result for the given operator. For both semi and anti
83 * joins, however, the selectivity is defined as the fraction of the left-hand
84 * side relation's rows that are expected to have a match (ie, at least one
85 * row with a TRUE result) in the right-hand side.
87 * For both oprrest and oprjoin functions, the operator's input collation OID
88 * (if any) is passed using the standard fmgr mechanism, so that the estimator
89 * function can fetch it with PG_GET_COLLATION(). Note, however, that all
90 * statistics in pg_statistic are currently built using the database's default
91 * collation. Thus, in most cases where we are looking at statistics, we
92 * should ignore the actual operator collation and use DEFAULT_COLLATION_OID.
93 * We expect that the error induced by doing this is usually not large enough
94 * to justify complicating matters.
103 #include "access/gin.h"
104 #include "access/htup_details.h"
105 #include "access/sysattr.h"
106 #include "catalog/index.h"
107 #include "catalog/pg_collation.h"
108 #include "catalog/pg_opfamily.h"
109 #include "catalog/pg_statistic.h"
110 #include "catalog/pg_type.h"
111 #include "executor/executor.h"
112 #include "mb/pg_wchar.h"
113 #include "nodes/makefuncs.h"
114 #include "nodes/nodeFuncs.h"
115 #include "optimizer/clauses.h"
116 #include "optimizer/cost.h"
117 #include "optimizer/pathnode.h"
118 #include "optimizer/paths.h"
119 #include "optimizer/plancat.h"
120 #include "optimizer/predtest.h"
121 #include "optimizer/restrictinfo.h"
122 #include "optimizer/var.h"
123 #include "parser/parse_clause.h"
124 #include "parser/parse_coerce.h"
125 #include "parser/parsetree.h"
126 #include "utils/builtins.h"
127 #include "utils/bytea.h"
128 #include "utils/date.h"
129 #include "utils/datum.h"
130 #include "utils/fmgroids.h"
131 #include "utils/lsyscache.h"
132 #include "utils/nabstime.h"
133 #include "utils/pg_locale.h"
134 #include "utils/rel.h"
135 #include "utils/selfuncs.h"
136 #include "utils/spccache.h"
137 #include "utils/syscache.h"
138 #include "utils/timestamp.h"
139 #include "utils/tqual.h"
140 #include "utils/typcache.h"
143 /* Hooks for plugins to get control when we ask for stats */
144 get_relation_stats_hook_type get_relation_stats_hook = NULL;
145 get_index_stats_hook_type get_index_stats_hook = NULL;
147 static double var_eq_const(VariableStatData *vardata, Oid operator,
148 Datum constval, bool constisnull,
150 static double var_eq_non_const(VariableStatData *vardata, Oid operator,
153 static double ineq_histogram_selectivity(PlannerInfo *root,
154 VariableStatData *vardata,
155 FmgrInfo *opproc, bool isgt,
156 Datum constval, Oid consttype);
157 static double eqjoinsel_inner(Oid operator,
158 VariableStatData *vardata1, VariableStatData *vardata2);
159 static double eqjoinsel_semi(Oid operator,
160 VariableStatData *vardata1, VariableStatData *vardata2,
161 RelOptInfo *inner_rel);
162 static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
163 Datum lobound, Datum hibound, Oid boundstypid,
164 double *scaledlobound, double *scaledhibound);
165 static double convert_numeric_to_scalar(Datum value, Oid typid);
166 static void convert_string_to_scalar(char *value,
169 double *scaledlobound,
171 double *scaledhibound);
172 static void convert_bytea_to_scalar(Datum value,
175 double *scaledlobound,
177 double *scaledhibound);
178 static double convert_one_string_to_scalar(char *value,
179 int rangelo, int rangehi);
180 static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
181 int rangelo, int rangehi);
182 static char *convert_string_datum(Datum value, Oid typid);
183 static double convert_timevalue_to_scalar(Datum value, Oid typid);
184 static void examine_simple_variable(PlannerInfo *root, Var *var,
185 VariableStatData *vardata);
186 static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
187 Oid sortop, Datum *min, Datum *max);
188 static bool get_actual_variable_range(PlannerInfo *root,
189 VariableStatData *vardata,
191 Datum *min, Datum *max);
192 static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
193 static Selectivity prefix_selectivity(PlannerInfo *root,
194 VariableStatData *vardata,
195 Oid vartype, Oid opfamily, Const *prefixcon);
196 static Selectivity like_selectivity(const char *patt, int pattlen,
197 bool case_insensitive);
198 static Selectivity regex_selectivity(const char *patt, int pattlen,
199 bool case_insensitive,
200 int fixed_prefix_len);
201 static Datum string_to_datum(const char *str, Oid datatype);
202 static Const *string_to_const(const char *str, Oid datatype);
203 static Const *string_to_bytea_const(const char *str, size_t str_len);
204 static List *add_predicate_to_quals(IndexOptInfo *index, List *indexQuals);
208 * eqsel - Selectivity of "=" for any data types.
210 * Note: this routine is also used to estimate selectivity for some
211 * operators that are not "=" but have comparable selectivity behavior,
212 * such as "~=" (geometric approximate-match). Even for "=", we must
213 * keep in mind that the left and right datatypes may differ.
216 eqsel(PG_FUNCTION_ARGS)
218 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
219 Oid operator = PG_GETARG_OID(1);
220 List *args = (List *) PG_GETARG_POINTER(2);
221 int varRelid = PG_GETARG_INT32(3);
222 VariableStatData vardata;
228 * If expression is not variable = something or something = variable, then
229 * punt and return a default estimate.
231 if (!get_restriction_variable(root, args, varRelid,
232 &vardata, &other, &varonleft))
233 PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
236 * We can do a lot better if the something is a constant. (Note: the
237 * Const might result from estimation rather than being a simple constant
240 if (IsA(other, Const))
241 selec = var_eq_const(&vardata, operator,
242 ((Const *) other)->constvalue,
243 ((Const *) other)->constisnull,
246 selec = var_eq_non_const(&vardata, operator, other,
249 ReleaseVariableStats(vardata);
251 PG_RETURN_FLOAT8((float8) selec);
255 * var_eq_const --- eqsel for var = const case
257 * This is split out so that some other estimation functions can use it.
260 var_eq_const(VariableStatData *vardata, Oid operator,
261 Datum constval, bool constisnull,
268 * If the constant is NULL, assume operator is strict and return zero, ie,
269 * operator will never return TRUE.
275 * If we matched the var to a unique index or DISTINCT clause, assume
276 * there is exactly one match regardless of anything else. (This is
277 * slightly bogus, since the index or clause's equality operator might be
278 * different from ours, but it's much more likely to be right than
279 * ignoring the information.)
281 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
282 return 1.0 / vardata->rel->tuples;
284 if (HeapTupleIsValid(vardata->statsTuple))
286 Form_pg_statistic stats;
294 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
297 * Is the constant "=" to any of the column's most common values?
298 * (Although the given operator may not really be "=", we will assume
299 * that seeing whether it returns TRUE is an appropriate test. If you
300 * don't like this, maybe you shouldn't be using eqsel for your
303 if (get_attstatsslot(vardata->statsTuple,
304 vardata->atttype, vardata->atttypmod,
305 STATISTIC_KIND_MCV, InvalidOid,
308 &numbers, &nnumbers))
312 fmgr_info(get_opcode(operator), &eqproc);
314 for (i = 0; i < nvalues; i++)
316 /* be careful to apply operator right way 'round */
318 match = DatumGetBool(FunctionCall2Coll(&eqproc,
319 DEFAULT_COLLATION_OID,
323 match = DatumGetBool(FunctionCall2Coll(&eqproc,
324 DEFAULT_COLLATION_OID,
333 /* no most-common-value info available */
336 i = nvalues = nnumbers = 0;
342 * Constant is "=" to this common value. We know selectivity
343 * exactly (or as exactly as ANALYZE could calculate it, anyway).
350 * Comparison is against a constant that is neither NULL nor any
351 * of the common values. Its selectivity cannot be more than
354 double sumcommon = 0.0;
355 double otherdistinct;
357 for (i = 0; i < nnumbers; i++)
358 sumcommon += numbers[i];
359 selec = 1.0 - sumcommon - stats->stanullfrac;
360 CLAMP_PROBABILITY(selec);
363 * and in fact it's probably a good deal less. We approximate that
364 * all the not-common values share this remaining fraction
365 * equally, so we divide by the number of other distinct values.
367 otherdistinct = get_variable_numdistinct(vardata, &isdefault) - nnumbers;
368 if (otherdistinct > 1)
369 selec /= otherdistinct;
372 * Another cross-check: selectivity shouldn't be estimated as more
373 * than the least common "most common value".
375 if (nnumbers > 0 && selec > numbers[nnumbers - 1])
376 selec = numbers[nnumbers - 1];
379 free_attstatsslot(vardata->atttype, values, nvalues,
385 * No ANALYZE stats available, so make a guess using estimated number
386 * of distinct values and assuming they are equally common. (The guess
387 * is unlikely to be very good, but we do know a few special cases.)
389 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
392 /* result should be in range, but make sure... */
393 CLAMP_PROBABILITY(selec);
399 * var_eq_non_const --- eqsel for var = something-other-than-const case
402 var_eq_non_const(VariableStatData *vardata, Oid operator,
410 * If we matched the var to a unique index or DISTINCT clause, assume
411 * there is exactly one match regardless of anything else. (This is
412 * slightly bogus, since the index or clause's equality operator might be
413 * different from ours, but it's much more likely to be right than
414 * ignoring the information.)
416 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
417 return 1.0 / vardata->rel->tuples;
419 if (HeapTupleIsValid(vardata->statsTuple))
421 Form_pg_statistic stats;
426 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
429 * Search is for a value that we do not know a priori, but we will
430 * assume it is not NULL. Estimate the selectivity as non-null
431 * fraction divided by number of distinct values, so that we get a
432 * result averaged over all possible values whether common or
433 * uncommon. (Essentially, we are assuming that the not-yet-known
434 * comparison value is equally likely to be any of the possible
435 * values, regardless of their frequency in the table. Is that a good
438 selec = 1.0 - stats->stanullfrac;
439 ndistinct = get_variable_numdistinct(vardata, &isdefault);
444 * Cross-check: selectivity should never be estimated as more than the
445 * most common value's.
447 if (get_attstatsslot(vardata->statsTuple,
448 vardata->atttype, vardata->atttypmod,
449 STATISTIC_KIND_MCV, InvalidOid,
452 &numbers, &nnumbers))
454 if (nnumbers > 0 && selec > numbers[0])
456 free_attstatsslot(vardata->atttype, NULL, 0, numbers, nnumbers);
462 * No ANALYZE stats available, so make a guess using estimated number
463 * of distinct values and assuming they are equally common. (The guess
464 * is unlikely to be very good, but we do know a few special cases.)
466 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
469 /* result should be in range, but make sure... */
470 CLAMP_PROBABILITY(selec);
476 * neqsel - Selectivity of "!=" for any data types.
478 * This routine is also used for some operators that are not "!="
479 * but have comparable selectivity behavior. See above comments
483 neqsel(PG_FUNCTION_ARGS)
485 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
486 Oid operator = PG_GETARG_OID(1);
487 List *args = (List *) PG_GETARG_POINTER(2);
488 int varRelid = PG_GETARG_INT32(3);
493 * We want 1 - eqsel() where the equality operator is the one associated
494 * with this != operator, that is, its negator.
496 eqop = get_negator(operator);
499 result = DatumGetFloat8(DirectFunctionCall4(eqsel,
500 PointerGetDatum(root),
501 ObjectIdGetDatum(eqop),
502 PointerGetDatum(args),
503 Int32GetDatum(varRelid)));
507 /* Use default selectivity (should we raise an error instead?) */
508 result = DEFAULT_EQ_SEL;
510 result = 1.0 - result;
511 PG_RETURN_FLOAT8(result);
515 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
517 * This is the guts of both scalarltsel and scalargtsel. The caller has
518 * commuted the clause, if necessary, so that we can treat the variable as
519 * being on the left. The caller must also make sure that the other side
520 * of the clause is a non-null Const, and dissect same into a value and
523 * This routine works for any datatype (or pair of datatypes) known to
524 * convert_to_scalar(). If it is applied to some other datatype,
525 * it will return a default estimate.
528 scalarineqsel(PlannerInfo *root, Oid operator, bool isgt,
529 VariableStatData *vardata, Datum constval, Oid consttype)
531 Form_pg_statistic stats;
538 if (!HeapTupleIsValid(vardata->statsTuple))
540 /* no stats available, so default result */
541 return DEFAULT_INEQ_SEL;
543 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
545 fmgr_info(get_opcode(operator), &opproc);
548 * If we have most-common-values info, add up the fractions of the MCV
549 * entries that satisfy MCV OP CONST. These fractions contribute directly
550 * to the result selectivity. Also add up the total fraction represented
553 mcv_selec = mcv_selectivity(vardata, &opproc, constval, true,
557 * If there is a histogram, determine which bin the constant falls in, and
558 * compute the resulting contribution to selectivity.
560 hist_selec = ineq_histogram_selectivity(root, vardata, &opproc, isgt,
561 constval, consttype);
564 * Now merge the results from the MCV and histogram calculations,
565 * realizing that the histogram covers only the non-null values that are
568 selec = 1.0 - stats->stanullfrac - sumcommon;
570 if (hist_selec >= 0.0)
575 * If no histogram but there are values not accounted for by MCV,
576 * arbitrarily assume half of them will match.
583 /* result should be in range, but make sure... */
584 CLAMP_PROBABILITY(selec);
590 * mcv_selectivity - Examine the MCV list for selectivity estimates
592 * Determine the fraction of the variable's MCV population that satisfies
593 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
594 * compute the fraction of the total column population represented by the MCV
595 * list. This code will work for any boolean-returning predicate operator.
597 * The function result is the MCV selectivity, and the fraction of the
598 * total population is returned into *sumcommonp. Zeroes are returned
599 * if there is no MCV list.
602 mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
603 Datum constval, bool varonleft,
617 if (HeapTupleIsValid(vardata->statsTuple) &&
618 get_attstatsslot(vardata->statsTuple,
619 vardata->atttype, vardata->atttypmod,
620 STATISTIC_KIND_MCV, InvalidOid,
623 &numbers, &nnumbers))
625 for (i = 0; i < nvalues; i++)
628 DatumGetBool(FunctionCall2Coll(opproc,
629 DEFAULT_COLLATION_OID,
632 DatumGetBool(FunctionCall2Coll(opproc,
633 DEFAULT_COLLATION_OID,
636 mcv_selec += numbers[i];
637 sumcommon += numbers[i];
639 free_attstatsslot(vardata->atttype, values, nvalues,
643 *sumcommonp = sumcommon;
648 * histogram_selectivity - Examine the histogram for selectivity estimates
650 * Determine the fraction of the variable's histogram entries that satisfy
651 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
653 * This code will work for any boolean-returning predicate operator, whether
654 * or not it has anything to do with the histogram sort operator. We are
655 * essentially using the histogram just as a representative sample. However,
656 * small histograms are unlikely to be all that representative, so the caller
657 * should be prepared to fall back on some other estimation approach when the
658 * histogram is missing or very small. It may also be prudent to combine this
659 * approach with another one when the histogram is small.
661 * If the actual histogram size is not at least min_hist_size, we won't bother
662 * to do the calculation at all. Also, if the n_skip parameter is > 0, we
663 * ignore the first and last n_skip histogram elements, on the grounds that
664 * they are outliers and hence not very representative. Typical values for
665 * these parameters are 10 and 1.
667 * The function result is the selectivity, or -1 if there is no histogram
668 * or it's smaller than min_hist_size.
670 * The output parameter *hist_size receives the actual histogram size,
671 * or zero if no histogram. Callers may use this number to decide how
672 * much faith to put in the function result.
674 * Note that the result disregards both the most-common-values (if any) and
675 * null entries. The caller is expected to combine this result with
676 * statistics for those portions of the column population. It may also be
677 * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
680 histogram_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
681 Datum constval, bool varonleft,
682 int min_hist_size, int n_skip,
689 /* check sanity of parameters */
691 Assert(min_hist_size > 2 * n_skip);
693 if (HeapTupleIsValid(vardata->statsTuple) &&
694 get_attstatsslot(vardata->statsTuple,
695 vardata->atttype, vardata->atttypmod,
696 STATISTIC_KIND_HISTOGRAM, InvalidOid,
701 *hist_size = nvalues;
702 if (nvalues >= min_hist_size)
707 for (i = n_skip; i < nvalues - n_skip; i++)
710 DatumGetBool(FunctionCall2Coll(opproc,
711 DEFAULT_COLLATION_OID,
714 DatumGetBool(FunctionCall2Coll(opproc,
715 DEFAULT_COLLATION_OID,
720 result = ((double) nmatch) / ((double) (nvalues - 2 * n_skip));
724 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
736 * ineq_histogram_selectivity - Examine the histogram for scalarineqsel
738 * Determine the fraction of the variable's histogram population that
739 * satisfies the inequality condition, ie, VAR < CONST or VAR > CONST.
741 * Returns -1 if there is no histogram (valid results will always be >= 0).
743 * Note that the result disregards both the most-common-values (if any) and
744 * null entries. The caller is expected to combine this result with
745 * statistics for those portions of the column population.
748 ineq_histogram_selectivity(PlannerInfo *root,
749 VariableStatData *vardata,
750 FmgrInfo *opproc, bool isgt,
751 Datum constval, Oid consttype)
761 * Someday, ANALYZE might store more than one histogram per rel/att,
762 * corresponding to more than one possible sort ordering defined for the
763 * column type. However, to make that work we will need to figure out
764 * which staop to search for --- it's not necessarily the one we have at
765 * hand! (For example, we might have a '<=' operator rather than the '<'
766 * operator that will appear in staop.) For now, assume that whatever
767 * appears in pg_statistic is sorted the same way our operator sorts, or
768 * the reverse way if isgt is TRUE.
770 if (HeapTupleIsValid(vardata->statsTuple) &&
771 get_attstatsslot(vardata->statsTuple,
772 vardata->atttype, vardata->atttypmod,
773 STATISTIC_KIND_HISTOGRAM, InvalidOid,
781 * Use binary search to find proper location, ie, the first slot
782 * at which the comparison fails. (If the given operator isn't
783 * actually sort-compatible with the histogram, you'll get garbage
784 * results ... but probably not any more garbage-y than you would
785 * from the old linear search.)
787 * If the binary search accesses the first or last histogram
788 * entry, we try to replace that endpoint with the true column min
789 * or max as found by get_actual_variable_range(). This
790 * ameliorates misestimates when the min or max is moving as a
791 * result of changes since the last ANALYZE. Note that this could
792 * result in effectively including MCVs into the histogram that
793 * weren't there before, but we don't try to correct for that.
796 int lobound = 0; /* first possible slot to search */
797 int hibound = nvalues; /* last+1 slot to search */
798 bool have_end = false;
801 * If there are only two histogram entries, we'll want up-to-date
802 * values for both. (If there are more than two, we need at most
803 * one of them to be updated, so we deal with that within the
807 have_end = get_actual_variable_range(root,
813 while (lobound < hibound)
815 int probe = (lobound + hibound) / 2;
819 * If we find ourselves about to compare to the first or last
820 * histogram entry, first try to replace it with the actual
821 * current min or max (unless we already did so above).
823 if (probe == 0 && nvalues > 2)
824 have_end = get_actual_variable_range(root,
829 else if (probe == nvalues - 1 && nvalues > 2)
830 have_end = get_actual_variable_range(root,
836 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
837 DEFAULT_COLLATION_OID,
850 /* Constant is below lower histogram boundary. */
853 else if (lobound >= nvalues)
855 /* Constant is above upper histogram boundary. */
867 * We have values[i-1] <= constant <= values[i].
869 * Convert the constant and the two nearest bin boundary
870 * values to a uniform comparison scale, and do a linear
871 * interpolation within this bin.
873 if (convert_to_scalar(constval, consttype, &val,
874 values[i - 1], values[i],
880 /* cope if bin boundaries appear identical */
885 else if (val >= high)
889 binfrac = (val - low) / (high - low);
892 * Watch out for the possibility that we got a NaN or
893 * Infinity from the division. This can happen
894 * despite the previous checks, if for example "low"
897 if (isnan(binfrac) ||
898 binfrac < 0.0 || binfrac > 1.0)
905 * Ideally we'd produce an error here, on the grounds that
906 * the given operator shouldn't have scalarXXsel
907 * registered as its selectivity func unless we can deal
908 * with its operand types. But currently, all manner of
909 * stuff is invoking scalarXXsel, so give a default
910 * estimate until that can be fixed.
916 * Now, compute the overall selectivity across the values
917 * represented by the histogram. We have i-1 full bins and
918 * binfrac partial bin below the constant.
920 histfrac = (double) (i - 1) + binfrac;
921 histfrac /= (double) (nvalues - 1);
925 * Now histfrac = fraction of histogram entries below the
928 * Account for "<" vs ">"
930 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
933 * The histogram boundaries are only approximate to begin with,
934 * and may well be out of date anyway. Therefore, don't believe
935 * extremely small or large selectivity estimates --- unless we
936 * got actual current endpoint values from the table.
939 CLAMP_PROBABILITY(hist_selec);
942 if (hist_selec < 0.0001)
944 else if (hist_selec > 0.9999)
949 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
956 * scalarltsel - Selectivity of "<" (also "<=") for scalars.
959 scalarltsel(PG_FUNCTION_ARGS)
961 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
962 Oid operator = PG_GETARG_OID(1);
963 List *args = (List *) PG_GETARG_POINTER(2);
964 int varRelid = PG_GETARG_INT32(3);
965 VariableStatData vardata;
974 * If expression is not variable op something or something op variable,
975 * then punt and return a default estimate.
977 if (!get_restriction_variable(root, args, varRelid,
978 &vardata, &other, &varonleft))
979 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
982 * Can't do anything useful if the something is not a constant, either.
984 if (!IsA(other, Const))
986 ReleaseVariableStats(vardata);
987 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
991 * If the constant is NULL, assume operator is strict and return zero, ie,
992 * operator will never return TRUE.
994 if (((Const *) other)->constisnull)
996 ReleaseVariableStats(vardata);
997 PG_RETURN_FLOAT8(0.0);
999 constval = ((Const *) other)->constvalue;
1000 consttype = ((Const *) other)->consttype;
1003 * Force the var to be on the left to simplify logic in scalarineqsel.
1007 /* we have var < other */
1012 /* we have other < var, commute to make var > other */
1013 operator = get_commutator(operator);
1016 /* Use default selectivity (should we raise an error instead?) */
1017 ReleaseVariableStats(vardata);
1018 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1023 selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
1025 ReleaseVariableStats(vardata);
1027 PG_RETURN_FLOAT8((float8) selec);
1031 * scalargtsel - Selectivity of ">" (also ">=") for integers.
1034 scalargtsel(PG_FUNCTION_ARGS)
1036 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1037 Oid operator = PG_GETARG_OID(1);
1038 List *args = (List *) PG_GETARG_POINTER(2);
1039 int varRelid = PG_GETARG_INT32(3);
1040 VariableStatData vardata;
1049 * If expression is not variable op something or something op variable,
1050 * then punt and return a default estimate.
1052 if (!get_restriction_variable(root, args, varRelid,
1053 &vardata, &other, &varonleft))
1054 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1057 * Can't do anything useful if the something is not a constant, either.
1059 if (!IsA(other, Const))
1061 ReleaseVariableStats(vardata);
1062 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1066 * If the constant is NULL, assume operator is strict and return zero, ie,
1067 * operator will never return TRUE.
1069 if (((Const *) other)->constisnull)
1071 ReleaseVariableStats(vardata);
1072 PG_RETURN_FLOAT8(0.0);
1074 constval = ((Const *) other)->constvalue;
1075 consttype = ((Const *) other)->consttype;
1078 * Force the var to be on the left to simplify logic in scalarineqsel.
1082 /* we have var > other */
1087 /* we have other > var, commute to make var < other */
1088 operator = get_commutator(operator);
1091 /* Use default selectivity (should we raise an error instead?) */
1092 ReleaseVariableStats(vardata);
1093 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1098 selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
1100 ReleaseVariableStats(vardata);
1102 PG_RETURN_FLOAT8((float8) selec);
1106 * patternsel - Generic code for pattern-match selectivity.
1109 patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
1111 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1112 Oid operator = PG_GETARG_OID(1);
1113 List *args = (List *) PG_GETARG_POINTER(2);
1114 int varRelid = PG_GETARG_INT32(3);
1115 Oid collation = PG_GET_COLLATION();
1116 VariableStatData vardata;
1123 Pattern_Prefix_Status pstatus;
1125 Const *prefix = NULL;
1126 Selectivity rest_selec = 0;
1130 * If this is for a NOT LIKE or similar operator, get the corresponding
1131 * positive-match operator and work with that. Set result to the correct
1132 * default estimate, too.
1136 operator = get_negator(operator);
1137 if (!OidIsValid(operator))
1138 elog(ERROR, "patternsel called for operator without a negator");
1139 result = 1.0 - DEFAULT_MATCH_SEL;
1143 result = DEFAULT_MATCH_SEL;
1147 * If expression is not variable op constant, then punt and return a
1150 if (!get_restriction_variable(root, args, varRelid,
1151 &vardata, &other, &varonleft))
1153 if (!varonleft || !IsA(other, Const))
1155 ReleaseVariableStats(vardata);
1160 * If the constant is NULL, assume operator is strict and return zero, ie,
1161 * operator will never return TRUE. (It's zero even for a negator op.)
1163 if (((Const *) other)->constisnull)
1165 ReleaseVariableStats(vardata);
1168 constval = ((Const *) other)->constvalue;
1169 consttype = ((Const *) other)->consttype;
1172 * The right-hand const is type text or bytea for all supported operators.
1173 * We do not expect to see binary-compatible types here, since
1174 * const-folding should have relabeled the const to exactly match the
1175 * operator's declared type.
1177 if (consttype != TEXTOID && consttype != BYTEAOID)
1179 ReleaseVariableStats(vardata);
1184 * Similarly, the exposed type of the left-hand side should be one of
1185 * those we know. (Do not look at vardata.atttype, which might be
1186 * something binary-compatible but different.) We can use it to choose
1187 * the index opfamily from which we must draw the comparison operators.
1189 * NOTE: It would be more correct to use the PATTERN opfamilies than the
1190 * simple ones, but at the moment ANALYZE will not generate statistics for
1191 * the PATTERN operators. But our results are so approximate anyway that
1192 * it probably hardly matters.
1194 vartype = vardata.vartype;
1199 opfamily = TEXT_BTREE_FAM_OID;
1202 opfamily = BPCHAR_BTREE_FAM_OID;
1205 opfamily = NAME_BTREE_FAM_OID;
1208 opfamily = BYTEA_BTREE_FAM_OID;
1211 ReleaseVariableStats(vardata);
1216 * Pull out any fixed prefix implied by the pattern, and estimate the
1217 * fractional selectivity of the remainder of the pattern. Unlike many of
1218 * the other functions in this file, we use the pattern operator's actual
1219 * collation for this step. This is not because we expect the collation
1220 * to make a big difference in the selectivity estimate (it seldom would),
1221 * but because we want to be sure we cache compiled regexps under the
1222 * right cache key, so that they can be re-used at runtime.
1224 patt = (Const *) other;
1225 pstatus = pattern_fixed_prefix(patt, ptype, collation,
1226 &prefix, &rest_selec);
1229 * If necessary, coerce the prefix constant to the right type.
1231 if (prefix && prefix->consttype != vartype)
1235 switch (prefix->consttype)
1238 prefixstr = TextDatumGetCString(prefix->constvalue);
1241 prefixstr = DatumGetCString(DirectFunctionCall1(byteaout,
1242 prefix->constvalue));
1245 elog(ERROR, "unrecognized consttype: %u",
1247 ReleaseVariableStats(vardata);
1250 prefix = string_to_const(prefixstr, vartype);
1254 if (pstatus == Pattern_Prefix_Exact)
1257 * Pattern specifies an exact match, so pretend operator is '='
1259 Oid eqopr = get_opfamily_member(opfamily, vartype, vartype,
1260 BTEqualStrategyNumber);
1262 if (eqopr == InvalidOid)
1263 elog(ERROR, "no = operator for opfamily %u", opfamily);
1264 result = var_eq_const(&vardata, eqopr, prefix->constvalue,
1270 * Not exact-match pattern. If we have a sufficiently large
1271 * histogram, estimate selectivity for the histogram part of the
1272 * population by counting matches in the histogram. If not, estimate
1273 * selectivity of the fixed prefix and remainder of pattern
1274 * separately, then combine the two to get an estimate of the
1275 * selectivity for the part of the column population represented by
1276 * the histogram. (For small histograms, we combine these
1279 * We then add up data for any most-common-values values; these are
1280 * not in the histogram population, and we can get exact answers for
1281 * them by applying the pattern operator, so there's no reason to
1282 * approximate. (If the MCVs cover a significant part of the total
1283 * population, this gives us a big leg up in accuracy.)
1292 /* Try to use the histogram entries to get selectivity */
1293 fmgr_info(get_opcode(operator), &opproc);
1295 selec = histogram_selectivity(&vardata, &opproc, constval, true,
1298 /* If not at least 100 entries, use the heuristic method */
1299 if (hist_size < 100)
1301 Selectivity heursel;
1302 Selectivity prefixsel;
1304 if (pstatus == Pattern_Prefix_Partial)
1305 prefixsel = prefix_selectivity(root, &vardata, vartype,
1309 heursel = prefixsel * rest_selec;
1311 if (selec < 0) /* fewer than 10 histogram entries? */
1316 * For histogram sizes from 10 to 100, we combine the
1317 * histogram and heuristic selectivities, putting increasingly
1318 * more trust in the histogram for larger sizes.
1320 double hist_weight = hist_size / 100.0;
1322 selec = selec * hist_weight + heursel * (1.0 - hist_weight);
1326 /* In any case, don't believe extremely small or large estimates. */
1329 else if (selec > 0.9999)
1333 * If we have most-common-values info, add up the fractions of the MCV
1334 * entries that satisfy MCV OP PATTERN. These fractions contribute
1335 * directly to the result selectivity. Also add up the total fraction
1336 * represented by MCV entries.
1338 mcv_selec = mcv_selectivity(&vardata, &opproc, constval, true,
1341 if (HeapTupleIsValid(vardata.statsTuple))
1342 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
1347 * Now merge the results from the MCV and histogram calculations,
1348 * realizing that the histogram covers only the non-null values that
1349 * are not listed in MCV.
1351 selec *= 1.0 - nullfrac - sumcommon;
1354 /* result should be in range, but make sure... */
1355 CLAMP_PROBABILITY(selec);
1361 pfree(DatumGetPointer(prefix->constvalue));
1365 ReleaseVariableStats(vardata);
1367 return negate ? (1.0 - result) : result;
1371 * regexeqsel - Selectivity of regular-expression pattern match.
1374 regexeqsel(PG_FUNCTION_ARGS)
1376 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, false));
1380 * icregexeqsel - Selectivity of case-insensitive regex match.
1383 icregexeqsel(PG_FUNCTION_ARGS)
1385 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, false));
1389 * likesel - Selectivity of LIKE pattern match.
1392 likesel(PG_FUNCTION_ARGS)
1394 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, false));
1398 * iclikesel - Selectivity of ILIKE pattern match.
1401 iclikesel(PG_FUNCTION_ARGS)
1403 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, false));
1407 * regexnesel - Selectivity of regular-expression pattern non-match.
1410 regexnesel(PG_FUNCTION_ARGS)
1412 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, true));
1416 * icregexnesel - Selectivity of case-insensitive regex non-match.
1419 icregexnesel(PG_FUNCTION_ARGS)
1421 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, true));
1425 * nlikesel - Selectivity of LIKE pattern non-match.
1428 nlikesel(PG_FUNCTION_ARGS)
1430 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, true));
1434 * icnlikesel - Selectivity of ILIKE pattern non-match.
1437 icnlikesel(PG_FUNCTION_ARGS)
1439 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, true));
1443 * booltestsel - Selectivity of BooleanTest Node.
1446 booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
1447 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1449 VariableStatData vardata;
1452 examine_variable(root, arg, varRelid, &vardata);
1454 if (HeapTupleIsValid(vardata.statsTuple))
1456 Form_pg_statistic stats;
1463 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1464 freq_null = stats->stanullfrac;
1466 if (get_attstatsslot(vardata.statsTuple,
1467 vardata.atttype, vardata.atttypmod,
1468 STATISTIC_KIND_MCV, InvalidOid,
1471 &numbers, &nnumbers)
1478 * Get first MCV frequency and derive frequency for true.
1480 if (DatumGetBool(values[0]))
1481 freq_true = numbers[0];
1483 freq_true = 1.0 - numbers[0] - freq_null;
1486 * Next derive frequency for false. Then use these as appropriate
1487 * to derive frequency for each case.
1489 freq_false = 1.0 - freq_true - freq_null;
1491 switch (booltesttype)
1494 /* select only NULL values */
1497 case IS_NOT_UNKNOWN:
1498 /* select non-NULL values */
1499 selec = 1.0 - freq_null;
1502 /* select only TRUE values */
1506 /* select non-TRUE values */
1507 selec = 1.0 - freq_true;
1510 /* select only FALSE values */
1514 /* select non-FALSE values */
1515 selec = 1.0 - freq_false;
1518 elog(ERROR, "unrecognized booltesttype: %d",
1519 (int) booltesttype);
1520 selec = 0.0; /* Keep compiler quiet */
1524 free_attstatsslot(vardata.atttype, values, nvalues,
1530 * No most-common-value info available. Still have null fraction
1531 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1532 * for null fraction and assume an even split for boolean tests.
1534 switch (booltesttype)
1539 * Use freq_null directly.
1543 case IS_NOT_UNKNOWN:
1546 * Select not unknown (not null) values. Calculate from
1549 selec = 1.0 - freq_null;
1555 selec = (1.0 - freq_null) / 2.0;
1558 elog(ERROR, "unrecognized booltesttype: %d",
1559 (int) booltesttype);
1560 selec = 0.0; /* Keep compiler quiet */
1568 * If we can't get variable statistics for the argument, perhaps
1569 * clause_selectivity can do something with it. We ignore the
1570 * possibility of a NULL value when using clause_selectivity, and just
1571 * assume the value is either TRUE or FALSE.
1573 switch (booltesttype)
1576 selec = DEFAULT_UNK_SEL;
1578 case IS_NOT_UNKNOWN:
1579 selec = DEFAULT_NOT_UNK_SEL;
1583 selec = (double) clause_selectivity(root, arg,
1589 selec = 1.0 - (double) clause_selectivity(root, arg,
1594 elog(ERROR, "unrecognized booltesttype: %d",
1595 (int) booltesttype);
1596 selec = 0.0; /* Keep compiler quiet */
1601 ReleaseVariableStats(vardata);
1603 /* result should be in range, but make sure... */
1604 CLAMP_PROBABILITY(selec);
1606 return (Selectivity) selec;
1610 * nulltestsel - Selectivity of NullTest Node.
1613 nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1614 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1616 VariableStatData vardata;
1619 examine_variable(root, arg, varRelid, &vardata);
1621 if (HeapTupleIsValid(vardata.statsTuple))
1623 Form_pg_statistic stats;
1626 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1627 freq_null = stats->stanullfrac;
1629 switch (nulltesttype)
1634 * Use freq_null directly.
1641 * Select not unknown (not null) values. Calculate from
1644 selec = 1.0 - freq_null;
1647 elog(ERROR, "unrecognized nulltesttype: %d",
1648 (int) nulltesttype);
1649 return (Selectivity) 0; /* keep compiler quiet */
1655 * No ANALYZE stats available, so make a guess
1657 switch (nulltesttype)
1660 selec = DEFAULT_UNK_SEL;
1663 selec = DEFAULT_NOT_UNK_SEL;
1666 elog(ERROR, "unrecognized nulltesttype: %d",
1667 (int) nulltesttype);
1668 return (Selectivity) 0; /* keep compiler quiet */
1672 ReleaseVariableStats(vardata);
1674 /* result should be in range, but make sure... */
1675 CLAMP_PROBABILITY(selec);
1677 return (Selectivity) selec;
1681 * strip_array_coercion - strip binary-compatible relabeling from an array expr
1683 * For array values, the parser normally generates ArrayCoerceExpr conversions,
1684 * but it seems possible that RelabelType might show up. Also, the planner
1685 * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1686 * so we need to be ready to deal with more than one level.
1689 strip_array_coercion(Node *node)
1693 if (node && IsA(node, ArrayCoerceExpr) &&
1694 ((ArrayCoerceExpr *) node)->elemfuncid == InvalidOid)
1696 node = (Node *) ((ArrayCoerceExpr *) node)->arg;
1698 else if (node && IsA(node, RelabelType))
1700 /* We don't really expect this case, but may as well cope */
1701 node = (Node *) ((RelabelType *) node)->arg;
1710 * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1713 scalararraysel(PlannerInfo *root,
1714 ScalarArrayOpExpr *clause,
1715 bool is_join_clause,
1718 SpecialJoinInfo *sjinfo)
1720 Oid operator = clause->opno;
1721 bool useOr = clause->useOr;
1722 bool isEquality = false;
1723 bool isInequality = false;
1726 Oid nominal_element_type;
1727 Oid nominal_element_collation;
1728 TypeCacheEntry *typentry;
1729 RegProcedure oprsel;
1730 FmgrInfo oprselproc;
1732 Selectivity s1disjoint;
1734 /* First, deconstruct the expression */
1735 Assert(list_length(clause->args) == 2);
1736 leftop = (Node *) linitial(clause->args);
1737 rightop = (Node *) lsecond(clause->args);
1739 /* get nominal (after relabeling) element type of rightop */
1740 nominal_element_type = get_base_element_type(exprType(rightop));
1741 if (!OidIsValid(nominal_element_type))
1742 return (Selectivity) 0.5; /* probably shouldn't happen */
1743 /* get nominal collation, too, for generating constants */
1744 nominal_element_collation = exprCollation(rightop);
1746 /* look through any binary-compatible relabeling of rightop */
1747 rightop = strip_array_coercion(rightop);
1750 * Detect whether the operator is the default equality or inequality
1751 * operator of the array element type.
1753 typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1754 if (OidIsValid(typentry->eq_opr))
1756 if (operator == typentry->eq_opr)
1758 else if (get_negator(operator) == typentry->eq_opr)
1759 isInequality = true;
1763 * If it is equality or inequality, we might be able to estimate this as a
1764 * form of array containment; for instance "const = ANY(column)" can be
1765 * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1766 * that, and returns the selectivity estimate if successful, or -1 if not.
1768 if ((isEquality || isInequality) && !is_join_clause)
1770 s1 = scalararraysel_containment(root, leftop, rightop,
1771 nominal_element_type,
1772 isEquality, useOr, varRelid);
1778 * Look up the underlying operator's selectivity estimator. Punt if it
1782 oprsel = get_oprjoin(operator);
1784 oprsel = get_oprrest(operator);
1786 return (Selectivity) 0.5;
1787 fmgr_info(oprsel, &oprselproc);
1790 * In the array-containment check above, we must only believe that an
1791 * operator is equality or inequality if it is the default btree equality
1792 * operator (or its negator) for the element type, since those are the
1793 * operators that array containment will use. But in what follows, we can
1794 * be a little laxer, and also believe that any operators using eqsel() or
1795 * neqsel() as selectivity estimator act like equality or inequality.
1797 if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1799 else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1800 isInequality = true;
1803 * We consider three cases:
1805 * 1. rightop is an Array constant: deconstruct the array, apply the
1806 * operator's selectivity function for each array element, and merge the
1807 * results in the same way that clausesel.c does for AND/OR combinations.
1809 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1810 * function for each element of the ARRAY[] construct, and merge.
1812 * 3. otherwise, make a guess ...
1814 if (rightop && IsA(rightop, Const))
1816 Datum arraydatum = ((Const *) rightop)->constvalue;
1817 bool arrayisnull = ((Const *) rightop)->constisnull;
1818 ArrayType *arrayval;
1827 if (arrayisnull) /* qual can't succeed if null array */
1828 return (Selectivity) 0.0;
1829 arrayval = DatumGetArrayTypeP(arraydatum);
1830 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1831 &elmlen, &elmbyval, &elmalign);
1832 deconstruct_array(arrayval,
1833 ARR_ELEMTYPE(arrayval),
1834 elmlen, elmbyval, elmalign,
1835 &elem_values, &elem_nulls, &num_elems);
1838 * For generic operators, we assume the probability of success is
1839 * independent for each array element. But for "= ANY" or "<> ALL",
1840 * if the array elements are distinct (which'd typically be the case)
1841 * then the probabilities are disjoint, and we should just sum them.
1843 * If we were being really tense we would try to confirm that the
1844 * elements are all distinct, but that would be expensive and it
1845 * doesn't seem to be worth the cycles; it would amount to penalizing
1846 * well-written queries in favor of poorly-written ones. However, we
1847 * do protect ourselves a little bit by checking whether the
1848 * disjointness assumption leads to an impossible (out of range)
1849 * probability; if so, we fall back to the normal calculation.
1851 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1853 for (i = 0; i < num_elems; i++)
1858 args = list_make2(leftop,
1859 makeConst(nominal_element_type,
1861 nominal_element_collation,
1867 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1868 clause->inputcollid,
1869 PointerGetDatum(root),
1870 ObjectIdGetDatum(operator),
1871 PointerGetDatum(args),
1872 Int16GetDatum(jointype),
1873 PointerGetDatum(sjinfo)));
1875 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1876 clause->inputcollid,
1877 PointerGetDatum(root),
1878 ObjectIdGetDatum(operator),
1879 PointerGetDatum(args),
1880 Int32GetDatum(varRelid)));
1884 s1 = s1 + s2 - s1 * s2;
1892 s1disjoint += s2 - 1.0;
1896 /* accept disjoint-probability estimate if in range */
1897 if ((useOr ? isEquality : isInequality) &&
1898 s1disjoint >= 0.0 && s1disjoint <= 1.0)
1901 else if (rightop && IsA(rightop, ArrayExpr) &&
1902 !((ArrayExpr *) rightop)->multidims)
1904 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1909 get_typlenbyval(arrayexpr->element_typeid,
1910 &elmlen, &elmbyval);
1913 * We use the assumption of disjoint probabilities here too, although
1914 * the odds of equal array elements are rather higher if the elements
1915 * are not all constants (which they won't be, else constant folding
1916 * would have reduced the ArrayExpr to a Const). In this path it's
1917 * critical to have the sanity check on the s1disjoint estimate.
1919 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1921 foreach(l, arrayexpr->elements)
1923 Node *elem = (Node *) lfirst(l);
1928 * Theoretically, if elem isn't of nominal_element_type we should
1929 * insert a RelabelType, but it seems unlikely that any operator
1930 * estimation function would really care ...
1932 args = list_make2(leftop, elem);
1934 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1935 clause->inputcollid,
1936 PointerGetDatum(root),
1937 ObjectIdGetDatum(operator),
1938 PointerGetDatum(args),
1939 Int16GetDatum(jointype),
1940 PointerGetDatum(sjinfo)));
1942 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1943 clause->inputcollid,
1944 PointerGetDatum(root),
1945 ObjectIdGetDatum(operator),
1946 PointerGetDatum(args),
1947 Int32GetDatum(varRelid)));
1951 s1 = s1 + s2 - s1 * s2;
1959 s1disjoint += s2 - 1.0;
1963 /* accept disjoint-probability estimate if in range */
1964 if ((useOr ? isEquality : isInequality) &&
1965 s1disjoint >= 0.0 && s1disjoint <= 1.0)
1970 CaseTestExpr *dummyexpr;
1976 * We need a dummy rightop to pass to the operator selectivity
1977 * routine. It can be pretty much anything that doesn't look like a
1978 * constant; CaseTestExpr is a convenient choice.
1980 dummyexpr = makeNode(CaseTestExpr);
1981 dummyexpr->typeId = nominal_element_type;
1982 dummyexpr->typeMod = -1;
1983 dummyexpr->collation = clause->inputcollid;
1984 args = list_make2(leftop, dummyexpr);
1986 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1987 clause->inputcollid,
1988 PointerGetDatum(root),
1989 ObjectIdGetDatum(operator),
1990 PointerGetDatum(args),
1991 Int16GetDatum(jointype),
1992 PointerGetDatum(sjinfo)));
1994 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1995 clause->inputcollid,
1996 PointerGetDatum(root),
1997 ObjectIdGetDatum(operator),
1998 PointerGetDatum(args),
1999 Int32GetDatum(varRelid)));
2000 s1 = useOr ? 0.0 : 1.0;
2003 * Arbitrarily assume 10 elements in the eventual array value (see
2004 * also estimate_array_length). We don't risk an assumption of
2005 * disjoint probabilities here.
2007 for (i = 0; i < 10; i++)
2010 s1 = s1 + s2 - s1 * s2;
2016 /* result should be in range, but make sure... */
2017 CLAMP_PROBABILITY(s1);
2023 * Estimate number of elements in the array yielded by an expression.
2025 * It's important that this agree with scalararraysel.
2028 estimate_array_length(Node *arrayexpr)
2030 /* look through any binary-compatible relabeling of arrayexpr */
2031 arrayexpr = strip_array_coercion(arrayexpr);
2033 if (arrayexpr && IsA(arrayexpr, Const))
2035 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2036 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2037 ArrayType *arrayval;
2041 arrayval = DatumGetArrayTypeP(arraydatum);
2042 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2044 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2045 !((ArrayExpr *) arrayexpr)->multidims)
2047 return list_length(((ArrayExpr *) arrayexpr)->elements);
2051 /* default guess --- see also scalararraysel */
2057 * rowcomparesel - Selectivity of RowCompareExpr Node.
2059 * We estimate RowCompare selectivity by considering just the first (high
2060 * order) columns, which makes it equivalent to an ordinary OpExpr. While
2061 * this estimate could be refined by considering additional columns, it
2062 * seems unlikely that we could do a lot better without multi-column
2066 rowcomparesel(PlannerInfo *root,
2067 RowCompareExpr *clause,
2068 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
2071 Oid opno = linitial_oid(clause->opnos);
2072 Oid inputcollid = linitial_oid(clause->inputcollids);
2074 bool is_join_clause;
2076 /* Build equivalent arg list for single operator */
2077 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2080 * Decide if it's a join clause. This should match clausesel.c's
2081 * treat_as_join_clause(), except that we intentionally consider only the
2082 * leading columns and not the rest of the clause.
2087 * Caller is forcing restriction mode (eg, because we are examining an
2088 * inner indexscan qual).
2090 is_join_clause = false;
2092 else if (sjinfo == NULL)
2095 * It must be a restriction clause, since it's being evaluated at a
2098 is_join_clause = false;
2103 * Otherwise, it's a join if there's more than one relation used.
2105 is_join_clause = (NumRelids((Node *) opargs) > 1);
2110 /* Estimate selectivity for a join clause. */
2111 s1 = join_selectivity(root, opno,
2119 /* Estimate selectivity for a restriction clause. */
2120 s1 = restriction_selectivity(root, opno,
2130 * eqjoinsel - Join selectivity of "="
2133 eqjoinsel(PG_FUNCTION_ARGS)
2135 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2136 Oid operator = PG_GETARG_OID(1);
2137 List *args = (List *) PG_GETARG_POINTER(2);
2140 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2142 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2144 VariableStatData vardata1;
2145 VariableStatData vardata2;
2146 bool join_is_reversed;
2147 RelOptInfo *inner_rel;
2149 get_join_variables(root, args, sjinfo,
2150 &vardata1, &vardata2, &join_is_reversed);
2152 switch (sjinfo->jointype)
2157 selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2163 * Look up the join's inner relation. min_righthand is sufficient
2164 * information because neither SEMI nor ANTI joins permit any
2165 * reassociation into or out of their RHS, so the righthand will
2166 * always be exactly that set of rels.
2168 inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2170 if (!join_is_reversed)
2171 selec = eqjoinsel_semi(operator, &vardata1, &vardata2,
2174 selec = eqjoinsel_semi(get_commutator(operator),
2175 &vardata2, &vardata1,
2179 /* other values not expected here */
2180 elog(ERROR, "unrecognized join type: %d",
2181 (int) sjinfo->jointype);
2182 selec = 0; /* keep compiler quiet */
2186 ReleaseVariableStats(vardata1);
2187 ReleaseVariableStats(vardata2);
2189 CLAMP_PROBABILITY(selec);
2191 PG_RETURN_FLOAT8((float8) selec);
2195 * eqjoinsel_inner --- eqjoinsel for normal inner join
2197 * We also use this for LEFT/FULL outer joins; it's not presently clear
2198 * that it's worth trying to distinguish them here.
2201 eqjoinsel_inner(Oid operator,
2202 VariableStatData *vardata1, VariableStatData *vardata2)
2209 Form_pg_statistic stats1 = NULL;
2210 Form_pg_statistic stats2 = NULL;
2211 bool have_mcvs1 = false;
2212 Datum *values1 = NULL;
2214 float4 *numbers1 = NULL;
2216 bool have_mcvs2 = false;
2217 Datum *values2 = NULL;
2219 float4 *numbers2 = NULL;
2222 nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2223 nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2225 if (HeapTupleIsValid(vardata1->statsTuple))
2227 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2228 have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2230 vardata1->atttypmod,
2234 &values1, &nvalues1,
2235 &numbers1, &nnumbers1);
2238 if (HeapTupleIsValid(vardata2->statsTuple))
2240 stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2241 have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2243 vardata2->atttypmod,
2247 &values2, &nvalues2,
2248 &numbers2, &nnumbers2);
2251 if (have_mcvs1 && have_mcvs2)
2254 * We have most-common-value lists for both relations. Run through
2255 * the lists to see which MCVs actually join to each other with the
2256 * given operator. This allows us to determine the exact join
2257 * selectivity for the portion of the relations represented by the MCV
2258 * lists. We still have to estimate for the remaining population, but
2259 * in a skewed distribution this gives us a big leg up in accuracy.
2260 * For motivation see the analysis in Y. Ioannidis and S.
2261 * Christodoulakis, "On the propagation of errors in the size of join
2262 * results", Technical Report 1018, Computer Science Dept., University
2263 * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2268 double nullfrac1 = stats1->stanullfrac;
2269 double nullfrac2 = stats2->stanullfrac;
2270 double matchprodfreq,
2282 fmgr_info(get_opcode(operator), &eqproc);
2283 hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2284 hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
2287 * Note we assume that each MCV will match at most one member of the
2288 * other MCV list. If the operator isn't really equality, there could
2289 * be multiple matches --- but we don't look for them, both for speed
2290 * and because the math wouldn't add up...
2292 matchprodfreq = 0.0;
2294 for (i = 0; i < nvalues1; i++)
2298 for (j = 0; j < nvalues2; j++)
2302 if (DatumGetBool(FunctionCall2Coll(&eqproc,
2303 DEFAULT_COLLATION_OID,
2307 hasmatch1[i] = hasmatch2[j] = true;
2308 matchprodfreq += numbers1[i] * numbers2[j];
2314 CLAMP_PROBABILITY(matchprodfreq);
2315 /* Sum up frequencies of matched and unmatched MCVs */
2316 matchfreq1 = unmatchfreq1 = 0.0;
2317 for (i = 0; i < nvalues1; i++)
2320 matchfreq1 += numbers1[i];
2322 unmatchfreq1 += numbers1[i];
2324 CLAMP_PROBABILITY(matchfreq1);
2325 CLAMP_PROBABILITY(unmatchfreq1);
2326 matchfreq2 = unmatchfreq2 = 0.0;
2327 for (i = 0; i < nvalues2; i++)
2330 matchfreq2 += numbers2[i];
2332 unmatchfreq2 += numbers2[i];
2334 CLAMP_PROBABILITY(matchfreq2);
2335 CLAMP_PROBABILITY(unmatchfreq2);
2340 * Compute total frequency of non-null values that are not in the MCV
2343 otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2344 otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2345 CLAMP_PROBABILITY(otherfreq1);
2346 CLAMP_PROBABILITY(otherfreq2);
2349 * We can estimate the total selectivity from the point of view of
2350 * relation 1 as: the known selectivity for matched MCVs, plus
2351 * unmatched MCVs that are assumed to match against random members of
2352 * relation 2's non-MCV population, plus non-MCV values that are
2353 * assumed to match against random members of relation 2's unmatched
2354 * MCVs plus non-MCV values.
2356 totalsel1 = matchprodfreq;
2358 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
2360 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2362 /* Same estimate from the point of view of relation 2. */
2363 totalsel2 = matchprodfreq;
2365 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
2367 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2371 * Use the smaller of the two estimates. This can be justified in
2372 * essentially the same terms as given below for the no-stats case: to
2373 * a first approximation, we are estimating from the point of view of
2374 * the relation with smaller nd.
2376 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2381 * We do not have MCV lists for both sides. Estimate the join
2382 * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2383 * is plausible if we assume that the join operator is strict and the
2384 * non-null values are about equally distributed: a given non-null
2385 * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2386 * of rel2, so total join rows are at most
2387 * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2388 * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2389 * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2390 * with MIN() is an upper bound. Using the MIN() means we estimate
2391 * from the point of view of the relation with smaller nd (since the
2392 * larger nd is determining the MIN). It is reasonable to assume that
2393 * most tuples in this rel will have join partners, so the bound is
2394 * probably reasonably tight and should be taken as-is.
2396 * XXX Can we be smarter if we have an MCV list for just one side? It
2397 * seems that if we assume equal distribution for the other side, we
2398 * end up with the same answer anyway.
2400 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2401 double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2403 selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2411 free_attstatsslot(vardata1->atttype, values1, nvalues1,
2412 numbers1, nnumbers1);
2414 free_attstatsslot(vardata2->atttype, values2, nvalues2,
2415 numbers2, nnumbers2);
2421 * eqjoinsel_semi --- eqjoinsel for semi join
2423 * (Also used for anti join, which we are supposed to estimate the same way.)
2424 * Caller has ensured that vardata1 is the LHS variable.
2427 eqjoinsel_semi(Oid operator,
2428 VariableStatData *vardata1, VariableStatData *vardata2,
2429 RelOptInfo *inner_rel)
2436 Form_pg_statistic stats1 = NULL;
2437 bool have_mcvs1 = false;
2438 Datum *values1 = NULL;
2440 float4 *numbers1 = NULL;
2442 bool have_mcvs2 = false;
2443 Datum *values2 = NULL;
2445 float4 *numbers2 = NULL;
2448 nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2449 nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2452 * We clamp nd2 to be not more than what we estimate the inner relation's
2453 * size to be. This is intuitively somewhat reasonable since obviously
2454 * there can't be more than that many distinct values coming from the
2455 * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2456 * likewise) is that this is the only pathway by which restriction clauses
2457 * applied to the inner rel will affect the join result size estimate,
2458 * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2459 * only the outer rel's size. If we clamped nd1 we'd be double-counting
2460 * the selectivity of outer-rel restrictions.
2462 * We can apply this clamping both with respect to the base relation from
2463 * which the join variable comes (if there is just one), and to the
2464 * immediate inner input relation of the current join.
2467 nd2 = Min(nd2, vardata2->rel->rows);
2468 nd2 = Min(nd2, inner_rel->rows);
2470 if (HeapTupleIsValid(vardata1->statsTuple))
2472 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2473 have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2475 vardata1->atttypmod,
2479 &values1, &nvalues1,
2480 &numbers1, &nnumbers1);
2483 if (HeapTupleIsValid(vardata2->statsTuple))
2485 have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2487 vardata2->atttypmod,
2491 &values2, &nvalues2,
2492 &numbers2, &nnumbers2);
2495 if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
2498 * We have most-common-value lists for both relations. Run through
2499 * the lists to see which MCVs actually join to each other with the
2500 * given operator. This allows us to determine the exact join
2501 * selectivity for the portion of the relations represented by the MCV
2502 * lists. We still have to estimate for the remaining population, but
2503 * in a skewed distribution this gives us a big leg up in accuracy.
2508 double nullfrac1 = stats1->stanullfrac;
2517 * The clamping above could have resulted in nd2 being less than
2518 * nvalues2; in which case, we assume that precisely the nd2 most
2519 * common values in the relation will appear in the join input, and so
2520 * compare to only the first nd2 members of the MCV list. Of course
2521 * this is frequently wrong, but it's the best bet we can make.
2523 clamped_nvalues2 = Min(nvalues2, nd2);
2525 fmgr_info(get_opcode(operator), &eqproc);
2526 hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2527 hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2530 * Note we assume that each MCV will match at most one member of the
2531 * other MCV list. If the operator isn't really equality, there could
2532 * be multiple matches --- but we don't look for them, both for speed
2533 * and because the math wouldn't add up...
2536 for (i = 0; i < nvalues1; i++)
2540 for (j = 0; j < clamped_nvalues2; j++)
2544 if (DatumGetBool(FunctionCall2Coll(&eqproc,
2545 DEFAULT_COLLATION_OID,
2549 hasmatch1[i] = hasmatch2[j] = true;
2555 /* Sum up frequencies of matched MCVs */
2557 for (i = 0; i < nvalues1; i++)
2560 matchfreq1 += numbers1[i];
2562 CLAMP_PROBABILITY(matchfreq1);
2567 * Now we need to estimate the fraction of relation 1 that has at
2568 * least one join partner. We know for certain that the matched MCVs
2569 * do, so that gives us a lower bound, but we're really in the dark
2570 * about everything else. Our crude approach is: if nd1 <= nd2 then
2571 * assume all non-null rel1 rows have join partners, else assume for
2572 * the uncertain rows that a fraction nd2/nd1 have join partners. We
2573 * can discount the known-matched MCVs from the distinct-values counts
2574 * before doing the division.
2576 * Crude as the above is, it's completely useless if we don't have
2577 * reliable ndistinct values for both sides. Hence, if either nd1 or
2578 * nd2 is default, punt and assume half of the uncertain rows have
2581 if (!isdefault1 && !isdefault2)
2585 if (nd1 <= nd2 || nd2 < 0)
2586 uncertainfrac = 1.0;
2588 uncertainfrac = nd2 / nd1;
2591 uncertainfrac = 0.5;
2592 uncertain = 1.0 - matchfreq1 - nullfrac1;
2593 CLAMP_PROBABILITY(uncertain);
2594 selec = matchfreq1 + uncertainfrac * uncertain;
2599 * Without MCV lists for both sides, we can only use the heuristic
2602 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2604 if (!isdefault1 && !isdefault2)
2606 if (nd1 <= nd2 || nd2 < 0)
2607 selec = 1.0 - nullfrac1;
2609 selec = (nd2 / nd1) * (1.0 - nullfrac1);
2612 selec = 0.5 * (1.0 - nullfrac1);
2616 free_attstatsslot(vardata1->atttype, values1, nvalues1,
2617 numbers1, nnumbers1);
2619 free_attstatsslot(vardata2->atttype, values2, nvalues2,
2620 numbers2, nnumbers2);
2626 * neqjoinsel - Join selectivity of "!="
2629 neqjoinsel(PG_FUNCTION_ARGS)
2631 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2632 Oid operator = PG_GETARG_OID(1);
2633 List *args = (List *) PG_GETARG_POINTER(2);
2634 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2635 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2640 * We want 1 - eqjoinsel() where the equality operator is the one
2641 * associated with this != operator, that is, its negator.
2643 eqop = get_negator(operator);
2646 result = DatumGetFloat8(DirectFunctionCall5(eqjoinsel,
2647 PointerGetDatum(root),
2648 ObjectIdGetDatum(eqop),
2649 PointerGetDatum(args),
2650 Int16GetDatum(jointype),
2651 PointerGetDatum(sjinfo)));
2655 /* Use default selectivity (should we raise an error instead?) */
2656 result = DEFAULT_EQ_SEL;
2658 result = 1.0 - result;
2659 PG_RETURN_FLOAT8(result);
2663 * scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
2666 scalarltjoinsel(PG_FUNCTION_ARGS)
2668 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2672 * scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
2675 scalargtjoinsel(PG_FUNCTION_ARGS)
2677 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2681 * patternjoinsel - Generic code for pattern-match join selectivity.
2684 patternjoinsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
2686 /* For the moment we just punt. */
2687 return negate ? (1.0 - DEFAULT_MATCH_SEL) : DEFAULT_MATCH_SEL;
2691 * regexeqjoinsel - Join selectivity of regular-expression pattern match.
2694 regexeqjoinsel(PG_FUNCTION_ARGS)
2696 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, false));
2700 * icregexeqjoinsel - Join selectivity of case-insensitive regex match.
2703 icregexeqjoinsel(PG_FUNCTION_ARGS)
2705 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, false));
2709 * likejoinsel - Join selectivity of LIKE pattern match.
2712 likejoinsel(PG_FUNCTION_ARGS)
2714 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, false));
2718 * iclikejoinsel - Join selectivity of ILIKE pattern match.
2721 iclikejoinsel(PG_FUNCTION_ARGS)
2723 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, false));
2727 * regexnejoinsel - Join selectivity of regex non-match.
2730 regexnejoinsel(PG_FUNCTION_ARGS)
2732 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, true));
2736 * icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
2739 icregexnejoinsel(PG_FUNCTION_ARGS)
2741 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, true));
2745 * nlikejoinsel - Join selectivity of LIKE pattern non-match.
2748 nlikejoinsel(PG_FUNCTION_ARGS)
2750 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, true));
2754 * icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
2757 icnlikejoinsel(PG_FUNCTION_ARGS)
2759 PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, true));
2763 * mergejoinscansel - Scan selectivity of merge join.
2765 * A merge join will stop as soon as it exhausts either input stream.
2766 * Therefore, if we can estimate the ranges of both input variables,
2767 * we can estimate how much of the input will actually be read. This
2768 * can have a considerable impact on the cost when using indexscans.
2770 * Also, we can estimate how much of each input has to be read before the
2771 * first join pair is found, which will affect the join's startup time.
2773 * clause should be a clause already known to be mergejoinable. opfamily,
2774 * strategy, and nulls_first specify the sort ordering being used.
2777 * *leftstart is set to the fraction of the left-hand variable expected
2778 * to be scanned before the first join pair is found (0 to 1).
2779 * *leftend is set to the fraction of the left-hand variable expected
2780 * to be scanned before the join terminates (0 to 1).
2781 * *rightstart, *rightend similarly for the right-hand variable.
2784 mergejoinscansel(PlannerInfo *root, Node *clause,
2785 Oid opfamily, int strategy, bool nulls_first,
2786 Selectivity *leftstart, Selectivity *leftend,
2787 Selectivity *rightstart, Selectivity *rightend)
2791 VariableStatData leftvar,
2812 /* Set default results if we can't figure anything out. */
2813 /* XXX should default "start" fraction be a bit more than 0? */
2814 *leftstart = *rightstart = 0.0;
2815 *leftend = *rightend = 1.0;
2817 /* Deconstruct the merge clause */
2818 if (!is_opclause(clause))
2819 return; /* shouldn't happen */
2820 opno = ((OpExpr *) clause)->opno;
2821 left = get_leftop((Expr *) clause);
2822 right = get_rightop((Expr *) clause);
2824 return; /* shouldn't happen */
2826 /* Look for stats for the inputs */
2827 examine_variable(root, left, 0, &leftvar);
2828 examine_variable(root, right, 0, &rightvar);
2830 /* Extract the operator's declared left/right datatypes */
2831 get_op_opfamily_properties(opno, opfamily, false,
2835 Assert(op_strategy == BTEqualStrategyNumber);
2838 * Look up the various operators we need. If we don't find them all, it
2839 * probably means the opfamily is broken, but we just fail silently.
2841 * Note: we expect that pg_statistic histograms will be sorted by the '<'
2842 * operator, regardless of which sort direction we are considering.
2846 case BTLessStrategyNumber:
2848 if (op_lefttype == op_righttype)
2851 ltop = get_opfamily_member(opfamily,
2852 op_lefttype, op_righttype,
2853 BTLessStrategyNumber);
2854 leop = get_opfamily_member(opfamily,
2855 op_lefttype, op_righttype,
2856 BTLessEqualStrategyNumber);
2866 ltop = get_opfamily_member(opfamily,
2867 op_lefttype, op_righttype,
2868 BTLessStrategyNumber);
2869 leop = get_opfamily_member(opfamily,
2870 op_lefttype, op_righttype,
2871 BTLessEqualStrategyNumber);
2872 lsortop = get_opfamily_member(opfamily,
2873 op_lefttype, op_lefttype,
2874 BTLessStrategyNumber);
2875 rsortop = get_opfamily_member(opfamily,
2876 op_righttype, op_righttype,
2877 BTLessStrategyNumber);
2880 revltop = get_opfamily_member(opfamily,
2881 op_righttype, op_lefttype,
2882 BTLessStrategyNumber);
2883 revleop = get_opfamily_member(opfamily,
2884 op_righttype, op_lefttype,
2885 BTLessEqualStrategyNumber);
2888 case BTGreaterStrategyNumber:
2889 /* descending-order case */
2891 if (op_lefttype == op_righttype)
2894 ltop = get_opfamily_member(opfamily,
2895 op_lefttype, op_righttype,
2896 BTGreaterStrategyNumber);
2897 leop = get_opfamily_member(opfamily,
2898 op_lefttype, op_righttype,
2899 BTGreaterEqualStrategyNumber);
2902 lstatop = get_opfamily_member(opfamily,
2903 op_lefttype, op_lefttype,
2904 BTLessStrategyNumber);
2911 ltop = get_opfamily_member(opfamily,
2912 op_lefttype, op_righttype,
2913 BTGreaterStrategyNumber);
2914 leop = get_opfamily_member(opfamily,
2915 op_lefttype, op_righttype,
2916 BTGreaterEqualStrategyNumber);
2917 lsortop = get_opfamily_member(opfamily,
2918 op_lefttype, op_lefttype,
2919 BTGreaterStrategyNumber);
2920 rsortop = get_opfamily_member(opfamily,
2921 op_righttype, op_righttype,
2922 BTGreaterStrategyNumber);
2923 lstatop = get_opfamily_member(opfamily,
2924 op_lefttype, op_lefttype,
2925 BTLessStrategyNumber);
2926 rstatop = get_opfamily_member(opfamily,
2927 op_righttype, op_righttype,
2928 BTLessStrategyNumber);
2929 revltop = get_opfamily_member(opfamily,
2930 op_righttype, op_lefttype,
2931 BTGreaterStrategyNumber);
2932 revleop = get_opfamily_member(opfamily,
2933 op_righttype, op_lefttype,
2934 BTGreaterEqualStrategyNumber);
2938 goto fail; /* shouldn't get here */
2941 if (!OidIsValid(lsortop) ||
2942 !OidIsValid(rsortop) ||
2943 !OidIsValid(lstatop) ||
2944 !OidIsValid(rstatop) ||
2945 !OidIsValid(ltop) ||
2946 !OidIsValid(leop) ||
2947 !OidIsValid(revltop) ||
2948 !OidIsValid(revleop))
2949 goto fail; /* insufficient info in catalogs */
2951 /* Try to get ranges of both inputs */
2954 if (!get_variable_range(root, &leftvar, lstatop,
2955 &leftmin, &leftmax))
2956 goto fail; /* no range available from stats */
2957 if (!get_variable_range(root, &rightvar, rstatop,
2958 &rightmin, &rightmax))
2959 goto fail; /* no range available from stats */
2963 /* need to swap the max and min */
2964 if (!get_variable_range(root, &leftvar, lstatop,
2965 &leftmax, &leftmin))
2966 goto fail; /* no range available from stats */
2967 if (!get_variable_range(root, &rightvar, rstatop,
2968 &rightmax, &rightmin))
2969 goto fail; /* no range available from stats */
2973 * Now, the fraction of the left variable that will be scanned is the
2974 * fraction that's <= the right-side maximum value. But only believe
2975 * non-default estimates, else stick with our 1.0.
2977 selec = scalarineqsel(root, leop, isgt, &leftvar,
2978 rightmax, op_righttype);
2979 if (selec != DEFAULT_INEQ_SEL)
2982 /* And similarly for the right variable. */
2983 selec = scalarineqsel(root, revleop, isgt, &rightvar,
2984 leftmax, op_lefttype);
2985 if (selec != DEFAULT_INEQ_SEL)
2989 * Only one of the two "end" fractions can really be less than 1.0;
2990 * believe the smaller estimate and reset the other one to exactly 1.0. If
2991 * we get exactly equal estimates (as can easily happen with self-joins),
2994 if (*leftend > *rightend)
2996 else if (*leftend < *rightend)
2999 *leftend = *rightend = 1.0;
3002 * Also, the fraction of the left variable that will be scanned before the
3003 * first join pair is found is the fraction that's < the right-side
3004 * minimum value. But only believe non-default estimates, else stick with
3007 selec = scalarineqsel(root, ltop, isgt, &leftvar,
3008 rightmin, op_righttype);
3009 if (selec != DEFAULT_INEQ_SEL)
3012 /* And similarly for the right variable. */
3013 selec = scalarineqsel(root, revltop, isgt, &rightvar,
3014 leftmin, op_lefttype);
3015 if (selec != DEFAULT_INEQ_SEL)
3016 *rightstart = selec;
3019 * Only one of the two "start" fractions can really be more than zero;
3020 * believe the larger estimate and reset the other one to exactly 0.0. If
3021 * we get exactly equal estimates (as can easily happen with self-joins),
3024 if (*leftstart < *rightstart)
3026 else if (*leftstart > *rightstart)
3029 *leftstart = *rightstart = 0.0;
3032 * If the sort order is nulls-first, we're going to have to skip over any
3033 * nulls too. These would not have been counted by scalarineqsel, and we
3034 * can safely add in this fraction regardless of whether we believe
3035 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3039 Form_pg_statistic stats;
3041 if (HeapTupleIsValid(leftvar.statsTuple))
3043 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3044 *leftstart += stats->stanullfrac;
3045 CLAMP_PROBABILITY(*leftstart);
3046 *leftend += stats->stanullfrac;
3047 CLAMP_PROBABILITY(*leftend);
3049 if (HeapTupleIsValid(rightvar.statsTuple))
3051 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3052 *rightstart += stats->stanullfrac;
3053 CLAMP_PROBABILITY(*rightstart);
3054 *rightend += stats->stanullfrac;
3055 CLAMP_PROBABILITY(*rightend);
3059 /* Disbelieve start >= end, just in case that can happen */
3060 if (*leftstart >= *leftend)
3065 if (*rightstart >= *rightend)
3072 ReleaseVariableStats(leftvar);
3073 ReleaseVariableStats(rightvar);
3078 * Helper routine for estimate_num_groups: add an item to a list of
3079 * GroupVarInfos, but only if it's not known equal to any of the existing
3084 Node *var; /* might be an expression, not just a Var */
3085 RelOptInfo *rel; /* relation it belongs to */
3086 double ndistinct; /* # distinct values */
3090 add_unique_group_var(PlannerInfo *root, List *varinfos,
3091 Node *var, VariableStatData *vardata)
3093 GroupVarInfo *varinfo;
3098 ndistinct = get_variable_numdistinct(vardata, &isdefault);
3100 /* cannot use foreach here because of possible list_delete */
3101 lc = list_head(varinfos);
3104 varinfo = (GroupVarInfo *) lfirst(lc);
3106 /* must advance lc before list_delete possibly pfree's it */
3109 /* Drop exact duplicates */
3110 if (equal(var, varinfo->var))
3114 * Drop known-equal vars, but only if they belong to different
3115 * relations (see comments for estimate_num_groups)
3117 if (vardata->rel != varinfo->rel &&
3118 exprs_known_equal(root, var, varinfo->var))
3120 if (varinfo->ndistinct <= ndistinct)
3122 /* Keep older item, forget new one */
3127 /* Delete the older item */
3128 varinfos = list_delete_ptr(varinfos, varinfo);
3133 varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3136 varinfo->rel = vardata->rel;
3137 varinfo->ndistinct = ndistinct;
3138 varinfos = lappend(varinfos, varinfo);
3143 * estimate_num_groups - Estimate number of groups in a grouped query
3145 * Given a query having a GROUP BY clause, estimate how many groups there
3146 * will be --- ie, the number of distinct combinations of the GROUP BY
3149 * This routine is also used to estimate the number of rows emitted by
3150 * a DISTINCT filtering step; that is an isomorphic problem. (Note:
3151 * actually, we only use it for DISTINCT when there's no grouping or
3152 * aggregation ahead of the DISTINCT.)
3156 * groupExprs - list of expressions being grouped by
3157 * input_rows - number of rows estimated to arrive at the group/unique
3160 * Given the lack of any cross-correlation statistics in the system, it's
3161 * impossible to do anything really trustworthy with GROUP BY conditions
3162 * involving multiple Vars. We should however avoid assuming the worst
3163 * case (all possible cross-product terms actually appear as groups) since
3164 * very often the grouped-by Vars are highly correlated. Our current approach
3166 * 1. Expressions yielding boolean are assumed to contribute two groups,
3167 * independently of their content, and are ignored in the subsequent
3168 * steps. This is mainly because tests like "col IS NULL" break the
3169 * heuristic used in step 2 especially badly.
3170 * 2. Reduce the given expressions to a list of unique Vars used. For
3171 * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3172 * It is clearly correct not to count the same Var more than once.
3173 * It is also reasonable to treat f(x) the same as x: f() cannot
3174 * increase the number of distinct values (unless it is volatile,
3175 * which we consider unlikely for grouping), but it probably won't
3176 * reduce the number of distinct values much either.
3177 * As a special case, if a GROUP BY expression can be matched to an
3178 * expressional index for which we have statistics, then we treat the
3179 * whole expression as though it were just a Var.
3180 * 3. If the list contains Vars of different relations that are known equal
3181 * due to equivalence classes, then drop all but one of the Vars from each
3182 * known-equal set, keeping the one with smallest estimated # of values
3183 * (since the extra values of the others can't appear in joined rows).
3184 * Note the reason we only consider Vars of different relations is that
3185 * if we considered ones of the same rel, we'd be double-counting the
3186 * restriction selectivity of the equality in the next step.
3187 * 4. For Vars within a single source rel, we multiply together the numbers
3188 * of values, clamp to the number of rows in the rel (divided by 10 if
3189 * more than one Var), and then multiply by the selectivity of the
3190 * restriction clauses for that rel. When there's more than one Var,
3191 * the initial product is probably too high (it's the worst case) but
3192 * clamping to a fraction of the rel's rows seems to be a helpful
3193 * heuristic for not letting the estimate get out of hand. (The factor
3194 * of 10 is derived from pre-Postgres-7.4 practice.) Multiplying
3195 * by the restriction selectivity is effectively assuming that the
3196 * restriction clauses are independent of the grouping, which is a crummy
3197 * assumption, but it's hard to do better.
3198 * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3199 * rel, and multiply the results together.
3200 * Note that rels not containing grouped Vars are ignored completely, as are
3201 * join clauses. Such rels cannot increase the number of groups, and we
3202 * assume such clauses do not reduce the number either (somewhat bogus,
3203 * but we don't have the info to do better).
3206 estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows)
3208 List *varinfos = NIL;
3213 * We don't ever want to return an estimate of zero groups, as that tends
3214 * to lead to division-by-zero and other unpleasantness. The input_rows
3215 * estimate is usually already at least 1, but clamp it just in case it
3218 input_rows = clamp_row_est(input_rows);
3221 * If no grouping columns, there's exactly one group. (This can't happen
3222 * for normal cases with GROUP BY or DISTINCT, but it is possible for
3223 * corner cases with set operations.)
3225 if (groupExprs == NIL)
3229 * Count groups derived from boolean grouping expressions. For other
3230 * expressions, find the unique Vars used, treating an expression as a Var
3231 * if we can find stats for it. For each one, record the statistical
3232 * estimate of number of distinct values (total in its table, without
3233 * regard for filtering).
3237 foreach(l, groupExprs)
3239 Node *groupexpr = (Node *) lfirst(l);
3240 VariableStatData vardata;
3244 /* Short-circuit for expressions returning boolean */
3245 if (exprType(groupexpr) == BOOLOID)
3252 * If examine_variable is able to deduce anything about the GROUP BY
3253 * expression, treat it as a single variable even if it's really more
3256 examine_variable(root, groupexpr, 0, &vardata);
3257 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3259 varinfos = add_unique_group_var(root, varinfos,
3260 groupexpr, &vardata);
3261 ReleaseVariableStats(vardata);
3264 ReleaseVariableStats(vardata);
3267 * Else pull out the component Vars. Handle PlaceHolderVars by
3268 * recursing into their arguments (effectively assuming that the
3269 * PlaceHolderVar doesn't change the number of groups, which boils
3270 * down to ignoring the possible addition of nulls to the result set).
3272 varshere = pull_var_clause(groupexpr,
3273 PVC_RECURSE_AGGREGATES,
3274 PVC_RECURSE_PLACEHOLDERS);
3277 * If we find any variable-free GROUP BY item, then either it is a
3278 * constant (and we can ignore it) or it contains a volatile function;
3279 * in the latter case we punt and assume that each input row will
3280 * yield a distinct group.
3282 if (varshere == NIL)
3284 if (contain_volatile_functions(groupexpr))
3290 * Else add variables to varinfos list
3292 foreach(l2, varshere)
3294 Node *var = (Node *) lfirst(l2);
3296 examine_variable(root, var, 0, &vardata);
3297 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3298 ReleaseVariableStats(vardata);
3303 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3306 if (varinfos == NIL)
3308 /* Guard against out-of-range answers */
3309 if (numdistinct > input_rows)
3310 numdistinct = input_rows;
3315 * Group Vars by relation and estimate total numdistinct.
3317 * For each iteration of the outer loop, we process the frontmost Var in
3318 * varinfos, plus all other Vars in the same relation. We remove these
3319 * Vars from the newvarinfos list for the next iteration. This is the
3320 * easiest way to group Vars of same rel together.
3324 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3325 RelOptInfo *rel = varinfo1->rel;
3326 double reldistinct = varinfo1->ndistinct;
3327 double relmaxndistinct = reldistinct;
3328 int relvarcount = 1;
3329 List *newvarinfos = NIL;
3332 * Get the product of numdistinct estimates of the Vars for this rel.
3333 * Also, construct new varinfos list of remaining Vars.
3335 for_each_cell(l, lnext(list_head(varinfos)))
3337 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3339 if (varinfo2->rel == varinfo1->rel)
3341 reldistinct *= varinfo2->ndistinct;
3342 if (relmaxndistinct < varinfo2->ndistinct)
3343 relmaxndistinct = varinfo2->ndistinct;
3348 /* not time to process varinfo2 yet */
3349 newvarinfos = lcons(varinfo2, newvarinfos);
3354 * Sanity check --- don't divide by zero if empty relation.
3356 Assert(rel->reloptkind == RELOPT_BASEREL);
3357 if (rel->tuples > 0)
3360 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3361 * fudge factor is because the Vars are probably correlated but we
3362 * don't know by how much. We should never clamp to less than the
3363 * largest ndistinct value for any of the Vars, though, since
3364 * there will surely be at least that many groups.
3366 double clamp = rel->tuples;
3368 if (relvarcount > 1)
3371 if (clamp < relmaxndistinct)
3373 clamp = relmaxndistinct;
3374 /* for sanity in case some ndistinct is too large: */
3375 if (clamp > rel->tuples)
3376 clamp = rel->tuples;
3379 if (reldistinct > clamp)
3380 reldistinct = clamp;
3383 * Multiply by restriction selectivity.
3385 reldistinct *= rel->rows / rel->tuples;
3388 * Update estimate of total distinct groups.
3390 numdistinct *= reldistinct;
3393 varinfos = newvarinfos;
3394 } while (varinfos != NIL);
3396 numdistinct = ceil(numdistinct);
3398 /* Guard against out-of-range answers */
3399 if (numdistinct > input_rows)
3400 numdistinct = input_rows;
3401 if (numdistinct < 1.0)
3408 * Estimate hash bucketsize fraction (ie, number of entries in a bucket
3409 * divided by total tuples in relation) if the specified expression is used
3412 * XXX This is really pretty bogus since we're effectively assuming that the
3413 * distribution of hash keys will be the same after applying restriction
3414 * clauses as it was in the underlying relation. However, we are not nearly
3415 * smart enough to figure out how the restrict clauses might change the
3416 * distribution, so this will have to do for now.
3418 * We are passed the number of buckets the executor will use for the given
3419 * input relation. If the data were perfectly distributed, with the same
3420 * number of tuples going into each available bucket, then the bucketsize
3421 * fraction would be 1/nbuckets. But this happy state of affairs will occur
3422 * only if (a) there are at least nbuckets distinct data values, and (b)
3423 * we have a not-too-skewed data distribution. Otherwise the buckets will
3424 * be nonuniformly occupied. If the other relation in the join has a key
3425 * distribution similar to this one's, then the most-loaded buckets are
3426 * exactly those that will be probed most often. Therefore, the "average"
3427 * bucket size for costing purposes should really be taken as something close
3428 * to the "worst case" bucket size. We try to estimate this by adjusting the
3429 * fraction if there are too few distinct data values, and then scaling up
3430 * by the ratio of the most common value's frequency to the average frequency.
3432 * If no statistics are available, use a default estimate of 0.1. This will
3433 * discourage use of a hash rather strongly if the inner relation is large,
3434 * which is what we want. We do not want to hash unless we know that the
3435 * inner rel is well-dispersed (or the alternatives seem much worse).
3438 estimate_hash_bucketsize(PlannerInfo *root, Node *hashkey, double nbuckets)
3440 VariableStatData vardata;
3450 examine_variable(root, hashkey, 0, &vardata);
3452 /* Get number of distinct values */
3453 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3455 /* If ndistinct isn't real, punt and return 0.1, per comments above */
3458 ReleaseVariableStats(vardata);
3459 return (Selectivity) 0.1;
3462 /* Get fraction that are null */
3463 if (HeapTupleIsValid(vardata.statsTuple))
3465 Form_pg_statistic stats;
3467 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3468 stanullfrac = stats->stanullfrac;
3473 /* Compute avg freq of all distinct data values in raw relation */
3474 avgfreq = (1.0 - stanullfrac) / ndistinct;
3477 * Adjust ndistinct to account for restriction clauses. Observe we are
3478 * assuming that the data distribution is affected uniformly by the
3479 * restriction clauses!
3481 * XXX Possibly better way, but much more expensive: multiply by
3482 * selectivity of rel's restriction clauses that mention the target Var.
3485 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3488 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3489 * number of buckets is less than the expected number of distinct values;
3490 * otherwise it is 1/ndistinct.
3492 if (ndistinct > nbuckets)
3493 estfract = 1.0 / nbuckets;
3495 estfract = 1.0 / ndistinct;
3498 * Look up the frequency of the most common value, if available.
3502 if (HeapTupleIsValid(vardata.statsTuple))
3504 if (get_attstatsslot(vardata.statsTuple,
3505 vardata.atttype, vardata.atttypmod,
3506 STATISTIC_KIND_MCV, InvalidOid,
3509 &numbers, &nnumbers))
3512 * The first MCV stat is for the most common value.
3515 mcvfreq = numbers[0];
3516 free_attstatsslot(vardata.atttype, NULL, 0,
3522 * Adjust estimated bucketsize upward to account for skewed distribution.
3524 if (avgfreq > 0.0 && mcvfreq > avgfreq)
3525 estfract *= mcvfreq / avgfreq;
3528 * Clamp bucketsize to sane range (the above adjustment could easily
3529 * produce an out-of-range result). We set the lower bound a little above
3530 * zero, since zero isn't a very sane result.
3532 if (estfract < 1.0e-6)
3534 else if (estfract > 1.0)
3537 ReleaseVariableStats(vardata);
3539 return (Selectivity) estfract;
3543 /*-------------------------------------------------------------------------
3547 *-------------------------------------------------------------------------
3552 * Convert non-NULL values of the indicated types to the comparison
3553 * scale needed by scalarineqsel().
3554 * Returns "true" if successful.
3556 * XXX this routine is a hack: ideally we should look up the conversion
3557 * subroutines in pg_type.
3559 * All numeric datatypes are simply converted to their equivalent
3560 * "double" values. (NUMERIC values that are outside the range of "double"
3561 * are clamped to +/- HUGE_VAL.)
3563 * String datatypes are converted by convert_string_to_scalar(),
3564 * which is explained below. The reason why this routine deals with
3565 * three values at a time, not just one, is that we need it for strings.
3567 * The bytea datatype is just enough different from strings that it has
3568 * to be treated separately.
3570 * The several datatypes representing absolute times are all converted
3571 * to Timestamp, which is actually a double, and then we just use that
3572 * double value. Note this will give correct results even for the "special"
3573 * values of Timestamp, since those are chosen to compare correctly;
3574 * see timestamp_cmp.
3576 * The several datatypes representing relative times (intervals) are all
3577 * converted to measurements expressed in seconds.
3580 convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
3581 Datum lobound, Datum hibound, Oid boundstypid,
3582 double *scaledlobound, double *scaledhibound)
3585 * Both the valuetypid and the boundstypid should exactly match the
3586 * declared input type(s) of the operator we are invoked for, so we just
3587 * error out if either is not recognized.
3589 * XXX The histogram we are interpolating between points of could belong
3590 * to a column that's only binary-compatible with the declared type. In
3591 * essence we are assuming that the semantics of binary-compatible types
3592 * are enough alike that we can use a histogram generated with one type's
3593 * operators to estimate selectivity for the other's. This is outright
3594 * wrong in some cases --- in particular signed versus unsigned
3595 * interpretation could trip us up. But it's useful enough in the
3596 * majority of cases that we do it anyway. Should think about more
3597 * rigorous ways to do it.
3602 * Built-in numeric types
3613 case REGPROCEDUREOID:
3615 case REGOPERATOROID:
3619 case REGDICTIONARYOID:
3620 *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
3621 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
3622 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
3626 * Built-in string types
3634 char *valstr = convert_string_datum(value, valuetypid);
3635 char *lostr = convert_string_datum(lobound, boundstypid);
3636 char *histr = convert_string_datum(hibound, boundstypid);
3638 convert_string_to_scalar(valstr, scaledvalue,
3639 lostr, scaledlobound,
3640 histr, scaledhibound);
3648 * Built-in bytea type
3652 convert_bytea_to_scalar(value, scaledvalue,
3653 lobound, scaledlobound,
3654 hibound, scaledhibound);
3659 * Built-in time types
3662 case TIMESTAMPTZOID:
3670 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
3671 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
3672 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
3676 * Built-in network types
3681 *scaledvalue = convert_network_to_scalar(value, valuetypid);
3682 *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
3683 *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
3686 /* Don't know how to convert */
3687 *scaledvalue = *scaledlobound = *scaledhibound = 0;
3692 * Do convert_to_scalar()'s work for any numeric data type.
3695 convert_numeric_to_scalar(Datum value, Oid typid)
3700 return (double) DatumGetBool(value);
3702 return (double) DatumGetInt16(value);
3704 return (double) DatumGetInt32(value);
3706 return (double) DatumGetInt64(value);
3708 return (double) DatumGetFloat4(value);
3710 return (double) DatumGetFloat8(value);
3712 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3714 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
3718 case REGPROCEDUREOID:
3720 case REGOPERATOROID:
3724 case REGDICTIONARYOID:
3725 /* we can treat OIDs as integers... */
3726 return (double) DatumGetObjectId(value);
3730 * Can't get here unless someone tries to use scalarltsel/scalargtsel on
3731 * an operator with one numeric and one non-numeric operand.
3733 elog(ERROR, "unsupported type: %u", typid);
3738 * Do convert_to_scalar()'s work for any character-string data type.
3740 * String datatypes are converted to a scale that ranges from 0 to 1,
3741 * where we visualize the bytes of the string as fractional digits.
3743 * We do not want the base to be 256, however, since that tends to
3744 * generate inflated selectivity estimates; few databases will have
3745 * occurrences of all 256 possible byte values at each position.
3746 * Instead, use the smallest and largest byte values seen in the bounds
3747 * as the estimated range for each byte, after some fudging to deal with
3748 * the fact that we probably aren't going to see the full range that way.
3750 * An additional refinement is that we discard any common prefix of the
3751 * three strings before computing the scaled values. This allows us to
3752 * "zoom in" when we encounter a narrow data range. An example is a phone
3753 * number database where all the values begin with the same area code.
3754 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
3755 * so this is more likely to happen than you might think.)
3758 convert_string_to_scalar(char *value,
3759 double *scaledvalue,
3761 double *scaledlobound,
3763 double *scaledhibound)
3769 rangelo = rangehi = (unsigned char) hibound[0];
3770 for (sptr = lobound; *sptr; sptr++)
3772 if (rangelo > (unsigned char) *sptr)
3773 rangelo = (unsigned char) *sptr;
3774 if (rangehi < (unsigned char) *sptr)
3775 rangehi = (unsigned char) *sptr;
3777 for (sptr = hibound; *sptr; sptr++)
3779 if (rangelo > (unsigned char) *sptr)
3780 rangelo = (unsigned char) *sptr;
3781 if (rangehi < (unsigned char) *sptr)
3782 rangehi = (unsigned char) *sptr;
3784 /* If range includes any upper-case ASCII chars, make it include all */
3785 if (rangelo <= 'Z' && rangehi >= 'A')
3792 /* Ditto lower-case */
3793 if (rangelo <= 'z' && rangehi >= 'a')
3801 if (rangelo <= '9' && rangehi >= '0')
3810 * If range includes less than 10 chars, assume we have not got enough
3811 * data, and make it include regular ASCII set.
3813 if (rangehi - rangelo < 9)
3820 * Now strip any common prefix of the three strings.
3824 if (*lobound != *hibound || *lobound != *value)
3826 lobound++, hibound++, value++;
3830 * Now we can do the conversions.
3832 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
3833 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
3834 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
3838 convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
3840 int slen = strlen(value);
3846 return 0.0; /* empty string has scalar value 0 */
3849 * Since base is at least 10, need not consider more than about 20 chars
3854 /* Convert initial characters to fraction */
3855 base = rangehi - rangelo + 1;
3860 int ch = (unsigned char) *value++;
3864 else if (ch > rangehi)
3866 num += ((double) (ch - rangelo)) / denom;
3874 * Convert a string-type Datum into a palloc'd, null-terminated string.
3876 * When using a non-C locale, we must pass the string through strxfrm()
3877 * before continuing, so as to generate correct locale-specific results.
3880 convert_string_datum(Datum value, Oid typid)
3887 val = (char *) palloc(2);
3888 val[0] = DatumGetChar(value);
3894 val = TextDatumGetCString(value);
3898 NameData *nm = (NameData *) DatumGetPointer(value);
3900 val = pstrdup(NameStr(*nm));
3906 * Can't get here unless someone tries to use scalarltsel on an
3907 * operator with one string and one non-string operand.
3909 elog(ERROR, "unsupported type: %u", typid);
3913 if (!lc_collate_is_c(DEFAULT_COLLATION_OID))
3917 size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
3920 * Note: originally we guessed at a suitable output buffer size, and
3921 * only needed to call strxfrm twice if our guess was too small.
3922 * However, it seems that some versions of Solaris have buggy strxfrm
3923 * that can write past the specified buffer length in that scenario.
3924 * So, do it the dumb way for portability.
3926 * Yet other systems (e.g., glibc) sometimes return a smaller value
3927 * from the second call than the first; thus the Assert must be <= not
3928 * == as you'd expect. Can't any of these people program their way
3929 * out of a paper bag?
3931 * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
3932 * bogus data or set an error. This is not really a problem unless it
3933 * crashes since it will only give an estimation error and nothing
3936 #if _MSC_VER == 1400 /* VS.Net 2005 */
3940 * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?
3941 * FeedbackID=99694 */
3945 xfrmlen = strxfrm(x, val, 0);
3948 xfrmlen = strxfrm(NULL, val, 0);
3953 * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
3954 * of trying to allocate this much memory (and fail), just return the
3955 * original string unmodified as if we were in the C locale.
3957 if (xfrmlen == INT_MAX)
3960 xfrmstr = (char *) palloc(xfrmlen + 1);
3961 xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
3962 Assert(xfrmlen2 <= xfrmlen);
3971 * Do convert_to_scalar()'s work for any bytea data type.
3973 * Very similar to convert_string_to_scalar except we can't assume
3974 * null-termination and therefore pass explicit lengths around.
3976 * Also, assumptions about likely "normal" ranges of characters have been
3977 * removed - a data range of 0..255 is always used, for now. (Perhaps
3978 * someday we will add information about actual byte data range to
3982 convert_bytea_to_scalar(Datum value,
3983 double *scaledvalue,
3985 double *scaledlobound,
3987 double *scaledhibound)
3991 valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
3992 loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
3993 hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
3996 unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
3997 *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
3998 *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
4001 * Assume bytea data is uniformly distributed across all byte values.
4007 * Now strip any common prefix of the three strings.
4009 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4010 for (i = 0; i < minlen; i++)
4012 if (*lostr != *histr || *lostr != *valstr)
4014 lostr++, histr++, valstr++;
4015 loboundlen--, hiboundlen--, valuelen--;
4019 * Now we can do the conversions.
4021 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4022 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4023 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4027 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
4028 int rangelo, int rangehi)
4035 return 0.0; /* empty string has scalar value 0 */
4038 * Since base is 256, need not consider more than about 10 chars (even
4039 * this many seems like overkill)
4044 /* Convert initial characters to fraction */
4045 base = rangehi - rangelo + 1;
4048 while (valuelen-- > 0)
4054 else if (ch > rangehi)
4056 num += ((double) (ch - rangelo)) / denom;
4064 * Do convert_to_scalar()'s work for any timevalue data type.
4067 convert_timevalue_to_scalar(Datum value, Oid typid)
4072 return DatumGetTimestamp(value);
4073 case TIMESTAMPTZOID:
4074 return DatumGetTimestampTz(value);
4076 return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
4079 return date2timestamp_no_overflow(DatumGetDateADT(value));
4082 Interval *interval = DatumGetIntervalP(value);
4085 * Convert the month part of Interval to days using assumed
4086 * average month length of 365.25/12.0 days. Not too
4087 * accurate, but plenty good enough for our purposes.
4089 #ifdef HAVE_INT64_TIMESTAMP
4090 return interval->time + interval->day * (double) USECS_PER_DAY +
4091 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4093 return interval->time + interval->day * SECS_PER_DAY +
4094 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * (double) SECS_PER_DAY);
4098 #ifdef HAVE_INT64_TIMESTAMP
4099 return (DatumGetRelativeTime(value) * 1000000.0);
4101 return DatumGetRelativeTime(value);
4105 TimeInterval tinterval = DatumGetTimeInterval(value);
4107 #ifdef HAVE_INT64_TIMESTAMP
4108 if (tinterval->status != 0)
4109 return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4111 if (tinterval->status != 0)
4112 return tinterval->data[1] - tinterval->data[0];
4114 return 0; /* for lack of a better idea */
4117 return DatumGetTimeADT(value);
4120 TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4122 /* use GMT-equivalent time */
4123 #ifdef HAVE_INT64_TIMESTAMP
4124 return (double) (timetz->time + (timetz->zone * 1000000.0));
4126 return (double) (timetz->time + timetz->zone);
4132 * Can't get here unless someone tries to use scalarltsel/scalargtsel on
4133 * an operator with one timevalue and one non-timevalue operand.
4135 elog(ERROR, "unsupported type: %u", typid);
4141 * get_restriction_variable
4142 * Examine the args of a restriction clause to see if it's of the
4143 * form (variable op pseudoconstant) or (pseudoconstant op variable),
4144 * where "variable" could be either a Var or an expression in vars of a
4145 * single relation. If so, extract information about the variable,
4146 * and also indicate which side it was on and the other argument.
4149 * root: the planner info
4150 * args: clause argument list
4151 * varRelid: see specs for restriction selectivity functions
4153 * Outputs: (these are valid only if TRUE is returned)
4154 * *vardata: gets information about variable (see examine_variable)
4155 * *other: gets other clause argument, aggressively reduced to a constant
4156 * *varonleft: set TRUE if variable is on the left, FALSE if on the right
4158 * Returns TRUE if a variable is identified, otherwise FALSE.
4160 * Note: if there are Vars on both sides of the clause, we must fail, because
4161 * callers are expecting that the other side will act like a pseudoconstant.
4164 get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
4165 VariableStatData *vardata, Node **other,
4170 VariableStatData rdata;
4172 /* Fail if not a binary opclause (probably shouldn't happen) */
4173 if (list_length(args) != 2)
4176 left = (Node *) linitial(args);
4177 right = (Node *) lsecond(args);
4180 * Examine both sides. Note that when varRelid is nonzero, Vars of other
4181 * relations will be treated as pseudoconstants.
4183 examine_variable(root, left, varRelid, vardata);
4184 examine_variable(root, right, varRelid, &rdata);
4187 * If one side is a variable and the other not, we win.
4189 if (vardata->rel && rdata.rel == NULL)
4192 *other = estimate_expression_value(root, rdata.var);
4193 /* Assume we need no ReleaseVariableStats(rdata) here */
4197 if (vardata->rel == NULL && rdata.rel)
4200 *other = estimate_expression_value(root, vardata->var);
4201 /* Assume we need no ReleaseVariableStats(*vardata) here */
4206 /* Ooops, clause has wrong structure (probably var op var) */
4207 ReleaseVariableStats(*vardata);
4208 ReleaseVariableStats(rdata);
4214 * get_join_variables
4215 * Apply examine_variable() to each side of a join clause.
4216 * Also, attempt to identify whether the join clause has the same
4217 * or reversed sense compared to the SpecialJoinInfo.
4219 * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4220 * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4221 * where we can't tell for sure, we default to assuming it's normal.
4224 get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
4225 VariableStatData *vardata1, VariableStatData *vardata2,
4226 bool *join_is_reversed)
4231 if (list_length(args) != 2)
4232 elog(ERROR, "join operator should take two arguments");
4234 left = (Node *) linitial(args);
4235 right = (Node *) lsecond(args);
4237 examine_variable(root, left, 0, vardata1);
4238 examine_variable(root, right, 0, vardata2);
4240 if (vardata1->rel &&
4241 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4242 *join_is_reversed = true; /* var1 is on RHS */
4243 else if (vardata2->rel &&
4244 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4245 *join_is_reversed = true; /* var2 is on LHS */
4247 *join_is_reversed = false;
4252 * Try to look up statistical data about an expression.
4253 * Fill in a VariableStatData struct to describe the expression.
4256 * root: the planner info
4257 * node: the expression tree to examine
4258 * varRelid: see specs for restriction selectivity functions
4260 * Outputs: *vardata is filled as follows:
4261 * var: the input expression (with any binary relabeling stripped, if
4262 * it is or contains a variable; but otherwise the type is preserved)
4263 * rel: RelOptInfo for relation containing variable; NULL if expression
4264 * contains no Vars (NOTE this could point to a RelOptInfo of a
4265 * subquery, not one in the current query).
4266 * statsTuple: the pg_statistic entry for the variable, if one exists;
4268 * freefunc: pointer to a function to release statsTuple with.
4269 * vartype: exposed type of the expression; this should always match
4270 * the declared input type of the operator we are estimating for.
4271 * atttype, atttypmod: type data to pass to get_attstatsslot(). This is
4272 * commonly the same as the exposed type of the variable argument,
4273 * but can be different in binary-compatible-type cases.
4274 * isunique: TRUE if we were able to match the var to a unique index or a
4275 * single-column DISTINCT clause, implying its values are unique for
4276 * this query. (Caution: this should be trusted for statistical
4277 * purposes only, since we do not check indimmediate nor verify that
4278 * the exact same definition of equality applies.)
4280 * Caller is responsible for doing ReleaseVariableStats() before exiting.
4283 examine_variable(PlannerInfo *root, Node *node, int varRelid,
4284 VariableStatData *vardata)
4290 /* Make sure we don't return dangling pointers in vardata */
4291 MemSet(vardata, 0, sizeof(VariableStatData));
4293 /* Save the exposed type of the expression */
4294 vardata->vartype = exprType(node);
4296 /* Look inside any binary-compatible relabeling */
4298 if (IsA(node, RelabelType))
4299 basenode = (Node *) ((RelabelType *) node)->arg;
4303 /* Fast path for a simple Var */
4305 if (IsA(basenode, Var) &&
4306 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4308 Var *var = (Var *) basenode;
4310 /* Set up result fields other than the stats tuple */
4311 vardata->var = basenode; /* return Var without relabeling */
4312 vardata->rel = find_base_rel(root, var->varno);
4313 vardata->atttype = var->vartype;
4314 vardata->atttypmod = var->vartypmod;
4315 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4317 /* Try to locate some stats */
4318 examine_simple_variable(root, var, vardata);
4324 * Okay, it's a more complicated expression. Determine variable
4325 * membership. Note that when varRelid isn't zero, only vars of that
4326 * relation are considered "real" vars.
4328 varnos = pull_varnos(basenode);
4332 switch (bms_membership(varnos))
4335 /* No Vars at all ... must be pseudo-constant clause */
4338 if (varRelid == 0 || bms_is_member(varRelid, varnos))
4340 onerel = find_base_rel(root,
4341 (varRelid ? varRelid : bms_singleton_member(varnos)));
4342 vardata->rel = onerel;
4343 node = basenode; /* strip any relabeling */
4345 /* else treat it as a constant */
4350 /* treat it as a variable of a join relation */
4351 vardata->rel = find_join_rel(root, varnos);
4352 node = basenode; /* strip any relabeling */
4354 else if (bms_is_member(varRelid, varnos))
4356 /* ignore the vars belonging to other relations */
4357 vardata->rel = find_base_rel(root, varRelid);
4358 node = basenode; /* strip any relabeling */
4359 /* note: no point in expressional-index search here */
4361 /* else treat it as a constant */
4367 vardata->var = node;
4368 vardata->atttype = exprType(node);
4369 vardata->atttypmod = exprTypmod(node);
4374 * We have an expression in vars of a single relation. Try to match
4375 * it to expressional index columns, in hopes of finding some
4378 * XXX it's conceivable that there are multiple matches with different
4379 * index opfamilies; if so, we need to pick one that matches the
4380 * operator we are estimating for. FIXME later.
4384 foreach(ilist, onerel->indexlist)
4386 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4387 ListCell *indexpr_item;
4390 indexpr_item = list_head(index->indexprs);
4391 if (indexpr_item == NULL)
4392 continue; /* no expressions here... */
4394 for (pos = 0; pos < index->ncolumns; pos++)
4396 if (index->indexkeys[pos] == 0)
4400 if (indexpr_item == NULL)
4401 elog(ERROR, "too few entries in indexprs list");
4402 indexkey = (Node *) lfirst(indexpr_item);
4403 if (indexkey && IsA(indexkey, RelabelType))
4404 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4405 if (equal(node, indexkey))
4408 * Found a match ... is it a unique index? Tests here
4409 * should match has_unique_index().
4411 if (index->unique &&
4412 index->ncolumns == 1 &&
4413 (index->indpred == NIL || index->predOK))
4414 vardata->isunique = true;
4417 * Has it got stats? We only consider stats for
4418 * non-partial indexes, since partial indexes probably
4419 * don't reflect whole-relation statistics; the above
4420 * check for uniqueness is the only info we take from
4423 * An index stats hook, however, must make its own
4424 * decisions about what to do with partial indexes.
4426 if (get_index_stats_hook &&
4427 (*get_index_stats_hook) (root, index->indexoid,
4431 * The hook took control of acquiring a stats
4432 * tuple. If it did supply a tuple, it'd better
4433 * have supplied a freefunc.
4435 if (HeapTupleIsValid(vardata->statsTuple) &&
4437 elog(ERROR, "no function provided to release variable stats with");
4439 else if (index->indpred == NIL)
4441 vardata->statsTuple =
4442 SearchSysCache3(STATRELATTINH,
4443 ObjectIdGetDatum(index->indexoid),
4444 Int16GetDatum(pos + 1),
4445 BoolGetDatum(false));
4446 vardata->freefunc = ReleaseSysCache;
4448 if (vardata->statsTuple)
4451 indexpr_item = lnext(indexpr_item);
4454 if (vardata->statsTuple)
4461 * examine_simple_variable
4462 * Handle a simple Var for examine_variable
4464 * This is split out as a subroutine so that we can recurse to deal with
4465 * Vars referencing subqueries.
4467 * We already filled in all the fields of *vardata except for the stats tuple.
4470 examine_simple_variable(PlannerInfo *root, Var *var,
4471 VariableStatData *vardata)
4473 RangeTblEntry *rte = root->simple_rte_array[var->varno];
4475 Assert(IsA(rte, RangeTblEntry));
4477 if (get_relation_stats_hook &&
4478 (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4481 * The hook took control of acquiring a stats tuple. If it did supply
4482 * a tuple, it'd better have supplied a freefunc.
4484 if (HeapTupleIsValid(vardata->statsTuple) &&
4486 elog(ERROR, "no function provided to release variable stats with");
4488 else if (rte->rtekind == RTE_RELATION)
4491 * Plain table or parent of an inheritance appendrel, so look up the
4492 * column in pg_statistic
4494 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
4495 ObjectIdGetDatum(rte->relid),
4496 Int16GetDatum(var->varattno),
4497 BoolGetDatum(rte->inh));
4498 vardata->freefunc = ReleaseSysCache;
4500 else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4503 * Plain subquery (not one that was converted to an appendrel).
4505 Query *subquery = rte->subquery;
4510 * Punt if subquery uses set operations or GROUP BY, as these will
4511 * mash underlying columns' stats beyond recognition. (Set ops are
4512 * particularly nasty; if we forged ahead, we would return stats
4513 * relevant to only the leftmost subselect...) DISTINCT is also
4514 * problematic, but we check that later because there is a possibility
4515 * of learning something even with it.
4517 if (subquery->setOperations ||
4518 subquery->groupClause)
4522 * OK, fetch RelOptInfo for subquery. Note that we don't change the
4523 * rel returned in vardata, since caller expects it to be a rel of the
4524 * caller's query level. Because we might already be recursing, we
4525 * can't use that rel pointer either, but have to look up the Var's
4528 rel = find_base_rel(root, var->varno);
4530 /* If the subquery hasn't been planned yet, we have to punt */
4531 if (rel->subroot == NULL)
4533 Assert(IsA(rel->subroot, PlannerInfo));
4536 * Switch our attention to the subquery as mangled by the planner. It
4537 * was okay to look at the pre-planning version for the tests above,
4538 * but now we need a Var that will refer to the subroot's live
4539 * RelOptInfos. For instance, if any subquery pullup happened during
4540 * planning, Vars in the targetlist might have gotten replaced, and we
4541 * need to see the replacement expressions.
4543 subquery = rel->subroot->parse;
4544 Assert(IsA(subquery, Query));
4546 /* Get the subquery output expression referenced by the upper Var */
4547 ste = get_tle_by_resno(subquery->targetList, var->varattno);
4548 if (ste == NULL || ste->resjunk)
4549 elog(ERROR, "subquery %s does not have attribute %d",
4550 rte->eref->aliasname, var->varattno);
4551 var = (Var *) ste->expr;
4554 * If subquery uses DISTINCT, we can't make use of any stats for the
4555 * variable ... but, if it's the only DISTINCT column, we are entitled
4556 * to consider it unique. We do the test this way so that it works
4557 * for cases involving DISTINCT ON.
4559 if (subquery->distinctClause)
4561 if (list_length(subquery->distinctClause) == 1 &&
4562 targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4563 vardata->isunique = true;
4564 /* cannot go further */
4569 * If the sub-query originated from a view with the security_barrier
4570 * attribute, we must not look at the variable's statistics, though it
4571 * seems all right to notice the existence of a DISTINCT clause. So
4574 * This is probably a harsher restriction than necessary; it's
4575 * certainly OK for the selectivity estimator (which is a C function,
4576 * and therefore omnipotent anyway) to look at the statistics. But
4577 * many selectivity estimators will happily *invoke the operator
4578 * function* to try to work out a good estimate - and that's not OK.
4579 * So for now, don't dig down for stats.
4581 if (rte->security_barrier)
4584 /* Can only handle a simple Var of subquery's query level */
4585 if (var && IsA(var, Var) &&
4586 var->varlevelsup == 0)
4589 * OK, recurse into the subquery. Note that the original setting
4590 * of vardata->isunique (which will surely be false) is left
4591 * unchanged in this situation. That's what we want, since even
4592 * if the underlying column is unique, the subquery may have
4593 * joined to other tables in a way that creates duplicates.
4595 examine_simple_variable(rel->subroot, var, vardata);
4601 * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
4602 * won't see RTE_JOIN here because join alias Vars have already been
4603 * flattened.) There's not much we can do with function outputs, but
4604 * maybe someday try to be smarter about VALUES and/or CTEs.
4610 * get_variable_numdistinct
4611 * Estimate the number of distinct values of a variable.
4613 * vardata: results of examine_variable
4614 * *isdefault: set to TRUE if the result is a default rather than based on
4615 * anything meaningful.
4617 * NB: be careful to produce an integral result, since callers may compare
4618 * the result to exact integer counts.
4621 get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
4629 * Determine the stadistinct value to use. There are cases where we can
4630 * get an estimate even without a pg_statistic entry, or can get a better
4631 * value than is in pg_statistic.
4633 if (HeapTupleIsValid(vardata->statsTuple))
4635 /* Use the pg_statistic entry */
4636 Form_pg_statistic stats;
4638 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4639 stadistinct = stats->stadistinct;
4641 else if (vardata->vartype == BOOLOID)
4644 * Special-case boolean columns: presumably, two distinct values.
4646 * Are there any other datatypes we should wire in special estimates
4654 * We don't keep statistics for system columns, but in some cases we
4655 * can infer distinctness anyway.
4657 if (vardata->var && IsA(vardata->var, Var))
4659 switch (((Var *) vardata->var)->varattno)
4661 case ObjectIdAttributeNumber:
4662 case SelfItemPointerAttributeNumber:
4663 stadistinct = -1.0; /* unique */
4665 case TableOidAttributeNumber:
4666 stadistinct = 1.0; /* only 1 value */
4669 stadistinct = 0.0; /* means "unknown" */
4674 stadistinct = 0.0; /* means "unknown" */
4677 * XXX consider using estimate_num_groups on expressions?
4682 * If there is a unique index or DISTINCT clause for the variable, assume
4683 * it is unique no matter what pg_statistic says; the statistics could be
4684 * out of date, or we might have found a partial unique index that proves
4685 * the var is unique for this query.
4687 if (vardata->isunique)
4691 * If we had an absolute estimate, use that.
4693 if (stadistinct > 0.0)
4697 * Otherwise we need to get the relation size; punt if not available.
4699 if (vardata->rel == NULL)
4702 return DEFAULT_NUM_DISTINCT;
4704 ntuples = vardata->rel->tuples;
4708 return DEFAULT_NUM_DISTINCT;
4712 * If we had a relative estimate, use that.
4714 if (stadistinct < 0.0)
4715 return floor((-stadistinct * ntuples) + 0.5);
4718 * With no data, estimate ndistinct = ntuples if the table is small, else
4719 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
4720 * that the behavior isn't discontinuous.
4722 if (ntuples < DEFAULT_NUM_DISTINCT)
4726 return DEFAULT_NUM_DISTINCT;
4730 * get_variable_range
4731 * Estimate the minimum and maximum value of the specified variable.
4732 * If successful, store values in *min and *max, and return TRUE.
4733 * If no data available, return FALSE.
4735 * sortop is the "<" comparison operator to use. This should generally
4736 * be "<" not ">", as only the former is likely to be found in pg_statistic.
4739 get_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop,
4740 Datum *min, Datum *max)
4744 bool have_data = false;
4752 * XXX It's very tempting to try to use the actual column min and max, if
4753 * we can get them relatively-cheaply with an index probe. However, since
4754 * this function is called many times during join planning, that could
4755 * have unpleasant effects on planning speed. Need more investigation
4756 * before enabling this.
4759 if (get_actual_variable_range(root, vardata, sortop, min, max))
4763 if (!HeapTupleIsValid(vardata->statsTuple))
4765 /* no stats available, so default result */
4769 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
4772 * If there is a histogram, grab the first and last values.
4774 * If there is a histogram that is sorted with some other operator than
4775 * the one we want, fail --- this suggests that there is data we can't
4778 if (get_attstatsslot(vardata->statsTuple,
4779 vardata->atttype, vardata->atttypmod,
4780 STATISTIC_KIND_HISTOGRAM, sortop,
4787 tmin = datumCopy(values[0], typByVal, typLen);
4788 tmax = datumCopy(values[nvalues - 1], typByVal, typLen);
4791 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4793 else if (get_attstatsslot(vardata->statsTuple,
4794 vardata->atttype, vardata->atttypmod,
4795 STATISTIC_KIND_HISTOGRAM, InvalidOid,
4800 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4805 * If we have most-common-values info, look for extreme MCVs. This is
4806 * needed even if we also have a histogram, since the histogram excludes
4807 * the MCVs. However, usually the MCVs will not be the extreme values, so
4808 * avoid unnecessary data copying.
4810 if (get_attstatsslot(vardata->statsTuple,
4811 vardata->atttype, vardata->atttypmod,
4812 STATISTIC_KIND_MCV, InvalidOid,
4817 bool tmin_is_mcv = false;
4818 bool tmax_is_mcv = false;
4821 fmgr_info(get_opcode(sortop), &opproc);
4823 for (i = 0; i < nvalues; i++)
4827 tmin = tmax = values[i];
4828 tmin_is_mcv = tmax_is_mcv = have_data = true;
4831 if (DatumGetBool(FunctionCall2Coll(&opproc,
4832 DEFAULT_COLLATION_OID,
4838 if (DatumGetBool(FunctionCall2Coll(&opproc,
4839 DEFAULT_COLLATION_OID,
4847 tmin = datumCopy(tmin, typByVal, typLen);
4849 tmax = datumCopy(tmax, typByVal, typLen);
4850 free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4860 * get_actual_variable_range
4861 * Attempt to identify the current *actual* minimum and/or maximum
4862 * of the specified variable, by looking for a suitable btree index
4863 * and fetching its low and/or high values.
4864 * If successful, store values in *min and *max, and return TRUE.
4865 * (Either pointer can be NULL if that endpoint isn't needed.)
4866 * If no data available, return FALSE.
4868 * sortop is the "<" comparison operator to use.
4871 get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
4873 Datum *min, Datum *max)
4875 bool have_data = false;
4876 RelOptInfo *rel = vardata->rel;
4880 /* No hope if no relation or it doesn't have indexes */
4881 if (rel == NULL || rel->indexlist == NIL)
4883 /* If it has indexes it must be a plain relation */
4884 rte = root->simple_rte_array[rel->relid];
4885 Assert(rte->rtekind == RTE_RELATION);
4887 /* Search through the indexes to see if any match our problem */
4888 foreach(lc, rel->indexlist)
4890 IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
4891 ScanDirection indexscandir;
4893 /* Ignore non-btree indexes */
4894 if (index->relam != BTREE_AM_OID)
4898 * Ignore partial indexes --- we only want stats that cover the entire
4901 if (index->indpred != NIL)
4905 * The index list might include hypothetical indexes inserted by a
4906 * get_relation_info hook --- don't try to access them.
4908 if (index->hypothetical)
4912 * The first index column must match the desired variable and sort
4913 * operator --- but we can use a descending-order index.
4915 if (!match_index_to_operand(vardata->var, 0, index))
4917 switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
4919 case BTLessStrategyNumber:
4920 if (index->reverse_sort[0])
4921 indexscandir = BackwardScanDirection;
4923 indexscandir = ForwardScanDirection;
4925 case BTGreaterStrategyNumber:
4926 if (index->reverse_sort[0])
4927 indexscandir = ForwardScanDirection;
4929 indexscandir = BackwardScanDirection;
4932 /* index doesn't match the sortop */
4937 * Found a suitable index to extract data from. We'll need an EState
4938 * and a bunch of other infrastructure.
4942 ExprContext *econtext;
4943 MemoryContext tmpcontext;
4944 MemoryContext oldcontext;
4947 IndexInfo *indexInfo;
4948 TupleTableSlot *slot;
4951 ScanKeyData scankeys[1];
4952 IndexScanDesc index_scan;
4954 Datum values[INDEX_MAX_KEYS];
4955 bool isnull[INDEX_MAX_KEYS];
4957 estate = CreateExecutorState();
4958 econtext = GetPerTupleExprContext(estate);
4959 /* Make sure any cruft is generated in the econtext's memory */
4960 tmpcontext = econtext->ecxt_per_tuple_memory;
4961 oldcontext = MemoryContextSwitchTo(tmpcontext);
4964 * Open the table and index so we can read from them. We should
4965 * already have at least AccessShareLock on the table, but not
4966 * necessarily on the index.
4968 heapRel = heap_open(rte->relid, NoLock);
4969 indexRel = index_open(index->indexoid, AccessShareLock);
4971 /* extract index key information from the index's pg_index info */
4972 indexInfo = BuildIndexInfo(indexRel);
4974 /* some other stuff */
4975 slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
4976 econtext->ecxt_scantuple = slot;
4977 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
4979 /* set up an IS NOT NULL scan key so that we ignore nulls */
4980 ScanKeyEntryInitialize(&scankeys[0],
4981 SK_ISNULL | SK_SEARCHNOTNULL,
4982 1, /* index col to scan */
4983 InvalidStrategy, /* no strategy */
4984 InvalidOid, /* no strategy subtype */
4985 InvalidOid, /* no collation */
4986 InvalidOid, /* no reg proc for this */
4987 (Datum) 0); /* constant */
4991 /* If min is requested ... */
4994 index_scan = index_beginscan(heapRel, indexRel, SnapshotNow,
4996 index_rescan(index_scan, scankeys, 1, NULL, 0);
4998 /* Fetch first tuple in sortop's direction */
4999 if ((tup = index_getnext(index_scan,
5000 indexscandir)) != NULL)
5002 /* Extract the index column values from the heap tuple */
5003 ExecStoreTuple(tup, slot, InvalidBuffer, false);
5004 FormIndexDatum(indexInfo, slot, estate,
5007 /* Shouldn't have got a null, but be careful */
5009 elog(ERROR, "found unexpected null value in index \"%s\"",
5010 RelationGetRelationName(indexRel));
5012 /* Copy the index column value out to caller's context */
5013 MemoryContextSwitchTo(oldcontext);
5014 *min = datumCopy(values[0], typByVal, typLen);
5015 MemoryContextSwitchTo(tmpcontext);
5020 index_endscan(index_scan);
5023 /* If max is requested, and we didn't find the index is empty */
5024 if (max && have_data)
5026 index_scan = index_beginscan(heapRel, indexRel, SnapshotNow,
5028 index_rescan(index_scan, scankeys, 1, NULL, 0);
5030 /* Fetch first tuple in reverse direction */
5031 if ((tup = index_getnext(index_scan,
5032 -indexscandir)) != NULL)
5034 /* Extract the index column values from the heap tuple */
5035 ExecStoreTuple(tup, slot, InvalidBuffer, false);
5036 FormIndexDatum(indexInfo, slot, estate,
5039 /* Shouldn't have got a null, but be careful */
5041 elog(ERROR, "found unexpected null value in index \"%s\"",
5042 RelationGetRelationName(indexRel));
5044 /* Copy the index column value out to caller's context */
5045 MemoryContextSwitchTo(oldcontext);
5046 *max = datumCopy(values[0], typByVal, typLen);
5047 MemoryContextSwitchTo(tmpcontext);
5052 index_endscan(index_scan);
5055 /* Clean everything up */
5056 ExecDropSingleTupleTableSlot(slot);
5058 index_close(indexRel, AccessShareLock);
5059 heap_close(heapRel, NoLock);
5061 MemoryContextSwitchTo(oldcontext);
5062 FreeExecutorState(estate);
5064 /* And we're done */
5073 * find_join_input_rel
5074 * Look up the input relation for a join.
5076 * We assume that the input relation's RelOptInfo must have been constructed
5080 find_join_input_rel(PlannerInfo *root, Relids relids)
5082 RelOptInfo *rel = NULL;
5084 switch (bms_membership(relids))
5087 /* should not happen */
5090 rel = find_base_rel(root, bms_singleton_member(relids));
5093 rel = find_join_rel(root, relids);
5098 elog(ERROR, "could not find RelOptInfo for given relids");
5104 /*-------------------------------------------------------------------------
5106 * Pattern analysis functions
5108 * These routines support analysis of LIKE and regular-expression patterns
5109 * by the planner/optimizer. It's important that they agree with the
5110 * regular-expression code in backend/regex/ and the LIKE code in
5111 * backend/utils/adt/like.c. Also, the computation of the fixed prefix
5112 * must be conservative: if we report a string longer than the true fixed
5113 * prefix, the query may produce actually wrong answers, rather than just
5114 * getting a bad selectivity estimate!
5116 * Note that the prefix-analysis functions are called from
5117 * backend/optimizer/path/indxpath.c as well as from routines in this file.
5119 *-------------------------------------------------------------------------
5123 * Check whether char is a letter (and, hence, subject to case-folding)
5125 * In multibyte character sets, we can't use isalpha, and it does not seem
5126 * worth trying to convert to wchar_t to use iswalpha. Instead, just assume
5127 * any multibyte char is potentially case-varying.
5130 pattern_char_isalpha(char c, bool is_multibyte,
5131 pg_locale_t locale, bool locale_is_c)
5134 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
5135 else if (is_multibyte && IS_HIGHBIT_SET(c))
5137 #ifdef HAVE_LOCALE_T
5139 return isalpha_l((unsigned char) c, locale);
5142 return isalpha((unsigned char) c);
5146 * Extract the fixed prefix, if any, for a pattern.
5148 * *prefix is set to a palloc'd prefix string (in the form of a Const node),
5149 * or to NULL if no fixed prefix exists for the pattern.
5150 * If rest_selec is not NULL, *rest_selec is set to an estimate of the
5151 * selectivity of the remainder of the pattern (without any fixed prefix).
5152 * The prefix Const has the same type (TEXT or BYTEA) as the input pattern.
5154 * The return value distinguishes no fixed prefix, a partial prefix,
5155 * or an exact-match-only pattern.
5158 static Pattern_Prefix_Status
5159 like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
5160 Const **prefix_const, Selectivity *rest_selec)
5165 Oid typeid = patt_const->consttype;
5168 bool is_multibyte = (pg_database_encoding_max_length() > 1);
5169 pg_locale_t locale = 0;
5170 bool locale_is_c = false;
5172 /* the right-hand const is type text or bytea */
5173 Assert(typeid == BYTEAOID || typeid == TEXTOID);
5175 if (case_insensitive)
5177 if (typeid == BYTEAOID)
5179 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5180 errmsg("case insensitive matching not supported on type bytea")));
5182 /* If case-insensitive, we need locale info */
5183 if (lc_ctype_is_c(collation))
5185 else if (collation != DEFAULT_COLLATION_OID)
5187 if (!OidIsValid(collation))
5190 * This typically means that the parser could not resolve a
5191 * conflict of implicit collations, so report it that way.
5194 (errcode(ERRCODE_INDETERMINATE_COLLATION),
5195 errmsg("could not determine which collation to use for ILIKE"),
5196 errhint("Use the COLLATE clause to set the collation explicitly.")));
5198 locale = pg_newlocale_from_collation(collation);
5202 if (typeid != BYTEAOID)
5204 patt = TextDatumGetCString(patt_const->constvalue);
5205 pattlen = strlen(patt);
5209 bytea *bstr = DatumGetByteaP(patt_const->constvalue);
5211 pattlen = VARSIZE(bstr) - VARHDRSZ;
5212 patt = (char *) palloc(pattlen);
5213 memcpy(patt, VARDATA(bstr), pattlen);
5214 if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
5218 match = palloc(pattlen + 1);
5220 for (pos = 0; pos < pattlen; pos++)
5222 /* % and _ are wildcard characters in LIKE */
5223 if (patt[pos] == '%' ||
5227 /* Backslash escapes the next character */
5228 if (patt[pos] == '\\')
5235 /* Stop if case-varying character (it's sort of a wildcard) */
5236 if (case_insensitive &&
5237 pattern_char_isalpha(patt[pos], is_multibyte, locale, locale_is_c))
5240 match[match_pos++] = patt[pos];
5243 match[match_pos] = '\0';
5245 if (typeid != BYTEAOID)
5246 *prefix_const = string_to_const(match, typeid);
5248 *prefix_const = string_to_bytea_const(match, match_pos);
5250 if (rest_selec != NULL)
5251 *rest_selec = like_selectivity(&patt[pos], pattlen - pos,
5257 /* in LIKE, an empty pattern is an exact match! */
5259 return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
5262 return Pattern_Prefix_Partial;
5264 return Pattern_Prefix_None;
5267 static Pattern_Prefix_Status
5268 regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
5269 Const **prefix_const, Selectivity *rest_selec)
5271 Oid typeid = patt_const->consttype;
5276 * Should be unnecessary, there are no bytea regex operators defined. As
5277 * such, it should be noted that the rest of this function has *not* been
5278 * made safe for binary (possibly NULL containing) strings.
5280 if (typeid == BYTEAOID)
5282 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5283 errmsg("regular-expression matching not supported on type bytea")));
5285 /* Use the regexp machinery to extract the prefix, if any */
5286 prefix = regexp_fixed_prefix(DatumGetTextPP(patt_const->constvalue),
5287 case_insensitive, collation,
5292 *prefix_const = NULL;
5294 if (rest_selec != NULL)
5296 char *patt = TextDatumGetCString(patt_const->constvalue);
5298 *rest_selec = regex_selectivity(patt, strlen(patt),
5304 return Pattern_Prefix_None;
5307 *prefix_const = string_to_const(prefix, typeid);
5309 if (rest_selec != NULL)
5313 /* Exact match, so there's no additional selectivity */
5318 char *patt = TextDatumGetCString(patt_const->constvalue);
5320 *rest_selec = regex_selectivity(patt, strlen(patt),
5330 return Pattern_Prefix_Exact; /* pattern specifies exact match */
5332 return Pattern_Prefix_Partial;
5335 Pattern_Prefix_Status
5336 pattern_fixed_prefix(Const *patt, Pattern_Type ptype, Oid collation,
5337 Const **prefix, Selectivity *rest_selec)
5339 Pattern_Prefix_Status result;
5343 case Pattern_Type_Like:
5344 result = like_fixed_prefix(patt, false, collation,
5345 prefix, rest_selec);
5347 case Pattern_Type_Like_IC:
5348 result = like_fixed_prefix(patt, true, collation,
5349 prefix, rest_selec);
5351 case Pattern_Type_Regex:
5352 result = regex_fixed_prefix(patt, false, collation,
5353 prefix, rest_selec);
5355 case Pattern_Type_Regex_IC:
5356 result = regex_fixed_prefix(patt, true, collation,
5357 prefix, rest_selec);
5360 elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5361 result = Pattern_Prefix_None; /* keep compiler quiet */
5368 * Estimate the selectivity of a fixed prefix for a pattern match.
5370 * A fixed prefix "foo" is estimated as the selectivity of the expression
5371 * "variable >= 'foo' AND variable < 'fop'" (see also indxpath.c).
5373 * The selectivity estimate is with respect to the portion of the column
5374 * population represented by the histogram --- the caller must fold this
5375 * together with info about MCVs and NULLs.
5377 * We use the >= and < operators from the specified btree opfamily to do the
5378 * estimation. The given variable and Const must be of the associated
5381 * XXX Note: we make use of the upper bound to estimate operator selectivity
5382 * even if the locale is such that we cannot rely on the upper-bound string.
5383 * The selectivity only needs to be approximately right anyway, so it seems
5384 * more useful to use the upper-bound code than not.
5387 prefix_selectivity(PlannerInfo *root, VariableStatData *vardata,
5388 Oid vartype, Oid opfamily, Const *prefixcon)
5390 Selectivity prefixsel;
5393 Const *greaterstrcon;
5396 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5397 BTGreaterEqualStrategyNumber);
5398 if (cmpopr == InvalidOid)
5399 elog(ERROR, "no >= operator for opfamily %u", opfamily);
5400 fmgr_info(get_opcode(cmpopr), &opproc);
5402 prefixsel = ineq_histogram_selectivity(root, vardata, &opproc, true,
5403 prefixcon->constvalue,
5404 prefixcon->consttype);
5406 if (prefixsel < 0.0)
5408 /* No histogram is present ... return a suitable default estimate */
5409 return DEFAULT_MATCH_SEL;
5413 * If we can create a string larger than the prefix, say
5417 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5418 BTLessStrategyNumber);
5419 if (cmpopr == InvalidOid)
5420 elog(ERROR, "no < operator for opfamily %u", opfamily);
5421 fmgr_info(get_opcode(cmpopr), &opproc);
5422 greaterstrcon = make_greater_string(prefixcon, &opproc,
5423 DEFAULT_COLLATION_OID);
5428 topsel = ineq_histogram_selectivity(root, vardata, &opproc, false,
5429 greaterstrcon->constvalue,
5430 greaterstrcon->consttype);
5432 /* ineq_histogram_selectivity worked before, it shouldn't fail now */
5433 Assert(topsel >= 0.0);
5436 * Merge the two selectivities in the same way as for a range query
5437 * (see clauselist_selectivity()). Note that we don't need to worry
5438 * about double-exclusion of nulls, since ineq_histogram_selectivity
5439 * doesn't count those anyway.
5441 prefixsel = topsel + prefixsel - 1.0;
5445 * If the prefix is long then the two bounding values might be too close
5446 * together for the histogram to distinguish them usefully, resulting in a
5447 * zero estimate (plus or minus roundoff error). To avoid returning a
5448 * ridiculously small estimate, compute the estimated selectivity for
5449 * "variable = 'foo'", and clamp to that. (Obviously, the resultant
5450 * estimate should be at least that.)
5452 * We apply this even if we couldn't make a greater string. That case
5453 * suggests that the prefix is near the maximum possible, and thus
5454 * probably off the end of the histogram, and thus we probably got a very
5455 * small estimate from the >= condition; so we still need to clamp.
5457 cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5458 BTEqualStrategyNumber);
5459 if (cmpopr == InvalidOid)
5460 elog(ERROR, "no = operator for opfamily %u", opfamily);
5461 eq_sel = var_eq_const(vardata, cmpopr, prefixcon->constvalue,
5464 prefixsel = Max(prefixsel, eq_sel);
5471 * Estimate the selectivity of a pattern of the specified type.
5472 * Note that any fixed prefix of the pattern will have been removed already,
5473 * so actually we may be looking at just a fragment of the pattern.
5475 * For now, we use a very simplistic approach: fixed characters reduce the
5476 * selectivity a good deal, character ranges reduce it a little,
5477 * wildcards (such as % for LIKE or .* for regex) increase it.
5480 #define FIXED_CHAR_SEL 0.20 /* about 1/5 */
5481 #define CHAR_RANGE_SEL 0.25
5482 #define ANY_CHAR_SEL 0.9 /* not 1, since it won't match end-of-string */
5483 #define FULL_WILDCARD_SEL 5.0
5484 #define PARTIAL_WILDCARD_SEL 2.0
5487 like_selectivity(const char *patt, int pattlen, bool case_insensitive)
5489 Selectivity sel = 1.0;
5492 /* Skip any leading wildcard; it's already factored into initial sel */
5493 for (pos = 0; pos < pattlen; pos++)
5495 if (patt[pos] != '%' && patt[pos] != '_')
5499 for (; pos < pattlen; pos++)
5501 /* % and _ are wildcard characters in LIKE */
5502 if (patt[pos] == '%')
5503 sel *= FULL_WILDCARD_SEL;
5504 else if (patt[pos] == '_')
5505 sel *= ANY_CHAR_SEL;
5506 else if (patt[pos] == '\\')
5508 /* Backslash quotes the next character */
5512 sel *= FIXED_CHAR_SEL;
5515 sel *= FIXED_CHAR_SEL;
5517 /* Could get sel > 1 if multiple wildcards */
5524 regex_selectivity_sub(const char *patt, int pattlen, bool case_insensitive)
5526 Selectivity sel = 1.0;
5527 int paren_depth = 0;
5528 int paren_pos = 0; /* dummy init to keep compiler quiet */
5531 for (pos = 0; pos < pattlen; pos++)
5533 if (patt[pos] == '(')
5535 if (paren_depth == 0)
5536 paren_pos = pos; /* remember start of parenthesized item */
5539 else if (patt[pos] == ')' && paren_depth > 0)
5542 if (paren_depth == 0)
5543 sel *= regex_selectivity_sub(patt + (paren_pos + 1),
5544 pos - (paren_pos + 1),
5547 else if (patt[pos] == '|' && paren_depth == 0)
5550 * If unquoted | is present at paren level 0 in pattern, we have
5551 * multiple alternatives; sum their probabilities.
5553 sel += regex_selectivity_sub(patt + (pos + 1),
5554 pattlen - (pos + 1),
5556 break; /* rest of pattern is now processed */
5558 else if (patt[pos] == '[')
5560 bool negclass = false;
5562 if (patt[++pos] == '^')
5567 if (patt[pos] == ']') /* ']' at start of class is not
5570 while (pos < pattlen && patt[pos] != ']')
5572 if (paren_depth == 0)
5573 sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
5575 else if (patt[pos] == '.')
5577 if (paren_depth == 0)
5578 sel *= ANY_CHAR_SEL;
5580 else if (patt[pos] == '*' ||
5584 /* Ought to be smarter about quantifiers... */
5585 if (paren_depth == 0)
5586 sel *= PARTIAL_WILDCARD_SEL;
5588 else if (patt[pos] == '{')
5590 while (pos < pattlen && patt[pos] != '}')
5592 if (paren_depth == 0)
5593 sel *= PARTIAL_WILDCARD_SEL;
5595 else if (patt[pos] == '\\')
5597 /* backslash quotes the next character */
5601 if (paren_depth == 0)
5602 sel *= FIXED_CHAR_SEL;
5606 if (paren_depth == 0)
5607 sel *= FIXED_CHAR_SEL;
5610 /* Could get sel > 1 if multiple wildcards */
5617 regex_selectivity(const char *patt, int pattlen, bool case_insensitive,
5618 int fixed_prefix_len)
5622 /* If patt doesn't end with $, consider it to have a trailing wildcard */
5623 if (pattlen > 0 && patt[pattlen - 1] == '$' &&
5624 (pattlen == 1 || patt[pattlen - 2] != '\\'))
5626 /* has trailing $ */
5627 sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
5632 sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
5633 sel *= FULL_WILDCARD_SEL;
5636 /* If there's a fixed prefix, discount its selectivity */
5637 if (fixed_prefix_len > 0)
5638 sel /= pow(FIXED_CHAR_SEL, fixed_prefix_len);
5640 /* Make sure result stays in range */
5641 CLAMP_PROBABILITY(sel);
5647 * For bytea, the increment function need only increment the current byte
5648 * (there are no multibyte characters to worry about).
5651 byte_increment(unsigned char *ptr, int len)
5660 * Try to generate a string greater than the given string or any
5661 * string it is a prefix of. If successful, return a palloc'd string
5662 * in the form of a Const node; else return NULL.
5664 * The caller must provide the appropriate "less than" comparison function
5665 * for testing the strings, along with the collation to use.
5667 * The key requirement here is that given a prefix string, say "foo",
5668 * we must be able to generate another string "fop" that is greater than
5669 * all strings "foobar" starting with "foo". We can test that we have
5670 * generated a string greater than the prefix string, but in non-C collations
5671 * that is not a bulletproof guarantee that an extension of the string might
5672 * not sort after it; an example is that "foo " is less than "foo!", but it
5673 * is not clear that a "dictionary" sort ordering will consider "foo!" less
5674 * than "foo bar". CAUTION: Therefore, this function should be used only for
5675 * estimation purposes when working in a non-C collation.
5677 * To try to catch most cases where an extended string might otherwise sort
5678 * before the result value, we determine which of the strings "Z", "z", "y",
5679 * and "9" is seen as largest by the collation, and append that to the given
5680 * prefix before trying to find a string that compares as larger.
5682 * To search for a greater string, we repeatedly "increment" the rightmost
5683 * character, using an encoding-specific character incrementer function.
5684 * When it's no longer possible to increment the last character, we truncate
5685 * off that character and start incrementing the next-to-rightmost.
5686 * For example, if "z" were the last character in the sort order, then we
5687 * could produce "foo" as a string greater than "fonz".
5689 * This could be rather slow in the worst case, but in most cases we
5690 * won't have to try more than one or two strings before succeeding.
5692 * Note that it's important for the character incrementer not to be too anal
5693 * about producing every possible character code, since in some cases the only
5694 * way to get a larger string is to increment a previous character position.
5695 * So we don't want to spend too much time trying every possible character
5696 * code at the last position. A good rule of thumb is to be sure that we
5697 * don't try more than 256*K values for a K-byte character (and definitely
5698 * not 256^K, which is what an exhaustive search would approach).
5701 make_greater_string(const Const *str_const, FmgrInfo *ltproc, Oid collation)
5703 Oid datatype = str_const->consttype;
5707 text *cmptxt = NULL;
5708 mbcharacter_incrementer charinc;
5711 * Get a modifiable copy of the prefix string in C-string format, and set
5712 * up the string we will compare to as a Datum. In C locale this can just
5713 * be the given prefix string, otherwise we need to add a suffix. Types
5714 * NAME and BYTEA sort bytewise so they don't need a suffix either.
5716 if (datatype == NAMEOID)
5718 workstr = DatumGetCString(DirectFunctionCall1(nameout,
5719 str_const->constvalue));
5720 len = strlen(workstr);
5721 cmpstr = str_const->constvalue;
5723 else if (datatype == BYTEAOID)
5725 bytea *bstr = DatumGetByteaP(str_const->constvalue);
5727 len = VARSIZE(bstr) - VARHDRSZ;
5728 workstr = (char *) palloc(len);
5729 memcpy(workstr, VARDATA(bstr), len);
5730 if ((Pointer) bstr != DatumGetPointer(str_const->constvalue))
5732 cmpstr = str_const->constvalue;
5736 workstr = TextDatumGetCString(str_const->constvalue);
5737 len = strlen(workstr);
5738 if (lc_collate_is_c(collation) || len == 0)
5739 cmpstr = str_const->constvalue;
5742 /* If first time through, determine the suffix to use */
5743 static char suffixchar = 0;
5744 static Oid suffixcollation = 0;
5746 if (!suffixchar || suffixcollation != collation)
5751 if (varstr_cmp(best, 1, "z", 1, collation) < 0)
5753 if (varstr_cmp(best, 1, "y", 1, collation) < 0)
5755 if (varstr_cmp(best, 1, "9", 1, collation) < 0)
5758 suffixcollation = collation;
5761 /* And build the string to compare to */
5762 cmptxt = (text *) palloc(VARHDRSZ + len + 1);
5763 SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
5764 memcpy(VARDATA(cmptxt), workstr, len);
5765 *(VARDATA(cmptxt) + len) = suffixchar;
5766 cmpstr = PointerGetDatum(cmptxt);
5770 /* Select appropriate character-incrementer function */
5771 if (datatype == BYTEAOID)
5772 charinc = byte_increment;
5774 charinc = pg_database_encoding_character_incrementer();
5776 /* And search ... */
5780 unsigned char *lastchar;
5782 /* Identify the last character --- for bytea, just the last byte */
5783 if (datatype == BYTEAOID)
5786 charlen = len - pg_mbcliplen(workstr, len, len - 1);
5787 lastchar = (unsigned char *) (workstr + len - charlen);
5790 * Try to generate a larger string by incrementing the last character
5791 * (for BYTEA, we treat each byte as a character).
5793 * Note: the incrementer function is expected to return true if it's
5794 * generated a valid-per-the-encoding new character, otherwise false.
5795 * The contents of the character on false return are unspecified.
5797 while (charinc(lastchar, charlen))
5799 Const *workstr_const;
5801 if (datatype == BYTEAOID)
5802 workstr_const = string_to_bytea_const(workstr, len);
5804 workstr_const = string_to_const(workstr, datatype);
5806 if (DatumGetBool(FunctionCall2Coll(ltproc,
5809 workstr_const->constvalue)))
5811 /* Successfully made a string larger than cmpstr */
5815 return workstr_const;
5818 /* No good, release unusable value and try again */
5819 pfree(DatumGetPointer(workstr_const->constvalue));
5820 pfree(workstr_const);
5824 * No luck here, so truncate off the last character and try to
5825 * increment the next one.
5828 workstr[len] = '\0';
5840 * Generate a Datum of the appropriate type from a C string.
5841 * Note that all of the supported types are pass-by-ref, so the
5842 * returned value should be pfree'd if no longer needed.
5845 string_to_datum(const char *str, Oid datatype)
5847 Assert(str != NULL);
5850 * We cheat a little by assuming that CStringGetTextDatum() will do for
5851 * bpchar and varchar constants too...
5853 if (datatype == NAMEOID)
5854 return DirectFunctionCall1(namein, CStringGetDatum(str));
5855 else if (datatype == BYTEAOID)
5856 return DirectFunctionCall1(byteain, CStringGetDatum(str));
5858 return CStringGetTextDatum(str);
5862 * Generate a Const node of the appropriate type from a C string.
5865 string_to_const(const char *str, Oid datatype)
5867 Datum conval = string_to_datum(str, datatype);
5872 * We only need to support a few datatypes here, so hard-wire properties
5873 * instead of incurring the expense of catalog lookups.
5880 collation = DEFAULT_COLLATION_OID;
5885 collation = InvalidOid;
5886 constlen = NAMEDATALEN;
5890 collation = InvalidOid;
5895 elog(ERROR, "unexpected datatype in string_to_const: %u",
5900 return makeConst(datatype, -1, collation, constlen,
5901 conval, false, false);
5905 * Generate a Const node of bytea type from a binary C string and a length.
5908 string_to_bytea_const(const char *str, size_t str_len)
5910 bytea *bstr = palloc(VARHDRSZ + str_len);
5913 memcpy(VARDATA(bstr), str, str_len);
5914 SET_VARSIZE(bstr, VARHDRSZ + str_len);
5915 conval = PointerGetDatum(bstr);
5917 return makeConst(BYTEAOID, -1, InvalidOid, -1, conval, false, false);
5920 /*-------------------------------------------------------------------------
5922 * Index cost estimation functions
5924 *-------------------------------------------------------------------------
5928 * genericcostestimate is a general-purpose estimator that can be used for
5929 * most index types. In some cases we use genericcostestimate as the base
5930 * code and then incorporate additional index-type-specific knowledge in
5931 * the type-specific calling function. To avoid code duplication, we make
5932 * genericcostestimate return a number of intermediate values as well as
5933 * its preliminary estimates of the output cost values. The GenericCosts
5934 * struct includes all these values.
5936 * Callers should initialize all fields of GenericCosts to zero. In addition,
5937 * they can set numIndexTuples to some positive value if they have a better
5938 * than default way of estimating the number of leaf index tuples visited.
5942 /* These are the values the cost estimator must return to the planner */
5943 Cost indexStartupCost; /* index-related startup cost */
5944 Cost indexTotalCost; /* total index-related scan cost */
5945 Selectivity indexSelectivity; /* selectivity of index */
5946 double indexCorrelation; /* order correlation of index */
5948 /* Intermediate values we obtain along the way */
5949 double numIndexPages; /* number of leaf pages visited */
5950 double numIndexTuples; /* number of leaf tuples visited */
5951 double spc_random_page_cost; /* relevant random_page_cost value */
5952 double num_sa_scans; /* # indexscans from ScalarArrayOps */
5956 genericcostestimate(PlannerInfo *root,
5959 GenericCosts *costs)
5961 IndexOptInfo *index = path->indexinfo;
5962 List *indexQuals = path->indexquals;
5963 List *indexOrderBys = path->indexorderbys;
5964 Cost indexStartupCost;
5965 Cost indexTotalCost;
5966 Selectivity indexSelectivity;
5967 double indexCorrelation;
5968 double numIndexPages;
5969 double numIndexTuples;
5970 double spc_random_page_cost;
5971 double num_sa_scans;
5972 double num_outer_scans;
5974 QualCost index_qual_cost;
5975 double qual_op_cost;
5976 double qual_arg_cost;
5977 List *selectivityQuals;
5981 * If the index is partial, AND the index predicate with the explicitly
5982 * given indexquals to produce a more accurate idea of the index
5985 selectivityQuals = add_predicate_to_quals(index, indexQuals);
5988 * Check for ScalarArrayOpExpr index quals, and estimate the number of
5989 * index scans that will be performed.
5992 foreach(l, indexQuals)
5994 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
5996 if (IsA(rinfo->clause, ScalarArrayOpExpr))
5998 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
5999 int alength = estimate_array_length(lsecond(saop->args));
6002 num_sa_scans *= alength;
6006 /* Estimate the fraction of main-table tuples that will be visited */
6007 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6013 * If caller didn't give us an estimate, estimate the number of index
6014 * tuples that will be visited. We do it in this rather peculiar-looking
6015 * way in order to get the right answer for partial indexes.
6017 numIndexTuples = costs->numIndexTuples;
6018 if (numIndexTuples <= 0.0)
6020 numIndexTuples = indexSelectivity * index->rel->tuples;
6023 * The above calculation counts all the tuples visited across all
6024 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6025 * average per-indexscan number, so adjust. This is a handy place to
6026 * round to integer, too. (If caller supplied tuple estimate, it's
6027 * responsible for handling these considerations.)
6029 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6033 * We can bound the number of tuples by the index size in any case. Also,
6034 * always estimate at least one tuple is touched, even when
6035 * indexSelectivity estimate is tiny.
6037 if (numIndexTuples > index->tuples)
6038 numIndexTuples = index->tuples;
6039 if (numIndexTuples < 1.0)
6040 numIndexTuples = 1.0;
6043 * Estimate the number of index pages that will be retrieved.
6045 * We use the simplistic method of taking a pro-rata fraction of the total
6046 * number of index pages. In effect, this counts only leaf pages and not
6047 * any overhead such as index metapage or upper tree levels.
6049 * In practice access to upper index levels is often nearly free because
6050 * those tend to stay in cache under load; moreover, the cost involved is
6051 * highly dependent on index type. We therefore ignore such costs here
6052 * and leave it to the caller to add a suitable charge if needed.
6054 if (index->pages > 1 && index->tuples > 1)
6055 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6057 numIndexPages = 1.0;
6059 /* fetch estimated page cost for schema containing index */
6060 get_tablespace_page_costs(index->reltablespace,
6061 &spc_random_page_cost,
6065 * Now compute the disk access costs.
6067 * The above calculations are all per-index-scan. However, if we are in a
6068 * nestloop inner scan, we can expect the scan to be repeated (with
6069 * different search keys) for each row of the outer relation. Likewise,
6070 * ScalarArrayOpExpr quals result in multiple index scans. This creates
6071 * the potential for cache effects to reduce the number of disk page
6072 * fetches needed. We want to estimate the average per-scan I/O cost in
6073 * the presence of caching.
6075 * We use the Mackert-Lohman formula (see costsize.c for details) to
6076 * estimate the total number of page fetches that occur. While this
6077 * wasn't what it was designed for, it seems a reasonable model anyway.
6078 * Note that we are counting pages not tuples anymore, so we take N = T =
6079 * index size, as if there were one "tuple" per page.
6081 num_outer_scans = loop_count;
6082 num_scans = num_sa_scans * num_outer_scans;
6086 double pages_fetched;
6088 /* total page fetches ignoring cache effects */
6089 pages_fetched = numIndexPages * num_scans;
6091 /* use Mackert and Lohman formula to adjust for cache effects */
6092 pages_fetched = index_pages_fetched(pages_fetched,
6094 (double) index->pages,
6098 * Now compute the total disk access cost, and then report a pro-rated
6099 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6100 * since that's internal to the indexscan.)
6102 indexTotalCost = (pages_fetched * spc_random_page_cost)
6108 * For a single index scan, we just charge spc_random_page_cost per
6111 indexTotalCost = numIndexPages * spc_random_page_cost;
6115 * CPU cost: any complex expressions in the indexquals will need to be
6116 * evaluated once at the start of the scan to reduce them to runtime keys
6117 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6118 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6119 * indexqual operator. Because we have numIndexTuples as a per-scan
6120 * number, we have to multiply by num_sa_scans to get the correct result
6121 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6122 * ORDER BY expressions.
6124 * Note: this neglects the possible costs of rechecking lossy operators.
6125 * Detecting that that might be needed seems more expensive than it's
6126 * worth, though, considering all the other inaccuracies here ...
6128 cost_qual_eval(&index_qual_cost, indexQuals, root);
6129 qual_arg_cost = index_qual_cost.startup + index_qual_cost.per_tuple;
6130 cost_qual_eval(&index_qual_cost, indexOrderBys, root);
6131 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6132 qual_op_cost = cpu_operator_cost *
6133 (list_length(indexQuals) + list_length(indexOrderBys));
6134 qual_arg_cost -= qual_op_cost;
6135 if (qual_arg_cost < 0) /* just in case... */
6138 indexStartupCost = qual_arg_cost;
6139 indexTotalCost += qual_arg_cost;
6140 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6143 * Generic assumption about index correlation: there isn't any.
6145 indexCorrelation = 0.0;
6148 * Return everything to caller.
6150 costs->indexStartupCost = indexStartupCost;
6151 costs->indexTotalCost = indexTotalCost;
6152 costs->indexSelectivity = indexSelectivity;
6153 costs->indexCorrelation = indexCorrelation;
6154 costs->numIndexPages = numIndexPages;
6155 costs->numIndexTuples = numIndexTuples;
6156 costs->spc_random_page_cost = spc_random_page_cost;
6157 costs->num_sa_scans = num_sa_scans;
6161 * If the index is partial, add its predicate to the given qual list.
6163 * ANDing the index predicate with the explicitly given indexquals produces
6164 * a more accurate idea of the index's selectivity. However, we need to be
6165 * careful not to insert redundant clauses, because clauselist_selectivity()
6166 * is easily fooled into computing a too-low selectivity estimate. Our
6167 * approach is to add only the predicate clause(s) that cannot be proven to
6168 * be implied by the given indexquals. This successfully handles cases such
6169 * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
6170 * There are many other cases where we won't detect redundancy, leading to a
6171 * too-low selectivity estimate, which will bias the system in favor of using
6172 * partial indexes where possible. That is not necessarily bad though.
6174 * Note that indexQuals contains RestrictInfo nodes while the indpred
6175 * does not, so the output list will be mixed. This is OK for both
6176 * predicate_implied_by() and clauselist_selectivity(), but might be
6177 * problematic if the result were passed to other things.
6180 add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
6182 List *predExtraQuals = NIL;
6185 if (index->indpred == NIL)
6188 foreach(lc, index->indpred)
6190 Node *predQual = (Node *) lfirst(lc);
6191 List *oneQual = list_make1(predQual);
6193 if (!predicate_implied_by(oneQual, indexQuals))
6194 predExtraQuals = list_concat(predExtraQuals, oneQual);
6196 /* list_concat avoids modifying the passed-in indexQuals list */
6197 return list_concat(predExtraQuals, indexQuals);
6202 btcostestimate(PG_FUNCTION_ARGS)
6204 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6205 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6206 double loop_count = PG_GETARG_FLOAT8(2);
6207 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6208 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6209 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6210 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6211 IndexOptInfo *index = path->indexinfo;
6215 VariableStatData vardata;
6216 double numIndexTuples;
6218 List *indexBoundQuals;
6222 bool found_is_null_op;
6223 double num_sa_scans;
6228 * For a btree scan, only leading '=' quals plus inequality quals for the
6229 * immediately next attribute contribute to index selectivity (these are
6230 * the "boundary quals" that determine the starting and stopping points of
6231 * the index scan). Additional quals can suppress visits to the heap, so
6232 * it's OK to count them in indexSelectivity, but they should not count
6233 * for estimating numIndexTuples. So we must examine the given indexquals
6234 * to find out which ones count as boundary quals. We rely on the
6235 * knowledge that they are given in index column order.
6237 * For a RowCompareExpr, we consider only the first column, just as
6238 * rowcomparesel() does.
6240 * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6241 * index scans not one, but the ScalarArrayOpExpr's operator can be
6242 * considered to act the same as it normally does.
6244 indexBoundQuals = NIL;
6248 found_is_null_op = false;
6250 forboth(lcc, path->indexquals, lci, path->indexqualcols)
6252 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
6255 *rightop PG_USED_FOR_ASSERTS_ONLY;
6258 bool is_null_op = false;
6260 if (indexcol != lfirst_int(lci))
6262 /* Beginning of a new column's quals */
6264 break; /* done if no '=' qual for indexcol */
6267 if (indexcol != lfirst_int(lci))
6268 break; /* no quals at all for indexcol */
6271 Assert(IsA(rinfo, RestrictInfo));
6272 clause = rinfo->clause;
6274 if (IsA(clause, OpExpr))
6276 leftop = get_leftop(clause);
6277 rightop = get_rightop(clause);
6278 clause_op = ((OpExpr *) clause)->opno;
6280 else if (IsA(clause, RowCompareExpr))
6282 RowCompareExpr *rc = (RowCompareExpr *) clause;
6284 leftop = (Node *) linitial(rc->largs);
6285 rightop = (Node *) linitial(rc->rargs);
6286 clause_op = linitial_oid(rc->opnos);
6288 else if (IsA(clause, ScalarArrayOpExpr))
6290 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6292 leftop = (Node *) linitial(saop->args);
6293 rightop = (Node *) lsecond(saop->args);
6294 clause_op = saop->opno;
6297 else if (IsA(clause, NullTest))
6299 NullTest *nt = (NullTest *) clause;
6301 leftop = (Node *) nt->arg;
6303 clause_op = InvalidOid;
6304 if (nt->nulltesttype == IS_NULL)
6306 found_is_null_op = true;
6312 elog(ERROR, "unsupported indexqual type: %d",
6313 (int) nodeTag(clause));
6314 continue; /* keep compiler quiet */
6317 if (match_index_to_operand(leftop, indexcol, index))
6319 /* clause_op is correct */
6323 Assert(match_index_to_operand(rightop, indexcol, index));
6324 /* Must flip operator to get the opfamily member */
6325 clause_op = get_commutator(clause_op);
6328 /* check for equality operator */
6329 if (OidIsValid(clause_op))
6331 op_strategy = get_op_opfamily_strategy(clause_op,
6332 index->opfamily[indexcol]);
6333 Assert(op_strategy != 0); /* not a member of opfamily?? */
6334 if (op_strategy == BTEqualStrategyNumber)
6337 else if (is_null_op)
6339 /* IS NULL is like = for purposes of selectivity determination */
6342 /* count up number of SA scans induced by indexBoundQuals only */
6343 if (IsA(clause, ScalarArrayOpExpr))
6345 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6346 int alength = estimate_array_length(lsecond(saop->args));
6349 num_sa_scans *= alength;
6351 indexBoundQuals = lappend(indexBoundQuals, rinfo);
6355 * If index is unique and we found an '=' clause for each column, we can
6356 * just assume numIndexTuples = 1 and skip the expensive
6357 * clauselist_selectivity calculations. However, a ScalarArrayOp or
6358 * NullTest invalidates that theory, even though it sets eqQualHere.
6360 if (index->unique &&
6361 indexcol == index->ncolumns - 1 &&
6365 numIndexTuples = 1.0;
6368 List *selectivityQuals;
6369 Selectivity btreeSelectivity;
6372 * If the index is partial, AND the index predicate with the
6373 * index-bound quals to produce a more accurate idea of the number of
6374 * rows covered by the bound conditions.
6376 selectivityQuals = add_predicate_to_quals(index, indexBoundQuals);
6378 btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6382 numIndexTuples = btreeSelectivity * index->rel->tuples;
6385 * As in genericcostestimate(), we have to adjust for any
6386 * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6389 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6393 * Now do generic index cost estimation.
6395 MemSet(&costs, 0, sizeof(costs));
6396 costs.numIndexTuples = numIndexTuples;
6398 genericcostestimate(root, path, loop_count, &costs);
6401 * Add a CPU-cost component to represent the costs of initial btree
6402 * descent. We don't charge any I/O cost for touching upper btree levels,
6403 * since they tend to stay in cache, but we still have to do about log2(N)
6404 * comparisons to descend a btree of N leaf tuples. We charge one
6405 * cpu_operator_cost per comparison.
6407 * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6408 * ones after the first one are not startup cost so far as the overall
6409 * plan is concerned, so add them only to "total" cost.
6411 if (index->tuples > 1) /* avoid computing log(0) */
6413 descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6414 costs.indexStartupCost += descentCost;
6415 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6419 * Even though we're not charging I/O cost for touching upper btree pages,
6420 * it's still reasonable to charge some CPU cost per page descended
6421 * through. Moreover, if we had no such charge at all, bloated indexes
6422 * would appear to have the same search cost as unbloated ones, at least
6423 * in cases where only a single leaf page is expected to be visited. This
6424 * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6425 * touched. The number of such pages is btree tree height plus one (ie,
6426 * we charge for the leaf page too). As above, charge once per SA scan.
6428 descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6429 costs.indexStartupCost += descentCost;
6430 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6433 * If we can get an estimate of the first column's ordering correlation C
6434 * from pg_statistic, estimate the index correlation as C for a
6435 * single-column index, or C * 0.75 for multiple columns. (The idea here
6436 * is that multiple columns dilute the importance of the first column's
6437 * ordering, but don't negate it entirely. Before 8.0 we divided the
6438 * correlation by the number of columns, but that seems too strong.)
6440 MemSet(&vardata, 0, sizeof(vardata));
6442 if (index->indexkeys[0] != 0)
6444 /* Simple variable --- look to stats for the underlying table */
6445 RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6447 Assert(rte->rtekind == RTE_RELATION);
6449 Assert(relid != InvalidOid);
6450 colnum = index->indexkeys[0];
6452 if (get_relation_stats_hook &&
6453 (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6456 * The hook took control of acquiring a stats tuple. If it did
6457 * supply a tuple, it'd better have supplied a freefunc.
6459 if (HeapTupleIsValid(vardata.statsTuple) &&
6461 elog(ERROR, "no function provided to release variable stats with");
6465 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6466 ObjectIdGetDatum(relid),
6467 Int16GetDatum(colnum),
6468 BoolGetDatum(rte->inh));
6469 vardata.freefunc = ReleaseSysCache;
6474 /* Expression --- maybe there are stats for the index itself */
6475 relid = index->indexoid;
6478 if (get_index_stats_hook &&
6479 (*get_index_stats_hook) (root, relid, colnum, &vardata))
6482 * The hook took control of acquiring a stats tuple. If it did
6483 * supply a tuple, it'd better have supplied a freefunc.
6485 if (HeapTupleIsValid(vardata.statsTuple) &&
6487 elog(ERROR, "no function provided to release variable stats with");
6491 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6492 ObjectIdGetDatum(relid),
6493 Int16GetDatum(colnum),
6494 BoolGetDatum(false));
6495 vardata.freefunc = ReleaseSysCache;
6499 if (HeapTupleIsValid(vardata.statsTuple))
6505 sortop = get_opfamily_member(index->opfamily[0],
6506 index->opcintype[0],
6507 index->opcintype[0],
6508 BTLessStrategyNumber);
6509 if (OidIsValid(sortop) &&
6510 get_attstatsslot(vardata.statsTuple, InvalidOid, 0,
6511 STATISTIC_KIND_CORRELATION,
6515 &numbers, &nnumbers))
6517 double varCorrelation;
6519 Assert(nnumbers == 1);
6520 varCorrelation = numbers[0];
6522 if (index->reverse_sort[0])
6523 varCorrelation = -varCorrelation;
6525 if (index->ncolumns > 1)
6526 costs.indexCorrelation = varCorrelation * 0.75;
6528 costs.indexCorrelation = varCorrelation;
6530 free_attstatsslot(InvalidOid, NULL, 0, numbers, nnumbers);
6534 ReleaseVariableStats(vardata);
6536 *indexStartupCost = costs.indexStartupCost;
6537 *indexTotalCost = costs.indexTotalCost;
6538 *indexSelectivity = costs.indexSelectivity;
6539 *indexCorrelation = costs.indexCorrelation;
6545 hashcostestimate(PG_FUNCTION_ARGS)
6547 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6548 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6549 double loop_count = PG_GETARG_FLOAT8(2);
6550 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6551 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6552 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6553 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6556 MemSet(&costs, 0, sizeof(costs));
6558 genericcostestimate(root, path, loop_count, &costs);
6561 * A hash index has no descent costs as such, since the index AM can go
6562 * directly to the target bucket after computing the hash value. There
6563 * are a couple of other hash-specific costs that we could conceivably add
6566 * Ideally we'd charge spc_random_page_cost for each page in the target
6567 * bucket, not just the numIndexPages pages that genericcostestimate
6568 * thought we'd visit. However in most cases we don't know which bucket
6569 * that will be. There's no point in considering the average bucket size
6570 * because the hash AM makes sure that's always one page.
6572 * Likewise, we could consider charging some CPU for each index tuple in
6573 * the bucket, if we knew how many there were. But the per-tuple cost is
6574 * just a hash value comparison, not a general datatype-dependent
6575 * comparison, so any such charge ought to be quite a bit less than
6576 * cpu_operator_cost; which makes it probably not worth worrying about.
6578 * A bigger issue is that chance hash-value collisions will result in
6579 * wasted probes into the heap. We don't currently attempt to model this
6580 * cost on the grounds that it's rare, but maybe it's not rare enough.
6581 * (Any fix for this ought to consider the generic lossy-operator problem,
6582 * though; it's not entirely hash-specific.)
6585 *indexStartupCost = costs.indexStartupCost;
6586 *indexTotalCost = costs.indexTotalCost;
6587 *indexSelectivity = costs.indexSelectivity;
6588 *indexCorrelation = costs.indexCorrelation;
6594 gistcostestimate(PG_FUNCTION_ARGS)
6596 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6597 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6598 double loop_count = PG_GETARG_FLOAT8(2);
6599 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6600 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6601 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6602 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6603 IndexOptInfo *index = path->indexinfo;
6607 MemSet(&costs, 0, sizeof(costs));
6609 genericcostestimate(root, path, loop_count, &costs);
6612 * We model index descent costs similarly to those for btree, but to do
6613 * that we first need an idea of the tree height. We somewhat arbitrarily
6614 * assume that the fanout is 100, meaning the tree height is at most
6615 * log100(index->pages).
6617 * Although this computation isn't really expensive enough to require
6618 * caching, we might as well use index->tree_height to cache it.
6620 if (index->tree_height < 0) /* unknown? */
6622 if (index->pages > 1) /* avoid computing log(0) */
6623 index->tree_height = (int) (log(index->pages) / log(100.0));
6625 index->tree_height = 0;
6629 * Add a CPU-cost component to represent the costs of initial descent.
6630 * We just use log(N) here not log2(N) since the branching factor isn't
6631 * necessarily two anyway. As for btree, charge once per SA scan.
6633 if (index->tuples > 1) /* avoid computing log(0) */
6635 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6636 costs.indexStartupCost += descentCost;
6637 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6641 * Likewise add a per-page charge, calculated the same as for btrees.
6643 descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6644 costs.indexStartupCost += descentCost;
6645 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6647 *indexStartupCost = costs.indexStartupCost;
6648 *indexTotalCost = costs.indexTotalCost;
6649 *indexSelectivity = costs.indexSelectivity;
6650 *indexCorrelation = costs.indexCorrelation;
6656 spgcostestimate(PG_FUNCTION_ARGS)
6658 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6659 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
6660 double loop_count = PG_GETARG_FLOAT8(2);
6661 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
6662 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
6663 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
6664 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
6665 IndexOptInfo *index = path->indexinfo;
6669 MemSet(&costs, 0, sizeof(costs));
6671 genericcostestimate(root, path, loop_count, &costs);
6674 * We model index descent costs similarly to those for btree, but to do
6675 * that we first need an idea of the tree height. We somewhat arbitrarily
6676 * assume that the fanout is 100, meaning the tree height is at most
6677 * log100(index->pages).
6679 * Although this computation isn't really expensive enough to require
6680 * caching, we might as well use index->tree_height to cache it.
6682 if (index->tree_height < 0) /* unknown? */
6684 if (index->pages > 1) /* avoid computing log(0) */
6685 index->tree_height = (int) (log(index->pages) / log(100.0));
6687 index->tree_height = 0;
6691 * Add a CPU-cost component to represent the costs of initial descent.
6692 * We just use log(N) here not log2(N) since the branching factor isn't
6693 * necessarily two anyway. As for btree, charge once per SA scan.
6695 if (index->tuples > 1) /* avoid computing log(0) */
6697 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6698 costs.indexStartupCost += descentCost;
6699 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6703 * Likewise add a per-page charge, calculated the same as for btrees.
6705 descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6706 costs.indexStartupCost += descentCost;
6707 costs.indexTotalCost += costs.num_sa_scans * descentCost;
6709 *indexStartupCost = costs.indexStartupCost;
6710 *indexTotalCost = costs.indexTotalCost;
6711 *indexSelectivity = costs.indexSelectivity;
6712 *indexCorrelation = costs.indexCorrelation;
6719 * Support routines for gincostestimate
6725 double partialEntries;
6726 double exactEntries;
6727 double searchEntries;
6731 /* Find the index column matching "op"; return its index, or -1 if no match */
6733 find_index_column(Node *op, IndexOptInfo *index)
6737 for (i = 0; i < index->ncolumns; i++)
6739 if (match_index_to_operand(op, i, index))
6747 * Estimate the number of index terms that need to be searched for while
6748 * testing the given GIN query, and increment the counts in *counts
6749 * appropriately. If the query is unsatisfiable, return false.
6752 gincost_pattern(IndexOptInfo *index, int indexcol,
6753 Oid clause_op, Datum query,
6754 GinQualCounts *counts)
6762 bool *partial_matches = NULL;
6763 Pointer *extra_data = NULL;
6764 bool *nullFlags = NULL;
6765 int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
6769 * Get the operator's strategy number and declared input data types within
6770 * the index opfamily. (We don't need the latter, but we use
6771 * get_op_opfamily_properties because it will throw error if it fails to
6772 * find a matching pg_amop entry.)
6774 get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
6775 &strategy_op, &lefttype, &righttype);
6778 * GIN always uses the "default" support functions, which are those with
6779 * lefttype == righttype == the opclass' opcintype (see
6780 * IndexSupportInitialize in relcache.c).
6782 extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
6783 index->opcintype[indexcol],
6784 index->opcintype[indexcol],
6785 GIN_EXTRACTQUERY_PROC);
6787 if (!OidIsValid(extractProcOid))
6789 /* should not happen; throw same error as index_getprocinfo */
6790 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
6791 GIN_EXTRACTQUERY_PROC, indexcol + 1,
6792 get_rel_name(index->indexoid));
6796 * Choose collation to pass to extractProc (should match initGinState).
6798 if (OidIsValid(index->indexcollations[indexcol]))
6799 collation = index->indexcollations[indexcol];
6801 collation = DEFAULT_COLLATION_OID;
6803 OidFunctionCall7Coll(extractProcOid,
6806 PointerGetDatum(&nentries),
6807 UInt16GetDatum(strategy_op),
6808 PointerGetDatum(&partial_matches),
6809 PointerGetDatum(&extra_data),
6810 PointerGetDatum(&nullFlags),
6811 PointerGetDatum(&searchMode));
6813 if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
6815 /* No match is possible */
6819 for (i = 0; i < nentries; i++)
6822 * For partial match we haven't any information to estimate number of
6823 * matched entries in index, so, we just estimate it as 100
6825 if (partial_matches && partial_matches[i])
6826 counts->partialEntries += 100;
6828 counts->exactEntries++;
6830 counts->searchEntries++;
6833 if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
6835 /* Treat "include empty" like an exact-match item */
6836 counts->exactEntries++;
6837 counts->searchEntries++;
6839 else if (searchMode != GIN_SEARCH_MODE_DEFAULT)
6841 /* It's GIN_SEARCH_MODE_ALL */
6842 counts->haveFullScan = true;
6849 * Estimate the number of index terms that need to be searched for while
6850 * testing the given GIN index clause, and increment the counts in *counts
6851 * appropriately. If the query is unsatisfiable, return false.
6854 gincost_opexpr(IndexOptInfo *index, OpExpr *clause, GinQualCounts *counts)
6856 Node *leftop = get_leftop((Expr *) clause);
6857 Node *rightop = get_rightop((Expr *) clause);
6858 Oid clause_op = clause->opno;
6862 /* Locate the operand being compared to the index column */
6863 if ((indexcol = find_index_column(leftop, index)) >= 0)
6867 else if ((indexcol = find_index_column(rightop, index)) >= 0)
6870 clause_op = get_commutator(clause_op);
6874 elog(ERROR, "could not match index to operand");
6875 operand = NULL; /* keep compiler quiet */
6878 if (IsA(operand, RelabelType))
6879 operand = (Node *) ((RelabelType *) operand)->arg;
6882 * It's impossible to call extractQuery method for unknown operand. So
6883 * unless operand is a Const we can't do much; just assume there will be
6884 * one ordinary search entry from the operand at runtime.
6886 if (!IsA(operand, Const))
6888 counts->exactEntries++;
6889 counts->searchEntries++;
6893 /* If Const is null, there can be no matches */
6894 if (((Const *) operand)->constisnull)
6897 /* Otherwise, apply extractQuery and get the actual term counts */
6898 return gincost_pattern(index, indexcol, clause_op,
6899 ((Const *) operand)->constvalue,
6904 * Estimate the number of index terms that need to be searched for while
6905 * testing the given GIN index clause, and increment the counts in *counts
6906 * appropriately. If the query is unsatisfiable, return false.
6908 * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
6909 * each of which involves one value from the RHS array, plus all the
6910 * non-array quals (if any). To model this, we average the counts across
6911 * the RHS elements, and add the averages to the counts in *counts (which
6912 * correspond to per-indexscan costs). We also multiply counts->arrayScans
6913 * by N, causing gincostestimate to scale up its estimates accordingly.
6916 gincost_scalararrayopexpr(IndexOptInfo *index, ScalarArrayOpExpr *clause,
6917 double numIndexEntries,
6918 GinQualCounts *counts)
6920 Node *leftop = (Node *) linitial(clause->args);
6921 Node *rightop = (Node *) lsecond(clause->args);
6922 Oid clause_op = clause->opno;
6924 ArrayType *arrayval;
6931 GinQualCounts arraycounts;
6932 int numPossible = 0;
6935 Assert(clause->useOr);
6937 /* index column must be on the left */
6938 if ((indexcol = find_index_column(leftop, index)) < 0)
6939 elog(ERROR, "could not match index to operand");
6941 if (IsA(rightop, RelabelType))
6942 rightop = (Node *) ((RelabelType *) rightop)->arg;
6945 * It's impossible to call extractQuery method for unknown operand. So
6946 * unless operand is a Const we can't do much; just assume there will be
6947 * one ordinary search entry from each array entry at runtime, and fall
6948 * back on a probably-bad estimate of the number of array entries.
6950 if (!IsA(rightop, Const))
6952 counts->exactEntries++;
6953 counts->searchEntries++;
6954 counts->arrayScans *= estimate_array_length(rightop);
6958 /* If Const is null, there can be no matches */
6959 if (((Const *) rightop)->constisnull)
6962 /* Otherwise, extract the array elements and iterate over them */
6963 arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
6964 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
6965 &elmlen, &elmbyval, &elmalign);
6966 deconstruct_array(arrayval,
6967 ARR_ELEMTYPE(arrayval),
6968 elmlen, elmbyval, elmalign,
6969 &elemValues, &elemNulls, &numElems);
6971 memset(&arraycounts, 0, sizeof(arraycounts));
6973 for (i = 0; i < numElems; i++)
6975 GinQualCounts elemcounts;
6977 /* NULL can't match anything, so ignore, as the executor will */
6981 /* Otherwise, apply extractQuery and get the actual term counts */
6982 memset(&elemcounts, 0, sizeof(elemcounts));
6984 if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
6987 /* We ignore array elements that are unsatisfiable patterns */
6990 if (elemcounts.haveFullScan)
6993 * Full index scan will be required. We treat this as if
6994 * every key in the index had been listed in the query; is
6997 elemcounts.partialEntries = 0;
6998 elemcounts.exactEntries = numIndexEntries;
6999 elemcounts.searchEntries = numIndexEntries;
7001 arraycounts.partialEntries += elemcounts.partialEntries;
7002 arraycounts.exactEntries += elemcounts.exactEntries;
7003 arraycounts.searchEntries += elemcounts.searchEntries;
7007 if (numPossible == 0)
7009 /* No satisfiable patterns in the array */
7014 * Now add the averages to the global counts. This will give us an
7015 * estimate of the average number of terms searched for in each indexscan,
7016 * including contributions from both array and non-array quals.
7018 counts->partialEntries += arraycounts.partialEntries / numPossible;
7019 counts->exactEntries += arraycounts.exactEntries / numPossible;
7020 counts->searchEntries += arraycounts.searchEntries / numPossible;
7022 counts->arrayScans *= numPossible;
7028 * GIN has search behavior completely different from other index types
7031 gincostestimate(PG_FUNCTION_ARGS)
7033 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
7034 IndexPath *path = (IndexPath *) PG_GETARG_POINTER(1);
7035 double loop_count = PG_GETARG_FLOAT8(2);
7036 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(3);
7037 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(4);
7038 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(5);
7039 double *indexCorrelation = (double *) PG_GETARG_POINTER(6);
7040 IndexOptInfo *index = path->indexinfo;
7041 List *indexQuals = path->indexquals;
7042 List *indexOrderBys = path->indexorderbys;
7044 List *selectivityQuals;
7045 double numPages = index->pages,
7046 numTuples = index->tuples;
7047 double numEntryPages,
7051 GinQualCounts counts;
7053 double entryPagesFetched,
7055 dataPagesFetchedBySel;
7056 double qual_op_cost,
7058 spc_random_page_cost,
7060 QualCost index_qual_cost;
7062 GinStatsData ginStats;
7065 * Obtain statistic information from the meta page
7067 indexRel = index_open(index->indexoid, AccessShareLock);
7068 ginGetStats(indexRel, &ginStats);
7069 index_close(indexRel, AccessShareLock);
7071 numEntryPages = ginStats.nEntryPages;
7072 numDataPages = ginStats.nDataPages;
7073 numPendingPages = ginStats.nPendingPages;
7074 numEntries = ginStats.nEntries;
7077 * nPendingPages can be trusted, but the other fields are as of the last
7078 * VACUUM. Scale them by the ratio numPages / nTotalPages to account for
7079 * growth since then. If the fields are zero (implying no VACUUM at all,
7080 * and an index created pre-9.1), assume all pages are entry pages.
7082 if (ginStats.nTotalPages == 0 || ginStats.nEntryPages == 0)
7084 numEntryPages = numPages;
7086 numEntries = numTuples; /* bogus, but no other info available */
7090 double scale = numPages / ginStats.nTotalPages;
7092 numEntryPages = ceil(numEntryPages * scale);
7093 numDataPages = ceil(numDataPages * scale);
7094 numEntries = ceil(numEntries * scale);
7095 /* ensure we didn't round up too much */
7096 numEntryPages = Min(numEntryPages, numPages);
7097 numDataPages = Min(numDataPages, numPages - numEntryPages);
7100 /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
7105 * Include predicate in selectivityQuals (should match
7106 * genericcostestimate)
7108 if (index->indpred != NIL)
7110 List *predExtraQuals = NIL;
7112 foreach(l, index->indpred)
7114 Node *predQual = (Node *) lfirst(l);
7115 List *oneQual = list_make1(predQual);
7117 if (!predicate_implied_by(oneQual, indexQuals))
7118 predExtraQuals = list_concat(predExtraQuals, oneQual);
7120 /* list_concat avoids modifying the passed-in indexQuals list */
7121 selectivityQuals = list_concat(predExtraQuals, indexQuals);
7124 selectivityQuals = indexQuals;
7126 /* Estimate the fraction of main-table tuples that will be visited */
7127 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7132 /* fetch estimated page cost for schema containing index */
7133 get_tablespace_page_costs(index->reltablespace,
7134 &spc_random_page_cost,
7138 * Generic assumption about index correlation: there isn't any.
7140 *indexCorrelation = 0.0;
7143 * Examine quals to estimate number of search entries & partial matches
7145 memset(&counts, 0, sizeof(counts));
7146 counts.arrayScans = 1;
7147 matchPossible = true;
7149 foreach(l, indexQuals)
7151 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
7154 Assert(IsA(rinfo, RestrictInfo));
7155 clause = rinfo->clause;
7156 if (IsA(clause, OpExpr))
7158 matchPossible = gincost_opexpr(index,
7164 else if (IsA(clause, ScalarArrayOpExpr))
7166 matchPossible = gincost_scalararrayopexpr(index,
7167 (ScalarArrayOpExpr *) clause,
7175 /* shouldn't be anything else for a GIN index */
7176 elog(ERROR, "unsupported GIN indexqual type: %d",
7177 (int) nodeTag(clause));
7181 /* Fall out if there were any provably-unsatisfiable quals */
7184 *indexStartupCost = 0;
7185 *indexTotalCost = 0;
7186 *indexSelectivity = 0;
7190 if (counts.haveFullScan || indexQuals == NIL)
7193 * Full index scan will be required. We treat this as if every key in
7194 * the index had been listed in the query; is that reasonable?
7196 counts.partialEntries = 0;
7197 counts.exactEntries = numEntries;
7198 counts.searchEntries = numEntries;
7201 /* Will we have more than one iteration of a nestloop scan? */
7202 outer_scans = loop_count;
7205 * Compute cost to begin scan, first of all, pay attention to pending
7208 entryPagesFetched = numPendingPages;
7211 * Estimate number of entry pages read. We need to do
7212 * counts.searchEntries searches. Use a power function as it should be,
7213 * but tuples on leaf pages usually is much greater. Here we include all
7214 * searches in entry tree, including search of first entry in partial
7217 entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
7220 * Add an estimate of entry pages read by partial match algorithm. It's a
7221 * scan over leaf pages in entry tree. We haven't any useful stats here,
7222 * so estimate it as proportion.
7224 entryPagesFetched += ceil(numEntryPages * counts.partialEntries / numEntries);
7227 * Partial match algorithm reads all data pages before doing actual scan,
7228 * so it's a startup cost. Again, we haven't any useful stats here, so,
7229 * estimate it as proportion
7231 dataPagesFetched = ceil(numDataPages * counts.partialEntries / numEntries);
7234 * Calculate cache effects if more than one scan due to nestloops or array
7235 * quals. The result is pro-rated per nestloop scan, but the array qual
7236 * factor shouldn't be pro-rated (compare genericcostestimate).
7238 if (outer_scans > 1 || counts.arrayScans > 1)
7240 entryPagesFetched *= outer_scans * counts.arrayScans;
7241 entryPagesFetched = index_pages_fetched(entryPagesFetched,
7242 (BlockNumber) numEntryPages,
7243 numEntryPages, root);
7244 entryPagesFetched /= outer_scans;
7245 dataPagesFetched *= outer_scans * counts.arrayScans;
7246 dataPagesFetched = index_pages_fetched(dataPagesFetched,
7247 (BlockNumber) numDataPages,
7248 numDataPages, root);
7249 dataPagesFetched /= outer_scans;
7253 * Here we use random page cost because logically-close pages could be far
7256 *indexStartupCost = (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
7259 * Now we compute the number of data pages fetched while the scan
7263 /* data pages scanned for each exact (non-partial) matched entry */
7264 dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
7267 * Estimate number of data pages read, using selectivity estimation and
7268 * capacity of data page.
7270 dataPagesFetchedBySel = ceil(*indexSelectivity *
7271 (numTuples / (BLCKSZ / SizeOfIptrData)));
7273 if (dataPagesFetchedBySel > dataPagesFetched)
7276 * At least one of entries is very frequent and, unfortunately, we
7277 * couldn't get statistic about entries (only tsvector has such
7278 * statistics). So, we obviously have too small estimation of pages
7279 * fetched from data tree. Re-estimate it from known capacity of data
7282 dataPagesFetched = dataPagesFetchedBySel;
7285 /* Account for cache effects, the same as above */
7286 if (outer_scans > 1 || counts.arrayScans > 1)
7288 dataPagesFetched *= outer_scans * counts.arrayScans;
7289 dataPagesFetched = index_pages_fetched(dataPagesFetched,
7290 (BlockNumber) numDataPages,
7291 numDataPages, root);
7292 dataPagesFetched /= outer_scans;
7295 /* And apply random_page_cost as the cost per page */
7296 *indexTotalCost = *indexStartupCost +
7297 dataPagesFetched * spc_random_page_cost;
7300 * Add on index qual eval costs, much as in genericcostestimate
7302 cost_qual_eval(&index_qual_cost, indexQuals, root);
7303 qual_arg_cost = index_qual_cost.startup + index_qual_cost.per_tuple;
7304 cost_qual_eval(&index_qual_cost, indexOrderBys, root);
7305 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
7306 qual_op_cost = cpu_operator_cost *
7307 (list_length(indexQuals) + list_length(indexOrderBys));
7308 qual_arg_cost -= qual_op_cost;
7309 if (qual_arg_cost < 0) /* just in case... */
7312 *indexStartupCost += qual_arg_cost;
7313 *indexTotalCost += qual_arg_cost;
7314 *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost + qual_op_cost);