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.107 2002/04/03 05:39:31 petere 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);
75 #include "access/heapam.h"
76 #include "catalog/catname.h"
77 #include "catalog/pg_operator.h"
78 #include "catalog/pg_proc.h"
79 #include "catalog/pg_statistic.h"
80 #include "catalog/pg_type.h"
81 #include "mb/pg_wchar.h"
82 #include "nodes/makefuncs.h"
83 #include "optimizer/clauses.h"
84 #include "optimizer/cost.h"
85 #include "optimizer/pathnode.h"
86 #include "optimizer/plancat.h"
87 #include "optimizer/prep.h"
88 #include "parser/parse_func.h"
89 #include "parser/parse_oper.h"
90 #include "parser/parsetree.h"
91 #include "utils/builtins.h"
92 #include "utils/date.h"
93 #include "utils/datum.h"
94 #include "utils/int8.h"
95 #include "utils/lsyscache.h"
96 #include "utils/pg_locale.h"
97 #include "utils/selfuncs.h"
98 #include "utils/syscache.h"
102 * Note: the default selectivity estimates are not chosen entirely at random.
103 * We want them to be small enough to ensure that indexscans will be used if
104 * available, for typical table densities of ~100 tuples/page. Thus, for
105 * example, 0.01 is not quite small enough, since that makes it appear that
106 * nearly all pages will be hit anyway. Also, since we sometimes estimate
107 * eqsel as 1/num_distinct, we probably want DEFAULT_NUM_DISTINCT to equal
111 /* default selectivity estimate for equalities such as "A = b" */
112 #define DEFAULT_EQ_SEL 0.005
114 /* default selectivity estimate for inequalities such as "A < b" */
115 #define DEFAULT_INEQ_SEL (1.0 / 3.0)
117 /* default selectivity estimate for pattern-match operators such as LIKE */
118 #define DEFAULT_MATCH_SEL 0.005
120 /* default number of distinct values in a table */
121 #define DEFAULT_NUM_DISTINCT 200
123 /* default selectivity estimate for boolean and null test nodes */
124 #define DEFAULT_UNK_SEL 0.005
125 #define DEFAULT_NOT_UNK_SEL (1.0 - DEFAULT_UNK_SEL)
126 #define DEFAULT_BOOL_SEL 0.5
129 * Clamp a computed probability estimate (which may suffer from roundoff or
130 * estimation errors) to valid range. Argument must be a float variable.
132 #define CLAMP_PROBABILITY(p) \
141 static bool get_var_maximum(Query *root, Var *var, Oid sortop, Datum *max);
142 static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
143 Datum lobound, Datum hibound, Oid boundstypid,
144 double *scaledlobound, double *scaledhibound);
145 static double convert_numeric_to_scalar(Datum value, Oid typid);
146 static void convert_string_to_scalar(unsigned char *value,
148 unsigned char *lobound,
149 double *scaledlobound,
150 unsigned char *hibound,
151 double *scaledhibound);
152 static void convert_bytea_to_scalar(Datum value,
155 double *scaledlobound,
157 double *scaledhibound);
158 static double convert_one_string_to_scalar(unsigned char *value,
159 int rangelo, int rangehi);
160 static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
161 int rangelo, int rangehi);
162 static unsigned char *convert_string_datum(Datum value, Oid typid);
163 static double convert_timevalue_to_scalar(Datum value, Oid typid);
164 static double get_att_numdistinct(Query *root, Var *var,
165 Form_pg_statistic stats);
166 static bool get_restriction_var(List *args, int varRelid,
167 Var **var, Node **other,
169 static void get_join_vars(List *args, Var **var1, Var **var2);
170 static Selectivity prefix_selectivity(Query *root, Var *var, char *prefix);
171 static Selectivity pattern_selectivity(char *patt, Pattern_Type ptype);
172 static bool string_lessthan(const char *str1, const char *str2,
174 static Oid find_operator(const char *opname, Oid datatype);
175 static Datum string_to_datum(const char *str, Oid datatype);
176 static Const *string_to_const(const char *str, Oid datatype);
180 * eqsel - Selectivity of "=" for any data types.
182 * Note: this routine is also used to estimate selectivity for some
183 * operators that are not "=" but have comparable selectivity behavior,
184 * such as "~=" (geometric approximate-match). Even for "=", we must
185 * keep in mind that the left and right datatypes may differ.
188 eqsel(PG_FUNCTION_ARGS)
190 Query *root = (Query *) PG_GETARG_POINTER(0);
191 Oid operator = PG_GETARG_OID(1);
192 List *args = (List *) PG_GETARG_POINTER(2);
193 int varRelid = PG_GETARG_INT32(3);
198 HeapTuple statsTuple;
206 * If expression is not var = something or something = var for a
207 * simple var of a real relation (no subqueries, for now), then punt
208 * and return a default estimate.
210 if (!get_restriction_var(args, varRelid,
211 &var, &other, &varonleft))
212 PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
213 relid = getrelid(var->varno, root->rtable);
214 if (relid == InvalidOid)
215 PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
218 * If the something is a NULL constant, assume operator is strict and
219 * return zero, ie, operator will never return TRUE.
221 if (IsA(other, Const) &&((Const *) other)->constisnull)
222 PG_RETURN_FLOAT8(0.0);
224 /* get stats for the attribute, if available */
225 statsTuple = SearchSysCache(STATRELATT,
226 ObjectIdGetDatum(relid),
227 Int16GetDatum(var->varattno),
229 if (HeapTupleIsValid(statsTuple))
231 Form_pg_statistic stats;
233 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
235 if (IsA(other, Const))
237 /* Var is being compared to a known non-null constant */
238 Datum constval = ((Const *) other)->constvalue;
243 * Is the constant "=" to any of the column's most common
244 * values? (Although the given operator may not really be
245 * "=", we will assume that seeing whether it returns TRUE is
246 * an appropriate test. If you don't like this, maybe you
247 * shouldn't be using eqsel for your operator...)
249 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
250 STATISTIC_KIND_MCV, InvalidOid,
252 &numbers, &nnumbers))
256 fmgr_info(get_opcode(operator), &eqproc);
258 for (i = 0; i < nvalues; i++)
260 /* be careful to apply operator right way 'round */
262 match = DatumGetBool(FunctionCall2(&eqproc,
266 match = DatumGetBool(FunctionCall2(&eqproc,
275 /* no most-common-value info available */
278 i = nvalues = nnumbers = 0;
284 * Constant is "=" to this common value. We know
285 * selectivity exactly (or as exactly as VACUUM could
286 * calculate it, anyway).
293 * Comparison is against a constant that is neither NULL
294 * nor any of the common values. Its selectivity cannot
297 double sumcommon = 0.0;
298 double otherdistinct;
300 for (i = 0; i < nnumbers; i++)
301 sumcommon += numbers[i];
302 selec = 1.0 - sumcommon - stats->stanullfrac;
303 CLAMP_PROBABILITY(selec);
306 * and in fact it's probably a good deal less. We
307 * approximate that all the not-common values share this
308 * remaining fraction equally, so we divide by the number
309 * of other distinct values.
311 otherdistinct = get_att_numdistinct(root, var, stats)
313 if (otherdistinct > 1)
314 selec /= otherdistinct;
317 * Another cross-check: selectivity shouldn't be estimated
318 * as more than the least common "most common value".
320 if (nnumbers > 0 && selec > numbers[nnumbers - 1])
321 selec = numbers[nnumbers - 1];
324 free_attstatsslot(var->vartype, values, nvalues,
332 * Search is for a value that we do not know a priori, but we
333 * will assume it is not NULL. Estimate the selectivity as
334 * non-null fraction divided by number of distinct values, so
335 * that we get a result averaged over all possible values
336 * whether common or uncommon. (Essentially, we are assuming
337 * that the not-yet-known comparison value is equally likely
338 * to be any of the possible values, regardless of their
339 * frequency in the table. Is that a good idea?)
341 selec = 1.0 - stats->stanullfrac;
342 ndistinct = get_att_numdistinct(root, var, stats);
347 * Cross-check: selectivity should never be estimated as more
348 * than the most common value's.
350 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
351 STATISTIC_KIND_MCV, InvalidOid,
353 &numbers, &nnumbers))
355 if (nnumbers > 0 && selec > numbers[0])
357 free_attstatsslot(var->vartype, NULL, 0, numbers, nnumbers);
361 ReleaseSysCache(statsTuple);
366 * No VACUUM ANALYZE stats available, so make a guess using
367 * estimated number of distinct values and assuming they are
368 * equally common. (The guess is unlikely to be very good, but we
369 * do know a few special cases.)
371 selec = 1.0 / get_att_numdistinct(root, var, NULL);
374 /* result should be in range, but make sure... */
375 CLAMP_PROBABILITY(selec);
377 PG_RETURN_FLOAT8((float8) selec);
381 * neqsel - Selectivity of "!=" for any data types.
383 * This routine is also used for some operators that are not "!="
384 * but have comparable selectivity behavior. See above comments
388 neqsel(PG_FUNCTION_ARGS)
390 Query *root = (Query *) PG_GETARG_POINTER(0);
391 Oid operator = PG_GETARG_OID(1);
392 List *args = (List *) PG_GETARG_POINTER(2);
393 int varRelid = PG_GETARG_INT32(3);
398 * We want 1 - eqsel() where the equality operator is the one
399 * associated with this != operator, that is, its negator.
401 eqop = get_negator(operator);
404 result = DatumGetFloat8(DirectFunctionCall4(eqsel,
405 PointerGetDatum(root),
406 ObjectIdGetDatum(eqop),
407 PointerGetDatum(args),
408 Int32GetDatum(varRelid)));
412 /* Use default selectivity (should we raise an error instead?) */
413 result = DEFAULT_EQ_SEL;
415 result = 1.0 - result;
416 PG_RETURN_FLOAT8(result);
420 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
422 * This is the guts of both scalarltsel and scalargtsel. The caller has
423 * commuted the clause, if necessary, so that we can treat the Var as
424 * being on the left. The caller must also make sure that the other side
425 * of the clause is a non-null Const, and dissect same into a value and
428 * This routine works for any datatype (or pair of datatypes) known to
429 * convert_to_scalar(). If it is applied to some other datatype,
430 * it will return a default estimate.
433 scalarineqsel(Query *root, Oid operator, bool isgt,
434 Var *var, Datum constval, Oid consttype)
437 HeapTuple statsTuple;
438 Form_pg_statistic stats;
451 * If expression is not var op something or something op var for a
452 * simple var of a real relation (no subqueries, for now), then punt
453 * and return a default estimate.
455 relid = getrelid(var->varno, root->rtable);
456 if (relid == InvalidOid)
457 return DEFAULT_INEQ_SEL;
459 /* get stats for the attribute */
460 statsTuple = SearchSysCache(STATRELATT,
461 ObjectIdGetDatum(relid),
462 Int16GetDatum(var->varattno),
464 if (!HeapTupleIsValid(statsTuple))
466 /* no stats available, so default result */
467 return DEFAULT_INEQ_SEL;
469 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
471 fmgr_info(get_opcode(operator), &opproc);
474 * If we have most-common-values info, add up the fractions of the MCV
475 * entries that satisfy MCV OP CONST. These fractions contribute
476 * directly to the result selectivity. Also add up the total fraction
477 * represented by MCV entries.
482 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
483 STATISTIC_KIND_MCV, InvalidOid,
485 &numbers, &nnumbers))
487 for (i = 0; i < nvalues; i++)
489 if (DatumGetBool(FunctionCall2(&opproc,
492 mcv_selec += numbers[i];
493 sumcommon += numbers[i];
495 free_attstatsslot(var->vartype, values, nvalues, numbers, nnumbers);
499 * If there is a histogram, determine which bin the constant falls in,
500 * and compute the resulting contribution to selectivity.
502 * Someday, VACUUM might store more than one histogram per rel/att,
503 * corresponding to more than one possible sort ordering defined for
504 * the column type. However, to make that work we will need to figure
505 * out which staop to search for --- it's not necessarily the one we
506 * have at hand! (For example, we might have a '<=' operator rather
507 * than the '<' operator that will appear in staop.) For now, assume
508 * that whatever appears in pg_statistic is sorted the same way our
509 * operator sorts, or the reverse way if isgt is TRUE.
513 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
514 STATISTIC_KIND_HISTOGRAM, InvalidOid,
523 ltcmp = DatumGetBool(FunctionCall2(&opproc,
530 /* Constant is below lower histogram boundary. */
536 * Scan to find proper location. This could be made
537 * faster by using a binary-search method, but it's
538 * probably not worth the trouble for typical histogram
541 for (i = 1; i < nvalues; i++)
543 ltcmp = DatumGetBool(FunctionCall2(&opproc,
553 /* Constant is above upper histogram boundary. */
564 * We have values[i-1] < constant < values[i].
566 * Convert the constant and the two nearest bin boundary
567 * values to a uniform comparison scale, and do a
568 * linear interpolation within this bin.
570 if (convert_to_scalar(constval, consttype, &val,
571 values[i - 1], values[i],
577 /* cope if bin boundaries appear identical */
582 else if (val >= high)
586 binfrac = (val - low) / (high - low);
589 * Watch out for the possibility that we got a
590 * NaN or Infinity from the division. This
591 * can happen despite the previous checks, if
592 * for example "low" is -Infinity.
594 if (isnan(binfrac) ||
595 binfrac < 0.0 || binfrac > 1.0)
602 * Ideally we'd produce an error here, on the
603 * grounds that the given operator shouldn't have
604 * scalarXXsel registered as its selectivity func
605 * unless we can deal with its operand types. But
606 * currently, all manner of stuff is invoking
607 * scalarXXsel, so give a default estimate until
614 * Now, compute the overall selectivity across the
615 * values represented by the histogram. We have i-1
616 * full bins and binfrac partial bin below the
619 histfrac = (double) (i - 1) + binfrac;
620 histfrac /= (double) (nvalues - 1);
625 * Now histfrac = fraction of histogram entries below the
628 * Account for "<" vs ">"
630 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
633 * The histogram boundaries are only approximate to begin
634 * with, and may well be out of date anyway. Therefore, don't
635 * believe extremely small or large selectivity estimates.
637 if (hist_selec < 0.0001)
639 else if (hist_selec > 0.9999)
643 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
647 * Now merge the results from the MCV and histogram calculations,
648 * realizing that the histogram covers only the non-null values that
649 * are not listed in MCV.
651 selec = 1.0 - stats->stanullfrac - sumcommon;
653 if (hist_selec > 0.0)
658 * If no histogram but there are values not accounted for by MCV,
659 * arbitrarily assume half of them will match.
666 ReleaseSysCache(statsTuple);
668 /* result should be in range, but make sure... */
669 CLAMP_PROBABILITY(selec);
675 * scalarltsel - Selectivity of "<" (also "<=") for scalars.
678 scalarltsel(PG_FUNCTION_ARGS)
680 Query *root = (Query *) PG_GETARG_POINTER(0);
681 Oid operator = PG_GETARG_OID(1);
682 List *args = (List *) PG_GETARG_POINTER(2);
683 int varRelid = PG_GETARG_INT32(3);
693 * If expression is not var op something or something op var for a
694 * simple var of a real relation (no subqueries, for now), then punt
695 * and return a default estimate.
697 if (!get_restriction_var(args, varRelid,
698 &var, &other, &varonleft))
699 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
702 * Can't do anything useful if the something is not a constant,
705 if (!IsA(other, Const))
706 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
709 * If the constant is NULL, assume operator is strict and return zero,
710 * ie, operator will never return TRUE.
712 if (((Const *) other)->constisnull)
713 PG_RETURN_FLOAT8(0.0);
714 constval = ((Const *) other)->constvalue;
715 consttype = ((Const *) other)->consttype;
718 * Force the var to be on the left to simplify logic in scalarineqsel.
722 /* we have var < other */
727 /* we have other < var, commute to make var > other */
728 operator = get_commutator(operator);
731 /* Use default selectivity (should we raise an error instead?) */
732 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
737 selec = scalarineqsel(root, operator, isgt, var, constval, consttype);
739 PG_RETURN_FLOAT8((float8) selec);
743 * scalargtsel - Selectivity of ">" (also ">=") for integers.
746 scalargtsel(PG_FUNCTION_ARGS)
748 Query *root = (Query *) PG_GETARG_POINTER(0);
749 Oid operator = PG_GETARG_OID(1);
750 List *args = (List *) PG_GETARG_POINTER(2);
751 int varRelid = PG_GETARG_INT32(3);
761 * If expression is not var op something or something op var for a
762 * simple var of a real relation (no subqueries, for now), then punt
763 * and return a default estimate.
765 if (!get_restriction_var(args, varRelid,
766 &var, &other, &varonleft))
767 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
770 * Can't do anything useful if the something is not a constant,
773 if (!IsA(other, Const))
774 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
777 * If the constant is NULL, assume operator is strict and return zero,
778 * ie, operator will never return TRUE.
780 if (((Const *) other)->constisnull)
781 PG_RETURN_FLOAT8(0.0);
782 constval = ((Const *) other)->constvalue;
783 consttype = ((Const *) other)->consttype;
786 * Force the var to be on the left to simplify logic in scalarineqsel.
790 /* we have var > other */
795 /* we have other > var, commute to make var < other */
796 operator = get_commutator(operator);
799 /* Use default selectivity (should we raise an error instead?) */
800 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
805 selec = scalarineqsel(root, operator, isgt, var, constval, consttype);
807 PG_RETURN_FLOAT8((float8) selec);
811 * patternsel - Generic code for pattern-match selectivity.
814 patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype)
816 Query *root = (Query *) PG_GETARG_POINTER(0);
819 Oid operator = PG_GETARG_OID(1);
821 List *args = (List *) PG_GETARG_POINTER(2);
822 int varRelid = PG_GETARG_INT32(3);
829 Pattern_Prefix_Status pstatus;
835 * If expression is not var op constant for a simple var of a real
836 * relation (no subqueries, for now), then punt and return a default
839 if (!get_restriction_var(args, varRelid,
840 &var, &other, &varonleft))
841 return DEFAULT_MATCH_SEL;
842 if (!varonleft || !IsA(other, Const))
843 return DEFAULT_MATCH_SEL;
844 relid = getrelid(var->varno, root->rtable);
845 if (relid == InvalidOid)
846 return DEFAULT_MATCH_SEL;
849 * If the constant is NULL, assume operator is strict and return zero,
850 * ie, operator will never return TRUE.
852 if (((Const *) other)->constisnull)
854 constval = ((Const *) other)->constvalue;
855 /* the right-hand const is type text for all supported operators */
856 Assert(((Const *) other)->consttype == TEXTOID);
857 patt = DatumGetCString(DirectFunctionCall1(textout, constval));
859 /* divide pattern into fixed prefix and remainder */
860 pstatus = pattern_fixed_prefix(patt, ptype, &prefix, &rest);
862 if (pstatus == Pattern_Prefix_Exact)
865 * Pattern specifies an exact match, so pretend operator is '='
867 Oid eqopr = find_operator("=", var->vartype);
871 if (eqopr == InvalidOid)
872 elog(ERROR, "patternsel: no = operator for type %u",
874 eqcon = string_to_const(prefix, var->vartype);
875 eqargs = makeList2(var, eqcon);
876 result = DatumGetFloat8(DirectFunctionCall4(eqsel,
877 PointerGetDatum(root),
878 ObjectIdGetDatum(eqopr),
879 PointerGetDatum(eqargs),
880 Int32GetDatum(varRelid)));
885 * Not exact-match pattern. We estimate selectivity of the fixed
886 * prefix and remainder of pattern separately, then combine the
889 Selectivity prefixsel;
893 if (pstatus == Pattern_Prefix_Partial)
894 prefixsel = prefix_selectivity(root, var, prefix);
897 restsel = pattern_selectivity(rest, ptype);
898 selec = prefixsel * restsel;
899 /* result should be in range, but make sure... */
900 CLAMP_PROBABILITY(selec);
912 * regexeqsel - Selectivity of regular-expression pattern match.
915 regexeqsel(PG_FUNCTION_ARGS)
917 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex));
921 * icregexeqsel - Selectivity of case-insensitive regex match.
924 icregexeqsel(PG_FUNCTION_ARGS)
926 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC));
930 * likesel - Selectivity of LIKE pattern match.
933 likesel(PG_FUNCTION_ARGS)
935 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like));
939 * iclikesel - Selectivity of ILIKE pattern match.
942 iclikesel(PG_FUNCTION_ARGS)
944 PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC));
948 * regexnesel - Selectivity of regular-expression pattern non-match.
951 regexnesel(PG_FUNCTION_ARGS)
955 result = patternsel(fcinfo, Pattern_Type_Regex);
956 result = 1.0 - result;
957 PG_RETURN_FLOAT8(result);
961 * icregexnesel - Selectivity of case-insensitive regex non-match.
964 icregexnesel(PG_FUNCTION_ARGS)
968 result = patternsel(fcinfo, Pattern_Type_Regex_IC);
969 result = 1.0 - result;
970 PG_RETURN_FLOAT8(result);
974 * nlikesel - Selectivity of LIKE pattern non-match.
977 nlikesel(PG_FUNCTION_ARGS)
981 result = patternsel(fcinfo, Pattern_Type_Like);
982 result = 1.0 - result;
983 PG_RETURN_FLOAT8(result);
987 * icnlikesel - Selectivity of ILIKE pattern non-match.
990 icnlikesel(PG_FUNCTION_ARGS)
994 result = patternsel(fcinfo, Pattern_Type_Like_IC);
995 result = 1.0 - result;
996 PG_RETURN_FLOAT8(result);
1000 * booltestsel - Selectivity of BooleanTest Node.
1003 booltestsel(Query *root, BooleanTest *clause, int varRelid)
1008 HeapTuple statsTuple;
1015 Assert(clause && IsA(clause, BooleanTest));
1017 arg = (Node *) clause->arg;
1020 * Ignore any binary-compatible relabeling (probably unnecessary, but
1023 if (IsA(arg, RelabelType))
1024 arg = ((RelabelType *) arg)->arg;
1026 if (IsA(arg, Var) &&(varRelid == 0 || varRelid == ((Var *) arg)->varno))
1031 * If argument is not a Var, we can't get statistics for it, but
1032 * perhaps clause_selectivity can do something with it. We ignore
1033 * the possibility of a NULL value when using clause_selectivity,
1034 * and just assume the value is either TRUE or FALSE.
1036 switch (clause->booltesttype)
1039 selec = DEFAULT_UNK_SEL;
1041 case IS_NOT_UNKNOWN:
1042 selec = DEFAULT_NOT_UNK_SEL;
1046 selec = (double) clause_selectivity(root, arg, varRelid);
1050 selec = 1.0 - (double) clause_selectivity(root, arg, varRelid);
1053 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1054 (int) clause->booltesttype);
1055 selec = 0.0; /* Keep compiler quiet */
1058 return (Selectivity) selec;
1061 /* get stats for the attribute, if available */
1062 relid = getrelid(var->varno, root->rtable);
1063 if (relid == InvalidOid)
1066 statsTuple = SearchSysCache(STATRELATT,
1067 ObjectIdGetDatum(relid),
1068 Int16GetDatum(var->varattno),
1071 if (HeapTupleIsValid(statsTuple))
1073 Form_pg_statistic stats;
1076 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
1078 freq_null = stats->stanullfrac;
1080 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1081 STATISTIC_KIND_MCV, InvalidOid,
1083 &numbers, &nnumbers)
1090 * Get first MCV frequency and derive frequency for true.
1092 if (DatumGetBool(values[0]))
1093 freq_true = numbers[0];
1095 freq_true = 1.0 - numbers[0] - freq_null;
1098 * Next derive freqency for false. Then use these as
1099 * appropriate to derive frequency for each case.
1101 freq_false = 1.0 - freq_true - freq_null;
1103 switch (clause->booltesttype)
1106 /* select only NULL values */
1109 case IS_NOT_UNKNOWN:
1110 /* select non-NULL values */
1111 selec = 1.0 - freq_null;
1114 /* select only TRUE values */
1118 /* select non-TRUE values */
1119 selec = 1.0 - freq_true;
1122 /* select only FALSE values */
1126 /* select non-FALSE values */
1127 selec = 1.0 - freq_false;
1130 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1131 (int) clause->booltesttype);
1132 selec = 0.0; /* Keep compiler quiet */
1136 free_attstatsslot(var->vartype, values, nvalues,
1142 * No most-common-value info available. Still have null
1143 * fraction information, so use it for IS [NOT] UNKNOWN.
1144 * Otherwise adjust for null fraction and assume an even split
1145 * for boolean tests.
1147 switch (clause->booltesttype)
1152 * Use freq_null directly.
1156 case IS_NOT_UNKNOWN:
1159 * Select not unknown (not null) values. Calculate
1162 selec = 1.0 - freq_null;
1168 selec = (1.0 - freq_null) / 2.0;
1171 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1172 (int) clause->booltesttype);
1173 selec = 0.0; /* Keep compiler quiet */
1178 ReleaseSysCache(statsTuple);
1183 * No VACUUM ANALYZE stats available, so use a default value.
1184 * (Note: not much point in recursing to clause_selectivity here.)
1186 switch (clause->booltesttype)
1189 selec = DEFAULT_UNK_SEL;
1191 case IS_NOT_UNKNOWN:
1192 selec = DEFAULT_NOT_UNK_SEL;
1198 selec = DEFAULT_BOOL_SEL;
1201 elog(ERROR, "booltestsel: unexpected booltesttype %d",
1202 (int) clause->booltesttype);
1203 selec = 0.0; /* Keep compiler quiet */
1208 /* result should be in range, but make sure... */
1209 CLAMP_PROBABILITY(selec);
1211 return (Selectivity) selec;
1215 * nulltestsel - Selectivity of NullTest Node.
1218 nulltestsel(Query *root, NullTest *clause, int varRelid)
1223 HeapTuple statsTuple;
1228 Assert(clause && IsA(clause, NullTest));
1230 switch (clause->nulltesttype)
1233 defselec = DEFAULT_UNK_SEL;
1236 defselec = DEFAULT_NOT_UNK_SEL;
1239 elog(ERROR, "nulltestsel: unexpected nulltesttype %d",
1240 (int) clause->nulltesttype);
1241 return (Selectivity) 0; /* keep compiler quiet */
1244 arg = (Node *) clause->arg;
1247 * Ignore any binary-compatible relabeling
1249 if (IsA(arg, RelabelType))
1250 arg = ((RelabelType *) arg)->arg;
1252 if (IsA(arg, Var) &&(varRelid == 0 || varRelid == ((Var *) arg)->varno))
1257 * punt if non-Var argument
1259 return (Selectivity) defselec;
1262 relid = getrelid(var->varno, root->rtable);
1263 if (relid == InvalidOid)
1264 return (Selectivity) defselec;
1266 /* get stats for the attribute, if available */
1267 statsTuple = SearchSysCache(STATRELATT,
1268 ObjectIdGetDatum(relid),
1269 Int16GetDatum(var->varattno),
1271 if (HeapTupleIsValid(statsTuple))
1273 Form_pg_statistic stats;
1275 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
1276 freq_null = stats->stanullfrac;
1278 switch (clause->nulltesttype)
1283 * Use freq_null directly.
1290 * Select not unknown (not null) values. Calculate from
1293 selec = 1.0 - freq_null;
1296 elog(ERROR, "nulltestsel: unexpected nulltesttype %d",
1297 (int) clause->nulltesttype);
1298 return (Selectivity) 0; /* keep compiler quiet */
1301 ReleaseSysCache(statsTuple);
1306 * No VACUUM ANALYZE stats available, so make a guess
1311 /* result should be in range, but make sure... */
1312 CLAMP_PROBABILITY(selec);
1314 return (Selectivity) selec;
1318 * eqjoinsel - Join selectivity of "="
1321 eqjoinsel(PG_FUNCTION_ARGS)
1323 Query *root = (Query *) PG_GETARG_POINTER(0);
1324 Oid operator = PG_GETARG_OID(1);
1325 List *args = (List *) PG_GETARG_POINTER(2);
1330 get_join_vars(args, &var1, &var2);
1332 if (var1 == NULL && var2 == NULL)
1333 selec = DEFAULT_EQ_SEL;
1336 HeapTuple statsTuple1 = NULL;
1337 HeapTuple statsTuple2 = NULL;
1338 Form_pg_statistic stats1 = NULL;
1339 Form_pg_statistic stats2 = NULL;
1340 double nd1 = DEFAULT_NUM_DISTINCT;
1341 double nd2 = DEFAULT_NUM_DISTINCT;
1342 bool have_mcvs1 = false;
1343 Datum *values1 = NULL;
1345 float4 *numbers1 = NULL;
1347 bool have_mcvs2 = false;
1348 Datum *values2 = NULL;
1350 float4 *numbers2 = NULL;
1355 /* get stats for the attribute, if available */
1356 Oid relid1 = getrelid(var1->varno, root->rtable);
1358 if (relid1 != InvalidOid)
1360 statsTuple1 = SearchSysCache(STATRELATT,
1361 ObjectIdGetDatum(relid1),
1362 Int16GetDatum(var1->varattno),
1364 if (HeapTupleIsValid(statsTuple1))
1366 stats1 = (Form_pg_statistic) GETSTRUCT(statsTuple1);
1367 have_mcvs1 = get_attstatsslot(statsTuple1,
1372 &values1, &nvalues1,
1373 &numbers1, &nnumbers1);
1376 nd1 = get_att_numdistinct(root, var1, stats1);
1382 /* get stats for the attribute, if available */
1383 Oid relid2 = getrelid(var2->varno, root->rtable);
1385 if (relid2 != InvalidOid)
1387 statsTuple2 = SearchSysCache(STATRELATT,
1388 ObjectIdGetDatum(relid2),
1389 Int16GetDatum(var2->varattno),
1391 if (HeapTupleIsValid(statsTuple2))
1393 stats2 = (Form_pg_statistic) GETSTRUCT(statsTuple2);
1394 have_mcvs2 = get_attstatsslot(statsTuple2,
1399 &values2, &nvalues2,
1400 &numbers2, &nnumbers2);
1403 nd2 = get_att_numdistinct(root, var2, stats2);
1407 if (have_mcvs1 && have_mcvs2)
1410 * We have most-common-value lists for both relations. Run
1411 * through the lists to see which MCVs actually join to each
1412 * other with the given operator. This allows us to determine
1413 * the exact join selectivity for the portion of the relations
1414 * represented by the MCV lists. We still have to estimate
1415 * for the remaining population, but in a skewed distribution
1416 * this gives us a big leg up in accuracy. For motivation see
1417 * the analysis in Y. Ioannidis and S. Christodoulakis, "On
1418 * the propagation of errors in the size of join results",
1419 * Technical Report 1018, Computer Science Dept., University
1420 * of Wisconsin, Madison, March 1991 (available from
1426 double matchprodfreq,
1438 fmgr_info(get_opcode(operator), &eqproc);
1439 hasmatch1 = (bool *) palloc(nvalues1 * sizeof(bool));
1440 memset(hasmatch1, 0, nvalues1 * sizeof(bool));
1441 hasmatch2 = (bool *) palloc(nvalues2 * sizeof(bool));
1442 memset(hasmatch2, 0, nvalues2 * sizeof(bool));
1445 * Note we assume that each MCV will match at most one member
1446 * of the other MCV list. If the operator isn't really
1447 * equality, there could be multiple matches --- but we don't
1448 * look for them, both for speed and because the math wouldn't
1451 matchprodfreq = 0.0;
1453 for (i = 0; i < nvalues1; i++)
1457 for (j = 0; j < nvalues2; j++)
1461 if (DatumGetBool(FunctionCall2(&eqproc,
1465 hasmatch1[i] = hasmatch2[j] = true;
1466 matchprodfreq += numbers1[i] * numbers2[j];
1472 CLAMP_PROBABILITY(matchprodfreq);
1473 /* Sum up frequencies of matched and unmatched MCVs */
1474 matchfreq1 = unmatchfreq1 = 0.0;
1475 for (i = 0; i < nvalues1; i++)
1478 matchfreq1 += numbers1[i];
1480 unmatchfreq1 += numbers1[i];
1482 CLAMP_PROBABILITY(matchfreq1);
1483 CLAMP_PROBABILITY(unmatchfreq1);
1484 matchfreq2 = unmatchfreq2 = 0.0;
1485 for (i = 0; i < nvalues2; i++)
1488 matchfreq2 += numbers2[i];
1490 unmatchfreq2 += numbers2[i];
1492 CLAMP_PROBABILITY(matchfreq2);
1493 CLAMP_PROBABILITY(unmatchfreq2);
1498 * Compute total frequency of non-null values that are not in
1501 otherfreq1 = 1.0 - stats1->stanullfrac - matchfreq1 - unmatchfreq1;
1502 otherfreq2 = 1.0 - stats2->stanullfrac - matchfreq2 - unmatchfreq2;
1503 CLAMP_PROBABILITY(otherfreq1);
1504 CLAMP_PROBABILITY(otherfreq2);
1507 * We can estimate the total selectivity from the point of
1508 * view of relation 1 as: the known selectivity for matched
1509 * MCVs, plus unmatched MCVs that are assumed to match against
1510 * random members of relation 2's non-MCV population, plus
1511 * non-MCV values that are assumed to match against random
1512 * members of relation 2's unmatched MCVs plus non-MCV values.
1514 totalsel1 = matchprodfreq;
1516 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
1518 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
1520 /* Same estimate from the point of view of relation 2. */
1521 totalsel2 = matchprodfreq;
1523 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
1525 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
1529 * Use the smaller of the two estimates. This can be
1530 * justified in essentially the same terms as given below for
1531 * the no-stats case: to a first approximation, we are
1532 * estimating from the point of view of the relation with
1535 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
1540 * We do not have MCV lists for both sides. Estimate the join
1541 * selectivity as MIN(1/nd1, 1/nd2). This is plausible if we
1542 * assume that the values are about equally distributed: a
1543 * given tuple of rel1 will join to either 0 or N2/nd2 rows of
1544 * rel2, so total join rows are at most N1*N2/nd2 giving a
1545 * join selectivity of not more than 1/nd2. By the same logic
1546 * it is not more than 1/nd1, so MIN(1/nd1, 1/nd2) is an upper
1547 * bound. Using the MIN() means we estimate from the point of
1548 * view of the relation with smaller nd (since the larger nd
1549 * is determining the MIN). It is reasonable to assume that
1550 * most tuples in this rel will have join partners, so the
1551 * bound is probably reasonably tight and should be taken
1554 * XXX Can we be smarter if we have an MCV list for just one
1555 * side? It seems that if we assume equal distribution for the
1556 * other side, we end up with the same answer anyway.
1565 free_attstatsslot(var1->vartype, values1, nvalues1,
1566 numbers1, nnumbers1);
1568 free_attstatsslot(var2->vartype, values2, nvalues2,
1569 numbers2, nnumbers2);
1570 if (HeapTupleIsValid(statsTuple1))
1571 ReleaseSysCache(statsTuple1);
1572 if (HeapTupleIsValid(statsTuple2))
1573 ReleaseSysCache(statsTuple2);
1576 CLAMP_PROBABILITY(selec);
1578 PG_RETURN_FLOAT8((float8) selec);
1582 * neqjoinsel - Join selectivity of "!="
1585 neqjoinsel(PG_FUNCTION_ARGS)
1587 Query *root = (Query *) PG_GETARG_POINTER(0);
1588 Oid operator = PG_GETARG_OID(1);
1589 List *args = (List *) PG_GETARG_POINTER(2);
1594 * We want 1 - eqjoinsel() where the equality operator is the one
1595 * associated with this != operator, that is, its negator.
1597 eqop = get_negator(operator);
1600 result = DatumGetFloat8(DirectFunctionCall3(eqjoinsel,
1601 PointerGetDatum(root),
1602 ObjectIdGetDatum(eqop),
1603 PointerGetDatum(args)));
1608 /* Use default selectivity (should we raise an error instead?) */
1609 result = DEFAULT_EQ_SEL;
1611 result = 1.0 - result;
1612 PG_RETURN_FLOAT8(result);
1616 * scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
1619 scalarltjoinsel(PG_FUNCTION_ARGS)
1621 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1625 * scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
1628 scalargtjoinsel(PG_FUNCTION_ARGS)
1630 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1634 * regexeqjoinsel - Join selectivity of regular-expression pattern match.
1637 regexeqjoinsel(PG_FUNCTION_ARGS)
1639 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1643 * icregexeqjoinsel - Join selectivity of case-insensitive regex match.
1646 icregexeqjoinsel(PG_FUNCTION_ARGS)
1648 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1652 * likejoinsel - Join selectivity of LIKE pattern match.
1655 likejoinsel(PG_FUNCTION_ARGS)
1657 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1661 * iclikejoinsel - Join selectivity of ILIKE pattern match.
1664 iclikejoinsel(PG_FUNCTION_ARGS)
1666 PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1670 * regexnejoinsel - Join selectivity of regex non-match.
1673 regexnejoinsel(PG_FUNCTION_ARGS)
1677 result = DatumGetFloat8(regexeqjoinsel(fcinfo));
1678 result = 1.0 - result;
1679 PG_RETURN_FLOAT8(result);
1683 * icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
1686 icregexnejoinsel(PG_FUNCTION_ARGS)
1690 result = DatumGetFloat8(icregexeqjoinsel(fcinfo));
1691 result = 1.0 - result;
1692 PG_RETURN_FLOAT8(result);
1696 * nlikejoinsel - Join selectivity of LIKE pattern non-match.
1699 nlikejoinsel(PG_FUNCTION_ARGS)
1703 result = DatumGetFloat8(likejoinsel(fcinfo));
1704 result = 1.0 - result;
1705 PG_RETURN_FLOAT8(result);
1709 * icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
1712 icnlikejoinsel(PG_FUNCTION_ARGS)
1716 result = DatumGetFloat8(iclikejoinsel(fcinfo));
1717 result = 1.0 - result;
1718 PG_RETURN_FLOAT8(result);
1722 * mergejoinscansel - Scan selectivity of merge join.
1724 * A merge join will stop as soon as it exhausts either input stream.
1725 * Therefore, if we can estimate the ranges of both input variables,
1726 * we can estimate how much of the input will actually be read. This
1727 * can have a considerable impact on the cost when using indexscans.
1729 * clause should be a clause already known to be mergejoinable.
1731 * *leftscan is set to the fraction of the left-hand variable expected
1732 * to be scanned (0 to 1), and similarly *rightscan for the right-hand
1736 mergejoinscansel(Query *root, Node *clause,
1737 Selectivity *leftscan,
1738 Selectivity *rightscan)
1752 /* Set default results if we can't figure anything out. */
1753 *leftscan = *rightscan = 1.0;
1755 /* Deconstruct the merge clause */
1756 if (!is_opclause(clause))
1757 return; /* shouldn't happen */
1758 opno = ((Oper *) ((Expr *) clause)->oper)->opno;
1759 left = get_leftop((Expr *) clause);
1760 right = get_rightop((Expr *) clause);
1762 return; /* shouldn't happen */
1764 /* Can't do anything if inputs are not Vars */
1765 if (!IsA(left, Var) ||!IsA(right, Var))
1768 /* Verify mergejoinability and get left and right "<" operators */
1769 if (!op_mergejoinable(opno,
1774 return; /* shouldn't happen */
1776 /* Try to get maximum values of both vars */
1777 if (!get_var_maximum(root, left, lsortop, &leftmax))
1778 return; /* no max available from stats */
1780 if (!get_var_maximum(root, right, rsortop, &rightmax))
1781 return; /* no max available from stats */
1783 /* Look up the "left < right" and "left > right" operators */
1784 op_mergejoin_crossops(opno, <op, >op, NULL, NULL);
1786 /* Look up the "right < left" operator */
1787 revltop = get_commutator(gtop);
1788 if (!OidIsValid(revltop))
1789 return; /* shouldn't happen */
1792 * Now, the fraction of the left variable that will be scanned is the
1793 * fraction that's <= the right-side maximum value. But only believe
1794 * non-default estimates, else stick with our 1.0.
1796 selec = scalarineqsel(root, ltop, false, left,
1797 rightmax, right->vartype);
1798 if (selec != DEFAULT_INEQ_SEL)
1801 /* And similarly for the right variable. */
1802 selec = scalarineqsel(root, revltop, false, right,
1803 leftmax, left->vartype);
1804 if (selec != DEFAULT_INEQ_SEL)
1808 * Only one of the two fractions can really be less than 1.0; believe
1809 * the smaller estimate and reset the other one to exactly 1.0.
1811 if (*leftscan > *rightscan)
1819 * Estimate the maximum value of the specified variable.
1820 * If successful, store value in *max and return TRUE.
1821 * If no data available, return FALSE.
1823 * sortop is the "<" comparison operator to use. (To extract the
1824 * minimum instead of the maximum, just pass the ">" operator instead.)
1827 get_var_maximum(Query *root, Var *var, Oid sortop, Datum *max)
1830 bool have_max = false;
1832 HeapTuple statsTuple;
1833 Form_pg_statistic stats;
1840 relid = getrelid(var->varno, root->rtable);
1841 if (relid == InvalidOid)
1844 /* get stats for the attribute */
1845 statsTuple = SearchSysCache(STATRELATT,
1846 ObjectIdGetDatum(relid),
1847 Int16GetDatum(var->varattno),
1849 if (!HeapTupleIsValid(statsTuple))
1851 /* no stats available, so default result */
1854 stats = (Form_pg_statistic) GETSTRUCT(statsTuple);
1856 get_typlenbyval(var->vartype, &typLen, &typByVal);
1859 * If there is a histogram, grab the last or first value as appropriate.
1861 * If there is a histogram that is sorted with some other operator
1862 * than the one we want, fail --- this suggests that there is data
1865 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1866 STATISTIC_KIND_HISTOGRAM, sortop,
1872 tmax = datumCopy(values[nvalues-1], typByVal, typLen);
1875 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1879 Oid rsortop = get_commutator(sortop);
1881 if (OidIsValid(rsortop) &&
1882 get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1883 STATISTIC_KIND_HISTOGRAM, rsortop,
1889 tmax = datumCopy(values[0], typByVal, typLen);
1892 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1894 else if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1895 STATISTIC_KIND_HISTOGRAM, InvalidOid,
1899 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1900 ReleaseSysCache(statsTuple);
1906 * If we have most-common-values info, look for a large MCV. This
1907 * is needed even if we also have a histogram, since the histogram
1908 * excludes the MCVs. However, usually the MCVs will not be the
1909 * extreme values, so avoid unnecessary data copying.
1911 if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod,
1912 STATISTIC_KIND_MCV, InvalidOid,
1916 bool large_mcv = false;
1919 fmgr_info(get_opcode(sortop), &opproc);
1921 for (i = 0; i < nvalues; i++)
1926 large_mcv = have_max = true;
1928 else if (DatumGetBool(FunctionCall2(&opproc, tmax, values[i])))
1935 tmax = datumCopy(tmax, typByVal, typLen);
1936 free_attstatsslot(var->vartype, values, nvalues, NULL, 0);
1939 ReleaseSysCache(statsTuple);
1947 * Convert non-NULL values of the indicated types to the comparison
1948 * scale needed by scalarltsel()/scalargtsel().
1949 * Returns "true" if successful.
1951 * XXX this routine is a hack: ideally we should look up the conversion
1952 * subroutines in pg_type.
1954 * All numeric datatypes are simply converted to their equivalent
1955 * "double" values. (NUMERIC values that are outside the range of "double"
1956 * are clamped to +/- HUGE_VAL.)
1958 * String datatypes are converted by convert_string_to_scalar(),
1959 * which is explained below. The reason why this routine deals with
1960 * three values at a time, not just one, is that we need it for strings.
1962 * The bytea datatype is just enough different from strings that it has
1963 * to be treated separately.
1965 * The several datatypes representing absolute times are all converted
1966 * to Timestamp, which is actually a double, and then we just use that
1967 * double value. Note this will give correct results even for the "special"
1968 * values of Timestamp, since those are chosen to compare correctly;
1969 * see timestamp_cmp.
1971 * The several datatypes representing relative times (intervals) are all
1972 * converted to measurements expressed in seconds.
1975 convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
1976 Datum lobound, Datum hibound, Oid boundstypid,
1977 double *scaledlobound, double *scaledhibound)
1982 * Built-in numeric types
1993 *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
1994 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
1995 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
1999 * Built-in string types
2007 unsigned char *valstr = convert_string_datum(value, valuetypid);
2008 unsigned char *lostr = convert_string_datum(lobound, boundstypid);
2009 unsigned char *histr = convert_string_datum(hibound, boundstypid);
2011 convert_string_to_scalar(valstr, scaledvalue,
2012 lostr, scaledlobound,
2013 histr, scaledhibound);
2021 * Built-in bytea type
2025 convert_bytea_to_scalar(value, scaledvalue,
2026 lobound, scaledlobound,
2027 hibound, scaledhibound);
2032 * Built-in time types
2035 case TIMESTAMPTZOID:
2043 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
2044 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
2045 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
2049 * Built-in network types
2054 *scaledvalue = convert_network_to_scalar(value, valuetypid);
2055 *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
2056 *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
2059 /* Don't know how to convert */
2064 * Do convert_to_scalar()'s work for any numeric data type.
2067 convert_numeric_to_scalar(Datum value, Oid typid)
2072 return (double) DatumGetBool(value);
2074 return (double) DatumGetInt16(value);
2076 return (double) DatumGetInt32(value);
2078 return (double) DatumGetInt64(value);
2080 return (double) DatumGetFloat4(value);
2082 return (double) DatumGetFloat8(value);
2084 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
2086 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
2090 /* we can treat OIDs as integers... */
2091 return (double) DatumGetObjectId(value);
2095 * Can't get here unless someone tries to use scalarltsel/scalargtsel
2096 * on an operator with one numeric and one non-numeric operand.
2098 elog(ERROR, "convert_numeric_to_scalar: unsupported type %u", typid);
2103 * Do convert_to_scalar()'s work for any character-string data type.
2105 * String datatypes are converted to a scale that ranges from 0 to 1,
2106 * where we visualize the bytes of the string as fractional digits.
2108 * We do not want the base to be 256, however, since that tends to
2109 * generate inflated selectivity estimates; few databases will have
2110 * occurrences of all 256 possible byte values at each position.
2111 * Instead, use the smallest and largest byte values seen in the bounds
2112 * as the estimated range for each byte, after some fudging to deal with
2113 * the fact that we probably aren't going to see the full range that way.
2115 * An additional refinement is that we discard any common prefix of the
2116 * three strings before computing the scaled values. This allows us to
2117 * "zoom in" when we encounter a narrow data range. An example is a phone
2118 * number database where all the values begin with the same area code.
2119 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
2120 * so this is more likely to happen than you might think.)
2123 convert_string_to_scalar(unsigned char *value,
2124 double *scaledvalue,
2125 unsigned char *lobound,
2126 double *scaledlobound,
2127 unsigned char *hibound,
2128 double *scaledhibound)
2132 unsigned char *sptr;
2134 rangelo = rangehi = hibound[0];
2135 for (sptr = lobound; *sptr; sptr++)
2137 if (rangelo > *sptr)
2139 if (rangehi < *sptr)
2142 for (sptr = hibound; *sptr; sptr++)
2144 if (rangelo > *sptr)
2146 if (rangehi < *sptr)
2149 /* If range includes any upper-case ASCII chars, make it include all */
2150 if (rangelo <= 'Z' && rangehi >= 'A')
2157 /* Ditto lower-case */
2158 if (rangelo <= 'z' && rangehi >= 'a')
2166 if (rangelo <= '9' && rangehi >= '0')
2175 * If range includes less than 10 chars, assume we have not got enough
2176 * data, and make it include regular ASCII set.
2178 if (rangehi - rangelo < 9)
2185 * Now strip any common prefix of the three strings.
2189 if (*lobound != *hibound || *lobound != *value)
2191 lobound++, hibound++, value++;
2195 * Now we can do the conversions.
2197 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
2198 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
2199 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
2203 convert_one_string_to_scalar(unsigned char *value, int rangelo, int rangehi)
2205 int slen = strlen((char *) value);
2211 return 0.0; /* empty string has scalar value 0 */
2214 * Since base is at least 10, need not consider more than about 20
2220 /* Convert initial characters to fraction */
2221 base = rangehi - rangelo + 1;
2230 else if (ch > rangehi)
2232 num += ((double) (ch - rangelo)) / denom;
2240 * Convert a string-type Datum into a palloc'd, null-terminated string.
2242 * When using a non-C locale, we must pass the string through strxfrm()
2243 * before continuing, so as to generate correct locale-specific results.
2245 static unsigned char *
2246 convert_string_datum(Datum value, Oid typid)
2256 val = (char *) palloc(2);
2257 val[0] = DatumGetChar(value);
2264 char *str = (char *) VARDATA(DatumGetPointer(value));
2265 int strlength = VARSIZE(DatumGetPointer(value)) - VARHDRSZ;
2267 val = (char *) palloc(strlength + 1);
2268 memcpy(val, str, strlength);
2269 val[strlength] = '\0';
2274 NameData *nm = (NameData *) DatumGetPointer(value);
2276 val = pstrdup(NameStr(*nm));
2282 * Can't get here unless someone tries to use scalarltsel on
2283 * an operator with one string and one non-string operand.
2285 elog(ERROR, "convert_string_datum: unsupported type %u", typid);
2289 if (!lc_collate_is_c())
2291 /* Guess that transformed string is not much bigger than original */
2292 xfrmsize = strlen(val) + 32; /* arbitrary pad value here... */
2293 xfrmstr = (char *) palloc(xfrmsize);
2294 xfrmlen = strxfrm(xfrmstr, val, xfrmsize);
2295 if (xfrmlen >= xfrmsize)
2297 /* Oops, didn't make it */
2299 xfrmstr = (char *) palloc(xfrmlen + 1);
2300 xfrmlen = strxfrm(xfrmstr, val, xfrmlen + 1);
2306 return (unsigned char *) val;
2310 * Do convert_to_scalar()'s work for any bytea data type.
2312 * Very similar to convert_string_to_scalar except we can't assume
2313 * null-termination and therefore pass explicit lengths around.
2315 * Also, assumptions about likely "normal" ranges of characters have been
2316 * removed - a data range of 0..255 is always used, for now. (Perhaps
2317 * someday we will add information about actual byte data range to
2321 convert_bytea_to_scalar(Datum value,
2322 double *scaledvalue,
2324 double *scaledlobound,
2326 double *scaledhibound)
2330 valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
2331 loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
2332 hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
2335 unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
2336 *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
2337 *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
2340 * Assume bytea data is uniformly distributed across all byte values.
2346 * Now strip any common prefix of the three strings.
2348 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
2349 for (i = 0; i < minlen; i++)
2351 if (*lostr != *histr || *lostr != *valstr)
2353 lostr++, histr++, valstr++;
2354 loboundlen--, hiboundlen--, valuelen--;
2358 * Now we can do the conversions.
2360 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
2361 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
2362 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
2366 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
2367 int rangelo, int rangehi)
2374 return 0.0; /* empty string has scalar value 0 */
2377 * Since base is 256, need not consider more than about 10 chars (even
2378 * this many seems like overkill)
2383 /* Convert initial characters to fraction */
2384 base = rangehi - rangelo + 1;
2387 while (valuelen-- > 0)
2393 else if (ch > rangehi)
2395 num += ((double) (ch - rangelo)) / denom;
2403 * Do convert_to_scalar()'s work for any timevalue data type.
2406 convert_timevalue_to_scalar(Datum value, Oid typid)
2411 return DatumGetTimestamp(value);
2412 case TIMESTAMPTZOID:
2413 return DatumGetTimestampTz(value);
2415 return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
2418 return DatumGetTimestamp(DirectFunctionCall1(date_timestamp,
2422 Interval *interval = DatumGetIntervalP(value);
2425 * Convert the month part of Interval to days using
2426 * assumed average month length of 365.25/12.0 days. Not
2427 * too accurate, but plenty good enough for our purposes.
2429 return interval->time +
2430 interval->month * (365.25 / 12.0 * 24.0 * 60.0 * 60.0);
2433 return DatumGetRelativeTime(value);
2436 TimeInterval interval = DatumGetTimeInterval(value);
2438 if (interval->status != 0)
2439 return interval->data[1] - interval->data[0];
2440 return 0; /* for lack of a better idea */
2443 return DatumGetTimeADT(value);
2446 TimeTzADT *timetz = DatumGetTimeTzADTP(value);
2448 /* use GMT-equivalent time */
2449 return (double) (timetz->time + timetz->zone);
2454 * Can't get here unless someone tries to use scalarltsel/scalargtsel
2455 * on an operator with one timevalue and one non-timevalue operand.
2457 elog(ERROR, "convert_timevalue_to_scalar: unsupported type %u", typid);
2463 * get_att_numdistinct
2464 * Estimate the number of distinct values of an attribute.
2466 * var: identifies the attribute to examine.
2467 * stats: pg_statistic tuple for attribute, or NULL if not available.
2469 * NB: be careful to produce an integral result, since callers may compare
2470 * the result to exact integer counts.
2473 get_att_numdistinct(Query *root, Var *var, Form_pg_statistic stats)
2479 * Special-case boolean columns: presumably, two distinct values.
2481 * Are there any other cases we should wire in special estimates for?
2483 if (var->vartype == BOOLOID)
2487 * Otherwise we need to get the relation size.
2489 rel = find_base_rel(root, var->varno);
2490 ntuples = rel->tuples;
2493 return DEFAULT_NUM_DISTINCT; /* no data available; return a
2497 * Look to see if there is a unique index on the attribute. If so, we
2498 * assume it's distinct, ignoring pg_statistic info which could be out
2501 if (has_unique_index(rel, var->varattno))
2505 * If ANALYZE determined a fixed or scaled estimate, use it.
2509 if (stats->stadistinct > 0.0)
2510 return stats->stadistinct;
2511 if (stats->stadistinct < 0.0)
2512 return floor((-stats->stadistinct * ntuples) + 0.5);
2516 * ANALYZE does not compute stats for system attributes, but some of
2517 * them can reasonably be assumed unique anyway.
2519 switch (var->varattno)
2521 case ObjectIdAttributeNumber:
2522 case SelfItemPointerAttributeNumber:
2524 case TableOidAttributeNumber:
2529 * Estimate ndistinct = ntuples if the table is small, else use
2532 if (ntuples < DEFAULT_NUM_DISTINCT)
2535 return DEFAULT_NUM_DISTINCT;
2539 * get_restriction_var
2540 * Examine the args of a restriction clause to see if it's of the
2541 * form (var op something) or (something op var). If so, extract
2542 * and return the var and the other argument.
2545 * args: clause argument list
2546 * varRelid: see specs for restriction selectivity functions
2548 * Outputs: (these are set only if TRUE is returned)
2549 * *var: gets Var node
2550 * *other: gets other clause argument
2551 * *varonleft: set TRUE if var is on the left, FALSE if on the right
2553 * Returns TRUE if a Var is identified, otherwise FALSE.
2556 get_restriction_var(List *args,
2565 if (length(args) != 2)
2568 left = (Node *) lfirst(args);
2569 right = (Node *) lsecond(args);
2571 /* Ignore any binary-compatible relabeling */
2573 if (IsA(left, RelabelType))
2574 left = ((RelabelType *) left)->arg;
2575 if (IsA(right, RelabelType))
2576 right = ((RelabelType *) right)->arg;
2578 /* Look for the var */
2580 if (IsA(left, Var) &&
2581 (varRelid == 0 || varRelid == ((Var *) left)->varno))
2583 *var = (Var *) left;
2587 else if (IsA(right, Var) &&
2588 (varRelid == 0 || varRelid == ((Var *) right)->varno))
2590 *var = (Var *) right;
2596 /* Duh, it's too complicated for me... */
2606 * Extract the two Vars from a join clause's argument list. Returns
2607 * NULL for arguments that are not simple vars.
2610 get_join_vars(List *args, Var **var1, Var **var2)
2615 if (length(args) != 2)
2622 left = (Node *) lfirst(args);
2623 right = (Node *) lsecond(args);
2625 /* Ignore any binary-compatible relabeling */
2626 if (IsA(left, RelabelType))
2627 left = ((RelabelType *) left)->arg;
2628 if (IsA(right, RelabelType))
2629 right = ((RelabelType *) right)->arg;
2632 *var1 = (Var *) left;
2636 if (IsA(right, Var))
2637 *var2 = (Var *) right;
2642 /*-------------------------------------------------------------------------
2644 * Pattern analysis functions
2646 * These routines support analysis of LIKE and regular-expression patterns
2647 * by the planner/optimizer. It's important that they agree with the
2648 * regular-expression code in backend/regex/ and the LIKE code in
2649 * backend/utils/adt/like.c.
2651 * Note that the prefix-analysis functions are called from
2652 * backend/optimizer/path/indxpath.c as well as from routines in this file.
2654 *-------------------------------------------------------------------------
2658 * Extract the fixed prefix, if any, for a pattern.
2659 * *prefix is set to a palloc'd prefix string,
2660 * or to NULL if no fixed prefix exists for the pattern.
2661 * *rest is set to point to the remainder of the pattern after the
2662 * portion describing the fixed prefix.
2663 * The return value distinguishes no fixed prefix, a partial prefix,
2664 * or an exact-match-only pattern.
2667 static Pattern_Prefix_Status
2668 like_fixed_prefix(char *patt, bool case_insensitive,
2669 char **prefix, char **rest)
2675 *prefix = match = palloc(strlen(patt) + 1);
2678 for (pos = 0; patt[pos]; pos++)
2680 /* % and _ are wildcard characters in LIKE */
2681 if (patt[pos] == '%' ||
2684 /* Backslash quotes the next character */
2685 if (patt[pos] == '\\')
2688 if (patt[pos] == '\0')
2693 * XXX I suspect isalpha() is not an adequately locale-sensitive
2694 * test for characters that can vary under case folding?
2696 if (case_insensitive && isalpha((unsigned char) patt[pos]))
2700 * NOTE: this code used to think that %% meant a literal %, but
2701 * textlike() itself does not think that, and the SQL92 spec
2702 * doesn't say any such thing either.
2704 match[match_pos++] = patt[pos];
2707 match[match_pos] = '\0';
2710 /* in LIKE, an empty pattern is an exact match! */
2711 if (patt[pos] == '\0')
2712 return Pattern_Prefix_Exact; /* reached end of pattern, so
2716 return Pattern_Prefix_Partial;
2720 return Pattern_Prefix_None;
2723 static Pattern_Prefix_Status
2724 regex_fixed_prefix(char *patt, bool case_insensitive,
2725 char **prefix, char **rest)
2732 /* Pattern must be anchored left */
2737 return Pattern_Prefix_None;
2741 * If unquoted | is present at paren level 0 in pattern, then there
2742 * are multiple alternatives for the start of the string.
2745 for (pos = 1; patt[pos]; pos++)
2747 if (patt[pos] == '|' && paren_depth == 0)
2751 return Pattern_Prefix_None;
2753 else if (patt[pos] == '(')
2755 else if (patt[pos] == ')' && paren_depth > 0)
2757 else if (patt[pos] == '\\')
2759 /* backslash quotes the next character */
2761 if (patt[pos] == '\0')
2766 /* OK, allocate space for pattern */
2767 *prefix = match = palloc(strlen(patt) + 1);
2770 /* note start at pos 1 to skip leading ^ */
2771 for (pos = 1; patt[pos]; pos++)
2774 * Check for characters that indicate multiple possible matches
2775 * here. XXX I suspect isalpha() is not an adequately
2776 * locale-sensitive test for characters that can vary under case
2779 if (patt[pos] == '.' ||
2783 (case_insensitive && isalpha((unsigned char) patt[pos])))
2787 * Check for quantifiers. Except for +, this means the preceding
2788 * character is optional, so we must remove it from the prefix
2791 if (patt[pos] == '*' ||
2800 if (patt[pos] == '+')
2805 if (patt[pos] == '\\')
2807 /* backslash quotes the next character */
2809 if (patt[pos] == '\0')
2812 match[match_pos++] = patt[pos];
2815 match[match_pos] = '\0';
2818 if (patt[pos] == '$' && patt[pos + 1] == '\0')
2820 *rest = &patt[pos + 1];
2821 return Pattern_Prefix_Exact; /* pattern specifies exact match */
2825 return Pattern_Prefix_Partial;
2829 return Pattern_Prefix_None;
2832 Pattern_Prefix_Status
2833 pattern_fixed_prefix(char *patt, Pattern_Type ptype,
2834 char **prefix, char **rest)
2836 Pattern_Prefix_Status result;
2840 case Pattern_Type_Like:
2841 result = like_fixed_prefix(patt, false, prefix, rest);
2843 case Pattern_Type_Like_IC:
2844 result = like_fixed_prefix(patt, true, prefix, rest);
2846 case Pattern_Type_Regex:
2847 result = regex_fixed_prefix(patt, false, prefix, rest);
2849 case Pattern_Type_Regex_IC:
2850 result = regex_fixed_prefix(patt, true, prefix, rest);
2853 elog(ERROR, "pattern_fixed_prefix: bogus ptype");
2854 result = Pattern_Prefix_None; /* keep compiler quiet */
2861 * Estimate the selectivity of a fixed prefix for a pattern match.
2863 * A fixed prefix "foo" is estimated as the selectivity of the expression
2864 * "var >= 'foo' AND var < 'fop'" (see also indxqual.c).
2866 * XXX Note: we make use of the upper bound to estimate operator selectivity
2867 * even if the locale is such that we cannot rely on the upper-bound string.
2868 * The selectivity only needs to be approximately right anyway, so it seems
2869 * more useful to use the upper-bound code than not.
2872 prefix_selectivity(Query *root, Var *var, char *prefix)
2874 Selectivity prefixsel;
2880 cmpopr = find_operator(">=", var->vartype);
2881 if (cmpopr == InvalidOid)
2882 elog(ERROR, "prefix_selectivity: no >= operator for type %u",
2884 prefixcon = string_to_const(prefix, var->vartype);
2885 cmpargs = makeList2(var, prefixcon);
2886 /* Assume scalargtsel is appropriate for all supported types */
2887 prefixsel = DatumGetFloat8(DirectFunctionCall4(scalargtsel,
2888 PointerGetDatum(root),
2889 ObjectIdGetDatum(cmpopr),
2890 PointerGetDatum(cmpargs),
2894 * If we can create a string larger than the prefix, say
2898 greaterstr = make_greater_string(prefix, var->vartype);
2903 cmpopr = find_operator("<", var->vartype);
2904 if (cmpopr == InvalidOid)
2905 elog(ERROR, "prefix_selectivity: no < operator for type %u",
2907 prefixcon = string_to_const(greaterstr, var->vartype);
2908 cmpargs = makeList2(var, prefixcon);
2909 /* Assume scalarltsel is appropriate for all supported types */
2910 topsel = DatumGetFloat8(DirectFunctionCall4(scalarltsel,
2911 PointerGetDatum(root),
2912 ObjectIdGetDatum(cmpopr),
2913 PointerGetDatum(cmpargs),
2917 * Merge the two selectivities in the same way as for a range
2918 * query (see clauselist_selectivity()).
2920 prefixsel = topsel + prefixsel - 1.0;
2923 * A zero or slightly negative prefixsel should be converted into
2924 * a small positive value; we probably are dealing with a very
2925 * tight range and got a bogus result due to roundoff errors.
2926 * However, if prefixsel is very negative, then we probably have
2927 * default selectivity estimates on one or both sides of the
2928 * range. In that case, insert a not-so-wildly-optimistic default
2931 if (prefixsel <= 0.0)
2933 if (prefixsel < -0.01)
2936 * No data available --- use a default estimate that is
2937 * small, but not real small.
2944 * It's just roundoff error; use a small positive value
2946 prefixsel = 1.0e-10;
2956 * Estimate the selectivity of a pattern of the specified type.
2957 * Note that any fixed prefix of the pattern will have been removed already.
2959 * For now, we use a very simplistic approach: fixed characters reduce the
2960 * selectivity a good deal, character ranges reduce it a little,
2961 * wildcards (such as % for LIKE or .* for regex) increase it.
2964 #define FIXED_CHAR_SEL 0.20 /* about 1/5 */
2965 #define CHAR_RANGE_SEL 0.25
2966 #define ANY_CHAR_SEL 0.9 /* not 1, since it won't match
2968 #define FULL_WILDCARD_SEL 5.0
2969 #define PARTIAL_WILDCARD_SEL 2.0
2972 like_selectivity(char *patt, bool case_insensitive)
2974 Selectivity sel = 1.0;
2977 /* Skip any leading %; it's already factored into initial sel */
2978 pos = (*patt == '%') ? 1 : 0;
2979 for (; patt[pos]; pos++)
2981 /* % and _ are wildcard characters in LIKE */
2982 if (patt[pos] == '%')
2983 sel *= FULL_WILDCARD_SEL;
2984 else if (patt[pos] == '_')
2985 sel *= ANY_CHAR_SEL;
2986 else if (patt[pos] == '\\')
2988 /* Backslash quotes the next character */
2990 if (patt[pos] == '\0')
2992 sel *= FIXED_CHAR_SEL;
2995 sel *= FIXED_CHAR_SEL;
2997 /* Could get sel > 1 if multiple wildcards */
3004 regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive)
3006 Selectivity sel = 1.0;
3007 int paren_depth = 0;
3008 int paren_pos = 0; /* dummy init to keep compiler quiet */
3011 for (pos = 0; pos < pattlen; pos++)
3013 if (patt[pos] == '(')
3015 if (paren_depth == 0)
3016 paren_pos = pos; /* remember start of parenthesized item */
3019 else if (patt[pos] == ')' && paren_depth > 0)
3022 if (paren_depth == 0)
3023 sel *= regex_selectivity_sub(patt + (paren_pos + 1),
3024 pos - (paren_pos + 1),
3027 else if (patt[pos] == '|' && paren_depth == 0)
3030 * If unquoted | is present at paren level 0 in pattern, we
3031 * have multiple alternatives; sum their probabilities.
3033 sel += regex_selectivity_sub(patt + (pos + 1),
3034 pattlen - (pos + 1),
3036 break; /* rest of pattern is now processed */
3038 else if (patt[pos] == '[')
3040 bool negclass = false;
3042 if (patt[++pos] == '^')
3047 if (patt[pos] == ']') /* ']' at start of class is not
3050 while (pos < pattlen && patt[pos] != ']')
3052 if (paren_depth == 0)
3053 sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
3055 else if (patt[pos] == '.')
3057 if (paren_depth == 0)
3058 sel *= ANY_CHAR_SEL;
3060 else if (patt[pos] == '*' ||
3064 /* Ought to be smarter about quantifiers... */
3065 if (paren_depth == 0)
3066 sel *= PARTIAL_WILDCARD_SEL;
3068 else if (patt[pos] == '{')
3070 while (pos < pattlen && patt[pos] != '}')
3072 if (paren_depth == 0)
3073 sel *= PARTIAL_WILDCARD_SEL;
3075 else if (patt[pos] == '\\')
3077 /* backslash quotes the next character */
3081 if (paren_depth == 0)
3082 sel *= FIXED_CHAR_SEL;
3086 if (paren_depth == 0)
3087 sel *= FIXED_CHAR_SEL;
3090 /* Could get sel > 1 if multiple wildcards */
3097 regex_selectivity(char *patt, bool case_insensitive)
3100 int pattlen = strlen(patt);
3102 /* If patt doesn't end with $, consider it to have a trailing wildcard */
3103 if (pattlen > 0 && patt[pattlen - 1] == '$' &&
3104 (pattlen == 1 || patt[pattlen - 2] != '\\'))
3106 /* has trailing $ */
3107 sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
3112 sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
3113 sel *= FULL_WILDCARD_SEL;
3121 pattern_selectivity(char *patt, Pattern_Type ptype)
3127 case Pattern_Type_Like:
3128 result = like_selectivity(patt, false);
3130 case Pattern_Type_Like_IC:
3131 result = like_selectivity(patt, true);
3133 case Pattern_Type_Regex:
3134 result = regex_selectivity(patt, false);
3136 case Pattern_Type_Regex_IC:
3137 result = regex_selectivity(patt, true);
3140 elog(ERROR, "pattern_selectivity: bogus ptype");
3141 result = 1.0; /* keep compiler quiet */
3149 * We want test whether the database's LC_COLLATE setting is safe for
3150 * LIKE/regexp index optimization.
3152 * The key requirement here is that given a prefix string, say "foo",
3153 * we must be able to generate another string "fop" that is greater
3154 * than all strings "foobar" starting with "foo". Unfortunately, a
3155 * non-C locale may have arbitrary collation rules in which "fop" >
3156 * "foo" is not sufficient to ensure "fop" > "foobar". Until we can
3157 * come up with a more bulletproof way of generating the upper-bound
3158 * string, the optimization is disabled in all non-C locales.
3160 * (In theory, locales other than C may be LIKE-safe so this function
3161 * could be different from lc_collate_is_c(), but in a different
3162 * theory, non-C locales are completely unpredicable so it's unlikely
3166 locale_is_like_safe(void)
3168 return lc_collate_is_c();
3172 * Try to generate a string greater than the given string or any string it is
3173 * a prefix of. If successful, return a palloc'd string; else return NULL.
3175 * To work correctly in non-ASCII locales with weird collation orders,
3176 * we cannot simply increment "foo" to "fop" --- we have to check whether
3177 * we actually produced a string greater than the given one. If not,
3178 * increment the righthand byte again and repeat. If we max out the righthand
3179 * byte, truncate off the last character and start incrementing the next.
3180 * For example, if "z" were the last character in the sort order, then we
3181 * could produce "foo" as a string greater than "fonz".
3183 * This could be rather slow in the worst case, but in most cases we won't
3184 * have to try more than one or two strings before succeeding.
3186 * XXX this is actually not sufficient, since it only copes with the case
3187 * where individual characters collate in an order different from their
3188 * numeric code assignments. It does not handle cases where there are
3189 * cross-character effects, such as specially sorted digraphs, multiple
3190 * sort passes, etc. For now, we just shut down the whole thing in locales
3191 * that do such things :-(
3194 make_greater_string(const char *str, Oid datatype)
3200 * Make a modifiable copy, which will be our return value if
3203 workstr = pstrdup((char *) str);
3205 while ((len = strlen(workstr)) > 0)
3207 unsigned char *lastchar = (unsigned char *) (workstr + len - 1);
3210 * Try to generate a larger string by incrementing the last byte.
3212 while (*lastchar < (unsigned char) 255)
3215 if (string_lessthan(str, workstr, datatype))
3216 return workstr; /* Success! */
3220 * Truncate off the last character, which might be more than 1
3221 * byte in MULTIBYTE case.
3224 len = pg_mbcliplen((const unsigned char *) workstr, len, len - 1);
3225 workstr[len] = '\0';
3237 * Test whether two strings are "<" according to the rules of the given
3238 * datatype. We do this the hard way, ie, actually calling the type's
3239 * "<" operator function, to ensure we get the right result...
3242 string_lessthan(const char *str1, const char *str2, Oid datatype)
3244 Datum datum1 = string_to_datum(str1, datatype);
3245 Datum datum2 = string_to_datum(str2, datatype);
3251 result = DatumGetBool(DirectFunctionCall2(text_lt,
3256 result = DatumGetBool(DirectFunctionCall2(bpcharlt,
3261 result = DatumGetBool(DirectFunctionCall2(varcharlt,
3266 result = DatumGetBool(DirectFunctionCall2(namelt,
3271 result = DatumGetBool(DirectFunctionCall2(bytealt,
3276 elog(ERROR, "string_lessthan: unexpected datatype %u", datatype);
3281 pfree(DatumGetPointer(datum1));
3282 pfree(DatumGetPointer(datum2));
3287 /* See if there is a binary op of the given name for the given datatype */
3289 find_operator(const char *opname, Oid datatype)
3291 return GetSysCacheOid(OPERNAME,
3292 PointerGetDatum(opname),
3293 ObjectIdGetDatum(datatype),
3294 ObjectIdGetDatum(datatype),
3299 * Generate a Datum of the appropriate type from a C string.
3300 * Note that all of the supported types are pass-by-ref, so the
3301 * returned value should be pfree'd if no longer needed.
3304 string_to_datum(const char *str, Oid datatype)
3307 * We cheat a little by assuming that textin() will do for bpchar and
3308 * varchar constants too...
3310 if (datatype == NAMEOID)
3311 return DirectFunctionCall1(namein, CStringGetDatum(str));
3313 return DirectFunctionCall1(textin, CStringGetDatum(str));
3317 * Generate a Const node of the appropriate type from a C string.
3320 string_to_const(const char *str, Oid datatype)
3322 Datum conval = string_to_datum(str, datatype);
3324 return makeConst(datatype, ((datatype == NAMEOID) ? NAMEDATALEN : -1),
3325 conval, false, false, false, false);
3328 /*-------------------------------------------------------------------------
3330 * Index cost estimation functions
3332 * genericcostestimate is a general-purpose estimator for use when we
3333 * don't have any better idea about how to estimate. Index-type-specific
3334 * knowledge can be incorporated in the type-specific routines.
3336 *-------------------------------------------------------------------------
3340 genericcostestimate(Query *root, RelOptInfo *rel,
3341 IndexOptInfo *index, List *indexQuals,
3342 Cost *indexStartupCost,
3343 Cost *indexTotalCost,
3344 Selectivity *indexSelectivity,
3345 double *indexCorrelation)
3347 double numIndexTuples;
3348 double numIndexPages;
3349 List *selectivityQuals = indexQuals;
3352 * If the index is partial, AND the index predicate with the
3353 * explicitly given indexquals to produce a more accurate idea of the
3354 * index restriction. This may produce redundant clauses, which we
3355 * hope that cnfify and clauselist_selectivity will deal with
3358 * Note that index->indpred and indexQuals are both in implicit-AND form
3359 * to start with, which we have to make explicit to hand to
3360 * canonicalize_qual, and then we get back implicit-AND form again.
3362 if (index->indpred != NIL)
3366 andedQuals = make_ands_explicit(nconc(listCopy(index->indpred),
3368 selectivityQuals = canonicalize_qual(andedQuals, true);
3371 /* Estimate the fraction of main-table tuples that will be visited */
3372 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
3373 lfirsti(rel->relids));
3376 * Estimate the number of tuples that will be visited. We do it in
3377 * this rather peculiar-looking way in order to get the right answer
3378 * for partial indexes. We can bound the number of tuples by the
3379 * index size, in any case.
3381 numIndexTuples = *indexSelectivity * rel->tuples;
3383 if (numIndexTuples > index->tuples)
3384 numIndexTuples = index->tuples;
3387 * Always estimate at least one tuple is touched, even when
3388 * indexSelectivity estimate is tiny.
3390 if (numIndexTuples < 1.0)
3391 numIndexTuples = 1.0;
3394 * Estimate the number of index pages that will be retrieved.
3396 * For all currently-supported index types, the first page of the index
3397 * is a metadata page, and we should figure on fetching that plus a
3398 * pro-rated fraction of the remaining pages.
3400 if (index->pages > 1 && index->tuples > 0)
3402 numIndexPages = (numIndexTuples / index->tuples) * (index->pages - 1);
3403 numIndexPages += 1; /* count the metapage too */
3404 numIndexPages = ceil(numIndexPages);
3407 numIndexPages = 1.0;
3410 * Compute the index access cost.
3412 * Our generic assumption is that the index pages will be read
3413 * sequentially, so they have cost 1.0 each, not random_page_cost.
3414 * Also, we charge for evaluation of the indexquals at each index
3415 * tuple. All the costs are assumed to be paid incrementally during
3418 *indexStartupCost = 0;
3419 *indexTotalCost = numIndexPages +
3420 (cpu_index_tuple_cost + cost_qual_eval(indexQuals)) * numIndexTuples;
3423 * Generic assumption about index correlation: there isn't any.
3425 *indexCorrelation = 0.0;
3430 btcostestimate(PG_FUNCTION_ARGS)
3432 Query *root = (Query *) PG_GETARG_POINTER(0);
3433 RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
3434 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
3435 List *indexQuals = (List *) PG_GETARG_POINTER(3);
3436 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
3437 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
3438 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
3439 double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
3441 genericcostestimate(root, rel, index, indexQuals,
3442 indexStartupCost, indexTotalCost,
3443 indexSelectivity, indexCorrelation);
3446 * If it's a functional index, leave the default zero-correlation
3447 * estimate in place. If not, and if we can get an estimate for the
3448 * first variable's ordering correlation C from pg_statistic, estimate
3449 * the index correlation as C / number-of-columns. (The idea here is
3450 * that multiple columns dilute the importance of the first column's
3451 * ordering, but don't negate it entirely.)
3453 if (index->indproc == InvalidOid)
3458 relid = getrelid(lfirsti(rel->relids), root->rtable);
3459 Assert(relid != InvalidOid);
3460 tuple = SearchSysCache(STATRELATT,
3461 ObjectIdGetDatum(relid),
3462 Int16GetDatum(index->indexkeys[0]),
3464 if (HeapTupleIsValid(tuple))
3471 get_atttypetypmod(relid, index->indexkeys[0],
3473 if (get_attstatsslot(tuple, typid, typmod,
3474 STATISTIC_KIND_CORRELATION,
3476 NULL, NULL, &numbers, &nnumbers))
3478 double varCorrelation;
3481 Assert(nnumbers == 1);
3482 varCorrelation = numbers[0];
3483 for (nKeys = 1; index->indexkeys[nKeys] != 0; nKeys++)
3486 *indexCorrelation = varCorrelation / nKeys;
3488 free_attstatsslot(typid, NULL, 0, numbers, nnumbers);
3490 ReleaseSysCache(tuple);
3498 rtcostestimate(PG_FUNCTION_ARGS)
3500 Query *root = (Query *) PG_GETARG_POINTER(0);
3501 RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
3502 IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
3503 List *indexQuals = (List *) PG_GETARG_POINTER(3);
3504 Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
3505 Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
3506 Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
3507 double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
3509 genericcostestimate(root, rel, index, indexQuals,
3510 indexStartupCost, indexTotalCost,
3511 indexSelectivity, indexCorrelation);
3517 hashcostestimate(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 gistcostestimate(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);