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