Avoid crash in estimate_array_length with null root pointer.
[pgsql.git] / src / backend / utils / adt / selfuncs.c
blobf4b3e91baa89c8d78af9d22f241a5c759ea604a8
1 /*-------------------------------------------------------------------------
3 * selfuncs.c
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 located via the index AM's API struct,
11 * which is obtained from the handler function registered in pg_am.
13 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
17 * IDENTIFICATION
18 * src/backend/utils/adt/selfuncs.c
20 *-------------------------------------------------------------------------
23 /*----------
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
28 * one relation.
29 * Join clause estimation: the clause involves vars of multiple rels.
30 * Join selectivity estimation is far more difficult and usually less accurate
31 * than restriction estimation.
33 * When dealing with the inner scan of a nestloop join, we consider the
34 * join's joinclauses as restriction clauses for the inner relation, and
35 * treat vars of the outer relation as parameters (a/k/a constants of unknown
36 * values). So, restriction estimators need to be able to accept an argument
37 * telling which relation is to be treated as the variable.
39 * The call convention for a restriction estimator (oprrest function) is
41 * Selectivity oprrest (PlannerInfo *root,
42 * Oid operator,
43 * List *args,
44 * int varRelid);
46 * root: general information about the query (rtable and RelOptInfo lists
47 * are particularly important for the estimator).
48 * operator: OID of the specific operator in question.
49 * args: argument list from the operator clause.
50 * varRelid: if not zero, the relid (rtable index) of the relation to
51 * be treated as the variable relation. May be zero if the args list
52 * is known to contain vars of only one relation.
54 * This is represented at the SQL level (in pg_proc) as
56 * float8 oprrest (internal, oid, internal, int4);
58 * The result is a selectivity, that is, a fraction (0 to 1) of the rows
59 * of the relation that are expected to produce a TRUE result for the
60 * given operator.
62 * The call convention for a join estimator (oprjoin function) is similar
63 * except that varRelid is not needed, and instead join information is
64 * supplied:
66 * Selectivity oprjoin (PlannerInfo *root,
67 * Oid operator,
68 * List *args,
69 * JoinType jointype,
70 * SpecialJoinInfo *sjinfo);
72 * float8 oprjoin (internal, oid, internal, int2, internal);
74 * (Before Postgres 8.4, join estimators had only the first four of these
75 * parameters. That signature is still allowed, but deprecated.) The
76 * relationship between jointype and sjinfo is explained in the comments for
77 * clause_selectivity() --- the short version is that jointype is usually
78 * best ignored in favor of examining sjinfo.
80 * Join selectivity for regular inner and outer joins is defined as the
81 * fraction (0 to 1) of the cross product of the relations that is expected
82 * to produce a TRUE result for the given operator. For both semi and anti
83 * joins, however, the selectivity is defined as the fraction of the left-hand
84 * side relation's rows that are expected to have a match (ie, at least one
85 * row with a TRUE result) in the right-hand side.
87 * For both oprrest and oprjoin functions, the operator's input collation OID
88 * (if any) is passed using the standard fmgr mechanism, so that the estimator
89 * function can fetch it with PG_GET_COLLATION(). Note, however, that all
90 * statistics in pg_statistic are currently built using the relevant column's
91 * collation.
92 *----------
95 #include "postgres.h"
97 #include <ctype.h>
98 #include <math.h>
100 #include "access/brin.h"
101 #include "access/brin_page.h"
102 #include "access/gin.h"
103 #include "access/table.h"
104 #include "access/tableam.h"
105 #include "access/visibilitymap.h"
106 #include "catalog/pg_am.h"
107 #include "catalog/pg_collation.h"
108 #include "catalog/pg_operator.h"
109 #include "catalog/pg_statistic.h"
110 #include "catalog/pg_statistic_ext.h"
111 #include "executor/nodeAgg.h"
112 #include "miscadmin.h"
113 #include "nodes/makefuncs.h"
114 #include "nodes/nodeFuncs.h"
115 #include "optimizer/clauses.h"
116 #include "optimizer/cost.h"
117 #include "optimizer/optimizer.h"
118 #include "optimizer/pathnode.h"
119 #include "optimizer/paths.h"
120 #include "optimizer/plancat.h"
121 #include "parser/parse_clause.h"
122 #include "parser/parse_relation.h"
123 #include "parser/parsetree.h"
124 #include "statistics/statistics.h"
125 #include "storage/bufmgr.h"
126 #include "utils/acl.h"
127 #include "utils/array.h"
128 #include "utils/builtins.h"
129 #include "utils/date.h"
130 #include "utils/datum.h"
131 #include "utils/fmgroids.h"
132 #include "utils/index_selfuncs.h"
133 #include "utils/lsyscache.h"
134 #include "utils/memutils.h"
135 #include "utils/pg_locale.h"
136 #include "utils/rel.h"
137 #include "utils/selfuncs.h"
138 #include "utils/snapmgr.h"
139 #include "utils/spccache.h"
140 #include "utils/syscache.h"
141 #include "utils/timestamp.h"
142 #include "utils/typcache.h"
144 #define DEFAULT_PAGE_CPU_MULTIPLIER 50.0
146 /* Hooks for plugins to get control when we ask for stats */
147 get_relation_stats_hook_type get_relation_stats_hook = NULL;
148 get_index_stats_hook_type get_index_stats_hook = NULL;
150 static double eqsel_internal(PG_FUNCTION_ARGS, bool negate);
151 static double eqjoinsel_inner(Oid opfuncoid, Oid collation,
152 VariableStatData *vardata1, VariableStatData *vardata2,
153 double nd1, double nd2,
154 bool isdefault1, bool isdefault2,
155 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
156 Form_pg_statistic stats1, Form_pg_statistic stats2,
157 bool have_mcvs1, bool have_mcvs2);
158 static double eqjoinsel_semi(Oid opfuncoid, Oid collation,
159 VariableStatData *vardata1, VariableStatData *vardata2,
160 double nd1, double nd2,
161 bool isdefault1, bool isdefault2,
162 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
163 Form_pg_statistic stats1, Form_pg_statistic stats2,
164 bool have_mcvs1, bool have_mcvs2,
165 RelOptInfo *inner_rel);
166 static bool estimate_multivariate_ndistinct(PlannerInfo *root,
167 RelOptInfo *rel, List **varinfos, double *ndistinct);
168 static bool convert_to_scalar(Datum value, Oid valuetypid, Oid collid,
169 double *scaledvalue,
170 Datum lobound, Datum hibound, Oid boundstypid,
171 double *scaledlobound, double *scaledhibound);
172 static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure);
173 static void convert_string_to_scalar(char *value,
174 double *scaledvalue,
175 char *lobound,
176 double *scaledlobound,
177 char *hibound,
178 double *scaledhibound);
179 static void convert_bytea_to_scalar(Datum value,
180 double *scaledvalue,
181 Datum lobound,
182 double *scaledlobound,
183 Datum hibound,
184 double *scaledhibound);
185 static double convert_one_string_to_scalar(char *value,
186 int rangelo, int rangehi);
187 static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
188 int rangelo, int rangehi);
189 static char *convert_string_datum(Datum value, Oid typid, Oid collid,
190 bool *failure);
191 static double convert_timevalue_to_scalar(Datum value, Oid typid,
192 bool *failure);
193 static void examine_simple_variable(PlannerInfo *root, Var *var,
194 VariableStatData *vardata);
195 static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
196 Oid sortop, Oid collation,
197 Datum *min, Datum *max);
198 static void get_stats_slot_range(AttStatsSlot *sslot,
199 Oid opfuncoid, FmgrInfo *opproc,
200 Oid collation, int16 typLen, bool typByVal,
201 Datum *min, Datum *max, bool *p_have_data);
202 static bool get_actual_variable_range(PlannerInfo *root,
203 VariableStatData *vardata,
204 Oid sortop, Oid collation,
205 Datum *min, Datum *max);
206 static bool get_actual_variable_endpoint(Relation heapRel,
207 Relation indexRel,
208 ScanDirection indexscandir,
209 ScanKey scankeys,
210 int16 typLen,
211 bool typByVal,
212 TupleTableSlot *tableslot,
213 MemoryContext outercontext,
214 Datum *endpointDatum);
215 static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
219 * eqsel - Selectivity of "=" for any data types.
221 * Note: this routine is also used to estimate selectivity for some
222 * operators that are not "=" but have comparable selectivity behavior,
223 * such as "~=" (geometric approximate-match). Even for "=", we must
224 * keep in mind that the left and right datatypes may differ.
226 Datum
227 eqsel(PG_FUNCTION_ARGS)
229 PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
233 * Common code for eqsel() and neqsel()
235 static double
236 eqsel_internal(PG_FUNCTION_ARGS, bool negate)
238 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
239 Oid operator = PG_GETARG_OID(1);
240 List *args = (List *) PG_GETARG_POINTER(2);
241 int varRelid = PG_GETARG_INT32(3);
242 Oid collation = PG_GET_COLLATION();
243 VariableStatData vardata;
244 Node *other;
245 bool varonleft;
246 double selec;
249 * When asked about <>, we do the estimation using the corresponding =
250 * operator, then convert to <> via "1.0 - eq_selectivity - nullfrac".
252 if (negate)
254 operator = get_negator(operator);
255 if (!OidIsValid(operator))
257 /* Use default selectivity (should we raise an error instead?) */
258 return 1.0 - DEFAULT_EQ_SEL;
263 * If expression is not variable = something or something = variable, then
264 * punt and return a default estimate.
266 if (!get_restriction_variable(root, args, varRelid,
267 &vardata, &other, &varonleft))
268 return negate ? (1.0 - DEFAULT_EQ_SEL) : DEFAULT_EQ_SEL;
271 * We can do a lot better if the something is a constant. (Note: the
272 * Const might result from estimation rather than being a simple constant
273 * in the query.)
275 if (IsA(other, Const))
276 selec = var_eq_const(&vardata, operator, collation,
277 ((Const *) other)->constvalue,
278 ((Const *) other)->constisnull,
279 varonleft, negate);
280 else
281 selec = var_eq_non_const(&vardata, operator, collation, other,
282 varonleft, negate);
284 ReleaseVariableStats(vardata);
286 return selec;
290 * var_eq_const --- eqsel for var = const case
292 * This is exported so that some other estimation functions can use it.
294 double
295 var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
296 Datum constval, bool constisnull,
297 bool varonleft, bool negate)
299 double selec;
300 double nullfrac = 0.0;
301 bool isdefault;
302 Oid opfuncoid;
305 * If the constant is NULL, assume operator is strict and return zero, ie,
306 * operator will never return TRUE. (It's zero even for a negator op.)
308 if (constisnull)
309 return 0.0;
312 * Grab the nullfrac for use below. Note we allow use of nullfrac
313 * regardless of security check.
315 if (HeapTupleIsValid(vardata->statsTuple))
317 Form_pg_statistic stats;
319 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
320 nullfrac = stats->stanullfrac;
324 * If we matched the var to a unique index or DISTINCT clause, assume
325 * there is exactly one match regardless of anything else. (This is
326 * slightly bogus, since the index or clause's equality operator might be
327 * different from ours, but it's much more likely to be right than
328 * ignoring the information.)
330 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
332 selec = 1.0 / vardata->rel->tuples;
334 else if (HeapTupleIsValid(vardata->statsTuple) &&
335 statistic_proc_security_check(vardata,
336 (opfuncoid = get_opcode(oproid))))
338 AttStatsSlot sslot;
339 bool match = false;
340 int i;
343 * Is the constant "=" to any of the column's most common values?
344 * (Although the given operator may not really be "=", we will assume
345 * that seeing whether it returns TRUE is an appropriate test. If you
346 * don't like this, maybe you shouldn't be using eqsel for your
347 * operator...)
349 if (get_attstatsslot(&sslot, vardata->statsTuple,
350 STATISTIC_KIND_MCV, InvalidOid,
351 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
353 LOCAL_FCINFO(fcinfo, 2);
354 FmgrInfo eqproc;
356 fmgr_info(opfuncoid, &eqproc);
359 * Save a few cycles by setting up the fcinfo struct just once.
360 * Using FunctionCallInvoke directly also avoids failure if the
361 * eqproc returns NULL, though really equality functions should
362 * never do that.
364 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
365 NULL, NULL);
366 fcinfo->args[0].isnull = false;
367 fcinfo->args[1].isnull = false;
368 /* be careful to apply operator right way 'round */
369 if (varonleft)
370 fcinfo->args[1].value = constval;
371 else
372 fcinfo->args[0].value = constval;
374 for (i = 0; i < sslot.nvalues; i++)
376 Datum fresult;
378 if (varonleft)
379 fcinfo->args[0].value = sslot.values[i];
380 else
381 fcinfo->args[1].value = sslot.values[i];
382 fcinfo->isnull = false;
383 fresult = FunctionCallInvoke(fcinfo);
384 if (!fcinfo->isnull && DatumGetBool(fresult))
386 match = true;
387 break;
391 else
393 /* no most-common-value info available */
394 i = 0; /* keep compiler quiet */
397 if (match)
400 * Constant is "=" to this common value. We know selectivity
401 * exactly (or as exactly as ANALYZE could calculate it, anyway).
403 selec = sslot.numbers[i];
405 else
408 * Comparison is against a constant that is neither NULL nor any
409 * of the common values. Its selectivity cannot be more than
410 * this:
412 double sumcommon = 0.0;
413 double otherdistinct;
415 for (i = 0; i < sslot.nnumbers; i++)
416 sumcommon += sslot.numbers[i];
417 selec = 1.0 - sumcommon - nullfrac;
418 CLAMP_PROBABILITY(selec);
421 * and in fact it's probably a good deal less. We approximate that
422 * all the not-common values share this remaining fraction
423 * equally, so we divide by the number of other distinct values.
425 otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
426 sslot.nnumbers;
427 if (otherdistinct > 1)
428 selec /= otherdistinct;
431 * Another cross-check: selectivity shouldn't be estimated as more
432 * than the least common "most common value".
434 if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
435 selec = sslot.numbers[sslot.nnumbers - 1];
438 free_attstatsslot(&sslot);
440 else
443 * No ANALYZE stats available, so make a guess using estimated number
444 * of distinct values and assuming they are equally common. (The guess
445 * is unlikely to be very good, but we do know a few special cases.)
447 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
450 /* now adjust if we wanted <> rather than = */
451 if (negate)
452 selec = 1.0 - selec - nullfrac;
454 /* result should be in range, but make sure... */
455 CLAMP_PROBABILITY(selec);
457 return selec;
461 * var_eq_non_const --- eqsel for var = something-other-than-const case
463 * This is exported so that some other estimation functions can use it.
465 double
466 var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
467 Node *other,
468 bool varonleft, bool negate)
470 double selec;
471 double nullfrac = 0.0;
472 bool isdefault;
475 * Grab the nullfrac for use below.
477 if (HeapTupleIsValid(vardata->statsTuple))
479 Form_pg_statistic stats;
481 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
482 nullfrac = stats->stanullfrac;
486 * If we matched the var to a unique index or DISTINCT clause, assume
487 * there is exactly one match regardless of anything else. (This is
488 * slightly bogus, since the index or clause's equality operator might be
489 * different from ours, but it's much more likely to be right than
490 * ignoring the information.)
492 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
494 selec = 1.0 / vardata->rel->tuples;
496 else if (HeapTupleIsValid(vardata->statsTuple))
498 double ndistinct;
499 AttStatsSlot sslot;
502 * Search is for a value that we do not know a priori, but we will
503 * assume it is not NULL. Estimate the selectivity as non-null
504 * fraction divided by number of distinct values, so that we get a
505 * result averaged over all possible values whether common or
506 * uncommon. (Essentially, we are assuming that the not-yet-known
507 * comparison value is equally likely to be any of the possible
508 * values, regardless of their frequency in the table. Is that a good
509 * idea?)
511 selec = 1.0 - nullfrac;
512 ndistinct = get_variable_numdistinct(vardata, &isdefault);
513 if (ndistinct > 1)
514 selec /= ndistinct;
517 * Cross-check: selectivity should never be estimated as more than the
518 * most common value's.
520 if (get_attstatsslot(&sslot, vardata->statsTuple,
521 STATISTIC_KIND_MCV, InvalidOid,
522 ATTSTATSSLOT_NUMBERS))
524 if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
525 selec = sslot.numbers[0];
526 free_attstatsslot(&sslot);
529 else
532 * No ANALYZE stats available, so make a guess using estimated number
533 * of distinct values and assuming they are equally common. (The guess
534 * is unlikely to be very good, but we do know a few special cases.)
536 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
539 /* now adjust if we wanted <> rather than = */
540 if (negate)
541 selec = 1.0 - selec - nullfrac;
543 /* result should be in range, but make sure... */
544 CLAMP_PROBABILITY(selec);
546 return selec;
550 * neqsel - Selectivity of "!=" for any data types.
552 * This routine is also used for some operators that are not "!="
553 * but have comparable selectivity behavior. See above comments
554 * for eqsel().
556 Datum
557 neqsel(PG_FUNCTION_ARGS)
559 PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, true));
563 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
565 * This is the guts of scalarltsel/scalarlesel/scalargtsel/scalargesel.
566 * The isgt and iseq flags distinguish which of the four cases apply.
568 * The caller has commuted the clause, if necessary, so that we can treat
569 * the variable as being on the left. The caller must also make sure that
570 * the other side of the clause is a non-null Const, and dissect that into
571 * a value and datatype. (This definition simplifies some callers that
572 * want to estimate against a computed value instead of a Const node.)
574 * This routine works for any datatype (or pair of datatypes) known to
575 * convert_to_scalar(). If it is applied to some other datatype,
576 * it will return an approximate estimate based on assuming that the constant
577 * value falls in the middle of the bin identified by binary search.
579 static double
580 scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq,
581 Oid collation,
582 VariableStatData *vardata, Datum constval, Oid consttype)
584 Form_pg_statistic stats;
585 FmgrInfo opproc;
586 double mcv_selec,
587 hist_selec,
588 sumcommon;
589 double selec;
591 if (!HeapTupleIsValid(vardata->statsTuple))
594 * No stats are available. Typically this means we have to fall back
595 * on the default estimate; but if the variable is CTID then we can
596 * make an estimate based on comparing the constant to the table size.
598 if (vardata->var && IsA(vardata->var, Var) &&
599 ((Var *) vardata->var)->varattno == SelfItemPointerAttributeNumber)
601 ItemPointer itemptr;
602 double block;
603 double density;
606 * If the relation's empty, we're going to include all of it.
607 * (This is mostly to avoid divide-by-zero below.)
609 if (vardata->rel->pages == 0)
610 return 1.0;
612 itemptr = (ItemPointer) DatumGetPointer(constval);
613 block = ItemPointerGetBlockNumberNoCheck(itemptr);
616 * Determine the average number of tuples per page (density).
618 * Since the last page will, on average, be only half full, we can
619 * estimate it to have half as many tuples as earlier pages. So
620 * give it half the weight of a regular page.
622 density = vardata->rel->tuples / (vardata->rel->pages - 0.5);
624 /* If target is the last page, use half the density. */
625 if (block >= vardata->rel->pages - 1)
626 density *= 0.5;
629 * Using the average tuples per page, calculate how far into the
630 * page the itemptr is likely to be and adjust block accordingly,
631 * by adding that fraction of a whole block (but never more than a
632 * whole block, no matter how high the itemptr's offset is). Here
633 * we are ignoring the possibility of dead-tuple line pointers,
634 * which is fairly bogus, but we lack the info to do better.
636 if (density > 0.0)
638 OffsetNumber offset = ItemPointerGetOffsetNumberNoCheck(itemptr);
640 block += Min(offset / density, 1.0);
644 * Convert relative block number to selectivity. Again, the last
645 * page has only half weight.
647 selec = block / (vardata->rel->pages - 0.5);
650 * The calculation so far gave us a selectivity for the "<=" case.
651 * We'll have one fewer tuple for "<" and one additional tuple for
652 * ">=", the latter of which we'll reverse the selectivity for
653 * below, so we can simply subtract one tuple for both cases. The
654 * cases that need this adjustment can be identified by iseq being
655 * equal to isgt.
657 if (iseq == isgt && vardata->rel->tuples >= 1.0)
658 selec -= (1.0 / vardata->rel->tuples);
660 /* Finally, reverse the selectivity for the ">", ">=" cases. */
661 if (isgt)
662 selec = 1.0 - selec;
664 CLAMP_PROBABILITY(selec);
665 return selec;
668 /* no stats available, so default result */
669 return DEFAULT_INEQ_SEL;
671 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
673 fmgr_info(get_opcode(operator), &opproc);
676 * If we have most-common-values info, add up the fractions of the MCV
677 * entries that satisfy MCV OP CONST. These fractions contribute directly
678 * to the result selectivity. Also add up the total fraction represented
679 * by MCV entries.
681 mcv_selec = mcv_selectivity(vardata, &opproc, collation, constval, true,
682 &sumcommon);
685 * If there is a histogram, determine which bin the constant falls in, and
686 * compute the resulting contribution to selectivity.
688 hist_selec = ineq_histogram_selectivity(root, vardata,
689 operator, &opproc, isgt, iseq,
690 collation,
691 constval, consttype);
694 * Now merge the results from the MCV and histogram calculations,
695 * realizing that the histogram covers only the non-null values that are
696 * not listed in MCV.
698 selec = 1.0 - stats->stanullfrac - sumcommon;
700 if (hist_selec >= 0.0)
701 selec *= hist_selec;
702 else
705 * If no histogram but there are values not accounted for by MCV,
706 * arbitrarily assume half of them will match.
708 selec *= 0.5;
711 selec += mcv_selec;
713 /* result should be in range, but make sure... */
714 CLAMP_PROBABILITY(selec);
716 return selec;
720 * mcv_selectivity - Examine the MCV list for selectivity estimates
722 * Determine the fraction of the variable's MCV population that satisfies
723 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
724 * compute the fraction of the total column population represented by the MCV
725 * list. This code will work for any boolean-returning predicate operator.
727 * The function result is the MCV selectivity, and the fraction of the
728 * total population is returned into *sumcommonp. Zeroes are returned
729 * if there is no MCV list.
731 double
732 mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation,
733 Datum constval, bool varonleft,
734 double *sumcommonp)
736 double mcv_selec,
737 sumcommon;
738 AttStatsSlot sslot;
739 int i;
741 mcv_selec = 0.0;
742 sumcommon = 0.0;
744 if (HeapTupleIsValid(vardata->statsTuple) &&
745 statistic_proc_security_check(vardata, opproc->fn_oid) &&
746 get_attstatsslot(&sslot, vardata->statsTuple,
747 STATISTIC_KIND_MCV, InvalidOid,
748 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
750 LOCAL_FCINFO(fcinfo, 2);
753 * We invoke the opproc "by hand" so that we won't fail on NULL
754 * results. Such cases won't arise for normal comparison functions,
755 * but generic_restriction_selectivity could perhaps be used with
756 * operators that can return NULL. A small side benefit is to not
757 * need to re-initialize the fcinfo struct from scratch each time.
759 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
760 NULL, NULL);
761 fcinfo->args[0].isnull = false;
762 fcinfo->args[1].isnull = false;
763 /* be careful to apply operator right way 'round */
764 if (varonleft)
765 fcinfo->args[1].value = constval;
766 else
767 fcinfo->args[0].value = constval;
769 for (i = 0; i < sslot.nvalues; i++)
771 Datum fresult;
773 if (varonleft)
774 fcinfo->args[0].value = sslot.values[i];
775 else
776 fcinfo->args[1].value = sslot.values[i];
777 fcinfo->isnull = false;
778 fresult = FunctionCallInvoke(fcinfo);
779 if (!fcinfo->isnull && DatumGetBool(fresult))
780 mcv_selec += sslot.numbers[i];
781 sumcommon += sslot.numbers[i];
783 free_attstatsslot(&sslot);
786 *sumcommonp = sumcommon;
787 return mcv_selec;
791 * histogram_selectivity - Examine the histogram for selectivity estimates
793 * Determine the fraction of the variable's histogram entries that satisfy
794 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
796 * This code will work for any boolean-returning predicate operator, whether
797 * or not it has anything to do with the histogram sort operator. We are
798 * essentially using the histogram just as a representative sample. However,
799 * small histograms are unlikely to be all that representative, so the caller
800 * should be prepared to fall back on some other estimation approach when the
801 * histogram is missing or very small. It may also be prudent to combine this
802 * approach with another one when the histogram is small.
804 * If the actual histogram size is not at least min_hist_size, we won't bother
805 * to do the calculation at all. Also, if the n_skip parameter is > 0, we
806 * ignore the first and last n_skip histogram elements, on the grounds that
807 * they are outliers and hence not very representative. Typical values for
808 * these parameters are 10 and 1.
810 * The function result is the selectivity, or -1 if there is no histogram
811 * or it's smaller than min_hist_size.
813 * The output parameter *hist_size receives the actual histogram size,
814 * or zero if no histogram. Callers may use this number to decide how
815 * much faith to put in the function result.
817 * Note that the result disregards both the most-common-values (if any) and
818 * null entries. The caller is expected to combine this result with
819 * statistics for those portions of the column population. It may also be
820 * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
822 double
823 histogram_selectivity(VariableStatData *vardata,
824 FmgrInfo *opproc, Oid collation,
825 Datum constval, bool varonleft,
826 int min_hist_size, int n_skip,
827 int *hist_size)
829 double result;
830 AttStatsSlot sslot;
832 /* check sanity of parameters */
833 Assert(n_skip >= 0);
834 Assert(min_hist_size > 2 * n_skip);
836 if (HeapTupleIsValid(vardata->statsTuple) &&
837 statistic_proc_security_check(vardata, opproc->fn_oid) &&
838 get_attstatsslot(&sslot, vardata->statsTuple,
839 STATISTIC_KIND_HISTOGRAM, InvalidOid,
840 ATTSTATSSLOT_VALUES))
842 *hist_size = sslot.nvalues;
843 if (sslot.nvalues >= min_hist_size)
845 LOCAL_FCINFO(fcinfo, 2);
846 int nmatch = 0;
847 int i;
850 * We invoke the opproc "by hand" so that we won't fail on NULL
851 * results. Such cases won't arise for normal comparison
852 * functions, but generic_restriction_selectivity could perhaps be
853 * used with operators that can return NULL. A small side benefit
854 * is to not need to re-initialize the fcinfo struct from scratch
855 * each time.
857 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
858 NULL, NULL);
859 fcinfo->args[0].isnull = false;
860 fcinfo->args[1].isnull = false;
861 /* be careful to apply operator right way 'round */
862 if (varonleft)
863 fcinfo->args[1].value = constval;
864 else
865 fcinfo->args[0].value = constval;
867 for (i = n_skip; i < sslot.nvalues - n_skip; i++)
869 Datum fresult;
871 if (varonleft)
872 fcinfo->args[0].value = sslot.values[i];
873 else
874 fcinfo->args[1].value = sslot.values[i];
875 fcinfo->isnull = false;
876 fresult = FunctionCallInvoke(fcinfo);
877 if (!fcinfo->isnull && DatumGetBool(fresult))
878 nmatch++;
880 result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
882 else
883 result = -1;
884 free_attstatsslot(&sslot);
886 else
888 *hist_size = 0;
889 result = -1;
892 return result;
896 * generic_restriction_selectivity - Selectivity for almost anything
898 * This function estimates selectivity for operators that we don't have any
899 * special knowledge about, but are on data types that we collect standard
900 * MCV and/or histogram statistics for. (Additional assumptions are that
901 * the operator is strict and immutable, or at least stable.)
903 * If we have "VAR OP CONST" or "CONST OP VAR", selectivity is estimated by
904 * applying the operator to each element of the column's MCV and/or histogram
905 * stats, and merging the results using the assumption that the histogram is
906 * a reasonable random sample of the column's non-MCV population. Note that
907 * if the operator's semantics are related to the histogram ordering, this
908 * might not be such a great assumption; other functions such as
909 * scalarineqsel() are probably a better match in such cases.
911 * Otherwise, fall back to the default selectivity provided by the caller.
913 double
914 generic_restriction_selectivity(PlannerInfo *root, Oid oproid, Oid collation,
915 List *args, int varRelid,
916 double default_selectivity)
918 double selec;
919 VariableStatData vardata;
920 Node *other;
921 bool varonleft;
924 * If expression is not variable OP something or something OP variable,
925 * then punt and return the default estimate.
927 if (!get_restriction_variable(root, args, varRelid,
928 &vardata, &other, &varonleft))
929 return default_selectivity;
932 * If the something is a NULL constant, assume operator is strict and
933 * return zero, ie, operator will never return TRUE.
935 if (IsA(other, Const) &&
936 ((Const *) other)->constisnull)
938 ReleaseVariableStats(vardata);
939 return 0.0;
942 if (IsA(other, Const))
944 /* Variable is being compared to a known non-null constant */
945 Datum constval = ((Const *) other)->constvalue;
946 FmgrInfo opproc;
947 double mcvsum;
948 double mcvsel;
949 double nullfrac;
950 int hist_size;
952 fmgr_info(get_opcode(oproid), &opproc);
955 * Calculate the selectivity for the column's most common values.
957 mcvsel = mcv_selectivity(&vardata, &opproc, collation,
958 constval, varonleft,
959 &mcvsum);
962 * If the histogram is large enough, see what fraction of it matches
963 * the query, and assume that's representative of the non-MCV
964 * population. Otherwise use the default selectivity for the non-MCV
965 * population.
967 selec = histogram_selectivity(&vardata, &opproc, collation,
968 constval, varonleft,
969 10, 1, &hist_size);
970 if (selec < 0)
972 /* Nope, fall back on default */
973 selec = default_selectivity;
975 else if (hist_size < 100)
978 * For histogram sizes from 10 to 100, we combine the histogram
979 * and default selectivities, putting increasingly more trust in
980 * the histogram for larger sizes.
982 double hist_weight = hist_size / 100.0;
984 selec = selec * hist_weight +
985 default_selectivity * (1.0 - hist_weight);
988 /* In any case, don't believe extremely small or large estimates. */
989 if (selec < 0.0001)
990 selec = 0.0001;
991 else if (selec > 0.9999)
992 selec = 0.9999;
994 /* Don't forget to account for nulls. */
995 if (HeapTupleIsValid(vardata.statsTuple))
996 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
997 else
998 nullfrac = 0.0;
1001 * Now merge the results from the MCV and histogram calculations,
1002 * realizing that the histogram covers only the non-null values that
1003 * are not listed in MCV.
1005 selec *= 1.0 - nullfrac - mcvsum;
1006 selec += mcvsel;
1008 else
1010 /* Comparison value is not constant, so we can't do anything */
1011 selec = default_selectivity;
1014 ReleaseVariableStats(vardata);
1016 /* result should be in range, but make sure... */
1017 CLAMP_PROBABILITY(selec);
1019 return selec;
1023 * ineq_histogram_selectivity - Examine the histogram for scalarineqsel
1025 * Determine the fraction of the variable's histogram population that
1026 * satisfies the inequality condition, ie, VAR < (or <=, >, >=) CONST.
1027 * The isgt and iseq flags distinguish which of the four cases apply.
1029 * While opproc could be looked up from the operator OID, common callers
1030 * also need to call it separately, so we make the caller pass both.
1032 * Returns -1 if there is no histogram (valid results will always be >= 0).
1034 * Note that the result disregards both the most-common-values (if any) and
1035 * null entries. The caller is expected to combine this result with
1036 * statistics for those portions of the column population.
1038 * This is exported so that some other estimation functions can use it.
1040 double
1041 ineq_histogram_selectivity(PlannerInfo *root,
1042 VariableStatData *vardata,
1043 Oid opoid, FmgrInfo *opproc, bool isgt, bool iseq,
1044 Oid collation,
1045 Datum constval, Oid consttype)
1047 double hist_selec;
1048 AttStatsSlot sslot;
1050 hist_selec = -1.0;
1053 * Someday, ANALYZE might store more than one histogram per rel/att,
1054 * corresponding to more than one possible sort ordering defined for the
1055 * column type. Right now, we know there is only one, so just grab it and
1056 * see if it matches the query.
1058 * Note that we can't use opoid as search argument; the staop appearing in
1059 * pg_statistic will be for the relevant '<' operator, but what we have
1060 * might be some other inequality operator such as '>='. (Even if opoid
1061 * is a '<' operator, it could be cross-type.) Hence we must use
1062 * comparison_ops_are_compatible() to see if the operators match.
1064 if (HeapTupleIsValid(vardata->statsTuple) &&
1065 statistic_proc_security_check(vardata, opproc->fn_oid) &&
1066 get_attstatsslot(&sslot, vardata->statsTuple,
1067 STATISTIC_KIND_HISTOGRAM, InvalidOid,
1068 ATTSTATSSLOT_VALUES))
1070 if (sslot.nvalues > 1 &&
1071 sslot.stacoll == collation &&
1072 comparison_ops_are_compatible(sslot.staop, opoid))
1075 * Use binary search to find the desired location, namely the
1076 * right end of the histogram bin containing the comparison value,
1077 * which is the leftmost entry for which the comparison operator
1078 * succeeds (if isgt) or fails (if !isgt).
1080 * In this loop, we pay no attention to whether the operator iseq
1081 * or not; that detail will be mopped up below. (We cannot tell,
1082 * anyway, whether the operator thinks the values are equal.)
1084 * If the binary search accesses the first or last histogram
1085 * entry, we try to replace that endpoint with the true column min
1086 * or max as found by get_actual_variable_range(). This
1087 * ameliorates misestimates when the min or max is moving as a
1088 * result of changes since the last ANALYZE. Note that this could
1089 * result in effectively including MCVs into the histogram that
1090 * weren't there before, but we don't try to correct for that.
1092 double histfrac;
1093 int lobound = 0; /* first possible slot to search */
1094 int hibound = sslot.nvalues; /* last+1 slot to search */
1095 bool have_end = false;
1098 * If there are only two histogram entries, we'll want up-to-date
1099 * values for both. (If there are more than two, we need at most
1100 * one of them to be updated, so we deal with that within the
1101 * loop.)
1103 if (sslot.nvalues == 2)
1104 have_end = get_actual_variable_range(root,
1105 vardata,
1106 sslot.staop,
1107 collation,
1108 &sslot.values[0],
1109 &sslot.values[1]);
1111 while (lobound < hibound)
1113 int probe = (lobound + hibound) / 2;
1114 bool ltcmp;
1117 * If we find ourselves about to compare to the first or last
1118 * histogram entry, first try to replace it with the actual
1119 * current min or max (unless we already did so above).
1121 if (probe == 0 && sslot.nvalues > 2)
1122 have_end = get_actual_variable_range(root,
1123 vardata,
1124 sslot.staop,
1125 collation,
1126 &sslot.values[0],
1127 NULL);
1128 else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
1129 have_end = get_actual_variable_range(root,
1130 vardata,
1131 sslot.staop,
1132 collation,
1133 NULL,
1134 &sslot.values[probe]);
1136 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
1137 collation,
1138 sslot.values[probe],
1139 constval));
1140 if (isgt)
1141 ltcmp = !ltcmp;
1142 if (ltcmp)
1143 lobound = probe + 1;
1144 else
1145 hibound = probe;
1148 if (lobound <= 0)
1151 * Constant is below lower histogram boundary. More
1152 * precisely, we have found that no entry in the histogram
1153 * satisfies the inequality clause (if !isgt) or they all do
1154 * (if isgt). We estimate that that's true of the entire
1155 * table, so set histfrac to 0.0 (which we'll flip to 1.0
1156 * below, if isgt).
1158 histfrac = 0.0;
1160 else if (lobound >= sslot.nvalues)
1163 * Inverse case: constant is above upper histogram boundary.
1165 histfrac = 1.0;
1167 else
1169 /* We have values[i-1] <= constant <= values[i]. */
1170 int i = lobound;
1171 double eq_selec = 0;
1172 double val,
1173 high,
1174 low;
1175 double binfrac;
1178 * In the cases where we'll need it below, obtain an estimate
1179 * of the selectivity of "x = constval". We use a calculation
1180 * similar to what var_eq_const() does for a non-MCV constant,
1181 * ie, estimate that all distinct non-MCV values occur equally
1182 * often. But multiplication by "1.0 - sumcommon - nullfrac"
1183 * will be done by our caller, so we shouldn't do that here.
1184 * Therefore we can't try to clamp the estimate by reference
1185 * to the least common MCV; the result would be too small.
1187 * Note: since this is effectively assuming that constval
1188 * isn't an MCV, it's logically dubious if constval in fact is
1189 * one. But we have to apply *some* correction for equality,
1190 * and anyway we cannot tell if constval is an MCV, since we
1191 * don't have a suitable equality operator at hand.
1193 if (i == 1 || isgt == iseq)
1195 double otherdistinct;
1196 bool isdefault;
1197 AttStatsSlot mcvslot;
1199 /* Get estimated number of distinct values */
1200 otherdistinct = get_variable_numdistinct(vardata,
1201 &isdefault);
1203 /* Subtract off the number of known MCVs */
1204 if (get_attstatsslot(&mcvslot, vardata->statsTuple,
1205 STATISTIC_KIND_MCV, InvalidOid,
1206 ATTSTATSSLOT_NUMBERS))
1208 otherdistinct -= mcvslot.nnumbers;
1209 free_attstatsslot(&mcvslot);
1212 /* If result doesn't seem sane, leave eq_selec at 0 */
1213 if (otherdistinct > 1)
1214 eq_selec = 1.0 / otherdistinct;
1218 * Convert the constant and the two nearest bin boundary
1219 * values to a uniform comparison scale, and do a linear
1220 * interpolation within this bin.
1222 if (convert_to_scalar(constval, consttype, collation,
1223 &val,
1224 sslot.values[i - 1], sslot.values[i],
1225 vardata->vartype,
1226 &low, &high))
1228 if (high <= low)
1230 /* cope if bin boundaries appear identical */
1231 binfrac = 0.5;
1233 else if (val <= low)
1234 binfrac = 0.0;
1235 else if (val >= high)
1236 binfrac = 1.0;
1237 else
1239 binfrac = (val - low) / (high - low);
1242 * Watch out for the possibility that we got a NaN or
1243 * Infinity from the division. This can happen
1244 * despite the previous checks, if for example "low"
1245 * is -Infinity.
1247 if (isnan(binfrac) ||
1248 binfrac < 0.0 || binfrac > 1.0)
1249 binfrac = 0.5;
1252 else
1255 * Ideally we'd produce an error here, on the grounds that
1256 * the given operator shouldn't have scalarXXsel
1257 * registered as its selectivity func unless we can deal
1258 * with its operand types. But currently, all manner of
1259 * stuff is invoking scalarXXsel, so give a default
1260 * estimate until that can be fixed.
1262 binfrac = 0.5;
1266 * Now, compute the overall selectivity across the values
1267 * represented by the histogram. We have i-1 full bins and
1268 * binfrac partial bin below the constant.
1270 histfrac = (double) (i - 1) + binfrac;
1271 histfrac /= (double) (sslot.nvalues - 1);
1274 * At this point, histfrac is an estimate of the fraction of
1275 * the population represented by the histogram that satisfies
1276 * "x <= constval". Somewhat remarkably, this statement is
1277 * true regardless of which operator we were doing the probes
1278 * with, so long as convert_to_scalar() delivers reasonable
1279 * results. If the probe constant is equal to some histogram
1280 * entry, we would have considered the bin to the left of that
1281 * entry if probing with "<" or ">=", or the bin to the right
1282 * if probing with "<=" or ">"; but binfrac would have come
1283 * out as 1.0 in the first case and 0.0 in the second, leading
1284 * to the same histfrac in either case. For probe constants
1285 * between histogram entries, we find the same bin and get the
1286 * same estimate with any operator.
1288 * The fact that the estimate corresponds to "x <= constval"
1289 * and not "x < constval" is because of the way that ANALYZE
1290 * constructs the histogram: each entry is, effectively, the
1291 * rightmost value in its sample bucket. So selectivity
1292 * values that are exact multiples of 1/(histogram_size-1)
1293 * should be understood as estimates including a histogram
1294 * entry plus everything to its left.
1296 * However, that breaks down for the first histogram entry,
1297 * which necessarily is the leftmost value in its sample
1298 * bucket. That means the first histogram bin is slightly
1299 * narrower than the rest, by an amount equal to eq_selec.
1300 * Another way to say that is that we want "x <= leftmost" to
1301 * be estimated as eq_selec not zero. So, if we're dealing
1302 * with the first bin (i==1), rescale to make that true while
1303 * adjusting the rest of that bin linearly.
1305 if (i == 1)
1306 histfrac += eq_selec * (1.0 - binfrac);
1309 * "x <= constval" is good if we want an estimate for "<=" or
1310 * ">", but if we are estimating for "<" or ">=", we now need
1311 * to decrease the estimate by eq_selec.
1313 if (isgt == iseq)
1314 histfrac -= eq_selec;
1318 * Now the estimate is finished for "<" and "<=" cases. If we are
1319 * estimating for ">" or ">=", flip it.
1321 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
1324 * The histogram boundaries are only approximate to begin with,
1325 * and may well be out of date anyway. Therefore, don't believe
1326 * extremely small or large selectivity estimates --- unless we
1327 * got actual current endpoint values from the table, in which
1328 * case just do the usual sanity clamp. Somewhat arbitrarily, we
1329 * set the cutoff for other cases at a hundredth of the histogram
1330 * resolution.
1332 if (have_end)
1333 CLAMP_PROBABILITY(hist_selec);
1334 else
1336 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1338 if (hist_selec < cutoff)
1339 hist_selec = cutoff;
1340 else if (hist_selec > 1.0 - cutoff)
1341 hist_selec = 1.0 - cutoff;
1344 else if (sslot.nvalues > 1)
1347 * If we get here, we have a histogram but it's not sorted the way
1348 * we want. Do a brute-force search to see how many of the
1349 * entries satisfy the comparison condition, and take that
1350 * fraction as our estimate. (This is identical to the inner loop
1351 * of histogram_selectivity; maybe share code?)
1353 LOCAL_FCINFO(fcinfo, 2);
1354 int nmatch = 0;
1356 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
1357 NULL, NULL);
1358 fcinfo->args[0].isnull = false;
1359 fcinfo->args[1].isnull = false;
1360 fcinfo->args[1].value = constval;
1361 for (int i = 0; i < sslot.nvalues; i++)
1363 Datum fresult;
1365 fcinfo->args[0].value = sslot.values[i];
1366 fcinfo->isnull = false;
1367 fresult = FunctionCallInvoke(fcinfo);
1368 if (!fcinfo->isnull && DatumGetBool(fresult))
1369 nmatch++;
1371 hist_selec = ((double) nmatch) / ((double) sslot.nvalues);
1374 * As above, clamp to a hundredth of the histogram resolution.
1375 * This case is surely even less trustworthy than the normal one,
1376 * so we shouldn't believe exact 0 or 1 selectivity. (Maybe the
1377 * clamp should be more restrictive in this case?)
1380 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1382 if (hist_selec < cutoff)
1383 hist_selec = cutoff;
1384 else if (hist_selec > 1.0 - cutoff)
1385 hist_selec = 1.0 - cutoff;
1389 free_attstatsslot(&sslot);
1392 return hist_selec;
1396 * Common wrapper function for the selectivity estimators that simply
1397 * invoke scalarineqsel().
1399 static Datum
1400 scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
1402 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1403 Oid operator = PG_GETARG_OID(1);
1404 List *args = (List *) PG_GETARG_POINTER(2);
1405 int varRelid = PG_GETARG_INT32(3);
1406 Oid collation = PG_GET_COLLATION();
1407 VariableStatData vardata;
1408 Node *other;
1409 bool varonleft;
1410 Datum constval;
1411 Oid consttype;
1412 double selec;
1415 * If expression is not variable op something or something op variable,
1416 * then punt and return a default estimate.
1418 if (!get_restriction_variable(root, args, varRelid,
1419 &vardata, &other, &varonleft))
1420 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1423 * Can't do anything useful if the something is not a constant, either.
1425 if (!IsA(other, Const))
1427 ReleaseVariableStats(vardata);
1428 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1432 * If the constant is NULL, assume operator is strict and return zero, ie,
1433 * operator will never return TRUE.
1435 if (((Const *) other)->constisnull)
1437 ReleaseVariableStats(vardata);
1438 PG_RETURN_FLOAT8(0.0);
1440 constval = ((Const *) other)->constvalue;
1441 consttype = ((Const *) other)->consttype;
1444 * Force the var to be on the left to simplify logic in scalarineqsel.
1446 if (!varonleft)
1448 operator = get_commutator(operator);
1449 if (!operator)
1451 /* Use default selectivity (should we raise an error instead?) */
1452 ReleaseVariableStats(vardata);
1453 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1455 isgt = !isgt;
1458 /* The rest of the work is done by scalarineqsel(). */
1459 selec = scalarineqsel(root, operator, isgt, iseq, collation,
1460 &vardata, constval, consttype);
1462 ReleaseVariableStats(vardata);
1464 PG_RETURN_FLOAT8((float8) selec);
1468 * scalarltsel - Selectivity of "<" for scalars.
1470 Datum
1471 scalarltsel(PG_FUNCTION_ARGS)
1473 return scalarineqsel_wrapper(fcinfo, false, false);
1477 * scalarlesel - Selectivity of "<=" for scalars.
1479 Datum
1480 scalarlesel(PG_FUNCTION_ARGS)
1482 return scalarineqsel_wrapper(fcinfo, false, true);
1486 * scalargtsel - Selectivity of ">" for scalars.
1488 Datum
1489 scalargtsel(PG_FUNCTION_ARGS)
1491 return scalarineqsel_wrapper(fcinfo, true, false);
1495 * scalargesel - Selectivity of ">=" for scalars.
1497 Datum
1498 scalargesel(PG_FUNCTION_ARGS)
1500 return scalarineqsel_wrapper(fcinfo, true, true);
1504 * boolvarsel - Selectivity of Boolean variable.
1506 * This can actually be called on any boolean-valued expression. If it
1507 * involves only Vars of the specified relation, and if there are statistics
1508 * about the Var or expression (the latter is possible if it's indexed) then
1509 * we'll produce a real estimate; otherwise it's just a default.
1511 Selectivity
1512 boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
1514 VariableStatData vardata;
1515 double selec;
1517 examine_variable(root, arg, varRelid, &vardata);
1518 if (HeapTupleIsValid(vardata.statsTuple))
1521 * A boolean variable V is equivalent to the clause V = 't', so we
1522 * compute the selectivity as if that is what we have.
1524 selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1525 BoolGetDatum(true), false, true, false);
1527 else
1529 /* Otherwise, the default estimate is 0.5 */
1530 selec = 0.5;
1532 ReleaseVariableStats(vardata);
1533 return selec;
1537 * booltestsel - Selectivity of BooleanTest Node.
1539 Selectivity
1540 booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
1541 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1543 VariableStatData vardata;
1544 double selec;
1546 examine_variable(root, arg, varRelid, &vardata);
1548 if (HeapTupleIsValid(vardata.statsTuple))
1550 Form_pg_statistic stats;
1551 double freq_null;
1552 AttStatsSlot sslot;
1554 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1555 freq_null = stats->stanullfrac;
1557 if (get_attstatsslot(&sslot, vardata.statsTuple,
1558 STATISTIC_KIND_MCV, InvalidOid,
1559 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)
1560 && sslot.nnumbers > 0)
1562 double freq_true;
1563 double freq_false;
1566 * Get first MCV frequency and derive frequency for true.
1568 if (DatumGetBool(sslot.values[0]))
1569 freq_true = sslot.numbers[0];
1570 else
1571 freq_true = 1.0 - sslot.numbers[0] - freq_null;
1574 * Next derive frequency for false. Then use these as appropriate
1575 * to derive frequency for each case.
1577 freq_false = 1.0 - freq_true - freq_null;
1579 switch (booltesttype)
1581 case IS_UNKNOWN:
1582 /* select only NULL values */
1583 selec = freq_null;
1584 break;
1585 case IS_NOT_UNKNOWN:
1586 /* select non-NULL values */
1587 selec = 1.0 - freq_null;
1588 break;
1589 case IS_TRUE:
1590 /* select only TRUE values */
1591 selec = freq_true;
1592 break;
1593 case IS_NOT_TRUE:
1594 /* select non-TRUE values */
1595 selec = 1.0 - freq_true;
1596 break;
1597 case IS_FALSE:
1598 /* select only FALSE values */
1599 selec = freq_false;
1600 break;
1601 case IS_NOT_FALSE:
1602 /* select non-FALSE values */
1603 selec = 1.0 - freq_false;
1604 break;
1605 default:
1606 elog(ERROR, "unrecognized booltesttype: %d",
1607 (int) booltesttype);
1608 selec = 0.0; /* Keep compiler quiet */
1609 break;
1612 free_attstatsslot(&sslot);
1614 else
1617 * No most-common-value info available. Still have null fraction
1618 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1619 * for null fraction and assume a 50-50 split of TRUE and FALSE.
1621 switch (booltesttype)
1623 case IS_UNKNOWN:
1624 /* select only NULL values */
1625 selec = freq_null;
1626 break;
1627 case IS_NOT_UNKNOWN:
1628 /* select non-NULL values */
1629 selec = 1.0 - freq_null;
1630 break;
1631 case IS_TRUE:
1632 case IS_FALSE:
1633 /* Assume we select half of the non-NULL values */
1634 selec = (1.0 - freq_null) / 2.0;
1635 break;
1636 case IS_NOT_TRUE:
1637 case IS_NOT_FALSE:
1638 /* Assume we select NULLs plus half of the non-NULLs */
1639 /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1640 selec = (freq_null + 1.0) / 2.0;
1641 break;
1642 default:
1643 elog(ERROR, "unrecognized booltesttype: %d",
1644 (int) booltesttype);
1645 selec = 0.0; /* Keep compiler quiet */
1646 break;
1650 else
1653 * If we can't get variable statistics for the argument, perhaps
1654 * clause_selectivity can do something with it. We ignore the
1655 * possibility of a NULL value when using clause_selectivity, and just
1656 * assume the value is either TRUE or FALSE.
1658 switch (booltesttype)
1660 case IS_UNKNOWN:
1661 selec = DEFAULT_UNK_SEL;
1662 break;
1663 case IS_NOT_UNKNOWN:
1664 selec = DEFAULT_NOT_UNK_SEL;
1665 break;
1666 case IS_TRUE:
1667 case IS_NOT_FALSE:
1668 selec = (double) clause_selectivity(root, arg,
1669 varRelid,
1670 jointype, sjinfo);
1671 break;
1672 case IS_FALSE:
1673 case IS_NOT_TRUE:
1674 selec = 1.0 - (double) clause_selectivity(root, arg,
1675 varRelid,
1676 jointype, sjinfo);
1677 break;
1678 default:
1679 elog(ERROR, "unrecognized booltesttype: %d",
1680 (int) booltesttype);
1681 selec = 0.0; /* Keep compiler quiet */
1682 break;
1686 ReleaseVariableStats(vardata);
1688 /* result should be in range, but make sure... */
1689 CLAMP_PROBABILITY(selec);
1691 return (Selectivity) selec;
1695 * nulltestsel - Selectivity of NullTest Node.
1697 Selectivity
1698 nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1699 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1701 VariableStatData vardata;
1702 double selec;
1704 examine_variable(root, arg, varRelid, &vardata);
1706 if (HeapTupleIsValid(vardata.statsTuple))
1708 Form_pg_statistic stats;
1709 double freq_null;
1711 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1712 freq_null = stats->stanullfrac;
1714 switch (nulltesttype)
1716 case IS_NULL:
1719 * Use freq_null directly.
1721 selec = freq_null;
1722 break;
1723 case IS_NOT_NULL:
1726 * Select not unknown (not null) values. Calculate from
1727 * freq_null.
1729 selec = 1.0 - freq_null;
1730 break;
1731 default:
1732 elog(ERROR, "unrecognized nulltesttype: %d",
1733 (int) nulltesttype);
1734 return (Selectivity) 0; /* keep compiler quiet */
1737 else if (vardata.var && IsA(vardata.var, Var) &&
1738 ((Var *) vardata.var)->varattno < 0)
1741 * There are no stats for system columns, but we know they are never
1742 * NULL.
1744 selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
1746 else
1749 * No ANALYZE stats available, so make a guess
1751 switch (nulltesttype)
1753 case IS_NULL:
1754 selec = DEFAULT_UNK_SEL;
1755 break;
1756 case IS_NOT_NULL:
1757 selec = DEFAULT_NOT_UNK_SEL;
1758 break;
1759 default:
1760 elog(ERROR, "unrecognized nulltesttype: %d",
1761 (int) nulltesttype);
1762 return (Selectivity) 0; /* keep compiler quiet */
1766 ReleaseVariableStats(vardata);
1768 /* result should be in range, but make sure... */
1769 CLAMP_PROBABILITY(selec);
1771 return (Selectivity) selec;
1775 * strip_array_coercion - strip binary-compatible relabeling from an array expr
1777 * For array values, the parser normally generates ArrayCoerceExpr conversions,
1778 * but it seems possible that RelabelType might show up. Also, the planner
1779 * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1780 * so we need to be ready to deal with more than one level.
1782 static Node *
1783 strip_array_coercion(Node *node)
1785 for (;;)
1787 if (node && IsA(node, ArrayCoerceExpr))
1789 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
1792 * If the per-element expression is just a RelabelType on top of
1793 * CaseTestExpr, then we know it's a binary-compatible relabeling.
1795 if (IsA(acoerce->elemexpr, RelabelType) &&
1796 IsA(((RelabelType *) acoerce->elemexpr)->arg, CaseTestExpr))
1797 node = (Node *) acoerce->arg;
1798 else
1799 break;
1801 else if (node && IsA(node, RelabelType))
1803 /* We don't really expect this case, but may as well cope */
1804 node = (Node *) ((RelabelType *) node)->arg;
1806 else
1807 break;
1809 return node;
1813 * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1815 Selectivity
1816 scalararraysel(PlannerInfo *root,
1817 ScalarArrayOpExpr *clause,
1818 bool is_join_clause,
1819 int varRelid,
1820 JoinType jointype,
1821 SpecialJoinInfo *sjinfo)
1823 Oid operator = clause->opno;
1824 bool useOr = clause->useOr;
1825 bool isEquality = false;
1826 bool isInequality = false;
1827 Node *leftop;
1828 Node *rightop;
1829 Oid nominal_element_type;
1830 Oid nominal_element_collation;
1831 TypeCacheEntry *typentry;
1832 RegProcedure oprsel;
1833 FmgrInfo oprselproc;
1834 Selectivity s1;
1835 Selectivity s1disjoint;
1837 /* First, deconstruct the expression */
1838 Assert(list_length(clause->args) == 2);
1839 leftop = (Node *) linitial(clause->args);
1840 rightop = (Node *) lsecond(clause->args);
1842 /* aggressively reduce both sides to constants */
1843 leftop = estimate_expression_value(root, leftop);
1844 rightop = estimate_expression_value(root, rightop);
1846 /* get nominal (after relabeling) element type of rightop */
1847 nominal_element_type = get_base_element_type(exprType(rightop));
1848 if (!OidIsValid(nominal_element_type))
1849 return (Selectivity) 0.5; /* probably shouldn't happen */
1850 /* get nominal collation, too, for generating constants */
1851 nominal_element_collation = exprCollation(rightop);
1853 /* look through any binary-compatible relabeling of rightop */
1854 rightop = strip_array_coercion(rightop);
1857 * Detect whether the operator is the default equality or inequality
1858 * operator of the array element type.
1860 typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1861 if (OidIsValid(typentry->eq_opr))
1863 if (operator == typentry->eq_opr)
1864 isEquality = true;
1865 else if (get_negator(operator) == typentry->eq_opr)
1866 isInequality = true;
1870 * If it is equality or inequality, we might be able to estimate this as a
1871 * form of array containment; for instance "const = ANY(column)" can be
1872 * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1873 * that, and returns the selectivity estimate if successful, or -1 if not.
1875 if ((isEquality || isInequality) && !is_join_clause)
1877 s1 = scalararraysel_containment(root, leftop, rightop,
1878 nominal_element_type,
1879 isEquality, useOr, varRelid);
1880 if (s1 >= 0.0)
1881 return s1;
1885 * Look up the underlying operator's selectivity estimator. Punt if it
1886 * hasn't got one.
1888 if (is_join_clause)
1889 oprsel = get_oprjoin(operator);
1890 else
1891 oprsel = get_oprrest(operator);
1892 if (!oprsel)
1893 return (Selectivity) 0.5;
1894 fmgr_info(oprsel, &oprselproc);
1897 * In the array-containment check above, we must only believe that an
1898 * operator is equality or inequality if it is the default btree equality
1899 * operator (or its negator) for the element type, since those are the
1900 * operators that array containment will use. But in what follows, we can
1901 * be a little laxer, and also believe that any operators using eqsel() or
1902 * neqsel() as selectivity estimator act like equality or inequality.
1904 if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1905 isEquality = true;
1906 else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1907 isInequality = true;
1910 * We consider three cases:
1912 * 1. rightop is an Array constant: deconstruct the array, apply the
1913 * operator's selectivity function for each array element, and merge the
1914 * results in the same way that clausesel.c does for AND/OR combinations.
1916 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1917 * function for each element of the ARRAY[] construct, and merge.
1919 * 3. otherwise, make a guess ...
1921 if (rightop && IsA(rightop, Const))
1923 Datum arraydatum = ((Const *) rightop)->constvalue;
1924 bool arrayisnull = ((Const *) rightop)->constisnull;
1925 ArrayType *arrayval;
1926 int16 elmlen;
1927 bool elmbyval;
1928 char elmalign;
1929 int num_elems;
1930 Datum *elem_values;
1931 bool *elem_nulls;
1932 int i;
1934 if (arrayisnull) /* qual can't succeed if null array */
1935 return (Selectivity) 0.0;
1936 arrayval = DatumGetArrayTypeP(arraydatum);
1937 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1938 &elmlen, &elmbyval, &elmalign);
1939 deconstruct_array(arrayval,
1940 ARR_ELEMTYPE(arrayval),
1941 elmlen, elmbyval, elmalign,
1942 &elem_values, &elem_nulls, &num_elems);
1945 * For generic operators, we assume the probability of success is
1946 * independent for each array element. But for "= ANY" or "<> ALL",
1947 * if the array elements are distinct (which'd typically be the case)
1948 * then the probabilities are disjoint, and we should just sum them.
1950 * If we were being really tense we would try to confirm that the
1951 * elements are all distinct, but that would be expensive and it
1952 * doesn't seem to be worth the cycles; it would amount to penalizing
1953 * well-written queries in favor of poorly-written ones. However, we
1954 * do protect ourselves a little bit by checking whether the
1955 * disjointness assumption leads to an impossible (out of range)
1956 * probability; if so, we fall back to the normal calculation.
1958 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1960 for (i = 0; i < num_elems; i++)
1962 List *args;
1963 Selectivity s2;
1965 args = list_make2(leftop,
1966 makeConst(nominal_element_type,
1968 nominal_element_collation,
1969 elmlen,
1970 elem_values[i],
1971 elem_nulls[i],
1972 elmbyval));
1973 if (is_join_clause)
1974 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1975 clause->inputcollid,
1976 PointerGetDatum(root),
1977 ObjectIdGetDatum(operator),
1978 PointerGetDatum(args),
1979 Int16GetDatum(jointype),
1980 PointerGetDatum(sjinfo)));
1981 else
1982 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1983 clause->inputcollid,
1984 PointerGetDatum(root),
1985 ObjectIdGetDatum(operator),
1986 PointerGetDatum(args),
1987 Int32GetDatum(varRelid)));
1989 if (useOr)
1991 s1 = s1 + s2 - s1 * s2;
1992 if (isEquality)
1993 s1disjoint += s2;
1995 else
1997 s1 = s1 * s2;
1998 if (isInequality)
1999 s1disjoint += s2 - 1.0;
2003 /* accept disjoint-probability estimate if in range */
2004 if ((useOr ? isEquality : isInequality) &&
2005 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2006 s1 = s1disjoint;
2008 else if (rightop && IsA(rightop, ArrayExpr) &&
2009 !((ArrayExpr *) rightop)->multidims)
2011 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2012 int16 elmlen;
2013 bool elmbyval;
2014 ListCell *l;
2016 get_typlenbyval(arrayexpr->element_typeid,
2017 &elmlen, &elmbyval);
2020 * We use the assumption of disjoint probabilities here too, although
2021 * the odds of equal array elements are rather higher if the elements
2022 * are not all constants (which they won't be, else constant folding
2023 * would have reduced the ArrayExpr to a Const). In this path it's
2024 * critical to have the sanity check on the s1disjoint estimate.
2026 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2028 foreach(l, arrayexpr->elements)
2030 Node *elem = (Node *) lfirst(l);
2031 List *args;
2032 Selectivity s2;
2035 * Theoretically, if elem isn't of nominal_element_type we should
2036 * insert a RelabelType, but it seems unlikely that any operator
2037 * estimation function would really care ...
2039 args = list_make2(leftop, elem);
2040 if (is_join_clause)
2041 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2042 clause->inputcollid,
2043 PointerGetDatum(root),
2044 ObjectIdGetDatum(operator),
2045 PointerGetDatum(args),
2046 Int16GetDatum(jointype),
2047 PointerGetDatum(sjinfo)));
2048 else
2049 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2050 clause->inputcollid,
2051 PointerGetDatum(root),
2052 ObjectIdGetDatum(operator),
2053 PointerGetDatum(args),
2054 Int32GetDatum(varRelid)));
2056 if (useOr)
2058 s1 = s1 + s2 - s1 * s2;
2059 if (isEquality)
2060 s1disjoint += s2;
2062 else
2064 s1 = s1 * s2;
2065 if (isInequality)
2066 s1disjoint += s2 - 1.0;
2070 /* accept disjoint-probability estimate if in range */
2071 if ((useOr ? isEquality : isInequality) &&
2072 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2073 s1 = s1disjoint;
2075 else
2077 CaseTestExpr *dummyexpr;
2078 List *args;
2079 Selectivity s2;
2080 int i;
2083 * We need a dummy rightop to pass to the operator selectivity
2084 * routine. It can be pretty much anything that doesn't look like a
2085 * constant; CaseTestExpr is a convenient choice.
2087 dummyexpr = makeNode(CaseTestExpr);
2088 dummyexpr->typeId = nominal_element_type;
2089 dummyexpr->typeMod = -1;
2090 dummyexpr->collation = clause->inputcollid;
2091 args = list_make2(leftop, dummyexpr);
2092 if (is_join_clause)
2093 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2094 clause->inputcollid,
2095 PointerGetDatum(root),
2096 ObjectIdGetDatum(operator),
2097 PointerGetDatum(args),
2098 Int16GetDatum(jointype),
2099 PointerGetDatum(sjinfo)));
2100 else
2101 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2102 clause->inputcollid,
2103 PointerGetDatum(root),
2104 ObjectIdGetDatum(operator),
2105 PointerGetDatum(args),
2106 Int32GetDatum(varRelid)));
2107 s1 = useOr ? 0.0 : 1.0;
2110 * Arbitrarily assume 10 elements in the eventual array value (see
2111 * also estimate_array_length). We don't risk an assumption of
2112 * disjoint probabilities here.
2114 for (i = 0; i < 10; i++)
2116 if (useOr)
2117 s1 = s1 + s2 - s1 * s2;
2118 else
2119 s1 = s1 * s2;
2123 /* result should be in range, but make sure... */
2124 CLAMP_PROBABILITY(s1);
2126 return s1;
2130 * Estimate number of elements in the array yielded by an expression.
2132 * Note: the result is integral, but we use "double" to avoid overflow
2133 * concerns. Most callers will use it in double-type expressions anyway.
2135 * Note: in some code paths root can be passed as NULL, resulting in
2136 * slightly worse estimates.
2138 double
2139 estimate_array_length(PlannerInfo *root, Node *arrayexpr)
2141 /* look through any binary-compatible relabeling of arrayexpr */
2142 arrayexpr = strip_array_coercion(arrayexpr);
2144 if (arrayexpr && IsA(arrayexpr, Const))
2146 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2147 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2148 ArrayType *arrayval;
2150 if (arrayisnull)
2151 return 0;
2152 arrayval = DatumGetArrayTypeP(arraydatum);
2153 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2155 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2156 !((ArrayExpr *) arrayexpr)->multidims)
2158 return list_length(((ArrayExpr *) arrayexpr)->elements);
2160 else if (arrayexpr && root)
2162 /* See if we can find any statistics about it */
2163 VariableStatData vardata;
2164 AttStatsSlot sslot;
2165 double nelem = 0;
2167 examine_variable(root, arrayexpr, 0, &vardata);
2168 if (HeapTupleIsValid(vardata.statsTuple))
2171 * Found stats, so use the average element count, which is stored
2172 * in the last stanumbers element of the DECHIST statistics.
2173 * Actually that is the average count of *distinct* elements;
2174 * perhaps we should scale it up somewhat?
2176 if (get_attstatsslot(&sslot, vardata.statsTuple,
2177 STATISTIC_KIND_DECHIST, InvalidOid,
2178 ATTSTATSSLOT_NUMBERS))
2180 if (sslot.nnumbers > 0)
2181 nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2182 free_attstatsslot(&sslot);
2185 ReleaseVariableStats(vardata);
2187 if (nelem > 0)
2188 return nelem;
2191 /* Else use a default guess --- this should match scalararraysel */
2192 return 10;
2196 * rowcomparesel - Selectivity of RowCompareExpr Node.
2198 * We estimate RowCompare selectivity by considering just the first (high
2199 * order) columns, which makes it equivalent to an ordinary OpExpr. While
2200 * this estimate could be refined by considering additional columns, it
2201 * seems unlikely that we could do a lot better without multi-column
2202 * statistics.
2204 Selectivity
2205 rowcomparesel(PlannerInfo *root,
2206 RowCompareExpr *clause,
2207 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
2209 Selectivity s1;
2210 Oid opno = linitial_oid(clause->opnos);
2211 Oid inputcollid = linitial_oid(clause->inputcollids);
2212 List *opargs;
2213 bool is_join_clause;
2215 /* Build equivalent arg list for single operator */
2216 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2219 * Decide if it's a join clause. This should match clausesel.c's
2220 * treat_as_join_clause(), except that we intentionally consider only the
2221 * leading columns and not the rest of the clause.
2223 if (varRelid != 0)
2226 * Caller is forcing restriction mode (eg, because we are examining an
2227 * inner indexscan qual).
2229 is_join_clause = false;
2231 else if (sjinfo == NULL)
2234 * It must be a restriction clause, since it's being evaluated at a
2235 * scan node.
2237 is_join_clause = false;
2239 else
2242 * Otherwise, it's a join if there's more than one base relation used.
2244 is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2247 if (is_join_clause)
2249 /* Estimate selectivity for a join clause. */
2250 s1 = join_selectivity(root, opno,
2251 opargs,
2252 inputcollid,
2253 jointype,
2254 sjinfo);
2256 else
2258 /* Estimate selectivity for a restriction clause. */
2259 s1 = restriction_selectivity(root, opno,
2260 opargs,
2261 inputcollid,
2262 varRelid);
2265 return s1;
2269 * eqjoinsel - Join selectivity of "="
2271 Datum
2272 eqjoinsel(PG_FUNCTION_ARGS)
2274 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2275 Oid operator = PG_GETARG_OID(1);
2276 List *args = (List *) PG_GETARG_POINTER(2);
2278 #ifdef NOT_USED
2279 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2280 #endif
2281 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2282 Oid collation = PG_GET_COLLATION();
2283 double selec;
2284 double selec_inner;
2285 VariableStatData vardata1;
2286 VariableStatData vardata2;
2287 double nd1;
2288 double nd2;
2289 bool isdefault1;
2290 bool isdefault2;
2291 Oid opfuncoid;
2292 AttStatsSlot sslot1;
2293 AttStatsSlot sslot2;
2294 Form_pg_statistic stats1 = NULL;
2295 Form_pg_statistic stats2 = NULL;
2296 bool have_mcvs1 = false;
2297 bool have_mcvs2 = false;
2298 bool get_mcv_stats;
2299 bool join_is_reversed;
2300 RelOptInfo *inner_rel;
2302 get_join_variables(root, args, sjinfo,
2303 &vardata1, &vardata2, &join_is_reversed);
2305 nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2306 nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2308 opfuncoid = get_opcode(operator);
2310 memset(&sslot1, 0, sizeof(sslot1));
2311 memset(&sslot2, 0, sizeof(sslot2));
2314 * There is no use in fetching one side's MCVs if we lack MCVs for the
2315 * other side, so do a quick check to verify that both stats exist.
2317 get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
2318 HeapTupleIsValid(vardata2.statsTuple) &&
2319 get_attstatsslot(&sslot1, vardata1.statsTuple,
2320 STATISTIC_KIND_MCV, InvalidOid,
2321 0) &&
2322 get_attstatsslot(&sslot2, vardata2.statsTuple,
2323 STATISTIC_KIND_MCV, InvalidOid,
2324 0));
2326 if (HeapTupleIsValid(vardata1.statsTuple))
2328 /* note we allow use of nullfrac regardless of security check */
2329 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2330 if (get_mcv_stats &&
2331 statistic_proc_security_check(&vardata1, opfuncoid))
2332 have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2333 STATISTIC_KIND_MCV, InvalidOid,
2334 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
2337 if (HeapTupleIsValid(vardata2.statsTuple))
2339 /* note we allow use of nullfrac regardless of security check */
2340 stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2341 if (get_mcv_stats &&
2342 statistic_proc_security_check(&vardata2, opfuncoid))
2343 have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2344 STATISTIC_KIND_MCV, InvalidOid,
2345 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
2348 /* We need to compute the inner-join selectivity in all cases */
2349 selec_inner = eqjoinsel_inner(opfuncoid, collation,
2350 &vardata1, &vardata2,
2351 nd1, nd2,
2352 isdefault1, isdefault2,
2353 &sslot1, &sslot2,
2354 stats1, stats2,
2355 have_mcvs1, have_mcvs2);
2357 switch (sjinfo->jointype)
2359 case JOIN_INNER:
2360 case JOIN_LEFT:
2361 case JOIN_FULL:
2362 selec = selec_inner;
2363 break;
2364 case JOIN_SEMI:
2365 case JOIN_ANTI:
2368 * Look up the join's inner relation. min_righthand is sufficient
2369 * information because neither SEMI nor ANTI joins permit any
2370 * reassociation into or out of their RHS, so the righthand will
2371 * always be exactly that set of rels.
2373 inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2375 if (!join_is_reversed)
2376 selec = eqjoinsel_semi(opfuncoid, collation,
2377 &vardata1, &vardata2,
2378 nd1, nd2,
2379 isdefault1, isdefault2,
2380 &sslot1, &sslot2,
2381 stats1, stats2,
2382 have_mcvs1, have_mcvs2,
2383 inner_rel);
2384 else
2386 Oid commop = get_commutator(operator);
2387 Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2389 selec = eqjoinsel_semi(commopfuncoid, collation,
2390 &vardata2, &vardata1,
2391 nd2, nd1,
2392 isdefault2, isdefault1,
2393 &sslot2, &sslot1,
2394 stats2, stats1,
2395 have_mcvs2, have_mcvs1,
2396 inner_rel);
2400 * We should never estimate the output of a semijoin to be more
2401 * rows than we estimate for an inner join with the same input
2402 * rels and join condition; it's obviously impossible for that to
2403 * happen. The former estimate is N1 * Ssemi while the latter is
2404 * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner. Doing
2405 * this is worthwhile because of the shakier estimation rules we
2406 * use in eqjoinsel_semi, particularly in cases where it has to
2407 * punt entirely.
2409 selec = Min(selec, inner_rel->rows * selec_inner);
2410 break;
2411 default:
2412 /* other values not expected here */
2413 elog(ERROR, "unrecognized join type: %d",
2414 (int) sjinfo->jointype);
2415 selec = 0; /* keep compiler quiet */
2416 break;
2419 free_attstatsslot(&sslot1);
2420 free_attstatsslot(&sslot2);
2422 ReleaseVariableStats(vardata1);
2423 ReleaseVariableStats(vardata2);
2425 CLAMP_PROBABILITY(selec);
2427 PG_RETURN_FLOAT8((float8) selec);
2431 * eqjoinsel_inner --- eqjoinsel for normal inner join
2433 * We also use this for LEFT/FULL outer joins; it's not presently clear
2434 * that it's worth trying to distinguish them here.
2436 static double
2437 eqjoinsel_inner(Oid opfuncoid, Oid collation,
2438 VariableStatData *vardata1, VariableStatData *vardata2,
2439 double nd1, double nd2,
2440 bool isdefault1, bool isdefault2,
2441 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2442 Form_pg_statistic stats1, Form_pg_statistic stats2,
2443 bool have_mcvs1, bool have_mcvs2)
2445 double selec;
2447 if (have_mcvs1 && have_mcvs2)
2450 * We have most-common-value lists for both relations. Run through
2451 * the lists to see which MCVs actually join to each other with the
2452 * given operator. This allows us to determine the exact join
2453 * selectivity for the portion of the relations represented by the MCV
2454 * lists. We still have to estimate for the remaining population, but
2455 * in a skewed distribution this gives us a big leg up in accuracy.
2456 * For motivation see the analysis in Y. Ioannidis and S.
2457 * Christodoulakis, "On the propagation of errors in the size of join
2458 * results", Technical Report 1018, Computer Science Dept., University
2459 * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2461 LOCAL_FCINFO(fcinfo, 2);
2462 FmgrInfo eqproc;
2463 bool *hasmatch1;
2464 bool *hasmatch2;
2465 double nullfrac1 = stats1->stanullfrac;
2466 double nullfrac2 = stats2->stanullfrac;
2467 double matchprodfreq,
2468 matchfreq1,
2469 matchfreq2,
2470 unmatchfreq1,
2471 unmatchfreq2,
2472 otherfreq1,
2473 otherfreq2,
2474 totalsel1,
2475 totalsel2;
2476 int i,
2477 nmatches;
2479 fmgr_info(opfuncoid, &eqproc);
2482 * Save a few cycles by setting up the fcinfo struct just once. Using
2483 * FunctionCallInvoke directly also avoids failure if the eqproc
2484 * returns NULL, though really equality functions should never do
2485 * that.
2487 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2488 NULL, NULL);
2489 fcinfo->args[0].isnull = false;
2490 fcinfo->args[1].isnull = false;
2492 hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2493 hasmatch2 = (bool *) palloc0(sslot2->nvalues * sizeof(bool));
2496 * Note we assume that each MCV will match at most one member of the
2497 * other MCV list. If the operator isn't really equality, there could
2498 * be multiple matches --- but we don't look for them, both for speed
2499 * and because the math wouldn't add up...
2501 matchprodfreq = 0.0;
2502 nmatches = 0;
2503 for (i = 0; i < sslot1->nvalues; i++)
2505 int j;
2507 fcinfo->args[0].value = sslot1->values[i];
2509 for (j = 0; j < sslot2->nvalues; j++)
2511 Datum fresult;
2513 if (hasmatch2[j])
2514 continue;
2515 fcinfo->args[1].value = sslot2->values[j];
2516 fcinfo->isnull = false;
2517 fresult = FunctionCallInvoke(fcinfo);
2518 if (!fcinfo->isnull && DatumGetBool(fresult))
2520 hasmatch1[i] = hasmatch2[j] = true;
2521 matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2522 nmatches++;
2523 break;
2527 CLAMP_PROBABILITY(matchprodfreq);
2528 /* Sum up frequencies of matched and unmatched MCVs */
2529 matchfreq1 = unmatchfreq1 = 0.0;
2530 for (i = 0; i < sslot1->nvalues; i++)
2532 if (hasmatch1[i])
2533 matchfreq1 += sslot1->numbers[i];
2534 else
2535 unmatchfreq1 += sslot1->numbers[i];
2537 CLAMP_PROBABILITY(matchfreq1);
2538 CLAMP_PROBABILITY(unmatchfreq1);
2539 matchfreq2 = unmatchfreq2 = 0.0;
2540 for (i = 0; i < sslot2->nvalues; i++)
2542 if (hasmatch2[i])
2543 matchfreq2 += sslot2->numbers[i];
2544 else
2545 unmatchfreq2 += sslot2->numbers[i];
2547 CLAMP_PROBABILITY(matchfreq2);
2548 CLAMP_PROBABILITY(unmatchfreq2);
2549 pfree(hasmatch1);
2550 pfree(hasmatch2);
2553 * Compute total frequency of non-null values that are not in the MCV
2554 * lists.
2556 otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2557 otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2558 CLAMP_PROBABILITY(otherfreq1);
2559 CLAMP_PROBABILITY(otherfreq2);
2562 * We can estimate the total selectivity from the point of view of
2563 * relation 1 as: the known selectivity for matched MCVs, plus
2564 * unmatched MCVs that are assumed to match against random members of
2565 * relation 2's non-MCV population, plus non-MCV values that are
2566 * assumed to match against random members of relation 2's unmatched
2567 * MCVs plus non-MCV values.
2569 totalsel1 = matchprodfreq;
2570 if (nd2 > sslot2->nvalues)
2571 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2572 if (nd2 > nmatches)
2573 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2574 (nd2 - nmatches);
2575 /* Same estimate from the point of view of relation 2. */
2576 totalsel2 = matchprodfreq;
2577 if (nd1 > sslot1->nvalues)
2578 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2579 if (nd1 > nmatches)
2580 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2581 (nd1 - nmatches);
2584 * Use the smaller of the two estimates. This can be justified in
2585 * essentially the same terms as given below for the no-stats case: to
2586 * a first approximation, we are estimating from the point of view of
2587 * the relation with smaller nd.
2589 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2591 else
2594 * We do not have MCV lists for both sides. Estimate the join
2595 * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2596 * is plausible if we assume that the join operator is strict and the
2597 * non-null values are about equally distributed: a given non-null
2598 * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2599 * of rel2, so total join rows are at most
2600 * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2601 * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2602 * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2603 * with MIN() is an upper bound. Using the MIN() means we estimate
2604 * from the point of view of the relation with smaller nd (since the
2605 * larger nd is determining the MIN). It is reasonable to assume that
2606 * most tuples in this rel will have join partners, so the bound is
2607 * probably reasonably tight and should be taken as-is.
2609 * XXX Can we be smarter if we have an MCV list for just one side? It
2610 * seems that if we assume equal distribution for the other side, we
2611 * end up with the same answer anyway.
2613 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2614 double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2616 selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2617 if (nd1 > nd2)
2618 selec /= nd1;
2619 else
2620 selec /= nd2;
2623 return selec;
2627 * eqjoinsel_semi --- eqjoinsel for semi join
2629 * (Also used for anti join, which we are supposed to estimate the same way.)
2630 * Caller has ensured that vardata1 is the LHS variable.
2631 * Unlike eqjoinsel_inner, we have to cope with opfuncoid being InvalidOid.
2633 static double
2634 eqjoinsel_semi(Oid opfuncoid, Oid collation,
2635 VariableStatData *vardata1, VariableStatData *vardata2,
2636 double nd1, double nd2,
2637 bool isdefault1, bool isdefault2,
2638 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2639 Form_pg_statistic stats1, Form_pg_statistic stats2,
2640 bool have_mcvs1, bool have_mcvs2,
2641 RelOptInfo *inner_rel)
2643 double selec;
2646 * We clamp nd2 to be not more than what we estimate the inner relation's
2647 * size to be. This is intuitively somewhat reasonable since obviously
2648 * there can't be more than that many distinct values coming from the
2649 * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2650 * likewise) is that this is the only pathway by which restriction clauses
2651 * applied to the inner rel will affect the join result size estimate,
2652 * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2653 * only the outer rel's size. If we clamped nd1 we'd be double-counting
2654 * the selectivity of outer-rel restrictions.
2656 * We can apply this clamping both with respect to the base relation from
2657 * which the join variable comes (if there is just one), and to the
2658 * immediate inner input relation of the current join.
2660 * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2661 * great, maybe, but it didn't come out of nowhere either. This is most
2662 * helpful when the inner relation is empty and consequently has no stats.
2664 if (vardata2->rel)
2666 if (nd2 >= vardata2->rel->rows)
2668 nd2 = vardata2->rel->rows;
2669 isdefault2 = false;
2672 if (nd2 >= inner_rel->rows)
2674 nd2 = inner_rel->rows;
2675 isdefault2 = false;
2678 if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2681 * We have most-common-value lists for both relations. Run through
2682 * the lists to see which MCVs actually join to each other with the
2683 * given operator. This allows us to determine the exact join
2684 * selectivity for the portion of the relations represented by the MCV
2685 * lists. We still have to estimate for the remaining population, but
2686 * in a skewed distribution this gives us a big leg up in accuracy.
2688 LOCAL_FCINFO(fcinfo, 2);
2689 FmgrInfo eqproc;
2690 bool *hasmatch1;
2691 bool *hasmatch2;
2692 double nullfrac1 = stats1->stanullfrac;
2693 double matchfreq1,
2694 uncertainfrac,
2695 uncertain;
2696 int i,
2697 nmatches,
2698 clamped_nvalues2;
2701 * The clamping above could have resulted in nd2 being less than
2702 * sslot2->nvalues; in which case, we assume that precisely the nd2
2703 * most common values in the relation will appear in the join input,
2704 * and so compare to only the first nd2 members of the MCV list. Of
2705 * course this is frequently wrong, but it's the best bet we can make.
2707 clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2709 fmgr_info(opfuncoid, &eqproc);
2712 * Save a few cycles by setting up the fcinfo struct just once. Using
2713 * FunctionCallInvoke directly also avoids failure if the eqproc
2714 * returns NULL, though really equality functions should never do
2715 * that.
2717 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2718 NULL, NULL);
2719 fcinfo->args[0].isnull = false;
2720 fcinfo->args[1].isnull = false;
2722 hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2723 hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2726 * Note we assume that each MCV will match at most one member of the
2727 * other MCV list. If the operator isn't really equality, there could
2728 * be multiple matches --- but we don't look for them, both for speed
2729 * and because the math wouldn't add up...
2731 nmatches = 0;
2732 for (i = 0; i < sslot1->nvalues; i++)
2734 int j;
2736 fcinfo->args[0].value = sslot1->values[i];
2738 for (j = 0; j < clamped_nvalues2; j++)
2740 Datum fresult;
2742 if (hasmatch2[j])
2743 continue;
2744 fcinfo->args[1].value = sslot2->values[j];
2745 fcinfo->isnull = false;
2746 fresult = FunctionCallInvoke(fcinfo);
2747 if (!fcinfo->isnull && DatumGetBool(fresult))
2749 hasmatch1[i] = hasmatch2[j] = true;
2750 nmatches++;
2751 break;
2755 /* Sum up frequencies of matched MCVs */
2756 matchfreq1 = 0.0;
2757 for (i = 0; i < sslot1->nvalues; i++)
2759 if (hasmatch1[i])
2760 matchfreq1 += sslot1->numbers[i];
2762 CLAMP_PROBABILITY(matchfreq1);
2763 pfree(hasmatch1);
2764 pfree(hasmatch2);
2767 * Now we need to estimate the fraction of relation 1 that has at
2768 * least one join partner. We know for certain that the matched MCVs
2769 * do, so that gives us a lower bound, but we're really in the dark
2770 * about everything else. Our crude approach is: if nd1 <= nd2 then
2771 * assume all non-null rel1 rows have join partners, else assume for
2772 * the uncertain rows that a fraction nd2/nd1 have join partners. We
2773 * can discount the known-matched MCVs from the distinct-values counts
2774 * before doing the division.
2776 * Crude as the above is, it's completely useless if we don't have
2777 * reliable ndistinct values for both sides. Hence, if either nd1 or
2778 * nd2 is default, punt and assume half of the uncertain rows have
2779 * join partners.
2781 if (!isdefault1 && !isdefault2)
2783 nd1 -= nmatches;
2784 nd2 -= nmatches;
2785 if (nd1 <= nd2 || nd2 < 0)
2786 uncertainfrac = 1.0;
2787 else
2788 uncertainfrac = nd2 / nd1;
2790 else
2791 uncertainfrac = 0.5;
2792 uncertain = 1.0 - matchfreq1 - nullfrac1;
2793 CLAMP_PROBABILITY(uncertain);
2794 selec = matchfreq1 + uncertainfrac * uncertain;
2796 else
2799 * Without MCV lists for both sides, we can only use the heuristic
2800 * about nd1 vs nd2.
2802 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2804 if (!isdefault1 && !isdefault2)
2806 if (nd1 <= nd2 || nd2 < 0)
2807 selec = 1.0 - nullfrac1;
2808 else
2809 selec = (nd2 / nd1) * (1.0 - nullfrac1);
2811 else
2812 selec = 0.5 * (1.0 - nullfrac1);
2815 return selec;
2819 * neqjoinsel - Join selectivity of "!="
2821 Datum
2822 neqjoinsel(PG_FUNCTION_ARGS)
2824 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2825 Oid operator = PG_GETARG_OID(1);
2826 List *args = (List *) PG_GETARG_POINTER(2);
2827 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2828 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2829 Oid collation = PG_GET_COLLATION();
2830 float8 result;
2832 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2835 * For semi-joins, if there is more than one distinct value in the RHS
2836 * relation then every non-null LHS row must find a row to join since
2837 * it can only be equal to one of them. We'll assume that there is
2838 * always more than one distinct RHS value for the sake of stability,
2839 * though in theory we could have special cases for empty RHS
2840 * (selectivity = 0) and single-distinct-value RHS (selectivity =
2841 * fraction of LHS that has the same value as the single RHS value).
2843 * For anti-joins, if we use the same assumption that there is more
2844 * than one distinct key in the RHS relation, then every non-null LHS
2845 * row must be suppressed by the anti-join.
2847 * So either way, the selectivity estimate should be 1 - nullfrac.
2849 VariableStatData leftvar;
2850 VariableStatData rightvar;
2851 bool reversed;
2852 HeapTuple statsTuple;
2853 double nullfrac;
2855 get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
2856 statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
2857 if (HeapTupleIsValid(statsTuple))
2858 nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
2859 else
2860 nullfrac = 0.0;
2861 ReleaseVariableStats(leftvar);
2862 ReleaseVariableStats(rightvar);
2864 result = 1.0 - nullfrac;
2866 else
2869 * We want 1 - eqjoinsel() where the equality operator is the one
2870 * associated with this != operator, that is, its negator.
2872 Oid eqop = get_negator(operator);
2874 if (eqop)
2876 result =
2877 DatumGetFloat8(DirectFunctionCall5Coll(eqjoinsel,
2878 collation,
2879 PointerGetDatum(root),
2880 ObjectIdGetDatum(eqop),
2881 PointerGetDatum(args),
2882 Int16GetDatum(jointype),
2883 PointerGetDatum(sjinfo)));
2885 else
2887 /* Use default selectivity (should we raise an error instead?) */
2888 result = DEFAULT_EQ_SEL;
2890 result = 1.0 - result;
2893 PG_RETURN_FLOAT8(result);
2897 * scalarltjoinsel - Join selectivity of "<" for scalars
2899 Datum
2900 scalarltjoinsel(PG_FUNCTION_ARGS)
2902 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2906 * scalarlejoinsel - Join selectivity of "<=" for scalars
2908 Datum
2909 scalarlejoinsel(PG_FUNCTION_ARGS)
2911 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2915 * scalargtjoinsel - Join selectivity of ">" for scalars
2917 Datum
2918 scalargtjoinsel(PG_FUNCTION_ARGS)
2920 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2924 * scalargejoinsel - Join selectivity of ">=" for scalars
2926 Datum
2927 scalargejoinsel(PG_FUNCTION_ARGS)
2929 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2934 * mergejoinscansel - Scan selectivity of merge join.
2936 * A merge join will stop as soon as it exhausts either input stream.
2937 * Therefore, if we can estimate the ranges of both input variables,
2938 * we can estimate how much of the input will actually be read. This
2939 * can have a considerable impact on the cost when using indexscans.
2941 * Also, we can estimate how much of each input has to be read before the
2942 * first join pair is found, which will affect the join's startup time.
2944 * clause should be a clause already known to be mergejoinable. opfamily,
2945 * strategy, and nulls_first specify the sort ordering being used.
2947 * The outputs are:
2948 * *leftstart is set to the fraction of the left-hand variable expected
2949 * to be scanned before the first join pair is found (0 to 1).
2950 * *leftend is set to the fraction of the left-hand variable expected
2951 * to be scanned before the join terminates (0 to 1).
2952 * *rightstart, *rightend similarly for the right-hand variable.
2954 void
2955 mergejoinscansel(PlannerInfo *root, Node *clause,
2956 Oid opfamily, int strategy, bool nulls_first,
2957 Selectivity *leftstart, Selectivity *leftend,
2958 Selectivity *rightstart, Selectivity *rightend)
2960 Node *left,
2961 *right;
2962 VariableStatData leftvar,
2963 rightvar;
2964 int op_strategy;
2965 Oid op_lefttype;
2966 Oid op_righttype;
2967 Oid opno,
2968 collation,
2969 lsortop,
2970 rsortop,
2971 lstatop,
2972 rstatop,
2973 ltop,
2974 leop,
2975 revltop,
2976 revleop;
2977 bool isgt;
2978 Datum leftmin,
2979 leftmax,
2980 rightmin,
2981 rightmax;
2982 double selec;
2984 /* Set default results if we can't figure anything out. */
2985 /* XXX should default "start" fraction be a bit more than 0? */
2986 *leftstart = *rightstart = 0.0;
2987 *leftend = *rightend = 1.0;
2989 /* Deconstruct the merge clause */
2990 if (!is_opclause(clause))
2991 return; /* shouldn't happen */
2992 opno = ((OpExpr *) clause)->opno;
2993 collation = ((OpExpr *) clause)->inputcollid;
2994 left = get_leftop((Expr *) clause);
2995 right = get_rightop((Expr *) clause);
2996 if (!right)
2997 return; /* shouldn't happen */
2999 /* Look for stats for the inputs */
3000 examine_variable(root, left, 0, &leftvar);
3001 examine_variable(root, right, 0, &rightvar);
3003 /* Extract the operator's declared left/right datatypes */
3004 get_op_opfamily_properties(opno, opfamily, false,
3005 &op_strategy,
3006 &op_lefttype,
3007 &op_righttype);
3008 Assert(op_strategy == BTEqualStrategyNumber);
3011 * Look up the various operators we need. If we don't find them all, it
3012 * probably means the opfamily is broken, but we just fail silently.
3014 * Note: we expect that pg_statistic histograms will be sorted by the '<'
3015 * operator, regardless of which sort direction we are considering.
3017 switch (strategy)
3019 case BTLessStrategyNumber:
3020 isgt = false;
3021 if (op_lefttype == op_righttype)
3023 /* easy case */
3024 ltop = get_opfamily_member(opfamily,
3025 op_lefttype, op_righttype,
3026 BTLessStrategyNumber);
3027 leop = get_opfamily_member(opfamily,
3028 op_lefttype, op_righttype,
3029 BTLessEqualStrategyNumber);
3030 lsortop = ltop;
3031 rsortop = ltop;
3032 lstatop = lsortop;
3033 rstatop = rsortop;
3034 revltop = ltop;
3035 revleop = leop;
3037 else
3039 ltop = get_opfamily_member(opfamily,
3040 op_lefttype, op_righttype,
3041 BTLessStrategyNumber);
3042 leop = get_opfamily_member(opfamily,
3043 op_lefttype, op_righttype,
3044 BTLessEqualStrategyNumber);
3045 lsortop = get_opfamily_member(opfamily,
3046 op_lefttype, op_lefttype,
3047 BTLessStrategyNumber);
3048 rsortop = get_opfamily_member(opfamily,
3049 op_righttype, op_righttype,
3050 BTLessStrategyNumber);
3051 lstatop = lsortop;
3052 rstatop = rsortop;
3053 revltop = get_opfamily_member(opfamily,
3054 op_righttype, op_lefttype,
3055 BTLessStrategyNumber);
3056 revleop = get_opfamily_member(opfamily,
3057 op_righttype, op_lefttype,
3058 BTLessEqualStrategyNumber);
3060 break;
3061 case BTGreaterStrategyNumber:
3062 /* descending-order case */
3063 isgt = true;
3064 if (op_lefttype == op_righttype)
3066 /* easy case */
3067 ltop = get_opfamily_member(opfamily,
3068 op_lefttype, op_righttype,
3069 BTGreaterStrategyNumber);
3070 leop = get_opfamily_member(opfamily,
3071 op_lefttype, op_righttype,
3072 BTGreaterEqualStrategyNumber);
3073 lsortop = ltop;
3074 rsortop = ltop;
3075 lstatop = get_opfamily_member(opfamily,
3076 op_lefttype, op_lefttype,
3077 BTLessStrategyNumber);
3078 rstatop = lstatop;
3079 revltop = ltop;
3080 revleop = leop;
3082 else
3084 ltop = get_opfamily_member(opfamily,
3085 op_lefttype, op_righttype,
3086 BTGreaterStrategyNumber);
3087 leop = get_opfamily_member(opfamily,
3088 op_lefttype, op_righttype,
3089 BTGreaterEqualStrategyNumber);
3090 lsortop = get_opfamily_member(opfamily,
3091 op_lefttype, op_lefttype,
3092 BTGreaterStrategyNumber);
3093 rsortop = get_opfamily_member(opfamily,
3094 op_righttype, op_righttype,
3095 BTGreaterStrategyNumber);
3096 lstatop = get_opfamily_member(opfamily,
3097 op_lefttype, op_lefttype,
3098 BTLessStrategyNumber);
3099 rstatop = get_opfamily_member(opfamily,
3100 op_righttype, op_righttype,
3101 BTLessStrategyNumber);
3102 revltop = get_opfamily_member(opfamily,
3103 op_righttype, op_lefttype,
3104 BTGreaterStrategyNumber);
3105 revleop = get_opfamily_member(opfamily,
3106 op_righttype, op_lefttype,
3107 BTGreaterEqualStrategyNumber);
3109 break;
3110 default:
3111 goto fail; /* shouldn't get here */
3114 if (!OidIsValid(lsortop) ||
3115 !OidIsValid(rsortop) ||
3116 !OidIsValid(lstatop) ||
3117 !OidIsValid(rstatop) ||
3118 !OidIsValid(ltop) ||
3119 !OidIsValid(leop) ||
3120 !OidIsValid(revltop) ||
3121 !OidIsValid(revleop))
3122 goto fail; /* insufficient info in catalogs */
3124 /* Try to get ranges of both inputs */
3125 if (!isgt)
3127 if (!get_variable_range(root, &leftvar, lstatop, collation,
3128 &leftmin, &leftmax))
3129 goto fail; /* no range available from stats */
3130 if (!get_variable_range(root, &rightvar, rstatop, collation,
3131 &rightmin, &rightmax))
3132 goto fail; /* no range available from stats */
3134 else
3136 /* need to swap the max and min */
3137 if (!get_variable_range(root, &leftvar, lstatop, collation,
3138 &leftmax, &leftmin))
3139 goto fail; /* no range available from stats */
3140 if (!get_variable_range(root, &rightvar, rstatop, collation,
3141 &rightmax, &rightmin))
3142 goto fail; /* no range available from stats */
3146 * Now, the fraction of the left variable that will be scanned is the
3147 * fraction that's <= the right-side maximum value. But only believe
3148 * non-default estimates, else stick with our 1.0.
3150 selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
3151 rightmax, op_righttype);
3152 if (selec != DEFAULT_INEQ_SEL)
3153 *leftend = selec;
3155 /* And similarly for the right variable. */
3156 selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
3157 leftmax, op_lefttype);
3158 if (selec != DEFAULT_INEQ_SEL)
3159 *rightend = selec;
3162 * Only one of the two "end" fractions can really be less than 1.0;
3163 * believe the smaller estimate and reset the other one to exactly 1.0. If
3164 * we get exactly equal estimates (as can easily happen with self-joins),
3165 * believe neither.
3167 if (*leftend > *rightend)
3168 *leftend = 1.0;
3169 else if (*leftend < *rightend)
3170 *rightend = 1.0;
3171 else
3172 *leftend = *rightend = 1.0;
3175 * Also, the fraction of the left variable that will be scanned before the
3176 * first join pair is found is the fraction that's < the right-side
3177 * minimum value. But only believe non-default estimates, else stick with
3178 * our own default.
3180 selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
3181 rightmin, op_righttype);
3182 if (selec != DEFAULT_INEQ_SEL)
3183 *leftstart = selec;
3185 /* And similarly for the right variable. */
3186 selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
3187 leftmin, op_lefttype);
3188 if (selec != DEFAULT_INEQ_SEL)
3189 *rightstart = selec;
3192 * Only one of the two "start" fractions can really be more than zero;
3193 * believe the larger estimate and reset the other one to exactly 0.0. If
3194 * we get exactly equal estimates (as can easily happen with self-joins),
3195 * believe neither.
3197 if (*leftstart < *rightstart)
3198 *leftstart = 0.0;
3199 else if (*leftstart > *rightstart)
3200 *rightstart = 0.0;
3201 else
3202 *leftstart = *rightstart = 0.0;
3205 * If the sort order is nulls-first, we're going to have to skip over any
3206 * nulls too. These would not have been counted by scalarineqsel, and we
3207 * can safely add in this fraction regardless of whether we believe
3208 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3210 if (nulls_first)
3212 Form_pg_statistic stats;
3214 if (HeapTupleIsValid(leftvar.statsTuple))
3216 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3217 *leftstart += stats->stanullfrac;
3218 CLAMP_PROBABILITY(*leftstart);
3219 *leftend += stats->stanullfrac;
3220 CLAMP_PROBABILITY(*leftend);
3222 if (HeapTupleIsValid(rightvar.statsTuple))
3224 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3225 *rightstart += stats->stanullfrac;
3226 CLAMP_PROBABILITY(*rightstart);
3227 *rightend += stats->stanullfrac;
3228 CLAMP_PROBABILITY(*rightend);
3232 /* Disbelieve start >= end, just in case that can happen */
3233 if (*leftstart >= *leftend)
3235 *leftstart = 0.0;
3236 *leftend = 1.0;
3238 if (*rightstart >= *rightend)
3240 *rightstart = 0.0;
3241 *rightend = 1.0;
3244 fail:
3245 ReleaseVariableStats(leftvar);
3246 ReleaseVariableStats(rightvar);
3251 * matchingsel -- generic matching-operator selectivity support
3253 * Use these for any operators that (a) are on data types for which we collect
3254 * standard statistics, and (b) have behavior for which the default estimate
3255 * (twice DEFAULT_EQ_SEL) is sane. Typically that is good for match-like
3256 * operators.
3259 Datum
3260 matchingsel(PG_FUNCTION_ARGS)
3262 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
3263 Oid operator = PG_GETARG_OID(1);
3264 List *args = (List *) PG_GETARG_POINTER(2);
3265 int varRelid = PG_GETARG_INT32(3);
3266 Oid collation = PG_GET_COLLATION();
3267 double selec;
3269 /* Use generic restriction selectivity logic. */
3270 selec = generic_restriction_selectivity(root, operator, collation,
3271 args, varRelid,
3272 DEFAULT_MATCHING_SEL);
3274 PG_RETURN_FLOAT8((float8) selec);
3277 Datum
3278 matchingjoinsel(PG_FUNCTION_ARGS)
3280 /* Just punt, for the moment. */
3281 PG_RETURN_FLOAT8(DEFAULT_MATCHING_SEL);
3286 * Helper routine for estimate_num_groups: add an item to a list of
3287 * GroupVarInfos, but only if it's not known equal to any of the existing
3288 * entries.
3290 typedef struct
3292 Node *var; /* might be an expression, not just a Var */
3293 RelOptInfo *rel; /* relation it belongs to */
3294 double ndistinct; /* # distinct values */
3295 bool isdefault; /* true if DEFAULT_NUM_DISTINCT was used */
3296 } GroupVarInfo;
3298 static List *
3299 add_unique_group_var(PlannerInfo *root, List *varinfos,
3300 Node *var, VariableStatData *vardata)
3302 GroupVarInfo *varinfo;
3303 double ndistinct;
3304 bool isdefault;
3305 ListCell *lc;
3307 ndistinct = get_variable_numdistinct(vardata, &isdefault);
3309 foreach(lc, varinfos)
3311 varinfo = (GroupVarInfo *) lfirst(lc);
3313 /* Drop exact duplicates */
3314 if (equal(var, varinfo->var))
3315 return varinfos;
3318 * Drop known-equal vars, but only if they belong to different
3319 * relations (see comments for estimate_num_groups)
3321 if (vardata->rel != varinfo->rel &&
3322 exprs_known_equal(root, var, varinfo->var))
3324 if (varinfo->ndistinct <= ndistinct)
3326 /* Keep older item, forget new one */
3327 return varinfos;
3329 else
3331 /* Delete the older item */
3332 varinfos = foreach_delete_current(varinfos, lc);
3337 varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3339 varinfo->var = var;
3340 varinfo->rel = vardata->rel;
3341 varinfo->ndistinct = ndistinct;
3342 varinfo->isdefault = isdefault;
3343 varinfos = lappend(varinfos, varinfo);
3344 return varinfos;
3348 * estimate_num_groups - Estimate number of groups in a grouped query
3350 * Given a query having a GROUP BY clause, estimate how many groups there
3351 * will be --- ie, the number of distinct combinations of the GROUP BY
3352 * expressions.
3354 * This routine is also used to estimate the number of rows emitted by
3355 * a DISTINCT filtering step; that is an isomorphic problem. (Note:
3356 * actually, we only use it for DISTINCT when there's no grouping or
3357 * aggregation ahead of the DISTINCT.)
3359 * Inputs:
3360 * root - the query
3361 * groupExprs - list of expressions being grouped by
3362 * input_rows - number of rows estimated to arrive at the group/unique
3363 * filter step
3364 * pgset - NULL, or a List** pointing to a grouping set to filter the
3365 * groupExprs against
3367 * Outputs:
3368 * estinfo - When passed as non-NULL, the function will set bits in the
3369 * "flags" field in order to provide callers with additional information
3370 * about the estimation. Currently, we only set the SELFLAG_USED_DEFAULT
3371 * bit if we used any default values in the estimation.
3373 * Given the lack of any cross-correlation statistics in the system, it's
3374 * impossible to do anything really trustworthy with GROUP BY conditions
3375 * involving multiple Vars. We should however avoid assuming the worst
3376 * case (all possible cross-product terms actually appear as groups) since
3377 * very often the grouped-by Vars are highly correlated. Our current approach
3378 * is as follows:
3379 * 1. Expressions yielding boolean are assumed to contribute two groups,
3380 * independently of their content, and are ignored in the subsequent
3381 * steps. This is mainly because tests like "col IS NULL" break the
3382 * heuristic used in step 2 especially badly.
3383 * 2. Reduce the given expressions to a list of unique Vars used. For
3384 * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3385 * It is clearly correct not to count the same Var more than once.
3386 * It is also reasonable to treat f(x) the same as x: f() cannot
3387 * increase the number of distinct values (unless it is volatile,
3388 * which we consider unlikely for grouping), but it probably won't
3389 * reduce the number of distinct values much either.
3390 * As a special case, if a GROUP BY expression can be matched to an
3391 * expressional index for which we have statistics, then we treat the
3392 * whole expression as though it were just a Var.
3393 * 3. If the list contains Vars of different relations that are known equal
3394 * due to equivalence classes, then drop all but one of the Vars from each
3395 * known-equal set, keeping the one with smallest estimated # of values
3396 * (since the extra values of the others can't appear in joined rows).
3397 * Note the reason we only consider Vars of different relations is that
3398 * if we considered ones of the same rel, we'd be double-counting the
3399 * restriction selectivity of the equality in the next step.
3400 * 4. For Vars within a single source rel, we multiply together the numbers
3401 * of values, clamp to the number of rows in the rel (divided by 10 if
3402 * more than one Var), and then multiply by a factor based on the
3403 * selectivity of the restriction clauses for that rel. When there's
3404 * more than one Var, the initial product is probably too high (it's the
3405 * worst case) but clamping to a fraction of the rel's rows seems to be a
3406 * helpful heuristic for not letting the estimate get out of hand. (The
3407 * factor of 10 is derived from pre-Postgres-7.4 practice.) The factor
3408 * we multiply by to adjust for the restriction selectivity assumes that
3409 * the restriction clauses are independent of the grouping, which may not
3410 * be a valid assumption, but it's hard to do better.
3411 * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3412 * rel, and multiply the results together.
3413 * Note that rels not containing grouped Vars are ignored completely, as are
3414 * join clauses. Such rels cannot increase the number of groups, and we
3415 * assume such clauses do not reduce the number either (somewhat bogus,
3416 * but we don't have the info to do better).
3418 double
3419 estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3420 List **pgset, EstimationInfo *estinfo)
3422 List *varinfos = NIL;
3423 double srf_multiplier = 1.0;
3424 double numdistinct;
3425 ListCell *l;
3426 int i;
3428 /* Zero the estinfo output parameter, if non-NULL */
3429 if (estinfo != NULL)
3430 memset(estinfo, 0, sizeof(EstimationInfo));
3433 * We don't ever want to return an estimate of zero groups, as that tends
3434 * to lead to division-by-zero and other unpleasantness. The input_rows
3435 * estimate is usually already at least 1, but clamp it just in case it
3436 * isn't.
3438 input_rows = clamp_row_est(input_rows);
3441 * If no grouping columns, there's exactly one group. (This can't happen
3442 * for normal cases with GROUP BY or DISTINCT, but it is possible for
3443 * corner cases with set operations.)
3445 if (groupExprs == NIL || (pgset && *pgset == NIL))
3446 return 1.0;
3449 * Count groups derived from boolean grouping expressions. For other
3450 * expressions, find the unique Vars used, treating an expression as a Var
3451 * if we can find stats for it. For each one, record the statistical
3452 * estimate of number of distinct values (total in its table, without
3453 * regard for filtering).
3455 numdistinct = 1.0;
3457 i = 0;
3458 foreach(l, groupExprs)
3460 Node *groupexpr = (Node *) lfirst(l);
3461 double this_srf_multiplier;
3462 VariableStatData vardata;
3463 List *varshere;
3464 ListCell *l2;
3466 /* is expression in this grouping set? */
3467 if (pgset && !list_member_int(*pgset, i++))
3468 continue;
3471 * Set-returning functions in grouping columns are a bit problematic.
3472 * The code below will effectively ignore their SRF nature and come up
3473 * with a numdistinct estimate as though they were scalar functions.
3474 * We compensate by scaling up the end result by the largest SRF
3475 * rowcount estimate. (This will be an overestimate if the SRF
3476 * produces multiple copies of any output value, but it seems best to
3477 * assume the SRF's outputs are distinct. In any case, it's probably
3478 * pointless to worry too much about this without much better
3479 * estimates for SRF output rowcounts than we have today.)
3481 this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3482 if (srf_multiplier < this_srf_multiplier)
3483 srf_multiplier = this_srf_multiplier;
3485 /* Short-circuit for expressions returning boolean */
3486 if (exprType(groupexpr) == BOOLOID)
3488 numdistinct *= 2.0;
3489 continue;
3493 * If examine_variable is able to deduce anything about the GROUP BY
3494 * expression, treat it as a single variable even if it's really more
3495 * complicated.
3497 * XXX This has the consequence that if there's a statistics object on
3498 * the expression, we don't split it into individual Vars. This
3499 * affects our selection of statistics in
3500 * estimate_multivariate_ndistinct, because it's probably better to
3501 * use more accurate estimate for each expression and treat them as
3502 * independent, than to combine estimates for the extracted variables
3503 * when we don't know how that relates to the expressions.
3505 examine_variable(root, groupexpr, 0, &vardata);
3506 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3508 varinfos = add_unique_group_var(root, varinfos,
3509 groupexpr, &vardata);
3510 ReleaseVariableStats(vardata);
3511 continue;
3513 ReleaseVariableStats(vardata);
3516 * Else pull out the component Vars. Handle PlaceHolderVars by
3517 * recursing into their arguments (effectively assuming that the
3518 * PlaceHolderVar doesn't change the number of groups, which boils
3519 * down to ignoring the possible addition of nulls to the result set).
3521 varshere = pull_var_clause(groupexpr,
3522 PVC_RECURSE_AGGREGATES |
3523 PVC_RECURSE_WINDOWFUNCS |
3524 PVC_RECURSE_PLACEHOLDERS);
3527 * If we find any variable-free GROUP BY item, then either it is a
3528 * constant (and we can ignore it) or it contains a volatile function;
3529 * in the latter case we punt and assume that each input row will
3530 * yield a distinct group.
3532 if (varshere == NIL)
3534 if (contain_volatile_functions(groupexpr))
3535 return input_rows;
3536 continue;
3540 * Else add variables to varinfos list
3542 foreach(l2, varshere)
3544 Node *var = (Node *) lfirst(l2);
3546 examine_variable(root, var, 0, &vardata);
3547 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3548 ReleaseVariableStats(vardata);
3553 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3554 * list.
3556 if (varinfos == NIL)
3558 /* Apply SRF multiplier as we would do in the long path */
3559 numdistinct *= srf_multiplier;
3560 /* Round off */
3561 numdistinct = ceil(numdistinct);
3562 /* Guard against out-of-range answers */
3563 if (numdistinct > input_rows)
3564 numdistinct = input_rows;
3565 if (numdistinct < 1.0)
3566 numdistinct = 1.0;
3567 return numdistinct;
3571 * Group Vars by relation and estimate total numdistinct.
3573 * For each iteration of the outer loop, we process the frontmost Var in
3574 * varinfos, plus all other Vars in the same relation. We remove these
3575 * Vars from the newvarinfos list for the next iteration. This is the
3576 * easiest way to group Vars of same rel together.
3580 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3581 RelOptInfo *rel = varinfo1->rel;
3582 double reldistinct = 1;
3583 double relmaxndistinct = reldistinct;
3584 int relvarcount = 0;
3585 List *newvarinfos = NIL;
3586 List *relvarinfos = NIL;
3589 * Split the list of varinfos in two - one for the current rel, one
3590 * for remaining Vars on other rels.
3592 relvarinfos = lappend(relvarinfos, varinfo1);
3593 for_each_from(l, varinfos, 1)
3595 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3597 if (varinfo2->rel == varinfo1->rel)
3599 /* varinfos on current rel */
3600 relvarinfos = lappend(relvarinfos, varinfo2);
3602 else
3604 /* not time to process varinfo2 yet */
3605 newvarinfos = lappend(newvarinfos, varinfo2);
3610 * Get the numdistinct estimate for the Vars of this rel. We
3611 * iteratively search for multivariate n-distinct with maximum number
3612 * of vars; assuming that each var group is independent of the others,
3613 * we multiply them together. Any remaining relvarinfos after no more
3614 * multivariate matches are found are assumed independent too, so
3615 * their individual ndistinct estimates are multiplied also.
3617 * While iterating, count how many separate numdistinct values we
3618 * apply. We apply a fudge factor below, but only if we multiplied
3619 * more than one such values.
3621 while (relvarinfos)
3623 double mvndistinct;
3625 if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3626 &mvndistinct))
3628 reldistinct *= mvndistinct;
3629 if (relmaxndistinct < mvndistinct)
3630 relmaxndistinct = mvndistinct;
3631 relvarcount++;
3633 else
3635 foreach(l, relvarinfos)
3637 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3639 reldistinct *= varinfo2->ndistinct;
3640 if (relmaxndistinct < varinfo2->ndistinct)
3641 relmaxndistinct = varinfo2->ndistinct;
3642 relvarcount++;
3645 * When varinfo2's isdefault is set then we'd better set
3646 * the SELFLAG_USED_DEFAULT bit in the EstimationInfo.
3648 if (estinfo != NULL && varinfo2->isdefault)
3649 estinfo->flags |= SELFLAG_USED_DEFAULT;
3652 /* we're done with this relation */
3653 relvarinfos = NIL;
3658 * Sanity check --- don't divide by zero if empty relation.
3660 Assert(IS_SIMPLE_REL(rel));
3661 if (rel->tuples > 0)
3664 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3665 * fudge factor is because the Vars are probably correlated but we
3666 * don't know by how much. We should never clamp to less than the
3667 * largest ndistinct value for any of the Vars, though, since
3668 * there will surely be at least that many groups.
3670 double clamp = rel->tuples;
3672 if (relvarcount > 1)
3674 clamp *= 0.1;
3675 if (clamp < relmaxndistinct)
3677 clamp = relmaxndistinct;
3678 /* for sanity in case some ndistinct is too large: */
3679 if (clamp > rel->tuples)
3680 clamp = rel->tuples;
3683 if (reldistinct > clamp)
3684 reldistinct = clamp;
3687 * Update the estimate based on the restriction selectivity,
3688 * guarding against division by zero when reldistinct is zero.
3689 * Also skip this if we know that we are returning all rows.
3691 if (reldistinct > 0 && rel->rows < rel->tuples)
3694 * Given a table containing N rows with n distinct values in a
3695 * uniform distribution, if we select p rows at random then
3696 * the expected number of distinct values selected is
3698 * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3700 * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3702 * See "Approximating block accesses in database
3703 * organizations", S. B. Yao, Communications of the ACM,
3704 * Volume 20 Issue 4, April 1977 Pages 260-261.
3706 * Alternatively, re-arranging the terms from the factorials,
3707 * this may be written as
3709 * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3711 * This form of the formula is more efficient to compute in
3712 * the common case where p is larger than N/n. Additionally,
3713 * as pointed out by Dell'Era, if i << N for all terms in the
3714 * product, it can be approximated by
3716 * n * (1 - ((N-p)/N)^(N/n))
3718 * See "Expected distinct values when selecting from a bag
3719 * without replacement", Alberto Dell'Era,
3720 * http://www.adellera.it/investigations/distinct_balls/.
3722 * The condition i << N is equivalent to n >> 1, so this is a
3723 * good approximation when the number of distinct values in
3724 * the table is large. It turns out that this formula also
3725 * works well even when n is small.
3727 reldistinct *=
3728 (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3729 rel->tuples / reldistinct));
3731 reldistinct = clamp_row_est(reldistinct);
3734 * Update estimate of total distinct groups.
3736 numdistinct *= reldistinct;
3739 varinfos = newvarinfos;
3740 } while (varinfos != NIL);
3742 /* Now we can account for the effects of any SRFs */
3743 numdistinct *= srf_multiplier;
3745 /* Round off */
3746 numdistinct = ceil(numdistinct);
3748 /* Guard against out-of-range answers */
3749 if (numdistinct > input_rows)
3750 numdistinct = input_rows;
3751 if (numdistinct < 1.0)
3752 numdistinct = 1.0;
3754 return numdistinct;
3758 * Estimate hash bucket statistics when the specified expression is used
3759 * as a hash key for the given number of buckets.
3761 * This attempts to determine two values:
3763 * 1. The frequency of the most common value of the expression (returns
3764 * zero into *mcv_freq if we can't get that).
3766 * 2. The "bucketsize fraction", ie, average number of entries in a bucket
3767 * divided by total tuples in relation.
3769 * XXX This is really pretty bogus since we're effectively assuming that the
3770 * distribution of hash keys will be the same after applying restriction
3771 * clauses as it was in the underlying relation. However, we are not nearly
3772 * smart enough to figure out how the restrict clauses might change the
3773 * distribution, so this will have to do for now.
3775 * We are passed the number of buckets the executor will use for the given
3776 * input relation. If the data were perfectly distributed, with the same
3777 * number of tuples going into each available bucket, then the bucketsize
3778 * fraction would be 1/nbuckets. But this happy state of affairs will occur
3779 * only if (a) there are at least nbuckets distinct data values, and (b)
3780 * we have a not-too-skewed data distribution. Otherwise the buckets will
3781 * be nonuniformly occupied. If the other relation in the join has a key
3782 * distribution similar to this one's, then the most-loaded buckets are
3783 * exactly those that will be probed most often. Therefore, the "average"
3784 * bucket size for costing purposes should really be taken as something close
3785 * to the "worst case" bucket size. We try to estimate this by adjusting the
3786 * fraction if there are too few distinct data values, and then scaling up
3787 * by the ratio of the most common value's frequency to the average frequency.
3789 * If no statistics are available, use a default estimate of 0.1. This will
3790 * discourage use of a hash rather strongly if the inner relation is large,
3791 * which is what we want. We do not want to hash unless we know that the
3792 * inner rel is well-dispersed (or the alternatives seem much worse).
3794 * The caller should also check that the mcv_freq is not so large that the
3795 * most common value would by itself require an impractically large bucket.
3796 * In a hash join, the executor can split buckets if they get too big, but
3797 * obviously that doesn't help for a bucket that contains many duplicates of
3798 * the same value.
3800 void
3801 estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets,
3802 Selectivity *mcv_freq,
3803 Selectivity *bucketsize_frac)
3805 VariableStatData vardata;
3806 double estfract,
3807 ndistinct,
3808 stanullfrac,
3809 avgfreq;
3810 bool isdefault;
3811 AttStatsSlot sslot;
3813 examine_variable(root, hashkey, 0, &vardata);
3815 /* Look up the frequency of the most common value, if available */
3816 *mcv_freq = 0.0;
3818 if (HeapTupleIsValid(vardata.statsTuple))
3820 if (get_attstatsslot(&sslot, vardata.statsTuple,
3821 STATISTIC_KIND_MCV, InvalidOid,
3822 ATTSTATSSLOT_NUMBERS))
3825 * The first MCV stat is for the most common value.
3827 if (sslot.nnumbers > 0)
3828 *mcv_freq = sslot.numbers[0];
3829 free_attstatsslot(&sslot);
3833 /* Get number of distinct values */
3834 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3837 * If ndistinct isn't real, punt. We normally return 0.1, but if the
3838 * mcv_freq is known to be even higher than that, use it instead.
3840 if (isdefault)
3842 *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3843 ReleaseVariableStats(vardata);
3844 return;
3847 /* Get fraction that are null */
3848 if (HeapTupleIsValid(vardata.statsTuple))
3850 Form_pg_statistic stats;
3852 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3853 stanullfrac = stats->stanullfrac;
3855 else
3856 stanullfrac = 0.0;
3858 /* Compute avg freq of all distinct data values in raw relation */
3859 avgfreq = (1.0 - stanullfrac) / ndistinct;
3862 * Adjust ndistinct to account for restriction clauses. Observe we are
3863 * assuming that the data distribution is affected uniformly by the
3864 * restriction clauses!
3866 * XXX Possibly better way, but much more expensive: multiply by
3867 * selectivity of rel's restriction clauses that mention the target Var.
3869 if (vardata.rel && vardata.rel->tuples > 0)
3871 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3872 ndistinct = clamp_row_est(ndistinct);
3876 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3877 * number of buckets is less than the expected number of distinct values;
3878 * otherwise it is 1/ndistinct.
3880 if (ndistinct > nbuckets)
3881 estfract = 1.0 / nbuckets;
3882 else
3883 estfract = 1.0 / ndistinct;
3886 * Adjust estimated bucketsize upward to account for skewed distribution.
3888 if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3889 estfract *= *mcv_freq / avgfreq;
3892 * Clamp bucketsize to sane range (the above adjustment could easily
3893 * produce an out-of-range result). We set the lower bound a little above
3894 * zero, since zero isn't a very sane result.
3896 if (estfract < 1.0e-6)
3897 estfract = 1.0e-6;
3898 else if (estfract > 1.0)
3899 estfract = 1.0;
3901 *bucketsize_frac = (Selectivity) estfract;
3903 ReleaseVariableStats(vardata);
3907 * estimate_hashagg_tablesize
3908 * estimate the number of bytes that a hash aggregate hashtable will
3909 * require based on the agg_costs, path width and number of groups.
3911 * We return the result as "double" to forestall any possible overflow
3912 * problem in the multiplication by dNumGroups.
3914 * XXX this may be over-estimating the size now that hashagg knows to omit
3915 * unneeded columns from the hashtable. Also for mixed-mode grouping sets,
3916 * grouping columns not in the hashed set are counted here even though hashagg
3917 * won't store them. Is this a problem?
3919 double
3920 estimate_hashagg_tablesize(PlannerInfo *root, Path *path,
3921 const AggClauseCosts *agg_costs, double dNumGroups)
3923 Size hashentrysize;
3925 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
3926 path->pathtarget->width,
3927 agg_costs->transitionSpace);
3930 * Note that this disregards the effect of fill-factor and growth policy
3931 * of the hash table. That's probably ok, given that the default
3932 * fill-factor is relatively high. It'd be hard to meaningfully factor in
3933 * "double-in-size" growth policies here.
3935 return hashentrysize * dNumGroups;
3939 /*-------------------------------------------------------------------------
3941 * Support routines
3943 *-------------------------------------------------------------------------
3947 * Find applicable ndistinct statistics for the given list of VarInfos (which
3948 * must all belong to the given rel), and update *ndistinct to the estimate of
3949 * the MVNDistinctItem that best matches. If a match it found, *varinfos is
3950 * updated to remove the list of matched varinfos.
3952 * Varinfos that aren't for simple Vars are ignored.
3954 * Return true if we're able to find a match, false otherwise.
3956 static bool
3957 estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel,
3958 List **varinfos, double *ndistinct)
3960 ListCell *lc;
3961 int nmatches_vars;
3962 int nmatches_exprs;
3963 Oid statOid = InvalidOid;
3964 MVNDistinct *stats;
3965 StatisticExtInfo *matched_info = NULL;
3966 RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
3968 /* bail out immediately if the table has no extended statistics */
3969 if (!rel->statlist)
3970 return false;
3972 /* look for the ndistinct statistics object matching the most vars */
3973 nmatches_vars = 0; /* we require at least two matches */
3974 nmatches_exprs = 0;
3975 foreach(lc, rel->statlist)
3977 ListCell *lc2;
3978 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3979 int nshared_vars = 0;
3980 int nshared_exprs = 0;
3982 /* skip statistics of other kinds */
3983 if (info->kind != STATS_EXT_NDISTINCT)
3984 continue;
3986 /* skip statistics with mismatching stxdinherit value */
3987 if (info->inherit != rte->inh)
3988 continue;
3991 * Determine how many expressions (and variables in non-matched
3992 * expressions) match. We'll then use these numbers to pick the
3993 * statistics object that best matches the clauses.
3995 foreach(lc2, *varinfos)
3997 ListCell *lc3;
3998 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
3999 AttrNumber attnum;
4001 Assert(varinfo->rel == rel);
4003 /* simple Var, search in statistics keys directly */
4004 if (IsA(varinfo->var, Var))
4006 attnum = ((Var *) varinfo->var)->varattno;
4009 * Ignore system attributes - we don't support statistics on
4010 * them, so can't match them (and it'd fail as the values are
4011 * negative).
4013 if (!AttrNumberIsForUserDefinedAttr(attnum))
4014 continue;
4016 if (bms_is_member(attnum, info->keys))
4017 nshared_vars++;
4019 continue;
4022 /* expression - see if it's in the statistics object */
4023 foreach(lc3, info->exprs)
4025 Node *expr = (Node *) lfirst(lc3);
4027 if (equal(varinfo->var, expr))
4029 nshared_exprs++;
4030 break;
4035 if (nshared_vars + nshared_exprs < 2)
4036 continue;
4039 * Does this statistics object match more columns than the currently
4040 * best object? If so, use this one instead.
4042 * XXX This should break ties using name of the object, or something
4043 * like that, to make the outcome stable.
4045 if ((nshared_exprs > nmatches_exprs) ||
4046 (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
4048 statOid = info->statOid;
4049 nmatches_vars = nshared_vars;
4050 nmatches_exprs = nshared_exprs;
4051 matched_info = info;
4055 /* No match? */
4056 if (statOid == InvalidOid)
4057 return false;
4059 Assert(nmatches_vars + nmatches_exprs > 1);
4061 stats = statext_ndistinct_load(statOid, rte->inh);
4064 * If we have a match, search it for the specific item that matches (there
4065 * must be one), and construct the output values.
4067 if (stats)
4069 int i;
4070 List *newlist = NIL;
4071 MVNDistinctItem *item = NULL;
4072 ListCell *lc2;
4073 Bitmapset *matched = NULL;
4074 AttrNumber attnum_offset;
4077 * How much we need to offset the attnums? If there are no
4078 * expressions, no offset is needed. Otherwise offset enough to move
4079 * the lowest one (which is equal to number of expressions) to 1.
4081 if (matched_info->exprs)
4082 attnum_offset = (list_length(matched_info->exprs) + 1);
4083 else
4084 attnum_offset = 0;
4086 /* see what actually matched */
4087 foreach(lc2, *varinfos)
4089 ListCell *lc3;
4090 int idx;
4091 bool found = false;
4093 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4096 * Process a simple Var expression, by matching it to keys
4097 * directly. If there's a matching expression, we'll try matching
4098 * it later.
4100 if (IsA(varinfo->var, Var))
4102 AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4105 * Ignore expressions on system attributes. Can't rely on the
4106 * bms check for negative values.
4108 if (!AttrNumberIsForUserDefinedAttr(attnum))
4109 continue;
4111 /* Is the variable covered by the statistics object? */
4112 if (!bms_is_member(attnum, matched_info->keys))
4113 continue;
4115 attnum = attnum + attnum_offset;
4117 /* ensure sufficient offset */
4118 Assert(AttrNumberIsForUserDefinedAttr(attnum));
4120 matched = bms_add_member(matched, attnum);
4122 found = true;
4126 * XXX Maybe we should allow searching the expressions even if we
4127 * found an attribute matching the expression? That would handle
4128 * trivial expressions like "(a)" but it seems fairly useless.
4130 if (found)
4131 continue;
4133 /* expression - see if it's in the statistics object */
4134 idx = 0;
4135 foreach(lc3, matched_info->exprs)
4137 Node *expr = (Node *) lfirst(lc3);
4139 if (equal(varinfo->var, expr))
4141 AttrNumber attnum = -(idx + 1);
4143 attnum = attnum + attnum_offset;
4145 /* ensure sufficient offset */
4146 Assert(AttrNumberIsForUserDefinedAttr(attnum));
4148 matched = bms_add_member(matched, attnum);
4150 /* there should be just one matching expression */
4151 break;
4154 idx++;
4158 /* Find the specific item that exactly matches the combination */
4159 for (i = 0; i < stats->nitems; i++)
4161 int j;
4162 MVNDistinctItem *tmpitem = &stats->items[i];
4164 if (tmpitem->nattributes != bms_num_members(matched))
4165 continue;
4167 /* assume it's the right item */
4168 item = tmpitem;
4170 /* check that all item attributes/expressions fit the match */
4171 for (j = 0; j < tmpitem->nattributes; j++)
4173 AttrNumber attnum = tmpitem->attributes[j];
4176 * Thanks to how we constructed the matched bitmap above, we
4177 * can just offset all attnums the same way.
4179 attnum = attnum + attnum_offset;
4181 if (!bms_is_member(attnum, matched))
4183 /* nah, it's not this item */
4184 item = NULL;
4185 break;
4190 * If the item has all the matched attributes, we know it's the
4191 * right one - there can't be a better one. matching more.
4193 if (item)
4194 break;
4198 * Make sure we found an item. There has to be one, because ndistinct
4199 * statistics includes all combinations of attributes.
4201 if (!item)
4202 elog(ERROR, "corrupt MVNDistinct entry");
4204 /* Form the output varinfo list, keeping only unmatched ones */
4205 foreach(lc, *varinfos)
4207 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
4208 ListCell *lc3;
4209 bool found = false;
4212 * Let's look at plain variables first, because it's the most
4213 * common case and the check is quite cheap. We can simply get the
4214 * attnum and check (with an offset) matched bitmap.
4216 if (IsA(varinfo->var, Var))
4218 AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4221 * If it's a system attribute, we're done. We don't support
4222 * extended statistics on system attributes, so it's clearly
4223 * not matched. Just keep the expression and continue.
4225 if (!AttrNumberIsForUserDefinedAttr(attnum))
4227 newlist = lappend(newlist, varinfo);
4228 continue;
4231 /* apply the same offset as above */
4232 attnum += attnum_offset;
4234 /* if it's not matched, keep the varinfo */
4235 if (!bms_is_member(attnum, matched))
4236 newlist = lappend(newlist, varinfo);
4238 /* The rest of the loop deals with complex expressions. */
4239 continue;
4243 * Process complex expressions, not just simple Vars.
4245 * First, we search for an exact match of an expression. If we
4246 * find one, we can just discard the whole GroupVarInfo, with all
4247 * the variables we extracted from it.
4249 * Otherwise we inspect the individual vars, and try matching it
4250 * to variables in the item.
4252 foreach(lc3, matched_info->exprs)
4254 Node *expr = (Node *) lfirst(lc3);
4256 if (equal(varinfo->var, expr))
4258 found = true;
4259 break;
4263 /* found exact match, skip */
4264 if (found)
4265 continue;
4267 newlist = lappend(newlist, varinfo);
4270 *varinfos = newlist;
4271 *ndistinct = item->ndistinct;
4272 return true;
4275 return false;
4279 * convert_to_scalar
4280 * Convert non-NULL values of the indicated types to the comparison
4281 * scale needed by scalarineqsel().
4282 * Returns "true" if successful.
4284 * XXX this routine is a hack: ideally we should look up the conversion
4285 * subroutines in pg_type.
4287 * All numeric datatypes are simply converted to their equivalent
4288 * "double" values. (NUMERIC values that are outside the range of "double"
4289 * are clamped to +/- HUGE_VAL.)
4291 * String datatypes are converted by convert_string_to_scalar(),
4292 * which is explained below. The reason why this routine deals with
4293 * three values at a time, not just one, is that we need it for strings.
4295 * The bytea datatype is just enough different from strings that it has
4296 * to be treated separately.
4298 * The several datatypes representing absolute times are all converted
4299 * to Timestamp, which is actually an int64, and then we promote that to
4300 * a double. Note this will give correct results even for the "special"
4301 * values of Timestamp, since those are chosen to compare correctly;
4302 * see timestamp_cmp.
4304 * The several datatypes representing relative times (intervals) are all
4305 * converted to measurements expressed in seconds.
4307 static bool
4308 convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue,
4309 Datum lobound, Datum hibound, Oid boundstypid,
4310 double *scaledlobound, double *scaledhibound)
4312 bool failure = false;
4315 * Both the valuetypid and the boundstypid should exactly match the
4316 * declared input type(s) of the operator we are invoked for. However,
4317 * extensions might try to use scalarineqsel as estimator for operators
4318 * with input type(s) we don't handle here; in such cases, we want to
4319 * return false, not fail. In any case, we mustn't assume that valuetypid
4320 * and boundstypid are identical.
4322 * XXX The histogram we are interpolating between points of could belong
4323 * to a column that's only binary-compatible with the declared type. In
4324 * essence we are assuming that the semantics of binary-compatible types
4325 * are enough alike that we can use a histogram generated with one type's
4326 * operators to estimate selectivity for the other's. This is outright
4327 * wrong in some cases --- in particular signed versus unsigned
4328 * interpretation could trip us up. But it's useful enough in the
4329 * majority of cases that we do it anyway. Should think about more
4330 * rigorous ways to do it.
4332 switch (valuetypid)
4335 * Built-in numeric types
4337 case BOOLOID:
4338 case INT2OID:
4339 case INT4OID:
4340 case INT8OID:
4341 case FLOAT4OID:
4342 case FLOAT8OID:
4343 case NUMERICOID:
4344 case OIDOID:
4345 case REGPROCOID:
4346 case REGPROCEDUREOID:
4347 case REGOPEROID:
4348 case REGOPERATOROID:
4349 case REGCLASSOID:
4350 case REGTYPEOID:
4351 case REGCOLLATIONOID:
4352 case REGCONFIGOID:
4353 case REGDICTIONARYOID:
4354 case REGROLEOID:
4355 case REGNAMESPACEOID:
4356 *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4357 &failure);
4358 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4359 &failure);
4360 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4361 &failure);
4362 return !failure;
4365 * Built-in string types
4367 case CHAROID:
4368 case BPCHAROID:
4369 case VARCHAROID:
4370 case TEXTOID:
4371 case NAMEOID:
4373 char *valstr = convert_string_datum(value, valuetypid,
4374 collid, &failure);
4375 char *lostr = convert_string_datum(lobound, boundstypid,
4376 collid, &failure);
4377 char *histr = convert_string_datum(hibound, boundstypid,
4378 collid, &failure);
4381 * Bail out if any of the values is not of string type. We
4382 * might leak converted strings for the other value(s), but
4383 * that's not worth troubling over.
4385 if (failure)
4386 return false;
4388 convert_string_to_scalar(valstr, scaledvalue,
4389 lostr, scaledlobound,
4390 histr, scaledhibound);
4391 pfree(valstr);
4392 pfree(lostr);
4393 pfree(histr);
4394 return true;
4398 * Built-in bytea type
4400 case BYTEAOID:
4402 /* We only support bytea vs bytea comparison */
4403 if (boundstypid != BYTEAOID)
4404 return false;
4405 convert_bytea_to_scalar(value, scaledvalue,
4406 lobound, scaledlobound,
4407 hibound, scaledhibound);
4408 return true;
4412 * Built-in time types
4414 case TIMESTAMPOID:
4415 case TIMESTAMPTZOID:
4416 case DATEOID:
4417 case INTERVALOID:
4418 case TIMEOID:
4419 case TIMETZOID:
4420 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
4421 &failure);
4422 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
4423 &failure);
4424 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
4425 &failure);
4426 return !failure;
4429 * Built-in network types
4431 case INETOID:
4432 case CIDROID:
4433 case MACADDROID:
4434 case MACADDR8OID:
4435 *scaledvalue = convert_network_to_scalar(value, valuetypid,
4436 &failure);
4437 *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
4438 &failure);
4439 *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
4440 &failure);
4441 return !failure;
4443 /* Don't know how to convert */
4444 *scaledvalue = *scaledlobound = *scaledhibound = 0;
4445 return false;
4449 * Do convert_to_scalar()'s work for any numeric data type.
4451 * On failure (e.g., unsupported typid), set *failure to true;
4452 * otherwise, that variable is not changed.
4454 static double
4455 convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
4457 switch (typid)
4459 case BOOLOID:
4460 return (double) DatumGetBool(value);
4461 case INT2OID:
4462 return (double) DatumGetInt16(value);
4463 case INT4OID:
4464 return (double) DatumGetInt32(value);
4465 case INT8OID:
4466 return (double) DatumGetInt64(value);
4467 case FLOAT4OID:
4468 return (double) DatumGetFloat4(value);
4469 case FLOAT8OID:
4470 return (double) DatumGetFloat8(value);
4471 case NUMERICOID:
4472 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4473 return (double)
4474 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
4475 value));
4476 case OIDOID:
4477 case REGPROCOID:
4478 case REGPROCEDUREOID:
4479 case REGOPEROID:
4480 case REGOPERATOROID:
4481 case REGCLASSOID:
4482 case REGTYPEOID:
4483 case REGCOLLATIONOID:
4484 case REGCONFIGOID:
4485 case REGDICTIONARYOID:
4486 case REGROLEOID:
4487 case REGNAMESPACEOID:
4488 /* we can treat OIDs as integers... */
4489 return (double) DatumGetObjectId(value);
4492 *failure = true;
4493 return 0;
4497 * Do convert_to_scalar()'s work for any character-string data type.
4499 * String datatypes are converted to a scale that ranges from 0 to 1,
4500 * where we visualize the bytes of the string as fractional digits.
4502 * We do not want the base to be 256, however, since that tends to
4503 * generate inflated selectivity estimates; few databases will have
4504 * occurrences of all 256 possible byte values at each position.
4505 * Instead, use the smallest and largest byte values seen in the bounds
4506 * as the estimated range for each byte, after some fudging to deal with
4507 * the fact that we probably aren't going to see the full range that way.
4509 * An additional refinement is that we discard any common prefix of the
4510 * three strings before computing the scaled values. This allows us to
4511 * "zoom in" when we encounter a narrow data range. An example is a phone
4512 * number database where all the values begin with the same area code.
4513 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
4514 * so this is more likely to happen than you might think.)
4516 static void
4517 convert_string_to_scalar(char *value,
4518 double *scaledvalue,
4519 char *lobound,
4520 double *scaledlobound,
4521 char *hibound,
4522 double *scaledhibound)
4524 int rangelo,
4525 rangehi;
4526 char *sptr;
4528 rangelo = rangehi = (unsigned char) hibound[0];
4529 for (sptr = lobound; *sptr; sptr++)
4531 if (rangelo > (unsigned char) *sptr)
4532 rangelo = (unsigned char) *sptr;
4533 if (rangehi < (unsigned char) *sptr)
4534 rangehi = (unsigned char) *sptr;
4536 for (sptr = hibound; *sptr; sptr++)
4538 if (rangelo > (unsigned char) *sptr)
4539 rangelo = (unsigned char) *sptr;
4540 if (rangehi < (unsigned char) *sptr)
4541 rangehi = (unsigned char) *sptr;
4543 /* If range includes any upper-case ASCII chars, make it include all */
4544 if (rangelo <= 'Z' && rangehi >= 'A')
4546 if (rangelo > 'A')
4547 rangelo = 'A';
4548 if (rangehi < 'Z')
4549 rangehi = 'Z';
4551 /* Ditto lower-case */
4552 if (rangelo <= 'z' && rangehi >= 'a')
4554 if (rangelo > 'a')
4555 rangelo = 'a';
4556 if (rangehi < 'z')
4557 rangehi = 'z';
4559 /* Ditto digits */
4560 if (rangelo <= '9' && rangehi >= '0')
4562 if (rangelo > '0')
4563 rangelo = '0';
4564 if (rangehi < '9')
4565 rangehi = '9';
4569 * If range includes less than 10 chars, assume we have not got enough
4570 * data, and make it include regular ASCII set.
4572 if (rangehi - rangelo < 9)
4574 rangelo = ' ';
4575 rangehi = 127;
4579 * Now strip any common prefix of the three strings.
4581 while (*lobound)
4583 if (*lobound != *hibound || *lobound != *value)
4584 break;
4585 lobound++, hibound++, value++;
4589 * Now we can do the conversions.
4591 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4592 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4593 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4596 static double
4597 convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
4599 int slen = strlen(value);
4600 double num,
4601 denom,
4602 base;
4604 if (slen <= 0)
4605 return 0.0; /* empty string has scalar value 0 */
4608 * There seems little point in considering more than a dozen bytes from
4609 * the string. Since base is at least 10, that will give us nominal
4610 * resolution of at least 12 decimal digits, which is surely far more
4611 * precision than this estimation technique has got anyway (especially in
4612 * non-C locales). Also, even with the maximum possible base of 256, this
4613 * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4614 * overflow on any known machine.
4616 if (slen > 12)
4617 slen = 12;
4619 /* Convert initial characters to fraction */
4620 base = rangehi - rangelo + 1;
4621 num = 0.0;
4622 denom = base;
4623 while (slen-- > 0)
4625 int ch = (unsigned char) *value++;
4627 if (ch < rangelo)
4628 ch = rangelo - 1;
4629 else if (ch > rangehi)
4630 ch = rangehi + 1;
4631 num += ((double) (ch - rangelo)) / denom;
4632 denom *= base;
4635 return num;
4639 * Convert a string-type Datum into a palloc'd, null-terminated string.
4641 * On failure (e.g., unsupported typid), set *failure to true;
4642 * otherwise, that variable is not changed. (We'll return NULL on failure.)
4644 * When using a non-C locale, we must pass the string through strxfrm()
4645 * before continuing, so as to generate correct locale-specific results.
4647 static char *
4648 convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
4650 char *val;
4652 switch (typid)
4654 case CHAROID:
4655 val = (char *) palloc(2);
4656 val[0] = DatumGetChar(value);
4657 val[1] = '\0';
4658 break;
4659 case BPCHAROID:
4660 case VARCHAROID:
4661 case TEXTOID:
4662 val = TextDatumGetCString(value);
4663 break;
4664 case NAMEOID:
4666 NameData *nm = (NameData *) DatumGetPointer(value);
4668 val = pstrdup(NameStr(*nm));
4669 break;
4671 default:
4672 *failure = true;
4673 return NULL;
4676 if (!lc_collate_is_c(collid))
4678 char *xfrmstr;
4679 size_t xfrmlen;
4680 size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4683 * XXX: We could guess at a suitable output buffer size and only call
4684 * strxfrm twice if our guess is too small.
4686 * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4687 * bogus data or set an error. This is not really a problem unless it
4688 * crashes since it will only give an estimation error and nothing
4689 * fatal.
4691 xfrmlen = strxfrm(NULL, val, 0);
4692 #ifdef WIN32
4695 * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4696 * of trying to allocate this much memory (and fail), just return the
4697 * original string unmodified as if we were in the C locale.
4699 if (xfrmlen == INT_MAX)
4700 return val;
4701 #endif
4702 xfrmstr = (char *) palloc(xfrmlen + 1);
4703 xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4706 * Some systems (e.g., glibc) can return a smaller value from the
4707 * second call than the first; thus the Assert must be <= not ==.
4709 Assert(xfrmlen2 <= xfrmlen);
4710 pfree(val);
4711 val = xfrmstr;
4714 return val;
4718 * Do convert_to_scalar()'s work for any bytea data type.
4720 * Very similar to convert_string_to_scalar except we can't assume
4721 * null-termination and therefore pass explicit lengths around.
4723 * Also, assumptions about likely "normal" ranges of characters have been
4724 * removed - a data range of 0..255 is always used, for now. (Perhaps
4725 * someday we will add information about actual byte data range to
4726 * pg_statistic.)
4728 static void
4729 convert_bytea_to_scalar(Datum value,
4730 double *scaledvalue,
4731 Datum lobound,
4732 double *scaledlobound,
4733 Datum hibound,
4734 double *scaledhibound)
4736 bytea *valuep = DatumGetByteaPP(value);
4737 bytea *loboundp = DatumGetByteaPP(lobound);
4738 bytea *hiboundp = DatumGetByteaPP(hibound);
4739 int rangelo,
4740 rangehi,
4741 valuelen = VARSIZE_ANY_EXHDR(valuep),
4742 loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4743 hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4745 minlen;
4746 unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4747 unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4748 unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4751 * Assume bytea data is uniformly distributed across all byte values.
4753 rangelo = 0;
4754 rangehi = 255;
4757 * Now strip any common prefix of the three strings.
4759 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4760 for (i = 0; i < minlen; i++)
4762 if (*lostr != *histr || *lostr != *valstr)
4763 break;
4764 lostr++, histr++, valstr++;
4765 loboundlen--, hiboundlen--, valuelen--;
4769 * Now we can do the conversions.
4771 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4772 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4773 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4776 static double
4777 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
4778 int rangelo, int rangehi)
4780 double num,
4781 denom,
4782 base;
4784 if (valuelen <= 0)
4785 return 0.0; /* empty string has scalar value 0 */
4788 * Since base is 256, need not consider more than about 10 chars (even
4789 * this many seems like overkill)
4791 if (valuelen > 10)
4792 valuelen = 10;
4794 /* Convert initial characters to fraction */
4795 base = rangehi - rangelo + 1;
4796 num = 0.0;
4797 denom = base;
4798 while (valuelen-- > 0)
4800 int ch = *value++;
4802 if (ch < rangelo)
4803 ch = rangelo - 1;
4804 else if (ch > rangehi)
4805 ch = rangehi + 1;
4806 num += ((double) (ch - rangelo)) / denom;
4807 denom *= base;
4810 return num;
4814 * Do convert_to_scalar()'s work for any timevalue data type.
4816 * On failure (e.g., unsupported typid), set *failure to true;
4817 * otherwise, that variable is not changed.
4819 static double
4820 convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
4822 switch (typid)
4824 case TIMESTAMPOID:
4825 return DatumGetTimestamp(value);
4826 case TIMESTAMPTZOID:
4827 return DatumGetTimestampTz(value);
4828 case DATEOID:
4829 return date2timestamp_no_overflow(DatumGetDateADT(value));
4830 case INTERVALOID:
4832 Interval *interval = DatumGetIntervalP(value);
4835 * Convert the month part of Interval to days using assumed
4836 * average month length of 365.25/12.0 days. Not too
4837 * accurate, but plenty good enough for our purposes.
4839 * This also works for infinite intervals, which just have all
4840 * fields set to INT_MIN/INT_MAX, and so will produce a result
4841 * smaller/larger than any finite interval.
4843 return interval->time + interval->day * (double) USECS_PER_DAY +
4844 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4846 case TIMEOID:
4847 return DatumGetTimeADT(value);
4848 case TIMETZOID:
4850 TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4852 /* use GMT-equivalent time */
4853 return (double) (timetz->time + (timetz->zone * 1000000.0));
4857 *failure = true;
4858 return 0;
4863 * get_restriction_variable
4864 * Examine the args of a restriction clause to see if it's of the
4865 * form (variable op pseudoconstant) or (pseudoconstant op variable),
4866 * where "variable" could be either a Var or an expression in vars of a
4867 * single relation. If so, extract information about the variable,
4868 * and also indicate which side it was on and the other argument.
4870 * Inputs:
4871 * root: the planner info
4872 * args: clause argument list
4873 * varRelid: see specs for restriction selectivity functions
4875 * Outputs: (these are valid only if true is returned)
4876 * *vardata: gets information about variable (see examine_variable)
4877 * *other: gets other clause argument, aggressively reduced to a constant
4878 * *varonleft: set true if variable is on the left, false if on the right
4880 * Returns true if a variable is identified, otherwise false.
4882 * Note: if there are Vars on both sides of the clause, we must fail, because
4883 * callers are expecting that the other side will act like a pseudoconstant.
4885 bool
4886 get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
4887 VariableStatData *vardata, Node **other,
4888 bool *varonleft)
4890 Node *left,
4891 *right;
4892 VariableStatData rdata;
4894 /* Fail if not a binary opclause (probably shouldn't happen) */
4895 if (list_length(args) != 2)
4896 return false;
4898 left = (Node *) linitial(args);
4899 right = (Node *) lsecond(args);
4902 * Examine both sides. Note that when varRelid is nonzero, Vars of other
4903 * relations will be treated as pseudoconstants.
4905 examine_variable(root, left, varRelid, vardata);
4906 examine_variable(root, right, varRelid, &rdata);
4909 * If one side is a variable and the other not, we win.
4911 if (vardata->rel && rdata.rel == NULL)
4913 *varonleft = true;
4914 *other = estimate_expression_value(root, rdata.var);
4915 /* Assume we need no ReleaseVariableStats(rdata) here */
4916 return true;
4919 if (vardata->rel == NULL && rdata.rel)
4921 *varonleft = false;
4922 *other = estimate_expression_value(root, vardata->var);
4923 /* Assume we need no ReleaseVariableStats(*vardata) here */
4924 *vardata = rdata;
4925 return true;
4928 /* Oops, clause has wrong structure (probably var op var) */
4929 ReleaseVariableStats(*vardata);
4930 ReleaseVariableStats(rdata);
4932 return false;
4936 * get_join_variables
4937 * Apply examine_variable() to each side of a join clause.
4938 * Also, attempt to identify whether the join clause has the same
4939 * or reversed sense compared to the SpecialJoinInfo.
4941 * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4942 * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4943 * where we can't tell for sure, we default to assuming it's normal.
4945 void
4946 get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
4947 VariableStatData *vardata1, VariableStatData *vardata2,
4948 bool *join_is_reversed)
4950 Node *left,
4951 *right;
4953 if (list_length(args) != 2)
4954 elog(ERROR, "join operator should take two arguments");
4956 left = (Node *) linitial(args);
4957 right = (Node *) lsecond(args);
4959 examine_variable(root, left, 0, vardata1);
4960 examine_variable(root, right, 0, vardata2);
4962 if (vardata1->rel &&
4963 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4964 *join_is_reversed = true; /* var1 is on RHS */
4965 else if (vardata2->rel &&
4966 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4967 *join_is_reversed = true; /* var2 is on LHS */
4968 else
4969 *join_is_reversed = false;
4972 /* statext_expressions_load copies the tuple, so just pfree it. */
4973 static void
4974 ReleaseDummy(HeapTuple tuple)
4976 pfree(tuple);
4980 * examine_variable
4981 * Try to look up statistical data about an expression.
4982 * Fill in a VariableStatData struct to describe the expression.
4984 * Inputs:
4985 * root: the planner info
4986 * node: the expression tree to examine
4987 * varRelid: see specs for restriction selectivity functions
4989 * Outputs: *vardata is filled as follows:
4990 * var: the input expression (with any binary relabeling stripped, if
4991 * it is or contains a variable; but otherwise the type is preserved)
4992 * rel: RelOptInfo for relation containing variable; NULL if expression
4993 * contains no Vars (NOTE this could point to a RelOptInfo of a
4994 * subquery, not one in the current query).
4995 * statsTuple: the pg_statistic entry for the variable, if one exists;
4996 * otherwise NULL.
4997 * freefunc: pointer to a function to release statsTuple with.
4998 * vartype: exposed type of the expression; this should always match
4999 * the declared input type of the operator we are estimating for.
5000 * atttype, atttypmod: actual type/typmod of the "var" expression. This is
5001 * commonly the same as the exposed type of the variable argument,
5002 * but can be different in binary-compatible-type cases.
5003 * isunique: true if we were able to match the var to a unique index or a
5004 * single-column DISTINCT clause, implying its values are unique for
5005 * this query. (Caution: this should be trusted for statistical
5006 * purposes only, since we do not check indimmediate nor verify that
5007 * the exact same definition of equality applies.)
5008 * acl_ok: true if current user has permission to read the column(s)
5009 * underlying the pg_statistic entry. This is consulted by
5010 * statistic_proc_security_check().
5012 * Caller is responsible for doing ReleaseVariableStats() before exiting.
5014 void
5015 examine_variable(PlannerInfo *root, Node *node, int varRelid,
5016 VariableStatData *vardata)
5018 Node *basenode;
5019 Relids varnos;
5020 RelOptInfo *onerel;
5022 /* Make sure we don't return dangling pointers in vardata */
5023 MemSet(vardata, 0, sizeof(VariableStatData));
5025 /* Save the exposed type of the expression */
5026 vardata->vartype = exprType(node);
5028 /* Look inside any binary-compatible relabeling */
5030 if (IsA(node, RelabelType))
5031 basenode = (Node *) ((RelabelType *) node)->arg;
5032 else
5033 basenode = node;
5035 /* Fast path for a simple Var */
5037 if (IsA(basenode, Var) &&
5038 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5040 Var *var = (Var *) basenode;
5042 /* Set up result fields other than the stats tuple */
5043 vardata->var = basenode; /* return Var without relabeling */
5044 vardata->rel = find_base_rel(root, var->varno);
5045 vardata->atttype = var->vartype;
5046 vardata->atttypmod = var->vartypmod;
5047 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5049 /* Try to locate some stats */
5050 examine_simple_variable(root, var, vardata);
5052 return;
5056 * Okay, it's a more complicated expression. Determine variable
5057 * membership. Note that when varRelid isn't zero, only vars of that
5058 * relation are considered "real" vars.
5060 varnos = pull_varnos(root, basenode);
5062 onerel = NULL;
5064 if (bms_is_empty(varnos))
5066 /* No Vars at all ... must be pseudo-constant clause */
5068 else
5070 int relid;
5072 if (bms_get_singleton_member(varnos, &relid))
5074 if (varRelid == 0 || varRelid == relid)
5076 onerel = find_base_rel(root, relid);
5077 vardata->rel = onerel;
5078 node = basenode; /* strip any relabeling */
5080 /* else treat it as a constant */
5082 else
5084 /* varnos has multiple relids */
5085 if (varRelid == 0)
5087 /* treat it as a variable of a join relation */
5088 vardata->rel = find_join_rel(root, varnos);
5089 node = basenode; /* strip any relabeling */
5091 else if (bms_is_member(varRelid, varnos))
5093 /* ignore the vars belonging to other relations */
5094 vardata->rel = find_base_rel(root, varRelid);
5095 node = basenode; /* strip any relabeling */
5096 /* note: no point in expressional-index search here */
5098 /* else treat it as a constant */
5102 bms_free(varnos);
5104 vardata->var = node;
5105 vardata->atttype = exprType(node);
5106 vardata->atttypmod = exprTypmod(node);
5108 if (onerel)
5111 * We have an expression in vars of a single relation. Try to match
5112 * it to expressional index columns, in hopes of finding some
5113 * statistics.
5115 * Note that we consider all index columns including INCLUDE columns,
5116 * since there could be stats for such columns. But the test for
5117 * uniqueness needs to be warier.
5119 * XXX it's conceivable that there are multiple matches with different
5120 * index opfamilies; if so, we need to pick one that matches the
5121 * operator we are estimating for. FIXME later.
5123 ListCell *ilist;
5124 ListCell *slist;
5125 Oid userid;
5128 * Determine the user ID to use for privilege checks: either
5129 * onerel->userid if it's set (e.g., in case we're accessing the table
5130 * via a view), or the current user otherwise.
5132 * If we drill down to child relations, we keep using the same userid:
5133 * it's going to be the same anyway, due to how we set up the relation
5134 * tree (q.v. build_simple_rel).
5136 userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
5138 foreach(ilist, onerel->indexlist)
5140 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5141 ListCell *indexpr_item;
5142 int pos;
5144 indexpr_item = list_head(index->indexprs);
5145 if (indexpr_item == NULL)
5146 continue; /* no expressions here... */
5148 for (pos = 0; pos < index->ncolumns; pos++)
5150 if (index->indexkeys[pos] == 0)
5152 Node *indexkey;
5154 if (indexpr_item == NULL)
5155 elog(ERROR, "too few entries in indexprs list");
5156 indexkey = (Node *) lfirst(indexpr_item);
5157 if (indexkey && IsA(indexkey, RelabelType))
5158 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5159 if (equal(node, indexkey))
5162 * Found a match ... is it a unique index? Tests here
5163 * should match has_unique_index().
5165 if (index->unique &&
5166 index->nkeycolumns == 1 &&
5167 pos == 0 &&
5168 (index->indpred == NIL || index->predOK))
5169 vardata->isunique = true;
5172 * Has it got stats? We only consider stats for
5173 * non-partial indexes, since partial indexes probably
5174 * don't reflect whole-relation statistics; the above
5175 * check for uniqueness is the only info we take from
5176 * a partial index.
5178 * An index stats hook, however, must make its own
5179 * decisions about what to do with partial indexes.
5181 if (get_index_stats_hook &&
5182 (*get_index_stats_hook) (root, index->indexoid,
5183 pos + 1, vardata))
5186 * The hook took control of acquiring a stats
5187 * tuple. If it did supply a tuple, it'd better
5188 * have supplied a freefunc.
5190 if (HeapTupleIsValid(vardata->statsTuple) &&
5191 !vardata->freefunc)
5192 elog(ERROR, "no function provided to release variable stats with");
5194 else if (index->indpred == NIL)
5196 vardata->statsTuple =
5197 SearchSysCache3(STATRELATTINH,
5198 ObjectIdGetDatum(index->indexoid),
5199 Int16GetDatum(pos + 1),
5200 BoolGetDatum(false));
5201 vardata->freefunc = ReleaseSysCache;
5203 if (HeapTupleIsValid(vardata->statsTuple))
5205 /* Get index's table for permission check */
5206 RangeTblEntry *rte;
5208 rte = planner_rt_fetch(index->rel->relid, root);
5209 Assert(rte->rtekind == RTE_RELATION);
5212 * For simplicity, we insist on the whole
5213 * table being selectable, rather than trying
5214 * to identify which column(s) the index
5215 * depends on. Also require all rows to be
5216 * selectable --- there must be no
5217 * securityQuals from security barrier views
5218 * or RLS policies.
5220 vardata->acl_ok =
5221 rte->securityQuals == NIL &&
5222 (pg_class_aclcheck(rte->relid, userid,
5223 ACL_SELECT) == ACLCHECK_OK);
5226 * If the user doesn't have permissions to
5227 * access an inheritance child relation, check
5228 * the permissions of the table actually
5229 * mentioned in the query, since most likely
5230 * the user does have that permission. Note
5231 * that whole-table select privilege on the
5232 * parent doesn't quite guarantee that the
5233 * user could read all columns of the child.
5234 * But in practice it's unlikely that any
5235 * interesting security violation could result
5236 * from allowing access to the expression
5237 * index's stats, so we allow it anyway. See
5238 * similar code in examine_simple_variable()
5239 * for additional comments.
5241 if (!vardata->acl_ok &&
5242 root->append_rel_array != NULL)
5244 AppendRelInfo *appinfo;
5245 Index varno = index->rel->relid;
5247 appinfo = root->append_rel_array[varno];
5248 while (appinfo &&
5249 planner_rt_fetch(appinfo->parent_relid,
5250 root)->rtekind == RTE_RELATION)
5252 varno = appinfo->parent_relid;
5253 appinfo = root->append_rel_array[varno];
5255 if (varno != index->rel->relid)
5257 /* Repeat access check on this rel */
5258 rte = planner_rt_fetch(varno, root);
5259 Assert(rte->rtekind == RTE_RELATION);
5261 vardata->acl_ok =
5262 rte->securityQuals == NIL &&
5263 (pg_class_aclcheck(rte->relid,
5264 userid,
5265 ACL_SELECT) == ACLCHECK_OK);
5269 else
5271 /* suppress leakproofness checks later */
5272 vardata->acl_ok = true;
5275 if (vardata->statsTuple)
5276 break;
5278 indexpr_item = lnext(index->indexprs, indexpr_item);
5281 if (vardata->statsTuple)
5282 break;
5286 * Search extended statistics for one with a matching expression.
5287 * There might be multiple ones, so just grab the first one. In the
5288 * future, we might consider the statistics target (and pick the most
5289 * accurate statistics) and maybe some other parameters.
5291 foreach(slist, onerel->statlist)
5293 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5294 RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5295 ListCell *expr_item;
5296 int pos;
5299 * Stop once we've found statistics for the expression (either
5300 * from extended stats, or for an index in the preceding loop).
5302 if (vardata->statsTuple)
5303 break;
5305 /* skip stats without per-expression stats */
5306 if (info->kind != STATS_EXT_EXPRESSIONS)
5307 continue;
5309 /* skip stats with mismatching stxdinherit value */
5310 if (info->inherit != rte->inh)
5311 continue;
5313 pos = 0;
5314 foreach(expr_item, info->exprs)
5316 Node *expr = (Node *) lfirst(expr_item);
5318 Assert(expr);
5320 /* strip RelabelType before comparing it */
5321 if (expr && IsA(expr, RelabelType))
5322 expr = (Node *) ((RelabelType *) expr)->arg;
5324 /* found a match, see if we can extract pg_statistic row */
5325 if (equal(node, expr))
5328 * XXX Not sure if we should cache the tuple somewhere.
5329 * Now we just create a new copy every time.
5331 vardata->statsTuple =
5332 statext_expressions_load(info->statOid, rte->inh, pos);
5334 vardata->freefunc = ReleaseDummy;
5337 * For simplicity, we insist on the whole table being
5338 * selectable, rather than trying to identify which
5339 * column(s) the statistics object depends on. Also
5340 * require all rows to be selectable --- there must be no
5341 * securityQuals from security barrier views or RLS
5342 * policies.
5344 vardata->acl_ok =
5345 rte->securityQuals == NIL &&
5346 (pg_class_aclcheck(rte->relid, userid,
5347 ACL_SELECT) == ACLCHECK_OK);
5350 * If the user doesn't have permissions to access an
5351 * inheritance child relation, check the permissions of
5352 * the table actually mentioned in the query, since most
5353 * likely the user does have that permission. Note that
5354 * whole-table select privilege on the parent doesn't
5355 * quite guarantee that the user could read all columns of
5356 * the child. But in practice it's unlikely that any
5357 * interesting security violation could result from
5358 * allowing access to the expression stats, so we allow it
5359 * anyway. See similar code in examine_simple_variable()
5360 * for additional comments.
5362 if (!vardata->acl_ok &&
5363 root->append_rel_array != NULL)
5365 AppendRelInfo *appinfo;
5366 Index varno = onerel->relid;
5368 appinfo = root->append_rel_array[varno];
5369 while (appinfo &&
5370 planner_rt_fetch(appinfo->parent_relid,
5371 root)->rtekind == RTE_RELATION)
5373 varno = appinfo->parent_relid;
5374 appinfo = root->append_rel_array[varno];
5376 if (varno != onerel->relid)
5378 /* Repeat access check on this rel */
5379 rte = planner_rt_fetch(varno, root);
5380 Assert(rte->rtekind == RTE_RELATION);
5382 vardata->acl_ok =
5383 rte->securityQuals == NIL &&
5384 (pg_class_aclcheck(rte->relid,
5385 userid,
5386 ACL_SELECT) == ACLCHECK_OK);
5390 break;
5393 pos++;
5400 * examine_simple_variable
5401 * Handle a simple Var for examine_variable
5403 * This is split out as a subroutine so that we can recurse to deal with
5404 * Vars referencing subqueries (either sub-SELECT-in-FROM or CTE style).
5406 * We already filled in all the fields of *vardata except for the stats tuple.
5408 static void
5409 examine_simple_variable(PlannerInfo *root, Var *var,
5410 VariableStatData *vardata)
5412 RangeTblEntry *rte = root->simple_rte_array[var->varno];
5414 Assert(IsA(rte, RangeTblEntry));
5416 if (get_relation_stats_hook &&
5417 (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
5420 * The hook took control of acquiring a stats tuple. If it did supply
5421 * a tuple, it'd better have supplied a freefunc.
5423 if (HeapTupleIsValid(vardata->statsTuple) &&
5424 !vardata->freefunc)
5425 elog(ERROR, "no function provided to release variable stats with");
5427 else if (rte->rtekind == RTE_RELATION)
5430 * Plain table or parent of an inheritance appendrel, so look up the
5431 * column in pg_statistic
5433 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
5434 ObjectIdGetDatum(rte->relid),
5435 Int16GetDatum(var->varattno),
5436 BoolGetDatum(rte->inh));
5437 vardata->freefunc = ReleaseSysCache;
5439 if (HeapTupleIsValid(vardata->statsTuple))
5441 RelOptInfo *onerel = find_base_rel_noerr(root, var->varno);
5442 Oid userid;
5445 * Check if user has permission to read this column. We require
5446 * all rows to be accessible, so there must be no securityQuals
5447 * from security barrier views or RLS policies.
5449 * Normally the Var will have an associated RelOptInfo from which
5450 * we can find out which userid to do the check as; but it might
5451 * not if it's a RETURNING Var for an INSERT target relation. In
5452 * that case use the RTEPermissionInfo associated with the RTE.
5454 if (onerel)
5455 userid = onerel->userid;
5456 else
5458 RTEPermissionInfo *perminfo;
5460 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
5461 userid = perminfo->checkAsUser;
5463 if (!OidIsValid(userid))
5464 userid = GetUserId();
5466 vardata->acl_ok =
5467 rte->securityQuals == NIL &&
5468 ((pg_class_aclcheck(rte->relid, userid,
5469 ACL_SELECT) == ACLCHECK_OK) ||
5470 (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
5471 ACL_SELECT) == ACLCHECK_OK));
5474 * If the user doesn't have permissions to access an inheritance
5475 * child relation or specifically this attribute, check the
5476 * permissions of the table/column actually mentioned in the
5477 * query, since most likely the user does have that permission
5478 * (else the query will fail at runtime), and if the user can read
5479 * the column there then he can get the values of the child table
5480 * too. To do that, we must find out which of the root parent's
5481 * attributes the child relation's attribute corresponds to.
5483 if (!vardata->acl_ok && var->varattno > 0 &&
5484 root->append_rel_array != NULL)
5486 AppendRelInfo *appinfo;
5487 Index varno = var->varno;
5488 int varattno = var->varattno;
5489 bool found = false;
5491 appinfo = root->append_rel_array[varno];
5494 * Partitions are mapped to their immediate parent, not the
5495 * root parent, so must be ready to walk up multiple
5496 * AppendRelInfos. But stop if we hit a parent that is not
5497 * RTE_RELATION --- that's a flattened UNION ALL subquery, not
5498 * an inheritance parent.
5500 while (appinfo &&
5501 planner_rt_fetch(appinfo->parent_relid,
5502 root)->rtekind == RTE_RELATION)
5504 int parent_varattno;
5506 found = false;
5507 if (varattno <= 0 || varattno > appinfo->num_child_cols)
5508 break; /* safety check */
5509 parent_varattno = appinfo->parent_colnos[varattno - 1];
5510 if (parent_varattno == 0)
5511 break; /* Var is local to child */
5513 varno = appinfo->parent_relid;
5514 varattno = parent_varattno;
5515 found = true;
5517 /* If the parent is itself a child, continue up. */
5518 appinfo = root->append_rel_array[varno];
5522 * In rare cases, the Var may be local to the child table, in
5523 * which case, we've got to live with having no access to this
5524 * column's stats.
5526 if (!found)
5527 return;
5529 /* Repeat the access check on this parent rel & column */
5530 rte = planner_rt_fetch(varno, root);
5531 Assert(rte->rtekind == RTE_RELATION);
5534 * Fine to use the same userid as it's the same in all
5535 * relations of a given inheritance tree.
5537 vardata->acl_ok =
5538 rte->securityQuals == NIL &&
5539 ((pg_class_aclcheck(rte->relid, userid,
5540 ACL_SELECT) == ACLCHECK_OK) ||
5541 (pg_attribute_aclcheck(rte->relid, varattno, userid,
5542 ACL_SELECT) == ACLCHECK_OK));
5545 else
5547 /* suppress any possible leakproofness checks later */
5548 vardata->acl_ok = true;
5551 else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
5552 (rte->rtekind == RTE_CTE && !rte->self_reference))
5555 * Plain subquery (not one that was converted to an appendrel) or
5556 * non-recursive CTE. In either case, we can try to find out what the
5557 * Var refers to within the subquery. We skip this for appendrel and
5558 * recursive-CTE cases because any column stats we did find would
5559 * likely not be very relevant.
5561 PlannerInfo *subroot;
5562 Query *subquery;
5563 List *subtlist;
5564 TargetEntry *ste;
5567 * Punt if it's a whole-row var rather than a plain column reference.
5569 if (var->varattno == InvalidAttrNumber)
5570 return;
5573 * Otherwise, find the subquery's planner subroot.
5575 if (rte->rtekind == RTE_SUBQUERY)
5577 RelOptInfo *rel;
5580 * Fetch RelOptInfo for subquery. Note that we don't change the
5581 * rel returned in vardata, since caller expects it to be a rel of
5582 * the caller's query level. Because we might already be
5583 * recursing, we can't use that rel pointer either, but have to
5584 * look up the Var's rel afresh.
5586 rel = find_base_rel(root, var->varno);
5588 subroot = rel->subroot;
5590 else
5592 /* CTE case is more difficult */
5593 PlannerInfo *cteroot;
5594 Index levelsup;
5595 int ndx;
5596 int plan_id;
5597 ListCell *lc;
5600 * Find the referenced CTE, and locate the subroot previously made
5601 * for it.
5603 levelsup = rte->ctelevelsup;
5604 cteroot = root;
5605 while (levelsup-- > 0)
5607 cteroot = cteroot->parent_root;
5608 if (!cteroot) /* shouldn't happen */
5609 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
5613 * Note: cte_plan_ids can be shorter than cteList, if we are still
5614 * working on planning the CTEs (ie, this is a side-reference from
5615 * another CTE). So we mustn't use forboth here.
5617 ndx = 0;
5618 foreach(lc, cteroot->parse->cteList)
5620 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
5622 if (strcmp(cte->ctename, rte->ctename) == 0)
5623 break;
5624 ndx++;
5626 if (lc == NULL) /* shouldn't happen */
5627 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
5628 if (ndx >= list_length(cteroot->cte_plan_ids))
5629 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
5630 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
5631 if (plan_id <= 0)
5632 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
5633 subroot = list_nth(root->glob->subroots, plan_id - 1);
5636 /* If the subquery hasn't been planned yet, we have to punt */
5637 if (subroot == NULL)
5638 return;
5639 Assert(IsA(subroot, PlannerInfo));
5642 * We must use the subquery parsetree as mangled by the planner, not
5643 * the raw version from the RTE, because we need a Var that will refer
5644 * to the subroot's live RelOptInfos. For instance, if any subquery
5645 * pullup happened during planning, Vars in the targetlist might have
5646 * gotten replaced, and we need to see the replacement expressions.
5648 subquery = subroot->parse;
5649 Assert(IsA(subquery, Query));
5652 * Punt if subquery uses set operations or GROUP BY, as these will
5653 * mash underlying columns' stats beyond recognition. (Set ops are
5654 * particularly nasty; if we forged ahead, we would return stats
5655 * relevant to only the leftmost subselect...) DISTINCT is also
5656 * problematic, but we check that later because there is a possibility
5657 * of learning something even with it.
5659 if (subquery->setOperations ||
5660 subquery->groupClause ||
5661 subquery->groupingSets)
5662 return;
5664 /* Get the subquery output expression referenced by the upper Var */
5665 if (subquery->returningList)
5666 subtlist = subquery->returningList;
5667 else
5668 subtlist = subquery->targetList;
5669 ste = get_tle_by_resno(subtlist, var->varattno);
5670 if (ste == NULL || ste->resjunk)
5671 elog(ERROR, "subquery %s does not have attribute %d",
5672 rte->eref->aliasname, var->varattno);
5673 var = (Var *) ste->expr;
5676 * If subquery uses DISTINCT, we can't make use of any stats for the
5677 * variable ... but, if it's the only DISTINCT column, we are entitled
5678 * to consider it unique. We do the test this way so that it works
5679 * for cases involving DISTINCT ON.
5681 if (subquery->distinctClause)
5683 if (list_length(subquery->distinctClause) == 1 &&
5684 targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5685 vardata->isunique = true;
5686 /* cannot go further */
5687 return;
5691 * If the sub-query originated from a view with the security_barrier
5692 * attribute, we must not look at the variable's statistics, though it
5693 * seems all right to notice the existence of a DISTINCT clause. So
5694 * stop here.
5696 * This is probably a harsher restriction than necessary; it's
5697 * certainly OK for the selectivity estimator (which is a C function,
5698 * and therefore omnipotent anyway) to look at the statistics. But
5699 * many selectivity estimators will happily *invoke the operator
5700 * function* to try to work out a good estimate - and that's not OK.
5701 * So for now, don't dig down for stats.
5703 if (rte->security_barrier)
5704 return;
5706 /* Can only handle a simple Var of subquery's query level */
5707 if (var && IsA(var, Var) &&
5708 var->varlevelsup == 0)
5711 * OK, recurse into the subquery. Note that the original setting
5712 * of vardata->isunique (which will surely be false) is left
5713 * unchanged in this situation. That's what we want, since even
5714 * if the underlying column is unique, the subquery may have
5715 * joined to other tables in a way that creates duplicates.
5717 examine_simple_variable(subroot, var, vardata);
5720 else
5723 * Otherwise, the Var comes from a FUNCTION or VALUES RTE. (We won't
5724 * see RTE_JOIN here because join alias Vars have already been
5725 * flattened.) There's not much we can do with function outputs, but
5726 * maybe someday try to be smarter about VALUES.
5732 * Check whether it is permitted to call func_oid passing some of the
5733 * pg_statistic data in vardata. We allow this either if the user has SELECT
5734 * privileges on the table or column underlying the pg_statistic data or if
5735 * the function is marked leak-proof.
5737 bool
5738 statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
5740 if (vardata->acl_ok)
5741 return true;
5743 if (!OidIsValid(func_oid))
5744 return false;
5746 if (get_func_leakproof(func_oid))
5747 return true;
5749 ereport(DEBUG2,
5750 (errmsg_internal("not using statistics because function \"%s\" is not leak-proof",
5751 get_func_name(func_oid))));
5752 return false;
5756 * get_variable_numdistinct
5757 * Estimate the number of distinct values of a variable.
5759 * vardata: results of examine_variable
5760 * *isdefault: set to true if the result is a default rather than based on
5761 * anything meaningful.
5763 * NB: be careful to produce a positive integral result, since callers may
5764 * compare the result to exact integer counts, or might divide by it.
5766 double
5767 get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
5769 double stadistinct;
5770 double stanullfrac = 0.0;
5771 double ntuples;
5773 *isdefault = false;
5776 * Determine the stadistinct value to use. There are cases where we can
5777 * get an estimate even without a pg_statistic entry, or can get a better
5778 * value than is in pg_statistic. Grab stanullfrac too if we can find it
5779 * (otherwise, assume no nulls, for lack of any better idea).
5781 if (HeapTupleIsValid(vardata->statsTuple))
5783 /* Use the pg_statistic entry */
5784 Form_pg_statistic stats;
5786 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
5787 stadistinct = stats->stadistinct;
5788 stanullfrac = stats->stanullfrac;
5790 else if (vardata->vartype == BOOLOID)
5793 * Special-case boolean columns: presumably, two distinct values.
5795 * Are there any other datatypes we should wire in special estimates
5796 * for?
5798 stadistinct = 2.0;
5800 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5803 * If the Var represents a column of a VALUES RTE, assume it's unique.
5804 * This could of course be very wrong, but it should tend to be true
5805 * in well-written queries. We could consider examining the VALUES'
5806 * contents to get some real statistics; but that only works if the
5807 * entries are all constants, and it would be pretty expensive anyway.
5809 stadistinct = -1.0; /* unique (and all non null) */
5811 else
5814 * We don't keep statistics for system columns, but in some cases we
5815 * can infer distinctness anyway.
5817 if (vardata->var && IsA(vardata->var, Var))
5819 switch (((Var *) vardata->var)->varattno)
5821 case SelfItemPointerAttributeNumber:
5822 stadistinct = -1.0; /* unique (and all non null) */
5823 break;
5824 case TableOidAttributeNumber:
5825 stadistinct = 1.0; /* only 1 value */
5826 break;
5827 default:
5828 stadistinct = 0.0; /* means "unknown" */
5829 break;
5832 else
5833 stadistinct = 0.0; /* means "unknown" */
5836 * XXX consider using estimate_num_groups on expressions?
5841 * If there is a unique index or DISTINCT clause for the variable, assume
5842 * it is unique no matter what pg_statistic says; the statistics could be
5843 * out of date, or we might have found a partial unique index that proves
5844 * the var is unique for this query. However, we'd better still believe
5845 * the null-fraction statistic.
5847 if (vardata->isunique)
5848 stadistinct = -1.0 * (1.0 - stanullfrac);
5851 * If we had an absolute estimate, use that.
5853 if (stadistinct > 0.0)
5854 return clamp_row_est(stadistinct);
5857 * Otherwise we need to get the relation size; punt if not available.
5859 if (vardata->rel == NULL)
5861 *isdefault = true;
5862 return DEFAULT_NUM_DISTINCT;
5864 ntuples = vardata->rel->tuples;
5865 if (ntuples <= 0.0)
5867 *isdefault = true;
5868 return DEFAULT_NUM_DISTINCT;
5872 * If we had a relative estimate, use that.
5874 if (stadistinct < 0.0)
5875 return clamp_row_est(-stadistinct * ntuples);
5878 * With no data, estimate ndistinct = ntuples if the table is small, else
5879 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
5880 * that the behavior isn't discontinuous.
5882 if (ntuples < DEFAULT_NUM_DISTINCT)
5883 return clamp_row_est(ntuples);
5885 *isdefault = true;
5886 return DEFAULT_NUM_DISTINCT;
5890 * get_variable_range
5891 * Estimate the minimum and maximum value of the specified variable.
5892 * If successful, store values in *min and *max, and return true.
5893 * If no data available, return false.
5895 * sortop is the "<" comparison operator to use. This should generally
5896 * be "<" not ">", as only the former is likely to be found in pg_statistic.
5897 * The collation must be specified too.
5899 static bool
5900 get_variable_range(PlannerInfo *root, VariableStatData *vardata,
5901 Oid sortop, Oid collation,
5902 Datum *min, Datum *max)
5904 Datum tmin = 0;
5905 Datum tmax = 0;
5906 bool have_data = false;
5907 int16 typLen;
5908 bool typByVal;
5909 Oid opfuncoid;
5910 FmgrInfo opproc;
5911 AttStatsSlot sslot;
5914 * XXX It's very tempting to try to use the actual column min and max, if
5915 * we can get them relatively-cheaply with an index probe. However, since
5916 * this function is called many times during join planning, that could
5917 * have unpleasant effects on planning speed. Need more investigation
5918 * before enabling this.
5920 #ifdef NOT_USED
5921 if (get_actual_variable_range(root, vardata, sortop, collation, min, max))
5922 return true;
5923 #endif
5925 if (!HeapTupleIsValid(vardata->statsTuple))
5927 /* no stats available, so default result */
5928 return false;
5932 * If we can't apply the sortop to the stats data, just fail. In
5933 * principle, if there's a histogram and no MCVs, we could return the
5934 * histogram endpoints without ever applying the sortop ... but it's
5935 * probably not worth trying, because whatever the caller wants to do with
5936 * the endpoints would likely fail the security check too.
5938 if (!statistic_proc_security_check(vardata,
5939 (opfuncoid = get_opcode(sortop))))
5940 return false;
5942 opproc.fn_oid = InvalidOid; /* mark this as not looked up yet */
5944 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5947 * If there is a histogram with the ordering we want, grab the first and
5948 * last values.
5950 if (get_attstatsslot(&sslot, vardata->statsTuple,
5951 STATISTIC_KIND_HISTOGRAM, sortop,
5952 ATTSTATSSLOT_VALUES))
5954 if (sslot.stacoll == collation && sslot.nvalues > 0)
5956 tmin = datumCopy(sslot.values[0], typByVal, typLen);
5957 tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
5958 have_data = true;
5960 free_attstatsslot(&sslot);
5964 * Otherwise, if there is a histogram with some other ordering, scan it
5965 * and get the min and max values according to the ordering we want. This
5966 * of course may not find values that are really extremal according to our
5967 * ordering, but it beats ignoring available data.
5969 if (!have_data &&
5970 get_attstatsslot(&sslot, vardata->statsTuple,
5971 STATISTIC_KIND_HISTOGRAM, InvalidOid,
5972 ATTSTATSSLOT_VALUES))
5974 get_stats_slot_range(&sslot, opfuncoid, &opproc,
5975 collation, typLen, typByVal,
5976 &tmin, &tmax, &have_data);
5977 free_attstatsslot(&sslot);
5981 * If we have most-common-values info, look for extreme MCVs. This is
5982 * needed even if we also have a histogram, since the histogram excludes
5983 * the MCVs. However, if we *only* have MCVs and no histogram, we should
5984 * be pretty wary of deciding that that is a full representation of the
5985 * data. Proceed only if the MCVs represent the whole table (to within
5986 * roundoff error).
5988 if (get_attstatsslot(&sslot, vardata->statsTuple,
5989 STATISTIC_KIND_MCV, InvalidOid,
5990 have_data ? ATTSTATSSLOT_VALUES :
5991 (ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)))
5993 bool use_mcvs = have_data;
5995 if (!have_data)
5997 double sumcommon = 0.0;
5998 double nullfrac;
5999 int i;
6001 for (i = 0; i < sslot.nnumbers; i++)
6002 sumcommon += sslot.numbers[i];
6003 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata->statsTuple))->stanullfrac;
6004 if (sumcommon + nullfrac > 0.99999)
6005 use_mcvs = true;
6008 if (use_mcvs)
6009 get_stats_slot_range(&sslot, opfuncoid, &opproc,
6010 collation, typLen, typByVal,
6011 &tmin, &tmax, &have_data);
6012 free_attstatsslot(&sslot);
6015 *min = tmin;
6016 *max = tmax;
6017 return have_data;
6021 * get_stats_slot_range: scan sslot for min/max values
6023 * Subroutine for get_variable_range: update min/max/have_data according
6024 * to what we find in the statistics array.
6026 static void
6027 get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
6028 Oid collation, int16 typLen, bool typByVal,
6029 Datum *min, Datum *max, bool *p_have_data)
6031 Datum tmin = *min;
6032 Datum tmax = *max;
6033 bool have_data = *p_have_data;
6034 bool found_tmin = false;
6035 bool found_tmax = false;
6037 /* Look up the comparison function, if we didn't already do so */
6038 if (opproc->fn_oid != opfuncoid)
6039 fmgr_info(opfuncoid, opproc);
6041 /* Scan all the slot's values */
6042 for (int i = 0; i < sslot->nvalues; i++)
6044 if (!have_data)
6046 tmin = tmax = sslot->values[i];
6047 found_tmin = found_tmax = true;
6048 *p_have_data = have_data = true;
6049 continue;
6051 if (DatumGetBool(FunctionCall2Coll(opproc,
6052 collation,
6053 sslot->values[i], tmin)))
6055 tmin = sslot->values[i];
6056 found_tmin = true;
6058 if (DatumGetBool(FunctionCall2Coll(opproc,
6059 collation,
6060 tmax, sslot->values[i])))
6062 tmax = sslot->values[i];
6063 found_tmax = true;
6068 * Copy the slot's values, if we found new extreme values.
6070 if (found_tmin)
6071 *min = datumCopy(tmin, typByVal, typLen);
6072 if (found_tmax)
6073 *max = datumCopy(tmax, typByVal, typLen);
6078 * get_actual_variable_range
6079 * Attempt to identify the current *actual* minimum and/or maximum
6080 * of the specified variable, by looking for a suitable btree index
6081 * and fetching its low and/or high values.
6082 * If successful, store values in *min and *max, and return true.
6083 * (Either pointer can be NULL if that endpoint isn't needed.)
6084 * If unsuccessful, return false.
6086 * sortop is the "<" comparison operator to use.
6087 * collation is the required collation.
6089 static bool
6090 get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
6091 Oid sortop, Oid collation,
6092 Datum *min, Datum *max)
6094 bool have_data = false;
6095 RelOptInfo *rel = vardata->rel;
6096 RangeTblEntry *rte;
6097 ListCell *lc;
6099 /* No hope if no relation or it doesn't have indexes */
6100 if (rel == NULL || rel->indexlist == NIL)
6101 return false;
6102 /* If it has indexes it must be a plain relation */
6103 rte = root->simple_rte_array[rel->relid];
6104 Assert(rte->rtekind == RTE_RELATION);
6106 /* ignore partitioned tables. Any indexes here are not real indexes */
6107 if (rte->relkind == RELKIND_PARTITIONED_TABLE)
6108 return false;
6110 /* Search through the indexes to see if any match our problem */
6111 foreach(lc, rel->indexlist)
6113 IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
6114 ScanDirection indexscandir;
6116 /* Ignore non-btree indexes */
6117 if (index->relam != BTREE_AM_OID)
6118 continue;
6121 * Ignore partial indexes --- we only want stats that cover the entire
6122 * relation.
6124 if (index->indpred != NIL)
6125 continue;
6128 * The index list might include hypothetical indexes inserted by a
6129 * get_relation_info hook --- don't try to access them.
6131 if (index->hypothetical)
6132 continue;
6135 * The first index column must match the desired variable, sortop, and
6136 * collation --- but we can use a descending-order index.
6138 if (collation != index->indexcollations[0])
6139 continue; /* test first 'cause it's cheapest */
6140 if (!match_index_to_operand(vardata->var, 0, index))
6141 continue;
6142 switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
6144 case BTLessStrategyNumber:
6145 if (index->reverse_sort[0])
6146 indexscandir = BackwardScanDirection;
6147 else
6148 indexscandir = ForwardScanDirection;
6149 break;
6150 case BTGreaterStrategyNumber:
6151 if (index->reverse_sort[0])
6152 indexscandir = ForwardScanDirection;
6153 else
6154 indexscandir = BackwardScanDirection;
6155 break;
6156 default:
6157 /* index doesn't match the sortop */
6158 continue;
6162 * Found a suitable index to extract data from. Set up some data that
6163 * can be used by both invocations of get_actual_variable_endpoint.
6166 MemoryContext tmpcontext;
6167 MemoryContext oldcontext;
6168 Relation heapRel;
6169 Relation indexRel;
6170 TupleTableSlot *slot;
6171 int16 typLen;
6172 bool typByVal;
6173 ScanKeyData scankeys[1];
6175 /* Make sure any cruft gets recycled when we're done */
6176 tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
6177 "get_actual_variable_range workspace",
6178 ALLOCSET_DEFAULT_SIZES);
6179 oldcontext = MemoryContextSwitchTo(tmpcontext);
6182 * Open the table and index so we can read from them. We should
6183 * already have some type of lock on each.
6185 heapRel = table_open(rte->relid, NoLock);
6186 indexRel = index_open(index->indexoid, NoLock);
6188 /* build some stuff needed for indexscan execution */
6189 slot = table_slot_create(heapRel, NULL);
6190 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
6192 /* set up an IS NOT NULL scan key so that we ignore nulls */
6193 ScanKeyEntryInitialize(&scankeys[0],
6194 SK_ISNULL | SK_SEARCHNOTNULL,
6195 1, /* index col to scan */
6196 InvalidStrategy, /* no strategy */
6197 InvalidOid, /* no strategy subtype */
6198 InvalidOid, /* no collation */
6199 InvalidOid, /* no reg proc for this */
6200 (Datum) 0); /* constant */
6202 /* If min is requested ... */
6203 if (min)
6205 have_data = get_actual_variable_endpoint(heapRel,
6206 indexRel,
6207 indexscandir,
6208 scankeys,
6209 typLen,
6210 typByVal,
6211 slot,
6212 oldcontext,
6213 min);
6215 else
6217 /* If min not requested, still want to fetch max */
6218 have_data = true;
6221 /* If max is requested, and we didn't already fail ... */
6222 if (max && have_data)
6224 /* scan in the opposite direction; all else is the same */
6225 have_data = get_actual_variable_endpoint(heapRel,
6226 indexRel,
6227 -indexscandir,
6228 scankeys,
6229 typLen,
6230 typByVal,
6231 slot,
6232 oldcontext,
6233 max);
6236 /* Clean everything up */
6237 ExecDropSingleTupleTableSlot(slot);
6239 index_close(indexRel, NoLock);
6240 table_close(heapRel, NoLock);
6242 MemoryContextSwitchTo(oldcontext);
6243 MemoryContextDelete(tmpcontext);
6245 /* And we're done */
6246 break;
6250 return have_data;
6254 * Get one endpoint datum (min or max depending on indexscandir) from the
6255 * specified index. Return true if successful, false if not.
6256 * On success, endpoint value is stored to *endpointDatum (and copied into
6257 * outercontext).
6259 * scankeys is a 1-element scankey array set up to reject nulls.
6260 * typLen/typByVal describe the datatype of the index's first column.
6261 * tableslot is a slot suitable to hold table tuples, in case we need
6262 * to probe the heap.
6263 * (We could compute these values locally, but that would mean computing them
6264 * twice when get_actual_variable_range needs both the min and the max.)
6266 * Failure occurs either when the index is empty, or we decide that it's
6267 * taking too long to find a suitable tuple.
6269 static bool
6270 get_actual_variable_endpoint(Relation heapRel,
6271 Relation indexRel,
6272 ScanDirection indexscandir,
6273 ScanKey scankeys,
6274 int16 typLen,
6275 bool typByVal,
6276 TupleTableSlot *tableslot,
6277 MemoryContext outercontext,
6278 Datum *endpointDatum)
6280 bool have_data = false;
6281 SnapshotData SnapshotNonVacuumable;
6282 IndexScanDesc index_scan;
6283 Buffer vmbuffer = InvalidBuffer;
6284 BlockNumber last_heap_block = InvalidBlockNumber;
6285 int n_visited_heap_pages = 0;
6286 ItemPointer tid;
6287 Datum values[INDEX_MAX_KEYS];
6288 bool isnull[INDEX_MAX_KEYS];
6289 MemoryContext oldcontext;
6292 * We use the index-only-scan machinery for this. With mostly-static
6293 * tables that's a win because it avoids a heap visit. It's also a win
6294 * for dynamic data, but the reason is less obvious; read on for details.
6296 * In principle, we should scan the index with our current active
6297 * snapshot, which is the best approximation we've got to what the query
6298 * will see when executed. But that won't be exact if a new snap is taken
6299 * before running the query, and it can be very expensive if a lot of
6300 * recently-dead or uncommitted rows exist at the beginning or end of the
6301 * index (because we'll laboriously fetch each one and reject it).
6302 * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
6303 * and uncommitted rows as well as normal visible rows. On the other
6304 * hand, it will reject known-dead rows, and thus not give a bogus answer
6305 * when the extreme value has been deleted (unless the deletion was quite
6306 * recent); that case motivates not using SnapshotAny here.
6308 * A crucial point here is that SnapshotNonVacuumable, with
6309 * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
6310 * condition that the indexscan will use to decide that index entries are
6311 * killable (see heap_hot_search_buffer()). Therefore, if the snapshot
6312 * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
6313 * have to continue scanning past it, we know that the indexscan will mark
6314 * that index entry killed. That means that the next
6315 * get_actual_variable_endpoint() call will not have to re-consider that
6316 * index entry. In this way we avoid repetitive work when this function
6317 * is used a lot during planning.
6319 * But using SnapshotNonVacuumable creates a hazard of its own. In a
6320 * recently-created index, some index entries may point at "broken" HOT
6321 * chains in which not all the tuple versions contain data matching the
6322 * index entry. The live tuple version(s) certainly do match the index,
6323 * but SnapshotNonVacuumable can accept recently-dead tuple versions that
6324 * don't match. Hence, if we took data from the selected heap tuple, we
6325 * might get a bogus answer that's not close to the index extremal value,
6326 * or could even be NULL. We avoid this hazard because we take the data
6327 * from the index entry not the heap.
6329 * Despite all this care, there are situations where we might find many
6330 * non-visible tuples near the end of the index. We don't want to expend
6331 * a huge amount of time here, so we give up once we've read too many heap
6332 * pages. When we fail for that reason, the caller will end up using
6333 * whatever extremal value is recorded in pg_statistic.
6335 InitNonVacuumableSnapshot(SnapshotNonVacuumable,
6336 GlobalVisTestFor(heapRel));
6338 index_scan = index_beginscan(heapRel, indexRel,
6339 &SnapshotNonVacuumable,
6340 1, 0);
6341 /* Set it up for index-only scan */
6342 index_scan->xs_want_itup = true;
6343 index_rescan(index_scan, scankeys, 1, NULL, 0);
6345 /* Fetch first/next tuple in specified direction */
6346 while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
6348 BlockNumber block = ItemPointerGetBlockNumber(tid);
6350 if (!VM_ALL_VISIBLE(heapRel,
6351 block,
6352 &vmbuffer))
6354 /* Rats, we have to visit the heap to check visibility */
6355 if (!index_fetch_heap(index_scan, tableslot))
6358 * No visible tuple for this index entry, so we need to
6359 * advance to the next entry. Before doing so, count heap
6360 * page fetches and give up if we've done too many.
6362 * We don't charge a page fetch if this is the same heap page
6363 * as the previous tuple. This is on the conservative side,
6364 * since other recently-accessed pages are probably still in
6365 * buffers too; but it's good enough for this heuristic.
6367 #define VISITED_PAGES_LIMIT 100
6369 if (block != last_heap_block)
6371 last_heap_block = block;
6372 n_visited_heap_pages++;
6373 if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
6374 break;
6377 continue; /* no visible tuple, try next index entry */
6380 /* We don't actually need the heap tuple for anything */
6381 ExecClearTuple(tableslot);
6384 * We don't care whether there's more than one visible tuple in
6385 * the HOT chain; if any are visible, that's good enough.
6390 * We expect that btree will return data in IndexTuple not HeapTuple
6391 * format. It's not lossy either.
6393 if (!index_scan->xs_itup)
6394 elog(ERROR, "no data returned for index-only scan");
6395 if (index_scan->xs_recheck)
6396 elog(ERROR, "unexpected recheck indication from btree");
6398 /* OK to deconstruct the index tuple */
6399 index_deform_tuple(index_scan->xs_itup,
6400 index_scan->xs_itupdesc,
6401 values, isnull);
6403 /* Shouldn't have got a null, but be careful */
6404 if (isnull[0])
6405 elog(ERROR, "found unexpected null value in index \"%s\"",
6406 RelationGetRelationName(indexRel));
6408 /* Copy the index column value out to caller's context */
6409 oldcontext = MemoryContextSwitchTo(outercontext);
6410 *endpointDatum = datumCopy(values[0], typByVal, typLen);
6411 MemoryContextSwitchTo(oldcontext);
6412 have_data = true;
6413 break;
6416 if (vmbuffer != InvalidBuffer)
6417 ReleaseBuffer(vmbuffer);
6418 index_endscan(index_scan);
6420 return have_data;
6424 * find_join_input_rel
6425 * Look up the input relation for a join.
6427 * We assume that the input relation's RelOptInfo must have been constructed
6428 * already.
6430 static RelOptInfo *
6431 find_join_input_rel(PlannerInfo *root, Relids relids)
6433 RelOptInfo *rel = NULL;
6435 if (!bms_is_empty(relids))
6437 int relid;
6439 if (bms_get_singleton_member(relids, &relid))
6440 rel = find_base_rel(root, relid);
6441 else
6442 rel = find_join_rel(root, relids);
6445 if (rel == NULL)
6446 elog(ERROR, "could not find RelOptInfo for given relids");
6448 return rel;
6452 /*-------------------------------------------------------------------------
6454 * Index cost estimation functions
6456 *-------------------------------------------------------------------------
6460 * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
6462 List *
6463 get_quals_from_indexclauses(List *indexclauses)
6465 List *result = NIL;
6466 ListCell *lc;
6468 foreach(lc, indexclauses)
6470 IndexClause *iclause = lfirst_node(IndexClause, lc);
6471 ListCell *lc2;
6473 foreach(lc2, iclause->indexquals)
6475 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6477 result = lappend(result, rinfo);
6480 return result;
6484 * Compute the total evaluation cost of the comparison operands in a list
6485 * of index qual expressions. Since we know these will be evaluated just
6486 * once per scan, there's no need to distinguish startup from per-row cost.
6488 * This can be used either on the result of get_quals_from_indexclauses(),
6489 * or directly on an indexorderbys list. In both cases, we expect that the
6490 * index key expression is on the left side of binary clauses.
6492 Cost
6493 index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
6495 Cost qual_arg_cost = 0;
6496 ListCell *lc;
6498 foreach(lc, indexquals)
6500 Expr *clause = (Expr *) lfirst(lc);
6501 Node *other_operand;
6502 QualCost index_qual_cost;
6505 * Index quals will have RestrictInfos, indexorderbys won't. Look
6506 * through RestrictInfo if present.
6508 if (IsA(clause, RestrictInfo))
6509 clause = ((RestrictInfo *) clause)->clause;
6511 if (IsA(clause, OpExpr))
6513 OpExpr *op = (OpExpr *) clause;
6515 other_operand = (Node *) lsecond(op->args);
6517 else if (IsA(clause, RowCompareExpr))
6519 RowCompareExpr *rc = (RowCompareExpr *) clause;
6521 other_operand = (Node *) rc->rargs;
6523 else if (IsA(clause, ScalarArrayOpExpr))
6525 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6527 other_operand = (Node *) lsecond(saop->args);
6529 else if (IsA(clause, NullTest))
6531 other_operand = NULL;
6533 else
6535 elog(ERROR, "unsupported indexqual type: %d",
6536 (int) nodeTag(clause));
6537 other_operand = NULL; /* keep compiler quiet */
6540 cost_qual_eval_node(&index_qual_cost, other_operand, root);
6541 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6543 return qual_arg_cost;
6546 void
6547 genericcostestimate(PlannerInfo *root,
6548 IndexPath *path,
6549 double loop_count,
6550 GenericCosts *costs)
6552 IndexOptInfo *index = path->indexinfo;
6553 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6554 List *indexOrderBys = path->indexorderbys;
6555 Cost indexStartupCost;
6556 Cost indexTotalCost;
6557 Selectivity indexSelectivity;
6558 double indexCorrelation;
6559 double numIndexPages;
6560 double numIndexTuples;
6561 double spc_random_page_cost;
6562 double num_sa_scans;
6563 double num_outer_scans;
6564 double num_scans;
6565 double qual_op_cost;
6566 double qual_arg_cost;
6567 List *selectivityQuals;
6568 ListCell *l;
6571 * If the index is partial, AND the index predicate with the explicitly
6572 * given indexquals to produce a more accurate idea of the index
6573 * selectivity.
6575 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6578 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
6579 * just assume that the number of index descents is the number of distinct
6580 * combinations of array elements from all of the scan's SAOP clauses.
6582 num_sa_scans = costs->num_sa_scans;
6583 if (num_sa_scans < 1)
6585 num_sa_scans = 1;
6586 foreach(l, indexQuals)
6588 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6590 if (IsA(rinfo->clause, ScalarArrayOpExpr))
6592 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6593 double alength = estimate_array_length(root, lsecond(saop->args));
6595 if (alength > 1)
6596 num_sa_scans *= alength;
6601 /* Estimate the fraction of main-table tuples that will be visited */
6602 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6603 index->rel->relid,
6604 JOIN_INNER,
6605 NULL);
6608 * If caller didn't give us an estimate, estimate the number of index
6609 * tuples that will be visited. We do it in this rather peculiar-looking
6610 * way in order to get the right answer for partial indexes.
6612 numIndexTuples = costs->numIndexTuples;
6613 if (numIndexTuples <= 0.0)
6615 numIndexTuples = indexSelectivity * index->rel->tuples;
6618 * The above calculation counts all the tuples visited across all
6619 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6620 * average per-indexscan number, so adjust. This is a handy place to
6621 * round to integer, too. (If caller supplied tuple estimate, it's
6622 * responsible for handling these considerations.)
6624 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6628 * We can bound the number of tuples by the index size in any case. Also,
6629 * always estimate at least one tuple is touched, even when
6630 * indexSelectivity estimate is tiny.
6632 if (numIndexTuples > index->tuples)
6633 numIndexTuples = index->tuples;
6634 if (numIndexTuples < 1.0)
6635 numIndexTuples = 1.0;
6638 * Estimate the number of index pages that will be retrieved.
6640 * We use the simplistic method of taking a pro-rata fraction of the total
6641 * number of index pages. In effect, this counts only leaf pages and not
6642 * any overhead such as index metapage or upper tree levels.
6644 * In practice access to upper index levels is often nearly free because
6645 * those tend to stay in cache under load; moreover, the cost involved is
6646 * highly dependent on index type. We therefore ignore such costs here
6647 * and leave it to the caller to add a suitable charge if needed.
6649 if (index->pages > 1 && index->tuples > 1)
6650 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6651 else
6652 numIndexPages = 1.0;
6654 /* fetch estimated page cost for tablespace containing index */
6655 get_tablespace_page_costs(index->reltablespace,
6656 &spc_random_page_cost,
6657 NULL);
6660 * Now compute the disk access costs.
6662 * The above calculations are all per-index-scan. However, if we are in a
6663 * nestloop inner scan, we can expect the scan to be repeated (with
6664 * different search keys) for each row of the outer relation. Likewise,
6665 * ScalarArrayOpExpr quals result in multiple index scans. This creates
6666 * the potential for cache effects to reduce the number of disk page
6667 * fetches needed. We want to estimate the average per-scan I/O cost in
6668 * the presence of caching.
6670 * We use the Mackert-Lohman formula (see costsize.c for details) to
6671 * estimate the total number of page fetches that occur. While this
6672 * wasn't what it was designed for, it seems a reasonable model anyway.
6673 * Note that we are counting pages not tuples anymore, so we take N = T =
6674 * index size, as if there were one "tuple" per page.
6676 num_outer_scans = loop_count;
6677 num_scans = num_sa_scans * num_outer_scans;
6679 if (num_scans > 1)
6681 double pages_fetched;
6683 /* total page fetches ignoring cache effects */
6684 pages_fetched = numIndexPages * num_scans;
6686 /* use Mackert and Lohman formula to adjust for cache effects */
6687 pages_fetched = index_pages_fetched(pages_fetched,
6688 index->pages,
6689 (double) index->pages,
6690 root);
6693 * Now compute the total disk access cost, and then report a pro-rated
6694 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6695 * since that's internal to the indexscan.)
6697 indexTotalCost = (pages_fetched * spc_random_page_cost)
6698 / num_outer_scans;
6700 else
6703 * For a single index scan, we just charge spc_random_page_cost per
6704 * page touched.
6706 indexTotalCost = numIndexPages * spc_random_page_cost;
6710 * CPU cost: any complex expressions in the indexquals will need to be
6711 * evaluated once at the start of the scan to reduce them to runtime keys
6712 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6713 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6714 * indexqual operator. Because we have numIndexTuples as a per-scan
6715 * number, we have to multiply by num_sa_scans to get the correct result
6716 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6717 * ORDER BY expressions.
6719 * Note: this neglects the possible costs of rechecking lossy operators.
6720 * Detecting that that might be needed seems more expensive than it's
6721 * worth, though, considering all the other inaccuracies here ...
6723 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
6724 index_other_operands_eval_cost(root, indexOrderBys);
6725 qual_op_cost = cpu_operator_cost *
6726 (list_length(indexQuals) + list_length(indexOrderBys));
6728 indexStartupCost = qual_arg_cost;
6729 indexTotalCost += qual_arg_cost;
6730 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6733 * Generic assumption about index correlation: there isn't any.
6735 indexCorrelation = 0.0;
6738 * Return everything to caller.
6740 costs->indexStartupCost = indexStartupCost;
6741 costs->indexTotalCost = indexTotalCost;
6742 costs->indexSelectivity = indexSelectivity;
6743 costs->indexCorrelation = indexCorrelation;
6744 costs->numIndexPages = numIndexPages;
6745 costs->numIndexTuples = numIndexTuples;
6746 costs->spc_random_page_cost = spc_random_page_cost;
6747 costs->num_sa_scans = num_sa_scans;
6751 * If the index is partial, add its predicate to the given qual list.
6753 * ANDing the index predicate with the explicitly given indexquals produces
6754 * a more accurate idea of the index's selectivity. However, we need to be
6755 * careful not to insert redundant clauses, because clauselist_selectivity()
6756 * is easily fooled into computing a too-low selectivity estimate. Our
6757 * approach is to add only the predicate clause(s) that cannot be proven to
6758 * be implied by the given indexquals. This successfully handles cases such
6759 * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
6760 * There are many other cases where we won't detect redundancy, leading to a
6761 * too-low selectivity estimate, which will bias the system in favor of using
6762 * partial indexes where possible. That is not necessarily bad though.
6764 * Note that indexQuals contains RestrictInfo nodes while the indpred
6765 * does not, so the output list will be mixed. This is OK for both
6766 * predicate_implied_by() and clauselist_selectivity(), but might be
6767 * problematic if the result were passed to other things.
6769 List *
6770 add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
6772 List *predExtraQuals = NIL;
6773 ListCell *lc;
6775 if (index->indpred == NIL)
6776 return indexQuals;
6778 foreach(lc, index->indpred)
6780 Node *predQual = (Node *) lfirst(lc);
6781 List *oneQual = list_make1(predQual);
6783 if (!predicate_implied_by(oneQual, indexQuals, false))
6784 predExtraQuals = list_concat(predExtraQuals, oneQual);
6786 return list_concat(predExtraQuals, indexQuals);
6790 void
6791 btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
6792 Cost *indexStartupCost, Cost *indexTotalCost,
6793 Selectivity *indexSelectivity, double *indexCorrelation,
6794 double *indexPages)
6796 IndexOptInfo *index = path->indexinfo;
6797 GenericCosts costs = {0};
6798 Oid relid;
6799 AttrNumber colnum;
6800 VariableStatData vardata = {0};
6801 double numIndexTuples;
6802 Cost descentCost;
6803 List *indexBoundQuals;
6804 int indexcol;
6805 bool eqQualHere;
6806 bool found_saop;
6807 bool found_is_null_op;
6808 double num_sa_scans;
6809 ListCell *lc;
6812 * For a btree scan, only leading '=' quals plus inequality quals for the
6813 * immediately next attribute contribute to index selectivity (these are
6814 * the "boundary quals" that determine the starting and stopping points of
6815 * the index scan). Additional quals can suppress visits to the heap, so
6816 * it's OK to count them in indexSelectivity, but they should not count
6817 * for estimating numIndexTuples. So we must examine the given indexquals
6818 * to find out which ones count as boundary quals. We rely on the
6819 * knowledge that they are given in index column order.
6821 * For a RowCompareExpr, we consider only the first column, just as
6822 * rowcomparesel() does.
6824 * If there's a ScalarArrayOpExpr in the quals, we'll actually perform up
6825 * to N index descents (not just one), but the ScalarArrayOpExpr's
6826 * operator can be considered to act the same as it normally does.
6828 indexBoundQuals = NIL;
6829 indexcol = 0;
6830 eqQualHere = false;
6831 found_saop = false;
6832 found_is_null_op = false;
6833 num_sa_scans = 1;
6834 foreach(lc, path->indexclauses)
6836 IndexClause *iclause = lfirst_node(IndexClause, lc);
6837 ListCell *lc2;
6839 if (indexcol != iclause->indexcol)
6841 /* Beginning of a new column's quals */
6842 if (!eqQualHere)
6843 break; /* done if no '=' qual for indexcol */
6844 eqQualHere = false;
6845 indexcol++;
6846 if (indexcol != iclause->indexcol)
6847 break; /* no quals at all for indexcol */
6850 /* Examine each indexqual associated with this index clause */
6851 foreach(lc2, iclause->indexquals)
6853 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6854 Expr *clause = rinfo->clause;
6855 Oid clause_op = InvalidOid;
6856 int op_strategy;
6858 if (IsA(clause, OpExpr))
6860 OpExpr *op = (OpExpr *) clause;
6862 clause_op = op->opno;
6864 else if (IsA(clause, RowCompareExpr))
6866 RowCompareExpr *rc = (RowCompareExpr *) clause;
6868 clause_op = linitial_oid(rc->opnos);
6870 else if (IsA(clause, ScalarArrayOpExpr))
6872 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6873 Node *other_operand = (Node *) lsecond(saop->args);
6874 double alength = estimate_array_length(root, other_operand);
6876 clause_op = saop->opno;
6877 found_saop = true;
6878 /* estimate SA descents by indexBoundQuals only */
6879 if (alength > 1)
6880 num_sa_scans *= alength;
6882 else if (IsA(clause, NullTest))
6884 NullTest *nt = (NullTest *) clause;
6886 if (nt->nulltesttype == IS_NULL)
6888 found_is_null_op = true;
6889 /* IS NULL is like = for selectivity purposes */
6890 eqQualHere = true;
6893 else
6894 elog(ERROR, "unsupported indexqual type: %d",
6895 (int) nodeTag(clause));
6897 /* check for equality operator */
6898 if (OidIsValid(clause_op))
6900 op_strategy = get_op_opfamily_strategy(clause_op,
6901 index->opfamily[indexcol]);
6902 Assert(op_strategy != 0); /* not a member of opfamily?? */
6903 if (op_strategy == BTEqualStrategyNumber)
6904 eqQualHere = true;
6907 indexBoundQuals = lappend(indexBoundQuals, rinfo);
6912 * If index is unique and we found an '=' clause for each column, we can
6913 * just assume numIndexTuples = 1 and skip the expensive
6914 * clauselist_selectivity calculations. However, a ScalarArrayOp or
6915 * NullTest invalidates that theory, even though it sets eqQualHere.
6917 if (index->unique &&
6918 indexcol == index->nkeycolumns - 1 &&
6919 eqQualHere &&
6920 !found_saop &&
6921 !found_is_null_op)
6922 numIndexTuples = 1.0;
6923 else
6925 List *selectivityQuals;
6926 Selectivity btreeSelectivity;
6929 * If the index is partial, AND the index predicate with the
6930 * index-bound quals to produce a more accurate idea of the number of
6931 * rows covered by the bound conditions.
6933 selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6935 btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6936 index->rel->relid,
6937 JOIN_INNER,
6938 NULL);
6939 numIndexTuples = btreeSelectivity * index->rel->tuples;
6942 * btree automatically combines individual ScalarArrayOpExpr primitive
6943 * index scans whenever the tuples covered by the next set of array
6944 * keys are close to tuples covered by the current set. That puts a
6945 * natural ceiling on the worst case number of descents -- there
6946 * cannot possibly be more than one descent per leaf page scanned.
6948 * Clamp the number of descents to at most 1/3 the number of index
6949 * pages. This avoids implausibly high estimates with low selectivity
6950 * paths, where scans usually require only one or two descents. This
6951 * is most likely to help when there are several SAOP clauses, where
6952 * naively accepting the total number of distinct combinations of
6953 * array elements as the number of descents would frequently lead to
6954 * wild overestimates.
6956 * We somewhat arbitrarily don't just make the cutoff the total number
6957 * of leaf pages (we make it 1/3 the total number of pages instead) to
6958 * give the btree code credit for its ability to continue on the leaf
6959 * level with low selectivity scans.
6961 num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
6962 num_sa_scans = Max(num_sa_scans, 1);
6965 * As in genericcostestimate(), we have to adjust for any
6966 * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6967 * to integer.
6969 * It is tempting to make genericcostestimate behave as if SAOP
6970 * clauses work in almost the same way as scalar operators during
6971 * btree scans, making the top-level scan look like a continuous scan
6972 * (as opposed to num_sa_scans-many primitive index scans). After
6973 * all, btree scans mostly work like that at runtime. However, such a
6974 * scheme would badly bias genericcostestimate's simplistic approach
6975 * to calculating numIndexPages through prorating.
6977 * Stick with the approach taken by non-native SAOP scans for now.
6978 * genericcostestimate will use the Mackert-Lohman formula to
6979 * compensate for repeat page fetches, even though that definitely
6980 * won't happen during btree scans (not for leaf pages, at least).
6981 * We're usually very pessimistic about the number of primitive index
6982 * scans that will be required, but it's not clear how to do better.
6984 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6988 * Now do generic index cost estimation.
6990 costs.numIndexTuples = numIndexTuples;
6991 costs.num_sa_scans = num_sa_scans;
6993 genericcostestimate(root, path, loop_count, &costs);
6996 * Add a CPU-cost component to represent the costs of initial btree
6997 * descent. We don't charge any I/O cost for touching upper btree levels,
6998 * since they tend to stay in cache, but we still have to do about log2(N)
6999 * comparisons to descend a btree of N leaf tuples. We charge one
7000 * cpu_operator_cost per comparison.
7002 * If there are ScalarArrayOpExprs, charge this once per estimated SA
7003 * index descent. The ones after the first one are not startup cost so
7004 * far as the overall plan goes, so just add them to "total" cost.
7006 if (index->tuples > 1) /* avoid computing log(0) */
7008 descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
7009 costs.indexStartupCost += descentCost;
7010 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7014 * Even though we're not charging I/O cost for touching upper btree pages,
7015 * it's still reasonable to charge some CPU cost per page descended
7016 * through. Moreover, if we had no such charge at all, bloated indexes
7017 * would appear to have the same search cost as unbloated ones, at least
7018 * in cases where only a single leaf page is expected to be visited. This
7019 * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
7020 * touched. The number of such pages is btree tree height plus one (ie,
7021 * we charge for the leaf page too). As above, charge once per estimated
7022 * SA index descent.
7024 descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7025 costs.indexStartupCost += descentCost;
7026 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7029 * If we can get an estimate of the first column's ordering correlation C
7030 * from pg_statistic, estimate the index correlation as C for a
7031 * single-column index, or C * 0.75 for multiple columns. (The idea here
7032 * is that multiple columns dilute the importance of the first column's
7033 * ordering, but don't negate it entirely. Before 8.0 we divided the
7034 * correlation by the number of columns, but that seems too strong.)
7036 if (index->indexkeys[0] != 0)
7038 /* Simple variable --- look to stats for the underlying table */
7039 RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
7041 Assert(rte->rtekind == RTE_RELATION);
7042 relid = rte->relid;
7043 Assert(relid != InvalidOid);
7044 colnum = index->indexkeys[0];
7046 if (get_relation_stats_hook &&
7047 (*get_relation_stats_hook) (root, rte, colnum, &vardata))
7050 * The hook took control of acquiring a stats tuple. If it did
7051 * supply a tuple, it'd better have supplied a freefunc.
7053 if (HeapTupleIsValid(vardata.statsTuple) &&
7054 !vardata.freefunc)
7055 elog(ERROR, "no function provided to release variable stats with");
7057 else
7059 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7060 ObjectIdGetDatum(relid),
7061 Int16GetDatum(colnum),
7062 BoolGetDatum(rte->inh));
7063 vardata.freefunc = ReleaseSysCache;
7066 else
7068 /* Expression --- maybe there are stats for the index itself */
7069 relid = index->indexoid;
7070 colnum = 1;
7072 if (get_index_stats_hook &&
7073 (*get_index_stats_hook) (root, relid, colnum, &vardata))
7076 * The hook took control of acquiring a stats tuple. If it did
7077 * supply a tuple, it'd better have supplied a freefunc.
7079 if (HeapTupleIsValid(vardata.statsTuple) &&
7080 !vardata.freefunc)
7081 elog(ERROR, "no function provided to release variable stats with");
7083 else
7085 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7086 ObjectIdGetDatum(relid),
7087 Int16GetDatum(colnum),
7088 BoolGetDatum(false));
7089 vardata.freefunc = ReleaseSysCache;
7093 if (HeapTupleIsValid(vardata.statsTuple))
7095 Oid sortop;
7096 AttStatsSlot sslot;
7098 sortop = get_opfamily_member(index->opfamily[0],
7099 index->opcintype[0],
7100 index->opcintype[0],
7101 BTLessStrategyNumber);
7102 if (OidIsValid(sortop) &&
7103 get_attstatsslot(&sslot, vardata.statsTuple,
7104 STATISTIC_KIND_CORRELATION, sortop,
7105 ATTSTATSSLOT_NUMBERS))
7107 double varCorrelation;
7109 Assert(sslot.nnumbers == 1);
7110 varCorrelation = sslot.numbers[0];
7112 if (index->reverse_sort[0])
7113 varCorrelation = -varCorrelation;
7115 if (index->nkeycolumns > 1)
7116 costs.indexCorrelation = varCorrelation * 0.75;
7117 else
7118 costs.indexCorrelation = varCorrelation;
7120 free_attstatsslot(&sslot);
7124 ReleaseVariableStats(vardata);
7126 *indexStartupCost = costs.indexStartupCost;
7127 *indexTotalCost = costs.indexTotalCost;
7128 *indexSelectivity = costs.indexSelectivity;
7129 *indexCorrelation = costs.indexCorrelation;
7130 *indexPages = costs.numIndexPages;
7133 void
7134 hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7135 Cost *indexStartupCost, Cost *indexTotalCost,
7136 Selectivity *indexSelectivity, double *indexCorrelation,
7137 double *indexPages)
7139 GenericCosts costs = {0};
7141 genericcostestimate(root, path, loop_count, &costs);
7144 * A hash index has no descent costs as such, since the index AM can go
7145 * directly to the target bucket after computing the hash value. There
7146 * are a couple of other hash-specific costs that we could conceivably add
7147 * here, though:
7149 * Ideally we'd charge spc_random_page_cost for each page in the target
7150 * bucket, not just the numIndexPages pages that genericcostestimate
7151 * thought we'd visit. However in most cases we don't know which bucket
7152 * that will be. There's no point in considering the average bucket size
7153 * because the hash AM makes sure that's always one page.
7155 * Likewise, we could consider charging some CPU for each index tuple in
7156 * the bucket, if we knew how many there were. But the per-tuple cost is
7157 * just a hash value comparison, not a general datatype-dependent
7158 * comparison, so any such charge ought to be quite a bit less than
7159 * cpu_operator_cost; which makes it probably not worth worrying about.
7161 * A bigger issue is that chance hash-value collisions will result in
7162 * wasted probes into the heap. We don't currently attempt to model this
7163 * cost on the grounds that it's rare, but maybe it's not rare enough.
7164 * (Any fix for this ought to consider the generic lossy-operator problem,
7165 * though; it's not entirely hash-specific.)
7168 *indexStartupCost = costs.indexStartupCost;
7169 *indexTotalCost = costs.indexTotalCost;
7170 *indexSelectivity = costs.indexSelectivity;
7171 *indexCorrelation = costs.indexCorrelation;
7172 *indexPages = costs.numIndexPages;
7175 void
7176 gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7177 Cost *indexStartupCost, Cost *indexTotalCost,
7178 Selectivity *indexSelectivity, double *indexCorrelation,
7179 double *indexPages)
7181 IndexOptInfo *index = path->indexinfo;
7182 GenericCosts costs = {0};
7183 Cost descentCost;
7185 genericcostestimate(root, path, loop_count, &costs);
7188 * We model index descent costs similarly to those for btree, but to do
7189 * that we first need an idea of the tree height. We somewhat arbitrarily
7190 * assume that the fanout is 100, meaning the tree height is at most
7191 * log100(index->pages).
7193 * Although this computation isn't really expensive enough to require
7194 * caching, we might as well use index->tree_height to cache it.
7196 if (index->tree_height < 0) /* unknown? */
7198 if (index->pages > 1) /* avoid computing log(0) */
7199 index->tree_height = (int) (log(index->pages) / log(100.0));
7200 else
7201 index->tree_height = 0;
7205 * Add a CPU-cost component to represent the costs of initial descent. We
7206 * just use log(N) here not log2(N) since the branching factor isn't
7207 * necessarily two anyway. As for btree, charge once per SA scan.
7209 if (index->tuples > 1) /* avoid computing log(0) */
7211 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7212 costs.indexStartupCost += descentCost;
7213 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7217 * Likewise add a per-page charge, calculated the same as for btrees.
7219 descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7220 costs.indexStartupCost += descentCost;
7221 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7223 *indexStartupCost = costs.indexStartupCost;
7224 *indexTotalCost = costs.indexTotalCost;
7225 *indexSelectivity = costs.indexSelectivity;
7226 *indexCorrelation = costs.indexCorrelation;
7227 *indexPages = costs.numIndexPages;
7230 void
7231 spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7232 Cost *indexStartupCost, Cost *indexTotalCost,
7233 Selectivity *indexSelectivity, double *indexCorrelation,
7234 double *indexPages)
7236 IndexOptInfo *index = path->indexinfo;
7237 GenericCosts costs = {0};
7238 Cost descentCost;
7240 genericcostestimate(root, path, loop_count, &costs);
7243 * We model index descent costs similarly to those for btree, but to do
7244 * that we first need an idea of the tree height. We somewhat arbitrarily
7245 * assume that the fanout is 100, meaning the tree height is at most
7246 * log100(index->pages).
7248 * Although this computation isn't really expensive enough to require
7249 * caching, we might as well use index->tree_height to cache it.
7251 if (index->tree_height < 0) /* unknown? */
7253 if (index->pages > 1) /* avoid computing log(0) */
7254 index->tree_height = (int) (log(index->pages) / log(100.0));
7255 else
7256 index->tree_height = 0;
7260 * Add a CPU-cost component to represent the costs of initial descent. We
7261 * just use log(N) here not log2(N) since the branching factor isn't
7262 * necessarily two anyway. As for btree, charge once per SA scan.
7264 if (index->tuples > 1) /* avoid computing log(0) */
7266 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7267 costs.indexStartupCost += descentCost;
7268 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7272 * Likewise add a per-page charge, calculated the same as for btrees.
7274 descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7275 costs.indexStartupCost += descentCost;
7276 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7278 *indexStartupCost = costs.indexStartupCost;
7279 *indexTotalCost = costs.indexTotalCost;
7280 *indexSelectivity = costs.indexSelectivity;
7281 *indexCorrelation = costs.indexCorrelation;
7282 *indexPages = costs.numIndexPages;
7287 * Support routines for gincostestimate
7290 typedef struct
7292 bool attHasFullScan[INDEX_MAX_KEYS];
7293 bool attHasNormalScan[INDEX_MAX_KEYS];
7294 double partialEntries;
7295 double exactEntries;
7296 double searchEntries;
7297 double arrayScans;
7298 } GinQualCounts;
7301 * Estimate the number of index terms that need to be searched for while
7302 * testing the given GIN query, and increment the counts in *counts
7303 * appropriately. If the query is unsatisfiable, return false.
7305 static bool
7306 gincost_pattern(IndexOptInfo *index, int indexcol,
7307 Oid clause_op, Datum query,
7308 GinQualCounts *counts)
7310 FmgrInfo flinfo;
7311 Oid extractProcOid;
7312 Oid collation;
7313 int strategy_op;
7314 Oid lefttype,
7315 righttype;
7316 int32 nentries = 0;
7317 bool *partial_matches = NULL;
7318 Pointer *extra_data = NULL;
7319 bool *nullFlags = NULL;
7320 int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
7321 int32 i;
7323 Assert(indexcol < index->nkeycolumns);
7326 * Get the operator's strategy number and declared input data types within
7327 * the index opfamily. (We don't need the latter, but we use
7328 * get_op_opfamily_properties because it will throw error if it fails to
7329 * find a matching pg_amop entry.)
7331 get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
7332 &strategy_op, &lefttype, &righttype);
7335 * GIN always uses the "default" support functions, which are those with
7336 * lefttype == righttype == the opclass' opcintype (see
7337 * IndexSupportInitialize in relcache.c).
7339 extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
7340 index->opcintype[indexcol],
7341 index->opcintype[indexcol],
7342 GIN_EXTRACTQUERY_PROC);
7344 if (!OidIsValid(extractProcOid))
7346 /* should not happen; throw same error as index_getprocinfo */
7347 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
7348 GIN_EXTRACTQUERY_PROC, indexcol + 1,
7349 get_rel_name(index->indexoid));
7353 * Choose collation to pass to extractProc (should match initGinState).
7355 if (OidIsValid(index->indexcollations[indexcol]))
7356 collation = index->indexcollations[indexcol];
7357 else
7358 collation = DEFAULT_COLLATION_OID;
7360 fmgr_info(extractProcOid, &flinfo);
7362 set_fn_opclass_options(&flinfo, index->opclassoptions[indexcol]);
7364 FunctionCall7Coll(&flinfo,
7365 collation,
7366 query,
7367 PointerGetDatum(&nentries),
7368 UInt16GetDatum(strategy_op),
7369 PointerGetDatum(&partial_matches),
7370 PointerGetDatum(&extra_data),
7371 PointerGetDatum(&nullFlags),
7372 PointerGetDatum(&searchMode));
7374 if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
7376 /* No match is possible */
7377 return false;
7380 for (i = 0; i < nentries; i++)
7383 * For partial match we haven't any information to estimate number of
7384 * matched entries in index, so, we just estimate it as 100
7386 if (partial_matches && partial_matches[i])
7387 counts->partialEntries += 100;
7388 else
7389 counts->exactEntries++;
7391 counts->searchEntries++;
7394 if (searchMode == GIN_SEARCH_MODE_DEFAULT)
7396 counts->attHasNormalScan[indexcol] = true;
7398 else if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
7400 /* Treat "include empty" like an exact-match item */
7401 counts->attHasNormalScan[indexcol] = true;
7402 counts->exactEntries++;
7403 counts->searchEntries++;
7405 else
7407 /* It's GIN_SEARCH_MODE_ALL */
7408 counts->attHasFullScan[indexcol] = true;
7411 return true;
7415 * Estimate the number of index terms that need to be searched for while
7416 * testing the given GIN index clause, and increment the counts in *counts
7417 * appropriately. If the query is unsatisfiable, return false.
7419 static bool
7420 gincost_opexpr(PlannerInfo *root,
7421 IndexOptInfo *index,
7422 int indexcol,
7423 OpExpr *clause,
7424 GinQualCounts *counts)
7426 Oid clause_op = clause->opno;
7427 Node *operand = (Node *) lsecond(clause->args);
7429 /* aggressively reduce to a constant, and look through relabeling */
7430 operand = estimate_expression_value(root, operand);
7432 if (IsA(operand, RelabelType))
7433 operand = (Node *) ((RelabelType *) operand)->arg;
7436 * It's impossible to call extractQuery method for unknown operand. So
7437 * unless operand is a Const we can't do much; just assume there will be
7438 * one ordinary search entry from the operand at runtime.
7440 if (!IsA(operand, Const))
7442 counts->exactEntries++;
7443 counts->searchEntries++;
7444 return true;
7447 /* If Const is null, there can be no matches */
7448 if (((Const *) operand)->constisnull)
7449 return false;
7451 /* Otherwise, apply extractQuery and get the actual term counts */
7452 return gincost_pattern(index, indexcol, clause_op,
7453 ((Const *) operand)->constvalue,
7454 counts);
7458 * Estimate the number of index terms that need to be searched for while
7459 * testing the given GIN index clause, and increment the counts in *counts
7460 * appropriately. If the query is unsatisfiable, return false.
7462 * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
7463 * each of which involves one value from the RHS array, plus all the
7464 * non-array quals (if any). To model this, we average the counts across
7465 * the RHS elements, and add the averages to the counts in *counts (which
7466 * correspond to per-indexscan costs). We also multiply counts->arrayScans
7467 * by N, causing gincostestimate to scale up its estimates accordingly.
7469 static bool
7470 gincost_scalararrayopexpr(PlannerInfo *root,
7471 IndexOptInfo *index,
7472 int indexcol,
7473 ScalarArrayOpExpr *clause,
7474 double numIndexEntries,
7475 GinQualCounts *counts)
7477 Oid clause_op = clause->opno;
7478 Node *rightop = (Node *) lsecond(clause->args);
7479 ArrayType *arrayval;
7480 int16 elmlen;
7481 bool elmbyval;
7482 char elmalign;
7483 int numElems;
7484 Datum *elemValues;
7485 bool *elemNulls;
7486 GinQualCounts arraycounts;
7487 int numPossible = 0;
7488 int i;
7490 Assert(clause->useOr);
7492 /* aggressively reduce to a constant, and look through relabeling */
7493 rightop = estimate_expression_value(root, rightop);
7495 if (IsA(rightop, RelabelType))
7496 rightop = (Node *) ((RelabelType *) rightop)->arg;
7499 * It's impossible to call extractQuery method for unknown operand. So
7500 * unless operand is a Const we can't do much; just assume there will be
7501 * one ordinary search entry from each array entry at runtime, and fall
7502 * back on a probably-bad estimate of the number of array entries.
7504 if (!IsA(rightop, Const))
7506 counts->exactEntries++;
7507 counts->searchEntries++;
7508 counts->arrayScans *= estimate_array_length(root, rightop);
7509 return true;
7512 /* If Const is null, there can be no matches */
7513 if (((Const *) rightop)->constisnull)
7514 return false;
7516 /* Otherwise, extract the array elements and iterate over them */
7517 arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
7518 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
7519 &elmlen, &elmbyval, &elmalign);
7520 deconstruct_array(arrayval,
7521 ARR_ELEMTYPE(arrayval),
7522 elmlen, elmbyval, elmalign,
7523 &elemValues, &elemNulls, &numElems);
7525 memset(&arraycounts, 0, sizeof(arraycounts));
7527 for (i = 0; i < numElems; i++)
7529 GinQualCounts elemcounts;
7531 /* NULL can't match anything, so ignore, as the executor will */
7532 if (elemNulls[i])
7533 continue;
7535 /* Otherwise, apply extractQuery and get the actual term counts */
7536 memset(&elemcounts, 0, sizeof(elemcounts));
7538 if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
7539 &elemcounts))
7541 /* We ignore array elements that are unsatisfiable patterns */
7542 numPossible++;
7544 if (elemcounts.attHasFullScan[indexcol] &&
7545 !elemcounts.attHasNormalScan[indexcol])
7548 * Full index scan will be required. We treat this as if
7549 * every key in the index had been listed in the query; is
7550 * that reasonable?
7552 elemcounts.partialEntries = 0;
7553 elemcounts.exactEntries = numIndexEntries;
7554 elemcounts.searchEntries = numIndexEntries;
7556 arraycounts.partialEntries += elemcounts.partialEntries;
7557 arraycounts.exactEntries += elemcounts.exactEntries;
7558 arraycounts.searchEntries += elemcounts.searchEntries;
7562 if (numPossible == 0)
7564 /* No satisfiable patterns in the array */
7565 return false;
7569 * Now add the averages to the global counts. This will give us an
7570 * estimate of the average number of terms searched for in each indexscan,
7571 * including contributions from both array and non-array quals.
7573 counts->partialEntries += arraycounts.partialEntries / numPossible;
7574 counts->exactEntries += arraycounts.exactEntries / numPossible;
7575 counts->searchEntries += arraycounts.searchEntries / numPossible;
7577 counts->arrayScans *= numPossible;
7579 return true;
7583 * GIN has search behavior completely different from other index types
7585 void
7586 gincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7587 Cost *indexStartupCost, Cost *indexTotalCost,
7588 Selectivity *indexSelectivity, double *indexCorrelation,
7589 double *indexPages)
7591 IndexOptInfo *index = path->indexinfo;
7592 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7593 List *selectivityQuals;
7594 double numPages = index->pages,
7595 numTuples = index->tuples;
7596 double numEntryPages,
7597 numDataPages,
7598 numPendingPages,
7599 numEntries;
7600 GinQualCounts counts;
7601 bool matchPossible;
7602 bool fullIndexScan;
7603 double partialScale;
7604 double entryPagesFetched,
7605 dataPagesFetched,
7606 dataPagesFetchedBySel;
7607 double qual_op_cost,
7608 qual_arg_cost,
7609 spc_random_page_cost,
7610 outer_scans;
7611 Cost descentCost;
7612 Relation indexRel;
7613 GinStatsData ginStats;
7614 ListCell *lc;
7615 int i;
7618 * Obtain statistical information from the meta page, if possible. Else
7619 * set ginStats to zeroes, and we'll cope below.
7621 if (!index->hypothetical)
7623 /* Lock should have already been obtained in plancat.c */
7624 indexRel = index_open(index->indexoid, NoLock);
7625 ginGetStats(indexRel, &ginStats);
7626 index_close(indexRel, NoLock);
7628 else
7630 memset(&ginStats, 0, sizeof(ginStats));
7634 * Assuming we got valid (nonzero) stats at all, nPendingPages can be
7635 * trusted, but the other fields are data as of the last VACUUM. We can
7636 * scale them up to account for growth since then, but that method only
7637 * goes so far; in the worst case, the stats might be for a completely
7638 * empty index, and scaling them will produce pretty bogus numbers.
7639 * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
7640 * it's grown more than that, fall back to estimating things only from the
7641 * assumed-accurate index size. But we'll trust nPendingPages in any case
7642 * so long as it's not clearly insane, ie, more than the index size.
7644 if (ginStats.nPendingPages < numPages)
7645 numPendingPages = ginStats.nPendingPages;
7646 else
7647 numPendingPages = 0;
7649 if (numPages > 0 && ginStats.nTotalPages <= numPages &&
7650 ginStats.nTotalPages > numPages / 4 &&
7651 ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
7654 * OK, the stats seem close enough to sane to be trusted. But we
7655 * still need to scale them by the ratio numPages / nTotalPages to
7656 * account for growth since the last VACUUM.
7658 double scale = numPages / ginStats.nTotalPages;
7660 numEntryPages = ceil(ginStats.nEntryPages * scale);
7661 numDataPages = ceil(ginStats.nDataPages * scale);
7662 numEntries = ceil(ginStats.nEntries * scale);
7663 /* ensure we didn't round up too much */
7664 numEntryPages = Min(numEntryPages, numPages - numPendingPages);
7665 numDataPages = Min(numDataPages,
7666 numPages - numPendingPages - numEntryPages);
7668 else
7671 * We might get here because it's a hypothetical index, or an index
7672 * created pre-9.1 and never vacuumed since upgrading (in which case
7673 * its stats would read as zeroes), or just because it's grown too
7674 * much since the last VACUUM for us to put our faith in scaling.
7676 * Invent some plausible internal statistics based on the index page
7677 * count (and clamp that to at least 10 pages, just in case). We
7678 * estimate that 90% of the index is entry pages, and the rest is data
7679 * pages. Estimate 100 entries per entry page; this is rather bogus
7680 * since it'll depend on the size of the keys, but it's more robust
7681 * than trying to predict the number of entries per heap tuple.
7683 numPages = Max(numPages, 10);
7684 numEntryPages = floor((numPages - numPendingPages) * 0.90);
7685 numDataPages = numPages - numPendingPages - numEntryPages;
7686 numEntries = floor(numEntryPages * 100);
7689 /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
7690 if (numEntries < 1)
7691 numEntries = 1;
7694 * If the index is partial, AND the index predicate with the index-bound
7695 * quals to produce a more accurate idea of the number of rows covered by
7696 * the bound conditions.
7698 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7700 /* Estimate the fraction of main-table tuples that will be visited */
7701 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7702 index->rel->relid,
7703 JOIN_INNER,
7704 NULL);
7706 /* fetch estimated page cost for tablespace containing index */
7707 get_tablespace_page_costs(index->reltablespace,
7708 &spc_random_page_cost,
7709 NULL);
7712 * Generic assumption about index correlation: there isn't any.
7714 *indexCorrelation = 0.0;
7717 * Examine quals to estimate number of search entries & partial matches
7719 memset(&counts, 0, sizeof(counts));
7720 counts.arrayScans = 1;
7721 matchPossible = true;
7723 foreach(lc, path->indexclauses)
7725 IndexClause *iclause = lfirst_node(IndexClause, lc);
7726 ListCell *lc2;
7728 foreach(lc2, iclause->indexquals)
7730 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7731 Expr *clause = rinfo->clause;
7733 if (IsA(clause, OpExpr))
7735 matchPossible = gincost_opexpr(root,
7736 index,
7737 iclause->indexcol,
7738 (OpExpr *) clause,
7739 &counts);
7740 if (!matchPossible)
7741 break;
7743 else if (IsA(clause, ScalarArrayOpExpr))
7745 matchPossible = gincost_scalararrayopexpr(root,
7746 index,
7747 iclause->indexcol,
7748 (ScalarArrayOpExpr *) clause,
7749 numEntries,
7750 &counts);
7751 if (!matchPossible)
7752 break;
7754 else
7756 /* shouldn't be anything else for a GIN index */
7757 elog(ERROR, "unsupported GIN indexqual type: %d",
7758 (int) nodeTag(clause));
7763 /* Fall out if there were any provably-unsatisfiable quals */
7764 if (!matchPossible)
7766 *indexStartupCost = 0;
7767 *indexTotalCost = 0;
7768 *indexSelectivity = 0;
7769 return;
7773 * If attribute has a full scan and at the same time doesn't have normal
7774 * scan, then we'll have to scan all non-null entries of that attribute.
7775 * Currently, we don't have per-attribute statistics for GIN. Thus, we
7776 * must assume the whole GIN index has to be scanned in this case.
7778 fullIndexScan = false;
7779 for (i = 0; i < index->nkeycolumns; i++)
7781 if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
7783 fullIndexScan = true;
7784 break;
7788 if (fullIndexScan || indexQuals == NIL)
7791 * Full index scan will be required. We treat this as if every key in
7792 * the index had been listed in the query; is that reasonable?
7794 counts.partialEntries = 0;
7795 counts.exactEntries = numEntries;
7796 counts.searchEntries = numEntries;
7799 /* Will we have more than one iteration of a nestloop scan? */
7800 outer_scans = loop_count;
7803 * Compute cost to begin scan, first of all, pay attention to pending
7804 * list.
7806 entryPagesFetched = numPendingPages;
7809 * Estimate number of entry pages read. We need to do
7810 * counts.searchEntries searches. Use a power function as it should be,
7811 * but tuples on leaf pages usually is much greater. Here we include all
7812 * searches in entry tree, including search of first entry in partial
7813 * match algorithm
7815 entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
7818 * Add an estimate of entry pages read by partial match algorithm. It's a
7819 * scan over leaf pages in entry tree. We haven't any useful stats here,
7820 * so estimate it as proportion. Because counts.partialEntries is really
7821 * pretty bogus (see code above), it's possible that it is more than
7822 * numEntries; clamp the proportion to ensure sanity.
7824 partialScale = counts.partialEntries / numEntries;
7825 partialScale = Min(partialScale, 1.0);
7827 entryPagesFetched += ceil(numEntryPages * partialScale);
7830 * Partial match algorithm reads all data pages before doing actual scan,
7831 * so it's a startup cost. Again, we haven't any useful stats here, so
7832 * estimate it as proportion.
7834 dataPagesFetched = ceil(numDataPages * partialScale);
7836 *indexStartupCost = 0;
7837 *indexTotalCost = 0;
7840 * Add a CPU-cost component to represent the costs of initial entry btree
7841 * descent. We don't charge any I/O cost for touching upper btree levels,
7842 * since they tend to stay in cache, but we still have to do about log2(N)
7843 * comparisons to descend a btree of N leaf tuples. We charge one
7844 * cpu_operator_cost per comparison.
7846 * If there are ScalarArrayOpExprs, charge this once per SA scan. The
7847 * ones after the first one are not startup cost so far as the overall
7848 * plan is concerned, so add them only to "total" cost.
7850 if (numEntries > 1) /* avoid computing log(0) */
7852 descentCost = ceil(log(numEntries) / log(2.0)) * cpu_operator_cost;
7853 *indexStartupCost += descentCost * counts.searchEntries;
7854 *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
7858 * Add a cpu cost per entry-page fetched. This is not amortized over a
7859 * loop.
7861 *indexStartupCost += entryPagesFetched * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7862 *indexTotalCost += entryPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7865 * Add a cpu cost per data-page fetched. This is also not amortized over a
7866 * loop. Since those are the data pages from the partial match algorithm,
7867 * charge them as startup cost.
7869 *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * dataPagesFetched;
7872 * Since we add the startup cost to the total cost later on, remove the
7873 * initial arrayscan from the total.
7875 *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7878 * Calculate cache effects if more than one scan due to nestloops or array
7879 * quals. The result is pro-rated per nestloop scan, but the array qual
7880 * factor shouldn't be pro-rated (compare genericcostestimate).
7882 if (outer_scans > 1 || counts.arrayScans > 1)
7884 entryPagesFetched *= outer_scans * counts.arrayScans;
7885 entryPagesFetched = index_pages_fetched(entryPagesFetched,
7886 (BlockNumber) numEntryPages,
7887 numEntryPages, root);
7888 entryPagesFetched /= outer_scans;
7889 dataPagesFetched *= outer_scans * counts.arrayScans;
7890 dataPagesFetched = index_pages_fetched(dataPagesFetched,
7891 (BlockNumber) numDataPages,
7892 numDataPages, root);
7893 dataPagesFetched /= outer_scans;
7897 * Here we use random page cost because logically-close pages could be far
7898 * apart on disk.
7900 *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
7903 * Now compute the number of data pages fetched during the scan.
7905 * We assume every entry to have the same number of items, and that there
7906 * is no overlap between them. (XXX: tsvector and array opclasses collect
7907 * statistics on the frequency of individual keys; it would be nice to use
7908 * those here.)
7910 dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
7913 * If there is a lot of overlap among the entries, in particular if one of
7914 * the entries is very frequent, the above calculation can grossly
7915 * under-estimate. As a simple cross-check, calculate a lower bound based
7916 * on the overall selectivity of the quals. At a minimum, we must read
7917 * one item pointer for each matching entry.
7919 * The width of each item pointer varies, based on the level of
7920 * compression. We don't have statistics on that, but an average of
7921 * around 3 bytes per item is fairly typical.
7923 dataPagesFetchedBySel = ceil(*indexSelectivity *
7924 (numTuples / (BLCKSZ / 3)));
7925 if (dataPagesFetchedBySel > dataPagesFetched)
7926 dataPagesFetched = dataPagesFetchedBySel;
7928 /* Add one page cpu-cost to the startup cost */
7929 *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
7932 * Add once again a CPU-cost for those data pages, before amortizing for
7933 * cache.
7935 *indexTotalCost += dataPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7937 /* Account for cache effects, the same as above */
7938 if (outer_scans > 1 || counts.arrayScans > 1)
7940 dataPagesFetched *= outer_scans * counts.arrayScans;
7941 dataPagesFetched = index_pages_fetched(dataPagesFetched,
7942 (BlockNumber) numDataPages,
7943 numDataPages, root);
7944 dataPagesFetched /= outer_scans;
7947 /* And apply random_page_cost as the cost per page */
7948 *indexTotalCost += *indexStartupCost +
7949 dataPagesFetched * spc_random_page_cost;
7952 * Add on index qual eval costs, much as in genericcostestimate. We charge
7953 * cpu but we can disregard indexorderbys, since GIN doesn't support
7954 * those.
7956 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7957 qual_op_cost = cpu_operator_cost * list_length(indexQuals);
7959 *indexStartupCost += qual_arg_cost;
7960 *indexTotalCost += qual_arg_cost;
7963 * Add a cpu cost per search entry, corresponding to the actual visited
7964 * entries.
7966 *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
7967 /* Now add a cpu cost per tuple in the posting lists / trees */
7968 *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
7969 *indexPages = dataPagesFetched;
7973 * BRIN has search behavior completely different from other index types
7975 void
7976 brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7977 Cost *indexStartupCost, Cost *indexTotalCost,
7978 Selectivity *indexSelectivity, double *indexCorrelation,
7979 double *indexPages)
7981 IndexOptInfo *index = path->indexinfo;
7982 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7983 double numPages = index->pages;
7984 RelOptInfo *baserel = index->rel;
7985 RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7986 Cost spc_seq_page_cost;
7987 Cost spc_random_page_cost;
7988 double qual_arg_cost;
7989 double qualSelectivity;
7990 BrinStatsData statsData;
7991 double indexRanges;
7992 double minimalRanges;
7993 double estimatedRanges;
7994 double selec;
7995 Relation indexRel;
7996 ListCell *l;
7997 VariableStatData vardata;
7999 Assert(rte->rtekind == RTE_RELATION);
8001 /* fetch estimated page cost for the tablespace containing the index */
8002 get_tablespace_page_costs(index->reltablespace,
8003 &spc_random_page_cost,
8004 &spc_seq_page_cost);
8007 * Obtain some data from the index itself, if possible. Otherwise invent
8008 * some plausible internal statistics based on the relation page count.
8010 if (!index->hypothetical)
8013 * A lock should have already been obtained on the index in plancat.c.
8015 indexRel = index_open(index->indexoid, NoLock);
8016 brinGetStats(indexRel, &statsData);
8017 index_close(indexRel, NoLock);
8019 /* work out the actual number of ranges in the index */
8020 indexRanges = Max(ceil((double) baserel->pages /
8021 statsData.pagesPerRange), 1.0);
8023 else
8026 * Assume default number of pages per range, and estimate the number
8027 * of ranges based on that.
8029 indexRanges = Max(ceil((double) baserel->pages /
8030 BRIN_DEFAULT_PAGES_PER_RANGE), 1.0);
8032 statsData.pagesPerRange = BRIN_DEFAULT_PAGES_PER_RANGE;
8033 statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
8037 * Compute index correlation
8039 * Because we can use all index quals equally when scanning, we can use
8040 * the largest correlation (in absolute value) among columns used by the
8041 * query. Start at zero, the worst possible case. If we cannot find any
8042 * correlation statistics, we will keep it as 0.
8044 *indexCorrelation = 0;
8046 foreach(l, path->indexclauses)
8048 IndexClause *iclause = lfirst_node(IndexClause, l);
8049 AttrNumber attnum = index->indexkeys[iclause->indexcol];
8051 /* attempt to lookup stats in relation for this index column */
8052 if (attnum != 0)
8054 /* Simple variable -- look to stats for the underlying table */
8055 if (get_relation_stats_hook &&
8056 (*get_relation_stats_hook) (root, rte, attnum, &vardata))
8059 * The hook took control of acquiring a stats tuple. If it
8060 * did supply a tuple, it'd better have supplied a freefunc.
8062 if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
8063 elog(ERROR,
8064 "no function provided to release variable stats with");
8066 else
8068 vardata.statsTuple =
8069 SearchSysCache3(STATRELATTINH,
8070 ObjectIdGetDatum(rte->relid),
8071 Int16GetDatum(attnum),
8072 BoolGetDatum(false));
8073 vardata.freefunc = ReleaseSysCache;
8076 else
8079 * Looks like we've found an expression column in the index. Let's
8080 * see if there's any stats for it.
8083 /* get the attnum from the 0-based index. */
8084 attnum = iclause->indexcol + 1;
8086 if (get_index_stats_hook &&
8087 (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
8090 * The hook took control of acquiring a stats tuple. If it
8091 * did supply a tuple, it'd better have supplied a freefunc.
8093 if (HeapTupleIsValid(vardata.statsTuple) &&
8094 !vardata.freefunc)
8095 elog(ERROR, "no function provided to release variable stats with");
8097 else
8099 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
8100 ObjectIdGetDatum(index->indexoid),
8101 Int16GetDatum(attnum),
8102 BoolGetDatum(false));
8103 vardata.freefunc = ReleaseSysCache;
8107 if (HeapTupleIsValid(vardata.statsTuple))
8109 AttStatsSlot sslot;
8111 if (get_attstatsslot(&sslot, vardata.statsTuple,
8112 STATISTIC_KIND_CORRELATION, InvalidOid,
8113 ATTSTATSSLOT_NUMBERS))
8115 double varCorrelation = 0.0;
8117 if (sslot.nnumbers > 0)
8118 varCorrelation = fabs(sslot.numbers[0]);
8120 if (varCorrelation > *indexCorrelation)
8121 *indexCorrelation = varCorrelation;
8123 free_attstatsslot(&sslot);
8127 ReleaseVariableStats(vardata);
8130 qualSelectivity = clauselist_selectivity(root, indexQuals,
8131 baserel->relid,
8132 JOIN_INNER, NULL);
8135 * Now calculate the minimum possible ranges we could match with if all of
8136 * the rows were in the perfect order in the table's heap.
8138 minimalRanges = ceil(indexRanges * qualSelectivity);
8141 * Now estimate the number of ranges that we'll touch by using the
8142 * indexCorrelation from the stats. Careful not to divide by zero (note
8143 * we're using the absolute value of the correlation).
8145 if (*indexCorrelation < 1.0e-10)
8146 estimatedRanges = indexRanges;
8147 else
8148 estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8150 /* we expect to visit this portion of the table */
8151 selec = estimatedRanges / indexRanges;
8153 CLAMP_PROBABILITY(selec);
8155 *indexSelectivity = selec;
8158 * Compute the index qual costs, much as in genericcostestimate, to add to
8159 * the index costs. We can disregard indexorderbys, since BRIN doesn't
8160 * support those.
8162 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
8165 * Compute the startup cost as the cost to read the whole revmap
8166 * sequentially, including the cost to execute the index quals.
8168 *indexStartupCost =
8169 spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8170 *indexStartupCost += qual_arg_cost;
8173 * To read a BRIN index there might be a bit of back and forth over
8174 * regular pages, as revmap might point to them out of sequential order;
8175 * calculate the total cost as reading the whole index in random order.
8177 *indexTotalCost = *indexStartupCost +
8178 spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8181 * Charge a small amount per range tuple which we expect to match to. This
8182 * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8183 * will set a bit for each page in the range when we find a matching
8184 * range, so we must multiply the charge by the number of pages in the
8185 * range.
8187 *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8188 statsData.pagesPerRange;
8190 *indexPages = index->pages;