Debian Codegraph @

src/backend/utils/adt/selfuncs.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * selfuncs.c
4 * Selectivity functions and index cost estimation functions for
5 * standard operators and index access methods.
6 *
7 * Selectivity routines are registered in the pg_operator catalog
8 * in the "oprrest" and "oprjoin" attributes.
9 *
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.
12 *
13 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
15 *
16 *
17 * IDENTIFICATION
18 * src/backend/utils/adt/selfuncs.c
19 *
20 *-------------------------------------------------------------------------
21 */
22
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.
32 *
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.
38 *
39 * The call convention for a restriction estimator (oprrest function) is
40 *
41 * Selectivity oprrest (PlannerInfo *root,
42 * Oid operator,
43 * List *args,
44 * int varRelid);
45 *
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.
53 *
54 * This is represented at the SQL level (in pg_proc) as
55 *
56 * float8 oprrest (internal, oid, internal, int4);
57 *
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.
61 *
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:
65 *
66 * Selectivity oprjoin (PlannerInfo *root,
67 * Oid operator,
68 * List *args,
69 * JoinType jointype,
70 * SpecialJoinInfo *sjinfo);
71 *
72 * float8 oprjoin (internal, oid, internal, int2, internal);
73 *
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.
79 *
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.
86 *
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 *----------
93 */
94
95 #include "postgres.h"
96
97 #include <ctype.h>
98 #include <math.h>
99
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 "rewrite/rewriteManip.h"
125 #include "statistics/statistics.h"
126 #include "storage/bufmgr.h"
127 #include "utils/acl.h"
128 #include "utils/array.h"
129 #include "utils/builtins.h"
130 #include "utils/date.h"
131 #include "utils/datum.h"
132 #include "utils/fmgroids.h"
133 #include "utils/index_selfuncs.h"
134 #include "utils/lsyscache.h"
135 #include "utils/memutils.h"
136 #include "utils/pg_locale.h"
137 #include "utils/rel.h"
138 #include "utils/selfuncs.h"
139 #include "utils/snapmgr.h"
140 #include "utils/spccache.h"
141 #include "utils/syscache.h"
142 #include "utils/timestamp.h"
143 #include "utils/typcache.h"
144
145 #define DEFAULT_PAGE_CPU_MULTIPLIER 50.0
146
147 /* Hooks for plugins to get control when we ask for stats */
148 get_relation_stats_hook_type get_relation_stats_hook = NULL;
149 get_index_stats_hook_type get_index_stats_hook = NULL;
150
151 static double eqsel_internal(PG_FUNCTION_ARGS, bool negate);
152 static double eqjoinsel_inner(Oid opfuncoid, Oid collation,
153 VariableStatData *vardata1, VariableStatData *vardata2,
154 double nd1, double nd2,
155 bool isdefault1, bool isdefault2,
156 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
157 Form_pg_statistic stats1, Form_pg_statistic stats2,
158 bool have_mcvs1, bool have_mcvs2);
159 static double eqjoinsel_semi(Oid opfuncoid, Oid collation,
160 VariableStatData *vardata1, VariableStatData *vardata2,
161 double nd1, double nd2,
162 bool isdefault1, bool isdefault2,
163 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
164 Form_pg_statistic stats1, Form_pg_statistic stats2,
165 bool have_mcvs1, bool have_mcvs2,
166 RelOptInfo *inner_rel);
167 static bool estimate_multivariate_ndistinct(PlannerInfo *root,
168 RelOptInfo *rel, List **varinfos, double *ndistinct);
169 static bool convert_to_scalar(Datum value, Oid valuetypid, Oid collid,
170 double *scaledvalue,
171 Datum lobound, Datum hibound, Oid boundstypid,
172 double *scaledlobound, double *scaledhibound);
173 static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure);
174 static void convert_string_to_scalar(char *value,
175 double *scaledvalue,
176 char *lobound,
177 double *scaledlobound,
178 char *hibound,
179 double *scaledhibound);
180 static void convert_bytea_to_scalar(Datum value,
181 double *scaledvalue,
182 Datum lobound,
183 double *scaledlobound,
184 Datum hibound,
185 double *scaledhibound);
186 static double convert_one_string_to_scalar(char *value,
187 int rangelo, int rangehi);
188 static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
189 int rangelo, int rangehi);
190 static char *convert_string_datum(Datum value, Oid typid, Oid collid,
191 bool *failure);
192 static double convert_timevalue_to_scalar(Datum value, Oid typid,
193 bool *failure);
194 static Node *strip_all_phvs_deep(PlannerInfo *root, Node *node);
195 static bool contain_placeholder_walker(Node *node, void *context);
196 static Node *strip_all_phvs_mutator(Node *node, void *context);
197 static void examine_simple_variable(PlannerInfo *root, Var *var,
198 VariableStatData *vardata);
199 static void examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
200 int indexcol, VariableStatData *vardata);
201 static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
202 Oid sortop, Oid collation,
203 Datum *min, Datum *max);
204 static void get_stats_slot_range(AttStatsSlot *sslot,
205 Oid opfuncoid, FmgrInfo *opproc,
206 Oid collation, int16 typLen, bool typByVal,
207 Datum *min, Datum *max, bool *p_have_data);
208 static bool get_actual_variable_range(PlannerInfo *root,
209 VariableStatData *vardata,
210 Oid sortop, Oid collation,
211 Datum *min, Datum *max);
212 static bool get_actual_variable_endpoint(Relation heapRel,
213 Relation indexRel,
214 ScanDirection indexscandir,
215 ScanKey scankeys,
216 int16 typLen,
217 bool typByVal,
218 TupleTableSlot *tableslot,
219 MemoryContext outercontext,
220 Datum *endpointDatum);
221 static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
222 static double btcost_correlation(IndexOptInfo *index,
223 VariableStatData *vardata);
224
225
226 /*
227 * eqsel - Selectivity of "=" for any data types.
228 *
229 * Note: this routine is also used to estimate selectivity for some
230 * operators that are not "=" but have comparable selectivity behavior,
231 * such as "~=" (geometric approximate-match). Even for "=", we must
232 * keep in mind that the left and right datatypes may differ.
233 */
234 Datum
235 eqsel(PG_FUNCTION_ARGS)
236 {
237 PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
238 }
239
240 /*
241 * Common code for eqsel() and neqsel()
242 */
243 static double
244 eqsel_internal(PG_FUNCTION_ARGS, bool negate)
245 {
246 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
247 Oid operator = PG_GETARG_OID(1);
248 List *args = (List *) PG_GETARG_POINTER(2);
249 int varRelid = PG_GETARG_INT32(3);
250 Oid collation = PG_GET_COLLATION();
251 VariableStatData vardata;
252 Node *other;
253 bool varonleft;
254 double selec;
255
256 /*
257 * When asked about <>, we do the estimation using the corresponding =
258 * operator, then convert to <> via "1.0 - eq_selectivity - nullfrac".
259 */
260 if (negate)
261 {
262 operator = get_negator(operator);
263 if (!OidIsValid(operator))
264 {
265 /* Use default selectivity (should we raise an error instead?) */
266 return 1.0 - DEFAULT_EQ_SEL;
267 }
268 }
269
270 /*
271 * If expression is not variable = something or something = variable, then
272 * punt and return a default estimate.
273 */
274 if (!get_restriction_variable(root, args, varRelid,
275 &vardata, &other, &varonleft))
276 return negate ? (1.0 - DEFAULT_EQ_SEL) : DEFAULT_EQ_SEL;
277
278 /*
279 * We can do a lot better if the something is a constant. (Note: the
280 * Const might result from estimation rather than being a simple constant
281 * in the query.)
282 */
283 if (IsA(other, Const))
284 selec = var_eq_const(&vardata, operator, collation,
285 ((Const *) other)->constvalue,
286 ((Const *) other)->constisnull,
287 varonleft, negate);
288 else
289 selec = var_eq_non_const(&vardata, operator, collation, other,
290 varonleft, negate);
291
292 ReleaseVariableStats(vardata);
293
294 return selec;
295 }
296
297 /*
298 * var_eq_const --- eqsel for var = const case
299 *
300 * This is exported so that some other estimation functions can use it.
301 */
302 double
303 var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
304 Datum constval, bool constisnull,
305 bool varonleft, bool negate)
306 {
307 double selec;
308 double nullfrac = 0.0;
309 bool isdefault;
310 Oid opfuncoid;
311
312 /*
313 * If the constant is NULL, assume operator is strict and return zero, ie,
314 * operator will never return TRUE. (It's zero even for a negator op.)
315 */
316 if (constisnull)
317 return 0.0;
318
319 /*
320 * Grab the nullfrac for use below. Note we allow use of nullfrac
321 * regardless of security check.
322 */
323 if (HeapTupleIsValid(vardata->statsTuple))
324 {
325 Form_pg_statistic stats;
326
327 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
328 nullfrac = stats->stanullfrac;
329 }
330
331 /*
332 * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
333 * assume there is exactly one match regardless of anything else. (This
334 * is slightly bogus, since the index or clause's equality operator might
335 * be different from ours, but it's much more likely to be right than
336 * ignoring the information.)
337 */
338 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
339 {
340 selec = 1.0 / vardata->rel->tuples;
341 }
342 else if (HeapTupleIsValid(vardata->statsTuple) &&
343 statistic_proc_security_check(vardata,
344 (opfuncoid = get_opcode(oproid))))
345 {
346 AttStatsSlot sslot;
347 bool match = false;
348 int i;
349
350 /*
351 * Is the constant "=" to any of the column's most common values?
352 * (Although the given operator may not really be "=", we will assume
353 * that seeing whether it returns TRUE is an appropriate test. If you
354 * don't like this, maybe you shouldn't be using eqsel for your
355 * operator...)
356 */
357 if (get_attstatsslot(&sslot, vardata->statsTuple,
358 STATISTIC_KIND_MCV, InvalidOid,
359 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
360 {
361 LOCAL_FCINFO(fcinfo, 2);
362 FmgrInfo eqproc;
363
364 fmgr_info(opfuncoid, &eqproc);
365
366 /*
367 * Save a few cycles by setting up the fcinfo struct just once.
368 * Using FunctionCallInvoke directly also avoids failure if the
369 * eqproc returns NULL, though really equality functions should
370 * never do that.
371 */
372 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
373 NULL, NULL);
374 fcinfo->args[0].isnull = false;
375 fcinfo->args[1].isnull = false;
376 /* be careful to apply operator right way 'round */
377 if (varonleft)
378 fcinfo->args[1].value = constval;
379 else
380 fcinfo->args[0].value = constval;
381
382 for (i = 0; i < sslot.nvalues; i++)
383 {
384 Datum fresult;
385
386 if (varonleft)
387 fcinfo->args[0].value = sslot.values[i];
388 else
389 fcinfo->args[1].value = sslot.values[i];
390 fcinfo->isnull = false;
391 fresult = FunctionCallInvoke(fcinfo);
392 if (!fcinfo->isnull && DatumGetBool(fresult))
393 {
394 match = true;
395 break;
396 }
397 }
398 }
399 else
400 {
401 /* no most-common-value info available */
402 i = 0; /* keep compiler quiet */
403 }
404
405 if (match)
406 {
407 /*
408 * Constant is "=" to this common value. We know selectivity
409 * exactly (or as exactly as ANALYZE could calculate it, anyway).
410 */
411 selec = sslot.numbers[i];
412 }
413 else
414 {
415 /*
416 * Comparison is against a constant that is neither NULL nor any
417 * of the common values. Its selectivity cannot be more than
418 * this:
419 */
420 double sumcommon = 0.0;
421 double otherdistinct;
422
423 for (i = 0; i < sslot.nnumbers; i++)
424 sumcommon += sslot.numbers[i];
425 selec = 1.0 - sumcommon - nullfrac;
426 CLAMP_PROBABILITY(selec);
427
428 /*
429 * and in fact it's probably a good deal less. We approximate that
430 * all the not-common values share this remaining fraction
431 * equally, so we divide by the number of other distinct values.
432 */
433 otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
434 sslot.nnumbers;
435 if (otherdistinct > 1)
436 selec /= otherdistinct;
437
438 /*
439 * Another cross-check: selectivity shouldn't be estimated as more
440 * than the least common "most common value".
441 */
442 if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
443 selec = sslot.numbers[sslot.nnumbers - 1];
444 }
445
446 free_attstatsslot(&sslot);
447 }
448 else
449 {
450 /*
451 * No ANALYZE stats available, so make a guess using estimated number
452 * of distinct values and assuming they are equally common. (The guess
453 * is unlikely to be very good, but we do know a few special cases.)
454 */
455 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
456 }
457
458 /* now adjust if we wanted <> rather than = */
459 if (negate)
460 selec = 1.0 - selec - nullfrac;
461
462 /* result should be in range, but make sure... */
463 CLAMP_PROBABILITY(selec);
464
465 return selec;
466 }
467
468 /*
469 * var_eq_non_const --- eqsel for var = something-other-than-const case
470 *
471 * This is exported so that some other estimation functions can use it.
472 */
473 double
474 var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
475 Node *other,
476 bool varonleft, bool negate)
477 {
478 double selec;
479 double nullfrac = 0.0;
480 bool isdefault;
481
482 /*
483 * Grab the nullfrac for use below.
484 */
485 if (HeapTupleIsValid(vardata->statsTuple))
486 {
487 Form_pg_statistic stats;
488
489 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
490 nullfrac = stats->stanullfrac;
491 }
492
493 /*
494 * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
495 * assume there is exactly one match regardless of anything else. (This
496 * is slightly bogus, since the index or clause's equality operator might
497 * be different from ours, but it's much more likely to be right than
498 * ignoring the information.)
499 */
500 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
501 {
502 selec = 1.0 / vardata->rel->tuples;
503 }
504 else if (HeapTupleIsValid(vardata->statsTuple))
505 {
506 double ndistinct;
507 AttStatsSlot sslot;
508
509 /*
510 * Search is for a value that we do not know a priori, but we will
511 * assume it is not NULL. Estimate the selectivity as non-null
512 * fraction divided by number of distinct values, so that we get a
513 * result averaged over all possible values whether common or
514 * uncommon. (Essentially, we are assuming that the not-yet-known
515 * comparison value is equally likely to be any of the possible
516 * values, regardless of their frequency in the table. Is that a good
517 * idea?)
518 */
519 selec = 1.0 - nullfrac;
520 ndistinct = get_variable_numdistinct(vardata, &isdefault);
521 if (ndistinct > 1)
522 selec /= ndistinct;
523
524 /*
525 * Cross-check: selectivity should never be estimated as more than the
526 * most common value's.
527 */
528 if (get_attstatsslot(&sslot, vardata->statsTuple,
529 STATISTIC_KIND_MCV, InvalidOid,
530 ATTSTATSSLOT_NUMBERS))
531 {
532 if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
533 selec = sslot.numbers[0];
534 free_attstatsslot(&sslot);
535 }
536 }
537 else
538 {
539 /*
540 * No ANALYZE stats available, so make a guess using estimated number
541 * of distinct values and assuming they are equally common. (The guess
542 * is unlikely to be very good, but we do know a few special cases.)
543 */
544 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
545 }
546
547 /* now adjust if we wanted <> rather than = */
548 if (negate)
549 selec = 1.0 - selec - nullfrac;
550
551 /* result should be in range, but make sure... */
552 CLAMP_PROBABILITY(selec);
553
554 return selec;
555 }
556
557 /*
558 * neqsel - Selectivity of "!=" for any data types.
559 *
560 * This routine is also used for some operators that are not "!="
561 * but have comparable selectivity behavior. See above comments
562 * for eqsel().
563 */
564 Datum
565 neqsel(PG_FUNCTION_ARGS)
566 {
567 PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, true));
568 }
569
570 /*
571 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
572 *
573 * This is the guts of scalarltsel/scalarlesel/scalargtsel/scalargesel.
574 * The isgt and iseq flags distinguish which of the four cases apply.
575 *
576 * The caller has commuted the clause, if necessary, so that we can treat
577 * the variable as being on the left. The caller must also make sure that
578 * the other side of the clause is a non-null Const, and dissect that into
579 * a value and datatype. (This definition simplifies some callers that
580 * want to estimate against a computed value instead of a Const node.)
581 *
582 * This routine works for any datatype (or pair of datatypes) known to
583 * convert_to_scalar(). If it is applied to some other datatype,
584 * it will return an approximate estimate based on assuming that the constant
585 * value falls in the middle of the bin identified by binary search.
586 */
587 static double
588 scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq,
589 Oid collation,
590 VariableStatData *vardata, Datum constval, Oid consttype)
591 {
592 Form_pg_statistic stats;
593 FmgrInfo opproc;
594 double mcv_selec,
595 hist_selec,
596 sumcommon;
597 double selec;
598
599 if (!HeapTupleIsValid(vardata->statsTuple))
600 {
601 /*
602 * No stats are available. Typically this means we have to fall back
603 * on the default estimate; but if the variable is CTID then we can
604 * make an estimate based on comparing the constant to the table size.
605 */
606 if (vardata->var && IsA(vardata->var, Var) &&
607 ((Var *) vardata->var)->varattno == SelfItemPointerAttributeNumber &&
608 consttype == TIDOID)
609 {
610 ItemPointer itemptr;
611 double block;
612 double density;
613
614 /*
615 * If the relation's empty, we're going to include all of it.
616 * (This is mostly to avoid divide-by-zero below.)
617 */
618 if (vardata->rel->pages == 0)
619 return 1.0;
620
621 itemptr = (ItemPointer) DatumGetPointer(constval);
622 block = ItemPointerGetBlockNumberNoCheck(itemptr);
623
624 /*
625 * Determine the average number of tuples per page (density).
626 *
627 * Since the last page will, on average, be only half full, we can
628 * estimate it to have half as many tuples as earlier pages. So
629 * give it half the weight of a regular page.
630 */
631 density = vardata->rel->tuples / (vardata->rel->pages - 0.5);
632
633 /* If target is the last page, use half the density. */
634 if (block >= vardata->rel->pages - 1)
635 density *= 0.5;
636
637 /*
638 * Using the average tuples per page, calculate how far into the
639 * page the itemptr is likely to be and adjust block accordingly,
640 * by adding that fraction of a whole block (but never more than a
641 * whole block, no matter how high the itemptr's offset is). Here
642 * we are ignoring the possibility of dead-tuple line pointers,
643 * which is fairly bogus, but we lack the info to do better.
644 */
645 if (density > 0.0)
646 {
647 OffsetNumber offset = ItemPointerGetOffsetNumberNoCheck(itemptr);
648
649 block += Min(offset / density, 1.0);
650 }
651
652 /*
653 * Convert relative block number to selectivity. Again, the last
654 * page has only half weight.
655 */
656 selec = block / (vardata->rel->pages - 0.5);
657
658 /*
659 * The calculation so far gave us a selectivity for the "<=" case.
660 * We'll have one fewer tuple for "<" and one additional tuple for
661 * ">=", the latter of which we'll reverse the selectivity for
662 * below, so we can simply subtract one tuple for both cases. The
663 * cases that need this adjustment can be identified by iseq being
664 * equal to isgt.
665 */
666 if (iseq == isgt && vardata->rel->tuples >= 1.0)
667 selec -= (1.0 / vardata->rel->tuples);
668
669 /* Finally, reverse the selectivity for the ">", ">=" cases. */
670 if (isgt)
671 selec = 1.0 - selec;
672
673 CLAMP_PROBABILITY(selec);
674 return selec;
675 }
676
677 /* no stats available, so default result */
678 return DEFAULT_INEQ_SEL;
679 }
680 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
681
682 fmgr_info(get_opcode(operator), &opproc);
683
684 /*
685 * If we have most-common-values info, add up the fractions of the MCV
686 * entries that satisfy MCV OP CONST. These fractions contribute directly
687 * to the result selectivity. Also add up the total fraction represented
688 * by MCV entries.
689 */
690 mcv_selec = mcv_selectivity(vardata, &opproc, collation, constval, true,
691 &sumcommon);
692
693 /*
694 * If there is a histogram, determine which bin the constant falls in, and
695 * compute the resulting contribution to selectivity.
696 */
697 hist_selec = ineq_histogram_selectivity(root, vardata,
698 operator, &opproc, isgt, iseq,
699 collation,
700 constval, consttype);
701
702 /*
703 * Now merge the results from the MCV and histogram calculations,
704 * realizing that the histogram covers only the non-null values that are
705 * not listed in MCV.
706 */
707 selec = 1.0 - stats->stanullfrac - sumcommon;
708
709 if (hist_selec >= 0.0)
710 selec *= hist_selec;
711 else
712 {
713 /*
714 * If no histogram but there are values not accounted for by MCV,
715 * arbitrarily assume half of them will match.
716 */
717 selec *= 0.5;
718 }
719
720 selec += mcv_selec;
721
722 /* result should be in range, but make sure... */
723 CLAMP_PROBABILITY(selec);
724
725 return selec;
726 }
727
728 /*
729 * mcv_selectivity - Examine the MCV list for selectivity estimates
730 *
731 * Determine the fraction of the variable's MCV population that satisfies
732 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
733 * compute the fraction of the total column population represented by the MCV
734 * list. This code will work for any boolean-returning predicate operator.
735 *
736 * The function result is the MCV selectivity, and the fraction of the
737 * total population is returned into *sumcommonp. Zeroes are returned
738 * if there is no MCV list.
739 */
740 double
741 mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation,
742 Datum constval, bool varonleft,
743 double *sumcommonp)
744 {
745 double mcv_selec,
746 sumcommon;
747 AttStatsSlot sslot;
748 int i;
749
750 mcv_selec = 0.0;
751 sumcommon = 0.0;
752
753 if (HeapTupleIsValid(vardata->statsTuple) &&
754 statistic_proc_security_check(vardata, opproc->fn_oid) &&
755 get_attstatsslot(&sslot, vardata->statsTuple,
756 STATISTIC_KIND_MCV, InvalidOid,
757 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
758 {
759 LOCAL_FCINFO(fcinfo, 2);
760
761 /*
762 * We invoke the opproc "by hand" so that we won't fail on NULL
763 * results. Such cases won't arise for normal comparison functions,
764 * but generic_restriction_selectivity could perhaps be used with
765 * operators that can return NULL. A small side benefit is to not
766 * need to re-initialize the fcinfo struct from scratch each time.
767 */
768 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
769 NULL, NULL);
770 fcinfo->args[0].isnull = false;
771 fcinfo->args[1].isnull = false;
772 /* be careful to apply operator right way 'round */
773 if (varonleft)
774 fcinfo->args[1].value = constval;
775 else
776 fcinfo->args[0].value = constval;
777
778 for (i = 0; i < sslot.nvalues; i++)
779 {
780 Datum fresult;
781
782 if (varonleft)
783 fcinfo->args[0].value = sslot.values[i];
784 else
785 fcinfo->args[1].value = sslot.values[i];
786 fcinfo->isnull = false;
787 fresult = FunctionCallInvoke(fcinfo);
788 if (!fcinfo->isnull && DatumGetBool(fresult))
789 mcv_selec += sslot.numbers[i];
790 sumcommon += sslot.numbers[i];
791 }
792 free_attstatsslot(&sslot);
793 }
794
795 *sumcommonp = sumcommon;
796 return mcv_selec;
797 }
798
799 /*
800 * histogram_selectivity - Examine the histogram for selectivity estimates
801 *
802 * Determine the fraction of the variable's histogram entries that satisfy
803 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
804 *
805 * This code will work for any boolean-returning predicate operator, whether
806 * or not it has anything to do with the histogram sort operator. We are
807 * essentially using the histogram just as a representative sample. However,
808 * small histograms are unlikely to be all that representative, so the caller
809 * should be prepared to fall back on some other estimation approach when the
810 * histogram is missing or very small. It may also be prudent to combine this
811 * approach with another one when the histogram is small.
812 *
813 * If the actual histogram size is not at least min_hist_size, we won't bother
814 * to do the calculation at all. Also, if the n_skip parameter is > 0, we
815 * ignore the first and last n_skip histogram elements, on the grounds that
816 * they are outliers and hence not very representative. Typical values for
817 * these parameters are 10 and 1.
818 *
819 * The function result is the selectivity, or -1 if there is no histogram
820 * or it's smaller than min_hist_size.
821 *
822 * The output parameter *hist_size receives the actual histogram size,
823 * or zero if no histogram. Callers may use this number to decide how
824 * much faith to put in the function result.
825 *
826 * Note that the result disregards both the most-common-values (if any) and
827 * null entries. The caller is expected to combine this result with
828 * statistics for those portions of the column population. It may also be
829 * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
830 */
831 double
832 histogram_selectivity(VariableStatData *vardata,
833 FmgrInfo *opproc, Oid collation,
834 Datum constval, bool varonleft,
835 int min_hist_size, int n_skip,
836 int *hist_size)
837 {
838 double result;
839 AttStatsSlot sslot;
840
841 /* check sanity of parameters */
842 Assert(n_skip >= 0);
843 Assert(min_hist_size > 2 * n_skip);
844
845 if (HeapTupleIsValid(vardata->statsTuple) &&
846 statistic_proc_security_check(vardata, opproc->fn_oid) &&
847 get_attstatsslot(&sslot, vardata->statsTuple,
848 STATISTIC_KIND_HISTOGRAM, InvalidOid,
849 ATTSTATSSLOT_VALUES))
850 {
851 *hist_size = sslot.nvalues;
852 if (sslot.nvalues >= min_hist_size)
853 {
854 LOCAL_FCINFO(fcinfo, 2);
855 int nmatch = 0;
856 int i;
857
858 /*
859 * We invoke the opproc "by hand" so that we won't fail on NULL
860 * results. Such cases won't arise for normal comparison
861 * functions, but generic_restriction_selectivity could perhaps be
862 * used with operators that can return NULL. A small side benefit
863 * is to not need to re-initialize the fcinfo struct from scratch
864 * each time.
865 */
866 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
867 NULL, NULL);
868 fcinfo->args[0].isnull = false;
869 fcinfo->args[1].isnull = false;
870 /* be careful to apply operator right way 'round */
871 if (varonleft)
872 fcinfo->args[1].value = constval;
873 else
874 fcinfo->args[0].value = constval;
875
876 for (i = n_skip; i < sslot.nvalues - n_skip; i++)
877 {
878 Datum fresult;
879
880 if (varonleft)
881 fcinfo->args[0].value = sslot.values[i];
882 else
883 fcinfo->args[1].value = sslot.values[i];
884 fcinfo->isnull = false;
885 fresult = FunctionCallInvoke(fcinfo);
886 if (!fcinfo->isnull && DatumGetBool(fresult))
887 nmatch++;
888 }
889 result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
890 }
891 else
892 result = -1;
893 free_attstatsslot(&sslot);
894 }
895 else
896 {
897 *hist_size = 0;
898 result = -1;
899 }
900
901 return result;
902 }
903
904 /*
905 * generic_restriction_selectivity - Selectivity for almost anything
906 *
907 * This function estimates selectivity for operators that we don't have any
908 * special knowledge about, but are on data types that we collect standard
909 * MCV and/or histogram statistics for. (Additional assumptions are that
910 * the operator is strict and immutable, or at least stable.)
911 *
912 * If we have "VAR OP CONST" or "CONST OP VAR", selectivity is estimated by
913 * applying the operator to each element of the column's MCV and/or histogram
914 * stats, and merging the results using the assumption that the histogram is
915 * a reasonable random sample of the column's non-MCV population. Note that
916 * if the operator's semantics are related to the histogram ordering, this
917 * might not be such a great assumption; other functions such as
918 * scalarineqsel() are probably a better match in such cases.
919 *
920 * Otherwise, fall back to the default selectivity provided by the caller.
921 */
922 double
923 generic_restriction_selectivity(PlannerInfo *root, Oid oproid, Oid collation,
924 List *args, int varRelid,
925 double default_selectivity)
926 {
927 double selec;
928 VariableStatData vardata;
929 Node *other;
930 bool varonleft;
931
932 /*
933 * If expression is not variable OP something or something OP variable,
934 * then punt and return the default estimate.
935 */
936 if (!get_restriction_variable(root, args, varRelid,
937 &vardata, &other, &varonleft))
938 return default_selectivity;
939
940 /*
941 * If the something is a NULL constant, assume operator is strict and
942 * return zero, ie, operator will never return TRUE.
943 */
944 if (IsA(other, Const) &&
945 ((Const *) other)->constisnull)
946 {
947 ReleaseVariableStats(vardata);
948 return 0.0;
949 }
950
951 if (IsA(other, Const))
952 {
953 /* Variable is being compared to a known non-null constant */
954 Datum constval = ((Const *) other)->constvalue;
955 FmgrInfo opproc;
956 double mcvsum;
957 double mcvsel;
958 double nullfrac;
959 int hist_size;
960
961 fmgr_info(get_opcode(oproid), &opproc);
962
963 /*
964 * Calculate the selectivity for the column's most common values.
965 */
966 mcvsel = mcv_selectivity(&vardata, &opproc, collation,
967 constval, varonleft,
968 &mcvsum);
969
970 /*
971 * If the histogram is large enough, see what fraction of it matches
972 * the query, and assume that's representative of the non-MCV
973 * population. Otherwise use the default selectivity for the non-MCV
974 * population.
975 */
976 selec = histogram_selectivity(&vardata, &opproc, collation,
977 constval, varonleft,
978 10, 1, &hist_size);
979 if (selec < 0)
980 {
981 /* Nope, fall back on default */
982 selec = default_selectivity;
983 }
984 else if (hist_size < 100)
985 {
986 /*
987 * For histogram sizes from 10 to 100, we combine the histogram
988 * and default selectivities, putting increasingly more trust in
989 * the histogram for larger sizes.
990 */
991 double hist_weight = hist_size / 100.0;
992
993 selec = selec * hist_weight +
994 default_selectivity * (1.0 - hist_weight);
995 }
996
997 /* In any case, don't believe extremely small or large estimates. */
998 if (selec < 0.0001)
999 selec = 0.0001;
1000 else if (selec > 0.9999)
1001 selec = 0.9999;
1002
1003 /* Don't forget to account for nulls. */
1004 if (HeapTupleIsValid(vardata.statsTuple))
1005 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
1006 else
1007 nullfrac = 0.0;
1008
1009 /*
1010 * Now merge the results from the MCV and histogram calculations,
1011 * realizing that the histogram covers only the non-null values that
1012 * are not listed in MCV.
1013 */
1014 selec *= 1.0 - nullfrac - mcvsum;
1015 selec += mcvsel;
1016 }
1017 else
1018 {
1019 /* Comparison value is not constant, so we can't do anything */
1020 selec = default_selectivity;
1021 }
1022
1023 ReleaseVariableStats(vardata);
1024
1025 /* result should be in range, but make sure... */
1026 CLAMP_PROBABILITY(selec);
1027
1028 return selec;
1029 }
1030
1031 /*
1032 * ineq_histogram_selectivity - Examine the histogram for scalarineqsel
1033 *
1034 * Determine the fraction of the variable's histogram population that
1035 * satisfies the inequality condition, ie, VAR < (or <=, >, >=) CONST.
1036 * The isgt and iseq flags distinguish which of the four cases apply.
1037 *
1038 * While opproc could be looked up from the operator OID, common callers
1039 * also need to call it separately, so we make the caller pass both.
1040 *
1041 * Returns -1 if there is no histogram (valid results will always be >= 0).
1042 *
1043 * Note that the result disregards both the most-common-values (if any) and
1044 * null entries. The caller is expected to combine this result with
1045 * statistics for those portions of the column population.
1046 *
1047 * This is exported so that some other estimation functions can use it.
1048 */
1049 double
1050 ineq_histogram_selectivity(PlannerInfo *root,
1051 VariableStatData *vardata,
1052 Oid opoid, FmgrInfo *opproc, bool isgt, bool iseq,
1053 Oid collation,
1054 Datum constval, Oid consttype)
1055 {
1056 double hist_selec;
1057 AttStatsSlot sslot;
1058
1059 hist_selec = -1.0;
1060
1061 /*
1062 * Someday, ANALYZE might store more than one histogram per rel/att,
1063 * corresponding to more than one possible sort ordering defined for the
1064 * column type. Right now, we know there is only one, so just grab it and
1065 * see if it matches the query.
1066 *
1067 * Note that we can't use opoid as search argument; the staop appearing in
1068 * pg_statistic will be for the relevant '<' operator, but what we have
1069 * might be some other inequality operator such as '>='. (Even if opoid
1070 * is a '<' operator, it could be cross-type.) Hence we must use
1071 * comparison_ops_are_compatible() to see if the operators match.
1072 */
1073 if (HeapTupleIsValid(vardata->statsTuple) &&
1074 statistic_proc_security_check(vardata, opproc->fn_oid) &&
1075 get_attstatsslot(&sslot, vardata->statsTuple,
1076 STATISTIC_KIND_HISTOGRAM, InvalidOid,
1077 ATTSTATSSLOT_VALUES))
1078 {
1079 if (sslot.nvalues > 1 &&
1080 sslot.stacoll == collation &&
1081 comparison_ops_are_compatible(sslot.staop, opoid))
1082 {
1083 /*
1084 * Use binary search to find the desired location, namely the
1085 * right end of the histogram bin containing the comparison value,
1086 * which is the leftmost entry for which the comparison operator
1087 * succeeds (if isgt) or fails (if !isgt).
1088 *
1089 * In this loop, we pay no attention to whether the operator iseq
1090 * or not; that detail will be mopped up below. (We cannot tell,
1091 * anyway, whether the operator thinks the values are equal.)
1092 *
1093 * If the binary search accesses the first or last histogram
1094 * entry, we try to replace that endpoint with the true column min
1095 * or max as found by get_actual_variable_range(). This
1096 * ameliorates misestimates when the min or max is moving as a
1097 * result of changes since the last ANALYZE. Note that this could
1098 * result in effectively including MCVs into the histogram that
1099 * weren't there before, but we don't try to correct for that.
1100 */
1101 double histfrac;
1102 int lobound = 0; /* first possible slot to search */
1103 int hibound = sslot.nvalues; /* last+1 slot to search */
1104 bool have_end = false;
1105
1106 /*
1107 * If there are only two histogram entries, we'll want up-to-date
1108 * values for both. (If there are more than two, we need at most
1109 * one of them to be updated, so we deal with that within the
1110 * loop.)
1111 */
1112 if (sslot.nvalues == 2)
1113 have_end = get_actual_variable_range(root,
1114 vardata,
1115 sslot.staop,
1116 collation,
1117 &sslot.values[0],
1118 &sslot.values[1]);
1119
1120 while (lobound < hibound)
1121 {
1122 int probe = (lobound + hibound) / 2;
1123 bool ltcmp;
1124
1125 /*
1126 * If we find ourselves about to compare to the first or last
1127 * histogram entry, first try to replace it with the actual
1128 * current min or max (unless we already did so above).
1129 */
1130 if (probe == 0 && sslot.nvalues > 2)
1131 have_end = get_actual_variable_range(root,
1132 vardata,
1133 sslot.staop,
1134 collation,
1135 &sslot.values[0],
1136 NULL);
1137 else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
1138 have_end = get_actual_variable_range(root,
1139 vardata,
1140 sslot.staop,
1141 collation,
1142 NULL,
1143 &sslot.values[probe]);
1144
1145 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
1146 collation,
1147 sslot.values[probe],
1148 constval));
1149 if (isgt)
1150 ltcmp = !ltcmp;
1151 if (ltcmp)
1152 lobound = probe + 1;
1153 else
1154 hibound = probe;
1155 }
1156
1157 if (lobound <= 0)
1158 {
1159 /*
1160 * Constant is below lower histogram boundary. More
1161 * precisely, we have found that no entry in the histogram
1162 * satisfies the inequality clause (if !isgt) or they all do
1163 * (if isgt). We estimate that that's true of the entire
1164 * table, so set histfrac to 0.0 (which we'll flip to 1.0
1165 * below, if isgt).
1166 */
1167 histfrac = 0.0;
1168 }
1169 else if (lobound >= sslot.nvalues)
1170 {
1171 /*
1172 * Inverse case: constant is above upper histogram boundary.
1173 */
1174 histfrac = 1.0;
1175 }
1176 else
1177 {
1178 /* We have values[i-1] <= constant <= values[i]. */
1179 int i = lobound;
1180 double eq_selec = 0;
1181 double val,
1182 high,
1183 low;
1184 double binfrac;
1185
1186 /*
1187 * In the cases where we'll need it below, obtain an estimate
1188 * of the selectivity of "x = constval". We use a calculation
1189 * similar to what var_eq_const() does for a non-MCV constant,
1190 * ie, estimate that all distinct non-MCV values occur equally
1191 * often. But multiplication by "1.0 - sumcommon - nullfrac"
1192 * will be done by our caller, so we shouldn't do that here.
1193 * Therefore we can't try to clamp the estimate by reference
1194 * to the least common MCV; the result would be too small.
1195 *
1196 * Note: since this is effectively assuming that constval
1197 * isn't an MCV, it's logically dubious if constval in fact is
1198 * one. But we have to apply *some* correction for equality,
1199 * and anyway we cannot tell if constval is an MCV, since we
1200 * don't have a suitable equality operator at hand.
1201 */
1202 if (i == 1 || isgt == iseq)
1203 {
1204 double otherdistinct;
1205 bool isdefault;
1206 AttStatsSlot mcvslot;
1207
1208 /* Get estimated number of distinct values */
1209 otherdistinct = get_variable_numdistinct(vardata,
1210 &isdefault);
1211
1212 /* Subtract off the number of known MCVs */
1213 if (get_attstatsslot(&mcvslot, vardata->statsTuple,
1214 STATISTIC_KIND_MCV, InvalidOid,
1215 ATTSTATSSLOT_NUMBERS))
1216 {
1217 otherdistinct -= mcvslot.nnumbers;
1218 free_attstatsslot(&mcvslot);
1219 }
1220
1221 /* If result doesn't seem sane, leave eq_selec at 0 */
1222 if (otherdistinct > 1)
1223 eq_selec = 1.0 / otherdistinct;
1224 }
1225
1226 /*
1227 * Convert the constant and the two nearest bin boundary
1228 * values to a uniform comparison scale, and do a linear
1229 * interpolation within this bin.
1230 */
1231 if (convert_to_scalar(constval, consttype, collation,
1232 &val,
1233 sslot.values[i - 1], sslot.values[i],
1234 vardata->vartype,
1235 &low, &high))
1236 {
1237 if (high <= low)
1238 {
1239 /* cope if bin boundaries appear identical */
1240 binfrac = 0.5;
1241 }
1242 else if (val <= low)
1243 binfrac = 0.0;
1244 else if (val >= high)
1245 binfrac = 1.0;
1246 else
1247 {
1248 binfrac = (val - low) / (high - low);
1249
1250 /*
1251 * Watch out for the possibility that we got a NaN or
1252 * Infinity from the division. This can happen
1253 * despite the previous checks, if for example "low"
1254 * is -Infinity.
1255 */
1256 if (isnan(binfrac) ||
1257 binfrac < 0.0 || binfrac > 1.0)
1258 binfrac = 0.5;
1259 }
1260 }
1261 else
1262 {
1263 /*
1264 * Ideally we'd produce an error here, on the grounds that
1265 * the given operator shouldn't have scalarXXsel
1266 * registered as its selectivity func unless we can deal
1267 * with its operand types. But currently, all manner of
1268 * stuff is invoking scalarXXsel, so give a default
1269 * estimate until that can be fixed.
1270 */
1271 binfrac = 0.5;
1272 }
1273
1274 /*
1275 * Now, compute the overall selectivity across the values
1276 * represented by the histogram. We have i-1 full bins and
1277 * binfrac partial bin below the constant.
1278 */
1279 histfrac = (double) (i - 1) + binfrac;
1280 histfrac /= (double) (sslot.nvalues - 1);
1281
1282 /*
1283 * At this point, histfrac is an estimate of the fraction of
1284 * the population represented by the histogram that satisfies
1285 * "x <= constval". Somewhat remarkably, this statement is
1286 * true regardless of which operator we were doing the probes
1287 * with, so long as convert_to_scalar() delivers reasonable
1288 * results. If the probe constant is equal to some histogram
1289 * entry, we would have considered the bin to the left of that
1290 * entry if probing with "<" or ">=", or the bin to the right
1291 * if probing with "<=" or ">"; but binfrac would have come
1292 * out as 1.0 in the first case and 0.0 in the second, leading
1293 * to the same histfrac in either case. For probe constants
1294 * between histogram entries, we find the same bin and get the
1295 * same estimate with any operator.
1296 *
1297 * The fact that the estimate corresponds to "x <= constval"
1298 * and not "x < constval" is because of the way that ANALYZE
1299 * constructs the histogram: each entry is, effectively, the
1300 * rightmost value in its sample bucket. So selectivity
1301 * values that are exact multiples of 1/(histogram_size-1)
1302 * should be understood as estimates including a histogram
1303 * entry plus everything to its left.
1304 *
1305 * However, that breaks down for the first histogram entry,
1306 * which necessarily is the leftmost value in its sample
1307 * bucket. That means the first histogram bin is slightly
1308 * narrower than the rest, by an amount equal to eq_selec.
1309 * Another way to say that is that we want "x <= leftmost" to
1310 * be estimated as eq_selec not zero. So, if we're dealing
1311 * with the first bin (i==1), rescale to make that true while
1312 * adjusting the rest of that bin linearly.
1313 */
1314 if (i == 1)
1315 histfrac += eq_selec * (1.0 - binfrac);
1316
1317 /*
1318 * "x <= constval" is good if we want an estimate for "<=" or
1319 * ">", but if we are estimating for "<" or ">=", we now need
1320 * to decrease the estimate by eq_selec.
1321 */
1322 if (isgt == iseq)
1323 histfrac -= eq_selec;
1324 }
1325
1326 /*
1327 * Now the estimate is finished for "<" and "<=" cases. If we are
1328 * estimating for ">" or ">=", flip it.
1329 */
1330 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
1331
1332 /*
1333 * The histogram boundaries are only approximate to begin with,
1334 * and may well be out of date anyway. Therefore, don't believe
1335 * extremely small or large selectivity estimates --- unless we
1336 * got actual current endpoint values from the table, in which
1337 * case just do the usual sanity clamp. Somewhat arbitrarily, we
1338 * set the cutoff for other cases at a hundredth of the histogram
1339 * resolution.
1340 */
1341 if (have_end)
1342 CLAMP_PROBABILITY(hist_selec);
1343 else
1344 {
1345 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1346
1347 if (hist_selec < cutoff)
1348 hist_selec = cutoff;
1349 else if (hist_selec > 1.0 - cutoff)
1350 hist_selec = 1.0 - cutoff;
1351 }
1352 }
1353 else if (sslot.nvalues > 1)
1354 {
1355 /*
1356 * If we get here, we have a histogram but it's not sorted the way
1357 * we want. Do a brute-force search to see how many of the
1358 * entries satisfy the comparison condition, and take that
1359 * fraction as our estimate. (This is identical to the inner loop
1360 * of histogram_selectivity; maybe share code?)
1361 */
1362 LOCAL_FCINFO(fcinfo, 2);
1363 int nmatch = 0;
1364
1365 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
1366 NULL, NULL);
1367 fcinfo->args[0].isnull = false;
1368 fcinfo->args[1].isnull = false;
1369 fcinfo->args[1].value = constval;
1370 for (int i = 0; i < sslot.nvalues; i++)
1371 {
1372 Datum fresult;
1373
1374 fcinfo->args[0].value = sslot.values[i];
1375 fcinfo->isnull = false;
1376 fresult = FunctionCallInvoke(fcinfo);
1377 if (!fcinfo->isnull && DatumGetBool(fresult))
1378 nmatch++;
1379 }
1380 hist_selec = ((double) nmatch) / ((double) sslot.nvalues);
1381
1382 /*
1383 * As above, clamp to a hundredth of the histogram resolution.
1384 * This case is surely even less trustworthy than the normal one,
1385 * so we shouldn't believe exact 0 or 1 selectivity. (Maybe the
1386 * clamp should be more restrictive in this case?)
1387 */
1388 {
1389 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1390
1391 if (hist_selec < cutoff)
1392 hist_selec = cutoff;
1393 else if (hist_selec > 1.0 - cutoff)
1394 hist_selec = 1.0 - cutoff;
1395 }
1396 }
1397
1398 free_attstatsslot(&sslot);
1399 }
1400
1401 return hist_selec;
1402 }
1403
1404 /*
1405 * Common wrapper function for the selectivity estimators that simply
1406 * invoke scalarineqsel().
1407 */
1408 static Datum
1409 scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
1410 {
1411 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1412 Oid operator = PG_GETARG_OID(1);
1413 List *args = (List *) PG_GETARG_POINTER(2);
1414 int varRelid = PG_GETARG_INT32(3);
1415 Oid collation = PG_GET_COLLATION();
1416 VariableStatData vardata;
1417 Node *other;
1418 bool varonleft;
1419 Datum constval;
1420 Oid consttype;
1421 double selec;
1422
1423 /*
1424 * If expression is not variable op something or something op variable,
1425 * then punt and return a default estimate.
1426 */
1427 if (!get_restriction_variable(root, args, varRelid,
1428 &vardata, &other, &varonleft))
1429 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1430
1431 /*
1432 * Can't do anything useful if the something is not a constant, either.
1433 */
1434 if (!IsA(other, Const))
1435 {
1436 ReleaseVariableStats(vardata);
1437 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1438 }
1439
1440 /*
1441 * If the constant is NULL, assume operator is strict and return zero, ie,
1442 * operator will never return TRUE.
1443 */
1444 if (((Const *) other)->constisnull)
1445 {
1446 ReleaseVariableStats(vardata);
1447 PG_RETURN_FLOAT8(0.0);
1448 }
1449 constval = ((Const *) other)->constvalue;
1450 consttype = ((Const *) other)->consttype;
1451
1452 /*
1453 * Force the var to be on the left to simplify logic in scalarineqsel.
1454 */
1455 if (!varonleft)
1456 {
1457 operator = get_commutator(operator);
1458 if (!operator)
1459 {
1460 /* Use default selectivity (should we raise an error instead?) */
1461 ReleaseVariableStats(vardata);
1462 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1463 }
1464 isgt = !isgt;
1465 }
1466
1467 /* The rest of the work is done by scalarineqsel(). */
1468 selec = scalarineqsel(root, operator, isgt, iseq, collation,
1469 &vardata, constval, consttype);
1470
1471 ReleaseVariableStats(vardata);
1472
1473 PG_RETURN_FLOAT8((float8) selec);
1474 }
1475
1476 /*
1477 * scalarltsel - Selectivity of "<" for scalars.
1478 */
1479 Datum
1480 scalarltsel(PG_FUNCTION_ARGS)
1481 {
1482 return scalarineqsel_wrapper(fcinfo, false, false);
1483 }
1484
1485 /*
1486 * scalarlesel - Selectivity of "<=" for scalars.
1487 */
1488 Datum
1489 scalarlesel(PG_FUNCTION_ARGS)
1490 {
1491 return scalarineqsel_wrapper(fcinfo, false, true);
1492 }
1493
1494 /*
1495 * scalargtsel - Selectivity of ">" for scalars.
1496 */
1497 Datum
1498 scalargtsel(PG_FUNCTION_ARGS)
1499 {
1500 return scalarineqsel_wrapper(fcinfo, true, false);
1501 }
1502
1503 /*
1504 * scalargesel - Selectivity of ">=" for scalars.
1505 */
1506 Datum
1507 scalargesel(PG_FUNCTION_ARGS)
1508 {
1509 return scalarineqsel_wrapper(fcinfo, true, true);
1510 }
1511
1512 /*
1513 * boolvarsel - Selectivity of Boolean variable.
1514 *
1515 * This can actually be called on any boolean-valued expression. If it
1516 * involves only Vars of the specified relation, and if there are statistics
1517 * about the Var or expression (the latter is possible if it's indexed) then
1518 * we'll produce a real estimate; otherwise it's just a default.
1519 */
1520 Selectivity
1521 boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
1522 {
1523 VariableStatData vardata;
1524 double selec;
1525
1526 examine_variable(root, arg, varRelid, &vardata);
1527 if (HeapTupleIsValid(vardata.statsTuple))
1528 {
1529 /*
1530 * A boolean variable V is equivalent to the clause V = 't', so we
1531 * compute the selectivity as if that is what we have.
1532 */
1533 selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1534 BoolGetDatum(true), false, true, false);
1535 }
1536 else
1537 {
1538 /* Otherwise, the default estimate is 0.5 */
1539 selec = 0.5;
1540 }
1541 ReleaseVariableStats(vardata);
1542 return selec;
1543 }
1544
1545 /*
1546 * booltestsel - Selectivity of BooleanTest Node.
1547 */
1548 Selectivity
1549 booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
1550 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1551 {
1552 VariableStatData vardata;
1553 double selec;
1554
1555 examine_variable(root, arg, varRelid, &vardata);
1556
1557 if (HeapTupleIsValid(vardata.statsTuple))
1558 {
1559 Form_pg_statistic stats;
1560 double freq_null;
1561 AttStatsSlot sslot;
1562
1563 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1564 freq_null = stats->stanullfrac;
1565
1566 if (get_attstatsslot(&sslot, vardata.statsTuple,
1567 STATISTIC_KIND_MCV, InvalidOid,
1568 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)
1569 && sslot.nnumbers > 0)
1570 {
1571 double freq_true;
1572 double freq_false;
1573
1574 /*
1575 * Get first MCV frequency and derive frequency for true.
1576 */
1577 if (DatumGetBool(sslot.values[0]))
1578 freq_true = sslot.numbers[0];
1579 else
1580 freq_true = 1.0 - sslot.numbers[0] - freq_null;
1581
1582 /*
1583 * Next derive frequency for false. Then use these as appropriate
1584 * to derive frequency for each case.
1585 */
1586 freq_false = 1.0 - freq_true - freq_null;
1587
1588 switch (booltesttype)
1589 {
1590 case IS_UNKNOWN:
1591 /* select only NULL values */
1592 selec = freq_null;
1593 break;
1594 case IS_NOT_UNKNOWN:
1595 /* select non-NULL values */
1596 selec = 1.0 - freq_null;
1597 break;
1598 case IS_TRUE:
1599 /* select only TRUE values */
1600 selec = freq_true;
1601 break;
1602 case IS_NOT_TRUE:
1603 /* select non-TRUE values */
1604 selec = 1.0 - freq_true;
1605 break;
1606 case IS_FALSE:
1607 /* select only FALSE values */
1608 selec = freq_false;
1609 break;
1610 case IS_NOT_FALSE:
1611 /* select non-FALSE values */
1612 selec = 1.0 - freq_false;
1613 break;
1614 default:
1615 elog(ERROR, "unrecognized booltesttype: %d",
1616 (int) booltesttype);
1617 selec = 0.0; /* Keep compiler quiet */
1618 break;
1619 }
1620
1621 free_attstatsslot(&sslot);
1622 }
1623 else
1624 {
1625 /*
1626 * No most-common-value info available. Still have null fraction
1627 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1628 * for null fraction and assume a 50-50 split of TRUE and FALSE.
1629 */
1630 switch (booltesttype)
1631 {
1632 case IS_UNKNOWN:
1633 /* select only NULL values */
1634 selec = freq_null;
1635 break;
1636 case IS_NOT_UNKNOWN:
1637 /* select non-NULL values */
1638 selec = 1.0 - freq_null;
1639 break;
1640 case IS_TRUE:
1641 case IS_FALSE:
1642 /* Assume we select half of the non-NULL values */
1643 selec = (1.0 - freq_null) / 2.0;
1644 break;
1645 case IS_NOT_TRUE:
1646 case IS_NOT_FALSE:
1647 /* Assume we select NULLs plus half of the non-NULLs */
1648 /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1649 selec = (freq_null + 1.0) / 2.0;
1650 break;
1651 default:
1652 elog(ERROR, "unrecognized booltesttype: %d",
1653 (int) booltesttype);
1654 selec = 0.0; /* Keep compiler quiet */
1655 break;
1656 }
1657 }
1658 }
1659 else
1660 {
1661 /*
1662 * If we can't get variable statistics for the argument, perhaps
1663 * clause_selectivity can do something with it. We ignore the
1664 * possibility of a NULL value when using clause_selectivity, and just
1665 * assume the value is either TRUE or FALSE.
1666 */
1667 switch (booltesttype)
1668 {
1669 case IS_UNKNOWN:
1670 selec = DEFAULT_UNK_SEL;
1671 break;
1672 case IS_NOT_UNKNOWN:
1673 selec = DEFAULT_NOT_UNK_SEL;
1674 break;
1675 case IS_TRUE:
1676 case IS_NOT_FALSE:
1677 selec = (double) clause_selectivity(root, arg,
1678 varRelid,
1679 jointype, sjinfo);
1680 break;
1681 case IS_FALSE:
1682 case IS_NOT_TRUE:
1683 selec = 1.0 - (double) clause_selectivity(root, arg,
1684 varRelid,
1685 jointype, sjinfo);
1686 break;
1687 default:
1688 elog(ERROR, "unrecognized booltesttype: %d",
1689 (int) booltesttype);
1690 selec = 0.0; /* Keep compiler quiet */
1691 break;
1692 }
1693 }
1694
1695 ReleaseVariableStats(vardata);
1696
1697 /* result should be in range, but make sure... */
1698 CLAMP_PROBABILITY(selec);
1699
1700 return (Selectivity) selec;
1701 }
1702
1703 /*
1704 * nulltestsel - Selectivity of NullTest Node.
1705 */
1706 Selectivity
1707 nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1708 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1709 {
1710 VariableStatData vardata;
1711 double selec;
1712
1713 examine_variable(root, arg, varRelid, &vardata);
1714
1715 if (HeapTupleIsValid(vardata.statsTuple))
1716 {
1717 Form_pg_statistic stats;
1718 double freq_null;
1719
1720 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1721 freq_null = stats->stanullfrac;
1722
1723 switch (nulltesttype)
1724 {
1725 case IS_NULL:
1726
1727 /*
1728 * Use freq_null directly.
1729 */
1730 selec = freq_null;
1731 break;
1732 case IS_NOT_NULL:
1733
1734 /*
1735 * Select not unknown (not null) values. Calculate from
1736 * freq_null.
1737 */
1738 selec = 1.0 - freq_null;
1739 break;
1740 default:
1741 elog(ERROR, "unrecognized nulltesttype: %d",
1742 (int) nulltesttype);
1743 return (Selectivity) 0; /* keep compiler quiet */
1744 }
1745 }
1746 else if (vardata.var && IsA(vardata.var, Var) &&
1747 ((Var *) vardata.var)->varattno < 0)
1748 {
1749 /*
1750 * There are no stats for system columns, but we know they are never
1751 * NULL.
1752 */
1753 selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
1754 }
1755 else
1756 {
1757 /*
1758 * No ANALYZE stats available, so make a guess
1759 */
1760 switch (nulltesttype)
1761 {
1762 case IS_NULL:
1763 selec = DEFAULT_UNK_SEL;
1764 break;
1765 case IS_NOT_NULL:
1766 selec = DEFAULT_NOT_UNK_SEL;
1767 break;
1768 default:
1769 elog(ERROR, "unrecognized nulltesttype: %d",
1770 (int) nulltesttype);
1771 return (Selectivity) 0; /* keep compiler quiet */
1772 }
1773 }
1774
1775 ReleaseVariableStats(vardata);
1776
1777 /* result should be in range, but make sure... */
1778 CLAMP_PROBABILITY(selec);
1779
1780 return (Selectivity) selec;
1781 }
1782
1783 /*
1784 * strip_array_coercion - strip binary-compatible relabeling from an array expr
1785 *
1786 * For array values, the parser normally generates ArrayCoerceExpr conversions,
1787 * but it seems possible that RelabelType might show up. Also, the planner
1788 * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1789 * so we need to be ready to deal with more than one level.
1790 */
1791 static Node *
1792 strip_array_coercion(Node *node)
1793 {
1794 for (;;)
1795 {
1796 if (node && IsA(node, ArrayCoerceExpr))
1797 {
1798 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
1799
1800 /*
1801 * If the per-element expression is just a RelabelType on top of
1802 * CaseTestExpr, then we know it's a binary-compatible relabeling.
1803 */
1804 if (IsA(acoerce->elemexpr, RelabelType) &&
1805 IsA(((RelabelType *) acoerce->elemexpr)->arg, CaseTestExpr))
1806 node = (Node *) acoerce->arg;
1807 else
1808 break;
1809 }
1810 else if (node && IsA(node, RelabelType))
1811 {
1812 /* We don't really expect this case, but may as well cope */
1813 node = (Node *) ((RelabelType *) node)->arg;
1814 }
1815 else
1816 break;
1817 }
1818 return node;
1819 }
1820
1821 /*
1822 * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1823 */
1824 Selectivity
1825 scalararraysel(PlannerInfo *root,
1826 ScalarArrayOpExpr *clause,
1827 bool is_join_clause,
1828 int varRelid,
1829 JoinType jointype,
1830 SpecialJoinInfo *sjinfo)
1831 {
1832 Oid operator = clause->opno;
1833 bool useOr = clause->useOr;
1834 bool isEquality = false;
1835 bool isInequality = false;
1836 Node *leftop;
1837 Node *rightop;
1838 Oid nominal_element_type;
1839 Oid nominal_element_collation;
1840 TypeCacheEntry *typentry;
1841 RegProcedure oprsel;
1842 FmgrInfo oprselproc;
1843 Selectivity s1;
1844 Selectivity s1disjoint;
1845
1846 /* First, deconstruct the expression */
1847 Assert(list_length(clause->args) == 2);
1848 leftop = (Node *) linitial(clause->args);
1849 rightop = (Node *) lsecond(clause->args);
1850
1851 /* aggressively reduce both sides to constants */
1852 leftop = estimate_expression_value(root, leftop);
1853 rightop = estimate_expression_value(root, rightop);
1854
1855 /* get nominal (after relabeling) element type of rightop */
1856 nominal_element_type = get_base_element_type(exprType(rightop));
1857 if (!OidIsValid(nominal_element_type))
1858 return (Selectivity) 0.5; /* probably shouldn't happen */
1859 /* get nominal collation, too, for generating constants */
1860 nominal_element_collation = exprCollation(rightop);
1861
1862 /* look through any binary-compatible relabeling of rightop */
1863 rightop = strip_array_coercion(rightop);
1864
1865 /*
1866 * Detect whether the operator is the default equality or inequality
1867 * operator of the array element type.
1868 */
1869 typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1870 if (OidIsValid(typentry->eq_opr))
1871 {
1872 if (operator == typentry->eq_opr)
1873 isEquality = true;
1874 else if (get_negator(operator) == typentry->eq_opr)
1875 isInequality = true;
1876 }
1877
1878 /*
1879 * If it is equality or inequality, we might be able to estimate this as a
1880 * form of array containment; for instance "const = ANY(column)" can be
1881 * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1882 * that, and returns the selectivity estimate if successful, or -1 if not.
1883 */
1884 if ((isEquality || isInequality) && !is_join_clause)
1885 {
1886 s1 = scalararraysel_containment(root, leftop, rightop,
1887 nominal_element_type,
1888 isEquality, useOr, varRelid);
1889 if (s1 >= 0.0)
1890 return s1;
1891 }
1892
1893 /*
1894 * Look up the underlying operator's selectivity estimator. Punt if it
1895 * hasn't got one.
1896 */
1897 if (is_join_clause)
1898 oprsel = get_oprjoin(operator);
1899 else
1900 oprsel = get_oprrest(operator);
1901 if (!oprsel)
1902 return (Selectivity) 0.5;
1903 fmgr_info(oprsel, &oprselproc);
1904
1905 /*
1906 * In the array-containment check above, we must only believe that an
1907 * operator is equality or inequality if it is the default btree equality
1908 * operator (or its negator) for the element type, since those are the
1909 * operators that array containment will use. But in what follows, we can
1910 * be a little laxer, and also believe that any operators using eqsel() or
1911 * neqsel() as selectivity estimator act like equality or inequality.
1912 */
1913 if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1914 isEquality = true;
1915 else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1916 isInequality = true;
1917
1918 /*
1919 * We consider three cases:
1920 *
1921 * 1. rightop is an Array constant: deconstruct the array, apply the
1922 * operator's selectivity function for each array element, and merge the
1923 * results in the same way that clausesel.c does for AND/OR combinations.
1924 *
1925 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1926 * function for each element of the ARRAY[] construct, and merge.
1927 *
1928 * 3. otherwise, make a guess ...
1929 */
1930 if (rightop && IsA(rightop, Const))
1931 {
1932 Datum arraydatum = ((Const *) rightop)->constvalue;
1933 bool arrayisnull = ((Const *) rightop)->constisnull;
1934 ArrayType *arrayval;
1935 int16 elmlen;
1936 bool elmbyval;
1937 char elmalign;
1938 int num_elems;
1939 Datum *elem_values;
1940 bool *elem_nulls;
1941 int i;
1942
1943 if (arrayisnull) /* qual can't succeed if null array */
1944 return (Selectivity) 0.0;
1945 arrayval = DatumGetArrayTypeP(arraydatum);
1946 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1947 &elmlen, &elmbyval, &elmalign);
1948 deconstruct_array(arrayval,
1949 ARR_ELEMTYPE(arrayval),
1950 elmlen, elmbyval, elmalign,
1951 &elem_values, &elem_nulls, &num_elems);
1952
1953 /*
1954 * For generic operators, we assume the probability of success is
1955 * independent for each array element. But for "= ANY" or "<> ALL",
1956 * if the array elements are distinct (which'd typically be the case)
1957 * then the probabilities are disjoint, and we should just sum them.
1958 *
1959 * If we were being really tense we would try to confirm that the
1960 * elements are all distinct, but that would be expensive and it
1961 * doesn't seem to be worth the cycles; it would amount to penalizing
1962 * well-written queries in favor of poorly-written ones. However, we
1963 * do protect ourselves a little bit by checking whether the
1964 * disjointness assumption leads to an impossible (out of range)
1965 * probability; if so, we fall back to the normal calculation.
1966 */
1967 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1968
1969 for (i = 0; i < num_elems; i++)
1970 {
1971 List *args;
1972 Selectivity s2;
1973
1974 args = list_make2(leftop,
1975 makeConst(nominal_element_type,
1976 -1,
1977 nominal_element_collation,
1978 elmlen,
1979 elem_values[i],
1980 elem_nulls[i],
1981 elmbyval));
1982 if (is_join_clause)
1983 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1984 clause->inputcollid,
1985 PointerGetDatum(root),
1986 ObjectIdGetDatum(operator),
1987 PointerGetDatum(args),
1988 Int16GetDatum(jointype),
1989 PointerGetDatum(sjinfo)));
1990 else
1991 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1992 clause->inputcollid,
1993 PointerGetDatum(root),
1994 ObjectIdGetDatum(operator),
1995 PointerGetDatum(args),
1996 Int32GetDatum(varRelid)));
1997
1998 if (useOr)
1999 {
2000 s1 = s1 + s2 - s1 * s2;
2001 if (isEquality)
2002 s1disjoint += s2;
2003 }
2004 else
2005 {
2006 s1 = s1 * s2;
2007 if (isInequality)
2008 s1disjoint += s2 - 1.0;
2009 }
2010 }
2011
2012 /* accept disjoint-probability estimate if in range */
2013 if ((useOr ? isEquality : isInequality) &&
2014 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2015 s1 = s1disjoint;
2016 }
2017 else if (rightop && IsA(rightop, ArrayExpr) &&
2018 !((ArrayExpr *) rightop)->multidims)
2019 {
2020 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2021 int16 elmlen;
2022 bool elmbyval;
2023 ListCell *l;
2024
2025 get_typlenbyval(arrayexpr->element_typeid,
2026 &elmlen, &elmbyval);
2027
2028 /*
2029 * We use the assumption of disjoint probabilities here too, although
2030 * the odds of equal array elements are rather higher if the elements
2031 * are not all constants (which they won't be, else constant folding
2032 * would have reduced the ArrayExpr to a Const). In this path it's
2033 * critical to have the sanity check on the s1disjoint estimate.
2034 */
2035 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2036
2037 foreach(l, arrayexpr->elements)
2038 {
2039 Node *elem = (Node *) lfirst(l);
2040 List *args;
2041 Selectivity s2;
2042
2043 /*
2044 * Theoretically, if elem isn't of nominal_element_type we should
2045 * insert a RelabelType, but it seems unlikely that any operator
2046 * estimation function would really care ...
2047 */
2048 args = list_make2(leftop, elem);
2049 if (is_join_clause)
2050 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2051 clause->inputcollid,
2052 PointerGetDatum(root),
2053 ObjectIdGetDatum(operator),
2054 PointerGetDatum(args),
2055 Int16GetDatum(jointype),
2056 PointerGetDatum(sjinfo)));
2057 else
2058 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2059 clause->inputcollid,
2060 PointerGetDatum(root),
2061 ObjectIdGetDatum(operator),
2062 PointerGetDatum(args),
2063 Int32GetDatum(varRelid)));
2064
2065 if (useOr)
2066 {
2067 s1 = s1 + s2 - s1 * s2;
2068 if (isEquality)
2069 s1disjoint += s2;
2070 }
2071 else
2072 {
2073 s1 = s1 * s2;
2074 if (isInequality)
2075 s1disjoint += s2 - 1.0;
2076 }
2077 }
2078
2079 /* accept disjoint-probability estimate if in range */
2080 if ((useOr ? isEquality : isInequality) &&
2081 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2082 s1 = s1disjoint;
2083 }
2084 else
2085 {
2086 CaseTestExpr *dummyexpr;
2087 List *args;
2088 Selectivity s2;
2089 int i;
2090
2091 /*
2092 * We need a dummy rightop to pass to the operator selectivity
2093 * routine. It can be pretty much anything that doesn't look like a
2094 * constant; CaseTestExpr is a convenient choice.
2095 */
2096 dummyexpr = makeNode(CaseTestExpr);
2097 dummyexpr->typeId = nominal_element_type;
2098 dummyexpr->typeMod = -1;
2099 dummyexpr->collation = clause->inputcollid;
2100 args = list_make2(leftop, dummyexpr);
2101 if (is_join_clause)
2102 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2103 clause->inputcollid,
2104 PointerGetDatum(root),
2105 ObjectIdGetDatum(operator),
2106 PointerGetDatum(args),
2107 Int16GetDatum(jointype),
2108 PointerGetDatum(sjinfo)));
2109 else
2110 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2111 clause->inputcollid,
2112 PointerGetDatum(root),
2113 ObjectIdGetDatum(operator),
2114 PointerGetDatum(args),
2115 Int32GetDatum(varRelid)));
2116 s1 = useOr ? 0.0 : 1.0;
2117
2118 /*
2119 * Arbitrarily assume 10 elements in the eventual array value (see
2120 * also estimate_array_length). We don't risk an assumption of
2121 * disjoint probabilities here.
2122 */
2123 for (i = 0; i < 10; i++)
2124 {
2125 if (useOr)
2126 s1 = s1 + s2 - s1 * s2;
2127 else
2128 s1 = s1 * s2;
2129 }
2130 }
2131
2132 /* result should be in range, but make sure... */
2133 CLAMP_PROBABILITY(s1);
2134
2135 return s1;
2136 }
2137
2138 /*
2139 * Estimate number of elements in the array yielded by an expression.
2140 *
2141 * Note: the result is integral, but we use "double" to avoid overflow
2142 * concerns. Most callers will use it in double-type expressions anyway.
2143 *
2144 * Note: in some code paths root can be passed as NULL, resulting in
2145 * slightly worse estimates.
2146 */
2147 double
2148 estimate_array_length(PlannerInfo *root, Node *arrayexpr)
2149 {
2150 /* look through any binary-compatible relabeling of arrayexpr */
2151 arrayexpr = strip_array_coercion(arrayexpr);
2152
2153 if (arrayexpr && IsA(arrayexpr, Const))
2154 {
2155 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2156 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2157 ArrayType *arrayval;
2158
2159 if (arrayisnull)
2160 return 0;
2161 arrayval = DatumGetArrayTypeP(arraydatum);
2162 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2163 }
2164 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2165 !((ArrayExpr *) arrayexpr)->multidims)
2166 {
2167 return list_length(((ArrayExpr *) arrayexpr)->elements);
2168 }
2169 else if (arrayexpr && root)
2170 {
2171 /* See if we can find any statistics about it */
2172 VariableStatData vardata;
2173 AttStatsSlot sslot;
2174 double nelem = 0;
2175
2176 /*
2177 * Skip calling examine_variable for Var with varno 0, which has no
2178 * valid relation entry and would error in find_base_rel. Such a Var
2179 * can appear when a nested set operation's output type doesn't match
2180 * the parent's expected type, because recurse_set_operations builds a
2181 * projection target list using generate_setop_tlist with varno 0, and
2182 * if the required type coercion involves an ArrayCoerceExpr, we can
2183 * be called on that Var.
2184 */
2185 if (IsA(arrayexpr, Var) && ((Var *) arrayexpr)->varno == 0)
2186 return 10; /* default guess, should match scalararraysel */
2187
2188 examine_variable(root, arrayexpr, 0, &vardata);
2189 if (HeapTupleIsValid(vardata.statsTuple))
2190 {
2191 /*
2192 * Found stats, so use the average element count, which is stored
2193 * in the last stanumbers element of the DECHIST statistics.
2194 * Actually that is the average count of *distinct* elements;
2195 * perhaps we should scale it up somewhat?
2196 */
2197 if (get_attstatsslot(&sslot, vardata.statsTuple,
2198 STATISTIC_KIND_DECHIST, InvalidOid,
2199 ATTSTATSSLOT_NUMBERS))
2200 {
2201 if (sslot.nnumbers > 0)
2202 nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2203 free_attstatsslot(&sslot);
2204 }
2205 }
2206 ReleaseVariableStats(vardata);
2207
2208 if (nelem > 0)
2209 return nelem;
2210 }
2211
2212 /* Else use a default guess --- this should match scalararraysel */
2213 return 10;
2214 }
2215
2216 /*
2217 * rowcomparesel - Selectivity of RowCompareExpr Node.
2218 *
2219 * We estimate RowCompare selectivity by considering just the first (high
2220 * order) columns, which makes it equivalent to an ordinary OpExpr. While
2221 * this estimate could be refined by considering additional columns, it
2222 * seems unlikely that we could do a lot better without multi-column
2223 * statistics.
2224 */
2225 Selectivity
2226 rowcomparesel(PlannerInfo *root,
2227 RowCompareExpr *clause,
2228 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
2229 {
2230 Selectivity s1;
2231 Oid opno = linitial_oid(clause->opnos);
2232 Oid inputcollid = linitial_oid(clause->inputcollids);
2233 List *opargs;
2234 bool is_join_clause;
2235
2236 /* Build equivalent arg list for single operator */
2237 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2238
2239 /*
2240 * Decide if it's a join clause. This should match clausesel.c's
2241 * treat_as_join_clause(), except that we intentionally consider only the
2242 * leading columns and not the rest of the clause.
2243 */
2244 if (varRelid != 0)
2245 {
2246 /*
2247 * Caller is forcing restriction mode (eg, because we are examining an
2248 * inner indexscan qual).
2249 */
2250 is_join_clause = false;
2251 }
2252 else if (sjinfo == NULL)
2253 {
2254 /*
2255 * It must be a restriction clause, since it's being evaluated at a
2256 * scan node.
2257 */
2258 is_join_clause = false;
2259 }
2260 else
2261 {
2262 /*
2263 * Otherwise, it's a join if there's more than one base relation used.
2264 */
2265 is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2266 }
2267
2268 if (is_join_clause)
2269 {
2270 /* Estimate selectivity for a join clause. */
2271 s1 = join_selectivity(root, opno,
2272 opargs,
2273 inputcollid,
2274 jointype,
2275 sjinfo);
2276 }
2277 else
2278 {
2279 /* Estimate selectivity for a restriction clause. */
2280 s1 = restriction_selectivity(root, opno,
2281 opargs,
2282 inputcollid,
2283 varRelid);
2284 }
2285
2286 return s1;
2287 }
2288
2289 /*
2290 * eqjoinsel - Join selectivity of "="
2291 */
2292 Datum
2293 eqjoinsel(PG_FUNCTION_ARGS)
2294 {
2295 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2296 Oid operator = PG_GETARG_OID(1);
2297 List *args = (List *) PG_GETARG_POINTER(2);
2298
2299 #ifdef NOT_USED
2300 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2301 #endif
2302 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2303 Oid collation = PG_GET_COLLATION();
2304 double selec;
2305 double selec_inner;
2306 VariableStatData vardata1;
2307 VariableStatData vardata2;
2308 double nd1;
2309 double nd2;
2310 bool isdefault1;
2311 bool isdefault2;
2312 Oid opfuncoid;
2313 AttStatsSlot sslot1;
2314 AttStatsSlot sslot2;
2315 Form_pg_statistic stats1 = NULL;
2316 Form_pg_statistic stats2 = NULL;
2317 bool have_mcvs1 = false;
2318 bool have_mcvs2 = false;
2319 bool get_mcv_stats;
2320 bool join_is_reversed;
2321 RelOptInfo *inner_rel;
2322
2323 get_join_variables(root, args, sjinfo,
2324 &vardata1, &vardata2, &join_is_reversed);
2325
2326 nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2327 nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2328
2329 opfuncoid = get_opcode(operator);
2330
2331 memset(&sslot1, 0, sizeof(sslot1));
2332 memset(&sslot2, 0, sizeof(sslot2));
2333
2334 /*
2335 * There is no use in fetching one side's MCVs if we lack MCVs for the
2336 * other side, so do a quick check to verify that both stats exist.
2337 */
2338 get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
2339 HeapTupleIsValid(vardata2.statsTuple) &&
2340 get_attstatsslot(&sslot1, vardata1.statsTuple,
2341 STATISTIC_KIND_MCV, InvalidOid,
2342 0) &&
2343 get_attstatsslot(&sslot2, vardata2.statsTuple,
2344 STATISTIC_KIND_MCV, InvalidOid,
2345 0));
2346
2347 if (HeapTupleIsValid(vardata1.statsTuple))
2348 {
2349 /* note we allow use of nullfrac regardless of security check */
2350 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2351 if (get_mcv_stats &&
2352 statistic_proc_security_check(&vardata1, opfuncoid))
2353 have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2354 STATISTIC_KIND_MCV, InvalidOid,
2355 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
2356 }
2357
2358 if (HeapTupleIsValid(vardata2.statsTuple))
2359 {
2360 /* note we allow use of nullfrac regardless of security check */
2361 stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2362 if (get_mcv_stats &&
2363 statistic_proc_security_check(&vardata2, opfuncoid))
2364 have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2365 STATISTIC_KIND_MCV, InvalidOid,
2366 ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
2367 }
2368
2369 /* We need to compute the inner-join selectivity in all cases */
2370 selec_inner = eqjoinsel_inner(opfuncoid, collation,
2371 &vardata1, &vardata2,
2372 nd1, nd2,
2373 isdefault1, isdefault2,
2374 &sslot1, &sslot2,
2375 stats1, stats2,
2376 have_mcvs1, have_mcvs2);
2377
2378 switch (sjinfo->jointype)
2379 {
2380 case JOIN_INNER:
2381 case JOIN_LEFT:
2382 case JOIN_FULL:
2383 selec = selec_inner;
2384 break;
2385 case JOIN_SEMI:
2386 case JOIN_ANTI:
2387
2388 /*
2389 * Look up the join's inner relation. min_righthand is sufficient
2390 * information because neither SEMI nor ANTI joins permit any
2391 * reassociation into or out of their RHS, so the righthand will
2392 * always be exactly that set of rels.
2393 */
2394 inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2395
2396 if (!join_is_reversed)
2397 selec = eqjoinsel_semi(opfuncoid, collation,
2398 &vardata1, &vardata2,
2399 nd1, nd2,
2400 isdefault1, isdefault2,
2401 &sslot1, &sslot2,
2402 stats1, stats2,
2403 have_mcvs1, have_mcvs2,
2404 inner_rel);
2405 else
2406 {
2407 Oid commop = get_commutator(operator);
2408 Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2409
2410 selec = eqjoinsel_semi(commopfuncoid, collation,
2411 &vardata2, &vardata1,
2412 nd2, nd1,
2413 isdefault2, isdefault1,
2414 &sslot2, &sslot1,
2415 stats2, stats1,
2416 have_mcvs2, have_mcvs1,
2417 inner_rel);
2418 }
2419
2420 /*
2421 * We should never estimate the output of a semijoin to be more
2422 * rows than we estimate for an inner join with the same input
2423 * rels and join condition; it's obviously impossible for that to
2424 * happen. The former estimate is N1 * Ssemi while the latter is
2425 * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner. Doing
2426 * this is worthwhile because of the shakier estimation rules we
2427 * use in eqjoinsel_semi, particularly in cases where it has to
2428 * punt entirely.
2429 */
2430 selec = Min(selec, inner_rel->rows * selec_inner);
2431 break;
2432 default:
2433 /* other values not expected here */
2434 elog(ERROR, "unrecognized join type: %d",
2435 (int) sjinfo->jointype);
2436 selec = 0; /* keep compiler quiet */
2437 break;
2438 }
2439
2440 free_attstatsslot(&sslot1);
2441 free_attstatsslot(&sslot2);
2442
2443 ReleaseVariableStats(vardata1);
2444 ReleaseVariableStats(vardata2);
2445
2446 CLAMP_PROBABILITY(selec);
2447
2448 PG_RETURN_FLOAT8((float8) selec);
2449 }
2450
2451 /*
2452 * eqjoinsel_inner --- eqjoinsel for normal inner join
2453 *
2454 * We also use this for LEFT/FULL outer joins; it's not presently clear
2455 * that it's worth trying to distinguish them here.
2456 */
2457 static double
2458 eqjoinsel_inner(Oid opfuncoid, Oid collation,
2459 VariableStatData *vardata1, VariableStatData *vardata2,
2460 double nd1, double nd2,
2461 bool isdefault1, bool isdefault2,
2462 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2463 Form_pg_statistic stats1, Form_pg_statistic stats2,
2464 bool have_mcvs1, bool have_mcvs2)
2465 {
2466 double selec;
2467
2468 if (have_mcvs1 && have_mcvs2)
2469 {
2470 /*
2471 * We have most-common-value lists for both relations. Run through
2472 * the lists to see which MCVs actually join to each other with the
2473 * given operator. This allows us to determine the exact join
2474 * selectivity for the portion of the relations represented by the MCV
2475 * lists. We still have to estimate for the remaining population, but
2476 * in a skewed distribution this gives us a big leg up in accuracy.
2477 * For motivation see the analysis in Y. Ioannidis and S.
2478 * Christodoulakis, "On the propagation of errors in the size of join
2479 * results", Technical Report 1018, Computer Science Dept., University
2480 * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2481 */
2482 LOCAL_FCINFO(fcinfo, 2);
2483 FmgrInfo eqproc;
2484 bool *hasmatch1;
2485 bool *hasmatch2;
2486 double nullfrac1 = stats1->stanullfrac;
2487 double nullfrac2 = stats2->stanullfrac;
2488 double matchprodfreq,
2489 matchfreq1,
2490 matchfreq2,
2491 unmatchfreq1,
2492 unmatchfreq2,
2493 otherfreq1,
2494 otherfreq2,
2495 totalsel1,
2496 totalsel2;
2497 int i,
2498 nmatches;
2499
2500 fmgr_info(opfuncoid, &eqproc);
2501
2502 /*
2503 * Save a few cycles by setting up the fcinfo struct just once. Using
2504 * FunctionCallInvoke directly also avoids failure if the eqproc
2505 * returns NULL, though really equality functions should never do
2506 * that.
2507 */
2508 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2509 NULL, NULL);
2510 fcinfo->args[0].isnull = false;
2511 fcinfo->args[1].isnull = false;
2512
2513 hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2514 hasmatch2 = (bool *) palloc0(sslot2->nvalues * sizeof(bool));
2515
2516 /*
2517 * Note we assume that each MCV will match at most one member of the
2518 * other MCV list. If the operator isn't really equality, there could
2519 * be multiple matches --- but we don't look for them, both for speed
2520 * and because the math wouldn't add up...
2521 */
2522 matchprodfreq = 0.0;
2523 nmatches = 0;
2524 for (i = 0; i < sslot1->nvalues; i++)
2525 {
2526 int j;
2527
2528 fcinfo->args[0].value = sslot1->values[i];
2529
2530 for (j = 0; j < sslot2->nvalues; j++)
2531 {
2532 Datum fresult;
2533
2534 if (hasmatch2[j])
2535 continue;
2536 fcinfo->args[1].value = sslot2->values[j];
2537 fcinfo->isnull = false;
2538 fresult = FunctionCallInvoke(fcinfo);
2539 if (!fcinfo->isnull && DatumGetBool(fresult))
2540 {
2541 hasmatch1[i] = hasmatch2[j] = true;
2542 matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2543 nmatches++;
2544 break;
2545 }
2546 }
2547 }
2548 CLAMP_PROBABILITY(matchprodfreq);
2549 /* Sum up frequencies of matched and unmatched MCVs */
2550 matchfreq1 = unmatchfreq1 = 0.0;
2551 for (i = 0; i < sslot1->nvalues; i++)
2552 {
2553 if (hasmatch1[i])
2554 matchfreq1 += sslot1->numbers[i];
2555 else
2556 unmatchfreq1 += sslot1->numbers[i];
2557 }
2558 CLAMP_PROBABILITY(matchfreq1);
2559 CLAMP_PROBABILITY(unmatchfreq1);
2560 matchfreq2 = unmatchfreq2 = 0.0;
2561 for (i = 0; i < sslot2->nvalues; i++)
2562 {
2563 if (hasmatch2[i])
2564 matchfreq2 += sslot2->numbers[i];
2565 else
2566 unmatchfreq2 += sslot2->numbers[i];
2567 }
2568 CLAMP_PROBABILITY(matchfreq2);
2569 CLAMP_PROBABILITY(unmatchfreq2);
2570 pfree(hasmatch1);
2571 pfree(hasmatch2);
2572
2573 /*
2574 * Compute total frequency of non-null values that are not in the MCV
2575 * lists.
2576 */
2577 otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2578 otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2579 CLAMP_PROBABILITY(otherfreq1);
2580 CLAMP_PROBABILITY(otherfreq2);
2581
2582 /*
2583 * We can estimate the total selectivity from the point of view of
2584 * relation 1 as: the known selectivity for matched MCVs, plus
2585 * unmatched MCVs that are assumed to match against random members of
2586 * relation 2's non-MCV population, plus non-MCV values that are
2587 * assumed to match against random members of relation 2's unmatched
2588 * MCVs plus non-MCV values.
2589 */
2590 totalsel1 = matchprodfreq;
2591 if (nd2 > sslot2->nvalues)
2592 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2593 if (nd2 > nmatches)
2594 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2595 (nd2 - nmatches);
2596 /* Same estimate from the point of view of relation 2. */
2597 totalsel2 = matchprodfreq;
2598 if (nd1 > sslot1->nvalues)
2599 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2600 if (nd1 > nmatches)
2601 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2602 (nd1 - nmatches);
2603
2604 /*
2605 * Use the smaller of the two estimates. This can be justified in
2606 * essentially the same terms as given below for the no-stats case: to
2607 * a first approximation, we are estimating from the point of view of
2608 * the relation with smaller nd.
2609 */
2610 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2611 }
2612 else
2613 {
2614 /*
2615 * We do not have MCV lists for both sides. Estimate the join
2616 * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2617 * is plausible if we assume that the join operator is strict and the
2618 * non-null values are about equally distributed: a given non-null
2619 * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2620 * of rel2, so total join rows are at most
2621 * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2622 * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2623 * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2624 * with MIN() is an upper bound. Using the MIN() means we estimate
2625 * from the point of view of the relation with smaller nd (since the
2626 * larger nd is determining the MIN). It is reasonable to assume that
2627 * most tuples in this rel will have join partners, so the bound is
2628 * probably reasonably tight and should be taken as-is.
2629 *
2630 * XXX Can we be smarter if we have an MCV list for just one side? It
2631 * seems that if we assume equal distribution for the other side, we
2632 * end up with the same answer anyway.
2633 */
2634 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2635 double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2636
2637 selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2638 if (nd1 > nd2)
2639 selec /= nd1;
2640 else
2641 selec /= nd2;
2642 }
2643
2644 return selec;
2645 }
2646
2647 /*
2648 * eqjoinsel_semi --- eqjoinsel for semi join
2649 *
2650 * (Also used for anti join, which we are supposed to estimate the same way.)
2651 * Caller has ensured that vardata1 is the LHS variable.
2652 * Unlike eqjoinsel_inner, we have to cope with opfuncoid being InvalidOid.
2653 */
2654 static double
2655 eqjoinsel_semi(Oid opfuncoid, Oid collation,
2656 VariableStatData *vardata1, VariableStatData *vardata2,
2657 double nd1, double nd2,
2658 bool isdefault1, bool isdefault2,
2659 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2660 Form_pg_statistic stats1, Form_pg_statistic stats2,
2661 bool have_mcvs1, bool have_mcvs2,
2662 RelOptInfo *inner_rel)
2663 {
2664 double selec;
2665
2666 /*
2667 * We clamp nd2 to be not more than what we estimate the inner relation's
2668 * size to be. This is intuitively somewhat reasonable since obviously
2669 * there can't be more than that many distinct values coming from the
2670 * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2671 * likewise) is that this is the only pathway by which restriction clauses
2672 * applied to the inner rel will affect the join result size estimate,
2673 * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2674 * only the outer rel's size. If we clamped nd1 we'd be double-counting
2675 * the selectivity of outer-rel restrictions.
2676 *
2677 * We can apply this clamping both with respect to the base relation from
2678 * which the join variable comes (if there is just one), and to the
2679 * immediate inner input relation of the current join.
2680 *
2681 * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2682 * great, maybe, but it didn't come out of nowhere either. This is most
2683 * helpful when the inner relation is empty and consequently has no stats.
2684 */
2685 if (vardata2->rel)
2686 {
2687 if (nd2 >= vardata2->rel->rows)
2688 {
2689 nd2 = vardata2->rel->rows;
2690 isdefault2 = false;
2691 }
2692 }
2693 if (nd2 >= inner_rel->rows)
2694 {
2695 nd2 = inner_rel->rows;
2696 isdefault2 = false;
2697 }
2698
2699 if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2700 {
2701 /*
2702 * We have most-common-value lists for both relations. Run through
2703 * the lists to see which MCVs actually join to each other with the
2704 * given operator. This allows us to determine the exact join
2705 * selectivity for the portion of the relations represented by the MCV
2706 * lists. We still have to estimate for the remaining population, but
2707 * in a skewed distribution this gives us a big leg up in accuracy.
2708 */
2709 LOCAL_FCINFO(fcinfo, 2);
2710 FmgrInfo eqproc;
2711 bool *hasmatch1;
2712 bool *hasmatch2;
2713 double nullfrac1 = stats1->stanullfrac;
2714 double matchfreq1,
2715 uncertainfrac,
2716 uncertain;
2717 int i,
2718 nmatches,
2719 clamped_nvalues2;
2720
2721 /*
2722 * The clamping above could have resulted in nd2 being less than
2723 * sslot2->nvalues; in which case, we assume that precisely the nd2
2724 * most common values in the relation will appear in the join input,
2725 * and so compare to only the first nd2 members of the MCV list. Of
2726 * course this is frequently wrong, but it's the best bet we can make.
2727 */
2728 clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2729
2730 fmgr_info(opfuncoid, &eqproc);
2731
2732 /*
2733 * Save a few cycles by setting up the fcinfo struct just once. Using
2734 * FunctionCallInvoke directly also avoids failure if the eqproc
2735 * returns NULL, though really equality functions should never do
2736 * that.
2737 */
2738 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2739 NULL, NULL);
2740 fcinfo->args[0].isnull = false;
2741 fcinfo->args[1].isnull = false;
2742
2743 hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2744 hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2745
2746 /*
2747 * Note we assume that each MCV will match at most one member of the
2748 * other MCV list. If the operator isn't really equality, there could
2749 * be multiple matches --- but we don't look for them, both for speed
2750 * and because the math wouldn't add up...
2751 */
2752 nmatches = 0;
2753 for (i = 0; i < sslot1->nvalues; i++)
2754 {
2755 int j;
2756
2757 fcinfo->args[0].value = sslot1->values[i];
2758
2759 for (j = 0; j < clamped_nvalues2; j++)
2760 {
2761 Datum fresult;
2762
2763 if (hasmatch2[j])
2764 continue;
2765 fcinfo->args[1].value = sslot2->values[j];
2766 fcinfo->isnull = false;
2767 fresult = FunctionCallInvoke(fcinfo);
2768 if (!fcinfo->isnull && DatumGetBool(fresult))
2769 {
2770 hasmatch1[i] = hasmatch2[j] = true;
2771 nmatches++;
2772 break;
2773 }
2774 }
2775 }
2776 /* Sum up frequencies of matched MCVs */
2777 matchfreq1 = 0.0;
2778 for (i = 0; i < sslot1->nvalues; i++)
2779 {
2780 if (hasmatch1[i])
2781 matchfreq1 += sslot1->numbers[i];
2782 }
2783 CLAMP_PROBABILITY(matchfreq1);
2784 pfree(hasmatch1);
2785 pfree(hasmatch2);
2786
2787 /*
2788 * Now we need to estimate the fraction of relation 1 that has at
2789 * least one join partner. We know for certain that the matched MCVs
2790 * do, so that gives us a lower bound, but we're really in the dark
2791 * about everything else. Our crude approach is: if nd1 <= nd2 then
2792 * assume all non-null rel1 rows have join partners, else assume for
2793 * the uncertain rows that a fraction nd2/nd1 have join partners. We
2794 * can discount the known-matched MCVs from the distinct-values counts
2795 * before doing the division.
2796 *
2797 * Crude as the above is, it's completely useless if we don't have
2798 * reliable ndistinct values for both sides. Hence, if either nd1 or
2799 * nd2 is default, punt and assume half of the uncertain rows have
2800 * join partners.
2801 */
2802 if (!isdefault1 && !isdefault2)
2803 {
2804 nd1 -= nmatches;
2805 nd2 -= nmatches;
2806 if (nd1 <= nd2 || nd2 < 0)
2807 uncertainfrac = 1.0;
2808 else
2809 uncertainfrac = nd2 / nd1;
2810 }
2811 else
2812 uncertainfrac = 0.5;
2813 uncertain = 1.0 - matchfreq1 - nullfrac1;
2814 CLAMP_PROBABILITY(uncertain);
2815 selec = matchfreq1 + uncertainfrac * uncertain;
2816 }
2817 else
2818 {
2819 /*
2820 * Without MCV lists for both sides, we can only use the heuristic
2821 * about nd1 vs nd2.
2822 */
2823 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2824
2825 if (!isdefault1 && !isdefault2)
2826 {
2827 if (nd1 <= nd2 || nd2 < 0)
2828 selec = 1.0 - nullfrac1;
2829 else
2830 selec = (nd2 / nd1) * (1.0 - nullfrac1);
2831 }
2832 else
2833 selec = 0.5 * (1.0 - nullfrac1);
2834 }
2835
2836 return selec;
2837 }
2838
2839 /*
2840 * neqjoinsel - Join selectivity of "!="
2841 */
2842 Datum
2843 neqjoinsel(PG_FUNCTION_ARGS)
2844 {
2845 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2846 Oid operator = PG_GETARG_OID(1);
2847 List *args = (List *) PG_GETARG_POINTER(2);
2848 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2849 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2850 Oid collation = PG_GET_COLLATION();
2851 float8 result;
2852
2853 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2854 {
2855 /*
2856 * For semi-joins, if there is more than one distinct value in the RHS
2857 * relation then every non-null LHS row must find a row to join since
2858 * it can only be equal to one of them. We'll assume that there is
2859 * always more than one distinct RHS value for the sake of stability,
2860 * though in theory we could have special cases for empty RHS
2861 * (selectivity = 0) and single-distinct-value RHS (selectivity =
2862 * fraction of LHS that has the same value as the single RHS value).
2863 *
2864 * For anti-joins, if we use the same assumption that there is more
2865 * than one distinct key in the RHS relation, then every non-null LHS
2866 * row must be suppressed by the anti-join.
2867 *
2868 * So either way, the selectivity estimate should be 1 - nullfrac.
2869 */
2870 VariableStatData leftvar;
2871 VariableStatData rightvar;
2872 bool reversed;
2873 HeapTuple statsTuple;
2874 double nullfrac;
2875
2876 get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
2877 statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
2878 if (HeapTupleIsValid(statsTuple))
2879 nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
2880 else
2881 nullfrac = 0.0;
2882 ReleaseVariableStats(leftvar);
2883 ReleaseVariableStats(rightvar);
2884
2885 result = 1.0 - nullfrac;
2886 }
2887 else
2888 {
2889 /*
2890 * We want 1 - eqjoinsel() where the equality operator is the one
2891 * associated with this != operator, that is, its negator.
2892 */
2893 Oid eqop = get_negator(operator);
2894
2895 if (eqop)
2896 {
2897 result =
2898 DatumGetFloat8(DirectFunctionCall5Coll(eqjoinsel,
2899 collation,
2900 PointerGetDatum(root),
2901 ObjectIdGetDatum(eqop),
2902 PointerGetDatum(args),
2903 Int16GetDatum(jointype),
2904 PointerGetDatum(sjinfo)));
2905 }
2906 else
2907 {
2908 /* Use default selectivity (should we raise an error instead?) */
2909 result = DEFAULT_EQ_SEL;
2910 }
2911 result = 1.0 - result;
2912 }
2913
2914 PG_RETURN_FLOAT8(result);
2915 }
2916
2917 /*
2918 * scalarltjoinsel - Join selectivity of "<" for scalars
2919 */
2920 Datum
2921 scalarltjoinsel(PG_FUNCTION_ARGS)
2922 {
2923 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2924 }
2925
2926 /*
2927 * scalarlejoinsel - Join selectivity of "<=" for scalars
2928 */
2929 Datum
2930 scalarlejoinsel(PG_FUNCTION_ARGS)
2931 {
2932 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2933 }
2934
2935 /*
2936 * scalargtjoinsel - Join selectivity of ">" for scalars
2937 */
2938 Datum
2939 scalargtjoinsel(PG_FUNCTION_ARGS)
2940 {
2941 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2942 }
2943
2944 /*
2945 * scalargejoinsel - Join selectivity of ">=" for scalars
2946 */
2947 Datum
2948 scalargejoinsel(PG_FUNCTION_ARGS)
2949 {
2950 PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2951 }
2952
2953
2954 /*
2955 * mergejoinscansel - Scan selectivity of merge join.
2956 *
2957 * A merge join will stop as soon as it exhausts either input stream.
2958 * Therefore, if we can estimate the ranges of both input variables,
2959 * we can estimate how much of the input will actually be read. This
2960 * can have a considerable impact on the cost when using indexscans.
2961 *
2962 * Also, we can estimate how much of each input has to be read before the
2963 * first join pair is found, which will affect the join's startup time.
2964 *
2965 * clause should be a clause already known to be mergejoinable. opfamily,
2966 * cmptype, and nulls_first specify the sort ordering being used.
2967 *
2968 * The outputs are:
2969 * *leftstart is set to the fraction of the left-hand variable expected
2970 * to be scanned before the first join pair is found (0 to 1).
2971 * *leftend is set to the fraction of the left-hand variable expected
2972 * to be scanned before the join terminates (0 to 1).
2973 * *rightstart, *rightend similarly for the right-hand variable.
2974 */
2975 void
2976 mergejoinscansel(PlannerInfo *root, Node *clause,
2977 Oid opfamily, CompareType cmptype, bool nulls_first,
2978 Selectivity *leftstart, Selectivity *leftend,
2979 Selectivity *rightstart, Selectivity *rightend)
2980 {
2981 Node *left,
2982 *right;
2983 VariableStatData leftvar,
2984 rightvar;
2985 Oid opmethod;
2986 int op_strategy;
2987 Oid op_lefttype;
2988 Oid op_righttype;
2989 Oid opno,
2990 collation,
2991 lsortop,
2992 rsortop,
2993 lstatop,
2994 rstatop,
2995 ltop,
2996 leop,
2997 revltop,
2998 revleop;
2999 StrategyNumber ltstrat,
3000 lestrat,
3001 gtstrat,
3002 gestrat;
3003 bool isgt;
3004 Datum leftmin,
3005 leftmax,
3006 rightmin,
3007 rightmax;
3008 double selec;
3009
3010 /* Set default results if we can't figure anything out. */
3011 /* XXX should default "start" fraction be a bit more than 0? */
3012 *leftstart = *rightstart = 0.0;
3013 *leftend = *rightend = 1.0;
3014
3015 /* Deconstruct the merge clause */
3016 if (!is_opclause(clause))
3017 return; /* shouldn't happen */
3018 opno = ((OpExpr *) clause)->opno;
3019 collation = ((OpExpr *) clause)->inputcollid;
3020 left = get_leftop((Expr *) clause);
3021 right = get_rightop((Expr *) clause);
3022 if (!right)
3023 return; /* shouldn't happen */
3024
3025 /* Look for stats for the inputs */
3026 examine_variable(root, left, 0, &leftvar);
3027 examine_variable(root, right, 0, &rightvar);
3028
3029 opmethod = get_opfamily_method(opfamily);
3030
3031 /* Extract the operator's declared left/right datatypes */
3032 get_op_opfamily_properties(opno, opfamily, false,
3033 &op_strategy,
3034 &op_lefttype,
3035 &op_righttype);
3036 Assert(IndexAmTranslateStrategy(op_strategy, opmethod, opfamily, true) == COMPARE_EQ);
3037
3038 /*
3039 * Look up the various operators we need. If we don't find them all, it
3040 * probably means the opfamily is broken, but we just fail silently.
3041 *
3042 * Note: we expect that pg_statistic histograms will be sorted by the '<'
3043 * operator, regardless of which sort direction we are considering.
3044 */
3045 switch (cmptype)
3046 {
3047 case COMPARE_LT:
3048 isgt = false;
3049 ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
3050 lestrat = IndexAmTranslateCompareType(COMPARE_LE, opmethod, opfamily, true);
3051 if (op_lefttype == op_righttype)
3052 {
3053 /* easy case */
3054 ltop = get_opfamily_member(opfamily,
3055 op_lefttype, op_righttype,
3056 ltstrat);
3057 leop = get_opfamily_member(opfamily,
3058 op_lefttype, op_righttype,
3059 lestrat);
3060 lsortop = ltop;
3061 rsortop = ltop;
3062 lstatop = lsortop;
3063 rstatop = rsortop;
3064 revltop = ltop;
3065 revleop = leop;
3066 }
3067 else
3068 {
3069 ltop = get_opfamily_member(opfamily,
3070 op_lefttype, op_righttype,
3071 ltstrat);
3072 leop = get_opfamily_member(opfamily,
3073 op_lefttype, op_righttype,
3074 lestrat);
3075 lsortop = get_opfamily_member(opfamily,
3076 op_lefttype, op_lefttype,
3077 ltstrat);
3078 rsortop = get_opfamily_member(opfamily,
3079 op_righttype, op_righttype,
3080 ltstrat);
3081 lstatop = lsortop;
3082 rstatop = rsortop;
3083 revltop = get_opfamily_member(opfamily,
3084 op_righttype, op_lefttype,
3085 ltstrat);
3086 revleop = get_opfamily_member(opfamily,
3087 op_righttype, op_lefttype,
3088 lestrat);
3089 }
3090 break;
3091 case COMPARE_GT:
3092 /* descending-order case */
3093 isgt = true;
3094 ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
3095 gtstrat = IndexAmTranslateCompareType(COMPARE_GT, opmethod, opfamily, true);
3096 gestrat = IndexAmTranslateCompareType(COMPARE_GE, opmethod, opfamily, true);
3097 if (op_lefttype == op_righttype)
3098 {
3099 /* easy case */
3100 ltop = get_opfamily_member(opfamily,
3101 op_lefttype, op_righttype,
3102 gtstrat);
3103 leop = get_opfamily_member(opfamily,
3104 op_lefttype, op_righttype,
3105 gestrat);
3106 lsortop = ltop;
3107 rsortop = ltop;
3108 lstatop = get_opfamily_member(opfamily,
3109 op_lefttype, op_lefttype,
3110 ltstrat);
3111 rstatop = lstatop;
3112 revltop = ltop;
3113 revleop = leop;
3114 }
3115 else
3116 {
3117 ltop = get_opfamily_member(opfamily,
3118 op_lefttype, op_righttype,
3119 gtstrat);
3120 leop = get_opfamily_member(opfamily,
3121 op_lefttype, op_righttype,
3122 gestrat);
3123 lsortop = get_opfamily_member(opfamily,
3124 op_lefttype, op_lefttype,
3125 gtstrat);
3126 rsortop = get_opfamily_member(opfamily,
3127 op_righttype, op_righttype,
3128 gtstrat);
3129 lstatop = get_opfamily_member(opfamily,
3130 op_lefttype, op_lefttype,
3131 ltstrat);
3132 rstatop = get_opfamily_member(opfamily,
3133 op_righttype, op_righttype,
3134 ltstrat);
3135 revltop = get_opfamily_member(opfamily,
3136 op_righttype, op_lefttype,
3137 gtstrat);
3138 revleop = get_opfamily_member(opfamily,
3139 op_righttype, op_lefttype,
3140 gestrat);
3141 }
3142 break;
3143 default:
3144 goto fail; /* shouldn't get here */
3145 }
3146
3147 if (!OidIsValid(lsortop) ||
3148 !OidIsValid(rsortop) ||
3149 !OidIsValid(lstatop) ||
3150 !OidIsValid(rstatop) ||
3151 !OidIsValid(ltop) ||
3152 !OidIsValid(leop) ||
3153 !OidIsValid(revltop) ||
3154 !OidIsValid(revleop))
3155 goto fail; /* insufficient info in catalogs */
3156
3157 /* Try to get ranges of both inputs */
3158 if (!isgt)
3159 {
3160 if (!get_variable_range(root, &leftvar, lstatop, collation,
3161 &leftmin, &leftmax))
3162 goto fail; /* no range available from stats */
3163 if (!get_variable_range(root, &rightvar, rstatop, collation,
3164 &rightmin, &rightmax))
3165 goto fail; /* no range available from stats */
3166 }
3167 else
3168 {
3169 /* need to swap the max and min */
3170 if (!get_variable_range(root, &leftvar, lstatop, collation,
3171 &leftmax, &leftmin))
3172 goto fail; /* no range available from stats */
3173 if (!get_variable_range(root, &rightvar, rstatop, collation,
3174 &rightmax, &rightmin))
3175 goto fail; /* no range available from stats */
3176 }
3177
3178 /*
3179 * Now, the fraction of the left variable that will be scanned is the
3180 * fraction that's <= the right-side maximum value. But only believe
3181 * non-default estimates, else stick with our 1.0.
3182 */
3183 selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
3184 rightmax, op_righttype);
3185 if (selec != DEFAULT_INEQ_SEL)
3186 *leftend = selec;
3187
3188 /* And similarly for the right variable. */
3189 selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
3190 leftmax, op_lefttype);
3191 if (selec != DEFAULT_INEQ_SEL)
3192 *rightend = selec;
3193
3194 /*
3195 * Only one of the two "end" fractions can really be less than 1.0;
3196 * believe the smaller estimate and reset the other one to exactly 1.0. If
3197 * we get exactly equal estimates (as can easily happen with self-joins),
3198 * believe neither.
3199 */
3200 if (*leftend > *rightend)
3201 *leftend = 1.0;
3202 else if (*leftend < *rightend)
3203 *rightend = 1.0;
3204 else
3205 *leftend = *rightend = 1.0;
3206
3207 /*
3208 * Also, the fraction of the left variable that will be scanned before the
3209 * first join pair is found is the fraction that's < the right-side
3210 * minimum value. But only believe non-default estimates, else stick with
3211 * our own default.
3212 */
3213 selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
3214 rightmin, op_righttype);
3215 if (selec != DEFAULT_INEQ_SEL)
3216 *leftstart = selec;
3217
3218 /* And similarly for the right variable. */
3219 selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
3220 leftmin, op_lefttype);
3221 if (selec != DEFAULT_INEQ_SEL)
3222 *rightstart = selec;
3223
3224 /*
3225 * Only one of the two "start" fractions can really be more than zero;
3226 * believe the larger estimate and reset the other one to exactly 0.0. If
3227 * we get exactly equal estimates (as can easily happen with self-joins),
3228 * believe neither.
3229 */
3230 if (*leftstart < *rightstart)
3231 *leftstart = 0.0;
3232 else if (*leftstart > *rightstart)
3233 *rightstart = 0.0;
3234 else
3235 *leftstart = *rightstart = 0.0;
3236
3237 /*
3238 * If the sort order is nulls-first, we're going to have to skip over any
3239 * nulls too. These would not have been counted by scalarineqsel, and we
3240 * can safely add in this fraction regardless of whether we believe
3241 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3242 */
3243 if (nulls_first)
3244 {
3245 Form_pg_statistic stats;
3246
3247 if (HeapTupleIsValid(leftvar.statsTuple))
3248 {
3249 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3250 *leftstart += stats->stanullfrac;
3251 CLAMP_PROBABILITY(*leftstart);
3252 *leftend += stats->stanullfrac;
3253 CLAMP_PROBABILITY(*leftend);
3254 }
3255 if (HeapTupleIsValid(rightvar.statsTuple))
3256 {
3257 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3258 *rightstart += stats->stanullfrac;
3259 CLAMP_PROBABILITY(*rightstart);
3260 *rightend += stats->stanullfrac;
3261 CLAMP_PROBABILITY(*rightend);
3262 }
3263 }
3264
3265 /* Disbelieve start >= end, just in case that can happen */
3266 if (*leftstart >= *leftend)
3267 {
3268 *leftstart = 0.0;
3269 *leftend = 1.0;
3270 }
3271 if (*rightstart >= *rightend)
3272 {
3273 *rightstart = 0.0;
3274 *rightend = 1.0;
3275 }
3276
3277 fail:
3278 ReleaseVariableStats(leftvar);
3279 ReleaseVariableStats(rightvar);
3280 }
3281
3282
3283 /*
3284 * matchingsel -- generic matching-operator selectivity support
3285 *
3286 * Use these for any operators that (a) are on data types for which we collect
3287 * standard statistics, and (b) have behavior for which the default estimate
3288 * (twice DEFAULT_EQ_SEL) is sane. Typically that is good for match-like
3289 * operators.
3290 */
3291
3292 Datum
3293 matchingsel(PG_FUNCTION_ARGS)
3294 {
3295 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
3296 Oid operator = PG_GETARG_OID(1);
3297 List *args = (List *) PG_GETARG_POINTER(2);
3298 int varRelid = PG_GETARG_INT32(3);
3299 Oid collation = PG_GET_COLLATION();
3300 double selec;
3301
3302 /* Use generic restriction selectivity logic. */
3303 selec = generic_restriction_selectivity(root, operator, collation,
3304 args, varRelid,
3305 DEFAULT_MATCHING_SEL);
3306
3307 PG_RETURN_FLOAT8((float8) selec);
3308 }
3309
3310 Datum
3311 matchingjoinsel(PG_FUNCTION_ARGS)
3312 {
3313 /* Just punt, for the moment. */
3314 PG_RETURN_FLOAT8(DEFAULT_MATCHING_SEL);
3315 }
3316
3317
3318 /*
3319 * Helper routine for estimate_num_groups: add an item to a list of
3320 * GroupVarInfos, but only if it's not known equal to any of the existing
3321 * entries.
3322 */
3323 typedef struct
3324 {
3325 Node *var; /* might be an expression, not just a Var */
3326 RelOptInfo *rel; /* relation it belongs to */
3327 double ndistinct; /* # distinct values */
3328 bool isdefault; /* true if DEFAULT_NUM_DISTINCT was used */
3329 } GroupVarInfo;
3330
3331 static List *
3332 add_unique_group_var(PlannerInfo *root, List *varinfos,
3333 Node *var, VariableStatData *vardata)
3334 {
3335 GroupVarInfo *varinfo;
3336 double ndistinct;
3337 bool isdefault;
3338 ListCell *lc;
3339
3340 ndistinct = get_variable_numdistinct(vardata, &isdefault);
3341
3342 /*
3343 * The nullingrels bits within the var could cause the same var to be
3344 * counted multiple times if it's marked with different nullingrels. They
3345 * could also prevent us from matching the var to the expressions in
3346 * extended statistics (see estimate_multivariate_ndistinct). So strip
3347 * them out first.
3348 */
3349 var = remove_nulling_relids(var, root->outer_join_rels, NULL);
3350
3351 foreach(lc, varinfos)
3352 {
3353 varinfo = (GroupVarInfo *) lfirst(lc);
3354
3355 /* Drop exact duplicates */
3356 if (equal(var, varinfo->var))
3357 return varinfos;
3358
3359 /*
3360 * Drop known-equal vars, but only if they belong to different
3361 * relations (see comments for estimate_num_groups). We aren't too
3362 * fussy about the semantics of "equal" here.
3363 */
3364 if (vardata->rel != varinfo->rel &&
3365 exprs_known_equal(root, var, varinfo->var, InvalidOid))
3366 {
3367 if (varinfo->ndistinct <= ndistinct)
3368 {
3369 /* Keep older item, forget new one */
3370 return varinfos;
3371 }
3372 else
3373 {
3374 /* Delete the older item */
3375 varinfos = foreach_delete_current(varinfos, lc);
3376 }
3377 }
3378 }
3379
3380 varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3381
3382 varinfo->var = var;
3383 varinfo->rel = vardata->rel;
3384 varinfo->ndistinct = ndistinct;
3385 varinfo->isdefault = isdefault;
3386 varinfos = lappend(varinfos, varinfo);
3387 return varinfos;
3388 }
3389
3390 /*
3391 * estimate_num_groups - Estimate number of groups in a grouped query
3392 *
3393 * Given a query having a GROUP BY clause, estimate how many groups there
3394 * will be --- ie, the number of distinct combinations of the GROUP BY
3395 * expressions.
3396 *
3397 * This routine is also used to estimate the number of rows emitted by
3398 * a DISTINCT filtering step; that is an isomorphic problem. (Note:
3399 * actually, we only use it for DISTINCT when there's no grouping or
3400 * aggregation ahead of the DISTINCT.)
3401 *
3402 * Inputs:
3403 * root - the query
3404 * groupExprs - list of expressions being grouped by
3405 * input_rows - number of rows estimated to arrive at the group/unique
3406 * filter step
3407 * pgset - NULL, or a List** pointing to a grouping set to filter the
3408 * groupExprs against
3409 *
3410 * Outputs:
3411 * estinfo - When passed as non-NULL, the function will set bits in the
3412 * "flags" field in order to provide callers with additional information
3413 * about the estimation. Currently, we only set the SELFLAG_USED_DEFAULT
3414 * bit if we used any default values in the estimation.
3415 *
3416 * Given the lack of any cross-correlation statistics in the system, it's
3417 * impossible to do anything really trustworthy with GROUP BY conditions
3418 * involving multiple Vars. We should however avoid assuming the worst
3419 * case (all possible cross-product terms actually appear as groups) since
3420 * very often the grouped-by Vars are highly correlated. Our current approach
3421 * is as follows:
3422 * 1. Expressions yielding boolean are assumed to contribute two groups,
3423 * independently of their content, and are ignored in the subsequent
3424 * steps. This is mainly because tests like "col IS NULL" break the
3425 * heuristic used in step 2 especially badly.
3426 * 2. Reduce the given expressions to a list of unique Vars used. For
3427 * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3428 * It is clearly correct not to count the same Var more than once.
3429 * It is also reasonable to treat f(x) the same as x: f() cannot
3430 * increase the number of distinct values (unless it is volatile,
3431 * which we consider unlikely for grouping), but it probably won't
3432 * reduce the number of distinct values much either.
3433 * As a special case, if a GROUP BY expression can be matched to an
3434 * expressional index for which we have statistics, then we treat the
3435 * whole expression as though it were just a Var.
3436 * 3. If the list contains Vars of different relations that are known equal
3437 * due to equivalence classes, then drop all but one of the Vars from each
3438 * known-equal set, keeping the one with smallest estimated # of values
3439 * (since the extra values of the others can't appear in joined rows).
3440 * Note the reason we only consider Vars of different relations is that
3441 * if we considered ones of the same rel, we'd be double-counting the
3442 * restriction selectivity of the equality in the next step.
3443 * 4. For Vars within a single source rel, we multiply together the numbers
3444 * of values, clamp to the number of rows in the rel (divided by 10 if
3445 * more than one Var), and then multiply by a factor based on the
3446 * selectivity of the restriction clauses for that rel. When there's
3447 * more than one Var, the initial product is probably too high (it's the
3448 * worst case) but clamping to a fraction of the rel's rows seems to be a
3449 * helpful heuristic for not letting the estimate get out of hand. (The
3450 * factor of 10 is derived from pre-Postgres-7.4 practice.) The factor
3451 * we multiply by to adjust for the restriction selectivity assumes that
3452 * the restriction clauses are independent of the grouping, which may not
3453 * be a valid assumption, but it's hard to do better.
3454 * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3455 * rel, and multiply the results together.
3456 * Note that rels not containing grouped Vars are ignored completely, as are
3457 * join clauses. Such rels cannot increase the number of groups, and we
3458 * assume such clauses do not reduce the number either (somewhat bogus,
3459 * but we don't have the info to do better).
3460 */
3461 double
3462 estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3463 List **pgset, EstimationInfo *estinfo)
3464 {
3465 List *varinfos = NIL;
3466 double srf_multiplier = 1.0;
3467 double numdistinct;
3468 ListCell *l;
3469 int i;
3470
3471 /* Zero the estinfo output parameter, if non-NULL */
3472 if (estinfo != NULL)
3473 memset(estinfo, 0, sizeof(EstimationInfo));
3474
3475 /*
3476 * We don't ever want to return an estimate of zero groups, as that tends
3477 * to lead to division-by-zero and other unpleasantness. The input_rows
3478 * estimate is usually already at least 1, but clamp it just in case it
3479 * isn't.
3480 */
3481 input_rows = clamp_row_est(input_rows);
3482
3483 /*
3484 * If no grouping columns, there's exactly one group. (This can't happen
3485 * for normal cases with GROUP BY or DISTINCT, but it is possible for
3486 * corner cases with set operations.)
3487 */
3488 if (groupExprs == NIL || (pgset && *pgset == NIL))
3489 return 1.0;
3490
3491 /*
3492 * Count groups derived from boolean grouping expressions. For other
3493 * expressions, find the unique Vars used, treating an expression as a Var
3494 * if we can find stats for it. For each one, record the statistical
3495 * estimate of number of distinct values (total in its table, without
3496 * regard for filtering).
3497 */
3498 numdistinct = 1.0;
3499
3500 i = 0;
3501 foreach(l, groupExprs)
3502 {
3503 Node *groupexpr = (Node *) lfirst(l);
3504 double this_srf_multiplier;
3505 VariableStatData vardata;
3506 List *varshere;
3507 ListCell *l2;
3508
3509 /* is expression in this grouping set? */
3510 if (pgset && !list_member_int(*pgset, i++))
3511 continue;
3512
3513 /*
3514 * Set-returning functions in grouping columns are a bit problematic.
3515 * The code below will effectively ignore their SRF nature and come up
3516 * with a numdistinct estimate as though they were scalar functions.
3517 * We compensate by scaling up the end result by the largest SRF
3518 * rowcount estimate. (This will be an overestimate if the SRF
3519 * produces multiple copies of any output value, but it seems best to
3520 * assume the SRF's outputs are distinct. In any case, it's probably
3521 * pointless to worry too much about this without much better
3522 * estimates for SRF output rowcounts than we have today.)
3523 */
3524 this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3525 if (srf_multiplier < this_srf_multiplier)
3526 srf_multiplier = this_srf_multiplier;
3527
3528 /* Short-circuit for expressions returning boolean */
3529 if (exprType(groupexpr) == BOOLOID)
3530 {
3531 numdistinct *= 2.0;
3532 continue;
3533 }
3534
3535 /*
3536 * If examine_variable is able to deduce anything about the GROUP BY
3537 * expression, treat it as a single variable even if it's really more
3538 * complicated.
3539 *
3540 * XXX This has the consequence that if there's a statistics object on
3541 * the expression, we don't split it into individual Vars. This
3542 * affects our selection of statistics in
3543 * estimate_multivariate_ndistinct, because it's probably better to
3544 * use more accurate estimate for each expression and treat them as
3545 * independent, than to combine estimates for the extracted variables
3546 * when we don't know how that relates to the expressions.
3547 */
3548 examine_variable(root, groupexpr, 0, &vardata);
3549 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3550 {
3551 varinfos = add_unique_group_var(root, varinfos,
3552 groupexpr, &vardata);
3553 ReleaseVariableStats(vardata);
3554 continue;
3555 }
3556 ReleaseVariableStats(vardata);
3557
3558 /*
3559 * Else pull out the component Vars. Handle PlaceHolderVars by
3560 * recursing into their arguments (effectively assuming that the
3561 * PlaceHolderVar doesn't change the number of groups, which boils
3562 * down to ignoring the possible addition of nulls to the result set).
3563 */
3564 varshere = pull_var_clause(groupexpr,
3565 PVC_RECURSE_AGGREGATES |
3566 PVC_RECURSE_WINDOWFUNCS |
3567 PVC_RECURSE_PLACEHOLDERS);
3568
3569 /*
3570 * If we find any variable-free GROUP BY item, then either it is a
3571 * constant (and we can ignore it) or it contains a volatile function;
3572 * in the latter case we punt and assume that each input row will
3573 * yield a distinct group.
3574 */
3575 if (varshere == NIL)
3576 {
3577 if (contain_volatile_functions(groupexpr))
3578 return input_rows;
3579 continue;
3580 }
3581
3582 /*
3583 * Else add variables to varinfos list
3584 */
3585 foreach(l2, varshere)
3586 {
3587 Node *var = (Node *) lfirst(l2);
3588
3589 examine_variable(root, var, 0, &vardata);
3590 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3591 ReleaseVariableStats(vardata);
3592 }
3593 }
3594
3595 /*
3596 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3597 * list.
3598 */
3599 if (varinfos == NIL)
3600 {
3601 /* Apply SRF multiplier as we would do in the long path */
3602 numdistinct *= srf_multiplier;
3603 /* Round off */
3604 numdistinct = ceil(numdistinct);
3605 /* Guard against out-of-range answers */
3606 if (numdistinct > input_rows)
3607 numdistinct = input_rows;
3608 if (numdistinct < 1.0)
3609 numdistinct = 1.0;
3610 return numdistinct;
3611 }
3612
3613 /*
3614 * Group Vars by relation and estimate total numdistinct.
3615 *
3616 * For each iteration of the outer loop, we process the frontmost Var in
3617 * varinfos, plus all other Vars in the same relation. We remove these
3618 * Vars from the newvarinfos list for the next iteration. This is the
3619 * easiest way to group Vars of same rel together.
3620 */
3621 do
3622 {
3623 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3624 RelOptInfo *rel = varinfo1->rel;
3625 double reldistinct = 1;
3626 double relmaxndistinct = reldistinct;
3627 int relvarcount = 0;
3628 List *newvarinfos = NIL;
3629 List *relvarinfos = NIL;
3630
3631 /*
3632 * Split the list of varinfos in two - one for the current rel, one
3633 * for remaining Vars on other rels.
3634 */
3635 relvarinfos = lappend(relvarinfos, varinfo1);
3636 for_each_from(l, varinfos, 1)
3637 {
3638 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3639
3640 if (varinfo2->rel == varinfo1->rel)
3641 {
3642 /* varinfos on current rel */
3643 relvarinfos = lappend(relvarinfos, varinfo2);
3644 }
3645 else
3646 {
3647 /* not time to process varinfo2 yet */
3648 newvarinfos = lappend(newvarinfos, varinfo2);
3649 }
3650 }
3651
3652 /*
3653 * Get the numdistinct estimate for the Vars of this rel. We
3654 * iteratively search for multivariate n-distinct with maximum number
3655 * of vars; assuming that each var group is independent of the others,
3656 * we multiply them together. Any remaining relvarinfos after no more
3657 * multivariate matches are found are assumed independent too, so
3658 * their individual ndistinct estimates are multiplied also.
3659 *
3660 * While iterating, count how many separate numdistinct values we
3661 * apply. We apply a fudge factor below, but only if we multiplied
3662 * more than one such values.
3663 */
3664 while (relvarinfos)
3665 {
3666 double mvndistinct;
3667
3668 if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3669 &mvndistinct))
3670 {
3671 reldistinct *= mvndistinct;
3672 if (relmaxndistinct < mvndistinct)
3673 relmaxndistinct = mvndistinct;
3674 relvarcount++;
3675 }
3676 else
3677 {
3678 foreach(l, relvarinfos)
3679 {
3680 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3681
3682 reldistinct *= varinfo2->ndistinct;
3683 if (relmaxndistinct < varinfo2->ndistinct)
3684 relmaxndistinct = varinfo2->ndistinct;
3685 relvarcount++;
3686
3687 /*
3688 * When varinfo2's isdefault is set then we'd better set
3689 * the SELFLAG_USED_DEFAULT bit in the EstimationInfo.
3690 */
3691 if (estinfo != NULL && varinfo2->isdefault)
3692 estinfo->flags |= SELFLAG_USED_DEFAULT;
3693 }
3694
3695 /* we're done with this relation */
3696 relvarinfos = NIL;
3697 }
3698 }
3699
3700 /*
3701 * Sanity check --- don't divide by zero if empty relation.
3702 */
3703 Assert(IS_SIMPLE_REL(rel));
3704 if (rel->tuples > 0)
3705 {
3706 /*
3707 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3708 * fudge factor is because the Vars are probably correlated but we
3709 * don't know by how much. We should never clamp to less than the
3710 * largest ndistinct value for any of the Vars, though, since
3711 * there will surely be at least that many groups.
3712 */
3713 double clamp = rel->tuples;
3714
3715 if (relvarcount > 1)
3716 {
3717 clamp *= 0.1;
3718 if (clamp < relmaxndistinct)
3719 {
3720 clamp = relmaxndistinct;
3721 /* for sanity in case some ndistinct is too large: */
3722 if (clamp > rel->tuples)
3723 clamp = rel->tuples;
3724 }
3725 }
3726 if (reldistinct > clamp)
3727 reldistinct = clamp;
3728
3729 /*
3730 * Update the estimate based on the restriction selectivity,
3731 * guarding against division by zero when reldistinct is zero.
3732 * Also skip this if we know that we are returning all rows.
3733 */
3734 if (reldistinct > 0 && rel->rows < rel->tuples)
3735 {
3736 /*
3737 * Given a table containing N rows with n distinct values in a
3738 * uniform distribution, if we select p rows at random then
3739 * the expected number of distinct values selected is
3740 *
3741 * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3742 *
3743 * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3744 *
3745 * See "Approximating block accesses in database
3746 * organizations", S. B. Yao, Communications of the ACM,
3747 * Volume 20 Issue 4, April 1977 Pages 260-261.
3748 *
3749 * Alternatively, re-arranging the terms from the factorials,
3750 * this may be written as
3751 *
3752 * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3753 *
3754 * This form of the formula is more efficient to compute in
3755 * the common case where p is larger than N/n. Additionally,
3756 * as pointed out by Dell'Era, if i << N for all terms in the
3757 * product, it can be approximated by
3758 *
3759 * n * (1 - ((N-p)/N)^(N/n))
3760 *
3761 * See "Expected distinct values when selecting from a bag
3762 * without replacement", Alberto Dell'Era,
3763 * http://www.adellera.it/investigations/distinct_balls/.
3764 *
3765 * The condition i << N is equivalent to n >> 1, so this is a
3766 * good approximation when the number of distinct values in
3767 * the table is large. It turns out that this formula also
3768 * works well even when n is small.
3769 */
3770 reldistinct *=
3771 (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3772 rel->tuples / reldistinct));
3773 }
3774 reldistinct = clamp_row_est(reldistinct);
3775
3776 /*
3777 * Update estimate of total distinct groups.
3778 */
3779 numdistinct *= reldistinct;
3780 }
3781
3782 varinfos = newvarinfos;
3783 } while (varinfos != NIL);
3784
3785 /* Now we can account for the effects of any SRFs */
3786 numdistinct *= srf_multiplier;
3787
3788 /* Round off */
3789 numdistinct = ceil(numdistinct);
3790
3791 /* Guard against out-of-range answers */
3792 if (numdistinct > input_rows)
3793 numdistinct = input_rows;
3794 if (numdistinct < 1.0)
3795 numdistinct = 1.0;
3796
3797 return numdistinct;
3798 }
3799
3800 /*
3801 * Try to estimate the bucket size of the hash join inner side when the join
3802 * condition contains two or more clauses by employing extended statistics.
3803 *
3804 * The main idea of this approach is that the distinct value generated by
3805 * multivariate estimation on two or more columns would provide less bucket size
3806 * than estimation on one separate column.
3807 *
3808 * IMPORTANT: It is crucial to synchronize the approach of combining different
3809 * estimations with the caller's method.
3810 *
3811 * Return a list of clauses that didn't fetch any extended statistics.
3812 */
3813 List *
3814 estimate_multivariate_bucketsize(PlannerInfo *root, RelOptInfo *inner,
3815 List *hashclauses,
3816 Selectivity *innerbucketsize)
3817 {
3818 List *clauses = list_copy(hashclauses);
3819 List *otherclauses = NIL;
3820 double ndistinct = 1.0;
3821
3822 if (list_length(hashclauses) <= 1)
3823
3824 /*
3825 * Nothing to do for a single clause. Could we employ univariate
3826 * extended stat here?
3827 */
3828 return hashclauses;
3829
3830 while (clauses != NIL)
3831 {
3832 ListCell *lc;
3833 int relid = -1;
3834 List *varinfos = NIL;
3835 List *origin_rinfos = NIL;
3836 double mvndistinct;
3837 List *origin_varinfos;
3838 int group_relid = -1;
3839 RelOptInfo *group_rel = NULL;
3840 ListCell *lc1,
3841 *lc2;
3842
3843 /*
3844 * Find clauses, referencing the same single base relation and try to
3845 * estimate such a group with extended statistics. Create varinfo for
3846 * an approved clause, push it to otherclauses, if it can't be
3847 * estimated here or ignore to process at the next iteration.
3848 */
3849 foreach(lc, clauses)
3850 {
3851 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
3852 Node *expr;
3853 Relids relids;
3854 GroupVarInfo *varinfo;
3855
3856 /*
3857 * Find the inner side of the join, which we need to estimate the
3858 * number of buckets. Use outer_is_left because the
3859 * clause_sides_match_join routine has called on hash clauses.
3860 */
3861 relids = rinfo->outer_is_left ?
3862 rinfo->right_relids : rinfo->left_relids;
3863 expr = rinfo->outer_is_left ?
3864 get_rightop(rinfo->clause) : get_leftop(rinfo->clause);
3865
3866 if (bms_get_singleton_member(relids, &relid) &&
3867 root->simple_rel_array[relid]->statlist != NIL)
3868 {
3869 bool is_duplicate = false;
3870
3871 /*
3872 * This inner-side expression references only one relation.
3873 * Extended statistics on this clause can exist.
3874 */
3875 if (group_relid < 0)
3876 {
3877 RangeTblEntry *rte = root->simple_rte_array[relid];
3878
3879 if (!rte || (rte->relkind != RELKIND_RELATION &&
3880 rte->relkind != RELKIND_MATVIEW &&
3881 rte->relkind != RELKIND_FOREIGN_TABLE &&
3882 rte->relkind != RELKIND_PARTITIONED_TABLE))
3883 {
3884 /* Extended statistics can't exist in principle */
3885 otherclauses = lappend(otherclauses, rinfo);
3886 clauses = foreach_delete_current(clauses, lc);
3887 continue;
3888 }
3889
3890 group_relid = relid;
3891 group_rel = root->simple_rel_array[relid];
3892 }
3893 else if (group_relid != relid)
3894
3895 /*
3896 * Being in the group forming state we don't need other
3897 * clauses.
3898 */
3899 continue;
3900
3901 /*
3902 * We're going to add the new clause to the varinfos list. We
3903 * might re-use add_unique_group_var(), but we don't do so for
3904 * two reasons.
3905 *
3906 * 1) We must keep the origin_rinfos list ordered exactly the
3907 * same way as varinfos.
3908 *
3909 * 2) add_unique_group_var() is designed for
3910 * estimate_num_groups(), where a larger number of groups is
3911 * worse. While estimating the number of hash buckets, we
3912 * have the opposite: a lesser number of groups is worse.
3913 * Therefore, we don't have to remove "known equal" vars: the
3914 * removed var may valuably contribute to the multivariate
3915 * statistics to grow the number of groups.
3916 */
3917
3918 /*
3919 * Clear nullingrels to correctly match hash keys. See
3920 * add_unique_group_var()'s comment for details.
3921 */
3922 expr = remove_nulling_relids(expr, root->outer_join_rels, NULL);
3923
3924 /*
3925 * Detect and exclude exact duplicates from the list of hash
3926 * keys (like add_unique_group_var does).
3927 */
3928 foreach(lc1, varinfos)
3929 {
3930 varinfo = (GroupVarInfo *) lfirst(lc1);
3931
3932 if (!equal(expr, varinfo->var))
3933 continue;
3934
3935 is_duplicate = true;
3936 break;
3937 }
3938
3939 if (is_duplicate)
3940 {
3941 /*
3942 * Skip exact duplicates. Adding them to the otherclauses
3943 * list also doesn't make sense.
3944 */
3945 continue;
3946 }
3947
3948 /*
3949 * Initialize GroupVarInfo. We only use it to call
3950 * estimate_multivariate_ndistinct(), which doesn't care about
3951 * ndistinct and isdefault fields. Thus, skip these fields.
3952 */
3953 varinfo = (GroupVarInfo *) palloc0(sizeof(GroupVarInfo));
3954 varinfo->var = expr;
3955 varinfo->rel = root->simple_rel_array[relid];
3956 varinfos = lappend(varinfos, varinfo);
3957
3958 /*
3959 * Remember the link to RestrictInfo for the case the clause
3960 * is failed to be estimated.
3961 */
3962 origin_rinfos = lappend(origin_rinfos, rinfo);
3963 }
3964 else
3965 {
3966 /* This clause can't be estimated with extended statistics */
3967 otherclauses = lappend(otherclauses, rinfo);
3968 }
3969
3970 clauses = foreach_delete_current(clauses, lc);
3971 }
3972
3973 if (list_length(varinfos) < 2)
3974 {
3975 /*
3976 * Multivariate statistics doesn't apply to single columns except
3977 * for expressions, but it has not been implemented yet.
3978 */
3979 otherclauses = list_concat(otherclauses, origin_rinfos);
3980 list_free_deep(varinfos);
3981 list_free(origin_rinfos);
3982 continue;
3983 }
3984
3985 Assert(group_rel != NULL);
3986
3987 /* Employ the extended statistics. */
3988 origin_varinfos = varinfos;
3989 for (;;)
3990 {
3991 bool estimated = estimate_multivariate_ndistinct(root,
3992 group_rel,
3993 &varinfos,
3994 &mvndistinct);
3995
3996 if (!estimated)
3997 break;
3998
3999 /*
4000 * We've got an estimation. Use ndistinct value in a consistent
4001 * way - according to the caller's logic (see
4002 * final_cost_hashjoin).
4003 */
4004 if (ndistinct < mvndistinct)
4005 ndistinct = mvndistinct;
4006 Assert(ndistinct >= 1.0);
4007 }
4008
4009 Assert(list_length(origin_varinfos) == list_length(origin_rinfos));
4010
4011 /* Collect unmatched clauses as otherclauses. */
4012 forboth(lc1, origin_varinfos, lc2, origin_rinfos)
4013 {
4014 GroupVarInfo *vinfo = lfirst(lc1);
4015
4016 if (!list_member_ptr(varinfos, vinfo))
4017 /* Already estimated */
4018 continue;
4019
4020 /* Can't be estimated here - push to the returning list */
4021 otherclauses = lappend(otherclauses, lfirst(lc2));
4022 }
4023 }
4024
4025 *innerbucketsize = 1.0 / ndistinct;
4026 return otherclauses;
4027 }
4028
4029 /*
4030 * Estimate hash bucket statistics when the specified expression is used
4031 * as a hash key for the given number of buckets.
4032 *
4033 * This attempts to determine two values:
4034 *
4035 * 1. The frequency of the most common value of the expression (returns
4036 * zero into *mcv_freq if we can't get that).
4037 *
4038 * 2. The "bucketsize fraction", ie, average number of entries in a bucket
4039 * divided by total tuples in relation.
4040 *
4041 * XXX This is really pretty bogus since we're effectively assuming that the
4042 * distribution of hash keys will be the same after applying restriction
4043 * clauses as it was in the underlying relation. However, we are not nearly
4044 * smart enough to figure out how the restrict clauses might change the
4045 * distribution, so this will have to do for now.
4046 *
4047 * We are passed the number of buckets the executor will use for the given
4048 * input relation. If the data were perfectly distributed, with the same
4049 * number of tuples going into each available bucket, then the bucketsize
4050 * fraction would be 1/nbuckets. But this happy state of affairs will occur
4051 * only if (a) there are at least nbuckets distinct data values, and (b)
4052 * we have a not-too-skewed data distribution. Otherwise the buckets will
4053 * be nonuniformly occupied. If the other relation in the join has a key
4054 * distribution similar to this one's, then the most-loaded buckets are
4055 * exactly those that will be probed most often. Therefore, the "average"
4056 * bucket size for costing purposes should really be taken as something close
4057 * to the "worst case" bucket size. We try to estimate this by adjusting the
4058 * fraction if there are too few distinct data values, and then scaling up
4059 * by the ratio of the most common value's frequency to the average frequency.
4060 *
4061 * If no statistics are available, use a default estimate of 0.1. This will
4062 * discourage use of a hash rather strongly if the inner relation is large,
4063 * which is what we want. We do not want to hash unless we know that the
4064 * inner rel is well-dispersed (or the alternatives seem much worse).
4065 *
4066 * The caller should also check that the mcv_freq is not so large that the
4067 * most common value would by itself require an impractically large bucket.
4068 * In a hash join, the executor can split buckets if they get too big, but
4069 * obviously that doesn't help for a bucket that contains many duplicates of
4070 * the same value.
4071 */
4072 void
4073 estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets,
4074 Selectivity *mcv_freq,
4075 Selectivity *bucketsize_frac)
4076 {
4077 VariableStatData vardata;
4078 double estfract,
4079 ndistinct,
4080 stanullfrac,
4081 avgfreq;
4082 bool isdefault;
4083 AttStatsSlot sslot;
4084
4085 examine_variable(root, hashkey, 0, &vardata);
4086
4087 /* Look up the frequency of the most common value, if available */
4088 *mcv_freq = 0.0;
4089
4090 if (HeapTupleIsValid(vardata.statsTuple))
4091 {
4092 if (get_attstatsslot(&sslot, vardata.statsTuple,
4093 STATISTIC_KIND_MCV, InvalidOid,
4094 ATTSTATSSLOT_NUMBERS))
4095 {
4096 /*
4097 * The first MCV stat is for the most common value.
4098 */
4099 if (sslot.nnumbers > 0)
4100 *mcv_freq = sslot.numbers[0];
4101 free_attstatsslot(&sslot);
4102 }
4103 }
4104
4105 /* Get number of distinct values */
4106 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
4107
4108 /*
4109 * If ndistinct isn't real, punt. We normally return 0.1, but if the
4110 * mcv_freq is known to be even higher than that, use it instead.
4111 */
4112 if (isdefault)
4113 {
4114 *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
4115 ReleaseVariableStats(vardata);
4116 return;
4117 }
4118
4119 /* Get fraction that are null */
4120 if (HeapTupleIsValid(vardata.statsTuple))
4121 {
4122 Form_pg_statistic stats;
4123
4124 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
4125 stanullfrac = stats->stanullfrac;
4126 }
4127 else
4128 stanullfrac = 0.0;
4129
4130 /* Compute avg freq of all distinct data values in raw relation */
4131 avgfreq = (1.0 - stanullfrac) / ndistinct;
4132
4133 /*
4134 * Adjust ndistinct to account for restriction clauses. Observe we are
4135 * assuming that the data distribution is affected uniformly by the
4136 * restriction clauses!
4137 *
4138 * XXX Possibly better way, but much more expensive: multiply by
4139 * selectivity of rel's restriction clauses that mention the target Var.
4140 */
4141 if (vardata.rel && vardata.rel->tuples > 0)
4142 {
4143 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
4144 ndistinct = clamp_row_est(ndistinct);
4145 }
4146
4147 /*
4148 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
4149 * number of buckets is less than the expected number of distinct values;
4150 * otherwise it is 1/ndistinct.
4151 */
4152 if (ndistinct > nbuckets)
4153 estfract = 1.0 / nbuckets;
4154 else
4155 estfract = 1.0 / ndistinct;
4156
4157 /*
4158 * Adjust estimated bucketsize upward to account for skewed distribution.
4159 */
4160 if (avgfreq > 0.0 && *mcv_freq > avgfreq)
4161 estfract *= *mcv_freq / avgfreq;
4162
4163 /*
4164 * Clamp bucketsize to sane range (the above adjustment could easily
4165 * produce an out-of-range result). We set the lower bound a little above
4166 * zero, since zero isn't a very sane result.
4167 */
4168 if (estfract < 1.0e-6)
4169 estfract = 1.0e-6;
4170 else if (estfract > 1.0)
4171 estfract = 1.0;
4172
4173 *bucketsize_frac = (Selectivity) estfract;
4174
4175 ReleaseVariableStats(vardata);
4176 }
4177
4178 /*
4179 * estimate_hashagg_tablesize
4180 * estimate the number of bytes that a hash aggregate hashtable will
4181 * require based on the agg_costs, path width and number of groups.
4182 *
4183 * We return the result as "double" to forestall any possible overflow
4184 * problem in the multiplication by dNumGroups.
4185 *
4186 * XXX this may be over-estimating the size now that hashagg knows to omit
4187 * unneeded columns from the hashtable. Also for mixed-mode grouping sets,
4188 * grouping columns not in the hashed set are counted here even though hashagg
4189 * won't store them. Is this a problem?
4190 */
4191 double
4192 estimate_hashagg_tablesize(PlannerInfo *root, Path *path,
4193 const AggClauseCosts *agg_costs, double dNumGroups)
4194 {
4195 Size hashentrysize;
4196
4197 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
4198 path->pathtarget->width,
4199 agg_costs->transitionSpace);
4200
4201 /*
4202 * Note that this disregards the effect of fill-factor and growth policy
4203 * of the hash table. That's probably ok, given that the default
4204 * fill-factor is relatively high. It'd be hard to meaningfully factor in
4205 * "double-in-size" growth policies here.
4206 */
4207 return hashentrysize * dNumGroups;
4208 }
4209
4210
4211 /*-------------------------------------------------------------------------
4212 *
4213 * Support routines
4214 *
4215 *-------------------------------------------------------------------------
4216 */
4217
4218 /*
4219 * Find the best matching ndistinct extended statistics for the given list of
4220 * GroupVarInfos.
4221 *
4222 * Callers must ensure that the given GroupVarInfos all belong to 'rel' and
4223 * the GroupVarInfos list does not contain any duplicate Vars or expressions.
4224 *
4225 * When statistics are found that match > 1 of the given GroupVarInfo, the
4226 * *ndistinct parameter is set according to the ndistinct estimate and a new
4227 * list is built with the matching GroupVarInfos removed, which is output via
4228 * the *varinfos parameter before returning true. When no matching stats are
4229 * found, false is returned and the *varinfos and *ndistinct parameters are
4230 * left untouched.
4231 */
4232 static bool
4233 estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel,
4234 List **varinfos, double *ndistinct)
4235 {
4236 ListCell *lc;
4237 int nmatches_vars;
4238 int nmatches_exprs;
4239 Oid statOid = InvalidOid;
4240 MVNDistinct *stats;
4241 StatisticExtInfo *matched_info = NULL;
4242 RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
4243
4244 /* bail out immediately if the table has no extended statistics */
4245 if (!rel->statlist)
4246 return false;
4247
4248 /* look for the ndistinct statistics object matching the most vars */
4249 nmatches_vars = 0; /* we require at least two matches */
4250 nmatches_exprs = 0;
4251 foreach(lc, rel->statlist)
4252 {
4253 ListCell *lc2;
4254 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
4255 int nshared_vars = 0;
4256 int nshared_exprs = 0;
4257
4258 /* skip statistics of other kinds */
4259 if (info->kind != STATS_EXT_NDISTINCT)
4260 continue;
4261
4262 /* skip statistics with mismatching stxdinherit value */
4263 if (info->inherit != rte->inh)
4264 continue;
4265
4266 /*
4267 * Determine how many expressions (and variables in non-matched
4268 * expressions) match. We'll then use these numbers to pick the
4269 * statistics object that best matches the clauses.
4270 */
4271 foreach(lc2, *varinfos)
4272 {
4273 ListCell *lc3;
4274 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4275 AttrNumber attnum;
4276
4277 Assert(varinfo->rel == rel);
4278
4279 /* simple Var, search in statistics keys directly */
4280 if (IsA(varinfo->var, Var))
4281 {
4282 attnum = ((Var *) varinfo->var)->varattno;
4283
4284 /*
4285 * Ignore system attributes - we don't support statistics on
4286 * them, so can't match them (and it'd fail as the values are
4287 * negative).
4288 */
4289 if (!AttrNumberIsForUserDefinedAttr(attnum))
4290 continue;
4291
4292 if (bms_is_member(attnum, info->keys))
4293 nshared_vars++;
4294
4295 continue;
4296 }
4297
4298 /* expression - see if it's in the statistics object */
4299 foreach(lc3, info->exprs)
4300 {
4301 Node *expr = (Node *) lfirst(lc3);
4302
4303 if (equal(varinfo->var, expr))
4304 {
4305 nshared_exprs++;
4306 break;
4307 }
4308 }
4309 }
4310
4311 /*
4312 * The ndistinct extended statistics contain estimates for a minimum
4313 * of pairs of columns which the statistics are defined on and
4314 * certainly not single columns. Here we skip unless we managed to
4315 * match to at least two columns.
4316 */
4317 if (nshared_vars + nshared_exprs < 2)
4318 continue;
4319
4320 /*
4321 * Check if these statistics are a better match than the previous best
4322 * match and if so, take note of the StatisticExtInfo.
4323 *
4324 * The statslist is sorted by statOid, so the StatisticExtInfo we
4325 * select as the best match is deterministic even when multiple sets
4326 * of statistics match equally as well.
4327 */
4328 if ((nshared_exprs > nmatches_exprs) ||
4329 (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
4330 {
4331 statOid = info->statOid;
4332 nmatches_vars = nshared_vars;
4333 nmatches_exprs = nshared_exprs;
4334 matched_info = info;
4335 }
4336 }
4337
4338 /* No match? */
4339 if (statOid == InvalidOid)
4340 return false;
4341
4342 Assert(nmatches_vars + nmatches_exprs > 1);
4343
4344 stats = statext_ndistinct_load(statOid, rte->inh);
4345
4346 /*
4347 * If we have a match, search it for the specific item that matches (there
4348 * must be one), and construct the output values.
4349 */
4350 if (stats)
4351 {
4352 int i;
4353 List *newlist = NIL;
4354 MVNDistinctItem *item = NULL;
4355 ListCell *lc2;
4356 Bitmapset *matched = NULL;
4357 AttrNumber attnum_offset;
4358
4359 /*
4360 * How much we need to offset the attnums? If there are no
4361 * expressions, no offset is needed. Otherwise offset enough to move
4362 * the lowest one (which is equal to number of expressions) to 1.
4363 */
4364 if (matched_info->exprs)
4365 attnum_offset = (list_length(matched_info->exprs) + 1);
4366 else
4367 attnum_offset = 0;
4368
4369 /* see what actually matched */
4370 foreach(lc2, *varinfos)
4371 {
4372 ListCell *lc3;
4373 int idx;
4374 bool found = false;
4375
4376 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4377
4378 /*
4379 * Process a simple Var expression, by matching it to keys
4380 * directly. If there's a matching expression, we'll try matching
4381 * it later.
4382 */
4383 if (IsA(varinfo->var, Var))
4384 {
4385 AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4386
4387 /*
4388 * Ignore expressions on system attributes. Can't rely on the
4389 * bms check for negative values.
4390 */
4391 if (!AttrNumberIsForUserDefinedAttr(attnum))
4392 continue;
4393
4394 /* Is the variable covered by the statistics object? */
4395 if (!bms_is_member(attnum, matched_info->keys))
4396 continue;
4397
4398 attnum = attnum + attnum_offset;
4399
4400 /* ensure sufficient offset */
4401 Assert(AttrNumberIsForUserDefinedAttr(attnum));
4402
4403 matched = bms_add_member(matched, attnum);
4404
4405 found = true;
4406 }
4407
4408 /*
4409 * XXX Maybe we should allow searching the expressions even if we
4410 * found an attribute matching the expression? That would handle
4411 * trivial expressions like "(a)" but it seems fairly useless.
4412 */
4413 if (found)
4414 continue;
4415
4416 /* expression - see if it's in the statistics object */
4417 idx = 0;
4418 foreach(lc3, matched_info->exprs)
4419 {
4420 Node *expr = (Node *) lfirst(lc3);
4421
4422 if (equal(varinfo->var, expr))
4423 {
4424 AttrNumber attnum = -(idx + 1);
4425
4426 attnum = attnum + attnum_offset;
4427
4428 /* ensure sufficient offset */
4429 Assert(AttrNumberIsForUserDefinedAttr(attnum));
4430
4431 matched = bms_add_member(matched, attnum);
4432
4433 /* there should be just one matching expression */
4434 break;
4435 }
4436
4437 idx++;
4438 }
4439 }
4440
4441 /* Find the specific item that exactly matches the combination */
4442 for (i = 0; i < stats->nitems; i++)
4443 {
4444 int j;
4445 MVNDistinctItem *tmpitem = &stats->items[i];
4446
4447 if (tmpitem->nattributes != bms_num_members(matched))
4448 continue;
4449
4450 /* assume it's the right item */
4451 item = tmpitem;
4452
4453 /* check that all item attributes/expressions fit the match */
4454 for (j = 0; j < tmpitem->nattributes; j++)
4455 {
4456 AttrNumber attnum = tmpitem->attributes[j];
4457
4458 /*
4459 * Thanks to how we constructed the matched bitmap above, we
4460 * can just offset all attnums the same way.
4461 */
4462 attnum = attnum + attnum_offset;
4463
4464 if (!bms_is_member(attnum, matched))
4465 {
4466 /* nah, it's not this item */
4467 item = NULL;
4468 break;
4469 }
4470 }
4471
4472 /*
4473 * If the item has all the matched attributes, we know it's the
4474 * right one - there can't be a better one. matching more.
4475 */
4476 if (item)
4477 break;
4478 }
4479
4480 /*
4481 * Make sure we found an item. There has to be one, because ndistinct
4482 * statistics includes all combinations of attributes.
4483 */
4484 if (!item)
4485 elog(ERROR, "corrupt MVNDistinct entry");
4486
4487 /* Form the output varinfo list, keeping only unmatched ones */
4488 foreach(lc, *varinfos)
4489 {
4490 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
4491 ListCell *lc3;
4492 bool found = false;
4493
4494 /*
4495 * Let's look at plain variables first, because it's the most
4496 * common case and the check is quite cheap. We can simply get the
4497 * attnum and check (with an offset) matched bitmap.
4498 */
4499 if (IsA(varinfo->var, Var))
4500 {
4501 AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4502
4503 /*
4504 * If it's a system attribute, we're done. We don't support
4505 * extended statistics on system attributes, so it's clearly
4506 * not matched. Just keep the expression and continue.
4507 */
4508 if (!AttrNumberIsForUserDefinedAttr(attnum))
4509 {
4510 newlist = lappend(newlist, varinfo);
4511 continue;
4512 }
4513
4514 /* apply the same offset as above */
4515 attnum += attnum_offset;
4516
4517 /* if it's not matched, keep the varinfo */
4518 if (!bms_is_member(attnum, matched))
4519 newlist = lappend(newlist, varinfo);
4520
4521 /* The rest of the loop deals with complex expressions. */
4522 continue;
4523 }
4524
4525 /*
4526 * Process complex expressions, not just simple Vars.
4527 *
4528 * First, we search for an exact match of an expression. If we
4529 * find one, we can just discard the whole GroupVarInfo, with all
4530 * the variables we extracted from it.
4531 *
4532 * Otherwise we inspect the individual vars, and try matching it
4533 * to variables in the item.
4534 */
4535 foreach(lc3, matched_info->exprs)
4536 {
4537 Node *expr = (Node *) lfirst(lc3);
4538
4539 if (equal(varinfo->var, expr))
4540 {
4541 found = true;
4542 break;
4543 }
4544 }
4545
4546 /* found exact match, skip */
4547 if (found)
4548 continue;
4549
4550 newlist = lappend(newlist, varinfo);
4551 }
4552
4553 *varinfos = newlist;
4554 *ndistinct = item->ndistinct;
4555 return true;
4556 }
4557
4558 return false;
4559 }
4560
4561 /*
4562 * convert_to_scalar
4563 * Convert non-NULL values of the indicated types to the comparison
4564 * scale needed by scalarineqsel().
4565 * Returns "true" if successful.
4566 *
4567 * XXX this routine is a hack: ideally we should look up the conversion
4568 * subroutines in pg_type.
4569 *
4570 * All numeric datatypes are simply converted to their equivalent
4571 * "double" values. (NUMERIC values that are outside the range of "double"
4572 * are clamped to +/- HUGE_VAL.)
4573 *
4574 * String datatypes are converted by convert_string_to_scalar(),
4575 * which is explained below. The reason why this routine deals with
4576 * three values at a time, not just one, is that we need it for strings.
4577 *
4578 * The bytea datatype is just enough different from strings that it has
4579 * to be treated separately.
4580 *
4581 * The several datatypes representing absolute times are all converted
4582 * to Timestamp, which is actually an int64, and then we promote that to
4583 * a double. Note this will give correct results even for the "special"
4584 * values of Timestamp, since those are chosen to compare correctly;
4585 * see timestamp_cmp.
4586 *
4587 * The several datatypes representing relative times (intervals) are all
4588 * converted to measurements expressed in seconds.
4589 */
4590 static bool
4591 convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue,
4592 Datum lobound, Datum hibound, Oid boundstypid,
4593 double *scaledlobound, double *scaledhibound)
4594 {
4595 bool failure = false;
4596
4597 /*
4598 * Both the valuetypid and the boundstypid should exactly match the
4599 * declared input type(s) of the operator we are invoked for. However,
4600 * extensions might try to use scalarineqsel as estimator for operators
4601 * with input type(s) we don't handle here; in such cases, we want to
4602 * return false, not fail. In any case, we mustn't assume that valuetypid
4603 * and boundstypid are identical.
4604 *
4605 * XXX The histogram we are interpolating between points of could belong
4606 * to a column that's only binary-compatible with the declared type. In
4607 * essence we are assuming that the semantics of binary-compatible types
4608 * are enough alike that we can use a histogram generated with one type's
4609 * operators to estimate selectivity for the other's. This is outright
4610 * wrong in some cases --- in particular signed versus unsigned
4611 * interpretation could trip us up. But it's useful enough in the
4612 * majority of cases that we do it anyway. Should think about more
4613 * rigorous ways to do it.
4614 */
4615 switch (valuetypid)
4616 {
4617 /*
4618 * Built-in numeric types
4619 */
4620 case BOOLOID:
4621 case INT2OID:
4622 case INT4OID:
4623 case INT8OID:
4624 case FLOAT4OID:
4625 case FLOAT8OID:
4626 case NUMERICOID:
4627 case OIDOID:
4628 case REGPROCOID:
4629 case REGPROCEDUREOID:
4630 case REGOPEROID:
4631 case REGOPERATOROID:
4632 case REGCLASSOID:
4633 case REGTYPEOID:
4634 case REGCOLLATIONOID:
4635 case REGCONFIGOID:
4636 case REGDICTIONARYOID:
4637 case REGROLEOID:
4638 case REGNAMESPACEOID:
4639 *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4640 &failure);
4641 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4642 &failure);
4643 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4644 &failure);
4645 return !failure;
4646
4647 /*
4648 * Built-in string types
4649 */
4650 case CHAROID:
4651 case BPCHAROID:
4652 case VARCHAROID:
4653 case TEXTOID:
4654 case NAMEOID:
4655 {
4656 char *valstr = convert_string_datum(value, valuetypid,
4657 collid, &failure);
4658 char *lostr = convert_string_datum(lobound, boundstypid,
4659 collid, &failure);
4660 char *histr = convert_string_datum(hibound, boundstypid,
4661 collid, &failure);
4662
4663 /*
4664 * Bail out if any of the values is not of string type. We
4665 * might leak converted strings for the other value(s), but
4666 * that's not worth troubling over.
4667 */
4668 if (failure)
4669 return false;
4670
4671 convert_string_to_scalar(valstr, scaledvalue,
4672 lostr, scaledlobound,
4673 histr, scaledhibound);
4674 pfree(valstr);
4675 pfree(lostr);
4676 pfree(histr);
4677 return true;
4678 }
4679
4680 /*
4681 * Built-in bytea type
4682 */
4683 case BYTEAOID:
4684 {
4685 /* We only support bytea vs bytea comparison */
4686 if (boundstypid != BYTEAOID)
4687 return false;
4688 convert_bytea_to_scalar(value, scaledvalue,
4689 lobound, scaledlobound,
4690 hibound, scaledhibound);
4691 return true;
4692 }
4693
4694 /*
4695 * Built-in time types
4696 */
4697 case TIMESTAMPOID:
4698 case TIMESTAMPTZOID:
4699 case DATEOID:
4700 case INTERVALOID:
4701 case TIMEOID:
4702 case TIMETZOID:
4703 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
4704 &failure);
4705 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
4706 &failure);
4707 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
4708 &failure);
4709 return !failure;
4710
4711 /*
4712 * Built-in network types
4713 */
4714 case INETOID:
4715 case CIDROID:
4716 case MACADDROID:
4717 case MACADDR8OID:
4718 *scaledvalue = convert_network_to_scalar(value, valuetypid,
4719 &failure);
4720 *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
4721 &failure);
4722 *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
4723 &failure);
4724 return !failure;
4725 }
4726 /* Don't know how to convert */
4727 *scaledvalue = *scaledlobound = *scaledhibound = 0;
4728 return false;
4729 }
4730
4731 /*
4732 * Do convert_to_scalar()'s work for any numeric data type.
4733 *
4734 * On failure (e.g., unsupported typid), set *failure to true;
4735 * otherwise, that variable is not changed.
4736 */
4737 static double
4738 convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
4739 {
4740 switch (typid)
4741 {
4742 case BOOLOID:
4743 return (double) DatumGetBool(value);
4744 case INT2OID:
4745 return (double) DatumGetInt16(value);
4746 case INT4OID:
4747 return (double) DatumGetInt32(value);
4748 case INT8OID:
4749 return (double) DatumGetInt64(value);
4750 case FLOAT4OID:
4751 return (double) DatumGetFloat4(value);
4752 case FLOAT8OID:
4753 return (double) DatumGetFloat8(value);
4754 case NUMERICOID:
4755 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4756 return (double)
4757 DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
4758 value));
4759 case OIDOID:
4760 case REGPROCOID:
4761 case REGPROCEDUREOID:
4762 case REGOPEROID:
4763 case REGOPERATOROID:
4764 case REGCLASSOID:
4765 case REGTYPEOID:
4766 case REGCOLLATIONOID:
4767 case REGCONFIGOID:
4768 case REGDICTIONARYOID:
4769 case REGROLEOID:
4770 case REGNAMESPACEOID:
4771 /* we can treat OIDs as integers... */
4772 return (double) DatumGetObjectId(value);
4773 }
4774
4775 *failure = true;
4776 return 0;
4777 }
4778
4779 /*
4780 * Do convert_to_scalar()'s work for any character-string data type.
4781 *
4782 * String datatypes are converted to a scale that ranges from 0 to 1,
4783 * where we visualize the bytes of the string as fractional digits.
4784 *
4785 * We do not want the base to be 256, however, since that tends to
4786 * generate inflated selectivity estimates; few databases will have
4787 * occurrences of all 256 possible byte values at each position.
4788 * Instead, use the smallest and largest byte values seen in the bounds
4789 * as the estimated range for each byte, after some fudging to deal with
4790 * the fact that we probably aren't going to see the full range that way.
4791 *
4792 * An additional refinement is that we discard any common prefix of the
4793 * three strings before computing the scaled values. This allows us to
4794 * "zoom in" when we encounter a narrow data range. An example is a phone
4795 * number database where all the values begin with the same area code.
4796 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
4797 * so this is more likely to happen than you might think.)
4798 */
4799 static void
4800 convert_string_to_scalar(char *value,
4801 double *scaledvalue,
4802 char *lobound,
4803 double *scaledlobound,
4804 char *hibound,
4805 double *scaledhibound)
4806 {
4807 int rangelo,
4808 rangehi;
4809 char *sptr;
4810
4811 rangelo = rangehi = (unsigned char) hibound[0];
4812 for (sptr = lobound; *sptr; sptr++)
4813 {
4814 if (rangelo > (unsigned char) *sptr)
4815 rangelo = (unsigned char) *sptr;
4816 if (rangehi < (unsigned char) *sptr)
4817 rangehi = (unsigned char) *sptr;
4818 }
4819 for (sptr = hibound; *sptr; sptr++)
4820 {
4821 if (rangelo > (unsigned char) *sptr)
4822 rangelo = (unsigned char) *sptr;
4823 if (rangehi < (unsigned char) *sptr)
4824 rangehi = (unsigned char) *sptr;
4825 }
4826 /* If range includes any upper-case ASCII chars, make it include all */
4827 if (rangelo <= 'Z' && rangehi >= 'A')
4828 {
4829 if (rangelo > 'A')
4830 rangelo = 'A';
4831 if (rangehi < 'Z')
4832 rangehi = 'Z';
4833 }
4834 /* Ditto lower-case */
4835 if (rangelo <= 'z' && rangehi >= 'a')
4836 {
4837 if (rangelo > 'a')
4838 rangelo = 'a';
4839 if (rangehi < 'z')
4840 rangehi = 'z';
4841 }
4842 /* Ditto digits */
4843 if (rangelo <= '9' && rangehi >= '0')
4844 {
4845 if (rangelo > '0')
4846 rangelo = '0';
4847 if (rangehi < '9')
4848 rangehi = '9';
4849 }
4850
4851 /*
4852 * If range includes less than 10 chars, assume we have not got enough
4853 * data, and make it include regular ASCII set.
4854 */
4855 if (rangehi - rangelo < 9)
4856 {
4857 rangelo = ' ';
4858 rangehi = 127;
4859 }
4860
4861 /*
4862 * Now strip any common prefix of the three strings.
4863 */
4864 while (*lobound)
4865 {
4866 if (*lobound != *hibound || *lobound != *value)
4867 break;
4868 lobound++, hibound++, value++;
4869 }
4870
4871 /*
4872 * Now we can do the conversions.
4873 */
4874 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4875 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4876 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4877 }
4878
4879 static double
4880 convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
4881 {
4882 int slen = strlen(value);
4883 double num,
4884 denom,
4885 base;
4886
4887 if (slen <= 0)
4888 return 0.0; /* empty string has scalar value 0 */
4889
4890 /*
4891 * There seems little point in considering more than a dozen bytes from
4892 * the string. Since base is at least 10, that will give us nominal
4893 * resolution of at least 12 decimal digits, which is surely far more
4894 * precision than this estimation technique has got anyway (especially in
4895 * non-C locales). Also, even with the maximum possible base of 256, this
4896 * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4897 * overflow on any known machine.
4898 */
4899 if (slen > 12)
4900 slen = 12;
4901
4902 /* Convert initial characters to fraction */
4903 base = rangehi - rangelo + 1;
4904 num = 0.0;
4905 denom = base;
4906 while (slen-- > 0)
4907 {
4908 int ch = (unsigned char) *value++;
4909
4910 if (ch < rangelo)
4911 ch = rangelo - 1;
4912 else if (ch > rangehi)
4913 ch = rangehi + 1;
4914 num += ((double) (ch - rangelo)) / denom;
4915 denom *= base;
4916 }
4917
4918 return num;
4919 }
4920
4921 /*
4922 * Convert a string-type Datum into a palloc'd, null-terminated string.
4923 *
4924 * On failure (e.g., unsupported typid), set *failure to true;
4925 * otherwise, that variable is not changed. (We'll return NULL on failure.)
4926 *
4927 * When using a non-C locale, we must pass the string through pg_strxfrm()
4928 * before continuing, so as to generate correct locale-specific results.
4929 */
4930 static char *
4931 convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
4932 {
4933 char *val;
4934 pg_locale_t mylocale;
4935
4936 switch (typid)
4937 {
4938 case CHAROID:
4939 val = (char *) palloc(2);
4940 val[0] = DatumGetChar(value);
4941 val[1] = '\0';
4942 break;
4943 case BPCHAROID:
4944 case VARCHAROID:
4945 case TEXTOID:
4946 val = TextDatumGetCString(value);
4947 break;
4948 case NAMEOID:
4949 {
4950 NameData *nm = (NameData *) DatumGetPointer(value);
4951
4952 val = pstrdup(NameStr(*nm));
4953 break;
4954 }
4955 default:
4956 *failure = true;
4957 return NULL;
4958 }
4959
4960 /*
4961 * If we don't have a collation, act as though it's "C". This would
4962 * normally happen only for the "char" type, but perhaps there are other
4963 * cases.
4964 */
4965 if (!OidIsValid(collid))
4966 return val;
4967
4968 mylocale = pg_newlocale_from_collation(collid);
4969
4970 if (!mylocale->collate_is_c)
4971 {
4972 char *xfrmstr;
4973 size_t xfrmlen;
4974 size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4975
4976 /*
4977 * XXX: We could guess at a suitable output buffer size and only call
4978 * pg_strxfrm() twice if our guess is too small.
4979 *
4980 * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4981 * bogus data or set an error. This is not really a problem unless it
4982 * crashes since it will only give an estimation error and nothing
4983 * fatal.
4984 *
4985 * XXX: we do not check pg_strxfrm_enabled(). On some platforms and in
4986 * some cases, libc strxfrm() may return the wrong results, but that
4987 * will only lead to an estimation error.
4988 */
4989 xfrmlen = pg_strxfrm(NULL, val, 0, mylocale);
4990 #ifdef WIN32
4991
4992 /*
4993 * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4994 * of trying to allocate this much memory (and fail), just return the
4995 * original string unmodified as if we were in the C locale.
4996 */
4997 if (xfrmlen == INT_MAX)
4998 return val;
4999 #endif
5000 xfrmstr = (char *) palloc(xfrmlen + 1);
5001 xfrmlen2 = pg_strxfrm(xfrmstr, val, xfrmlen + 1, mylocale);
5002
5003 /*
5004 * Some systems (e.g., glibc) can return a smaller value from the
5005 * second call than the first; thus the Assert must be <= not ==.
5006 */
5007 Assert(xfrmlen2 <= xfrmlen);
5008 pfree(val);
5009 val = xfrmstr;
5010 }
5011
5012 return val;
5013 }
5014
5015 /*
5016 * Do convert_to_scalar()'s work for any bytea data type.
5017 *
5018 * Very similar to convert_string_to_scalar except we can't assume
5019 * null-termination and therefore pass explicit lengths around.
5020 *
5021 * Also, assumptions about likely "normal" ranges of characters have been
5022 * removed - a data range of 0..255 is always used, for now. (Perhaps
5023 * someday we will add information about actual byte data range to
5024 * pg_statistic.)
5025 */
5026 static void
5027 convert_bytea_to_scalar(Datum value,
5028 double *scaledvalue,
5029 Datum lobound,
5030 double *scaledlobound,
5031 Datum hibound,
5032 double *scaledhibound)
5033 {
5034 bytea *valuep = DatumGetByteaPP(value);
5035 bytea *loboundp = DatumGetByteaPP(lobound);
5036 bytea *hiboundp = DatumGetByteaPP(hibound);
5037 int rangelo,
5038 rangehi,
5039 valuelen = VARSIZE_ANY_EXHDR(valuep),
5040 loboundlen = VARSIZE_ANY_EXHDR(loboundp),
5041 hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
5042 i,
5043 minlen;
5044 unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
5045 unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
5046 unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
5047
5048 /*
5049 * Assume bytea data is uniformly distributed across all byte values.
5050 */
5051 rangelo = 0;
5052 rangehi = 255;
5053
5054 /*
5055 * Now strip any common prefix of the three strings.
5056 */
5057 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
5058 for (i = 0; i < minlen; i++)
5059 {
5060 if (*lostr != *histr || *lostr != *valstr)
5061 break;
5062 lostr++, histr++, valstr++;
5063 loboundlen--, hiboundlen--, valuelen--;
5064 }
5065
5066 /*
5067 * Now we can do the conversions.
5068 */
5069 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
5070 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
5071 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
5072 }
5073
5074 static double
5075 convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
5076 int rangelo, int rangehi)
5077 {
5078 double num,
5079 denom,
5080 base;
5081
5082 if (valuelen <= 0)
5083 return 0.0; /* empty string has scalar value 0 */
5084
5085 /*
5086 * Since base is 256, need not consider more than about 10 chars (even
5087 * this many seems like overkill)
5088 */
5089 if (valuelen > 10)
5090 valuelen = 10;
5091
5092 /* Convert initial characters to fraction */
5093 base = rangehi - rangelo + 1;
5094 num = 0.0;
5095 denom = base;
5096 while (valuelen-- > 0)
5097 {
5098 int ch = *value++;
5099
5100 if (ch < rangelo)
5101 ch = rangelo - 1;
5102 else if (ch > rangehi)
5103 ch = rangehi + 1;
5104 num += ((double) (ch - rangelo)) / denom;
5105 denom *= base;
5106 }
5107
5108 return num;
5109 }
5110
5111 /*
5112 * Do convert_to_scalar()'s work for any timevalue data type.
5113 *
5114 * On failure (e.g., unsupported typid), set *failure to true;
5115 * otherwise, that variable is not changed.
5116 */
5117 static double
5118 convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
5119 {
5120 switch (typid)
5121 {
5122 case TIMESTAMPOID:
5123 return DatumGetTimestamp(value);
5124 case TIMESTAMPTZOID:
5125 return DatumGetTimestampTz(value);
5126 case DATEOID:
5127 return date2timestamp_no_overflow(DatumGetDateADT(value));
5128 case INTERVALOID:
5129 {
5130 Interval *interval = DatumGetIntervalP(value);
5131
5132 /*
5133 * Convert the month part of Interval to days using assumed
5134 * average month length of 365.25/12.0 days. Not too
5135 * accurate, but plenty good enough for our purposes.
5136 *
5137 * This also works for infinite intervals, which just have all
5138 * fields set to INT_MIN/INT_MAX, and so will produce a result
5139 * smaller/larger than any finite interval.
5140 */
5141 return interval->time + interval->day * (double) USECS_PER_DAY +
5142 interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
5143 }
5144 case TIMEOID:
5145 return DatumGetTimeADT(value);
5146 case TIMETZOID:
5147 {
5148 TimeTzADT *timetz = DatumGetTimeTzADTP(value);
5149
5150 /* use GMT-equivalent time */
5151 return (double) (timetz->time + (timetz->zone * 1000000.0));
5152 }
5153 }
5154
5155 *failure = true;
5156 return 0;
5157 }
5158
5159
5160 /*
5161 * get_restriction_variable
5162 * Examine the args of a restriction clause to see if it's of the
5163 * form (variable op pseudoconstant) or (pseudoconstant op variable),
5164 * where "variable" could be either a Var or an expression in vars of a
5165 * single relation. If so, extract information about the variable,
5166 * and also indicate which side it was on and the other argument.
5167 *
5168 * Inputs:
5169 * root: the planner info
5170 * args: clause argument list
5171 * varRelid: see specs for restriction selectivity functions
5172 *
5173 * Outputs: (these are valid only if true is returned)
5174 * *vardata: gets information about variable (see examine_variable)
5175 * *other: gets other clause argument, aggressively reduced to a constant
5176 * *varonleft: set true if variable is on the left, false if on the right
5177 *
5178 * Returns true if a variable is identified, otherwise false.
5179 *
5180 * Note: if there are Vars on both sides of the clause, we must fail, because
5181 * callers are expecting that the other side will act like a pseudoconstant.
5182 */
5183 bool
5184 get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
5185 VariableStatData *vardata, Node **other,
5186 bool *varonleft)
5187 {
5188 Node *left,
5189 *right;
5190 VariableStatData rdata;
5191
5192 /* Fail if not a binary opclause (probably shouldn't happen) */
5193 if (list_length(args) != 2)
5194 return false;
5195
5196 left = (Node *) linitial(args);
5197 right = (Node *) lsecond(args);
5198
5199 /*
5200 * Examine both sides. Note that when varRelid is nonzero, Vars of other
5201 * relations will be treated as pseudoconstants.
5202 */
5203 examine_variable(root, left, varRelid, vardata);
5204 examine_variable(root, right, varRelid, &rdata);
5205
5206 /*
5207 * If one side is a variable and the other not, we win.
5208 */
5209 if (vardata->rel && rdata.rel == NULL)
5210 {
5211 *varonleft = true;
5212 *other = estimate_expression_value(root, rdata.var);
5213 /* Assume we need no ReleaseVariableStats(rdata) here */
5214 return true;
5215 }
5216
5217 if (vardata->rel == NULL && rdata.rel)
5218 {
5219 *varonleft = false;
5220 *other = estimate_expression_value(root, vardata->var);
5221 /* Assume we need no ReleaseVariableStats(*vardata) here */
5222 *vardata = rdata;
5223 return true;
5224 }
5225
5226 /* Oops, clause has wrong structure (probably var op var) */
5227 ReleaseVariableStats(*vardata);
5228 ReleaseVariableStats(rdata);
5229
5230 return false;
5231 }
5232
5233 /*
5234 * get_join_variables
5235 * Apply examine_variable() to each side of a join clause.
5236 * Also, attempt to identify whether the join clause has the same
5237 * or reversed sense compared to the SpecialJoinInfo.
5238 *
5239 * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
5240 * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
5241 * where we can't tell for sure, we default to assuming it's normal.
5242 */
5243 void
5244 get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
5245 VariableStatData *vardata1, VariableStatData *vardata2,
5246 bool *join_is_reversed)
5247 {
5248 Node *left,
5249 *right;
5250
5251 if (list_length(args) != 2)
5252 elog(ERROR, "join operator should take two arguments");
5253
5254 left = (Node *) linitial(args);
5255 right = (Node *) lsecond(args);
5256
5257 examine_variable(root, left, 0, vardata1);
5258 examine_variable(root, right, 0, vardata2);
5259
5260 if (vardata1->rel &&
5261 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
5262 *join_is_reversed = true; /* var1 is on RHS */
5263 else if (vardata2->rel &&
5264 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
5265 *join_is_reversed = true; /* var2 is on LHS */
5266 else
5267 *join_is_reversed = false;
5268 }
5269
5270 /* statext_expressions_load copies the tuple, so just pfree it. */
5271 static void
5272 ReleaseDummy(HeapTuple tuple)
5273 {
5274 pfree(tuple);
5275 }
5276
5277 /*
5278 * examine_variable
5279 * Try to look up statistical data about an expression.
5280 * Fill in a VariableStatData struct to describe the expression.
5281 *
5282 * Inputs:
5283 * root: the planner info
5284 * node: the expression tree to examine
5285 * varRelid: see specs for restriction selectivity functions
5286 *
5287 * Outputs: *vardata is filled as follows:
5288 * var: the input expression (with any phvs or binary relabeling stripped,
5289 * if it is or contains a variable; but otherwise unchanged)
5290 * rel: RelOptInfo for relation containing variable; NULL if expression
5291 * contains no Vars (NOTE this could point to a RelOptInfo of a
5292 * subquery, not one in the current query).
5293 * statsTuple: the pg_statistic entry for the variable, if one exists;
5294 * otherwise NULL.
5295 * freefunc: pointer to a function to release statsTuple with.
5296 * vartype: exposed type of the expression; this should always match
5297 * the declared input type of the operator we are estimating for.
5298 * atttype, atttypmod: actual type/typmod of the "var" expression. This is
5299 * commonly the same as the exposed type of the variable argument,
5300 * but can be different in binary-compatible-type cases.
5301 * isunique: true if we were able to match the var to a unique index, a
5302 * single-column DISTINCT or GROUP-BY clause, implying its values are
5303 * unique for this query. (Caution: this should be trusted for
5304 * statistical purposes only, since we do not check indimmediate nor
5305 * verify that the exact same definition of equality applies.)
5306 * acl_ok: true if current user has permission to read all table rows from
5307 * the column(s) underlying the pg_statistic entry. This is consulted by
5308 * statistic_proc_security_check().
5309 *
5310 * Caller is responsible for doing ReleaseVariableStats() before exiting.
5311 */
5312 void
5313 examine_variable(PlannerInfo *root, Node *node, int varRelid,
5314 VariableStatData *vardata)
5315 {
5316 Node *basenode;
5317 Relids varnos;
5318 Relids basevarnos;
5319 RelOptInfo *onerel;
5320
5321 /* Make sure we don't return dangling pointers in vardata */
5322 MemSet(vardata, 0, sizeof(VariableStatData));
5323
5324 /* Save the exposed type of the expression */
5325 vardata->vartype = exprType(node);
5326
5327 /*
5328 * PlaceHolderVars are transparent for the purpose of statistics lookup;
5329 * they do not alter the value distribution of the underlying expression.
5330 * However, they can obscure the structure, preventing us from recognizing
5331 * matches to base columns, index expressions, or extended statistics. So
5332 * strip them out first.
5333 */
5334 basenode = strip_all_phvs_deep(root, node);
5335
5336 /*
5337 * Look inside any binary-compatible relabeling. We need to handle nested
5338 * RelabelType nodes here, because the prior stripping of PlaceHolderVars
5339 * may have brought separate RelabelTypes into adjacency.
5340 */
5341 while (IsA(basenode, RelabelType))
5342 basenode = (Node *) ((RelabelType *) basenode)->arg;
5343
5344 /* Fast path for a simple Var */
5345 if (IsA(basenode, Var) &&
5346 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5347 {
5348 Var *var = (Var *) basenode;
5349
5350 /* Set up result fields other than the stats tuple */
5351 vardata->var = basenode; /* return Var without phvs or relabeling */
5352 vardata->rel = find_base_rel(root, var->varno);
5353 vardata->atttype = var->vartype;
5354 vardata->atttypmod = var->vartypmod;
5355 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5356
5357 /* Try to locate some stats */
5358 examine_simple_variable(root, var, vardata);
5359
5360 return;
5361 }
5362
5363 /*
5364 * Okay, it's a more complicated expression. Determine variable
5365 * membership. Note that when varRelid isn't zero, only vars of that
5366 * relation are considered "real" vars.
5367 */
5368 varnos = pull_varnos(root, basenode);
5369 basevarnos = bms_difference(varnos, root->outer_join_rels);
5370
5371 onerel = NULL;
5372
5373 if (bms_is_empty(basevarnos))
5374 {
5375 /* No Vars at all ... must be pseudo-constant clause */
5376 }
5377 else
5378 {
5379 int relid;
5380
5381 /* Check if the expression is in vars of a single base relation */
5382 if (bms_get_singleton_member(basevarnos, &relid))
5383 {
5384 if (varRelid == 0 || varRelid == relid)
5385 {
5386 onerel = find_base_rel(root, relid);
5387 vardata->rel = onerel;
5388 node = basenode; /* strip any phvs or relabeling */
5389 }
5390 /* else treat it as a constant */
5391 }
5392 else
5393 {
5394 /* varnos has multiple relids */
5395 if (varRelid == 0)
5396 {
5397 /* treat it as a variable of a join relation */
5398 vardata->rel = find_join_rel(root, varnos);
5399 node = basenode; /* strip any phvs or relabeling */
5400 }
5401 else if (bms_is_member(varRelid, varnos))
5402 {
5403 /* ignore the vars belonging to other relations */
5404 vardata->rel = find_base_rel(root, varRelid);
5405 node = basenode; /* strip any phvs or relabeling */
5406 /* note: no point in expressional-index search here */
5407 }
5408 /* else treat it as a constant */
5409 }
5410 }
5411
5412 bms_free(basevarnos);
5413
5414 vardata->var = node;
5415 vardata->atttype = exprType(node);
5416 vardata->atttypmod = exprTypmod(node);
5417
5418 if (onerel)
5419 {
5420 /*
5421 * We have an expression in vars of a single relation. Try to match
5422 * it to expressional index columns, in hopes of finding some
5423 * statistics.
5424 *
5425 * Note that we consider all index columns including INCLUDE columns,
5426 * since there could be stats for such columns. But the test for
5427 * uniqueness needs to be warier.
5428 *
5429 * XXX it's conceivable that there are multiple matches with different
5430 * index opfamilies; if so, we need to pick one that matches the
5431 * operator we are estimating for. FIXME later.
5432 */
5433 ListCell *ilist;
5434 ListCell *slist;
5435
5436 /*
5437 * The nullingrels bits within the expression could prevent us from
5438 * matching it to expressional index columns or to the expressions in
5439 * extended statistics. So strip them out first.
5440 */
5441 if (bms_overlap(varnos, root->outer_join_rels))
5442 node = remove_nulling_relids(node, root->outer_join_rels, NULL);
5443
5444 foreach(ilist, onerel->indexlist)
5445 {
5446 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5447 ListCell *indexpr_item;
5448 int pos;
5449
5450 indexpr_item = list_head(index->indexprs);
5451 if (indexpr_item == NULL)
5452 continue; /* no expressions here... */
5453
5454 for (pos = 0; pos < index->ncolumns; pos++)
5455 {
5456 if (index->indexkeys[pos] == 0)
5457 {
5458 Node *indexkey;
5459
5460 if (indexpr_item == NULL)
5461 elog(ERROR, "too few entries in indexprs list");
5462 indexkey = (Node *) lfirst(indexpr_item);
5463 if (indexkey && IsA(indexkey, RelabelType))
5464 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5465 if (equal(node, indexkey))
5466 {
5467 /*
5468 * Found a match ... is it a unique index? Tests here
5469 * should match has_unique_index().
5470 */
5471 if (index->unique &&
5472 index->nkeycolumns == 1 &&
5473 pos == 0 &&
5474 (index->indpred == NIL || index->predOK))
5475 vardata->isunique = true;
5476
5477 /*
5478 * Has it got stats? We only consider stats for
5479 * non-partial indexes, since partial indexes probably
5480 * don't reflect whole-relation statistics; the above
5481 * check for uniqueness is the only info we take from
5482 * a partial index.
5483 *
5484 * An index stats hook, however, must make its own
5485 * decisions about what to do with partial indexes.
5486 */
5487 if (get_index_stats_hook &&
5488 (*get_index_stats_hook) (root, index->indexoid,
5489 pos + 1, vardata))
5490 {
5491 /*
5492 * The hook took control of acquiring a stats
5493 * tuple. If it did supply a tuple, it'd better
5494 * have supplied a freefunc.
5495 */
5496 if (HeapTupleIsValid(vardata->statsTuple) &&
5497 !vardata->freefunc)
5498 elog(ERROR, "no function provided to release variable stats with");
5499 }
5500 else if (index->indpred == NIL)
5501 {
5502 vardata->statsTuple =
5503 SearchSysCache3(STATRELATTINH,
5504 ObjectIdGetDatum(index->indexoid),
5505 Int16GetDatum(pos + 1),
5506 BoolGetDatum(false));
5507 vardata->freefunc = ReleaseSysCache;
5508
5509 if (HeapTupleIsValid(vardata->statsTuple))
5510 {
5511 /*
5512 * Test if user has permission to access all
5513 * rows from the index's table.
5514 *
5515 * For simplicity, we insist on the whole
5516 * table being selectable, rather than trying
5517 * to identify which column(s) the index
5518 * depends on.
5519 *
5520 * Note that for an inheritance child,
5521 * permissions are checked on the inheritance
5522 * root parent, and whole-table select
5523 * privilege on the parent doesn't quite
5524 * guarantee that the user could read all
5525 * columns of the child. But in practice it's
5526 * unlikely that any interesting security
5527 * violation could result from allowing access
5528 * to the expression index's stats, so we
5529 * allow it anyway. See similar code in
5530 * examine_simple_variable() for additional
5531 * comments.
5532 */
5533 vardata->acl_ok =
5534 all_rows_selectable(root,
5535 index->rel->relid,
5536 NULL);
5537 }
5538 else
5539 {
5540 /* suppress leakproofness checks later */
5541 vardata->acl_ok = true;
5542 }
5543 }
5544 if (vardata->statsTuple)
5545 break;
5546 }
5547 indexpr_item = lnext(index->indexprs, indexpr_item);
5548 }
5549 }
5550 if (vardata->statsTuple)
5551 break;
5552 }
5553
5554 /*
5555 * Search extended statistics for one with a matching expression.
5556 * There might be multiple ones, so just grab the first one. In the
5557 * future, we might consider the statistics target (and pick the most
5558 * accurate statistics) and maybe some other parameters.
5559 */
5560 foreach(slist, onerel->statlist)
5561 {
5562 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5563 RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5564 ListCell *expr_item;
5565 int pos;
5566
5567 /*
5568 * Stop once we've found statistics for the expression (either
5569 * from extended stats, or for an index in the preceding loop).
5570 */
5571 if (vardata->statsTuple)
5572 break;
5573
5574 /* skip stats without per-expression stats */
5575 if (info->kind != STATS_EXT_EXPRESSIONS)
5576 continue;
5577
5578 /* skip stats with mismatching stxdinherit value */
5579 if (info->inherit != rte->inh)
5580 continue;
5581
5582 pos = 0;
5583 foreach(expr_item, info->exprs)
5584 {
5585 Node *expr = (Node *) lfirst(expr_item);
5586
5587 Assert(expr);
5588
5589 /* strip RelabelType before comparing it */
5590 if (expr && IsA(expr, RelabelType))
5591 expr = (Node *) ((RelabelType *) expr)->arg;
5592
5593 /* found a match, see if we can extract pg_statistic row */
5594 if (equal(node, expr))
5595 {
5596 /*
5597 * XXX Not sure if we should cache the tuple somewhere.
5598 * Now we just create a new copy every time.
5599 */
5600 vardata->statsTuple =
5601 statext_expressions_load(info->statOid, rte->inh, pos);
5602
5603 /* Nothing to release if no data found */
5604 if (vardata->statsTuple != NULL)
5605 {
5606 vardata->freefunc = ReleaseDummy;
5607 }
5608
5609 /*
5610 * Test if user has permission to access all rows from the
5611 * table.
5612 *
5613 * For simplicity, we insist on the whole table being
5614 * selectable, rather than trying to identify which
5615 * column(s) the statistics object depends on.
5616 *
5617 * Note that for an inheritance child, permissions are
5618 * checked on the inheritance root parent, and whole-table
5619 * select privilege on the parent doesn't quite guarantee
5620 * that the user could read all columns of the child. But
5621 * in practice it's unlikely that any interesting security
5622 * violation could result from allowing access to the
5623 * expression stats, so we allow it anyway. See similar
5624 * code in examine_simple_variable() for additional
5625 * comments.
5626 */
5627 vardata->acl_ok = all_rows_selectable(root,
5628 onerel->relid,
5629 NULL);
5630
5631 break;
5632 }
5633
5634 pos++;
5635 }
5636 }
5637 }
5638
5639 bms_free(varnos);
5640 }
5641
5642 /*
5643 * strip_all_phvs_deep
5644 * Deeply strip all PlaceHolderVars in an expression.
5645
5646 * As a performance optimization, we first use a lightweight walker to check
5647 * for the presence of any PlaceHolderVars. The expensive mutator is invoked
5648 * only if a PlaceHolderVar is found, avoiding unnecessary memory allocation
5649 * and tree copying in the common case where no PlaceHolderVars are present.
5650 */
5651 static Node *
5652 strip_all_phvs_deep(PlannerInfo *root, Node *node)
5653 {
5654 /* If there are no PHVs anywhere, we needn't work hard */
5655 if (root->glob->lastPHId == 0)
5656 return node;
5657
5658 if (!contain_placeholder_walker(node, NULL))
5659 return node;
5660 return strip_all_phvs_mutator(node, NULL);
5661 }
5662
5663 /*
5664 * contain_placeholder_walker
5665 * Lightweight walker to check if an expression contains any
5666 * PlaceHolderVars
5667 */
5668 static bool
5669 contain_placeholder_walker(Node *node, void *context)
5670 {
5671 if (node == NULL)
5672 return false;
5673 if (IsA(node, PlaceHolderVar))
5674 return true;
5675
5676 return expression_tree_walker(node, contain_placeholder_walker, context);
5677 }
5678
5679 /*
5680 * strip_all_phvs_mutator
5681 * Mutator to deeply strip all PlaceHolderVars
5682 */
5683 static Node *
5684 strip_all_phvs_mutator(Node *node, void *context)
5685 {
5686 if (node == NULL)
5687 return NULL;
5688 if (IsA(node, PlaceHolderVar))
5689 {
5690 /* Strip it and recurse into its contained expression */
5691 PlaceHolderVar *phv = (PlaceHolderVar *) node;
5692
5693 return strip_all_phvs_mutator((Node *) phv->phexpr, context);
5694 }
5695
5696 return expression_tree_mutator(node, strip_all_phvs_mutator, context);
5697 }
5698
5699 /*
5700 * examine_simple_variable
5701 * Handle a simple Var for examine_variable
5702 *
5703 * This is split out as a subroutine so that we can recurse to deal with
5704 * Vars referencing subqueries (either sub-SELECT-in-FROM or CTE style).
5705 *
5706 * We already filled in all the fields of *vardata except for the stats tuple.
5707 */
5708 static void
5709 examine_simple_variable(PlannerInfo *root, Var *var,
5710 VariableStatData *vardata)
5711 {
5712 RangeTblEntry *rte = root->simple_rte_array[var->varno];
5713
5714 Assert(IsA(rte, RangeTblEntry));
5715
5716 if (get_relation_stats_hook &&
5717 (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
5718 {
5719 /*
5720 * The hook took control of acquiring a stats tuple. If it did supply
5721 * a tuple, it'd better have supplied a freefunc.
5722 */
5723 if (HeapTupleIsValid(vardata->statsTuple) &&
5724 !vardata->freefunc)
5725 elog(ERROR, "no function provided to release variable stats with");
5726 }
5727 else if (rte->rtekind == RTE_RELATION)
5728 {
5729 /*
5730 * Plain table or parent of an inheritance appendrel, so look up the
5731 * column in pg_statistic
5732 */
5733 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
5734 ObjectIdGetDatum(rte->relid),
5735 Int16GetDatum(var->varattno),
5736 BoolGetDatum(rte->inh));
5737 vardata->freefunc = ReleaseSysCache;
5738
5739 if (HeapTupleIsValid(vardata->statsTuple))
5740 {
5741 /*
5742 * Test if user has permission to read all rows from this column.
5743 *
5744 * This requires that the user has the appropriate SELECT
5745 * privileges and that there are no securityQuals from security
5746 * barrier views or RLS policies. If that's not the case, then we
5747 * only permit leakproof functions to be passed pg_statistic data
5748 * in vardata, otherwise the functions might reveal data that the
5749 * user doesn't have permission to see --- see
5750 * statistic_proc_security_check().
5751 */
5752 vardata->acl_ok =
5753 all_rows_selectable(root, var->varno,
5754 bms_make_singleton(var->varattno - FirstLowInvalidHeapAttributeNumber));
5755 }
5756 else
5757 {
5758 /* suppress any possible leakproofness checks later */
5759 vardata->acl_ok = true;
5760 }
5761 }
5762 else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
5763 (rte->rtekind == RTE_CTE && !rte->self_reference))
5764 {
5765 /*
5766 * Plain subquery (not one that was converted to an appendrel) or
5767 * non-recursive CTE. In either case, we can try to find out what the
5768 * Var refers to within the subquery. We skip this for appendrel and
5769 * recursive-CTE cases because any column stats we did find would
5770 * likely not be very relevant.
5771 */
5772 PlannerInfo *subroot;
5773 Query *subquery;
5774 List *subtlist;
5775 TargetEntry *ste;
5776
5777 /*
5778 * Punt if it's a whole-row var rather than a plain column reference.
5779 */
5780 if (var->varattno == InvalidAttrNumber)
5781 return;
5782
5783 /*
5784 * Otherwise, find the subquery's planner subroot.
5785 */
5786 if (rte->rtekind == RTE_SUBQUERY)
5787 {
5788 RelOptInfo *rel;
5789
5790 /*
5791 * Fetch RelOptInfo for subquery. Note that we don't change the
5792 * rel returned in vardata, since caller expects it to be a rel of
5793 * the caller's query level. Because we might already be
5794 * recursing, we can't use that rel pointer either, but have to
5795 * look up the Var's rel afresh.
5796 */
5797 rel = find_base_rel(root, var->varno);
5798
5799 subroot = rel->subroot;
5800 }
5801 else
5802 {
5803 /* CTE case is more difficult */
5804 PlannerInfo *cteroot;
5805 Index levelsup;
5806 int ndx;
5807 int plan_id;
5808 ListCell *lc;
5809
5810 /*
5811 * Find the referenced CTE, and locate the subroot previously made
5812 * for it.
5813 */
5814 levelsup = rte->ctelevelsup;
5815 cteroot = root;
5816 while (levelsup-- > 0)
5817 {
5818 cteroot = cteroot->parent_root;
5819 if (!cteroot) /* shouldn't happen */
5820 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
5821 }
5822
5823 /*
5824 * Note: cte_plan_ids can be shorter than cteList, if we are still
5825 * working on planning the CTEs (ie, this is a side-reference from
5826 * another CTE). So we mustn't use forboth here.
5827 */
5828 ndx = 0;
5829 foreach(lc, cteroot->parse->cteList)
5830 {
5831 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
5832
5833 if (strcmp(cte->ctename, rte->ctename) == 0)
5834 break;
5835 ndx++;
5836 }
5837 if (lc == NULL) /* shouldn't happen */
5838 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
5839 if (ndx >= list_length(cteroot->cte_plan_ids))
5840 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
5841 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
5842 if (plan_id <= 0)
5843 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
5844 subroot = list_nth(root->glob->subroots, plan_id - 1);
5845 }
5846
5847 /* If the subquery hasn't been planned yet, we have to punt */
5848 if (subroot == NULL)
5849 return;
5850 Assert(IsA(subroot, PlannerInfo));
5851
5852 /*
5853 * We must use the subquery parsetree as mangled by the planner, not
5854 * the raw version from the RTE, because we need a Var that will refer
5855 * to the subroot's live RelOptInfos. For instance, if any subquery
5856 * pullup happened during planning, Vars in the targetlist might have
5857 * gotten replaced, and we need to see the replacement expressions.
5858 */
5859 subquery = subroot->parse;
5860 Assert(IsA(subquery, Query));
5861
5862 /*
5863 * Punt if subquery uses set operations or grouping sets, as these
5864 * will mash underlying columns' stats beyond recognition. (Set ops
5865 * are particularly nasty; if we forged ahead, we would return stats
5866 * relevant to only the leftmost subselect...) DISTINCT is also
5867 * problematic, but we check that later because there is a possibility
5868 * of learning something even with it.
5869 */
5870 if (subquery->setOperations ||
5871 subquery->groupingSets)
5872 return;
5873
5874 /* Get the subquery output expression referenced by the upper Var */
5875 if (subquery->returningList)
5876 subtlist = subquery->returningList;
5877 else
5878 subtlist = subquery->targetList;
5879 ste = get_tle_by_resno(subtlist, var->varattno);
5880 if (ste == NULL || ste->resjunk)
5881 elog(ERROR, "subquery %s does not have attribute %d",
5882 rte->eref->aliasname, var->varattno);
5883 var = (Var *) ste->expr;
5884
5885 /*
5886 * If subquery uses DISTINCT, we can't make use of any stats for the
5887 * variable ... but, if it's the only DISTINCT column, we are entitled
5888 * to consider it unique. We do the test this way so that it works
5889 * for cases involving DISTINCT ON.
5890 */
5891 if (subquery->distinctClause)
5892 {
5893 if (list_length(subquery->distinctClause) == 1 &&
5894 targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5895 vardata->isunique = true;
5896 /* cannot go further */
5897 return;
5898 }
5899
5900 /* The same idea as with DISTINCT clause works for a GROUP-BY too */
5901 if (subquery->groupClause)
5902 {
5903 if (list_length(subquery->groupClause) == 1 &&
5904 targetIsInSortList(ste, InvalidOid, subquery->groupClause))
5905 vardata->isunique = true;
5906 /* cannot go further */
5907 return;
5908 }
5909
5910 /*
5911 * If the sub-query originated from a view with the security_barrier
5912 * attribute, we must not look at the variable's statistics, though it
5913 * seems all right to notice the existence of a DISTINCT clause. So
5914 * stop here.
5915 *
5916 * This is probably a harsher restriction than necessary; it's
5917 * certainly OK for the selectivity estimator (which is a C function,
5918 * and therefore omnipotent anyway) to look at the statistics. But
5919 * many selectivity estimators will happily *invoke the operator
5920 * function* to try to work out a good estimate - and that's not OK.
5921 * So for now, don't dig down for stats.
5922 */
5923 if (rte->security_barrier)
5924 return;
5925
5926 /* Can only handle a simple Var of subquery's query level */
5927 if (var && IsA(var, Var) &&
5928 var->varlevelsup == 0)
5929 {
5930 /*
5931 * OK, recurse into the subquery. Note that the original setting
5932 * of vardata->isunique (which will surely be false) is left
5933 * unchanged in this situation. That's what we want, since even
5934 * if the underlying column is unique, the subquery may have
5935 * joined to other tables in a way that creates duplicates.
5936 */
5937 examine_simple_variable(subroot, var, vardata);
5938 }
5939 }
5940 else
5941 {
5942 /*
5943 * Otherwise, the Var comes from a FUNCTION or VALUES RTE. (We won't
5944 * see RTE_JOIN here because join alias Vars have already been
5945 * flattened.) There's not much we can do with function outputs, but
5946 * maybe someday try to be smarter about VALUES.
5947 */
5948 }
5949 }
5950
5951 /*
5952 * all_rows_selectable
5953 * Test whether the user has permission to select all rows from a given
5954 * relation.
5955 *
5956 * Inputs:
5957 * root: the planner info
5958 * varno: the index of the relation (assumed to be an RTE_RELATION)
5959 * varattnos: the attributes for which permission is required, or NULL if
5960 * whole-table access is required
5961 *
5962 * Returns true if the user has the required select permissions, and there are
5963 * no securityQuals from security barrier views or RLS policies.
5964 *
5965 * Note that if the relation is an inheritance child relation, securityQuals
5966 * and access permissions are checked against the inheritance root parent (the
5967 * relation actually mentioned in the query) --- see the comments in
5968 * expand_single_inheritance_child() for an explanation of why it has to be
5969 * done this way.
5970 *
5971 * If varattnos is non-NULL, its attribute numbers should be offset by
5972 * FirstLowInvalidHeapAttributeNumber so that system attributes can be
5973 * checked. If varattnos is NULL, only table-level SELECT privileges are
5974 * checked, not any column-level privileges.
5975 *
5976 * Note: if the relation is accessed via a view, this function actually tests
5977 * whether the view owner has permission to select from the relation. To
5978 * ensure that the current user has permission, it is also necessary to check
5979 * that the current user has permission to select from the view, which we do
5980 * at planner-startup --- see subquery_planner().
5981 *
5982 * This is exported so that other estimation functions can use it.
5983 */
5984 bool
5985 all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
5986 {
5987 RelOptInfo *rel = find_base_rel_noerr(root, varno);
5988 RangeTblEntry *rte = planner_rt_fetch(varno, root);
5989 Oid userid;
5990 int varattno;
5991
5992 Assert(rte->rtekind == RTE_RELATION);
5993
5994 /*
5995 * Determine the user ID to use for privilege checks (either the current
5996 * user or the view owner, if we're accessing the table via a view).
5997 *
5998 * Normally the relation will have an associated RelOptInfo from which we
5999 * can find the userid, but it might not if it's a RETURNING Var for an
6000 * INSERT target relation. In that case use the RTEPermissionInfo
6001 * associated with the RTE.
6002 *
6003 * If we navigate up to a parent relation, we keep using the same userid,
6004 * since it's the same in all relations of a given inheritance tree.
6005 */
6006 if (rel)
6007 userid = rel->userid;
6008 else
6009 {
6010 RTEPermissionInfo *perminfo;
6011
6012 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
6013 userid = perminfo->checkAsUser;
6014 }
6015 if (!OidIsValid(userid))
6016 userid = GetUserId();
6017
6018 /*
6019 * Permissions and securityQuals must be checked on the table actually
6020 * mentioned in the query, so if this is an inheritance child, navigate up
6021 * to the inheritance root parent. If the user can read the whole table
6022 * or the required columns there, then they can read from the child table
6023 * too. For per-column checks, we must find out which of the root
6024 * parent's attributes the child relation's attributes correspond to.
6025 */
6026 if (root->append_rel_array != NULL)
6027 {
6028 AppendRelInfo *appinfo;
6029
6030 appinfo = root->append_rel_array[varno];
6031
6032 /*
6033 * Partitions are mapped to their immediate parent, not the root
6034 * parent, so must be ready to walk up multiple AppendRelInfos. But
6035 * stop if we hit a parent that is not RTE_RELATION --- that's a
6036 * flattened UNION ALL subquery, not an inheritance parent.
6037 */
6038 while (appinfo &&
6039 planner_rt_fetch(appinfo->parent_relid,
6040 root)->rtekind == RTE_RELATION)
6041 {
6042 Bitmapset *parent_varattnos = NULL;
6043
6044 /*
6045 * For each child attribute, find the corresponding parent
6046 * attribute. In rare cases, the attribute may be local to the
6047 * child table, in which case, we've got to live with having no
6048 * access to this column.
6049 */
6050 varattno = -1;
6051 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6052 {
6053 AttrNumber attno;
6054 AttrNumber parent_attno;
6055
6056 attno = varattno + FirstLowInvalidHeapAttributeNumber;
6057
6058 if (attno == InvalidAttrNumber)
6059 {
6060 /*
6061 * Whole-row reference, so must map each column of the
6062 * child to the parent table.
6063 */
6064 for (attno = 1; attno <= appinfo->num_child_cols; attno++)
6065 {
6066 parent_attno = appinfo->parent_colnos[attno - 1];
6067 if (parent_attno == 0)
6068 return false; /* attr is local to child */
6069 parent_varattnos =
6070 bms_add_member(parent_varattnos,
6071 parent_attno - FirstLowInvalidHeapAttributeNumber);
6072 }
6073 }
6074 else
6075 {
6076 if (attno < 0)
6077 {
6078 /* System attnos are the same in all tables */
6079 parent_attno = attno;
6080 }
6081 else
6082 {
6083 if (attno > appinfo->num_child_cols)
6084 return false; /* safety check */
6085 parent_attno = appinfo->parent_colnos[attno - 1];
6086 if (parent_attno == 0)
6087 return false; /* attr is local to child */
6088 }
6089 parent_varattnos =
6090 bms_add_member(parent_varattnos,
6091 parent_attno - FirstLowInvalidHeapAttributeNumber);
6092 }
6093 }
6094
6095 /* If the parent is itself a child, continue up */
6096 varno = appinfo->parent_relid;
6097 varattnos = parent_varattnos;
6098 appinfo = root->append_rel_array[varno];
6099 }
6100
6101 /* Perform the access check on this parent rel */
6102 rte = planner_rt_fetch(varno, root);
6103 Assert(rte->rtekind == RTE_RELATION);
6104 }
6105
6106 /*
6107 * For all rows to be accessible, there must be no securityQuals from
6108 * security barrier views or RLS policies.
6109 */
6110 if (rte->securityQuals != NIL)
6111 return false;
6112
6113 /*
6114 * Test for table-level SELECT privilege.
6115 *
6116 * If varattnos is non-NULL, this is sufficient to give access to all
6117 * requested attributes, even for a child table, since we have verified
6118 * that all required child columns have matching parent columns.
6119 *
6120 * If varattnos is NULL (whole-table access requested), this doesn't
6121 * necessarily guarantee that the user can read all columns of a child
6122 * table, but we allow it anyway (see comments in examine_variable()) and
6123 * don't bother checking any column privileges.
6124 */
6125 if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) == ACLCHECK_OK)
6126 return true;
6127
6128 if (varattnos == NULL)
6129 return false; /* whole-table access requested */
6130
6131 /*
6132 * Don't have table-level SELECT privilege, so check per-column
6133 * privileges.
6134 */
6135 varattno = -1;
6136 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6137 {
6138 AttrNumber attno = varattno + FirstLowInvalidHeapAttributeNumber;
6139
6140 if (attno == InvalidAttrNumber)
6141 {
6142 /* Whole-row reference, so must have access to all columns */
6143 if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
6144 ACLMASK_ALL) != ACLCHECK_OK)
6145 return false;
6146 }
6147 else
6148 {
6149 if (pg_attribute_aclcheck(rte->relid, attno, userid,
6150 ACL_SELECT) != ACLCHECK_OK)
6151 return false;
6152 }
6153 }
6154
6155 /* If we reach here, have all required column privileges */
6156 return true;
6157 }
6158
6159 /*
6160 * examine_indexcol_variable
6161 * Try to look up statistical data about an index column/expression.
6162 * Fill in a VariableStatData struct to describe the column.
6163 *
6164 * Inputs:
6165 * root: the planner info
6166 * index: the index whose column we're interested in
6167 * indexcol: 0-based index column number (subscripts index->indexkeys[])
6168 *
6169 * Outputs: *vardata is filled as follows:
6170 * var: the input expression (with any binary relabeling stripped, if
6171 * it is or contains a variable; but otherwise the type is preserved)
6172 * rel: RelOptInfo for table relation containing variable.
6173 * statsTuple: the pg_statistic entry for the variable, if one exists;
6174 * otherwise NULL.
6175 * freefunc: pointer to a function to release statsTuple with.
6176 *
6177 * Caller is responsible for doing ReleaseVariableStats() before exiting.
6178 */
6179 static void
6180 examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
6181 int indexcol, VariableStatData *vardata)
6182 {
6183 AttrNumber colnum;
6184 Oid relid;
6185
6186 if (index->indexkeys[indexcol] != 0)
6187 {
6188 /* Simple variable --- look to stats for the underlying table */
6189 RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6190
6191 Assert(rte->rtekind == RTE_RELATION);
6192 relid = rte->relid;
6193 Assert(relid != InvalidOid);
6194 colnum = index->indexkeys[indexcol];
6195 vardata->rel = index->rel;
6196
6197 if (get_relation_stats_hook &&
6198 (*get_relation_stats_hook) (root, rte, colnum, vardata))
6199 {
6200 /*
6201 * The hook took control of acquiring a stats tuple. If it did
6202 * supply a tuple, it'd better have supplied a freefunc.
6203 */
6204 if (HeapTupleIsValid(vardata->statsTuple) &&
6205 !vardata->freefunc)
6206 elog(ERROR, "no function provided to release variable stats with");
6207 }
6208 else
6209 {
6210 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
6211 ObjectIdGetDatum(relid),
6212 Int16GetDatum(colnum),
6213 BoolGetDatum(rte->inh));
6214 vardata->freefunc = ReleaseSysCache;
6215 }
6216 }
6217 else
6218 {
6219 /* Expression --- maybe there are stats for the index itself */
6220 relid = index->indexoid;
6221 colnum = indexcol + 1;
6222
6223 if (get_index_stats_hook &&
6224 (*get_index_stats_hook) (root, relid, colnum, vardata))
6225 {
6226 /*
6227 * The hook took control of acquiring a stats tuple. If it did
6228 * supply a tuple, it'd better have supplied a freefunc.
6229 */
6230 if (HeapTupleIsValid(vardata->statsTuple) &&
6231 !vardata->freefunc)
6232 elog(ERROR, "no function provided to release variable stats with");
6233 }
6234 else
6235 {
6236 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
6237 ObjectIdGetDatum(relid),
6238 Int16GetDatum(colnum),
6239 BoolGetDatum(false));
6240 vardata->freefunc = ReleaseSysCache;
6241 }
6242 }
6243 }
6244
6245 /*
6246 * Check whether it is permitted to call func_oid passing some of the
6247 * pg_statistic data in vardata. We allow this if either of the following
6248 * conditions is met: (1) the user has SELECT privileges on the table or
6249 * column underlying the pg_statistic data and there are no securityQuals from
6250 * security barrier views or RLS policies, or (2) the function is marked
6251 * leakproof.
6252 */
6253 bool
6254 statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
6255 {
6256 if (vardata->acl_ok)
6257 return true; /* have SELECT privs and no securityQuals */
6258
6259 if (!OidIsValid(func_oid))
6260 return false;
6261
6262 if (get_func_leakproof(func_oid))
6263 return true;
6264
6265 ereport(DEBUG2,
6266 (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
6267 get_func_name(func_oid))));
6268 return false;
6269 }
6270
6271 /*
6272 * get_variable_numdistinct
6273 * Estimate the number of distinct values of a variable.
6274 *
6275 * vardata: results of examine_variable
6276 * *isdefault: set to true if the result is a default rather than based on
6277 * anything meaningful.
6278 *
6279 * NB: be careful to produce a positive integral result, since callers may
6280 * compare the result to exact integer counts, or might divide by it.
6281 */
6282 double
6283 get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
6284 {
6285 double stadistinct;
6286 double stanullfrac = 0.0;
6287 double ntuples;
6288
6289 *isdefault = false;
6290
6291 /*
6292 * Determine the stadistinct value to use. There are cases where we can
6293 * get an estimate even without a pg_statistic entry, or can get a better
6294 * value than is in pg_statistic. Grab stanullfrac too if we can find it
6295 * (otherwise, assume no nulls, for lack of any better idea).
6296 */
6297 if (HeapTupleIsValid(vardata->statsTuple))
6298 {
6299 /* Use the pg_statistic entry */
6300 Form_pg_statistic stats;
6301
6302 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
6303 stadistinct = stats->stadistinct;
6304 stanullfrac = stats->stanullfrac;
6305 }
6306 else if (vardata->vartype == BOOLOID)
6307 {
6308 /*
6309 * Special-case boolean columns: presumably, two distinct values.
6310 *
6311 * Are there any other datatypes we should wire in special estimates
6312 * for?
6313 */
6314 stadistinct = 2.0;
6315 }
6316 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
6317 {
6318 /*
6319 * If the Var represents a column of a VALUES RTE, assume it's unique.
6320 * This could of course be very wrong, but it should tend to be true
6321 * in well-written queries. We could consider examining the VALUES'
6322 * contents to get some real statistics; but that only works if the
6323 * entries are all constants, and it would be pretty expensive anyway.
6324 */
6325 stadistinct = -1.0; /* unique (and all non null) */
6326 }
6327 else
6328 {
6329 /*
6330 * We don't keep statistics for system columns, but in some cases we
6331 * can infer distinctness anyway.
6332 */
6333 if (vardata->var && IsA(vardata->var, Var))
6334 {
6335 switch (((Var *) vardata->var)->varattno)
6336 {
6337 case SelfItemPointerAttributeNumber:
6338 stadistinct = -1.0; /* unique (and all non null) */
6339 break;
6340 case TableOidAttributeNumber:
6341 stadistinct = 1.0; /* only 1 value */
6342 break;
6343 default:
6344 stadistinct = 0.0; /* means "unknown" */
6345 break;
6346 }
6347 }
6348 else
6349 stadistinct = 0.0; /* means "unknown" */
6350
6351 /*
6352 * XXX consider using estimate_num_groups on expressions?
6353 */
6354 }
6355
6356 /*
6357 * If there is a unique index, DISTINCT or GROUP-BY clause for the
6358 * variable, assume it is unique no matter what pg_statistic says; the
6359 * statistics could be out of date, or we might have found a partial
6360 * unique index that proves the var is unique for this query. However,
6361 * we'd better still believe the null-fraction statistic.
6362 */
6363 if (vardata->isunique)
6364 stadistinct = -1.0 * (1.0 - stanullfrac);
6365
6366 /*
6367 * If we had an absolute estimate, use that.
6368 */
6369 if (stadistinct > 0.0)
6370 return clamp_row_est(stadistinct);
6371
6372 /*
6373 * Otherwise we need to get the relation size; punt if not available.
6374 */
6375 if (vardata->rel == NULL)
6376 {
6377 *isdefault = true;
6378 return DEFAULT_NUM_DISTINCT;
6379 }
6380 ntuples = vardata->rel->tuples;
6381 if (ntuples <= 0.0)
6382 {
6383 *isdefault = true;
6384 return DEFAULT_NUM_DISTINCT;
6385 }
6386
6387 /*
6388 * If we had a relative estimate, use that.
6389 */
6390 if (stadistinct < 0.0)
6391 return clamp_row_est(-stadistinct * ntuples);
6392
6393 /*
6394 * With no data, estimate ndistinct = ntuples if the table is small, else
6395 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
6396 * that the behavior isn't discontinuous.
6397 */
6398 if (ntuples < DEFAULT_NUM_DISTINCT)
6399 return clamp_row_est(ntuples);
6400
6401 *isdefault = true;
6402 return DEFAULT_NUM_DISTINCT;
6403 }
6404
6405 /*
6406 * get_variable_range
6407 * Estimate the minimum and maximum value of the specified variable.
6408 * If successful, store values in *min and *max, and return true.
6409 * If no data available, return false.
6410 *
6411 * sortop is the "<" comparison operator to use. This should generally
6412 * be "<" not ">", as only the former is likely to be found in pg_statistic.
6413 * The collation must be specified too.
6414 */
6415 static bool
6416 get_variable_range(PlannerInfo *root, VariableStatData *vardata,
6417 Oid sortop, Oid collation,
6418 Datum *min, Datum *max)
6419 {
6420 Datum tmin = 0;
6421 Datum tmax = 0;
6422 bool have_data = false;
6423 int16 typLen;
6424 bool typByVal;
6425 Oid opfuncoid;
6426 FmgrInfo opproc;
6427 AttStatsSlot sslot;
6428
6429 /*
6430 * XXX It's very tempting to try to use the actual column min and max, if
6431 * we can get them relatively-cheaply with an index probe. However, since
6432 * this function is called many times during join planning, that could
6433 * have unpleasant effects on planning speed. Need more investigation
6434 * before enabling this.
6435 */
6436 #ifdef NOT_USED
6437 if (get_actual_variable_range(root, vardata, sortop, collation, min, max))
6438 return true;
6439 #endif
6440
6441 if (!HeapTupleIsValid(vardata->statsTuple))
6442 {
6443 /* no stats available, so default result */
6444 return false;
6445 }
6446
6447 /*
6448 * If we can't apply the sortop to the stats data, just fail. In
6449 * principle, if there's a histogram and no MCVs, we could return the
6450 * histogram endpoints without ever applying the sortop ... but it's
6451 * probably not worth trying, because whatever the caller wants to do with
6452 * the endpoints would likely fail the security check too.
6453 */
6454 if (!statistic_proc_security_check(vardata,
6455 (opfuncoid = get_opcode(sortop))))
6456 return false;
6457
6458 opproc.fn_oid = InvalidOid; /* mark this as not looked up yet */
6459
6460 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
6461
6462 /*
6463 * If there is a histogram with the ordering we want, grab the first and
6464 * last values.
6465 */
6466 if (get_attstatsslot(&sslot, vardata->statsTuple,
6467 STATISTIC_KIND_HISTOGRAM, sortop,
6468 ATTSTATSSLOT_VALUES))
6469 {
6470 if (sslot.stacoll == collation && sslot.nvalues > 0)
6471 {
6472 tmin = datumCopy(sslot.values[0], typByVal, typLen);
6473 tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
6474 have_data = true;
6475 }
6476 free_attstatsslot(&sslot);
6477 }
6478
6479 /*
6480 * Otherwise, if there is a histogram with some other ordering, scan it
6481 * and get the min and max values according to the ordering we want. This
6482 * of course may not find values that are really extremal according to our
6483 * ordering, but it beats ignoring available data.
6484 */
6485 if (!have_data &&
6486 get_attstatsslot(&sslot, vardata->statsTuple,
6487 STATISTIC_KIND_HISTOGRAM, InvalidOid,
6488 ATTSTATSSLOT_VALUES))
6489 {
6490 get_stats_slot_range(&sslot, opfuncoid, &opproc,
6491 collation, typLen, typByVal,
6492 &tmin, &tmax, &have_data);
6493 free_attstatsslot(&sslot);
6494 }
6495
6496 /*
6497 * If we have most-common-values info, look for extreme MCVs. This is
6498 * needed even if we also have a histogram, since the histogram excludes
6499 * the MCVs. However, if we *only* have MCVs and no histogram, we should
6500 * be pretty wary of deciding that that is a full representation of the
6501 * data. Proceed only if the MCVs represent the whole table (to within
6502 * roundoff error).
6503 */
6504 if (get_attstatsslot(&sslot, vardata->statsTuple,
6505 STATISTIC_KIND_MCV, InvalidOid,
6506 have_data ? ATTSTATSSLOT_VALUES :
6507 (ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)))
6508 {
6509 bool use_mcvs = have_data;
6510
6511 if (!have_data)
6512 {
6513 double sumcommon = 0.0;
6514 double nullfrac;
6515 int i;
6516
6517 for (i = 0; i < sslot.nnumbers; i++)
6518 sumcommon += sslot.numbers[i];
6519 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata->statsTuple))->stanullfrac;
6520 if (sumcommon + nullfrac > 0.99999)
6521 use_mcvs = true;
6522 }
6523
6524 if (use_mcvs)
6525 get_stats_slot_range(&sslot, opfuncoid, &opproc,
6526 collation, typLen, typByVal,
6527 &tmin, &tmax, &have_data);
6528 free_attstatsslot(&sslot);
6529 }
6530
6531 *min = tmin;
6532 *max = tmax;
6533 return have_data;
6534 }
6535
6536 /*
6537 * get_stats_slot_range: scan sslot for min/max values
6538 *
6539 * Subroutine for get_variable_range: update min/max/have_data according
6540 * to what we find in the statistics array.
6541 */
6542 static void
6543 get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
6544 Oid collation, int16 typLen, bool typByVal,
6545 Datum *min, Datum *max, bool *p_have_data)
6546 {
6547 Datum tmin = *min;
6548 Datum tmax = *max;
6549 bool have_data = *p_have_data;
6550 bool found_tmin = false;
6551 bool found_tmax = false;
6552
6553 /* Look up the comparison function, if we didn't already do so */
6554 if (opproc->fn_oid != opfuncoid)
6555 fmgr_info(opfuncoid, opproc);
6556
6557 /* Scan all the slot's values */
6558 for (int i = 0; i < sslot->nvalues; i++)
6559 {
6560 if (!have_data)
6561 {
6562 tmin = tmax = sslot->values[i];
6563 found_tmin = found_tmax = true;
6564 *p_have_data = have_data = true;
6565 continue;
6566 }
6567 if (DatumGetBool(FunctionCall2Coll(opproc,
6568 collation,
6569 sslot->values[i], tmin)))
6570 {
6571 tmin = sslot->values[i];
6572 found_tmin = true;
6573 }
6574 if (DatumGetBool(FunctionCall2Coll(opproc,
6575 collation,
6576 tmax, sslot->values[i])))
6577 {
6578 tmax = sslot->values[i];
6579 found_tmax = true;
6580 }
6581 }
6582
6583 /*
6584 * Copy the slot's values, if we found new extreme values.
6585 */
6586 if (found_tmin)
6587 *min = datumCopy(tmin, typByVal, typLen);
6588 if (found_tmax)
6589 *max = datumCopy(tmax, typByVal, typLen);
6590 }
6591
6592
6593 /*
6594 * get_actual_variable_range
6595 * Attempt to identify the current *actual* minimum and/or maximum
6596 * of the specified variable, by looking for a suitable btree index
6597 * and fetching its low and/or high values.
6598 * If successful, store values in *min and *max, and return true.
6599 * (Either pointer can be NULL if that endpoint isn't needed.)
6600 * If unsuccessful, return false.
6601 *
6602 * sortop is the "<" comparison operator to use.
6603 * collation is the required collation.
6604 */
6605 static bool
6606 get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
6607 Oid sortop, Oid collation,
6608 Datum *min, Datum *max)
6609 {
6610 bool have_data = false;
6611 RelOptInfo *rel = vardata->rel;
6612 RangeTblEntry *rte;
6613 ListCell *lc;
6614
6615 /* No hope if no relation or it doesn't have indexes */
6616 if (rel == NULL || rel->indexlist == NIL)
6617 return false;
6618 /* If it has indexes it must be a plain relation */
6619 rte = root->simple_rte_array[rel->relid];
6620 Assert(rte->rtekind == RTE_RELATION);
6621
6622 /* ignore partitioned tables. Any indexes here are not real indexes */
6623 if (rte->relkind == RELKIND_PARTITIONED_TABLE)
6624 return false;
6625
6626 /* Search through the indexes to see if any match our problem */
6627 foreach(lc, rel->indexlist)
6628 {
6629 IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
6630 ScanDirection indexscandir;
6631 StrategyNumber strategy;
6632
6633 /* Ignore non-ordering indexes */
6634 if (index->sortopfamily == NULL)
6635 continue;
6636
6637 /*
6638 * Ignore partial indexes --- we only want stats that cover the entire
6639 * relation.
6640 */
6641 if (index->indpred != NIL)
6642 continue;
6643
6644 /*
6645 * The index list might include hypothetical indexes inserted by a
6646 * get_relation_info hook --- don't try to access them.
6647 */
6648 if (index->hypothetical)
6649 continue;
6650
6651 /*
6652 * get_actual_variable_endpoint uses the index-only-scan machinery, so
6653 * ignore indexes that can't use it on their first column.
6654 */
6655 if (!index->canreturn[0])
6656 continue;
6657
6658 /*
6659 * The first index column must match the desired variable, sortop, and
6660 * collation --- but we can use a descending-order index.
6661 */
6662 if (collation != index->indexcollations[0])
6663 continue; /* test first 'cause it's cheapest */
6664 if (!match_index_to_operand(vardata->var, 0, index))
6665 continue;
6666 strategy = get_op_opfamily_strategy(sortop, index->sortopfamily[0]);
6667 switch (IndexAmTranslateStrategy(strategy, index->relam, index->sortopfamily[0], true))
6668 {
6669 case COMPARE_LT:
6670 if (index->reverse_sort[0])
6671 indexscandir = BackwardScanDirection;
6672 else
6673 indexscandir = ForwardScanDirection;
6674 break;
6675 case COMPARE_GT:
6676 if (index->reverse_sort[0])
6677 indexscandir = ForwardScanDirection;
6678 else
6679 indexscandir = BackwardScanDirection;
6680 break;
6681 default:
6682 /* index doesn't match the sortop */
6683 continue;
6684 }
6685
6686 /*
6687 * Found a suitable index to extract data from. Set up some data that
6688 * can be used by both invocations of get_actual_variable_endpoint.
6689 */
6690 {
6691 MemoryContext tmpcontext;
6692 MemoryContext oldcontext;
6693 Relation heapRel;
6694 Relation indexRel;
6695 TupleTableSlot *slot;
6696 int16 typLen;
6697 bool typByVal;
6698 ScanKeyData scankeys[1];
6699
6700 /* Make sure any cruft gets recycled when we're done */
6701 tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
6702 "get_actual_variable_range workspace",
6703 ALLOCSET_DEFAULT_SIZES);
6704 oldcontext = MemoryContextSwitchTo(tmpcontext);
6705
6706 /*
6707 * Open the table and index so we can read from them. We should
6708 * already have some type of lock on each.
6709 */
6710 heapRel = table_open(rte->relid, NoLock);
6711 indexRel = index_open(index->indexoid, NoLock);
6712
6713 /* build some stuff needed for indexscan execution */
6714 slot = table_slot_create(heapRel, NULL);
6715 get_typlenbyval(vardata->atttype, &typLen, &typByVal);
6716
6717 /* set up an IS NOT NULL scan key so that we ignore nulls */
6718 ScanKeyEntryInitialize(&scankeys[0],
6719 SK_ISNULL | SK_SEARCHNOTNULL,
6720 1, /* index col to scan */
6721 InvalidStrategy, /* no strategy */
6722 InvalidOid, /* no strategy subtype */
6723 InvalidOid, /* no collation */
6724 InvalidOid, /* no reg proc for this */
6725 (Datum) 0); /* constant */
6726
6727 /* If min is requested ... */
6728 if (min)
6729 {
6730 have_data = get_actual_variable_endpoint(heapRel,
6731 indexRel,
6732 indexscandir,
6733 scankeys,
6734 typLen,
6735 typByVal,
6736 slot,
6737 oldcontext,
6738 min);
6739 }
6740 else
6741 {
6742 /* If min not requested, still want to fetch max */
6743 have_data = true;
6744 }
6745
6746 /* If max is requested, and we didn't already fail ... */
6747 if (max && have_data)
6748 {
6749 /* scan in the opposite direction; all else is the same */
6750 have_data = get_actual_variable_endpoint(heapRel,
6751 indexRel,
6752 -indexscandir,
6753 scankeys,
6754 typLen,
6755 typByVal,
6756 slot,
6757 oldcontext,
6758 max);
6759 }
6760
6761 /* Clean everything up */
6762 ExecDropSingleTupleTableSlot(slot);
6763
6764 index_close(indexRel, NoLock);
6765 table_close(heapRel, NoLock);
6766
6767 MemoryContextSwitchTo(oldcontext);
6768 MemoryContextDelete(tmpcontext);
6769
6770 /* And we're done */
6771 break;
6772 }
6773 }
6774
6775 return have_data;
6776 }
6777
6778 /*
6779 * Get one endpoint datum (min or max depending on indexscandir) from the
6780 * specified index. Return true if successful, false if not.
6781 * On success, endpoint value is stored to *endpointDatum (and copied into
6782 * outercontext).
6783 *
6784 * scankeys is a 1-element scankey array set up to reject nulls.
6785 * typLen/typByVal describe the datatype of the index's first column.
6786 * tableslot is a slot suitable to hold table tuples, in case we need
6787 * to probe the heap.
6788 * (We could compute these values locally, but that would mean computing them
6789 * twice when get_actual_variable_range needs both the min and the max.)
6790 *
6791 * Failure occurs either when the index is empty, or we decide that it's
6792 * taking too long to find a suitable tuple.
6793 */
6794 static bool
6795 get_actual_variable_endpoint(Relation heapRel,
6796 Relation indexRel,
6797 ScanDirection indexscandir,
6798 ScanKey scankeys,
6799 int16 typLen,
6800 bool typByVal,
6801 TupleTableSlot *tableslot,
6802 MemoryContext outercontext,
6803 Datum *endpointDatum)
6804 {
6805 bool have_data = false;
6806 SnapshotData SnapshotNonVacuumable;
6807 IndexScanDesc index_scan;
6808 Buffer vmbuffer = InvalidBuffer;
6809 BlockNumber last_heap_block = InvalidBlockNumber;
6810 int n_visited_heap_pages = 0;
6811 ItemPointer tid;
6812 Datum values[INDEX_MAX_KEYS];
6813 bool isnull[INDEX_MAX_KEYS];
6814 MemoryContext oldcontext;
6815
6816 /*
6817 * We use the index-only-scan machinery for this. With mostly-static
6818 * tables that's a win because it avoids a heap visit. It's also a win
6819 * for dynamic data, but the reason is less obvious; read on for details.
6820 *
6821 * In principle, we should scan the index with our current active
6822 * snapshot, which is the best approximation we've got to what the query
6823 * will see when executed. But that won't be exact if a new snap is taken
6824 * before running the query, and it can be very expensive if a lot of
6825 * recently-dead or uncommitted rows exist at the beginning or end of the
6826 * index (because we'll laboriously fetch each one and reject it).
6827 * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
6828 * and uncommitted rows as well as normal visible rows. On the other
6829 * hand, it will reject known-dead rows, and thus not give a bogus answer
6830 * when the extreme value has been deleted (unless the deletion was quite
6831 * recent); that case motivates not using SnapshotAny here.
6832 *
6833 * A crucial point here is that SnapshotNonVacuumable, with
6834 * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
6835 * condition that the indexscan will use to decide that index entries are
6836 * killable (see heap_hot_search_buffer()). Therefore, if the snapshot
6837 * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
6838 * have to continue scanning past it, we know that the indexscan will mark
6839 * that index entry killed. That means that the next
6840 * get_actual_variable_endpoint() call will not have to re-consider that
6841 * index entry. In this way we avoid repetitive work when this function
6842 * is used a lot during planning.
6843 *
6844 * But using SnapshotNonVacuumable creates a hazard of its own. In a
6845 * recently-created index, some index entries may point at "broken" HOT
6846 * chains in which not all the tuple versions contain data matching the
6847 * index entry. The live tuple version(s) certainly do match the index,
6848 * but SnapshotNonVacuumable can accept recently-dead tuple versions that
6849 * don't match. Hence, if we took data from the selected heap tuple, we
6850 * might get a bogus answer that's not close to the index extremal value,
6851 * or could even be NULL. We avoid this hazard because we take the data
6852 * from the index entry not the heap.
6853 *
6854 * Despite all this care, there are situations where we might find many
6855 * non-visible tuples near the end of the index. We don't want to expend
6856 * a huge amount of time here, so we give up once we've read too many heap
6857 * pages. When we fail for that reason, the caller will end up using
6858 * whatever extremal value is recorded in pg_statistic.
6859 */
6860 InitNonVacuumableSnapshot(SnapshotNonVacuumable,
6861 GlobalVisTestFor(heapRel));
6862
6863 index_scan = index_beginscan(heapRel, indexRel,
6864 &SnapshotNonVacuumable, NULL,
6865 1, 0);
6866 /* Set it up for index-only scan */
6867 index_scan->xs_want_itup = true;
6868 index_rescan(index_scan, scankeys, 1, NULL, 0);
6869
6870 /* Fetch first/next tuple in specified direction */
6871 while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
6872 {
6873 BlockNumber block = ItemPointerGetBlockNumber(tid);
6874
6875 if (!VM_ALL_VISIBLE(heapRel,
6876 block,
6877 &vmbuffer))
6878 {
6879 /* Rats, we have to visit the heap to check visibility */
6880 if (!index_fetch_heap(index_scan, tableslot))
6881 {
6882 /*
6883 * No visible tuple for this index entry, so we need to
6884 * advance to the next entry. Before doing so, count heap
6885 * page fetches and give up if we've done too many.
6886 *
6887 * We don't charge a page fetch if this is the same heap page
6888 * as the previous tuple. This is on the conservative side,
6889 * since other recently-accessed pages are probably still in
6890 * buffers too; but it's good enough for this heuristic.
6891 */
6892 #define VISITED_PAGES_LIMIT 100
6893
6894 if (block != last_heap_block)
6895 {
6896 last_heap_block = block;
6897 n_visited_heap_pages++;
6898 if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
6899 break;
6900 }
6901
6902 continue; /* no visible tuple, try next index entry */
6903 }
6904
6905 /* We don't actually need the heap tuple for anything */
6906 ExecClearTuple(tableslot);
6907
6908 /*
6909 * We don't care whether there's more than one visible tuple in
6910 * the HOT chain; if any are visible, that's good enough.
6911 */
6912 }
6913
6914 /*
6915 * We expect that the index will return data in IndexTuple not
6916 * HeapTuple format.
6917 */
6918 if (!index_scan->xs_itup)
6919 elog(ERROR, "no data returned for index-only scan");
6920
6921 /*
6922 * We do not yet support recheck here.
6923 */
6924 if (index_scan->xs_recheck)
6925 break;
6926
6927 /* OK to deconstruct the index tuple */
6928 index_deform_tuple(index_scan->xs_itup,
6929 index_scan->xs_itupdesc,
6930 values, isnull);
6931
6932 /* Shouldn't have got a null, but be careful */
6933 if (isnull[0])
6934 elog(ERROR, "found unexpected null value in index \"%s\"",
6935 RelationGetRelationName(indexRel));
6936
6937 /* Copy the index column value out to caller's context */
6938 oldcontext = MemoryContextSwitchTo(outercontext);
6939 *endpointDatum = datumCopy(values[0], typByVal, typLen);
6940 MemoryContextSwitchTo(oldcontext);
6941 have_data = true;
6942 break;
6943 }
6944
6945 if (vmbuffer != InvalidBuffer)
6946 ReleaseBuffer(vmbuffer);
6947 index_endscan(index_scan);
6948
6949 return have_data;
6950 }
6951
6952 /*
6953 * find_join_input_rel
6954 * Look up the input relation for a join.
6955 *
6956 * We assume that the input relation's RelOptInfo must have been constructed
6957 * already.
6958 */
6959 static RelOptInfo *
6960 find_join_input_rel(PlannerInfo *root, Relids relids)
6961 {
6962 RelOptInfo *rel = NULL;
6963
6964 if (!bms_is_empty(relids))
6965 {
6966 int relid;
6967
6968 if (bms_get_singleton_member(relids, &relid))
6969 rel = find_base_rel(root, relid);
6970 else
6971 rel = find_join_rel(root, relids);
6972 }
6973
6974 if (rel == NULL)
6975 elog(ERROR, "could not find RelOptInfo for given relids");
6976
6977 return rel;
6978 }
6979
6980
6981 /*-------------------------------------------------------------------------
6982 *
6983 * Index cost estimation functions
6984 *
6985 *-------------------------------------------------------------------------
6986 */
6987
6988 /*
6989 * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
6990 */
6991 List *
6992 get_quals_from_indexclauses(List *indexclauses)
6993 {
6994 List *result = NIL;
6995 ListCell *lc;
6996
6997 foreach(lc, indexclauses)
6998 {
6999 IndexClause *iclause = lfirst_node(IndexClause, lc);
7000 ListCell *lc2;
7001
7002 foreach(lc2, iclause->indexquals)
7003 {
7004 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7005
7006 result = lappend(result, rinfo);
7007 }
7008 }
7009 return result;
7010 }
7011
7012 /*
7013 * Compute the total evaluation cost of the comparison operands in a list
7014 * of index qual expressions. Since we know these will be evaluated just
7015 * once per scan, there's no need to distinguish startup from per-row cost.
7016 *
7017 * This can be used either on the result of get_quals_from_indexclauses(),
7018 * or directly on an indexorderbys list. In both cases, we expect that the
7019 * index key expression is on the left side of binary clauses.
7020 */
7021 Cost
7022 index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
7023 {
7024 Cost qual_arg_cost = 0;
7025 ListCell *lc;
7026
7027 foreach(lc, indexquals)
7028 {
7029 Expr *clause = (Expr *) lfirst(lc);
7030 Node *other_operand;
7031 QualCost index_qual_cost;
7032
7033 /*
7034 * Index quals will have RestrictInfos, indexorderbys won't. Look
7035 * through RestrictInfo if present.
7036 */
7037 if (IsA(clause, RestrictInfo))
7038 clause = ((RestrictInfo *) clause)->clause;
7039
7040 if (IsA(clause, OpExpr))
7041 {
7042 OpExpr *op = (OpExpr *) clause;
7043
7044 other_operand = (Node *) lsecond(op->args);
7045 }
7046 else if (IsA(clause, RowCompareExpr))
7047 {
7048 RowCompareExpr *rc = (RowCompareExpr *) clause;
7049
7050 other_operand = (Node *) rc->rargs;
7051 }
7052 else if (IsA(clause, ScalarArrayOpExpr))
7053 {
7054 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
7055
7056 other_operand = (Node *) lsecond(saop->args);
7057 }
7058 else if (IsA(clause, NullTest))
7059 {
7060 other_operand = NULL;
7061 }
7062 else
7063 {
7064 elog(ERROR, "unsupported indexqual type: %d",
7065 (int) nodeTag(clause));
7066 other_operand = NULL; /* keep compiler quiet */
7067 }
7068
7069 cost_qual_eval_node(&index_qual_cost, other_operand, root);
7070 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
7071 }
7072 return qual_arg_cost;
7073 }
7074
7075 void
7076 genericcostestimate(PlannerInfo *root,
7077 IndexPath *path,
7078 double loop_count,
7079 GenericCosts *costs)
7080 {
7081 IndexOptInfo *index = path->indexinfo;
7082 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7083 List *indexOrderBys = path->indexorderbys;
7084 Cost indexStartupCost;
7085 Cost indexTotalCost;
7086 Selectivity indexSelectivity;
7087 double indexCorrelation;
7088 double numIndexPages;
7089 double numIndexTuples;
7090 double spc_random_page_cost;
7091 double num_sa_scans;
7092 double num_outer_scans;
7093 double num_scans;
7094 double qual_op_cost;
7095 double qual_arg_cost;
7096 List *selectivityQuals;
7097 ListCell *l;
7098
7099 /*
7100 * If the index is partial, AND the index predicate with the explicitly
7101 * given indexquals to produce a more accurate idea of the index
7102 * selectivity.
7103 */
7104 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7105
7106 /*
7107 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
7108 * just assume that the number of index descents is the number of distinct
7109 * combinations of array elements from all of the scan's SAOP clauses.
7110 */
7111 num_sa_scans = costs->num_sa_scans;
7112 if (num_sa_scans < 1)
7113 {
7114 num_sa_scans = 1;
7115 foreach(l, indexQuals)
7116 {
7117 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
7118
7119 if (IsA(rinfo->clause, ScalarArrayOpExpr))
7120 {
7121 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
7122 double alength = estimate_array_length(root, lsecond(saop->args));
7123
7124 if (alength > 1)
7125 num_sa_scans *= alength;
7126 }
7127 }
7128 }
7129
7130 /* Estimate the fraction of main-table tuples that will be visited */
7131 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7132 index->rel->relid,
7133 JOIN_INNER,
7134 NULL);
7135
7136 /*
7137 * If caller didn't give us an estimate, estimate the number of index
7138 * tuples that will be visited. We do it in this rather peculiar-looking
7139 * way in order to get the right answer for partial indexes.
7140 */
7141 numIndexTuples = costs->numIndexTuples;
7142 if (numIndexTuples <= 0.0)
7143 {
7144 numIndexTuples = indexSelectivity * index->rel->tuples;
7145
7146 /*
7147 * The above calculation counts all the tuples visited across all
7148 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
7149 * average per-indexscan number, so adjust. This is a handy place to
7150 * round to integer, too. (If caller supplied tuple estimate, it's
7151 * responsible for handling these considerations.)
7152 */
7153 numIndexTuples = rint(numIndexTuples / num_sa_scans);
7154 }
7155
7156 /*
7157 * We can bound the number of tuples by the index size in any case. Also,
7158 * always estimate at least one tuple is touched, even when
7159 * indexSelectivity estimate is tiny.
7160 */
7161 if (numIndexTuples > index->tuples)
7162 numIndexTuples = index->tuples;
7163 if (numIndexTuples < 1.0)
7164 numIndexTuples = 1.0;
7165
7166 /*
7167 * Estimate the number of index pages that will be retrieved.
7168 *
7169 * We use the simplistic method of taking a pro-rata fraction of the total
7170 * number of index pages. In effect, this counts only leaf pages and not
7171 * any overhead such as index metapage or upper tree levels.
7172 *
7173 * In practice access to upper index levels is often nearly free because
7174 * those tend to stay in cache under load; moreover, the cost involved is
7175 * highly dependent on index type. We therefore ignore such costs here
7176 * and leave it to the caller to add a suitable charge if needed.
7177 */
7178 if (index->pages > 1 && index->tuples > 1)
7179 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
7180 else
7181 numIndexPages = 1.0;
7182
7183 /* fetch estimated page cost for tablespace containing index */
7184 get_tablespace_page_costs(index->reltablespace,
7185 &spc_random_page_cost,
7186 NULL);
7187
7188 /*
7189 * Now compute the disk access costs.
7190 *
7191 * The above calculations are all per-index-scan. However, if we are in a
7192 * nestloop inner scan, we can expect the scan to be repeated (with
7193 * different search keys) for each row of the outer relation. Likewise,
7194 * ScalarArrayOpExpr quals result in multiple index scans. This creates
7195 * the potential for cache effects to reduce the number of disk page
7196 * fetches needed. We want to estimate the average per-scan I/O cost in
7197 * the presence of caching.
7198 *
7199 * We use the Mackert-Lohman formula (see costsize.c for details) to
7200 * estimate the total number of page fetches that occur. While this
7201 * wasn't what it was designed for, it seems a reasonable model anyway.
7202 * Note that we are counting pages not tuples anymore, so we take N = T =
7203 * index size, as if there were one "tuple" per page.
7204 */
7205 num_outer_scans = loop_count;
7206 num_scans = num_sa_scans * num_outer_scans;
7207
7208 if (num_scans > 1)
7209 {
7210 double pages_fetched;
7211
7212 /* total page fetches ignoring cache effects */
7213 pages_fetched = numIndexPages * num_scans;
7214
7215 /* use Mackert and Lohman formula to adjust for cache effects */
7216 pages_fetched = index_pages_fetched(pages_fetched,
7217 index->pages,
7218 (double) index->pages,
7219 root);
7220
7221 /*
7222 * Now compute the total disk access cost, and then report a pro-rated
7223 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
7224 * since that's internal to the indexscan.)
7225 */
7226 indexTotalCost = (pages_fetched * spc_random_page_cost)
7227 / num_outer_scans;
7228 }
7229 else
7230 {
7231 /*
7232 * For a single index scan, we just charge spc_random_page_cost per
7233 * page touched.
7234 */
7235 indexTotalCost = numIndexPages * spc_random_page_cost;
7236 }
7237
7238 /*
7239 * CPU cost: any complex expressions in the indexquals will need to be
7240 * evaluated once at the start of the scan to reduce them to runtime keys
7241 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
7242 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
7243 * indexqual operator. Because we have numIndexTuples as a per-scan
7244 * number, we have to multiply by num_sa_scans to get the correct result
7245 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
7246 * ORDER BY expressions.
7247 *
7248 * Note: this neglects the possible costs of rechecking lossy operators.
7249 * Detecting that that might be needed seems more expensive than it's
7250 * worth, though, considering all the other inaccuracies here ...
7251 */
7252 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
7253 index_other_operands_eval_cost(root, indexOrderBys);
7254 qual_op_cost = cpu_operator_cost *
7255 (list_length(indexQuals) + list_length(indexOrderBys));
7256
7257 indexStartupCost = qual_arg_cost;
7258 indexTotalCost += qual_arg_cost;
7259 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
7260
7261 /*
7262 * Generic assumption about index correlation: there isn't any.
7263 */
7264 indexCorrelation = 0.0;
7265
7266 /*
7267 * Return everything to caller.
7268 */
7269 costs->indexStartupCost = indexStartupCost;
7270 costs->indexTotalCost = indexTotalCost;
7271 costs->indexSelectivity = indexSelectivity;
7272 costs->indexCorrelation = indexCorrelation;
7273 costs->numIndexPages = numIndexPages;
7274 costs->numIndexTuples = numIndexTuples;
7275 costs->spc_random_page_cost = spc_random_page_cost;
7276 costs->num_sa_scans = num_sa_scans;
7277 }
7278
7279 /*
7280 * If the index is partial, add its predicate to the given qual list.
7281 *
7282 * ANDing the index predicate with the explicitly given indexquals produces
7283 * a more accurate idea of the index's selectivity. However, we need to be
7284 * careful not to insert redundant clauses, because clauselist_selectivity()
7285 * is easily fooled into computing a too-low selectivity estimate. Our
7286 * approach is to add only the predicate clause(s) that cannot be proven to
7287 * be implied by the given indexquals. This successfully handles cases such
7288 * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
7289 * There are many other cases where we won't detect redundancy, leading to a
7290 * too-low selectivity estimate, which will bias the system in favor of using
7291 * partial indexes where possible. That is not necessarily bad though.
7292 *
7293 * Note that indexQuals contains RestrictInfo nodes while the indpred
7294 * does not, so the output list will be mixed. This is OK for both
7295 * predicate_implied_by() and clauselist_selectivity(), but might be
7296 * problematic if the result were passed to other things.
7297 */
7298 List *
7299 add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
7300 {
7301 List *predExtraQuals = NIL;
7302 ListCell *lc;
7303
7304 if (index->indpred == NIL)
7305 return indexQuals;
7306
7307 foreach(lc, index->indpred)
7308 {
7309 Node *predQual = (Node *) lfirst(lc);
7310 List *oneQual = list_make1(predQual);
7311
7312 if (!predicate_implied_by(oneQual, indexQuals, false))
7313 predExtraQuals = list_concat(predExtraQuals, oneQual);
7314 }
7315 return list_concat(predExtraQuals, indexQuals);
7316 }
7317
7318 /*
7319 * Estimate correlation of btree index's first column.
7320 *
7321 * If we can get an estimate of the first column's ordering correlation C
7322 * from pg_statistic, estimate the index correlation as C for a single-column
7323 * index, or C * 0.75 for multiple columns. The idea here is that multiple
7324 * columns dilute the importance of the first column's ordering, but don't
7325 * negate it entirely.
7326 *
7327 * We already filled in the stats tuple for *vardata when called.
7328 */
7329 static double
7330 btcost_correlation(IndexOptInfo *index, VariableStatData *vardata)
7331 {
7332 Oid sortop;
7333 AttStatsSlot sslot;
7334 double indexCorrelation = 0;
7335
7336 Assert(HeapTupleIsValid(vardata->statsTuple));
7337
7338 sortop = get_opfamily_member(index->opfamily[0],
7339 index->opcintype[0],
7340 index->opcintype[0],
7341 BTLessStrategyNumber);
7342 if (OidIsValid(sortop) &&
7343 get_attstatsslot(&sslot, vardata->statsTuple,
7344 STATISTIC_KIND_CORRELATION, sortop,
7345 ATTSTATSSLOT_NUMBERS))
7346 {
7347 double varCorrelation;
7348
7349 Assert(sslot.nnumbers == 1);
7350 varCorrelation = sslot.numbers[0];
7351
7352 if (index->reverse_sort[0])
7353 varCorrelation = -varCorrelation;
7354
7355 if (index->nkeycolumns > 1)
7356 indexCorrelation = varCorrelation * 0.75;
7357 else
7358 indexCorrelation = varCorrelation;
7359
7360 free_attstatsslot(&sslot);
7361 }
7362
7363 return indexCorrelation;
7364 }
7365
7366 void
7367 btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7368 Cost *indexStartupCost, Cost *indexTotalCost,
7369 Selectivity *indexSelectivity, double *indexCorrelation,
7370 double *indexPages)
7371 {
7372 IndexOptInfo *index = path->indexinfo;
7373 GenericCosts costs = {0};
7374 VariableStatData vardata = {0};
7375 double numIndexTuples;
7376 Cost descentCost;
7377 List *indexBoundQuals;
7378 List *indexSkipQuals;
7379 int indexcol;
7380 bool eqQualHere;
7381 bool found_row_compare;
7382 bool found_array;
7383 bool found_is_null_op;
7384 bool have_correlation = false;
7385 double num_sa_scans;
7386 double correlation = 0.0;
7387 ListCell *lc;
7388
7389 /*
7390 * For a btree scan, only leading '=' quals plus inequality quals for the
7391 * immediately next attribute contribute to index selectivity (these are
7392 * the "boundary quals" that determine the starting and stopping points of
7393 * the index scan). Additional quals can suppress visits to the heap, so
7394 * it's OK to count them in indexSelectivity, but they should not count
7395 * for estimating numIndexTuples. So we must examine the given indexquals
7396 * to find out which ones count as boundary quals. We rely on the
7397 * knowledge that they are given in index column order. Note that nbtree
7398 * preprocessing can add skip arrays that act as leading '=' quals in the
7399 * absence of ordinary input '=' quals, so in practice _most_ input quals
7400 * are able to act as index bound quals (which we take into account here).
7401 *
7402 * For a RowCompareExpr, we consider only the first column, just as
7403 * rowcomparesel() does.
7404 *
7405 * If there's a SAOP or skip array in the quals, we'll actually perform up
7406 * to N index descents (not just one), but the underlying array key's
7407 * operator can be considered to act the same as it normally does.
7408 */
7409 indexBoundQuals = NIL;
7410 indexSkipQuals = NIL;
7411 indexcol = 0;
7412 eqQualHere = false;
7413 found_row_compare = false;
7414 found_array = false;
7415 found_is_null_op = false;
7416 num_sa_scans = 1;
7417 foreach(lc, path->indexclauses)
7418 {
7419 IndexClause *iclause = lfirst_node(IndexClause, lc);
7420 ListCell *lc2;
7421
7422 if (indexcol < iclause->indexcol)
7423 {
7424 double num_sa_scans_prev_cols = num_sa_scans;
7425
7426 /*
7427 * Beginning of a new column's quals.
7428 *
7429 * Skip scans use skip arrays, which are ScalarArrayOp style
7430 * arrays that generate their elements procedurally and on demand.
7431 * Given a multi-column index on "(a, b)", and an SQL WHERE clause
7432 * "WHERE b = 42", a skip scan will effectively use an indexqual
7433 * "WHERE a = ANY('{every col a value}') AND b = 42". (Obviously,
7434 * the array on "a" must also return "IS NULL" matches, since our
7435 * WHERE clause used no strict operator on "a").
7436 *
7437 * Here we consider how nbtree will backfill skip arrays for any
7438 * index columns that lacked an '=' qual. This maintains our
7439 * num_sa_scans estimate, and determines if this new column (the
7440 * "iclause->indexcol" column, not the prior "indexcol" column)
7441 * can have its RestrictInfos/quals added to indexBoundQuals.
7442 *
7443 * We'll need to handle columns that have inequality quals, where
7444 * the skip array generates values from a range constrained by the
7445 * quals (not every possible value). We've been maintaining
7446 * indexSkipQuals to help with this; it will now contain all of
7447 * the prior column's quals (that is, indexcol's quals) when they
7448 * might be used for this.
7449 */
7450 if (found_row_compare)
7451 {
7452 /*
7453 * Skip arrays can't be added after a RowCompare input qual
7454 * due to limitations in nbtree
7455 */
7456 break;
7457 }
7458 if (eqQualHere)
7459 {
7460 /*
7461 * Don't need to add a skip array for an indexcol that already
7462 * has an '=' qual/equality constraint
7463 */
7464 indexcol++;
7465 indexSkipQuals = NIL;
7466 }
7467 eqQualHere = false;
7468
7469 while (indexcol < iclause->indexcol)
7470 {
7471 double ndistinct;
7472 bool isdefault = true;
7473
7474 found_array = true;
7475
7476 /*
7477 * A skipped attribute's ndistinct forms the basis of our
7478 * estimate of the total number of "array elements" used by
7479 * its skip array at runtime. Look that up first.
7480 */
7481 examine_indexcol_variable(root, index, indexcol, &vardata);
7482 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
7483
7484 if (indexcol == 0)
7485 {
7486 /*
7487 * Get an estimate of the leading column's correlation in
7488 * passing (avoids rereading variable stats below)
7489 */
7490 if (HeapTupleIsValid(vardata.statsTuple))
7491 correlation = btcost_correlation(index, &vardata);
7492 have_correlation = true;
7493 }
7494
7495 ReleaseVariableStats(vardata);
7496
7497 /*
7498 * If ndistinct is a default estimate, conservatively assume
7499 * that no skipping will happen at runtime
7500 */
7501 if (isdefault)
7502 {
7503 num_sa_scans = num_sa_scans_prev_cols;
7504 break; /* done building indexBoundQuals */
7505 }
7506
7507 /*
7508 * Apply indexcol's indexSkipQuals selectivity to ndistinct
7509 */
7510 if (indexSkipQuals != NIL)
7511 {
7512 List *partialSkipQuals;
7513 Selectivity ndistinctfrac;
7514
7515 /*
7516 * If the index is partial, AND the index predicate with
7517 * the index-bound quals to produce a more accurate idea
7518 * of the number of distinct values for prior indexcol
7519 */
7520 partialSkipQuals = add_predicate_to_index_quals(index,
7521 indexSkipQuals);
7522
7523 ndistinctfrac = clauselist_selectivity(root, partialSkipQuals,
7524 index->rel->relid,
7525 JOIN_INNER,
7526 NULL);
7527
7528 /*
7529 * If ndistinctfrac is selective (on its own), the scan is
7530 * unlikely to benefit from repositioning itself using
7531 * later quals. Do not allow iclause->indexcol's quals to
7532 * be added to indexBoundQuals (it would increase descent
7533 * costs, without lowering numIndexTuples costs by much).
7534 */
7535 if (ndistinctfrac < DEFAULT_RANGE_INEQ_SEL)
7536 {
7537 num_sa_scans = num_sa_scans_prev_cols;
7538 break; /* done building indexBoundQuals */
7539 }
7540
7541 /* Adjust ndistinct downward */
7542 ndistinct = rint(ndistinct * ndistinctfrac);
7543 ndistinct = Max(ndistinct, 1);
7544 }
7545
7546 /*
7547 * When there's no inequality quals, account for the need to
7548 * find an initial value by counting -inf/+inf as a value.
7549 *
7550 * We don't charge anything extra for possible next/prior key
7551 * index probes, which are sometimes used to find the next
7552 * valid skip array element (ahead of using the located
7553 * element value to relocate the scan to the next position
7554 * that might contain matching tuples). It seems hard to do
7555 * better here. Use of the skip support infrastructure often
7556 * avoids most next/prior key probes. But even when it can't,
7557 * there's a decent chance that most individual next/prior key
7558 * probes will locate a leaf page whose key space overlaps all
7559 * of the scan's keys (even the lower-order keys) -- which
7560 * also avoids the need for a separate, extra index descent.
7561 * Note also that these probes are much cheaper than non-probe
7562 * primitive index scans: they're reliably very selective.
7563 */
7564 if (indexSkipQuals == NIL)
7565 ndistinct += 1;
7566
7567 /*
7568 * Update num_sa_scans estimate by multiplying by ndistinct.
7569 *
7570 * We make the pessimistic assumption that there is no
7571 * naturally occurring cross-column correlation. This is
7572 * often wrong, but it seems best to err on the side of not
7573 * expecting skipping to be helpful...
7574 */
7575 num_sa_scans *= ndistinct;
7576
7577 /*
7578 * ...but back out of adding this latest group of 1 or more
7579 * skip arrays when num_sa_scans exceeds the total number of
7580 * index pages (revert to num_sa_scans from before indexcol).
7581 * This causes a sharp discontinuity in cost (as a function of
7582 * the indexcol's ndistinct), but that is representative of
7583 * actual runtime costs.
7584 *
7585 * Note that skipping is helpful when each primitive index
7586 * scan only manages to skip over 1 or 2 irrelevant leaf pages
7587 * on average. Skip arrays bring savings in CPU costs due to
7588 * the scan not needing to evaluate indexquals against every
7589 * tuple, which can greatly exceed any savings in I/O costs.
7590 * This test is a test of whether num_sa_scans implies that
7591 * we're past the point where the ability to skip ceases to
7592 * lower the scan's costs (even qual evaluation CPU costs).
7593 */
7594 if (index->pages < num_sa_scans)
7595 {
7596 num_sa_scans = num_sa_scans_prev_cols;
7597 break; /* done building indexBoundQuals */
7598 }
7599
7600 indexcol++;
7601 indexSkipQuals = NIL;
7602 }
7603
7604 /*
7605 * Finished considering the need to add skip arrays to bridge an
7606 * initial eqQualHere gap between the old and new index columns
7607 * (or there was no initial eqQualHere gap in the first place).
7608 *
7609 * If an initial gap could not be bridged, then new column's quals
7610 * (i.e. iclause->indexcol's quals) won't go into indexBoundQuals,
7611 * and so won't affect our final numIndexTuples estimate.
7612 */
7613 if (indexcol != iclause->indexcol)
7614 break; /* done building indexBoundQuals */
7615 }
7616
7617 Assert(indexcol == iclause->indexcol);
7618
7619 /* Examine each indexqual associated with this index clause */
7620 foreach(lc2, iclause->indexquals)
7621 {
7622 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7623 Expr *clause = rinfo->clause;
7624 Oid clause_op = InvalidOid;
7625 int op_strategy;
7626
7627 if (IsA(clause, OpExpr))
7628 {
7629 OpExpr *op = (OpExpr *) clause;
7630
7631 clause_op = op->opno;
7632 }
7633 else if (IsA(clause, RowCompareExpr))
7634 {
7635 RowCompareExpr *rc = (RowCompareExpr *) clause;
7636
7637 clause_op = linitial_oid(rc->opnos);
7638 found_row_compare = true;
7639 }
7640 else if (IsA(clause, ScalarArrayOpExpr))
7641 {
7642 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
7643 Node *other_operand = (Node *) lsecond(saop->args);
7644 double alength = estimate_array_length(root, other_operand);
7645
7646 clause_op = saop->opno;
7647 found_array = true;
7648 /* estimate SA descents by indexBoundQuals only */
7649 if (alength > 1)
7650 num_sa_scans *= alength;
7651 }
7652 else if (IsA(clause, NullTest))
7653 {
7654 NullTest *nt = (NullTest *) clause;
7655
7656 if (nt->nulltesttype == IS_NULL)
7657 {
7658 found_is_null_op = true;
7659 /* IS NULL is like = for selectivity/skip scan purposes */
7660 eqQualHere = true;
7661 }
7662 }
7663 else
7664 elog(ERROR, "unsupported indexqual type: %d",
7665 (int) nodeTag(clause));
7666
7667 /* check for equality operator */
7668 if (OidIsValid(clause_op))
7669 {
7670 op_strategy = get_op_opfamily_strategy(clause_op,
7671 index->opfamily[indexcol]);
7672 Assert(op_strategy != 0); /* not a member of opfamily?? */
7673 if (op_strategy == BTEqualStrategyNumber)
7674 eqQualHere = true;
7675 }
7676
7677 indexBoundQuals = lappend(indexBoundQuals, rinfo);
7678
7679 /*
7680 * We apply inequality selectivities to estimate index descent
7681 * costs with scans that use skip arrays. Save this indexcol's
7682 * RestrictInfos if it looks like they'll be needed for that.
7683 */
7684 if (!eqQualHere && !found_row_compare &&
7685 indexcol < index->nkeycolumns - 1)
7686 indexSkipQuals = lappend(indexSkipQuals, rinfo);
7687 }
7688 }
7689
7690 /*
7691 * If index is unique and we found an '=' clause for each column, we can
7692 * just assume numIndexTuples = 1 and skip the expensive
7693 * clauselist_selectivity calculations. However, an array or NullTest
7694 * always invalidates that theory (even when eqQualHere has been set).
7695 */
7696 if (index->unique &&
7697 indexcol == index->nkeycolumns - 1 &&
7698 eqQualHere &&
7699 !found_array &&
7700 !found_is_null_op)
7701 numIndexTuples = 1.0;
7702 else
7703 {
7704 List *selectivityQuals;
7705 Selectivity btreeSelectivity;
7706
7707 /*
7708 * If the index is partial, AND the index predicate with the
7709 * index-bound quals to produce a more accurate idea of the number of
7710 * rows covered by the bound conditions.
7711 */
7712 selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
7713
7714 btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
7715 index->rel->relid,
7716 JOIN_INNER,
7717 NULL);
7718 numIndexTuples = btreeSelectivity * index->rel->tuples;
7719
7720 /*
7721 * btree automatically combines individual array element primitive
7722 * index scans whenever the tuples covered by the next set of array
7723 * keys are close to tuples covered by the current set. That puts a
7724 * natural ceiling on the worst case number of descents -- there
7725 * cannot possibly be more than one descent per leaf page scanned.
7726 *
7727 * Clamp the number of descents to at most 1/3 the number of index
7728 * pages. This avoids implausibly high estimates with low selectivity
7729 * paths, where scans usually require only one or two descents. This
7730 * is most likely to help when there are several SAOP clauses, where
7731 * naively accepting the total number of distinct combinations of
7732 * array elements as the number of descents would frequently lead to
7733 * wild overestimates.
7734 *
7735 * We somewhat arbitrarily don't just make the cutoff the total number
7736 * of leaf pages (we make it 1/3 the total number of pages instead) to
7737 * give the btree code credit for its ability to continue on the leaf
7738 * level with low selectivity scans.
7739 *
7740 * Note: num_sa_scans includes both ScalarArrayOp array elements and
7741 * skip array elements whose qual affects our numIndexTuples estimate.
7742 */
7743 num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
7744 num_sa_scans = Max(num_sa_scans, 1);
7745
7746 /*
7747 * As in genericcostestimate(), we have to adjust for any array quals
7748 * included in indexBoundQuals, and then round to integer.
7749 *
7750 * It is tempting to make genericcostestimate behave as if array
7751 * clauses work in almost the same way as scalar operators during
7752 * btree scans, making the top-level scan look like a continuous scan
7753 * (as opposed to num_sa_scans-many primitive index scans). After
7754 * all, btree scans mostly work like that at runtime. However, such a
7755 * scheme would badly bias genericcostestimate's simplistic approach
7756 * to calculating numIndexPages through prorating.
7757 *
7758 * Stick with the approach taken by non-native SAOP scans for now.
7759 * genericcostestimate will use the Mackert-Lohman formula to
7760 * compensate for repeat page fetches, even though that definitely
7761 * won't happen during btree scans (not for leaf pages, at least).
7762 * We're usually very pessimistic about the number of primitive index
7763 * scans that will be required, but it's not clear how to do better.
7764 */
7765 numIndexTuples = rint(numIndexTuples / num_sa_scans);
7766 }
7767
7768 /*
7769 * Now do generic index cost estimation.
7770 */
7771 costs.numIndexTuples = numIndexTuples;
7772 costs.num_sa_scans = num_sa_scans;
7773
7774 genericcostestimate(root, path, loop_count, &costs);
7775
7776 /*
7777 * Add a CPU-cost component to represent the costs of initial btree
7778 * descent. We don't charge any I/O cost for touching upper btree levels,
7779 * since they tend to stay in cache, but we still have to do about log2(N)
7780 * comparisons to descend a btree of N leaf tuples. We charge one
7781 * cpu_operator_cost per comparison.
7782 *
7783 * If there are SAOP or skip array keys, charge this once per estimated
7784 * index descent. The ones after the first one are not startup cost so
7785 * far as the overall plan goes, so just add them to "total" cost.
7786 */
7787 if (index->tuples > 1) /* avoid computing log(0) */
7788 {
7789 descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
7790 costs.indexStartupCost += descentCost;
7791 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7792 }
7793
7794 /*
7795 * Even though we're not charging I/O cost for touching upper btree pages,
7796 * it's still reasonable to charge some CPU cost per page descended
7797 * through. Moreover, if we had no such charge at all, bloated indexes
7798 * would appear to have the same search cost as unbloated ones, at least
7799 * in cases where only a single leaf page is expected to be visited. This
7800 * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
7801 * touched. The number of such pages is btree tree height plus one (ie,
7802 * we charge for the leaf page too). As above, charge once per estimated
7803 * SAOP/skip array descent.
7804 */
7805 descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7806 costs.indexStartupCost += descentCost;
7807 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7808
7809 if (!have_correlation)
7810 {
7811 examine_indexcol_variable(root, index, 0, &vardata);
7812 if (HeapTupleIsValid(vardata.statsTuple))
7813 costs.indexCorrelation = btcost_correlation(index, &vardata);
7814 ReleaseVariableStats(vardata);
7815 }
7816 else
7817 {
7818 /* btcost_correlation already called earlier on */
7819 costs.indexCorrelation = correlation;
7820 }
7821
7822 *indexStartupCost = costs.indexStartupCost;
7823 *indexTotalCost = costs.indexTotalCost;
7824 *indexSelectivity = costs.indexSelectivity;
7825 *indexCorrelation = costs.indexCorrelation;
7826 *indexPages = costs.numIndexPages;
7827 }
7828
7829 void
7830 hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7831 Cost *indexStartupCost, Cost *indexTotalCost,
7832 Selectivity *indexSelectivity, double *indexCorrelation,
7833 double *indexPages)
7834 {
7835 GenericCosts costs = {0};
7836
7837 genericcostestimate(root, path, loop_count, &costs);
7838
7839 /*
7840 * A hash index has no descent costs as such, since the index AM can go
7841 * directly to the target bucket after computing the hash value. There
7842 * are a couple of other hash-specific costs that we could conceivably add
7843 * here, though:
7844 *
7845 * Ideally we'd charge spc_random_page_cost for each page in the target
7846 * bucket, not just the numIndexPages pages that genericcostestimate
7847 * thought we'd visit. However in most cases we don't know which bucket
7848 * that will be. There's no point in considering the average bucket size
7849 * because the hash AM makes sure that's always one page.
7850 *
7851 * Likewise, we could consider charging some CPU for each index tuple in
7852 * the bucket, if we knew how many there were. But the per-tuple cost is
7853 * just a hash value comparison, not a general datatype-dependent
7854 * comparison, so any such charge ought to be quite a bit less than
7855 * cpu_operator_cost; which makes it probably not worth worrying about.
7856 *
7857 * A bigger issue is that chance hash-value collisions will result in
7858 * wasted probes into the heap. We don't currently attempt to model this
7859 * cost on the grounds that it's rare, but maybe it's not rare enough.
7860 * (Any fix for this ought to consider the generic lossy-operator problem,
7861 * though; it's not entirely hash-specific.)
7862 */
7863
7864 *indexStartupCost = costs.indexStartupCost;
7865 *indexTotalCost = costs.indexTotalCost;
7866 *indexSelectivity = costs.indexSelectivity;
7867 *indexCorrelation = costs.indexCorrelation;
7868 *indexPages = costs.numIndexPages;
7869 }
7870
7871 void
7872 gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7873 Cost *indexStartupCost, Cost *indexTotalCost,
7874 Selectivity *indexSelectivity, double *indexCorrelation,
7875 double *indexPages)
7876 {
7877 IndexOptInfo *index = path->indexinfo;
7878 GenericCosts costs = {0};
7879 Cost descentCost;
7880
7881 genericcostestimate(root, path, loop_count, &costs);
7882
7883 /*
7884 * We model index descent costs similarly to those for btree, but to do
7885 * that we first need an idea of the tree height. We somewhat arbitrarily
7886 * assume that the fanout is 100, meaning the tree height is at most
7887 * log100(index->pages).
7888 *
7889 * Although this computation isn't really expensive enough to require
7890 * caching, we might as well use index->tree_height to cache it.
7891 */
7892 if (index->tree_height < 0) /* unknown? */
7893 {
7894 if (index->pages > 1) /* avoid computing log(0) */
7895 index->tree_height = (int) (log(index->pages) / log(100.0));
7896 else
7897 index->tree_height = 0;
7898 }
7899
7900 /*
7901 * Add a CPU-cost component to represent the costs of initial descent. We
7902 * just use log(N) here not log2(N) since the branching factor isn't
7903 * necessarily two anyway. As for btree, charge once per SA scan.
7904 */
7905 if (index->tuples > 1) /* avoid computing log(0) */
7906 {
7907 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7908 costs.indexStartupCost += descentCost;
7909 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7910 }
7911
7912 /*
7913 * Likewise add a per-page charge, calculated the same as for btrees.
7914 */
7915 descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7916 costs.indexStartupCost += descentCost;
7917 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7918
7919 *indexStartupCost = costs.indexStartupCost;
7920 *indexTotalCost = costs.indexTotalCost;
7921 *indexSelectivity = costs.indexSelectivity;
7922 *indexCorrelation = costs.indexCorrelation;
7923 *indexPages = costs.numIndexPages;
7924 }
7925
7926 void
7927 spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7928 Cost *indexStartupCost, Cost *indexTotalCost,
7929 Selectivity *indexSelectivity, double *indexCorrelation,
7930 double *indexPages)
7931 {
7932 IndexOptInfo *index = path->indexinfo;
7933 GenericCosts costs = {0};
7934 Cost descentCost;
7935
7936 genericcostestimate(root, path, loop_count, &costs);
7937
7938 /*
7939 * We model index descent costs similarly to those for btree, but to do
7940 * that we first need an idea of the tree height. We somewhat arbitrarily
7941 * assume that the fanout is 100, meaning the tree height is at most
7942 * log100(index->pages).
7943 *
7944 * Although this computation isn't really expensive enough to require
7945 * caching, we might as well use index->tree_height to cache it.
7946 */
7947 if (index->tree_height < 0) /* unknown? */
7948 {
7949 if (index->pages > 1) /* avoid computing log(0) */
7950 index->tree_height = (int) (log(index->pages) / log(100.0));
7951 else
7952 index->tree_height = 0;
7953 }
7954
7955 /*
7956 * Add a CPU-cost component to represent the costs of initial descent. We
7957 * just use log(N) here not log2(N) since the branching factor isn't
7958 * necessarily two anyway. As for btree, charge once per SA scan.
7959 */
7960 if (index->tuples > 1) /* avoid computing log(0) */
7961 {
7962 descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7963 costs.indexStartupCost += descentCost;
7964 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7965 }
7966
7967 /*
7968 * Likewise add a per-page charge, calculated the same as for btrees.
7969 */
7970 descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7971 costs.indexStartupCost += descentCost;
7972 costs.indexTotalCost += costs.num_sa_scans * descentCost;
7973
7974 *indexStartupCost = costs.indexStartupCost;
7975 *indexTotalCost = costs.indexTotalCost;
7976 *indexSelectivity = costs.indexSelectivity;
7977 *indexCorrelation = costs.indexCorrelation;
7978 *indexPages = costs.numIndexPages;
7979 }
7980
7981
7982 /*
7983 * Support routines for gincostestimate
7984 */
7985
7986 typedef struct
7987 {
7988 bool attHasFullScan[INDEX_MAX_KEYS];
7989 bool attHasNormalScan[INDEX_MAX_KEYS];
7990 double partialEntries;
7991 double exactEntries;
7992 double searchEntries;
7993 double arrayScans;
7994 } GinQualCounts;
7995
7996 /*
7997 * Estimate the number of index terms that need to be searched for while
7998 * testing the given GIN query, and increment the counts in *counts
7999 * appropriately. If the query is unsatisfiable, return false.
8000 */
8001 static bool
8002 gincost_pattern(IndexOptInfo *index, int indexcol,
8003 Oid clause_op, Datum query,
8004 GinQualCounts *counts)
8005 {
8006 FmgrInfo flinfo;
8007 Oid extractProcOid;
8008 Oid collation;
8009 int strategy_op;
8010 Oid lefttype,
8011 righttype;
8012 int32 nentries = 0;
8013 bool *partial_matches = NULL;
8014 Pointer *extra_data = NULL;
8015 bool *nullFlags = NULL;
8016 int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
8017 int32 i;
8018
8019 Assert(indexcol < index->nkeycolumns);
8020
8021 /*
8022 * Get the operator's strategy number and declared input data types within
8023 * the index opfamily. (We don't need the latter, but we use
8024 * get_op_opfamily_properties because it will throw error if it fails to
8025 * find a matching pg_amop entry.)
8026 */
8027 get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
8028 &strategy_op, &lefttype, &righttype);
8029
8030 /*
8031 * GIN always uses the "default" support functions, which are those with
8032 * lefttype == righttype == the opclass' opcintype (see
8033 * IndexSupportInitialize in relcache.c).
8034 */
8035 extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
8036 index->opcintype[indexcol],
8037 index->opcintype[indexcol],
8038 GIN_EXTRACTQUERY_PROC);
8039
8040 if (!OidIsValid(extractProcOid))
8041 {
8042 /* should not happen; throw same error as index_getprocinfo */
8043 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
8044 GIN_EXTRACTQUERY_PROC, indexcol + 1,
8045 get_rel_name(index->indexoid));
8046 }
8047
8048 /*
8049 * Choose collation to pass to extractProc (should match initGinState).
8050 */
8051 if (OidIsValid(index->indexcollations[indexcol]))
8052 collation = index->indexcollations[indexcol];
8053 else
8054 collation = DEFAULT_COLLATION_OID;
8055
8056 fmgr_info(extractProcOid, &flinfo);
8057
8058 set_fn_opclass_options(&flinfo, index->opclassoptions[indexcol]);
8059
8060 FunctionCall7Coll(&flinfo,
8061 collation,
8062 query,
8063 PointerGetDatum(&nentries),
8064 UInt16GetDatum(strategy_op),
8065 PointerGetDatum(&partial_matches),
8066 PointerGetDatum(&extra_data),
8067 PointerGetDatum(&nullFlags),
8068 PointerGetDatum(&searchMode));
8069
8070 if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
8071 {
8072 /* No match is possible */
8073 return false;
8074 }
8075
8076 for (i = 0; i < nentries; i++)
8077 {
8078 /*
8079 * For partial match we haven't any information to estimate number of
8080 * matched entries in index, so, we just estimate it as 100
8081 */
8082 if (partial_matches && partial_matches[i])
8083 counts->partialEntries += 100;
8084 else
8085 counts->exactEntries++;
8086
8087 counts->searchEntries++;
8088 }
8089
8090 if (searchMode == GIN_SEARCH_MODE_DEFAULT)
8091 {
8092 counts->attHasNormalScan[indexcol] = true;
8093 }
8094 else if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
8095 {
8096 /* Treat "include empty" like an exact-match item */
8097 counts->attHasNormalScan[indexcol] = true;
8098 counts->exactEntries++;
8099 counts->searchEntries++;
8100 }
8101 else
8102 {
8103 /* It's GIN_SEARCH_MODE_ALL */
8104 counts->attHasFullScan[indexcol] = true;
8105 }
8106
8107 return true;
8108 }
8109
8110 /*
8111 * Estimate the number of index terms that need to be searched for while
8112 * testing the given GIN index clause, and increment the counts in *counts
8113 * appropriately. If the query is unsatisfiable, return false.
8114 */
8115 static bool
8116 gincost_opexpr(PlannerInfo *root,
8117 IndexOptInfo *index,
8118 int indexcol,
8119 OpExpr *clause,
8120 GinQualCounts *counts)
8121 {
8122 Oid clause_op = clause->opno;
8123 Node *operand = (Node *) lsecond(clause->args);
8124
8125 /* aggressively reduce to a constant, and look through relabeling */
8126 operand = estimate_expression_value(root, operand);
8127
8128 if (IsA(operand, RelabelType))
8129 operand = (Node *) ((RelabelType *) operand)->arg;
8130
8131 /*
8132 * It's impossible to call extractQuery method for unknown operand. So
8133 * unless operand is a Const we can't do much; just assume there will be
8134 * one ordinary search entry from the operand at runtime.
8135 */
8136 if (!IsA(operand, Const))
8137 {
8138 counts->exactEntries++;
8139 counts->searchEntries++;
8140 return true;
8141 }
8142
8143 /* If Const is null, there can be no matches */
8144 if (((Const *) operand)->constisnull)
8145 return false;
8146
8147 /* Otherwise, apply extractQuery and get the actual term counts */
8148 return gincost_pattern(index, indexcol, clause_op,
8149 ((Const *) operand)->constvalue,
8150 counts);
8151 }
8152
8153 /*
8154 * Estimate the number of index terms that need to be searched for while
8155 * testing the given GIN index clause, and increment the counts in *counts
8156 * appropriately. If the query is unsatisfiable, return false.
8157 *
8158 * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
8159 * each of which involves one value from the RHS array, plus all the
8160 * non-array quals (if any). To model this, we average the counts across
8161 * the RHS elements, and add the averages to the counts in *counts (which
8162 * correspond to per-indexscan costs). We also multiply counts->arrayScans
8163 * by N, causing gincostestimate to scale up its estimates accordingly.
8164 */
8165 static bool
8166 gincost_scalararrayopexpr(PlannerInfo *root,
8167 IndexOptInfo *index,
8168 int indexcol,
8169 ScalarArrayOpExpr *clause,
8170 double numIndexEntries,
8171 GinQualCounts *counts)
8172 {
8173 Oid clause_op = clause->opno;
8174 Node *rightop = (Node *) lsecond(clause->args);
8175 ArrayType *arrayval;
8176 int16 elmlen;
8177 bool elmbyval;
8178 char elmalign;
8179 int numElems;
8180 Datum *elemValues;
8181 bool *elemNulls;
8182 GinQualCounts arraycounts;
8183 int numPossible = 0;
8184 int i;
8185
8186 Assert(clause->useOr);
8187
8188 /* aggressively reduce to a constant, and look through relabeling */
8189 rightop = estimate_expression_value(root, rightop);
8190
8191 if (IsA(rightop, RelabelType))
8192 rightop = (Node *) ((RelabelType *) rightop)->arg;
8193
8194 /*
8195 * It's impossible to call extractQuery method for unknown operand. So
8196 * unless operand is a Const we can't do much; just assume there will be
8197 * one ordinary search entry from each array entry at runtime, and fall
8198 * back on a probably-bad estimate of the number of array entries.
8199 */
8200 if (!IsA(rightop, Const))
8201 {
8202 counts->exactEntries++;
8203 counts->searchEntries++;
8204 counts->arrayScans *= estimate_array_length(root, rightop);
8205 return true;
8206 }
8207
8208 /* If Const is null, there can be no matches */
8209 if (((Const *) rightop)->constisnull)
8210 return false;
8211
8212 /* Otherwise, extract the array elements and iterate over them */
8213 arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
8214 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
8215 &elmlen, &elmbyval, &elmalign);
8216 deconstruct_array(arrayval,
8217 ARR_ELEMTYPE(arrayval),
8218 elmlen, elmbyval, elmalign,
8219 &elemValues, &elemNulls, &numElems);
8220
8221 memset(&arraycounts, 0, sizeof(arraycounts));
8222
8223 for (i = 0; i < numElems; i++)
8224 {
8225 GinQualCounts elemcounts;
8226
8227 /* NULL can't match anything, so ignore, as the executor will */
8228 if (elemNulls[i])
8229 continue;
8230
8231 /* Otherwise, apply extractQuery and get the actual term counts */
8232 memset(&elemcounts, 0, sizeof(elemcounts));
8233
8234 if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
8235 &elemcounts))
8236 {
8237 /* We ignore array elements that are unsatisfiable patterns */
8238 numPossible++;
8239
8240 if (elemcounts.attHasFullScan[indexcol] &&
8241 !elemcounts.attHasNormalScan[indexcol])
8242 {
8243 /*
8244 * Full index scan will be required. We treat this as if
8245 * every key in the index had been listed in the query; is
8246 * that reasonable?
8247 */
8248 elemcounts.partialEntries = 0;
8249 elemcounts.exactEntries = numIndexEntries;
8250 elemcounts.searchEntries = numIndexEntries;
8251 }
8252 arraycounts.partialEntries += elemcounts.partialEntries;
8253 arraycounts.exactEntries += elemcounts.exactEntries;
8254 arraycounts.searchEntries += elemcounts.searchEntries;
8255 }
8256 }
8257
8258 if (numPossible == 0)
8259 {
8260 /* No satisfiable patterns in the array */
8261 return false;
8262 }
8263
8264 /*
8265 * Now add the averages to the global counts. This will give us an
8266 * estimate of the average number of terms searched for in each indexscan,
8267 * including contributions from both array and non-array quals.
8268 */
8269 counts->partialEntries += arraycounts.partialEntries / numPossible;
8270 counts->exactEntries += arraycounts.exactEntries / numPossible;
8271 counts->searchEntries += arraycounts.searchEntries / numPossible;
8272
8273 counts->arrayScans *= numPossible;
8274
8275 return true;
8276 }
8277
8278 /*
8279 * GIN has search behavior completely different from other index types
8280 */
8281 void
8282 gincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
8283 Cost *indexStartupCost, Cost *indexTotalCost,
8284 Selectivity *indexSelectivity, double *indexCorrelation,
8285 double *indexPages)
8286 {
8287 IndexOptInfo *index = path->indexinfo;
8288 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
8289 List *selectivityQuals;
8290 double numPages = index->pages,
8291 numTuples = index->tuples;
8292 double numEntryPages,
8293 numDataPages,
8294 numPendingPages,
8295 numEntries;
8296 GinQualCounts counts;
8297 bool matchPossible;
8298 bool fullIndexScan;
8299 double partialScale;
8300 double entryPagesFetched,
8301 dataPagesFetched,
8302 dataPagesFetchedBySel;
8303 double qual_op_cost,
8304 qual_arg_cost,
8305 spc_random_page_cost,
8306 outer_scans;
8307 Cost descentCost;
8308 Relation indexRel;
8309 GinStatsData ginStats;
8310 ListCell *lc;
8311 int i;
8312
8313 /*
8314 * Obtain statistical information from the meta page, if possible. Else
8315 * set ginStats to zeroes, and we'll cope below.
8316 */
8317 if (!index->hypothetical)
8318 {
8319 /* Lock should have already been obtained in plancat.c */
8320 indexRel = index_open(index->indexoid, NoLock);
8321 ginGetStats(indexRel, &ginStats);
8322 index_close(indexRel, NoLock);
8323 }
8324 else
8325 {
8326 memset(&ginStats, 0, sizeof(ginStats));
8327 }
8328
8329 /*
8330 * Assuming we got valid (nonzero) stats at all, nPendingPages can be
8331 * trusted, but the other fields are data as of the last VACUUM. We can
8332 * scale them up to account for growth since then, but that method only
8333 * goes so far; in the worst case, the stats might be for a completely
8334 * empty index, and scaling them will produce pretty bogus numbers.
8335 * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
8336 * it's grown more than that, fall back to estimating things only from the
8337 * assumed-accurate index size. But we'll trust nPendingPages in any case
8338 * so long as it's not clearly insane, ie, more than the index size.
8339 */
8340 if (ginStats.nPendingPages < numPages)
8341 numPendingPages = ginStats.nPendingPages;
8342 else
8343 numPendingPages = 0;
8344
8345 if (numPages > 0 && ginStats.nTotalPages <= numPages &&
8346 ginStats.nTotalPages > numPages / 4 &&
8347 ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
8348 {
8349 /*
8350 * OK, the stats seem close enough to sane to be trusted. But we
8351 * still need to scale them by the ratio numPages / nTotalPages to
8352 * account for growth since the last VACUUM.
8353 */
8354 double scale = numPages / ginStats.nTotalPages;
8355
8356 numEntryPages = ceil(ginStats.nEntryPages * scale);
8357 numDataPages = ceil(ginStats.nDataPages * scale);
8358 numEntries = ceil(ginStats.nEntries * scale);
8359 /* ensure we didn't round up too much */
8360 numEntryPages = Min(numEntryPages, numPages - numPendingPages);
8361 numDataPages = Min(numDataPages,
8362 numPages - numPendingPages - numEntryPages);
8363 }
8364 else
8365 {
8366 /*
8367 * We might get here because it's a hypothetical index, or an index
8368 * created pre-9.1 and never vacuumed since upgrading (in which case
8369 * its stats would read as zeroes), or just because it's grown too
8370 * much since the last VACUUM for us to put our faith in scaling.
8371 *
8372 * Invent some plausible internal statistics based on the index page
8373 * count (and clamp that to at least 10 pages, just in case). We
8374 * estimate that 90% of the index is entry pages, and the rest is data
8375 * pages. Estimate 100 entries per entry page; this is rather bogus
8376 * since it'll depend on the size of the keys, but it's more robust
8377 * than trying to predict the number of entries per heap tuple.
8378 */
8379 numPages = Max(numPages, 10);
8380 numEntryPages = floor((numPages - numPendingPages) * 0.90);
8381 numDataPages = numPages - numPendingPages - numEntryPages;
8382 numEntries = floor(numEntryPages * 100);
8383 }
8384
8385 /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
8386 if (numEntries < 1)
8387 numEntries = 1;
8388
8389 /*
8390 * If the index is partial, AND the index predicate with the index-bound
8391 * quals to produce a more accurate idea of the number of rows covered by
8392 * the bound conditions.
8393 */
8394 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
8395
8396 /* Estimate the fraction of main-table tuples that will be visited */
8397 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
8398 index->rel->relid,
8399 JOIN_INNER,
8400 NULL);
8401
8402 /* fetch estimated page cost for tablespace containing index */
8403 get_tablespace_page_costs(index->reltablespace,
8404 &spc_random_page_cost,
8405 NULL);
8406
8407 /*
8408 * Generic assumption about index correlation: there isn't any.
8409 */
8410 *indexCorrelation = 0.0;
8411
8412 /*
8413 * Examine quals to estimate number of search entries & partial matches
8414 */
8415 memset(&counts, 0, sizeof(counts));
8416 counts.arrayScans = 1;
8417 matchPossible = true;
8418
8419 foreach(lc, path->indexclauses)
8420 {
8421 IndexClause *iclause = lfirst_node(IndexClause, lc);
8422 ListCell *lc2;
8423
8424 foreach(lc2, iclause->indexquals)
8425 {
8426 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
8427 Expr *clause = rinfo->clause;
8428
8429 if (IsA(clause, OpExpr))
8430 {
8431 matchPossible = gincost_opexpr(root,
8432 index,
8433 iclause->indexcol,
8434 (OpExpr *) clause,
8435 &counts);
8436 if (!matchPossible)
8437 break;
8438 }
8439 else if (IsA(clause, ScalarArrayOpExpr))
8440 {
8441 matchPossible = gincost_scalararrayopexpr(root,
8442 index,
8443 iclause->indexcol,
8444 (ScalarArrayOpExpr *) clause,
8445 numEntries,
8446 &counts);
8447 if (!matchPossible)
8448 break;
8449 }
8450 else
8451 {
8452 /* shouldn't be anything else for a GIN index */
8453 elog(ERROR, "unsupported GIN indexqual type: %d",
8454 (int) nodeTag(clause));
8455 }
8456 }
8457 }
8458
8459 /* Fall out if there were any provably-unsatisfiable quals */
8460 if (!matchPossible)
8461 {
8462 *indexStartupCost = 0;
8463 *indexTotalCost = 0;
8464 *indexSelectivity = 0;
8465 return;
8466 }
8467
8468 /*
8469 * If attribute has a full scan and at the same time doesn't have normal
8470 * scan, then we'll have to scan all non-null entries of that attribute.
8471 * Currently, we don't have per-attribute statistics for GIN. Thus, we
8472 * must assume the whole GIN index has to be scanned in this case.
8473 */
8474 fullIndexScan = false;
8475 for (i = 0; i < index->nkeycolumns; i++)
8476 {
8477 if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
8478 {
8479 fullIndexScan = true;
8480 break;
8481 }
8482 }
8483
8484 if (fullIndexScan || indexQuals == NIL)
8485 {
8486 /*
8487 * Full index scan will be required. We treat this as if every key in
8488 * the index had been listed in the query; is that reasonable?
8489 */
8490 counts.partialEntries = 0;
8491 counts.exactEntries = numEntries;
8492 counts.searchEntries = numEntries;
8493 }
8494
8495 /* Will we have more than one iteration of a nestloop scan? */
8496 outer_scans = loop_count;
8497
8498 /*
8499 * Compute cost to begin scan, first of all, pay attention to pending
8500 * list.
8501 */
8502 entryPagesFetched = numPendingPages;
8503
8504 /*
8505 * Estimate number of entry pages read. We need to do
8506 * counts.searchEntries searches. Use a power function as it should be,
8507 * but tuples on leaf pages usually is much greater. Here we include all
8508 * searches in entry tree, including search of first entry in partial
8509 * match algorithm
8510 */
8511 entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
8512
8513 /*
8514 * Add an estimate of entry pages read by partial match algorithm. It's a
8515 * scan over leaf pages in entry tree. We haven't any useful stats here,
8516 * so estimate it as proportion. Because counts.partialEntries is really
8517 * pretty bogus (see code above), it's possible that it is more than
8518 * numEntries; clamp the proportion to ensure sanity.
8519 */
8520 partialScale = counts.partialEntries / numEntries;
8521 partialScale = Min(partialScale, 1.0);
8522
8523 entryPagesFetched += ceil(numEntryPages * partialScale);
8524
8525 /*
8526 * Partial match algorithm reads all data pages before doing actual scan,
8527 * so it's a startup cost. Again, we haven't any useful stats here, so
8528 * estimate it as proportion.
8529 */
8530 dataPagesFetched = ceil(numDataPages * partialScale);
8531
8532 *indexStartupCost = 0;
8533 *indexTotalCost = 0;
8534
8535 /*
8536 * Add a CPU-cost component to represent the costs of initial entry btree
8537 * descent. We don't charge any I/O cost for touching upper btree levels,
8538 * since they tend to stay in cache, but we still have to do about log2(N)
8539 * comparisons to descend a btree of N leaf tuples. We charge one
8540 * cpu_operator_cost per comparison.
8541 *
8542 * If there are ScalarArrayOpExprs, charge this once per SA scan. The
8543 * ones after the first one are not startup cost so far as the overall
8544 * plan is concerned, so add them only to "total" cost.
8545 */
8546 if (numEntries > 1) /* avoid computing log(0) */
8547 {
8548 descentCost = ceil(log(numEntries) / log(2.0)) * cpu_operator_cost;
8549 *indexStartupCost += descentCost * counts.searchEntries;
8550 *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
8551 }
8552
8553 /*
8554 * Add a cpu cost per entry-page fetched. This is not amortized over a
8555 * loop.
8556 */
8557 *indexStartupCost += entryPagesFetched * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
8558 *indexTotalCost += entryPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
8559
8560 /*
8561 * Add a cpu cost per data-page fetched. This is also not amortized over a
8562 * loop. Since those are the data pages from the partial match algorithm,
8563 * charge them as startup cost.
8564 */
8565 *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * dataPagesFetched;
8566
8567 /*
8568 * Since we add the startup cost to the total cost later on, remove the
8569 * initial arrayscan from the total.
8570 */
8571 *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
8572
8573 /*
8574 * Calculate cache effects if more than one scan due to nestloops or array
8575 * quals. The result is pro-rated per nestloop scan, but the array qual
8576 * factor shouldn't be pro-rated (compare genericcostestimate).
8577 */
8578 if (outer_scans > 1 || counts.arrayScans > 1)
8579 {
8580 entryPagesFetched *= outer_scans * counts.arrayScans;
8581 entryPagesFetched = index_pages_fetched(entryPagesFetched,
8582 (BlockNumber) numEntryPages,
8583 numEntryPages, root);
8584 entryPagesFetched /= outer_scans;
8585 dataPagesFetched *= outer_scans * counts.arrayScans;
8586 dataPagesFetched = index_pages_fetched(dataPagesFetched,
8587 (BlockNumber) numDataPages,
8588 numDataPages, root);
8589 dataPagesFetched /= outer_scans;
8590 }
8591
8592 /*
8593 * Here we use random page cost because logically-close pages could be far
8594 * apart on disk.
8595 */
8596 *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
8597
8598 /*
8599 * Now compute the number of data pages fetched during the scan.
8600 *
8601 * We assume every entry to have the same number of items, and that there
8602 * is no overlap between them. (XXX: tsvector and array opclasses collect
8603 * statistics on the frequency of individual keys; it would be nice to use
8604 * those here.)
8605 */
8606 dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
8607
8608 /*
8609 * If there is a lot of overlap among the entries, in particular if one of
8610 * the entries is very frequent, the above calculation can grossly
8611 * under-estimate. As a simple cross-check, calculate a lower bound based
8612 * on the overall selectivity of the quals. At a minimum, we must read
8613 * one item pointer for each matching entry.
8614 *
8615 * The width of each item pointer varies, based on the level of
8616 * compression. We don't have statistics on that, but an average of
8617 * around 3 bytes per item is fairly typical.
8618 */
8619 dataPagesFetchedBySel = ceil(*indexSelectivity *
8620 (numTuples / (BLCKSZ / 3)));
8621 if (dataPagesFetchedBySel > dataPagesFetched)
8622 dataPagesFetched = dataPagesFetchedBySel;
8623
8624 /* Add one page cpu-cost to the startup cost */
8625 *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
8626
8627 /*
8628 * Add once again a CPU-cost for those data pages, before amortizing for
8629 * cache.
8630 */
8631 *indexTotalCost += dataPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
8632
8633 /* Account for cache effects, the same as above */
8634 if (outer_scans > 1 || counts.arrayScans > 1)
8635 {
8636 dataPagesFetched *= outer_scans * counts.arrayScans;
8637 dataPagesFetched = index_pages_fetched(dataPagesFetched,
8638 (BlockNumber) numDataPages,
8639 numDataPages, root);
8640 dataPagesFetched /= outer_scans;
8641 }
8642
8643 /* And apply random_page_cost as the cost per page */
8644 *indexTotalCost += *indexStartupCost +
8645 dataPagesFetched * spc_random_page_cost;
8646
8647 /*
8648 * Add on index qual eval costs, much as in genericcostestimate. We charge
8649 * cpu but we can disregard indexorderbys, since GIN doesn't support
8650 * those.
8651 */
8652 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
8653 qual_op_cost = cpu_operator_cost * list_length(indexQuals);
8654
8655 *indexStartupCost += qual_arg_cost;
8656 *indexTotalCost += qual_arg_cost;
8657
8658 /*
8659 * Add a cpu cost per search entry, corresponding to the actual visited
8660 * entries.
8661 */
8662 *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
8663 /* Now add a cpu cost per tuple in the posting lists / trees */
8664 *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
8665 *indexPages = dataPagesFetched;
8666 }
8667
8668 /*
8669 * BRIN has search behavior completely different from other index types
8670 */
8671 void
8672 brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
8673 Cost *indexStartupCost, Cost *indexTotalCost,
8674 Selectivity *indexSelectivity, double *indexCorrelation,
8675 double *indexPages)
8676 {
8677 IndexOptInfo *index = path->indexinfo;
8678 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
8679 double numPages = index->pages;
8680 RelOptInfo *baserel = index->rel;
8681 RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
8682 Cost spc_seq_page_cost;
8683 Cost spc_random_page_cost;
8684 double qual_arg_cost;
8685 double qualSelectivity;
8686 BrinStatsData statsData;
8687 double indexRanges;
8688 double minimalRanges;
8689 double estimatedRanges;
8690 double selec;
8691 Relation indexRel;
8692 ListCell *l;
8693 VariableStatData vardata;
8694
8695 Assert(rte->rtekind == RTE_RELATION);
8696
8697 /* fetch estimated page cost for the tablespace containing the index */
8698 get_tablespace_page_costs(index->reltablespace,
8699 &spc_random_page_cost,
8700 &spc_seq_page_cost);
8701
8702 /*
8703 * Obtain some data from the index itself, if possible. Otherwise invent
8704 * some plausible internal statistics based on the relation page count.
8705 */
8706 if (!index->hypothetical)
8707 {
8708 /*
8709 * A lock should have already been obtained on the index in plancat.c.
8710 */
8711 indexRel = index_open(index->indexoid, NoLock);
8712 brinGetStats(indexRel, &statsData);
8713 index_close(indexRel, NoLock);
8714
8715 /* work out the actual number of ranges in the index */
8716 indexRanges = Max(ceil((double) baserel->pages /
8717 statsData.pagesPerRange), 1.0);
8718 }
8719 else
8720 {
8721 /*
8722 * Assume default number of pages per range, and estimate the number
8723 * of ranges based on that.
8724 */
8725 indexRanges = Max(ceil((double) baserel->pages /
8726 BRIN_DEFAULT_PAGES_PER_RANGE), 1.0);
8727
8728 statsData.pagesPerRange = BRIN_DEFAULT_PAGES_PER_RANGE;
8729 statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
8730 }
8731
8732 /*
8733 * Compute index correlation
8734 *
8735 * Because we can use all index quals equally when scanning, we can use
8736 * the largest correlation (in absolute value) among columns used by the
8737 * query. Start at zero, the worst possible case. If we cannot find any
8738 * correlation statistics, we will keep it as 0.
8739 */
8740 *indexCorrelation = 0;
8741
8742 foreach(l, path->indexclauses)
8743 {
8744 IndexClause *iclause = lfirst_node(IndexClause, l);
8745 AttrNumber attnum = index->indexkeys[iclause->indexcol];
8746
8747 /* attempt to lookup stats in relation for this index column */
8748 if (attnum != 0)
8749 {
8750 /* Simple variable -- look to stats for the underlying table */
8751 if (get_relation_stats_hook &&
8752 (*get_relation_stats_hook) (root, rte, attnum, &vardata))
8753 {
8754 /*
8755 * The hook took control of acquiring a stats tuple. If it
8756 * did supply a tuple, it'd better have supplied a freefunc.
8757 */
8758 if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
8759 elog(ERROR,
8760 "no function provided to release variable stats with");
8761 }
8762 else
8763 {
8764 vardata.statsTuple =
8765 SearchSysCache3(STATRELATTINH,
8766 ObjectIdGetDatum(rte->relid),
8767 Int16GetDatum(attnum),
8768 BoolGetDatum(false));
8769 vardata.freefunc = ReleaseSysCache;
8770 }
8771 }
8772 else
8773 {
8774 /*
8775 * Looks like we've found an expression column in the index. Let's
8776 * see if there's any stats for it.
8777 */
8778
8779 /* get the attnum from the 0-based index. */
8780 attnum = iclause->indexcol + 1;
8781
8782 if (get_index_stats_hook &&
8783 (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
8784 {
8785 /*
8786 * The hook took control of acquiring a stats tuple. If it
8787 * did supply a tuple, it'd better have supplied a freefunc.
8788 */
8789 if (HeapTupleIsValid(vardata.statsTuple) &&
8790 !vardata.freefunc)
8791 elog(ERROR, "no function provided to release variable stats with");
8792 }
8793 else
8794 {
8795 vardata.statsTuple = SearchSysCache3(STATRELATTINH,
8796 ObjectIdGetDatum(index->indexoid),
8797 Int16GetDatum(attnum),
8798 BoolGetDatum(false));
8799 vardata.freefunc = ReleaseSysCache;
8800 }
8801 }
8802
8803 if (HeapTupleIsValid(vardata.statsTuple))
8804 {
8805 AttStatsSlot sslot;
8806
8807 if (get_attstatsslot(&sslot, vardata.statsTuple,
8808 STATISTIC_KIND_CORRELATION, InvalidOid,
8809 ATTSTATSSLOT_NUMBERS))
8810 {
8811 double varCorrelation = 0.0;
8812
8813 if (sslot.nnumbers > 0)
8814 varCorrelation = fabs(sslot.numbers[0]);
8815
8816 if (varCorrelation > *indexCorrelation)
8817 *indexCorrelation = varCorrelation;
8818
8819 free_attstatsslot(&sslot);
8820 }
8821 }
8822
8823 ReleaseVariableStats(vardata);
8824 }
8825
8826 qualSelectivity = clauselist_selectivity(root, indexQuals,
8827 baserel->relid,
8828 JOIN_INNER, NULL);
8829
8830 /*
8831 * Now calculate the minimum possible ranges we could match with if all of
8832 * the rows were in the perfect order in the table's heap.
8833 */
8834 minimalRanges = ceil(indexRanges * qualSelectivity);
8835
8836 /*
8837 * Now estimate the number of ranges that we'll touch by using the
8838 * indexCorrelation from the stats. Careful not to divide by zero (note
8839 * we're using the absolute value of the correlation).
8840 */
8841 if (*indexCorrelation < 1.0e-10)
8842 estimatedRanges = indexRanges;
8843 else
8844 estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8845
8846 /* we expect to visit this portion of the table */
8847 selec = estimatedRanges / indexRanges;
8848
8849 CLAMP_PROBABILITY(selec);
8850
8851 *indexSelectivity = selec;
8852
8853 /*
8854 * Compute the index qual costs, much as in genericcostestimate, to add to
8855 * the index costs. We can disregard indexorderbys, since BRIN doesn't
8856 * support those.
8857 */
8858 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
8859
8860 /*
8861 * Compute the startup cost as the cost to read the whole revmap
8862 * sequentially, including the cost to execute the index quals.
8863 */
8864 *indexStartupCost =
8865 spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8866 *indexStartupCost += qual_arg_cost;
8867
8868 /*
8869 * To read a BRIN index there might be a bit of back and forth over
8870 * regular pages, as revmap might point to them out of sequential order;
8871 * calculate the total cost as reading the whole index in random order.
8872 */
8873 *indexTotalCost = *indexStartupCost +
8874 spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8875
8876 /*
8877 * Charge a small amount per range tuple which we expect to match to. This
8878 * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8879 * will set a bit for each page in the range when we find a matching
8880 * range, so we must multiply the charge by the number of pages in the
8881 * range.
8882 */
8883 *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8884 statsData.pagesPerRange;
8885
8886 *indexPages = index->pages;
8887 }