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