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