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