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