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-2001, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
18 * $Header: /cvsroot/pgsql/src/backend/utils/adt/selfuncs.c,v 1.104 2002/03/01 04:09:25 tgl Exp $
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 (Query *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 (opaque, oid, opaque, int4);
58 * The call convention for a join estimator (oprjoin function) is similar
59 * except that varRelid is not needed:
61 * Selectivity oprjoin (Query *root,
65 * float8 oprjoin (opaque, oid, opaque);
77 #include "access/heapam.h"
78 #include "catalog/catname.h"
79 #include "catalog/pg_operator.h"
80 #include "catalog/pg_proc.h"
81 #include "catalog/pg_statistic.h"
82 #include "catalog/pg_type.h"
83 #include "mb/pg_wchar.h"
84 #include "nodes/makefuncs.h"
85 #include "optimizer/clauses.h"
86 #include "optimizer/cost.h"
87 #include "optimizer/pathnode.h"
88 #include "optimizer/plancat.h"
89 #include "optimizer/prep.h"
90 #include "parser/parse_func.h"
91 #include "parser/parse_oper.h"
92 #include "parser/parsetree.h"
93 #include "utils/builtins.h"
94 #include "utils/date.h"
95 #include "utils/datum.h"
96 #include "utils/int8.h"
97 #include "utils/lsyscache.h"
98 #include "utils/selfuncs.h"
99 #include "utils/syscache.h"
103 * Note: the default selectivity estimates are not chosen entirely at random.
104 * We want them to be small enough to ensure that indexscans will be used if
105 * available, for typical table densities of ~100 tuples/page. Thus, for
106 * example, 0.01 is not quite small enough, since that makes it appear that
107 * nearly all pages will be hit anyway. Also, since we sometimes estimate
108 * eqsel as 1/num_distinct, we probably want DEFAULT_NUM_DISTINCT to equal
112 /* default selectivity estimate for equalities such as "A = b" */
113 #define DEFAULT_EQ_SEL 0.005
115 /* default selectivity estimate for inequalities such as "A < b" */
116 #define DEFAULT_INEQ_SEL (1.0 / 3.0)
118 /* default selectivity estimate for pattern-match operators such as LIKE */
119 #define DEFAULT_MATCH_SEL 0.005
121 /* default number of distinct values in a table */
122 #define DEFAULT_NUM_DISTINCT 200
124 /* default selectivity estimate for boolean and null test nodes */
125 #define DEFAULT_UNK_SEL 0.005
126 #define DEFAULT_NOT_UNK_SEL (1.0 - DEFAULT_UNK_SEL)
127 #define DEFAULT_BOOL_SEL 0.5
130 * Clamp a computed probability estimate (which may suffer from roundoff or
131 * estimation errors) to valid range. Argument must be a float variable.
133 #define CLAMP_PROBABILITY(p) \
142 static bool get_var_maximum(Query *root, Var *var, Oid sortop, Datum *max);
143 static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
144 Datum lobound, Datum hibound, Oid boundstypid,
145 double *scaledlobound, double *scaledhibound);
146 static double convert_numeric_to_scalar(Datum value, Oid typid);
147 static void convert_string_to_scalar(unsigned char *value,
149 unsigned char *lobound,
150 double *scaledlobound,
151 unsigned char *hibound,
152 double *scaledhibound);
153 static void convert_bytea_to_scalar(Datum value,
156 double *scaledlobound,
158 double *scaledhibound);
159 static double convert_one_string_to_scalar(unsigned char *value,
160 int rangelo, int rangehi);
161 static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
162 int rangelo, int rangehi);
163 static unsigned char *convert_string_datum(Datum value, Oid typid);
164 static double convert_timevalue_to_scalar(Datum value, Oid typid);
165 static double get_att_numdistinct(Query *root, Var *var,
166 Form_pg_statistic stats);
167 static bool get_restriction_var(List *args, int varRelid,
168 Var **var, Node **other,
170 static void get_join_vars(List *args, Var **var1, Var **var2);
171 static Selectivity prefix_selectivity(Query *root, Var *var, char *prefix);
172 static Selectivity pattern_selectivity(char *patt, Pattern_Type ptype);
173 static bool string_lessthan(const char *str1, const char *str2,
175 static Oid find_operator(const char *opname, Oid datatype);
176 static Datum string_to_datum(const char *str, Oid datatype);
177 static Const *string_to_const(const char *str, Oid datatype);
181 * eqsel - Selectivity of "=" for any data types.
183 * Note: this routine is also used to estimate selectivity for some
184 * operators that are not "=" but have comparable selectivity behavior,
185 * such as "~=" (geometric approximate-match). Even for "=", we must
186 * keep in mind that the left and right datatypes may differ.
189 eqsel(PG_FUNCTION_ARGS)
191 Query *root = (Query *) PG_GETARG_POINTER(0);
192 Oid operator = PG_GETARG_OID(1);
193 List *args = (List *) PG_GETARG_POINTER(2);
194 int varRelid = PG_GETARG_INT32(3);
199 HeapTuple statsTuple;
207 * If expression is not var = something or something = var for a
208 * simple var of a real relation (no subqueries, for now), then punt
209 * and return a default estimate.
211 if (!get_restriction_var(args, varRelid,
212 &var, &other, &varonleft))
213 PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
214 relid = getrelid(var->varno, root->rtable);
215 if (relid == InvalidOid)
216 PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
219 * If the something is a NULL constant, assume operator is strict and
220 * return zero, ie, operator will never return TRUE.
222 if (IsA(other, Const) &&((Const *) other)->constisnull)
223 PG_RETURN_FLOAT8(0.0);
225 /* get stats for the attribute, if available */
226 statsTuple = SearchSysCache(STATRELATT,
227 ObjectIdGetDatum(relid),
228 Int16GetDatum(var->varattno),
230 if (HeapTupleIsValid(statsTuple))
232 Form_pg_statistic stats;
234 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
236 if (IsA(other, Const))
238 /* Var is being compared to a known non-null constant */
239 Datum constval = ((Const *) other)->constvalue;
244 * Is the constant "=" to any of the column's most common
245 * values? (Although the given operator may not really be
246 * "=", we will assume that seeing whether it returns TRUE is
247 * an appropriate test. If you don't like this, maybe you
248 * shouldn't be using eqsel for your operator...)
250 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
251 STATISTIC_KIND_MCV, InvalidOid,
253 &numbers, &nnumbers))
257 fmgr_info(get_opcode(operator), &eqproc);
259 for (i = 0; i < nvalues; i++)
261 /* be careful to apply operator right way 'round */
263 match = DatumGetBool(FunctionCall2(&eqproc,
267 match = DatumGetBool(FunctionCall2(&eqproc,
276 /* no most-common-value info available */
279 i = nvalues = nnumbers = 0;
285 * Constant is "=" to this common value. We know
286 * selectivity exactly (or as exactly as VACUUM could
287 * calculate it, anyway).
294 * Comparison is against a constant that is neither NULL
295 * nor any of the common values. Its selectivity cannot
298 double sumcommon = 0.0;
299 double otherdistinct;
301 for (i = 0; i < nnumbers; i++)
302 sumcommon += numbers[i];
303 selec = 1.0 - sumcommon - stats->stanullfrac;
304 CLAMP_PROBABILITY(selec);
307 * and in fact it's probably a good deal less. We
308 * approximate that all the not-common values share this
309 * remaining fraction equally, so we divide by the number
310 * of other distinct values.
312 otherdistinct = get_att_numdistinct(root, var, stats)
314 if (otherdistinct > 1)
315 selec /= otherdistinct;
318 * Another cross-check: selectivity shouldn't be estimated
319 * as more than the least common "most common value".
321 if (nnumbers > 0 && selec > numbers[nnumbers - 1])
322 selec = numbers[nnumbers - 1];
325 free_attstatsslot(var->vartype, values, nvalues,
333 * Search is for a value that we do not know a priori, but we
334 * will assume it is not NULL. Estimate the selectivity as
335 * non-null fraction divided by number of distinct values, so
336 * that we get a result averaged over all possible values
337 * whether common or uncommon. (Essentially, we are assuming
338 * that the not-yet-known comparison value is equally likely
339 * to be any of the possible values, regardless of their
340 * frequency in the table. Is that a good idea?)
342 selec = 1.0 - stats->stanullfrac;
343 ndistinct = get_att_numdistinct(root, var, stats);
348 * Cross-check: selectivity should never be estimated as more
349 * than the most common value's.
351 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
352 STATISTIC_KIND_MCV, InvalidOid,
354 &numbers, &nnumbers))
356 if (nnumbers > 0 && selec > numbers[0])
358 free_attstatsslot(var->vartype, NULL, 0, numbers, nnumbers);
362 ReleaseSysCache(statsTuple);
367 * No VACUUM ANALYZE stats available, so make a guess using
368 * estimated number of distinct values and assuming they are
369 * equally common. (The guess is unlikely to be very good, but we
370 * do know a few special cases.)
372 selec = 1.0 / get_att_numdistinct(root, var, NULL);
375 /* result should be in range, but make sure... */
376 CLAMP_PROBABILITY(selec);
378 PG_RETURN_FLOAT8((float8) selec);
382 * neqsel - Selectivity of "!=" for any data types.
384 * This routine is also used for some operators that are not "!="
385 * but have comparable selectivity behavior. See above comments
389 neqsel(PG_FUNCTION_ARGS)
391 Query *root = (Query *) PG_GETARG_POINTER(0);
392 Oid operator = PG_GETARG_OID(1);
393 List *args = (List *) PG_GETARG_POINTER(2);
394 int varRelid = PG_GETARG_INT32(3);
399 * We want 1 - eqsel() where the equality operator is the one
400 * associated with this != operator, that is, its negator.
402 eqop = get_negator(operator);
405 result = DatumGetFloat8(DirectFunctionCall4(eqsel,
406 PointerGetDatum(root),
407 ObjectIdGetDatum(eqop),
408 PointerGetDatum(args),
409 Int32GetDatum(varRelid)));
413 /* Use default selectivity (should we raise an error instead?) */
414 result = DEFAULT_EQ_SEL;
416 result = 1.0 - result;
417 PG_RETURN_FLOAT8(result);
421 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
423 * This is the guts of both scalarltsel and scalargtsel. The caller has
424 * commuted the clause, if necessary, so that we can treat the Var as
425 * being on the left. The caller must also make sure that the other side
426 * of the clause is a non-null Const, and dissect same into a value and
429 * This routine works for any datatype (or pair of datatypes) known to
430 * convert_to_scalar(). If it is applied to some other datatype,
431 * it will return a default estimate.
434 scalarineqsel(Query *root, Oid operator, bool isgt,
435 Var *var, Datum constval, Oid consttype)
438 HeapTuple statsTuple;
439 Form_pg_statistic stats;
452 * If expression is not var op something or something op var for a
453 * simple var of a real relation (no subqueries, for now), then punt
454 * and return a default estimate.
456 relid = getrelid(var->varno, root->rtable);
457 if (relid == InvalidOid)
458 return DEFAULT_INEQ_SEL;
460 /* get stats for the attribute */
461 statsTuple = SearchSysCache(STATRELATT,
462 ObjectIdGetDatum(relid),
463 Int16GetDatum(var->varattno),
465 if (!HeapTupleIsValid(statsTuple))
467 /* no stats available, so default result */
468 return DEFAULT_INEQ_SEL;
470 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
472 fmgr_info(get_opcode(operator), &opproc);
475 * If we have most-common-values info, add up the fractions of the MCV
476 * entries that satisfy MCV OP CONST. These fractions contribute
477 * directly to the result selectivity. Also add up the total fraction
478 * represented by MCV entries.
483 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
484 STATISTIC_KIND_MCV, InvalidOid,
486 &numbers, &nnumbers))
488 for (i = 0; i < nvalues; i++)
490 if (DatumGetBool(FunctionCall2(&opproc,
493 mcv_selec += numbers[i];
494 sumcommon += numbers[i];
496 free_attstatsslot(var->vartype, values, nvalues, numbers, nnumbers);
500 * If there is a histogram, determine which bin the constant falls in,
501 * and compute the resulting contribution to selectivity.
503 * Someday, VACUUM might store more than one histogram per rel/att,
504 * corresponding to more than one possible sort ordering defined for
505 * the column type. However, to make that work we will need to figure
506 * out which staop to search for --- it's not necessarily the one we
507 * have at hand! (For example, we might have a '<=' operator rather
508 * than the '<' operator that will appear in staop.) For now, assume
509 * that whatever appears in pg_statistic is sorted the same way our
510 * operator sorts, or the reverse way if isgt is TRUE.
514 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
515 STATISTIC_KIND_HISTOGRAM, InvalidOid,
524 ltcmp = DatumGetBool(FunctionCall2(&opproc,
531 /* Constant is below lower histogram boundary. */
537 * Scan to find proper location. This could be made
538 * faster by using a binary-search method, but it's
539 * probably not worth the trouble for typical histogram
542 for (i = 1; i < nvalues; i++)
544 ltcmp = DatumGetBool(FunctionCall2(&opproc,
554 /* Constant is above upper histogram boundary. */
565 * We have values[i-1] < constant < values[i].
567 * Convert the constant and the two nearest bin boundary
568 * values to a uniform comparison scale, and do a
569 * linear interpolation within this bin.
571 if (convert_to_scalar(constval, consttype, &val,
572 values[i - 1], values[i],
578 /* cope if bin boundaries appear identical */
583 else if (val >= high)
587 binfrac = (val - low) / (high - low);
590 * Watch out for the possibility that we got a
591 * NaN or Infinity from the division. This
592 * can happen despite the previous checks, if
593 * for example "low" is -Infinity.
595 if (isnan(binfrac) ||
596 binfrac < 0.0 || binfrac > 1.0)
603 * Ideally we'd produce an error here, on the
604 * grounds that the given operator shouldn't have
605 * scalarXXsel registered as its selectivity func
606 * unless we can deal with its operand types. But
607 * currently, all manner of stuff is invoking
608 * scalarXXsel, so give a default estimate until
615 * Now, compute the overall selectivity across the
616 * values represented by the histogram. We have i-1
617 * full bins and binfrac partial bin below the
620 histfrac = (double) (i - 1) + binfrac;
621 histfrac /= (double) (nvalues - 1);
626 * Now histfrac = fraction of histogram entries below the
629 * Account for "<" vs ">"
631 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
634 * The histogram boundaries are only approximate to begin
635 * with, and may well be out of date anyway. Therefore, don't
636 * believe extremely small or large selectivity estimates.
638 if (hist_selec < 0.0001)
640 else if (hist_selec > 0.9999)
644 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
648 * Now merge the results from the MCV and histogram calculations,
649 * realizing that the histogram covers only the non-null values that
650 * are not listed in MCV.
652 selec = 1.0 - stats->stanullfrac - sumcommon;
654 if (hist_selec > 0.0)
659 * If no histogram but there are values not accounted for by MCV,
660 * arbitrarily assume half of them will match.
667 ReleaseSysCache(statsTuple);
669 /* result should be in range, but make sure... */
670 CLAMP_PROBABILITY(selec);
676 * scalarltsel - Selectivity of "<" (also "<=") for scalars.
679 scalarltsel(PG_FUNCTION_ARGS)
681 Query *root = (Query *) PG_GETARG_POINTER(0);
682 Oid operator = PG_GETARG_OID(1);
683 List *args = (List *) PG_GETARG_POINTER(2);
684 int varRelid = PG_GETARG_INT32(3);
694 * If expression is not var op something or something op var for a
695 * simple var of a real relation (no subqueries, for now), then punt
696 * and return a default estimate.
698 if (!get_restriction_var(args, varRelid,
699 &var, &other, &varonleft))
700 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
703 * Can't do anything useful if the something is not a constant,
706 if (!IsA(other, Const))
707 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
710 * If the constant is NULL, assume operator is strict and return zero,
711 * ie, operator will never return TRUE.
713 if (((Const *) other)->constisnull)
714 PG_RETURN_FLOAT8(0.0);
715 constval = ((Const *) other)->constvalue;
716 consttype = ((Const *) other)->consttype;
719 * Force the var to be on the left to simplify logic in scalarineqsel.
723 /* we have var < other */
728 /* we have other < var, commute to make var > other */
729 operator = get_commutator(operator);
732 /* Use default selectivity (should we raise an error instead?) */
733 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
738 selec = scalarineqsel(root, operator, isgt, var, constval, consttype);
740 PG_RETURN_FLOAT8((float8) selec);
744 * scalargtsel - Selectivity of ">" (also ">=") for integers.
747 scalargtsel(PG_FUNCTION_ARGS)
749 Query *root = (Query *) PG_GETARG_POINTER(0);
750 Oid operator = PG_GETARG_OID(1);
751 List *args = (List *) PG_GETARG_POINTER(2);
752 int varRelid = PG_GETARG_INT32(3);
762 * If expression is not var op something or something op var for a
763 * simple var of a real relation (no subqueries, for now), then punt
764 * and return a default estimate.
766 if (!get_restriction_var(args, varRelid,
767 &var, &other, &varonleft))
768 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
771 * Can't do anything useful if the something is not a constant,
774 if (!IsA(other, Const))
775 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
778 * If the constant is NULL, assume operator is strict and return zero,
779 * ie, operator will never return TRUE.
781 if (((Const *) other)->constisnull)
782 PG_RETURN_FLOAT8(0.0);
783 constval = ((Const *) other)->constvalue;
784 consttype = ((Const *) other)->consttype;
787 * Force the var to be on the left to simplify logic in scalarineqsel.
791 /* we have var > other */
796 /* we have other > var, commute to make var < other */
797 operator = get_commutator(operator);
800 /* Use default selectivity (should we raise an error instead?) */
801 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
806 selec = scalarineqsel(root, operator, isgt, var, constval, consttype);
808 PG_RETURN_FLOAT8((float8) selec);
812 * patternsel - Generic code for pattern-match selectivity.
815 patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype)
817 Query *root = (Query *) PG_GETARG_POINTER(0);
820 Oid operator = PG_GETARG_OID(1);
822 List *args = (List *) PG_GETARG_POINTER(2);
823 int varRelid = PG_GETARG_INT32(3);
830 Pattern_Prefix_Status pstatus;
836 * If expression is not var op constant for a simple var of a real
837 * relation (no subqueries, for now), then punt and return a default
840 if (!get_restriction_var(args, varRelid,
841 &var, &other, &varonleft))
842 return DEFAULT_MATCH_SEL;
843 if (!varonleft || !IsA(other, Const))
844 return DEFAULT_MATCH_SEL;
845 relid = getrelid(var->varno, root->rtable);
846 if (relid == InvalidOid)
847 return DEFAULT_MATCH_SEL;
850 * If the constant is NULL, assume operator is strict and return zero,
851 * ie, operator will never return TRUE.
853 if (((Const *) other)->constisnull)
855 constval = ((Const *) other)->constvalue;
856 /* the right-hand const is type text for all supported operators */
857 Assert(((Const *) other)->consttype == TEXTOID);
858 patt = DatumGetCString(DirectFunctionCall1(textout, constval));
860 /* divide pattern into fixed prefix and remainder */
861 pstatus = pattern_fixed_prefix(patt, ptype, &prefix, &rest);
863 if (pstatus == Pattern_Prefix_Exact)
866 * Pattern specifies an exact match, so pretend operator is '='
868 Oid eqopr = find_operator("=", var->vartype);
872 if (eqopr == InvalidOid)
873 elog(ERROR, "patternsel: no = operator for type %u",
875 eqcon = string_to_const(prefix, var->vartype);
876 eqargs = makeList2(var, eqcon);
877 result = DatumGetFloat8(DirectFunctionCall4(eqsel,
878 PointerGetDatum(root),
879 ObjectIdGetDatum(eqopr),
880 PointerGetDatum(eqargs),
881 Int32GetDatum(varRelid)));
886 * Not exact-match pattern. We estimate selectivity of the fixed
887 * prefix and remainder of pattern separately, then combine the
890 Selectivity prefixsel;
894 if (pstatus == Pattern_Prefix_Partial)
895 prefixsel = prefix_selectivity(root, var, prefix);
898 restsel = pattern_selectivity(rest, ptype);
899 selec = prefixsel * restsel;
900 /* result should be in range, but make sure... */
901 CLAMP_PROBABILITY(selec);
913 * regexeqsel - Selectivity of regular-expression pattern match.
916 regexeqsel(PG_FUNCTION_ARGS)
918 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex));
922 * icregexeqsel - Selectivity of case-insensitive regex match.
925 icregexeqsel(PG_FUNCTION_ARGS)
927 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC));
931 * likesel - Selectivity of LIKE pattern match.
934 likesel(PG_FUNCTION_ARGS)
936 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like));
940 * iclikesel - Selectivity of ILIKE pattern match.
943 iclikesel(PG_FUNCTION_ARGS)
945 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC));
949 * regexnesel - Selectivity of regular-expression pattern non-match.
952 regexnesel(PG_FUNCTION_ARGS)
956 result = patternsel(fcinfo, Pattern_Type_Regex);
957 result = 1.0 - result;
958 PG_RETURN_FLOAT8(result);
962 * icregexnesel - Selectivity of case-insensitive regex non-match.
965 icregexnesel(PG_FUNCTION_ARGS)
969 result = patternsel(fcinfo, Pattern_Type_Regex_IC);
970 result = 1.0 - result;
971 PG_RETURN_FLOAT8(result);
975 * nlikesel - Selectivity of LIKE pattern non-match.
978 nlikesel(PG_FUNCTION_ARGS)
982 result = patternsel(fcinfo, Pattern_Type_Like);
983 result = 1.0 - result;
984 PG_RETURN_FLOAT8(result);
988 * icnlikesel - Selectivity of ILIKE pattern non-match.
991 icnlikesel(PG_FUNCTION_ARGS)
995 result = patternsel(fcinfo, Pattern_Type_Like_IC);
996 result = 1.0 - result;
997 PG_RETURN_FLOAT8(result);
1001 * booltestsel - Selectivity of BooleanTest Node.
1004 booltestsel(Query *root, BooleanTest *clause, int varRelid)
1009 HeapTuple statsTuple;
1016 Assert(clause && IsA(clause, BooleanTest));
1018 arg = (Node *) clause->arg;
1021 * Ignore any binary-compatible relabeling (probably unnecessary, but
1024 if (IsA(arg, RelabelType))
1025 arg = ((RelabelType *) arg)->arg;
1027 if (IsA(arg, Var) &&(varRelid == 0 || varRelid == ((Var *) arg)->varno))
1032 * If argument is not a Var, we can't get statistics for it, but
1033 * perhaps clause_selectivity can do something with it. We ignore
1034 * the possibility of a NULL value when using clause_selectivity,
1035 * and just assume the value is either TRUE or FALSE.
1037 switch (clause->booltesttype)
1040 selec = DEFAULT_UNK_SEL;
1042 case IS_NOT_UNKNOWN:
1043 selec = DEFAULT_NOT_UNK_SEL;
1047 selec = (double) clause_selectivity(root, arg, varRelid);
1051 selec = 1.0 - (double) clause_selectivity(root, arg, varRelid);
1054 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1055 (int) clause->booltesttype);
1056 selec = 0.0; /* Keep compiler quiet */
1059 return (Selectivity) selec;
1062 /* get stats for the attribute, if available */
1063 relid = getrelid(var->varno, root->rtable);
1064 if (relid == InvalidOid)
1067 statsTuple = SearchSysCache(STATRELATT,
1068 ObjectIdGetDatum(relid),
1069 Int16GetDatum(var->varattno),
1072 if (HeapTupleIsValid(statsTuple))
1074 Form_pg_statistic stats;
1077 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
1079 freq_null = stats->stanullfrac;
1081 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1082 STATISTIC_KIND_MCV, InvalidOid,
1084 &numbers, &nnumbers)
1091 * Get first MCV frequency and derive frequency for true.
1093 if (DatumGetBool(values[0]))
1094 freq_true = numbers[0];
1096 freq_true = 1.0 - numbers[0] - freq_null;
1099 * Next derive freqency for false. Then use these as
1100 * appropriate to derive frequency for each case.
1102 freq_false = 1.0 - freq_true - freq_null;
1104 switch (clause->booltesttype)
1107 /* select only NULL values */
1110 case IS_NOT_UNKNOWN:
1111 /* select non-NULL values */
1112 selec = 1.0 - freq_null;
1115 /* select only TRUE values */
1119 /* select non-TRUE values */
1120 selec = 1.0 - freq_true;
1123 /* select only FALSE values */
1127 /* select non-FALSE values */
1128 selec = 1.0 - freq_false;
1131 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1132 (int) clause->booltesttype);
1133 selec = 0.0; /* Keep compiler quiet */
1137 free_attstatsslot(var->vartype, values, nvalues,
1143 * No most-common-value info available. Still have null
1144 * fraction information, so use it for IS [NOT] UNKNOWN.
1145 * Otherwise adjust for null fraction and assume an even split
1146 * for boolean tests.
1148 switch (clause->booltesttype)
1153 * Use freq_null directly.
1157 case IS_NOT_UNKNOWN:
1160 * Select not unknown (not null) values. Calculate
1163 selec = 1.0 - freq_null;
1169 selec = (1.0 - freq_null) / 2.0;
1172 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1173 (int) clause->booltesttype);
1174 selec = 0.0; /* Keep compiler quiet */
1179 ReleaseSysCache(statsTuple);
1184 * No VACUUM ANALYZE stats available, so use a default value.
1185 * (Note: not much point in recursing to clause_selectivity here.)
1187 switch (clause->booltesttype)
1190 selec = DEFAULT_UNK_SEL;
1192 case IS_NOT_UNKNOWN:
1193 selec = DEFAULT_NOT_UNK_SEL;
1199 selec = DEFAULT_BOOL_SEL;
1202 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1203 (int) clause->booltesttype);
1204 selec = 0.0; /* Keep compiler quiet */
1209 /* result should be in range, but make sure... */
1210 CLAMP_PROBABILITY(selec);
1212 return (Selectivity) selec;
1216 * nulltestsel - Selectivity of NullTest Node.
1219 nulltestsel(Query *root, NullTest *clause, int varRelid)
1224 HeapTuple statsTuple;
1229 Assert(clause && IsA(clause, NullTest));
1231 switch (clause->nulltesttype)
1234 defselec = DEFAULT_UNK_SEL;
1237 defselec = DEFAULT_NOT_UNK_SEL;
1240 elog(ERROR, "nulltestsel: unexpected nulltesttype %d",
1241 (int) clause->nulltesttype);
1242 return (Selectivity) 0; /* keep compiler quiet */
1245 arg = (Node *) clause->arg;
1248 * Ignore any binary-compatible relabeling
1250 if (IsA(arg, RelabelType))
1251 arg = ((RelabelType *) arg)->arg;
1253 if (IsA(arg, Var) &&(varRelid == 0 || varRelid == ((Var *) arg)->varno))
1258 * punt if non-Var argument
1260 return (Selectivity) defselec;
1263 relid = getrelid(var->varno, root->rtable);
1264 if (relid == InvalidOid)
1265 return (Selectivity) defselec;
1267 /* get stats for the attribute, if available */
1268 statsTuple = SearchSysCache(STATRELATT,
1269 ObjectIdGetDatum(relid),
1270 Int16GetDatum(var->varattno),
1272 if (HeapTupleIsValid(statsTuple))
1274 Form_pg_statistic stats;
1276 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
1277 freq_null = stats->stanullfrac;
1279 switch (clause->nulltesttype)
1284 * Use freq_null directly.
1291 * Select not unknown (not null) values. Calculate from
1294 selec = 1.0 - freq_null;
1297 elog(ERROR, "nulltestsel: unexpected nulltesttype %d",
1298 (int) clause->nulltesttype);
1299 return (Selectivity) 0; /* keep compiler quiet */
1302 ReleaseSysCache(statsTuple);
1307 * No VACUUM ANALYZE stats available, so make a guess
1312 /* result should be in range, but make sure... */
1313 CLAMP_PROBABILITY(selec);
1315 return (Selectivity) selec;
1319 * eqjoinsel - Join selectivity of "="
1322 eqjoinsel(PG_FUNCTION_ARGS)
1324 Query *root = (Query *) PG_GETARG_POINTER(0);
1325 Oid operator = PG_GETARG_OID(1);
1326 List *args = (List *) PG_GETARG_POINTER(2);
1331 get_join_vars(args, &var1, &var2);
1333 if (var1 == NULL && var2 == NULL)
1334 selec = DEFAULT_EQ_SEL;
1337 HeapTuple statsTuple1 = NULL;
1338 HeapTuple statsTuple2 = NULL;
1339 Form_pg_statistic stats1 = NULL;
1340 Form_pg_statistic stats2 = NULL;
1341 double nd1 = DEFAULT_NUM_DISTINCT;
1342 double nd2 = DEFAULT_NUM_DISTINCT;
1343 bool have_mcvs1 = false;
1344 Datum *values1 = NULL;
1346 float4 *numbers1 = NULL;
1348 bool have_mcvs2 = false;
1349 Datum *values2 = NULL;
1351 float4 *numbers2 = NULL;
1356 /* get stats for the attribute, if available */
1357 Oid relid1 = getrelid(var1->varno, root->rtable);
1359 if (relid1 != InvalidOid)
1361 statsTuple1 = SearchSysCache(STATRELATT,
1362 ObjectIdGetDatum(relid1),
1363 Int16GetDatum(var1->varattno),
1365 if (HeapTupleIsValid(statsTuple1))
1367 stats1 = (Form_pg_statistic) GETSTRUCT(statsTuple1);
1368 have_mcvs1 = get_attstatsslot(statsTuple1,
1373 &values1, &nvalues1,
1374 &numbers1, &nnumbers1);
1377 nd1 = get_att_numdistinct(root, var1, stats1);
1383 /* get stats for the attribute, if available */
1384 Oid relid2 = getrelid(var2->varno, root->rtable);
1386 if (relid2 != InvalidOid)
1388 statsTuple2 = SearchSysCache(STATRELATT,
1389 ObjectIdGetDatum(relid2),
1390 Int16GetDatum(var2->varattno),
1392 if (HeapTupleIsValid(statsTuple2))
1394 stats2 = (Form_pg_statistic) GETSTRUCT(statsTuple2);
1395 have_mcvs2 = get_attstatsslot(statsTuple2,
1400 &values2, &nvalues2,
1401 &numbers2, &nnumbers2);
1404 nd2 = get_att_numdistinct(root, var2, stats2);
1408 if (have_mcvs1 && have_mcvs2)
1411 * We have most-common-value lists for both relations. Run
1412 * through the lists to see which MCVs actually join to each
1413 * other with the given operator. This allows us to determine
1414 * the exact join selectivity for the portion of the relations
1415 * represented by the MCV lists. We still have to estimate
1416 * for the remaining population, but in a skewed distribution
1417 * this gives us a big leg up in accuracy. For motivation see
1418 * the analysis in Y. Ioannidis and S. Christodoulakis, "On
1419 * the propagation of errors in the size of join results",
1420 * Technical Report 1018, Computer Science Dept., University
1421 * of Wisconsin, Madison, March 1991 (available from
1427 double matchprodfreq,
1439 fmgr_info(get_opcode(operator), &eqproc);
1440 hasmatch1 = (bool *) palloc(nvalues1 * sizeof(bool));
1441 memset(hasmatch1, 0, nvalues1 * sizeof(bool));
1442 hasmatch2 = (bool *) palloc(nvalues2 * sizeof(bool));
1443 memset(hasmatch2, 0, nvalues2 * sizeof(bool));
1446 * Note we assume that each MCV will match at most one member
1447 * of the other MCV list. If the operator isn't really
1448 * equality, there could be multiple matches --- but we don't
1449 * look for them, both for speed and because the math wouldn't
1452 matchprodfreq = 0.0;
1454 for (i = 0; i < nvalues1; i++)
1458 for (j = 0; j < nvalues2; j++)
1462 if (DatumGetBool(FunctionCall2(&eqproc,
1466 hasmatch1[i] = hasmatch2[j] = true;
1467 matchprodfreq += numbers1[i] * numbers2[j];
1473 CLAMP_PROBABILITY(matchprodfreq);
1474 /* Sum up frequencies of matched and unmatched MCVs */
1475 matchfreq1 = unmatchfreq1 = 0.0;
1476 for (i = 0; i < nvalues1; i++)
1479 matchfreq1 += numbers1[i];
1481 unmatchfreq1 += numbers1[i];
1483 CLAMP_PROBABILITY(matchfreq1);
1484 CLAMP_PROBABILITY(unmatchfreq1);
1485 matchfreq2 = unmatchfreq2 = 0.0;
1486 for (i = 0; i < nvalues2; i++)
1489 matchfreq2 += numbers2[i];
1491 unmatchfreq2 += numbers2[i];
1493 CLAMP_PROBABILITY(matchfreq2);
1494 CLAMP_PROBABILITY(unmatchfreq2);
1499 * Compute total frequency of non-null values that are not in
1502 otherfreq1 = 1.0 - stats1->stanullfrac - matchfreq1 - unmatchfreq1;
1503 otherfreq2 = 1.0 - stats2->stanullfrac - matchfreq2 - unmatchfreq2;
1504 CLAMP_PROBABILITY(otherfreq1);
1505 CLAMP_PROBABILITY(otherfreq2);
1508 * We can estimate the total selectivity from the point of
1509 * view of relation 1 as: the known selectivity for matched
1510 * MCVs, plus unmatched MCVs that are assumed to match against
1511 * random members of relation 2's non-MCV population, plus
1512 * non-MCV values that are assumed to match against random
1513 * members of relation 2's unmatched MCVs plus non-MCV values.
1515 totalsel1 = matchprodfreq;
1517 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
1519 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
1521 /* Same estimate from the point of view of relation 2. */
1522 totalsel2 = matchprodfreq;
1524 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
1526 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
1530 * Use the smaller of the two estimates. This can be
1531 * justified in essentially the same terms as given below for
1532 * the no-stats case: to a first approximation, we are
1533 * estimating from the point of view of the relation with
1536 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
1541 * We do not have MCV lists for both sides. Estimate the join
1542 * selectivity as MIN(1/nd1, 1/nd2). This is plausible if we
1543 * assume that the values are about equally distributed: a
1544 * given tuple of rel1 will join to either 0 or N2/nd2 rows of
1545 * rel2, so total join rows are at most N1*N2/nd2 giving a
1546 * join selectivity of not more than 1/nd2. By the same logic
1547 * it is not more than 1/nd1, so MIN(1/nd1, 1/nd2) is an upper
1548 * bound. Using the MIN() means we estimate from the point of
1549 * view of the relation with smaller nd (since the larger nd
1550 * is determining the MIN). It is reasonable to assume that
1551 * most tuples in this rel will have join partners, so the
1552 * bound is probably reasonably tight and should be taken
1555 * XXX Can we be smarter if we have an MCV list for just one
1556 * side? It seems that if we assume equal distribution for the
1557 * other side, we end up with the same answer anyway.
1566 free_attstatsslot(var1->vartype, values1, nvalues1,
1567 numbers1, nnumbers1);
1569 free_attstatsslot(var2->vartype, values2, nvalues2,
1570 numbers2, nnumbers2);
1571 if (HeapTupleIsValid(statsTuple1))
1572 ReleaseSysCache(statsTuple1);
1573 if (HeapTupleIsValid(statsTuple2))
1574 ReleaseSysCache(statsTuple2);
1577 CLAMP_PROBABILITY(selec);
1579 PG_RETURN_FLOAT8((float8) selec);
1583 * neqjoinsel - Join selectivity of "!="
1586 neqjoinsel(PG_FUNCTION_ARGS)
1588 Query *root = (Query *) PG_GETARG_POINTER(0);
1589 Oid operator = PG_GETARG_OID(1);
1590 List *args = (List *) PG_GETARG_POINTER(2);
1595 * We want 1 - eqjoinsel() where the equality operator is the one
1596 * associated with this != operator, that is, its negator.
1598 eqop = get_negator(operator);
1601 result = DatumGetFloat8(DirectFunctionCall3(eqjoinsel,
1602 PointerGetDatum(root),
1603 ObjectIdGetDatum(eqop),
1604 PointerGetDatum(args)));
1609 /* Use default selectivity (should we raise an error instead?) */
1610 result = DEFAULT_EQ_SEL;
1612 result = 1.0 - result;
1613 PG_RETURN_FLOAT8(result);
1617 * scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
1620 scalarltjoinsel(PG_FUNCTION_ARGS)
1622 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1626 * scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
1629 scalargtjoinsel(PG_FUNCTION_ARGS)
1631 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1635 * regexeqjoinsel - Join selectivity of regular-expression pattern match.
1638 regexeqjoinsel(PG_FUNCTION_ARGS)
1640 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1644 * icregexeqjoinsel - Join selectivity of case-insensitive regex match.
1647 icregexeqjoinsel(PG_FUNCTION_ARGS)
1649 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1653 * likejoinsel - Join selectivity of LIKE pattern match.
1656 likejoinsel(PG_FUNCTION_ARGS)
1658 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1662 * iclikejoinsel - Join selectivity of ILIKE pattern match.
1665 iclikejoinsel(PG_FUNCTION_ARGS)
1667 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1671 * regexnejoinsel - Join selectivity of regex non-match.
1674 regexnejoinsel(PG_FUNCTION_ARGS)
1678 result = DatumGetFloat8(regexeqjoinsel(fcinfo));
1679 result = 1.0 - result;
1680 PG_RETURN_FLOAT8(result);
1684 * icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
1687 icregexnejoinsel(PG_FUNCTION_ARGS)
1691 result = DatumGetFloat8(icregexeqjoinsel(fcinfo));
1692 result = 1.0 - result;
1693 PG_RETURN_FLOAT8(result);
1697 * nlikejoinsel - Join selectivity of LIKE pattern non-match.
1700 nlikejoinsel(PG_FUNCTION_ARGS)
1704 result = DatumGetFloat8(likejoinsel(fcinfo));
1705 result = 1.0 - result;
1706 PG_RETURN_FLOAT8(result);
1710 * icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
1713 icnlikejoinsel(PG_FUNCTION_ARGS)
1717 result = DatumGetFloat8(iclikejoinsel(fcinfo));
1718 result = 1.0 - result;
1719 PG_RETURN_FLOAT8(result);
1723 * mergejoinscansel - Scan selectivity of merge join.
1725 * A merge join will stop as soon as it exhausts either input stream.
1726 * Therefore, if we can estimate the ranges of both input variables,
1727 * we can estimate how much of the input will actually be read. This
1728 * can have a considerable impact on the cost when using indexscans.
1730 * clause should be a clause already known to be mergejoinable.
1732 * *leftscan is set to the fraction of the left-hand variable expected
1733 * to be scanned (0 to 1), and similarly *rightscan for the right-hand
1737 mergejoinscansel(Query *root, Node *clause,
1738 Selectivity *leftscan,
1739 Selectivity *rightscan)
1753 /* Set default results if we can't figure anything out. */
1754 *leftscan = *rightscan = 1.0;
1756 /* Deconstruct the merge clause */
1757 if (!is_opclause(clause))
1758 return; /* shouldn't happen */
1759 opno = ((Oper *) ((Expr *) clause)->oper)->opno;
1760 left = get_leftop((Expr *) clause);
1761 right = get_rightop((Expr *) clause);
1763 return; /* shouldn't happen */
1765 /* Can't do anything if inputs are not Vars */
1766 if (!IsA(left, Var) ||!IsA(right, Var))
1769 /* Verify mergejoinability and get left and right "<" operators */
1770 if (!op_mergejoinable(opno,
1775 return; /* shouldn't happen */
1777 /* Try to get maximum values of both vars */
1778 if (!get_var_maximum(root, left, lsortop, &leftmax))
1779 return; /* no max available from stats */
1781 if (!get_var_maximum(root, right, rsortop, &rightmax))
1782 return; /* no max available from stats */
1784 /* Look up the "left < right" and "left > right" operators */
1785 op_mergejoin_crossops(opno, <op, >op, NULL, NULL);
1787 /* Look up the "right < left" operator */
1788 revltop = get_commutator(gtop);
1789 if (!OidIsValid(revltop))
1790 return; /* shouldn't happen */
1793 * Now, the fraction of the left variable that will be scanned is the
1794 * fraction that's <= the right-side maximum value. But only believe
1795 * non-default estimates, else stick with our 1.0.
1797 selec = scalarineqsel(root, ltop, false, left,
1798 rightmax, right->vartype);
1799 if (selec != DEFAULT_INEQ_SEL)
1802 /* And similarly for the right variable. */
1803 selec = scalarineqsel(root, revltop, false, right,
1804 leftmax, left->vartype);
1805 if (selec != DEFAULT_INEQ_SEL)
1809 * Only one of the two fractions can really be less than 1.0; believe
1810 * the smaller estimate and reset the other one to exactly 1.0.
1812 if (*leftscan > *rightscan)
1820 * Estimate the maximum value of the specified variable.
1821 * If successful, store value in *max and return TRUE.
1822 * If no data available, return FALSE.
1824 * sortop is the "<" comparison operator to use. (To extract the
1825 * minimum instead of the maximum, just pass the ">" operator instead.)
1828 get_var_maximum(Query *root, Var *var, Oid sortop, Datum *max)
1831 bool have_max = false;
1833 HeapTuple statsTuple;
1834 Form_pg_statistic stats;
1841 relid = getrelid(var->varno, root->rtable);
1842 if (relid == InvalidOid)
1845 /* get stats for the attribute */
1846 statsTuple = SearchSysCache(STATRELATT,
1847 ObjectIdGetDatum(relid),
1848 Int16GetDatum(var->varattno),
1850 if (!HeapTupleIsValid(statsTuple))
1852 /* no stats available, so default result */
1855 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
1857 get_typlenbyval(var->vartype, &typLen, &typByVal);
1860 * If there is a histogram, grab the last or first value as appropriate.
1862 * If there is a histogram that is sorted with some other operator
1863 * than the one we want, fail --- this suggests that there is data
1866 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1867 STATISTIC_KIND_HISTOGRAM, sortop,
1873 tmax = datumCopy(values[nvalues-1], typByVal, typLen);
1876 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1880 Oid rsortop = get_commutator(sortop);
1882 if (OidIsValid(rsortop) &&
1883 get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1884 STATISTIC_KIND_HISTOGRAM, rsortop,
1890 tmax = datumCopy(values[0], typByVal, typLen);
1893 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1895 else if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1896 STATISTIC_KIND_HISTOGRAM, InvalidOid,
1900 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1901 ReleaseSysCache(statsTuple);
1907 * If we have most-common-values info, look for a large MCV. This
1908 * is needed even if we also have a histogram, since the histogram
1909 * excludes the MCVs. However, usually the MCVs will not be the
1910 * extreme values, so avoid unnecessary data copying.
1912 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1913 STATISTIC_KIND_MCV, InvalidOid,
1917 bool large_mcv = false;
1920 fmgr_info(get_opcode(sortop), &opproc);
1922 for (i = 0; i < nvalues; i++)
1927 large_mcv = have_max = true;
1929 else if (DatumGetBool(FunctionCall2(&opproc, tmax, values[i])))
1936 tmax = datumCopy(tmax, typByVal, typLen);
1937 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1940 ReleaseSysCache(statsTuple);
1948 * Convert non-NULL values of the indicated types to the comparison
1949 * scale needed by scalarltsel()/scalargtsel().
1950 * Returns "true" if successful.
1952 * XXX this routine is a hack: ideally we should look up the conversion
1953 * subroutines in pg_type.
1955 * All numeric datatypes are simply converted to their equivalent
1956 * "double" values. (NUMERIC values that are outside the range of "double"
1957 * are clamped to +/- HUGE_VAL.)
1959 * String datatypes are converted by convert_string_to_scalar(),
1960 * which is explained below. The reason why this routine deals with
1961 * three values at a time, not just one, is that we need it for strings.
1963 * The bytea datatype is just enough different from strings that it has
1964 * to be treated separately.
1966 * The several datatypes representing absolute times are all converted
1967 * to Timestamp, which is actually a double, and then we just use that
1968 * double value. Note this will give correct results even for the "special"
1969 * values of Timestamp, since those are chosen to compare correctly;
1970 * see timestamp_cmp.
1972 * The several datatypes representing relative times (intervals) are all
1973 * converted to measurements expressed in seconds.
1976 convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
1977 Datum lobound, Datum hibound, Oid boundstypid,
1978 double *scaledlobound, double *scaledhibound)
1983 * Built-in numeric types
1994 *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
1995 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
1996 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
2000 * Built-in string types
2008 unsigned char *valstr = convert_string_datum(value, valuetypid);
2009 unsigned char *lostr = convert_string_datum(lobound, boundstypid);
2010 unsigned char *histr = convert_string_datum(hibound, boundstypid);
2012 convert_string_to_scalar(valstr, scaledvalue,
2013 lostr, scaledlobound,
2014 histr, scaledhibound);
2022 * Built-in bytea type
2026 convert_bytea_to_scalar(value, scaledvalue,
2027 lobound, scaledlobound,
2028 hibound, scaledhibound);
2033 * Built-in time types
2036 case TIMESTAMPTZOID:
2044 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
2045 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
2046 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
2050 * Built-in network types
2055 *scaledvalue = convert_network_to_scalar(value, valuetypid);
2056 *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
2057 *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
2060 /* Don't know how to convert */
2065 * Do convert_to_scalar()'s work for any numeric data type.
2068 convert_numeric_to_scalar(Datum value, Oid typid)
2073 return (double) DatumGetBool(value);
2075 return (double) DatumGetInt16(value);
2077 return (double) DatumGetInt32(value);
2079 return (double) DatumGetInt64(value);
2081 return (double) DatumGetFloat4(value);
2083 return (double) DatumGetFloat8(value);
2085 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
2087 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
2091 /* we can treat OIDs as integers... */
2092 return (double) DatumGetObjectId(value);
2096 * Can't get here unless someone tries to use scalarltsel/scalargtsel
2097 * on an operator with one numeric and one non-numeric operand.
2099 elog(ERROR, "convert_numeric_to_scalar: unsupported type %u", typid);
2104 * Do convert_to_scalar()'s work for any character-string data type.
2106 * String datatypes are converted to a scale that ranges from 0 to 1,
2107 * where we visualize the bytes of the string as fractional digits.
2109 * We do not want the base to be 256, however, since that tends to
2110 * generate inflated selectivity estimates; few databases will have
2111 * occurrences of all 256 possible byte values at each position.
2112 * Instead, use the smallest and largest byte values seen in the bounds
2113 * as the estimated range for each byte, after some fudging to deal with
2114 * the fact that we probably aren't going to see the full range that way.
2116 * An additional refinement is that we discard any common prefix of the
2117 * three strings before computing the scaled values. This allows us to
2118 * "zoom in" when we encounter a narrow data range. An example is a phone
2119 * number database where all the values begin with the same area code.
2120 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
2121 * so this is more likely to happen than you might think.)
2124 convert_string_to_scalar(unsigned char *value,
2125 double *scaledvalue,
2126 unsigned char *lobound,
2127 double *scaledlobound,
2128 unsigned char *hibound,
2129 double *scaledhibound)
2133 unsigned char *sptr;
2135 rangelo = rangehi = hibound[0];
2136 for (sptr = lobound; *sptr; sptr++)
2138 if (rangelo > *sptr)
2140 if (rangehi < *sptr)
2143 for (sptr = hibound; *sptr; sptr++)
2145 if (rangelo > *sptr)
2147 if (rangehi < *sptr)
2150 /* If range includes any upper-case ASCII chars, make it include all */
2151 if (rangelo <= 'Z' && rangehi >= 'A')
2158 /* Ditto lower-case */
2159 if (rangelo <= 'z' && rangehi >= 'a')
2167 if (rangelo <= '9' && rangehi >= '0')
2176 * If range includes less than 10 chars, assume we have not got enough
2177 * data, and make it include regular ASCII set.
2179 if (rangehi - rangelo < 9)
2186 * Now strip any common prefix of the three strings.
2190 if (*lobound != *hibound || *lobound != *value)
2192 lobound++, hibound++, value++;
2196 * Now we can do the conversions.
2198 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
2199 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
2200 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
2204 convert_one_string_to_scalar(unsigned char *value, int rangelo, int rangehi)
2206 int slen = strlen((char *) value);
2212 return 0.0; /* empty string has scalar value 0 */
2215 * Since base is at least 10, need not consider more than about 20
2221 /* Convert initial characters to fraction */
2222 base = rangehi - rangelo + 1;
2231 else if (ch > rangehi)
2233 num += ((double) (ch - rangelo)) / denom;
2241 * Convert a string-type Datum into a palloc'd, null-terminated string.
2243 * If USE_LOCALE is defined, we must pass the string through strxfrm()
2244 * before continuing, so as to generate correct locale-specific results.
2246 static unsigned char *
2247 convert_string_datum(Datum value, Oid typid)
2260 val = (char *) palloc(2);
2261 val[0] = DatumGetChar(value);
2268 char *str = (char *) VARDATA(DatumGetPointer(value));
2269 int strlength = VARSIZE(DatumGetPointer(value)) - VARHDRSZ;
2271 val = (char *) palloc(strlength + 1);
2272 memcpy(val, str, strlength);
2273 val[strlength] = '\0';
2278 NameData *nm = (NameData *) DatumGetPointer(value);
2280 val = pstrdup(NameStr(*nm));
2286 * Can't get here unless someone tries to use scalarltsel on
2287 * an operator with one string and one non-string operand.
2289 elog(ERROR, "convert_string_datum: unsupported type %u", typid);
2294 /* Guess that transformed string is not much bigger than original */
2295 xfrmsize = strlen(val) + 32; /* arbitrary pad value here... */
2296 xfrmstr = (char *) palloc(xfrmsize);
2297 xfrmlen = strxfrm(xfrmstr, val, xfrmsize);
2298 if (xfrmlen >= xfrmsize)
2300 /* Oops, didn't make it */
2302 xfrmstr = (char *) palloc(xfrmlen + 1);
2303 xfrmlen = strxfrm(xfrmstr, val, xfrmlen + 1);
2309 return (unsigned char *) val;
2313 * Do convert_to_scalar()'s work for any bytea data type.
2315 * Very similar to convert_string_to_scalar except we can't assume
2316 * null-termination and therefore pass explicit lengths around.
2318 * Also, assumptions about likely "normal" ranges of characters have been
2319 * removed - a data range of 0..255 is always used, for now. (Perhaps
2320 * someday we will add information about actual byte data range to
2324 convert_bytea_to_scalar(Datum value,
2325 double *scaledvalue,
2327 double *scaledlobound,
2329 double *scaledhibound)
2333 valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
2334 loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
2335 hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
2338 unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
2339 *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
2340 *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
2343 * Assume bytea data is uniformly distributed across all byte values.
2349 * Now strip any common prefix of the three strings.
2351 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
2352 for (i = 0; i < minlen; i++)
2354 if (*lostr != *histr || *lostr != *valstr)
2356 lostr++, histr++, valstr++;
2357 loboundlen--, hiboundlen--, valuelen--;
2361 * Now we can do the conversions.
2363 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
2364 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
2365 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
2369 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
2370 int rangelo, int rangehi)
2377 return 0.0; /* empty string has scalar value 0 */
2380 * Since base is 256, need not consider more than about 10 chars (even
2381 * this many seems like overkill)
2386 /* Convert initial characters to fraction */
2387 base = rangehi - rangelo + 1;
2390 while (valuelen-- > 0)
2396 else if (ch > rangehi)
2398 num += ((double) (ch - rangelo)) / denom;
2406 * Do convert_to_scalar()'s work for any timevalue data type.
2409 convert_timevalue_to_scalar(Datum value, Oid typid)
2414 return DatumGetTimestamp(value);
2415 case TIMESTAMPTZOID:
2416 return DatumGetTimestampTz(value);
2418 return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
2421 return DatumGetTimestamp(DirectFunctionCall1(date_timestamp,
2425 Interval *interval = DatumGetIntervalP(value);
2428 * Convert the month part of Interval to days using
2429 * assumed average month length of 365.25/12.0 days. Not
2430 * too accurate, but plenty good enough for our purposes.
2432 return interval->time +
2433 interval->month * (365.25 / 12.0 * 24.0 * 60.0 * 60.0);
2436 return DatumGetRelativeTime(value);
2439 TimeInterval interval = DatumGetTimeInterval(value);
2441 if (interval->status != 0)
2442 return interval->data[1] - interval->data[0];
2443 return 0; /* for lack of a better idea */
2446 return DatumGetTimeADT(value);
2449 TimeTzADT *timetz = DatumGetTimeTzADTP(value);
2451 /* use GMT-equivalent time */
2452 return (double) (timetz->time + timetz->zone);
2457 * Can't get here unless someone tries to use scalarltsel/scalargtsel
2458 * on an operator with one timevalue and one non-timevalue operand.
2460 elog(ERROR, "convert_timevalue_to_scalar: unsupported type %u", typid);
2466 * get_att_numdistinct
2467 * Estimate the number of distinct values of an attribute.
2469 * var: identifies the attribute to examine.
2470 * stats: pg_statistic tuple for attribute, or NULL if not available.
2472 * NB: be careful to produce an integral result, since callers may compare
2473 * the result to exact integer counts.
2476 get_att_numdistinct(Query *root, Var *var, Form_pg_statistic stats)
2482 * Special-case boolean columns: presumably, two distinct values.
2484 * Are there any other cases we should wire in special estimates for?
2486 if (var->vartype == BOOLOID)
2490 * Otherwise we need to get the relation size.
2492 rel = find_base_rel(root, var->varno);
2493 ntuples = rel->tuples;
2496 return DEFAULT_NUM_DISTINCT; /* no data available; return a
2500 * Look to see if there is a unique index on the attribute. If so, we
2501 * assume it's distinct, ignoring pg_statistic info which could be out
2504 if (has_unique_index(rel, var->varattno))
2508 * If ANALYZE determined a fixed or scaled estimate, use it.
2512 if (stats->stadistinct > 0.0)
2513 return stats->stadistinct;
2514 if (stats->stadistinct < 0.0)
2515 return floor((-stats->stadistinct * ntuples) + 0.5);
2519 * ANALYZE does not compute stats for system attributes, but some of
2520 * them can reasonably be assumed unique anyway.
2522 switch (var->varattno)
2524 case ObjectIdAttributeNumber:
2525 case SelfItemPointerAttributeNumber:
2527 case TableOidAttributeNumber:
2532 * Estimate ndistinct = ntuples if the table is small, else use
2535 if (ntuples < DEFAULT_NUM_DISTINCT)
2538 return DEFAULT_NUM_DISTINCT;
2542 * get_restriction_var
2543 * Examine the args of a restriction clause to see if it's of the
2544 * form (var op something) or (something op var). If so, extract
2545 * and return the var and the other argument.
2548 * args: clause argument list
2549 * varRelid: see specs for restriction selectivity functions
2551 * Outputs: (these are set only if TRUE is returned)
2552 * *var: gets Var node
2553 * *other: gets other clause argument
2554 * *varonleft: set TRUE if var is on the left, FALSE if on the right
2556 * Returns TRUE if a Var is identified, otherwise FALSE.
2559 get_restriction_var(List *args,
2568 if (length(args) != 2)
2571 left = (Node *) lfirst(args);
2572 right = (Node *) lsecond(args);
2574 /* Ignore any binary-compatible relabeling */
2576 if (IsA(left, RelabelType))
2577 left = ((RelabelType *) left)->arg;
2578 if (IsA(right, RelabelType))
2579 right = ((RelabelType *) right)->arg;
2581 /* Look for the var */
2583 if (IsA(left, Var) &&
2584 (varRelid == 0 || varRelid == ((Var *) left)->varno))
2586 *var = (Var *) left;
2590 else if (IsA(right, Var) &&
2591 (varRelid == 0 || varRelid == ((Var *) right)->varno))
2593 *var = (Var *) right;
2599 /* Duh, it's too complicated for me... */
2609 * Extract the two Vars from a join clause's argument list. Returns
2610 * NULL for arguments that are not simple vars.
2613 get_join_vars(List *args, Var **var1, Var **var2)
2618 if (length(args) != 2)
2625 left = (Node *) lfirst(args);
2626 right = (Node *) lsecond(args);
2628 /* Ignore any binary-compatible relabeling */
2629 if (IsA(left, RelabelType))
2630 left = ((RelabelType *) left)->arg;
2631 if (IsA(right, RelabelType))
2632 right = ((RelabelType *) right)->arg;
2635 *var1 = (Var *) left;
2639 if (IsA(right, Var))
2640 *var2 = (Var *) right;
2645 /*-------------------------------------------------------------------------
2647 * Pattern analysis functions
2649 * These routines support analysis of LIKE and regular-expression patterns
2650 * by the planner/optimizer. It's important that they agree with the
2651 * regular-expression code in backend/regex/ and the LIKE code in
2652 * backend/utils/adt/like.c.
2654 * Note that the prefix-analysis functions are called from
2655 * backend/optimizer/path/indxpath.c as well as from routines in this file.
2657 *-------------------------------------------------------------------------
2661 * Extract the fixed prefix, if any, for a pattern.
2662 * *prefix is set to a palloc'd prefix string,
2663 * or to NULL if no fixed prefix exists for the pattern.
2664 * *rest is set to point to the remainder of the pattern after the
2665 * portion describing the fixed prefix.
2666 * The return value distinguishes no fixed prefix, a partial prefix,
2667 * or an exact-match-only pattern.
2670 static Pattern_Prefix_Status
2671 like_fixed_prefix(char *patt, bool case_insensitive,
2672 char **prefix, char **rest)
2678 *prefix = match = palloc(strlen(patt) + 1);
2681 for (pos = 0; patt[pos]; pos++)
2683 /* % and _ are wildcard characters in LIKE */
2684 if (patt[pos] == '%' ||
2687 /* Backslash quotes the next character */
2688 if (patt[pos] == '\\')
2691 if (patt[pos] == '\0')
2696 * XXX I suspect isalpha() is not an adequately locale-sensitive
2697 * test for characters that can vary under case folding?
2699 if (case_insensitive && isalpha((unsigned char) patt[pos]))
2703 * NOTE: this code used to think that %% meant a literal %, but
2704 * textlike() itself does not think that, and the SQL92 spec
2705 * doesn't say any such thing either.
2707 match[match_pos++] = patt[pos];
2710 match[match_pos] = '\0';
2713 /* in LIKE, an empty pattern is an exact match! */
2714 if (patt[pos] == '\0')
2715 return Pattern_Prefix_Exact; /* reached end of pattern, so
2719 return Pattern_Prefix_Partial;
2723 return Pattern_Prefix_None;
2726 static Pattern_Prefix_Status
2727 regex_fixed_prefix(char *patt, bool case_insensitive,
2728 char **prefix, char **rest)
2735 /* Pattern must be anchored left */
2740 return Pattern_Prefix_None;
2744 * If unquoted | is present at paren level 0 in pattern, then there
2745 * are multiple alternatives for the start of the string.
2748 for (pos = 1; patt[pos]; pos++)
2750 if (patt[pos] == '|' && paren_depth == 0)
2754 return Pattern_Prefix_None;
2756 else if (patt[pos] == '(')
2758 else if (patt[pos] == ')' && paren_depth > 0)
2760 else if (patt[pos] == '\\')
2762 /* backslash quotes the next character */
2764 if (patt[pos] == '\0')
2769 /* OK, allocate space for pattern */
2770 *prefix = match = palloc(strlen(patt) + 1);
2773 /* note start at pos 1 to skip leading ^ */
2774 for (pos = 1; patt[pos]; pos++)
2777 * Check for characters that indicate multiple possible matches
2778 * here. XXX I suspect isalpha() is not an adequately
2779 * locale-sensitive test for characters that can vary under case
2782 if (patt[pos] == '.' ||
2786 (case_insensitive && isalpha((unsigned char) patt[pos])))
2790 * Check for quantifiers. Except for +, this means the preceding
2791 * character is optional, so we must remove it from the prefix
2794 if (patt[pos] == '*' ||
2803 if (patt[pos] == '+')
2808 if (patt[pos] == '\\')
2810 /* backslash quotes the next character */
2812 if (patt[pos] == '\0')
2815 match[match_pos++] = patt[pos];
2818 match[match_pos] = '\0';
2821 if (patt[pos] == '$' && patt[pos + 1] == '\0')
2823 *rest = &patt[pos + 1];
2824 return Pattern_Prefix_Exact; /* pattern specifies exact match */
2828 return Pattern_Prefix_Partial;
2832 return Pattern_Prefix_None;
2835 Pattern_Prefix_Status
2836 pattern_fixed_prefix(char *patt, Pattern_Type ptype,
2837 char **prefix, char **rest)
2839 Pattern_Prefix_Status result;
2843 case Pattern_Type_Like:
2844 result = like_fixed_prefix(patt, false, prefix, rest);
2846 case Pattern_Type_Like_IC:
2847 result = like_fixed_prefix(patt, true, prefix, rest);
2849 case Pattern_Type_Regex:
2850 result = regex_fixed_prefix(patt, false, prefix, rest);
2852 case Pattern_Type_Regex_IC:
2853 result = regex_fixed_prefix(patt, true, prefix, rest);
2856 elog(ERROR, "pattern_fixed_prefix: bogus ptype");
2857 result = Pattern_Prefix_None; /* keep compiler quiet */
2864 * Estimate the selectivity of a fixed prefix for a pattern match.
2866 * A fixed prefix "foo" is estimated as the selectivity of the expression
2867 * "var >= 'foo' AND var < 'fop'" (see also indxqual.c).
2869 * XXX Note: we make use of the upper bound to estimate operator selectivity
2870 * even if the locale is such that we cannot rely on the upper-bound string.
2871 * The selectivity only needs to be approximately right anyway, so it seems
2872 * more useful to use the upper-bound code than not.
2875 prefix_selectivity(Query *root, Var *var, char *prefix)
2877 Selectivity prefixsel;
2883 cmpopr = find_operator(">=", var->vartype);
2884 if (cmpopr == InvalidOid)
2885 elog(ERROR, "prefix_selectivity: no >= operator for type %u",
2887 prefixcon = string_to_const(prefix, var->vartype);
2888 cmpargs = makeList2(var, prefixcon);
2889 /* Assume scalargtsel is appropriate for all supported types */
2890 prefixsel = DatumGetFloat8(DirectFunctionCall4(scalargtsel,
2891 PointerGetDatum(root),
2892 ObjectIdGetDatum(cmpopr),
2893 PointerGetDatum(cmpargs),
2897 * If we can create a string larger than the prefix, say
2901 greaterstr = make_greater_string(prefix, var->vartype);
2906 cmpopr = find_operator("<", var->vartype);
2907 if (cmpopr == InvalidOid)
2908 elog(ERROR, "prefix_selectivity: no < operator for type %u",
2910 prefixcon = string_to_const(greaterstr, var->vartype);
2911 cmpargs = makeList2(var, prefixcon);
2912 /* Assume scalarltsel is appropriate for all supported types */
2913 topsel = DatumGetFloat8(DirectFunctionCall4(scalarltsel,
2914 PointerGetDatum(root),
2915 ObjectIdGetDatum(cmpopr),
2916 PointerGetDatum(cmpargs),
2920 * Merge the two selectivities in the same way as for a range
2921 * query (see clauselist_selectivity()).
2923 prefixsel = topsel + prefixsel - 1.0;
2926 * A zero or slightly negative prefixsel should be converted into
2927 * a small positive value; we probably are dealing with a very
2928 * tight range and got a bogus result due to roundoff errors.
2929 * However, if prefixsel is very negative, then we probably have
2930 * default selectivity estimates on one or both sides of the
2931 * range. In that case, insert a not-so-wildly-optimistic default
2934 if (prefixsel <= 0.0)
2936 if (prefixsel < -0.01)
2939 * No data available --- use a default estimate that is
2940 * small, but not real small.
2947 * It's just roundoff error; use a small positive value
2949 prefixsel = 1.0e-10;
2959 * Estimate the selectivity of a pattern of the specified type.
2960 * Note that any fixed prefix of the pattern will have been removed already.
2962 * For now, we use a very simplistic approach: fixed characters reduce the
2963 * selectivity a good deal, character ranges reduce it a little,
2964 * wildcards (such as % for LIKE or .* for regex) increase it.
2967 #define FIXED_CHAR_SEL 0.04 /* about 1/25 */
2968 #define CHAR_RANGE_SEL 0.25
2969 #define ANY_CHAR_SEL 0.9 /* not 1, since it won't match
2971 #define FULL_WILDCARD_SEL 5.0
2972 #define PARTIAL_WILDCARD_SEL 2.0
2975 like_selectivity(char *patt, bool case_insensitive)
2977 Selectivity sel = 1.0;
2980 /* Skip any leading %; it's already factored into initial sel */
2981 pos = (*patt == '%') ? 1 : 0;
2982 for (; patt[pos]; pos++)
2984 /* % and _ are wildcard characters in LIKE */
2985 if (patt[pos] == '%')
2986 sel *= FULL_WILDCARD_SEL;
2987 else if (patt[pos] == '_')
2988 sel *= ANY_CHAR_SEL;
2989 else if (patt[pos] == '\\')
2991 /* Backslash quotes the next character */
2993 if (patt[pos] == '\0')
2995 sel *= FIXED_CHAR_SEL;
2998 sel *= FIXED_CHAR_SEL;
3000 /* Could get sel > 1 if multiple wildcards */
3007 regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive)
3009 Selectivity sel = 1.0;
3010 int paren_depth = 0;
3011 int paren_pos = 0; /* dummy init to keep compiler quiet */
3014 for (pos = 0; pos < pattlen; pos++)
3016 if (patt[pos] == '(')
3018 if (paren_depth == 0)
3019 paren_pos = pos; /* remember start of parenthesized item */
3022 else if (patt[pos] == ')' && paren_depth > 0)
3025 if (paren_depth == 0)
3026 sel *= regex_selectivity_sub(patt + (paren_pos + 1),
3027 pos - (paren_pos + 1),
3030 else if (patt[pos] == '|' && paren_depth == 0)
3033 * If unquoted | is present at paren level 0 in pattern, we
3034 * have multiple alternatives; sum their probabilities.
3036 sel += regex_selectivity_sub(patt + (pos + 1),
3037 pattlen - (pos + 1),
3039 break; /* rest of pattern is now processed */
3041 else if (patt[pos] == '[')
3043 bool negclass = false;
3045 if (patt[++pos] == '^')
3050 if (patt[pos] == ']') /* ']' at start of class is not
3053 while (pos < pattlen && patt[pos] != ']')
3055 if (paren_depth == 0)
3056 sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
3058 else if (patt[pos] == '.')
3060 if (paren_depth == 0)
3061 sel *= ANY_CHAR_SEL;
3063 else if (patt[pos] == '*' ||
3067 /* Ought to be smarter about quantifiers... */
3068 if (paren_depth == 0)
3069 sel *= PARTIAL_WILDCARD_SEL;
3071 else if (patt[pos] == '{')
3073 while (pos < pattlen && patt[pos] != '}')
3075 if (paren_depth == 0)
3076 sel *= PARTIAL_WILDCARD_SEL;
3078 else if (patt[pos] == '\\')
3080 /* backslash quotes the next character */
3084 if (paren_depth == 0)
3085 sel *= FIXED_CHAR_SEL;
3089 if (paren_depth == 0)
3090 sel *= FIXED_CHAR_SEL;
3093 /* Could get sel > 1 if multiple wildcards */
3100 regex_selectivity(char *patt, bool case_insensitive)
3103 int pattlen = strlen(patt);
3105 /* If patt doesn't end with $, consider it to have a trailing wildcard */
3106 if (pattlen > 0 && patt[pattlen - 1] == '$' &&
3107 (pattlen == 1 || patt[pattlen - 2] != '\\'))
3109 /* has trailing $ */
3110 sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
3115 sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
3116 sel *= FULL_WILDCARD_SEL;
3124 pattern_selectivity(char *patt, Pattern_Type ptype)
3130 case Pattern_Type_Like:
3131 result = like_selectivity(patt, false);
3133 case Pattern_Type_Like_IC:
3134 result = like_selectivity(patt, true);
3136 case Pattern_Type_Regex:
3137 result = regex_selectivity(patt, false);
3139 case Pattern_Type_Regex_IC:
3140 result = regex_selectivity(patt, true);
3143 elog(ERROR, "pattern_selectivity: bogus ptype");
3144 result = 1.0; /* keep compiler quiet */
3151 * Test whether the database's LOCALE setting is safe for LIKE/regexp index
3152 * optimization. The key requirement here is that given a prefix string,
3153 * say "foo", we must be able to generate another string "fop" that is
3154 * greater than all strings "foobar" starting with "foo". Unfortunately,
3155 * many non-C locales have bizarre collation rules in which "fop" > "foo"
3156 * is not sufficient to ensure "fop" > "foobar". Until we can come up
3157 * with a more bulletproof way of generating the upper-bound string,
3158 * disable the optimization in locales where it is not known to be safe.
3161 locale_is_like_safe(void)
3164 /* Cache result so we only have to compute it once */
3165 static int result = -1;
3169 return (bool) result;
3170 localeptr = setlocale(LC_COLLATE, NULL);
3172 elog(STOP, "Invalid LC_COLLATE setting");
3175 * Currently we accept only "C" and "POSIX" (do any systems still
3176 * return "POSIX"?). Which other locales allow safe optimization?
3178 if (strcmp(localeptr, "C") == 0)
3180 else if (strcmp(localeptr, "POSIX") == 0)
3184 return (bool) result;
3185 #else /* not USE_LOCALE */
3186 return true; /* We must be in C locale, which is OK */
3187 #endif /* USE_LOCALE */
3191 * Try to generate a string greater than the given string or any string it is
3192 * a prefix of. If successful, return a palloc'd string; else return NULL.
3194 * To work correctly in non-ASCII locales with weird collation orders,
3195 * we cannot simply increment "foo" to "fop" --- we have to check whether
3196 * we actually produced a string greater than the given one. If not,
3197 * increment the righthand byte again and repeat. If we max out the righthand
3198 * byte, truncate off the last character and start incrementing the next.
3199 * For example, if "z" were the last character in the sort order, then we
3200 * could produce "foo" as a string greater than "fonz".
3202 * This could be rather slow in the worst case, but in most cases we won't
3203 * have to try more than one or two strings before succeeding.
3205 * XXX this is actually not sufficient, since it only copes with the case
3206 * where individual characters collate in an order different from their
3207 * numeric code assignments. It does not handle cases where there are
3208 * cross-character effects, such as specially sorted digraphs, multiple
3209 * sort passes, etc. For now, we just shut down the whole thing in locales
3210 * that do such things :-(
3213 make_greater_string(const char *str, Oid datatype)
3219 * Make a modifiable copy, which will be our return value if
3222 workstr = pstrdup((char *) str);
3224 while ((len = strlen(workstr)) > 0)
3226 unsigned char *lastchar = (unsigned char *) (workstr + len - 1);
3229 * Try to generate a larger string by incrementing the last byte.
3231 while (*lastchar < (unsigned char) 255)
3234 if (string_lessthan(str, workstr, datatype))
3235 return workstr; /* Success! */
3239 * Truncate off the last character, which might be more than 1
3240 * byte in MULTIBYTE case.
3243 len = pg_mbcliplen((const unsigned char *) workstr, len, len - 1);
3244 workstr[len] = '\0';
3256 * Test whether two strings are "<" according to the rules of the given
3257 * datatype. We do this the hard way, ie, actually calling the type's
3258 * "<" operator function, to ensure we get the right result...
3261 string_lessthan(const char *str1, const char *str2, Oid datatype)
3263 Datum datum1 = string_to_datum(str1, datatype);
3264 Datum datum2 = string_to_datum(str2, datatype);
3270 result = DatumGetBool(DirectFunctionCall2(text_lt,
3275 result = DatumGetBool(DirectFunctionCall2(bpcharlt,
3280 result = DatumGetBool(DirectFunctionCall2(varcharlt,
3285 result = DatumGetBool(DirectFunctionCall2(namelt,
3290 result = DatumGetBool(DirectFunctionCall2(bytealt,
3295 elog(ERROR, "string_lessthan: unexpected datatype %u", datatype);
3300 pfree(DatumGetPointer(datum1));
3301 pfree(DatumGetPointer(datum2));
3306 /* See if there is a binary op of the given name for the given datatype */
3308 find_operator(const char *opname, Oid datatype)
3310 return GetSysCacheOid(OPERNAME,
3311 PointerGetDatum(opname),
3312 ObjectIdGetDatum(datatype),
3313 ObjectIdGetDatum(datatype),
3318 * Generate a Datum of the appropriate type from a C string.
3319 * Note that all of the supported types are pass-by-ref, so the
3320 * returned value should be pfree'd if no longer needed.
3323 string_to_datum(const char *str, Oid datatype)
3326 * We cheat a little by assuming that textin() will do for bpchar and
3327 * varchar constants too...
3329 if (datatype == NAMEOID)
3330 return DirectFunctionCall1(namein, CStringGetDatum(str));
3332 return DirectFunctionCall1(textin, CStringGetDatum(str));
3336 * Generate a Const node of the appropriate type from a C string.
3339 string_to_const(const char *str, Oid datatype)
3341 Datum conval = string_to_datum(str, datatype);
3343 return makeConst(datatype, ((datatype == NAMEOID) ? NAMEDATALEN : -1),
3344 conval, false, false, false, false);
3347 /*-------------------------------------------------------------------------
3349 * Index cost estimation functions
3351 * genericcostestimate is a general-purpose estimator for use when we
3352 * don't have any better idea about how to estimate. Index-type-specific
3353 * knowledge can be incorporated in the type-specific routines.
3355 *-------------------------------------------------------------------------
3359 genericcostestimate(Query *root, RelOptInfo *rel,
3360 IndexOptInfo *index, List *indexQuals,
3361 Cost *indexStartupCost,
3362 Cost *indexTotalCost,
3363 Selectivity *indexSelectivity,
3364 double *indexCorrelation)
3366 double numIndexTuples;
3367 double numIndexPages;
3368 List *selectivityQuals = indexQuals;
3371 * If the index is partial, AND the index predicate with the
3372 * explicitly given indexquals to produce a more accurate idea of the
3373 * index restriction. This may produce redundant clauses, which we
3374 * hope that cnfify and clauselist_selectivity will deal with
3377 * Note that index->indpred and indexQuals are both in implicit-AND form
3378 * to start with, which we have to make explicit to hand to
3379 * canonicalize_qual, and then we get back implicit-AND form again.
3381 if (index->indpred != NIL)
3385 andedQuals = make_ands_explicit(nconc(listCopy(index->indpred),
3387 selectivityQuals = canonicalize_qual(andedQuals, true);
3390 /* Estimate the fraction of main-table tuples that will be visited */
3391 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
3392 lfirsti(rel->relids));
3395 * Estimate the number of tuples that will be visited. We do it in
3396 * this rather peculiar-looking way in order to get the right answer
3397 * for partial indexes. We can bound the number of tuples by the
3398 * index size, in any case.
3400 numIndexTuples = *indexSelectivity * rel->tuples;
3402 if (numIndexTuples > index->tuples)
3403 numIndexTuples = index->tuples;
3406 * Always estimate at least one tuple is touched, even when
3407 * indexSelectivity estimate is tiny.
3409 if (numIndexTuples < 1.0)
3410 numIndexTuples = 1.0;
3413 * Estimate the number of index pages that will be retrieved.
3415 * For all currently-supported index types, the first page of the index
3416 * is a metadata page, and we should figure on fetching that plus a
3417 * pro-rated fraction of the remaining pages.
3419 if (index->pages > 1 && index->tuples > 0)
3421 numIndexPages = (numIndexTuples / index->tuples) * (index->pages - 1);
3422 numIndexPages += 1; /* count the metapage too */
3423 numIndexPages = ceil(numIndexPages);
3426 numIndexPages = 1.0;
3429 * Compute the index access cost.
3431 * Our generic assumption is that the index pages will be read
3432 * sequentially, so they have cost 1.0 each, not random_page_cost.
3433 * Also, we charge for evaluation of the indexquals at each index
3434 * tuple. All the costs are assumed to be paid incrementally during
3437 *indexStartupCost = 0;
3438 *indexTotalCost = numIndexPages +
3439 (cpu_index_tuple_cost + cost_qual_eval(indexQuals)) * numIndexTuples;
3442 * Generic assumption about index correlation: there isn't any.
3444 *indexCorrelation = 0.0;
3449 btcostestimate(PG_FUNCTION_ARGS)
3451 Query *root = (Query *) PG_GETARG_POINTER(0);
3452 RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
3453 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
3454 List *indexQuals = (List *) PG_GETARG_POINTER(3);
3455 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
3456 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
3457 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
3458 double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
3460 genericcostestimate(root, rel, index, indexQuals,
3461 indexStartupCost, indexTotalCost,
3462 indexSelectivity, indexCorrelation);
3465 * If it's a functional index, leave the default zero-correlation
3466 * estimate in place. If not, and if we can get an estimate for the
3467 * first variable's ordering correlation C from pg_statistic, estimate
3468 * the index correlation as C / number-of-columns. (The idea here is
3469 * that multiple columns dilute the importance of the first column's
3470 * ordering, but don't negate it entirely.)
3472 if (index->indproc == InvalidOid)
3477 relid = getrelid(lfirsti(rel->relids), root->rtable);
3478 Assert(relid != InvalidOid);
3479 tuple = SearchSysCache(STATRELATT,
3480 ObjectIdGetDatum(relid),
3481 Int16GetDatum(index->indexkeys[0]),
3483 if (HeapTupleIsValid(tuple))
3490 get_atttypetypmod(relid, index->indexkeys[0],
3492 if (get_attstatsslot(tuple, typid, typmod,
3493 STATISTIC_KIND_CORRELATION,
3495 NULL, NULL, &numbers, &nnumbers))
3497 double varCorrelation;
3500 Assert(nnumbers == 1);
3501 varCorrelation = numbers[0];
3502 for (nKeys = 1; index->indexkeys[nKeys] != 0; nKeys++)
3505 *indexCorrelation = varCorrelation / nKeys;
3507 free_attstatsslot(typid, NULL, 0, numbers, nnumbers);
3509 ReleaseSysCache(tuple);
3517 rtcostestimate(PG_FUNCTION_ARGS)
3519 Query *root = (Query *) PG_GETARG_POINTER(0);
3520 RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
3521 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
3522 List *indexQuals = (List *) PG_GETARG_POINTER(3);
3523 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
3524 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
3525 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
3526 double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
3528 genericcostestimate(root, rel, index, indexQuals,
3529 indexStartupCost, indexTotalCost,
3530 indexSelectivity, indexCorrelation);
3536 hashcostestimate(PG_FUNCTION_ARGS)
3538 Query *root = (Query *) PG_GETARG_POINTER(0);
3539 RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
3540 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
3541 List *indexQuals = (List *) PG_GETARG_POINTER(3);
3542 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
3543 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
3544 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
3545 double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
3547 genericcostestimate(root, rel, index, indexQuals,
3548 indexStartupCost, indexTotalCost,
3549 indexSelectivity, indexCorrelation);
3555 gistcostestimate(PG_FUNCTION_ARGS)
3557 Query *root = (Query *) PG_GETARG_POINTER(0);
3558 RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
3559 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
3560 List *indexQuals = (List *) PG_GETARG_POINTER(3);
3561 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
3562 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
3563 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
3564 double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
3566 genericcostestimate(root, rel, index, indexQuals,
3567 indexStartupCost, indexTotalCost,
3568 indexSelectivity, indexCorrelation);