PostgreSQL Source Code git master
selfuncs.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * selfuncs.c
4 * Selectivity functions and index cost estimation functions for
5 * standard operators and index access methods.
6 *
7 * Selectivity routines are registered in the pg_operator catalog
8 * in the "oprrest" and "oprjoin" attributes.
9 *
10 * Index cost functions are located via the index AM's API struct,
11 * which is obtained from the handler function registered in pg_am.
12 *
13 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
15 *
16 *
17 * IDENTIFICATION
18 * src/backend/utils/adt/selfuncs.c
19 *
20 *-------------------------------------------------------------------------
21 */
22
23/*----------
24 * Operator selectivity estimation functions are called to estimate the
25 * selectivity of WHERE clauses whose top-level operator is their operator.
26 * We divide the problem into two cases:
27 * Restriction clause estimation: the clause involves vars of just
28 * one relation.
29 * Join clause estimation: the clause involves vars of multiple rels.
30 * Join selectivity estimation is far more difficult and usually less accurate
31 * than restriction estimation.
32 *
33 * When dealing with the inner scan of a nestloop join, we consider the
34 * join's joinclauses as restriction clauses for the inner relation, and
35 * treat vars of the outer relation as parameters (a/k/a constants of unknown
36 * values). So, restriction estimators need to be able to accept an argument
37 * telling which relation is to be treated as the variable.
38 *
39 * The call convention for a restriction estimator (oprrest function) is
40 *
41 * Selectivity oprrest (PlannerInfo *root,
42 * Oid operator,
43 * List *args,
44 * int varRelid);
45 *
46 * root: general information about the query (rtable and RelOptInfo lists
47 * are particularly important for the estimator).
48 * operator: OID of the specific operator in question.
49 * args: argument list from the operator clause.
50 * varRelid: if not zero, the relid (rtable index) of the relation to
51 * be treated as the variable relation. May be zero if the args list
52 * is known to contain vars of only one relation.
53 *
54 * This is represented at the SQL level (in pg_proc) as
55 *
56 * float8 oprrest (internal, oid, internal, int4);
57 *
58 * The result is a selectivity, that is, a fraction (0 to 1) of the rows
59 * of the relation that are expected to produce a TRUE result for the
60 * given operator.
61 *
62 * The call convention for a join estimator (oprjoin function) is similar
63 * except that varRelid is not needed, and instead join information is
64 * supplied:
65 *
66 * Selectivity oprjoin (PlannerInfo *root,
67 * Oid operator,
68 * List *args,
69 * JoinType jointype,
70 * SpecialJoinInfo *sjinfo);
71 *
72 * float8 oprjoin (internal, oid, internal, int2, internal);
73 *
74 * (Before Postgres 8.4, join estimators had only the first four of these
75 * parameters. That signature is still allowed, but deprecated.) The
76 * relationship between jointype and sjinfo is explained in the comments for
77 * clause_selectivity() --- the short version is that jointype is usually
78 * best ignored in favor of examining sjinfo.
79 *
80 * Join selectivity for regular inner and outer joins is defined as the
81 * fraction (0 to 1) of the cross product of the relations that is expected
82 * to produce a TRUE result for the given operator. For both semi and anti
83 * joins, however, the selectivity is defined as the fraction of the left-hand
84 * side relation's rows that are expected to have a match (ie, at least one
85 * row with a TRUE result) in the right-hand side.
86 *
87 * For both oprrest and oprjoin functions, the operator's input collation OID
88 * (if any) is passed using the standard fmgr mechanism, so that the estimator
89 * function can fetch it with PG_GET_COLLATION(). Note, however, that all
90 * statistics in pg_statistic are currently built using the relevant column's
91 * collation.
92 *----------
93 */
94
95#include "postgres.h"
96
97#include <ctype.h>
98#include <math.h>
99
100#include "access/brin.h"
101#include "access/brin_page.h"
102#include "access/gin.h"
103#include "access/table.h"
104#include "access/tableam.h"
105#include "access/visibilitymap.h"
106#include "catalog/pg_am.h"
107#include "catalog/pg_collation.h"
108#include "catalog/pg_operator.h"
109#include "catalog/pg_statistic.h"
111#include "executor/nodeAgg.h"
112#include "miscadmin.h"
113#include "nodes/makefuncs.h"
114#include "nodes/nodeFuncs.h"
115#include "optimizer/clauses.h"
116#include "optimizer/cost.h"
117#include "optimizer/optimizer.h"
118#include "optimizer/pathnode.h"
119#include "optimizer/paths.h"
120#include "optimizer/plancat.h"
121#include "parser/parse_clause.h"
123#include "parser/parsetree.h"
124#include "rewrite/rewriteManip.h"
126#include "storage/bufmgr.h"
127#include "utils/acl.h"
128#include "utils/array.h"
129#include "utils/builtins.h"
130#include "utils/date.h"
131#include "utils/datum.h"
132#include "utils/fmgroids.h"
133#include "utils/index_selfuncs.h"
134#include "utils/lsyscache.h"
135#include "utils/memutils.h"
136#include "utils/pg_locale.h"
137#include "utils/rel.h"
138#include "utils/selfuncs.h"
139#include "utils/snapmgr.h"
140#include "utils/spccache.h"
141#include "utils/syscache.h"
142#include "utils/timestamp.h"
143#include "utils/typcache.h"
144
145#define DEFAULT_PAGE_CPU_MULTIPLIER 50.0
146
147/* Hooks for plugins to get control when we ask for stats */
150
151static double eqsel_internal(PG_FUNCTION_ARGS, bool negate);
152static double eqjoinsel_inner(Oid opfuncoid, Oid collation,
153 VariableStatData *vardata1, VariableStatData *vardata2,
154 double nd1, double nd2,
155 bool isdefault1, bool isdefault2,
156 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
158 bool have_mcvs1, bool have_mcvs2);
159static double eqjoinsel_semi(Oid opfuncoid, Oid collation,
160 VariableStatData *vardata1, VariableStatData *vardata2,
161 double nd1, double nd2,
162 bool isdefault1, bool isdefault2,
163 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
165 bool have_mcvs1, bool have_mcvs2,
166 RelOptInfo *inner_rel);
168 RelOptInfo *rel, List **varinfos, double *ndistinct);
169static bool convert_to_scalar(Datum value, Oid valuetypid, Oid collid,
170 double *scaledvalue,
171 Datum lobound, Datum hibound, Oid boundstypid,
172 double *scaledlobound, double *scaledhibound);
173static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure);
174static void convert_string_to_scalar(char *value,
175 double *scaledvalue,
176 char *lobound,
177 double *scaledlobound,
178 char *hibound,
179 double *scaledhibound);
181 double *scaledvalue,
182 Datum lobound,
183 double *scaledlobound,
184 Datum hibound,
185 double *scaledhibound);
186static double convert_one_string_to_scalar(char *value,
187 int rangelo, int rangehi);
188static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
189 int rangelo, int rangehi);
190static char *convert_string_datum(Datum value, Oid typid, Oid collid,
191 bool *failure);
192static double convert_timevalue_to_scalar(Datum value, Oid typid,
193 bool *failure);
195 VariableStatData *vardata);
197 Oid sortop, Oid collation,
198 Datum *min, Datum *max);
199static void get_stats_slot_range(AttStatsSlot *sslot,
200 Oid opfuncoid, FmgrInfo *opproc,
201 Oid collation, int16 typLen, bool typByVal,
202 Datum *min, Datum *max, bool *p_have_data);
204 VariableStatData *vardata,
205 Oid sortop, Oid collation,
206 Datum *min, Datum *max);
207static bool get_actual_variable_endpoint(Relation heapRel,
208 Relation indexRel,
209 ScanDirection indexscandir,
210 ScanKey scankeys,
211 int16 typLen,
212 bool typByVal,
213 TupleTableSlot *tableslot,
214 MemoryContext outercontext,
215 Datum *endpointDatum);
217
218
219/*
220 * eqsel - Selectivity of "=" for any data types.
221 *
222 * Note: this routine is also used to estimate selectivity for some
223 * operators that are not "=" but have comparable selectivity behavior,
224 * such as "~=" (geometric approximate-match). Even for "=", we must
225 * keep in mind that the left and right datatypes may differ.
226 */
227Datum
229{
230 PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
231}
232
233/*
234 * Common code for eqsel() and neqsel()
235 */
236static double
238{
240 Oid operator = PG_GETARG_OID(1);
242 int varRelid = PG_GETARG_INT32(3);
243 Oid collation = PG_GET_COLLATION();
244 VariableStatData vardata;
245 Node *other;
246 bool varonleft;
247 double selec;
248
249 /*
250 * When asked about <>, we do the estimation using the corresponding =
251 * operator, then convert to <> via "1.0 - eq_selectivity - nullfrac".
252 */
253 if (negate)
254 {
255 operator = get_negator(operator);
256 if (!OidIsValid(operator))
257 {
258 /* Use default selectivity (should we raise an error instead?) */
259 return 1.0 - DEFAULT_EQ_SEL;
260 }
261 }
262
263 /*
264 * If expression is not variable = something or something = variable, then
265 * punt and return a default estimate.
266 */
267 if (!get_restriction_variable(root, args, varRelid,
268 &vardata, &other, &varonleft))
269 return negate ? (1.0 - DEFAULT_EQ_SEL) : DEFAULT_EQ_SEL;
270
271 /*
272 * We can do a lot better if the something is a constant. (Note: the
273 * Const might result from estimation rather than being a simple constant
274 * in the query.)
275 */
276 if (IsA(other, Const))
277 selec = var_eq_const(&vardata, operator, collation,
278 ((Const *) other)->constvalue,
279 ((Const *) other)->constisnull,
280 varonleft, negate);
281 else
282 selec = var_eq_non_const(&vardata, operator, collation, other,
283 varonleft, negate);
284
285 ReleaseVariableStats(vardata);
286
287 return selec;
288}
289
290/*
291 * var_eq_const --- eqsel for var = const case
292 *
293 * This is exported so that some other estimation functions can use it.
294 */
295double
296var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
297 Datum constval, bool constisnull,
298 bool varonleft, bool negate)
299{
300 double selec;
301 double nullfrac = 0.0;
302 bool isdefault;
303 Oid opfuncoid;
304
305 /*
306 * If the constant is NULL, assume operator is strict and return zero, ie,
307 * operator will never return TRUE. (It's zero even for a negator op.)
308 */
309 if (constisnull)
310 return 0.0;
311
312 /*
313 * Grab the nullfrac for use below. Note we allow use of nullfrac
314 * regardless of security check.
315 */
316 if (HeapTupleIsValid(vardata->statsTuple))
317 {
318 Form_pg_statistic stats;
319
320 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
321 nullfrac = stats->stanullfrac;
322 }
323
324 /*
325 * If we matched the var to a unique index or DISTINCT clause, assume
326 * there is exactly one match regardless of anything else. (This is
327 * slightly bogus, since the index or clause's equality operator might be
328 * different from ours, but it's much more likely to be right than
329 * ignoring the information.)
330 */
331 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
332 {
333 selec = 1.0 / vardata->rel->tuples;
334 }
335 else if (HeapTupleIsValid(vardata->statsTuple) &&
337 (opfuncoid = get_opcode(oproid))))
338 {
339 AttStatsSlot sslot;
340 bool match = false;
341 int i;
342
343 /*
344 * Is the constant "=" to any of the column's most common values?
345 * (Although the given operator may not really be "=", we will assume
346 * that seeing whether it returns TRUE is an appropriate test. If you
347 * don't like this, maybe you shouldn't be using eqsel for your
348 * operator...)
349 */
350 if (get_attstatsslot(&sslot, vardata->statsTuple,
351 STATISTIC_KIND_MCV, InvalidOid,
353 {
354 LOCAL_FCINFO(fcinfo, 2);
355 FmgrInfo eqproc;
356
357 fmgr_info(opfuncoid, &eqproc);
358
359 /*
360 * Save a few cycles by setting up the fcinfo struct just once.
361 * Using FunctionCallInvoke directly also avoids failure if the
362 * eqproc returns NULL, though really equality functions should
363 * never do that.
364 */
365 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
366 NULL, NULL);
367 fcinfo->args[0].isnull = false;
368 fcinfo->args[1].isnull = false;
369 /* be careful to apply operator right way 'round */
370 if (varonleft)
371 fcinfo->args[1].value = constval;
372 else
373 fcinfo->args[0].value = constval;
374
375 for (i = 0; i < sslot.nvalues; i++)
376 {
377 Datum fresult;
378
379 if (varonleft)
380 fcinfo->args[0].value = sslot.values[i];
381 else
382 fcinfo->args[1].value = sslot.values[i];
383 fcinfo->isnull = false;
384 fresult = FunctionCallInvoke(fcinfo);
385 if (!fcinfo->isnull && DatumGetBool(fresult))
386 {
387 match = true;
388 break;
389 }
390 }
391 }
392 else
393 {
394 /* no most-common-value info available */
395 i = 0; /* keep compiler quiet */
396 }
397
398 if (match)
399 {
400 /*
401 * Constant is "=" to this common value. We know selectivity
402 * exactly (or as exactly as ANALYZE could calculate it, anyway).
403 */
404 selec = sslot.numbers[i];
405 }
406 else
407 {
408 /*
409 * Comparison is against a constant that is neither NULL nor any
410 * of the common values. Its selectivity cannot be more than
411 * this:
412 */
413 double sumcommon = 0.0;
414 double otherdistinct;
415
416 for (i = 0; i < sslot.nnumbers; i++)
417 sumcommon += sslot.numbers[i];
418 selec = 1.0 - sumcommon - nullfrac;
419 CLAMP_PROBABILITY(selec);
420
421 /*
422 * and in fact it's probably a good deal less. We approximate that
423 * all the not-common values share this remaining fraction
424 * equally, so we divide by the number of other distinct values.
425 */
426 otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
427 sslot.nnumbers;
428 if (otherdistinct > 1)
429 selec /= otherdistinct;
430
431 /*
432 * Another cross-check: selectivity shouldn't be estimated as more
433 * than the least common "most common value".
434 */
435 if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
436 selec = sslot.numbers[sslot.nnumbers - 1];
437 }
438
439 free_attstatsslot(&sslot);
440 }
441 else
442 {
443 /*
444 * No ANALYZE stats available, so make a guess using estimated number
445 * of distinct values and assuming they are equally common. (The guess
446 * is unlikely to be very good, but we do know a few special cases.)
447 */
448 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
449 }
450
451 /* now adjust if we wanted <> rather than = */
452 if (negate)
453 selec = 1.0 - selec - nullfrac;
454
455 /* result should be in range, but make sure... */
456 CLAMP_PROBABILITY(selec);
457
458 return selec;
459}
460
461/*
462 * var_eq_non_const --- eqsel for var = something-other-than-const case
463 *
464 * This is exported so that some other estimation functions can use it.
465 */
466double
467var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
468 Node *other,
469 bool varonleft, bool negate)
470{
471 double selec;
472 double nullfrac = 0.0;
473 bool isdefault;
474
475 /*
476 * Grab the nullfrac for use below.
477 */
478 if (HeapTupleIsValid(vardata->statsTuple))
479 {
480 Form_pg_statistic stats;
481
482 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
483 nullfrac = stats->stanullfrac;
484 }
485
486 /*
487 * If we matched the var to a unique index or DISTINCT clause, assume
488 * there is exactly one match regardless of anything else. (This is
489 * slightly bogus, since the index or clause's equality operator might be
490 * different from ours, but it's much more likely to be right than
491 * ignoring the information.)
492 */
493 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
494 {
495 selec = 1.0 / vardata->rel->tuples;
496 }
497 else if (HeapTupleIsValid(vardata->statsTuple))
498 {
499 double ndistinct;
500 AttStatsSlot sslot;
501
502 /*
503 * Search is for a value that we do not know a priori, but we will
504 * assume it is not NULL. Estimate the selectivity as non-null
505 * fraction divided by number of distinct values, so that we get a
506 * result averaged over all possible values whether common or
507 * uncommon. (Essentially, we are assuming that the not-yet-known
508 * comparison value is equally likely to be any of the possible
509 * values, regardless of their frequency in the table. Is that a good
510 * idea?)
511 */
512 selec = 1.0 - nullfrac;
513 ndistinct = get_variable_numdistinct(vardata, &isdefault);
514 if (ndistinct > 1)
515 selec /= ndistinct;
516
517 /*
518 * Cross-check: selectivity should never be estimated as more than the
519 * most common value's.
520 */
521 if (get_attstatsslot(&sslot, vardata->statsTuple,
522 STATISTIC_KIND_MCV, InvalidOid,
524 {
525 if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
526 selec = sslot.numbers[0];
527 free_attstatsslot(&sslot);
528 }
529 }
530 else
531 {
532 /*
533 * No ANALYZE stats available, so make a guess using estimated number
534 * of distinct values and assuming they are equally common. (The guess
535 * is unlikely to be very good, but we do know a few special cases.)
536 */
537 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
538 }
539
540 /* now adjust if we wanted <> rather than = */
541 if (negate)
542 selec = 1.0 - selec - nullfrac;
543
544 /* result should be in range, but make sure... */
545 CLAMP_PROBABILITY(selec);
546
547 return selec;
548}
549
550/*
551 * neqsel - Selectivity of "!=" for any data types.
552 *
553 * This routine is also used for some operators that are not "!="
554 * but have comparable selectivity behavior. See above comments
555 * for eqsel().
556 */
557Datum
559{
560 PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, true));
561}
562
563/*
564 * scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
565 *
566 * This is the guts of scalarltsel/scalarlesel/scalargtsel/scalargesel.
567 * The isgt and iseq flags distinguish which of the four cases apply.
568 *
569 * The caller has commuted the clause, if necessary, so that we can treat
570 * the variable as being on the left. The caller must also make sure that
571 * the other side of the clause is a non-null Const, and dissect that into
572 * a value and datatype. (This definition simplifies some callers that
573 * want to estimate against a computed value instead of a Const node.)
574 *
575 * This routine works for any datatype (or pair of datatypes) known to
576 * convert_to_scalar(). If it is applied to some other datatype,
577 * it will return an approximate estimate based on assuming that the constant
578 * value falls in the middle of the bin identified by binary search.
579 */
580static double
581scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq,
582 Oid collation,
583 VariableStatData *vardata, Datum constval, Oid consttype)
584{
585 Form_pg_statistic stats;
586 FmgrInfo opproc;
587 double mcv_selec,
588 hist_selec,
589 sumcommon;
590 double selec;
591
592 if (!HeapTupleIsValid(vardata->statsTuple))
593 {
594 /*
595 * No stats are available. Typically this means we have to fall back
596 * on the default estimate; but if the variable is CTID then we can
597 * make an estimate based on comparing the constant to the table size.
598 */
599 if (vardata->var && IsA(vardata->var, Var) &&
600 ((Var *) vardata->var)->varattno == SelfItemPointerAttributeNumber)
601 {
602 ItemPointer itemptr;
603 double block;
604 double density;
605
606 /*
607 * If the relation's empty, we're going to include all of it.
608 * (This is mostly to avoid divide-by-zero below.)
609 */
610 if (vardata->rel->pages == 0)
611 return 1.0;
612
613 itemptr = (ItemPointer) DatumGetPointer(constval);
614 block = ItemPointerGetBlockNumberNoCheck(itemptr);
615
616 /*
617 * Determine the average number of tuples per page (density).
618 *
619 * Since the last page will, on average, be only half full, we can
620 * estimate it to have half as many tuples as earlier pages. So
621 * give it half the weight of a regular page.
622 */
623 density = vardata->rel->tuples / (vardata->rel->pages - 0.5);
624
625 /* If target is the last page, use half the density. */
626 if (block >= vardata->rel->pages - 1)
627 density *= 0.5;
628
629 /*
630 * Using the average tuples per page, calculate how far into the
631 * page the itemptr is likely to be and adjust block accordingly,
632 * by adding that fraction of a whole block (but never more than a
633 * whole block, no matter how high the itemptr's offset is). Here
634 * we are ignoring the possibility of dead-tuple line pointers,
635 * which is fairly bogus, but we lack the info to do better.
636 */
637 if (density > 0.0)
638 {
640
641 block += Min(offset / density, 1.0);
642 }
643
644 /*
645 * Convert relative block number to selectivity. Again, the last
646 * page has only half weight.
647 */
648 selec = block / (vardata->rel->pages - 0.5);
649
650 /*
651 * The calculation so far gave us a selectivity for the "<=" case.
652 * We'll have one fewer tuple for "<" and one additional tuple for
653 * ">=", the latter of which we'll reverse the selectivity for
654 * below, so we can simply subtract one tuple for both cases. The
655 * cases that need this adjustment can be identified by iseq being
656 * equal to isgt.
657 */
658 if (iseq == isgt && vardata->rel->tuples >= 1.0)
659 selec -= (1.0 / vardata->rel->tuples);
660
661 /* Finally, reverse the selectivity for the ">", ">=" cases. */
662 if (isgt)
663 selec = 1.0 - selec;
664
665 CLAMP_PROBABILITY(selec);
666 return selec;
667 }
668
669 /* no stats available, so default result */
670 return DEFAULT_INEQ_SEL;
671 }
672 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
673
674 fmgr_info(get_opcode(operator), &opproc);
675
676 /*
677 * If we have most-common-values info, add up the fractions of the MCV
678 * entries that satisfy MCV OP CONST. These fractions contribute directly
679 * to the result selectivity. Also add up the total fraction represented
680 * by MCV entries.
681 */
682 mcv_selec = mcv_selectivity(vardata, &opproc, collation, constval, true,
683 &sumcommon);
684
685 /*
686 * If there is a histogram, determine which bin the constant falls in, and
687 * compute the resulting contribution to selectivity.
688 */
689 hist_selec = ineq_histogram_selectivity(root, vardata,
690 operator, &opproc, isgt, iseq,
691 collation,
692 constval, consttype);
693
694 /*
695 * Now merge the results from the MCV and histogram calculations,
696 * realizing that the histogram covers only the non-null values that are
697 * not listed in MCV.
698 */
699 selec = 1.0 - stats->stanullfrac - sumcommon;
700
701 if (hist_selec >= 0.0)
702 selec *= hist_selec;
703 else
704 {
705 /*
706 * If no histogram but there are values not accounted for by MCV,
707 * arbitrarily assume half of them will match.
708 */
709 selec *= 0.5;
710 }
711
712 selec += mcv_selec;
713
714 /* result should be in range, but make sure... */
715 CLAMP_PROBABILITY(selec);
716
717 return selec;
718}
719
720/*
721 * mcv_selectivity - Examine the MCV list for selectivity estimates
722 *
723 * Determine the fraction of the variable's MCV population that satisfies
724 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
725 * compute the fraction of the total column population represented by the MCV
726 * list. This code will work for any boolean-returning predicate operator.
727 *
728 * The function result is the MCV selectivity, and the fraction of the
729 * total population is returned into *sumcommonp. Zeroes are returned
730 * if there is no MCV list.
731 */
732double
733mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation,
734 Datum constval, bool varonleft,
735 double *sumcommonp)
736{
737 double mcv_selec,
738 sumcommon;
739 AttStatsSlot sslot;
740 int i;
741
742 mcv_selec = 0.0;
743 sumcommon = 0.0;
744
745 if (HeapTupleIsValid(vardata->statsTuple) &&
746 statistic_proc_security_check(vardata, opproc->fn_oid) &&
747 get_attstatsslot(&sslot, vardata->statsTuple,
748 STATISTIC_KIND_MCV, InvalidOid,
750 {
751 LOCAL_FCINFO(fcinfo, 2);
752
753 /*
754 * We invoke the opproc "by hand" so that we won't fail on NULL
755 * results. Such cases won't arise for normal comparison functions,
756 * but generic_restriction_selectivity could perhaps be used with
757 * operators that can return NULL. A small side benefit is to not
758 * need to re-initialize the fcinfo struct from scratch each time.
759 */
760 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
761 NULL, NULL);
762 fcinfo->args[0].isnull = false;
763 fcinfo->args[1].isnull = false;
764 /* be careful to apply operator right way 'round */
765 if (varonleft)
766 fcinfo->args[1].value = constval;
767 else
768 fcinfo->args[0].value = constval;
769
770 for (i = 0; i < sslot.nvalues; i++)
771 {
772 Datum fresult;
773
774 if (varonleft)
775 fcinfo->args[0].value = sslot.values[i];
776 else
777 fcinfo->args[1].value = sslot.values[i];
778 fcinfo->isnull = false;
779 fresult = FunctionCallInvoke(fcinfo);
780 if (!fcinfo->isnull && DatumGetBool(fresult))
781 mcv_selec += sslot.numbers[i];
782 sumcommon += sslot.numbers[i];
783 }
784 free_attstatsslot(&sslot);
785 }
786
787 *sumcommonp = sumcommon;
788 return mcv_selec;
789}
790
791/*
792 * histogram_selectivity - Examine the histogram for selectivity estimates
793 *
794 * Determine the fraction of the variable's histogram entries that satisfy
795 * the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
796 *
797 * This code will work for any boolean-returning predicate operator, whether
798 * or not it has anything to do with the histogram sort operator. We are
799 * essentially using the histogram just as a representative sample. However,
800 * small histograms are unlikely to be all that representative, so the caller
801 * should be prepared to fall back on some other estimation approach when the
802 * histogram is missing or very small. It may also be prudent to combine this
803 * approach with another one when the histogram is small.
804 *
805 * If the actual histogram size is not at least min_hist_size, we won't bother
806 * to do the calculation at all. Also, if the n_skip parameter is > 0, we
807 * ignore the first and last n_skip histogram elements, on the grounds that
808 * they are outliers and hence not very representative. Typical values for
809 * these parameters are 10 and 1.
810 *
811 * The function result is the selectivity, or -1 if there is no histogram
812 * or it's smaller than min_hist_size.
813 *
814 * The output parameter *hist_size receives the actual histogram size,
815 * or zero if no histogram. Callers may use this number to decide how
816 * much faith to put in the function result.
817 *
818 * Note that the result disregards both the most-common-values (if any) and
819 * null entries. The caller is expected to combine this result with
820 * statistics for those portions of the column population. It may also be
821 * prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
822 */
823double
825 FmgrInfo *opproc, Oid collation,
826 Datum constval, bool varonleft,
827 int min_hist_size, int n_skip,
828 int *hist_size)
829{
830 double result;
831 AttStatsSlot sslot;
832
833 /* check sanity of parameters */
834 Assert(n_skip >= 0);
835 Assert(min_hist_size > 2 * n_skip);
836
837 if (HeapTupleIsValid(vardata->statsTuple) &&
838 statistic_proc_security_check(vardata, opproc->fn_oid) &&
839 get_attstatsslot(&sslot, vardata->statsTuple,
840 STATISTIC_KIND_HISTOGRAM, InvalidOid,
842 {
843 *hist_size = sslot.nvalues;
844 if (sslot.nvalues >= min_hist_size)
845 {
846 LOCAL_FCINFO(fcinfo, 2);
847 int nmatch = 0;
848 int i;
849
850 /*
851 * We invoke the opproc "by hand" so that we won't fail on NULL
852 * results. Such cases won't arise for normal comparison
853 * functions, but generic_restriction_selectivity could perhaps be
854 * used with operators that can return NULL. A small side benefit
855 * is to not need to re-initialize the fcinfo struct from scratch
856 * each time.
857 */
858 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
859 NULL, NULL);
860 fcinfo->args[0].isnull = false;
861 fcinfo->args[1].isnull = false;
862 /* be careful to apply operator right way 'round */
863 if (varonleft)
864 fcinfo->args[1].value = constval;
865 else
866 fcinfo->args[0].value = constval;
867
868 for (i = n_skip; i < sslot.nvalues - n_skip; i++)
869 {
870 Datum fresult;
871
872 if (varonleft)
873 fcinfo->args[0].value = sslot.values[i];
874 else
875 fcinfo->args[1].value = sslot.values[i];
876 fcinfo->isnull = false;
877 fresult = FunctionCallInvoke(fcinfo);
878 if (!fcinfo->isnull && DatumGetBool(fresult))
879 nmatch++;
880 }
881 result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
882 }
883 else
884 result = -1;
885 free_attstatsslot(&sslot);
886 }
887 else
888 {
889 *hist_size = 0;
890 result = -1;
891 }
892
893 return result;
894}
895
896/*
897 * generic_restriction_selectivity - Selectivity for almost anything
898 *
899 * This function estimates selectivity for operators that we don't have any
900 * special knowledge about, but are on data types that we collect standard
901 * MCV and/or histogram statistics for. (Additional assumptions are that
902 * the operator is strict and immutable, or at least stable.)
903 *
904 * If we have "VAR OP CONST" or "CONST OP VAR", selectivity is estimated by
905 * applying the operator to each element of the column's MCV and/or histogram
906 * stats, and merging the results using the assumption that the histogram is
907 * a reasonable random sample of the column's non-MCV population. Note that
908 * if the operator's semantics are related to the histogram ordering, this
909 * might not be such a great assumption; other functions such as
910 * scalarineqsel() are probably a better match in such cases.
911 *
912 * Otherwise, fall back to the default selectivity provided by the caller.
913 */
914double
916 List *args, int varRelid,
917 double default_selectivity)
918{
919 double selec;
920 VariableStatData vardata;
921 Node *other;
922 bool varonleft;
923
924 /*
925 * If expression is not variable OP something or something OP variable,
926 * then punt and return the default estimate.
927 */
928 if (!get_restriction_variable(root, args, varRelid,
929 &vardata, &other, &varonleft))
930 return default_selectivity;
931
932 /*
933 * If the something is a NULL constant, assume operator is strict and
934 * return zero, ie, operator will never return TRUE.
935 */
936 if (IsA(other, Const) &&
937 ((Const *) other)->constisnull)
938 {
939 ReleaseVariableStats(vardata);
940 return 0.0;
941 }
942
943 if (IsA(other, Const))
944 {
945 /* Variable is being compared to a known non-null constant */
946 Datum constval = ((Const *) other)->constvalue;
947 FmgrInfo opproc;
948 double mcvsum;
949 double mcvsel;
950 double nullfrac;
951 int hist_size;
952
953 fmgr_info(get_opcode(oproid), &opproc);
954
955 /*
956 * Calculate the selectivity for the column's most common values.
957 */
958 mcvsel = mcv_selectivity(&vardata, &opproc, collation,
959 constval, varonleft,
960 &mcvsum);
961
962 /*
963 * If the histogram is large enough, see what fraction of it matches
964 * the query, and assume that's representative of the non-MCV
965 * population. Otherwise use the default selectivity for the non-MCV
966 * population.
967 */
968 selec = histogram_selectivity(&vardata, &opproc, collation,
969 constval, varonleft,
970 10, 1, &hist_size);
971 if (selec < 0)
972 {
973 /* Nope, fall back on default */
974 selec = default_selectivity;
975 }
976 else if (hist_size < 100)
977 {
978 /*
979 * For histogram sizes from 10 to 100, we combine the histogram
980 * and default selectivities, putting increasingly more trust in
981 * the histogram for larger sizes.
982 */
983 double hist_weight = hist_size / 100.0;
984
985 selec = selec * hist_weight +
986 default_selectivity * (1.0 - hist_weight);
987 }
988
989 /* In any case, don't believe extremely small or large estimates. */
990 if (selec < 0.0001)
991 selec = 0.0001;
992 else if (selec > 0.9999)
993 selec = 0.9999;
994
995 /* Don't forget to account for nulls. */
996 if (HeapTupleIsValid(vardata.statsTuple))
997 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
998 else
999 nullfrac = 0.0;
1000
1001 /*
1002 * Now merge the results from the MCV and histogram calculations,
1003 * realizing that the histogram covers only the non-null values that
1004 * are not listed in MCV.
1005 */
1006 selec *= 1.0 - nullfrac - mcvsum;
1007 selec += mcvsel;
1008 }
1009 else
1010 {
1011 /* Comparison value is not constant, so we can't do anything */
1012 selec = default_selectivity;
1013 }
1014
1015 ReleaseVariableStats(vardata);
1016
1017 /* result should be in range, but make sure... */
1018 CLAMP_PROBABILITY(selec);
1019
1020 return selec;
1021}
1022
1023/*
1024 * ineq_histogram_selectivity - Examine the histogram for scalarineqsel
1025 *
1026 * Determine the fraction of the variable's histogram population that
1027 * satisfies the inequality condition, ie, VAR < (or <=, >, >=) CONST.
1028 * The isgt and iseq flags distinguish which of the four cases apply.
1029 *
1030 * While opproc could be looked up from the operator OID, common callers
1031 * also need to call it separately, so we make the caller pass both.
1032 *
1033 * Returns -1 if there is no histogram (valid results will always be >= 0).
1034 *
1035 * Note that the result disregards both the most-common-values (if any) and
1036 * null entries. The caller is expected to combine this result with
1037 * statistics for those portions of the column population.
1038 *
1039 * This is exported so that some other estimation functions can use it.
1040 */
1041double
1043 VariableStatData *vardata,
1044 Oid opoid, FmgrInfo *opproc, bool isgt, bool iseq,
1045 Oid collation,
1046 Datum constval, Oid consttype)
1047{
1048 double hist_selec;
1049 AttStatsSlot sslot;
1050
1051 hist_selec = -1.0;
1052
1053 /*
1054 * Someday, ANALYZE might store more than one histogram per rel/att,
1055 * corresponding to more than one possible sort ordering defined for the
1056 * column type. Right now, we know there is only one, so just grab it and
1057 * see if it matches the query.
1058 *
1059 * Note that we can't use opoid as search argument; the staop appearing in
1060 * pg_statistic will be for the relevant '<' operator, but what we have
1061 * might be some other inequality operator such as '>='. (Even if opoid
1062 * is a '<' operator, it could be cross-type.) Hence we must use
1063 * comparison_ops_are_compatible() to see if the operators match.
1064 */
1065 if (HeapTupleIsValid(vardata->statsTuple) &&
1066 statistic_proc_security_check(vardata, opproc->fn_oid) &&
1067 get_attstatsslot(&sslot, vardata->statsTuple,
1068 STATISTIC_KIND_HISTOGRAM, InvalidOid,
1070 {
1071 if (sslot.nvalues > 1 &&
1072 sslot.stacoll == collation &&
1074 {
1075 /*
1076 * Use binary search to find the desired location, namely the
1077 * right end of the histogram bin containing the comparison value,
1078 * which is the leftmost entry for which the comparison operator
1079 * succeeds (if isgt) or fails (if !isgt).
1080 *
1081 * In this loop, we pay no attention to whether the operator iseq
1082 * or not; that detail will be mopped up below. (We cannot tell,
1083 * anyway, whether the operator thinks the values are equal.)
1084 *
1085 * If the binary search accesses the first or last histogram
1086 * entry, we try to replace that endpoint with the true column min
1087 * or max as found by get_actual_variable_range(). This
1088 * ameliorates misestimates when the min or max is moving as a
1089 * result of changes since the last ANALYZE. Note that this could
1090 * result in effectively including MCVs into the histogram that
1091 * weren't there before, but we don't try to correct for that.
1092 */
1093 double histfrac;
1094 int lobound = 0; /* first possible slot to search */
1095 int hibound = sslot.nvalues; /* last+1 slot to search */
1096 bool have_end = false;
1097
1098 /*
1099 * If there are only two histogram entries, we'll want up-to-date
1100 * values for both. (If there are more than two, we need at most
1101 * one of them to be updated, so we deal with that within the
1102 * loop.)
1103 */
1104 if (sslot.nvalues == 2)
1106 vardata,
1107 sslot.staop,
1108 collation,
1109 &sslot.values[0],
1110 &sslot.values[1]);
1111
1112 while (lobound < hibound)
1113 {
1114 int probe = (lobound + hibound) / 2;
1115 bool ltcmp;
1116
1117 /*
1118 * If we find ourselves about to compare to the first or last
1119 * histogram entry, first try to replace it with the actual
1120 * current min or max (unless we already did so above).
1121 */
1122 if (probe == 0 && sslot.nvalues > 2)
1124 vardata,
1125 sslot.staop,
1126 collation,
1127 &sslot.values[0],
1128 NULL);
1129 else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
1131 vardata,
1132 sslot.staop,
1133 collation,
1134 NULL,
1135 &sslot.values[probe]);
1136
1137 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
1138 collation,
1139 sslot.values[probe],
1140 constval));
1141 if (isgt)
1142 ltcmp = !ltcmp;
1143 if (ltcmp)
1144 lobound = probe + 1;
1145 else
1146 hibound = probe;
1147 }
1148
1149 if (lobound <= 0)
1150 {
1151 /*
1152 * Constant is below lower histogram boundary. More
1153 * precisely, we have found that no entry in the histogram
1154 * satisfies the inequality clause (if !isgt) or they all do
1155 * (if isgt). We estimate that that's true of the entire
1156 * table, so set histfrac to 0.0 (which we'll flip to 1.0
1157 * below, if isgt).
1158 */
1159 histfrac = 0.0;
1160 }
1161 else if (lobound >= sslot.nvalues)
1162 {
1163 /*
1164 * Inverse case: constant is above upper histogram boundary.
1165 */
1166 histfrac = 1.0;
1167 }
1168 else
1169 {
1170 /* We have values[i-1] <= constant <= values[i]. */
1171 int i = lobound;
1172 double eq_selec = 0;
1173 double val,
1174 high,
1175 low;
1176 double binfrac;
1177
1178 /*
1179 * In the cases where we'll need it below, obtain an estimate
1180 * of the selectivity of "x = constval". We use a calculation
1181 * similar to what var_eq_const() does for a non-MCV constant,
1182 * ie, estimate that all distinct non-MCV values occur equally
1183 * often. But multiplication by "1.0 - sumcommon - nullfrac"
1184 * will be done by our caller, so we shouldn't do that here.
1185 * Therefore we can't try to clamp the estimate by reference
1186 * to the least common MCV; the result would be too small.
1187 *
1188 * Note: since this is effectively assuming that constval
1189 * isn't an MCV, it's logically dubious if constval in fact is
1190 * one. But we have to apply *some* correction for equality,
1191 * and anyway we cannot tell if constval is an MCV, since we
1192 * don't have a suitable equality operator at hand.
1193 */
1194 if (i == 1 || isgt == iseq)
1195 {
1196 double otherdistinct;
1197 bool isdefault;
1198 AttStatsSlot mcvslot;
1199
1200 /* Get estimated number of distinct values */
1201 otherdistinct = get_variable_numdistinct(vardata,
1202 &isdefault);
1203
1204 /* Subtract off the number of known MCVs */
1205 if (get_attstatsslot(&mcvslot, vardata->statsTuple,
1206 STATISTIC_KIND_MCV, InvalidOid,
1208 {
1209 otherdistinct -= mcvslot.nnumbers;
1210 free_attstatsslot(&mcvslot);
1211 }
1212
1213 /* If result doesn't seem sane, leave eq_selec at 0 */
1214 if (otherdistinct > 1)
1215 eq_selec = 1.0 / otherdistinct;
1216 }
1217
1218 /*
1219 * Convert the constant and the two nearest bin boundary
1220 * values to a uniform comparison scale, and do a linear
1221 * interpolation within this bin.
1222 */
1223 if (convert_to_scalar(constval, consttype, collation,
1224 &val,
1225 sslot.values[i - 1], sslot.values[i],
1226 vardata->vartype,
1227 &low, &high))
1228 {
1229 if (high <= low)
1230 {
1231 /* cope if bin boundaries appear identical */
1232 binfrac = 0.5;
1233 }
1234 else if (val <= low)
1235 binfrac = 0.0;
1236 else if (val >= high)
1237 binfrac = 1.0;
1238 else
1239 {
1240 binfrac = (val - low) / (high - low);
1241
1242 /*
1243 * Watch out for the possibility that we got a NaN or
1244 * Infinity from the division. This can happen
1245 * despite the previous checks, if for example "low"
1246 * is -Infinity.
1247 */
1248 if (isnan(binfrac) ||
1249 binfrac < 0.0 || binfrac > 1.0)
1250 binfrac = 0.5;
1251 }
1252 }
1253 else
1254 {
1255 /*
1256 * Ideally we'd produce an error here, on the grounds that
1257 * the given operator shouldn't have scalarXXsel
1258 * registered as its selectivity func unless we can deal
1259 * with its operand types. But currently, all manner of
1260 * stuff is invoking scalarXXsel, so give a default
1261 * estimate until that can be fixed.
1262 */
1263 binfrac = 0.5;
1264 }
1265
1266 /*
1267 * Now, compute the overall selectivity across the values
1268 * represented by the histogram. We have i-1 full bins and
1269 * binfrac partial bin below the constant.
1270 */
1271 histfrac = (double) (i - 1) + binfrac;
1272 histfrac /= (double) (sslot.nvalues - 1);
1273
1274 /*
1275 * At this point, histfrac is an estimate of the fraction of
1276 * the population represented by the histogram that satisfies
1277 * "x <= constval". Somewhat remarkably, this statement is
1278 * true regardless of which operator we were doing the probes
1279 * with, so long as convert_to_scalar() delivers reasonable
1280 * results. If the probe constant is equal to some histogram
1281 * entry, we would have considered the bin to the left of that
1282 * entry if probing with "<" or ">=", or the bin to the right
1283 * if probing with "<=" or ">"; but binfrac would have come
1284 * out as 1.0 in the first case and 0.0 in the second, leading
1285 * to the same histfrac in either case. For probe constants
1286 * between histogram entries, we find the same bin and get the
1287 * same estimate with any operator.
1288 *
1289 * The fact that the estimate corresponds to "x <= constval"
1290 * and not "x < constval" is because of the way that ANALYZE
1291 * constructs the histogram: each entry is, effectively, the
1292 * rightmost value in its sample bucket. So selectivity
1293 * values that are exact multiples of 1/(histogram_size-1)
1294 * should be understood as estimates including a histogram
1295 * entry plus everything to its left.
1296 *
1297 * However, that breaks down for the first histogram entry,
1298 * which necessarily is the leftmost value in its sample
1299 * bucket. That means the first histogram bin is slightly
1300 * narrower than the rest, by an amount equal to eq_selec.
1301 * Another way to say that is that we want "x <= leftmost" to
1302 * be estimated as eq_selec not zero. So, if we're dealing
1303 * with the first bin (i==1), rescale to make that true while
1304 * adjusting the rest of that bin linearly.
1305 */
1306 if (i == 1)
1307 histfrac += eq_selec * (1.0 - binfrac);
1308
1309 /*
1310 * "x <= constval" is good if we want an estimate for "<=" or
1311 * ">", but if we are estimating for "<" or ">=", we now need
1312 * to decrease the estimate by eq_selec.
1313 */
1314 if (isgt == iseq)
1315 histfrac -= eq_selec;
1316 }
1317
1318 /*
1319 * Now the estimate is finished for "<" and "<=" cases. If we are
1320 * estimating for ">" or ">=", flip it.
1321 */
1322 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
1323
1324 /*
1325 * The histogram boundaries are only approximate to begin with,
1326 * and may well be out of date anyway. Therefore, don't believe
1327 * extremely small or large selectivity estimates --- unless we
1328 * got actual current endpoint values from the table, in which
1329 * case just do the usual sanity clamp. Somewhat arbitrarily, we
1330 * set the cutoff for other cases at a hundredth of the histogram
1331 * resolution.
1332 */
1333 if (have_end)
1334 CLAMP_PROBABILITY(hist_selec);
1335 else
1336 {
1337 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1338
1339 if (hist_selec < cutoff)
1340 hist_selec = cutoff;
1341 else if (hist_selec > 1.0 - cutoff)
1342 hist_selec = 1.0 - cutoff;
1343 }
1344 }
1345 else if (sslot.nvalues > 1)
1346 {
1347 /*
1348 * If we get here, we have a histogram but it's not sorted the way
1349 * we want. Do a brute-force search to see how many of the
1350 * entries satisfy the comparison condition, and take that
1351 * fraction as our estimate. (This is identical to the inner loop
1352 * of histogram_selectivity; maybe share code?)
1353 */
1354 LOCAL_FCINFO(fcinfo, 2);
1355 int nmatch = 0;
1356
1357 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
1358 NULL, NULL);
1359 fcinfo->args[0].isnull = false;
1360 fcinfo->args[1].isnull = false;
1361 fcinfo->args[1].value = constval;
1362 for (int i = 0; i < sslot.nvalues; i++)
1363 {
1364 Datum fresult;
1365
1366 fcinfo->args[0].value = sslot.values[i];
1367 fcinfo->isnull = false;
1368 fresult = FunctionCallInvoke(fcinfo);
1369 if (!fcinfo->isnull && DatumGetBool(fresult))
1370 nmatch++;
1371 }
1372 hist_selec = ((double) nmatch) / ((double) sslot.nvalues);
1373
1374 /*
1375 * As above, clamp to a hundredth of the histogram resolution.
1376 * This case is surely even less trustworthy than the normal one,
1377 * so we shouldn't believe exact 0 or 1 selectivity. (Maybe the
1378 * clamp should be more restrictive in this case?)
1379 */
1380 {
1381 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1382
1383 if (hist_selec < cutoff)
1384 hist_selec = cutoff;
1385 else if (hist_selec > 1.0 - cutoff)
1386 hist_selec = 1.0 - cutoff;
1387 }
1388 }
1389
1390 free_attstatsslot(&sslot);
1391 }
1392
1393 return hist_selec;
1394}
1395
1396/*
1397 * Common wrapper function for the selectivity estimators that simply
1398 * invoke scalarineqsel().
1399 */
1400static Datum
1402{
1404 Oid operator = PG_GETARG_OID(1);
1405 List *args = (List *) PG_GETARG_POINTER(2);
1406 int varRelid = PG_GETARG_INT32(3);
1407 Oid collation = PG_GET_COLLATION();
1408 VariableStatData vardata;
1409 Node *other;
1410 bool varonleft;
1411 Datum constval;
1412 Oid consttype;
1413 double selec;
1414
1415 /*
1416 * If expression is not variable op something or something op variable,
1417 * then punt and return a default estimate.
1418 */
1419 if (!get_restriction_variable(root, args, varRelid,
1420 &vardata, &other, &varonleft))
1422
1423 /*
1424 * Can't do anything useful if the something is not a constant, either.
1425 */
1426 if (!IsA(other, Const))
1427 {
1428 ReleaseVariableStats(vardata);
1430 }
1431
1432 /*
1433 * If the constant is NULL, assume operator is strict and return zero, ie,
1434 * operator will never return TRUE.
1435 */
1436 if (((Const *) other)->constisnull)
1437 {
1438 ReleaseVariableStats(vardata);
1439 PG_RETURN_FLOAT8(0.0);
1440 }
1441 constval = ((Const *) other)->constvalue;
1442 consttype = ((Const *) other)->consttype;
1443
1444 /*
1445 * Force the var to be on the left to simplify logic in scalarineqsel.
1446 */
1447 if (!varonleft)
1448 {
1449 operator = get_commutator(operator);
1450 if (!operator)
1451 {
1452 /* Use default selectivity (should we raise an error instead?) */
1453 ReleaseVariableStats(vardata);
1455 }
1456 isgt = !isgt;
1457 }
1458
1459 /* The rest of the work is done by scalarineqsel(). */
1460 selec = scalarineqsel(root, operator, isgt, iseq, collation,
1461 &vardata, constval, consttype);
1462
1463 ReleaseVariableStats(vardata);
1464
1465 PG_RETURN_FLOAT8((float8) selec);
1466}
1467
1468/*
1469 * scalarltsel - Selectivity of "<" for scalars.
1470 */
1471Datum
1473{
1474 return scalarineqsel_wrapper(fcinfo, false, false);
1475}
1476
1477/*
1478 * scalarlesel - Selectivity of "<=" for scalars.
1479 */
1480Datum
1482{
1483 return scalarineqsel_wrapper(fcinfo, false, true);
1484}
1485
1486/*
1487 * scalargtsel - Selectivity of ">" for scalars.
1488 */
1489Datum
1491{
1492 return scalarineqsel_wrapper(fcinfo, true, false);
1493}
1494
1495/*
1496 * scalargesel - Selectivity of ">=" for scalars.
1497 */
1498Datum
1500{
1501 return scalarineqsel_wrapper(fcinfo, true, true);
1502}
1503
1504/*
1505 * boolvarsel - Selectivity of Boolean variable.
1506 *
1507 * This can actually be called on any boolean-valued expression. If it
1508 * involves only Vars of the specified relation, and if there are statistics
1509 * about the Var or expression (the latter is possible if it's indexed) then
1510 * we'll produce a real estimate; otherwise it's just a default.
1511 */
1514{
1515 VariableStatData vardata;
1516 double selec;
1517
1518 examine_variable(root, arg, varRelid, &vardata);
1519 if (HeapTupleIsValid(vardata.statsTuple))
1520 {
1521 /*
1522 * A boolean variable V is equivalent to the clause V = 't', so we
1523 * compute the selectivity as if that is what we have.
1524 */
1525 selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1526 BoolGetDatum(true), false, true, false);
1527 }
1528 else
1529 {
1530 /* Otherwise, the default estimate is 0.5 */
1531 selec = 0.5;
1532 }
1533 ReleaseVariableStats(vardata);
1534 return selec;
1535}
1536
1537/*
1538 * booltestsel - Selectivity of BooleanTest Node.
1539 */
1542 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1543{
1544 VariableStatData vardata;
1545 double selec;
1546
1547 examine_variable(root, arg, varRelid, &vardata);
1548
1549 if (HeapTupleIsValid(vardata.statsTuple))
1550 {
1551 Form_pg_statistic stats;
1552 double freq_null;
1553 AttStatsSlot sslot;
1554
1555 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1556 freq_null = stats->stanullfrac;
1557
1558 if (get_attstatsslot(&sslot, vardata.statsTuple,
1559 STATISTIC_KIND_MCV, InvalidOid,
1561 && sslot.nnumbers > 0)
1562 {
1563 double freq_true;
1564 double freq_false;
1565
1566 /*
1567 * Get first MCV frequency and derive frequency for true.
1568 */
1569 if (DatumGetBool(sslot.values[0]))
1570 freq_true = sslot.numbers[0];
1571 else
1572 freq_true = 1.0 - sslot.numbers[0] - freq_null;
1573
1574 /*
1575 * Next derive frequency for false. Then use these as appropriate
1576 * to derive frequency for each case.
1577 */
1578 freq_false = 1.0 - freq_true - freq_null;
1579
1580 switch (booltesttype)
1581 {
1582 case IS_UNKNOWN:
1583 /* select only NULL values */
1584 selec = freq_null;
1585 break;
1586 case IS_NOT_UNKNOWN:
1587 /* select non-NULL values */
1588 selec = 1.0 - freq_null;
1589 break;
1590 case IS_TRUE:
1591 /* select only TRUE values */
1592 selec = freq_true;
1593 break;
1594 case IS_NOT_TRUE:
1595 /* select non-TRUE values */
1596 selec = 1.0 - freq_true;
1597 break;
1598 case IS_FALSE:
1599 /* select only FALSE values */
1600 selec = freq_false;
1601 break;
1602 case IS_NOT_FALSE:
1603 /* select non-FALSE values */
1604 selec = 1.0 - freq_false;
1605 break;
1606 default:
1607 elog(ERROR, "unrecognized booltesttype: %d",
1608 (int) booltesttype);
1609 selec = 0.0; /* Keep compiler quiet */
1610 break;
1611 }
1612
1613 free_attstatsslot(&sslot);
1614 }
1615 else
1616 {
1617 /*
1618 * No most-common-value info available. Still have null fraction
1619 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1620 * for null fraction and assume a 50-50 split of TRUE and FALSE.
1621 */
1622 switch (booltesttype)
1623 {
1624 case IS_UNKNOWN:
1625 /* select only NULL values */
1626 selec = freq_null;
1627 break;
1628 case IS_NOT_UNKNOWN:
1629 /* select non-NULL values */
1630 selec = 1.0 - freq_null;
1631 break;
1632 case IS_TRUE:
1633 case IS_FALSE:
1634 /* Assume we select half of the non-NULL values */
1635 selec = (1.0 - freq_null) / 2.0;
1636 break;
1637 case IS_NOT_TRUE:
1638 case IS_NOT_FALSE:
1639 /* Assume we select NULLs plus half of the non-NULLs */
1640 /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1641 selec = (freq_null + 1.0) / 2.0;
1642 break;
1643 default:
1644 elog(ERROR, "unrecognized booltesttype: %d",
1645 (int) booltesttype);
1646 selec = 0.0; /* Keep compiler quiet */
1647 break;
1648 }
1649 }
1650 }
1651 else
1652 {
1653 /*
1654 * If we can't get variable statistics for the argument, perhaps
1655 * clause_selectivity can do something with it. We ignore the
1656 * possibility of a NULL value when using clause_selectivity, and just
1657 * assume the value is either TRUE or FALSE.
1658 */
1659 switch (booltesttype)
1660 {
1661 case IS_UNKNOWN:
1662 selec = DEFAULT_UNK_SEL;
1663 break;
1664 case IS_NOT_UNKNOWN:
1665 selec = DEFAULT_NOT_UNK_SEL;
1666 break;
1667 case IS_TRUE:
1668 case IS_NOT_FALSE:
1669 selec = (double) clause_selectivity(root, arg,
1670 varRelid,
1671 jointype, sjinfo);
1672 break;
1673 case IS_FALSE:
1674 case IS_NOT_TRUE:
1675 selec = 1.0 - (double) clause_selectivity(root, arg,
1676 varRelid,
1677 jointype, sjinfo);
1678 break;
1679 default:
1680 elog(ERROR, "unrecognized booltesttype: %d",
1681 (int) booltesttype);
1682 selec = 0.0; /* Keep compiler quiet */
1683 break;
1684 }
1685 }
1686
1687 ReleaseVariableStats(vardata);
1688
1689 /* result should be in range, but make sure... */
1690 CLAMP_PROBABILITY(selec);
1691
1692 return (Selectivity) selec;
1693}
1694
1695/*
1696 * nulltestsel - Selectivity of NullTest Node.
1697 */
1700 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1701{
1702 VariableStatData vardata;
1703 double selec;
1704
1705 examine_variable(root, arg, varRelid, &vardata);
1706
1707 if (HeapTupleIsValid(vardata.statsTuple))
1708 {
1709 Form_pg_statistic stats;
1710 double freq_null;
1711
1712 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1713 freq_null = stats->stanullfrac;
1714
1715 switch (nulltesttype)
1716 {
1717 case IS_NULL:
1718
1719 /*
1720 * Use freq_null directly.
1721 */
1722 selec = freq_null;
1723 break;
1724 case IS_NOT_NULL:
1725
1726 /*
1727 * Select not unknown (not null) values. Calculate from
1728 * freq_null.
1729 */
1730 selec = 1.0 - freq_null;
1731 break;
1732 default:
1733 elog(ERROR, "unrecognized nulltesttype: %d",
1734 (int) nulltesttype);
1735 return (Selectivity) 0; /* keep compiler quiet */
1736 }
1737 }
1738 else if (vardata.var && IsA(vardata.var, Var) &&
1739 ((Var *) vardata.var)->varattno < 0)
1740 {
1741 /*
1742 * There are no stats for system columns, but we know they are never
1743 * NULL.
1744 */
1745 selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
1746 }
1747 else
1748 {
1749 /*
1750 * No ANALYZE stats available, so make a guess
1751 */
1752 switch (nulltesttype)
1753 {
1754 case IS_NULL:
1755 selec = DEFAULT_UNK_SEL;
1756 break;
1757 case IS_NOT_NULL:
1758 selec = DEFAULT_NOT_UNK_SEL;
1759 break;
1760 default:
1761 elog(ERROR, "unrecognized nulltesttype: %d",
1762 (int) nulltesttype);
1763 return (Selectivity) 0; /* keep compiler quiet */
1764 }
1765 }
1766
1767 ReleaseVariableStats(vardata);
1768
1769 /* result should be in range, but make sure... */
1770 CLAMP_PROBABILITY(selec);
1771
1772 return (Selectivity) selec;
1773}
1774
1775/*
1776 * strip_array_coercion - strip binary-compatible relabeling from an array expr
1777 *
1778 * For array values, the parser normally generates ArrayCoerceExpr conversions,
1779 * but it seems possible that RelabelType might show up. Also, the planner
1780 * is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1781 * so we need to be ready to deal with more than one level.
1782 */
1783static Node *
1785{
1786 for (;;)
1787 {
1788 if (node && IsA(node, ArrayCoerceExpr))
1789 {
1790 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
1791
1792 /*
1793 * If the per-element expression is just a RelabelType on top of
1794 * CaseTestExpr, then we know it's a binary-compatible relabeling.
1795 */
1796 if (IsA(acoerce->elemexpr, RelabelType) &&
1797 IsA(((RelabelType *) acoerce->elemexpr)->arg, CaseTestExpr))
1798 node = (Node *) acoerce->arg;
1799 else
1800 break;
1801 }
1802 else if (node && IsA(node, RelabelType))
1803 {
1804 /* We don't really expect this case, but may as well cope */
1805 node = (Node *) ((RelabelType *) node)->arg;
1806 }
1807 else
1808 break;
1809 }
1810 return node;
1811}
1812
1813/*
1814 * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1815 */
1818 ScalarArrayOpExpr *clause,
1819 bool is_join_clause,
1820 int varRelid,
1821 JoinType jointype,
1822 SpecialJoinInfo *sjinfo)
1823{
1824 Oid operator = clause->opno;
1825 bool useOr = clause->useOr;
1826 bool isEquality = false;
1827 bool isInequality = false;
1828 Node *leftop;
1829 Node *rightop;
1830 Oid nominal_element_type;
1831 Oid nominal_element_collation;
1832 TypeCacheEntry *typentry;
1833 RegProcedure oprsel;
1834 FmgrInfo oprselproc;
1836 Selectivity s1disjoint;
1837
1838 /* First, deconstruct the expression */
1839 Assert(list_length(clause->args) == 2);
1840 leftop = (Node *) linitial(clause->args);
1841 rightop = (Node *) lsecond(clause->args);
1842
1843 /* aggressively reduce both sides to constants */
1844 leftop = estimate_expression_value(root, leftop);
1845 rightop = estimate_expression_value(root, rightop);
1846
1847 /* get nominal (after relabeling) element type of rightop */
1848 nominal_element_type = get_base_element_type(exprType(rightop));
1849 if (!OidIsValid(nominal_element_type))
1850 return (Selectivity) 0.5; /* probably shouldn't happen */
1851 /* get nominal collation, too, for generating constants */
1852 nominal_element_collation = exprCollation(rightop);
1853
1854 /* look through any binary-compatible relabeling of rightop */
1855 rightop = strip_array_coercion(rightop);
1856
1857 /*
1858 * Detect whether the operator is the default equality or inequality
1859 * operator of the array element type.
1860 */
1861 typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1862 if (OidIsValid(typentry->eq_opr))
1863 {
1864 if (operator == typentry->eq_opr)
1865 isEquality = true;
1866 else if (get_negator(operator) == typentry->eq_opr)
1867 isInequality = true;
1868 }
1869
1870 /*
1871 * If it is equality or inequality, we might be able to estimate this as a
1872 * form of array containment; for instance "const = ANY(column)" can be
1873 * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1874 * that, and returns the selectivity estimate if successful, or -1 if not.
1875 */
1876 if ((isEquality || isInequality) && !is_join_clause)
1877 {
1878 s1 = scalararraysel_containment(root, leftop, rightop,
1879 nominal_element_type,
1880 isEquality, useOr, varRelid);
1881 if (s1 >= 0.0)
1882 return s1;
1883 }
1884
1885 /*
1886 * Look up the underlying operator's selectivity estimator. Punt if it
1887 * hasn't got one.
1888 */
1889 if (is_join_clause)
1890 oprsel = get_oprjoin(operator);
1891 else
1892 oprsel = get_oprrest(operator);
1893 if (!oprsel)
1894 return (Selectivity) 0.5;
1895 fmgr_info(oprsel, &oprselproc);
1896
1897 /*
1898 * In the array-containment check above, we must only believe that an
1899 * operator is equality or inequality if it is the default btree equality
1900 * operator (or its negator) for the element type, since those are the
1901 * operators that array containment will use. But in what follows, we can
1902 * be a little laxer, and also believe that any operators using eqsel() or
1903 * neqsel() as selectivity estimator act like equality or inequality.
1904 */
1905 if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1906 isEquality = true;
1907 else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1908 isInequality = true;
1909
1910 /*
1911 * We consider three cases:
1912 *
1913 * 1. rightop is an Array constant: deconstruct the array, apply the
1914 * operator's selectivity function for each array element, and merge the
1915 * results in the same way that clausesel.c does for AND/OR combinations.
1916 *
1917 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1918 * function for each element of the ARRAY[] construct, and merge.
1919 *
1920 * 3. otherwise, make a guess ...
1921 */
1922 if (rightop && IsA(rightop, Const))
1923 {
1924 Datum arraydatum = ((Const *) rightop)->constvalue;
1925 bool arrayisnull = ((Const *) rightop)->constisnull;
1926 ArrayType *arrayval;
1927 int16 elmlen;
1928 bool elmbyval;
1929 char elmalign;
1930 int num_elems;
1931 Datum *elem_values;
1932 bool *elem_nulls;
1933 int i;
1934
1935 if (arrayisnull) /* qual can't succeed if null array */
1936 return (Selectivity) 0.0;
1937 arrayval = DatumGetArrayTypeP(arraydatum);
1939 &elmlen, &elmbyval, &elmalign);
1940 deconstruct_array(arrayval,
1941 ARR_ELEMTYPE(arrayval),
1942 elmlen, elmbyval, elmalign,
1943 &elem_values, &elem_nulls, &num_elems);
1944
1945 /*
1946 * For generic operators, we assume the probability of success is
1947 * independent for each array element. But for "= ANY" or "<> ALL",
1948 * if the array elements are distinct (which'd typically be the case)
1949 * then the probabilities are disjoint, and we should just sum them.
1950 *
1951 * If we were being really tense we would try to confirm that the
1952 * elements are all distinct, but that would be expensive and it
1953 * doesn't seem to be worth the cycles; it would amount to penalizing
1954 * well-written queries in favor of poorly-written ones. However, we
1955 * do protect ourselves a little bit by checking whether the
1956 * disjointness assumption leads to an impossible (out of range)
1957 * probability; if so, we fall back to the normal calculation.
1958 */
1959 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1960
1961 for (i = 0; i < num_elems; i++)
1962 {
1963 List *args;
1965
1966 args = list_make2(leftop,
1967 makeConst(nominal_element_type,
1968 -1,
1969 nominal_element_collation,
1970 elmlen,
1971 elem_values[i],
1972 elem_nulls[i],
1973 elmbyval));
1974 if (is_join_clause)
1975 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1976 clause->inputcollid,
1978 ObjectIdGetDatum(operator),
1980 Int16GetDatum(jointype),
1981 PointerGetDatum(sjinfo)));
1982 else
1983 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1984 clause->inputcollid,
1986 ObjectIdGetDatum(operator),
1988 Int32GetDatum(varRelid)));
1989
1990 if (useOr)
1991 {
1992 s1 = s1 + s2 - s1 * s2;
1993 if (isEquality)
1994 s1disjoint += s2;
1995 }
1996 else
1997 {
1998 s1 = s1 * s2;
1999 if (isInequality)
2000 s1disjoint += s2 - 1.0;
2001 }
2002 }
2003
2004 /* accept disjoint-probability estimate if in range */
2005 if ((useOr ? isEquality : isInequality) &&
2006 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2007 s1 = s1disjoint;
2008 }
2009 else if (rightop && IsA(rightop, ArrayExpr) &&
2010 !((ArrayExpr *) rightop)->multidims)
2011 {
2012 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2013 int16 elmlen;
2014 bool elmbyval;
2015 ListCell *l;
2016
2017 get_typlenbyval(arrayexpr->element_typeid,
2018 &elmlen, &elmbyval);
2019
2020 /*
2021 * We use the assumption of disjoint probabilities here too, although
2022 * the odds of equal array elements are rather higher if the elements
2023 * are not all constants (which they won't be, else constant folding
2024 * would have reduced the ArrayExpr to a Const). In this path it's
2025 * critical to have the sanity check on the s1disjoint estimate.
2026 */
2027 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2028
2029 foreach(l, arrayexpr->elements)
2030 {
2031 Node *elem = (Node *) lfirst(l);
2032 List *args;
2034
2035 /*
2036 * Theoretically, if elem isn't of nominal_element_type we should
2037 * insert a RelabelType, but it seems unlikely that any operator
2038 * estimation function would really care ...
2039 */
2040 args = list_make2(leftop, elem);
2041 if (is_join_clause)
2042 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2043 clause->inputcollid,
2045 ObjectIdGetDatum(operator),
2047 Int16GetDatum(jointype),
2048 PointerGetDatum(sjinfo)));
2049 else
2050 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2051 clause->inputcollid,
2053 ObjectIdGetDatum(operator),
2055 Int32GetDatum(varRelid)));
2056
2057 if (useOr)
2058 {
2059 s1 = s1 + s2 - s1 * s2;
2060 if (isEquality)
2061 s1disjoint += s2;
2062 }
2063 else
2064 {
2065 s1 = s1 * s2;
2066 if (isInequality)
2067 s1disjoint += s2 - 1.0;
2068 }
2069 }
2070
2071 /* accept disjoint-probability estimate if in range */
2072 if ((useOr ? isEquality : isInequality) &&
2073 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2074 s1 = s1disjoint;
2075 }
2076 else
2077 {
2078 CaseTestExpr *dummyexpr;
2079 List *args;
2081 int i;
2082
2083 /*
2084 * We need a dummy rightop to pass to the operator selectivity
2085 * routine. It can be pretty much anything that doesn't look like a
2086 * constant; CaseTestExpr is a convenient choice.
2087 */
2088 dummyexpr = makeNode(CaseTestExpr);
2089 dummyexpr->typeId = nominal_element_type;
2090 dummyexpr->typeMod = -1;
2091 dummyexpr->collation = clause->inputcollid;
2092 args = list_make2(leftop, dummyexpr);
2093 if (is_join_clause)
2094 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2095 clause->inputcollid,
2097 ObjectIdGetDatum(operator),
2099 Int16GetDatum(jointype),
2100 PointerGetDatum(sjinfo)));
2101 else
2102 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2103 clause->inputcollid,
2105 ObjectIdGetDatum(operator),
2107 Int32GetDatum(varRelid)));
2108 s1 = useOr ? 0.0 : 1.0;
2109
2110 /*
2111 * Arbitrarily assume 10 elements in the eventual array value (see
2112 * also estimate_array_length). We don't risk an assumption of
2113 * disjoint probabilities here.
2114 */
2115 for (i = 0; i < 10; i++)
2116 {
2117 if (useOr)
2118 s1 = s1 + s2 - s1 * s2;
2119 else
2120 s1 = s1 * s2;
2121 }
2122 }
2123
2124 /* result should be in range, but make sure... */
2126
2127 return s1;
2128}
2129
2130/*
2131 * Estimate number of elements in the array yielded by an expression.
2132 *
2133 * Note: the result is integral, but we use "double" to avoid overflow
2134 * concerns. Most callers will use it in double-type expressions anyway.
2135 *
2136 * Note: in some code paths root can be passed as NULL, resulting in
2137 * slightly worse estimates.
2138 */
2139double
2141{
2142 /* look through any binary-compatible relabeling of arrayexpr */
2143 arrayexpr = strip_array_coercion(arrayexpr);
2144
2145 if (arrayexpr && IsA(arrayexpr, Const))
2146 {
2147 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2148 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2149 ArrayType *arrayval;
2150
2151 if (arrayisnull)
2152 return 0;
2153 arrayval = DatumGetArrayTypeP(arraydatum);
2154 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2155 }
2156 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2157 !((ArrayExpr *) arrayexpr)->multidims)
2158 {
2159 return list_length(((ArrayExpr *) arrayexpr)->elements);
2160 }
2161 else if (arrayexpr && root)
2162 {
2163 /* See if we can find any statistics about it */
2164 VariableStatData vardata;
2165 AttStatsSlot sslot;
2166 double nelem = 0;
2167
2168 examine_variable(root, arrayexpr, 0, &vardata);
2169 if (HeapTupleIsValid(vardata.statsTuple))
2170 {
2171 /*
2172 * Found stats, so use the average element count, which is stored
2173 * in the last stanumbers element of the DECHIST statistics.
2174 * Actually that is the average count of *distinct* elements;
2175 * perhaps we should scale it up somewhat?
2176 */
2177 if (get_attstatsslot(&sslot, vardata.statsTuple,
2178 STATISTIC_KIND_DECHIST, InvalidOid,
2180 {
2181 if (sslot.nnumbers > 0)
2182 nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2183 free_attstatsslot(&sslot);
2184 }
2185 }
2186 ReleaseVariableStats(vardata);
2187
2188 if (nelem > 0)
2189 return nelem;
2190 }
2191
2192 /* Else use a default guess --- this should match scalararraysel */
2193 return 10;
2194}
2195
2196/*
2197 * rowcomparesel - Selectivity of RowCompareExpr Node.
2198 *
2199 * We estimate RowCompare selectivity by considering just the first (high
2200 * order) columns, which makes it equivalent to an ordinary OpExpr. While
2201 * this estimate could be refined by considering additional columns, it
2202 * seems unlikely that we could do a lot better without multi-column
2203 * statistics.
2204 */
2207 RowCompareExpr *clause,
2208 int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
2209{
2211 Oid opno = linitial_oid(clause->opnos);
2212 Oid inputcollid = linitial_oid(clause->inputcollids);
2213 List *opargs;
2214 bool is_join_clause;
2215
2216 /* Build equivalent arg list for single operator */
2217 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2218
2219 /*
2220 * Decide if it's a join clause. This should match clausesel.c's
2221 * treat_as_join_clause(), except that we intentionally consider only the
2222 * leading columns and not the rest of the clause.
2223 */
2224 if (varRelid != 0)
2225 {
2226 /*
2227 * Caller is forcing restriction mode (eg, because we are examining an
2228 * inner indexscan qual).
2229 */
2230 is_join_clause = false;
2231 }
2232 else if (sjinfo == NULL)
2233 {
2234 /*
2235 * It must be a restriction clause, since it's being evaluated at a
2236 * scan node.
2237 */
2238 is_join_clause = false;
2239 }
2240 else
2241 {
2242 /*
2243 * Otherwise, it's a join if there's more than one base relation used.
2244 */
2245 is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2246 }
2247
2248 if (is_join_clause)
2249 {
2250 /* Estimate selectivity for a join clause. */
2251 s1 = join_selectivity(root, opno,
2252 opargs,
2253 inputcollid,
2254 jointype,
2255 sjinfo);
2256 }
2257 else
2258 {
2259 /* Estimate selectivity for a restriction clause. */
2261 opargs,
2262 inputcollid,
2263 varRelid);
2264 }
2265
2266 return s1;
2267}
2268
2269/*
2270 * eqjoinsel - Join selectivity of "="
2271 */
2272Datum
2274{
2276 Oid operator = PG_GETARG_OID(1);
2277 List *args = (List *) PG_GETARG_POINTER(2);
2278
2279#ifdef NOT_USED
2280 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2281#endif
2283 Oid collation = PG_GET_COLLATION();
2284 double selec;
2285 double selec_inner;
2286 VariableStatData vardata1;
2287 VariableStatData vardata2;
2288 double nd1;
2289 double nd2;
2290 bool isdefault1;
2291 bool isdefault2;
2292 Oid opfuncoid;
2293 AttStatsSlot sslot1;
2294 AttStatsSlot sslot2;
2295 Form_pg_statistic stats1 = NULL;
2296 Form_pg_statistic stats2 = NULL;
2297 bool have_mcvs1 = false;
2298 bool have_mcvs2 = false;
2299 bool get_mcv_stats;
2300 bool join_is_reversed;
2301 RelOptInfo *inner_rel;
2302
2303 get_join_variables(root, args, sjinfo,
2304 &vardata1, &vardata2, &join_is_reversed);
2305
2306 nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2307 nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2308
2309 opfuncoid = get_opcode(operator);
2310
2311 memset(&sslot1, 0, sizeof(sslot1));
2312 memset(&sslot2, 0, sizeof(sslot2));
2313
2314 /*
2315 * There is no use in fetching one side's MCVs if we lack MCVs for the
2316 * other side, so do a quick check to verify that both stats exist.
2317 */
2318 get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
2319 HeapTupleIsValid(vardata2.statsTuple) &&
2320 get_attstatsslot(&sslot1, vardata1.statsTuple,
2321 STATISTIC_KIND_MCV, InvalidOid,
2322 0) &&
2323 get_attstatsslot(&sslot2, vardata2.statsTuple,
2324 STATISTIC_KIND_MCV, InvalidOid,
2325 0));
2326
2327 if (HeapTupleIsValid(vardata1.statsTuple))
2328 {
2329 /* note we allow use of nullfrac regardless of security check */
2330 stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2331 if (get_mcv_stats &&
2332 statistic_proc_security_check(&vardata1, opfuncoid))
2333 have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2334 STATISTIC_KIND_MCV, InvalidOid,
2336 }
2337
2338 if (HeapTupleIsValid(vardata2.statsTuple))
2339 {
2340 /* note we allow use of nullfrac regardless of security check */
2341 stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2342 if (get_mcv_stats &&
2343 statistic_proc_security_check(&vardata2, opfuncoid))
2344 have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2345 STATISTIC_KIND_MCV, InvalidOid,
2347 }
2348
2349 /* We need to compute the inner-join selectivity in all cases */
2350 selec_inner = eqjoinsel_inner(opfuncoid, collation,
2351 &vardata1, &vardata2,
2352 nd1, nd2,
2353 isdefault1, isdefault2,
2354 &sslot1, &sslot2,
2355 stats1, stats2,
2356 have_mcvs1, have_mcvs2);
2357
2358 switch (sjinfo->jointype)
2359 {
2360 case JOIN_INNER:
2361 case JOIN_LEFT:
2362 case JOIN_FULL:
2363 selec = selec_inner;
2364 break;
2365 case JOIN_SEMI:
2366 case JOIN_ANTI:
2367
2368 /*
2369 * Look up the join's inner relation. min_righthand is sufficient
2370 * information because neither SEMI nor ANTI joins permit any
2371 * reassociation into or out of their RHS, so the righthand will
2372 * always be exactly that set of rels.
2373 */
2374 inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2375
2376 if (!join_is_reversed)
2377 selec = eqjoinsel_semi(opfuncoid, collation,
2378 &vardata1, &vardata2,
2379 nd1, nd2,
2380 isdefault1, isdefault2,
2381 &sslot1, &sslot2,
2382 stats1, stats2,
2383 have_mcvs1, have_mcvs2,
2384 inner_rel);
2385 else
2386 {
2387 Oid commop = get_commutator(operator);
2388 Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2389
2390 selec = eqjoinsel_semi(commopfuncoid, collation,
2391 &vardata2, &vardata1,
2392 nd2, nd1,
2393 isdefault2, isdefault1,
2394 &sslot2, &sslot1,
2395 stats2, stats1,
2396 have_mcvs2, have_mcvs1,
2397 inner_rel);
2398 }
2399
2400 /*
2401 * We should never estimate the output of a semijoin to be more
2402 * rows than we estimate for an inner join with the same input
2403 * rels and join condition; it's obviously impossible for that to
2404 * happen. The former estimate is N1 * Ssemi while the latter is
2405 * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner. Doing
2406 * this is worthwhile because of the shakier estimation rules we
2407 * use in eqjoinsel_semi, particularly in cases where it has to
2408 * punt entirely.
2409 */
2410 selec = Min(selec, inner_rel->rows * selec_inner);
2411 break;
2412 default:
2413 /* other values not expected here */
2414 elog(ERROR, "unrecognized join type: %d",
2415 (int) sjinfo->jointype);
2416 selec = 0; /* keep compiler quiet */
2417 break;
2418 }
2419
2420 free_attstatsslot(&sslot1);
2421 free_attstatsslot(&sslot2);
2422
2423 ReleaseVariableStats(vardata1);
2424 ReleaseVariableStats(vardata2);
2425
2426 CLAMP_PROBABILITY(selec);
2427
2428 PG_RETURN_FLOAT8((float8) selec);
2429}
2430
2431/*
2432 * eqjoinsel_inner --- eqjoinsel for normal inner join
2433 *
2434 * We also use this for LEFT/FULL outer joins; it's not presently clear
2435 * that it's worth trying to distinguish them here.
2436 */
2437static double
2438eqjoinsel_inner(Oid opfuncoid, Oid collation,
2439 VariableStatData *vardata1, VariableStatData *vardata2,
2440 double nd1, double nd2,
2441 bool isdefault1, bool isdefault2,
2442 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2443 Form_pg_statistic stats1, Form_pg_statistic stats2,
2444 bool have_mcvs1, bool have_mcvs2)
2445{
2446 double selec;
2447
2448 if (have_mcvs1 && have_mcvs2)
2449 {
2450 /*
2451 * We have most-common-value lists for both relations. Run through
2452 * the lists to see which MCVs actually join to each other with the
2453 * given operator. This allows us to determine the exact join
2454 * selectivity for the portion of the relations represented by the MCV
2455 * lists. We still have to estimate for the remaining population, but
2456 * in a skewed distribution this gives us a big leg up in accuracy.
2457 * For motivation see the analysis in Y. Ioannidis and S.
2458 * Christodoulakis, "On the propagation of errors in the size of join
2459 * results", Technical Report 1018, Computer Science Dept., University
2460 * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2461 */
2462 LOCAL_FCINFO(fcinfo, 2);
2463 FmgrInfo eqproc;
2464 bool *hasmatch1;
2465 bool *hasmatch2;
2466 double nullfrac1 = stats1->stanullfrac;
2467 double nullfrac2 = stats2->stanullfrac;
2468 double matchprodfreq,
2469 matchfreq1,
2470 matchfreq2,
2471 unmatchfreq1,
2472 unmatchfreq2,
2473 otherfreq1,
2474 otherfreq2,
2475 totalsel1,
2476 totalsel2;
2477 int i,
2478 nmatches;
2479
2480 fmgr_info(opfuncoid, &eqproc);
2481
2482 /*
2483 * Save a few cycles by setting up the fcinfo struct just once. Using
2484 * FunctionCallInvoke directly also avoids failure if the eqproc
2485 * returns NULL, though really equality functions should never do
2486 * that.
2487 */
2488 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2489 NULL, NULL);
2490 fcinfo->args[0].isnull = false;
2491 fcinfo->args[1].isnull = false;
2492
2493 hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2494 hasmatch2 = (bool *) palloc0(sslot2->nvalues * sizeof(bool));
2495
2496 /*
2497 * Note we assume that each MCV will match at most one member of the
2498 * other MCV list. If the operator isn't really equality, there could
2499 * be multiple matches --- but we don't look for them, both for speed
2500 * and because the math wouldn't add up...
2501 */
2502 matchprodfreq = 0.0;
2503 nmatches = 0;
2504 for (i = 0; i < sslot1->nvalues; i++)
2505 {
2506 int j;
2507
2508 fcinfo->args[0].value = sslot1->values[i];
2509
2510 for (j = 0; j < sslot2->nvalues; j++)
2511 {
2512 Datum fresult;
2513
2514 if (hasmatch2[j])
2515 continue;
2516 fcinfo->args[1].value = sslot2->values[j];
2517 fcinfo->isnull = false;
2518 fresult = FunctionCallInvoke(fcinfo);
2519 if (!fcinfo->isnull && DatumGetBool(fresult))
2520 {
2521 hasmatch1[i] = hasmatch2[j] = true;
2522 matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2523 nmatches++;
2524 break;
2525 }
2526 }
2527 }
2528 CLAMP_PROBABILITY(matchprodfreq);
2529 /* Sum up frequencies of matched and unmatched MCVs */
2530 matchfreq1 = unmatchfreq1 = 0.0;
2531 for (i = 0; i < sslot1->nvalues; i++)
2532 {
2533 if (hasmatch1[i])
2534 matchfreq1 += sslot1->numbers[i];
2535 else
2536 unmatchfreq1 += sslot1->numbers[i];
2537 }
2538 CLAMP_PROBABILITY(matchfreq1);
2539 CLAMP_PROBABILITY(unmatchfreq1);
2540 matchfreq2 = unmatchfreq2 = 0.0;
2541 for (i = 0; i < sslot2->nvalues; i++)
2542 {
2543 if (hasmatch2[i])
2544 matchfreq2 += sslot2->numbers[i];
2545 else
2546 unmatchfreq2 += sslot2->numbers[i];
2547 }
2548 CLAMP_PROBABILITY(matchfreq2);
2549 CLAMP_PROBABILITY(unmatchfreq2);
2550 pfree(hasmatch1);
2551 pfree(hasmatch2);
2552
2553 /*
2554 * Compute total frequency of non-null values that are not in the MCV
2555 * lists.
2556 */
2557 otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2558 otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2559 CLAMP_PROBABILITY(otherfreq1);
2560 CLAMP_PROBABILITY(otherfreq2);
2561
2562 /*
2563 * We can estimate the total selectivity from the point of view of
2564 * relation 1 as: the known selectivity for matched MCVs, plus
2565 * unmatched MCVs that are assumed to match against random members of
2566 * relation 2's non-MCV population, plus non-MCV values that are
2567 * assumed to match against random members of relation 2's unmatched
2568 * MCVs plus non-MCV values.
2569 */
2570 totalsel1 = matchprodfreq;
2571 if (nd2 > sslot2->nvalues)
2572 totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2573 if (nd2 > nmatches)
2574 totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2575 (nd2 - nmatches);
2576 /* Same estimate from the point of view of relation 2. */
2577 totalsel2 = matchprodfreq;
2578 if (nd1 > sslot1->nvalues)
2579 totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2580 if (nd1 > nmatches)
2581 totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2582 (nd1 - nmatches);
2583
2584 /*
2585 * Use the smaller of the two estimates. This can be justified in
2586 * essentially the same terms as given below for the no-stats case: to
2587 * a first approximation, we are estimating from the point of view of
2588 * the relation with smaller nd.
2589 */
2590 selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2591 }
2592 else
2593 {
2594 /*
2595 * We do not have MCV lists for both sides. Estimate the join
2596 * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2597 * is plausible if we assume that the join operator is strict and the
2598 * non-null values are about equally distributed: a given non-null
2599 * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2600 * of rel2, so total join rows are at most
2601 * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2602 * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2603 * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2604 * with MIN() is an upper bound. Using the MIN() means we estimate
2605 * from the point of view of the relation with smaller nd (since the
2606 * larger nd is determining the MIN). It is reasonable to assume that
2607 * most tuples in this rel will have join partners, so the bound is
2608 * probably reasonably tight and should be taken as-is.
2609 *
2610 * XXX Can we be smarter if we have an MCV list for just one side? It
2611 * seems that if we assume equal distribution for the other side, we
2612 * end up with the same answer anyway.
2613 */
2614 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2615 double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2616
2617 selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2618 if (nd1 > nd2)
2619 selec /= nd1;
2620 else
2621 selec /= nd2;
2622 }
2623
2624 return selec;
2625}
2626
2627/*
2628 * eqjoinsel_semi --- eqjoinsel for semi join
2629 *
2630 * (Also used for anti join, which we are supposed to estimate the same way.)
2631 * Caller has ensured that vardata1 is the LHS variable.
2632 * Unlike eqjoinsel_inner, we have to cope with opfuncoid being InvalidOid.
2633 */
2634static double
2635eqjoinsel_semi(Oid opfuncoid, Oid collation,
2636 VariableStatData *vardata1, VariableStatData *vardata2,
2637 double nd1, double nd2,
2638 bool isdefault1, bool isdefault2,
2639 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
2640 Form_pg_statistic stats1, Form_pg_statistic stats2,
2641 bool have_mcvs1, bool have_mcvs2,
2642 RelOptInfo *inner_rel)
2643{
2644 double selec;
2645
2646 /*
2647 * We clamp nd2 to be not more than what we estimate the inner relation's
2648 * size to be. This is intuitively somewhat reasonable since obviously
2649 * there can't be more than that many distinct values coming from the
2650 * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2651 * likewise) is that this is the only pathway by which restriction clauses
2652 * applied to the inner rel will affect the join result size estimate,
2653 * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2654 * only the outer rel's size. If we clamped nd1 we'd be double-counting
2655 * the selectivity of outer-rel restrictions.
2656 *
2657 * We can apply this clamping both with respect to the base relation from
2658 * which the join variable comes (if there is just one), and to the
2659 * immediate inner input relation of the current join.
2660 *
2661 * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2662 * great, maybe, but it didn't come out of nowhere either. This is most
2663 * helpful when the inner relation is empty and consequently has no stats.
2664 */
2665 if (vardata2->rel)
2666 {
2667 if (nd2 >= vardata2->rel->rows)
2668 {
2669 nd2 = vardata2->rel->rows;
2670 isdefault2 = false;
2671 }
2672 }
2673 if (nd2 >= inner_rel->rows)
2674 {
2675 nd2 = inner_rel->rows;
2676 isdefault2 = false;
2677 }
2678
2679 if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2680 {
2681 /*
2682 * We have most-common-value lists for both relations. Run through
2683 * the lists to see which MCVs actually join to each other with the
2684 * given operator. This allows us to determine the exact join
2685 * selectivity for the portion of the relations represented by the MCV
2686 * lists. We still have to estimate for the remaining population, but
2687 * in a skewed distribution this gives us a big leg up in accuracy.
2688 */
2689 LOCAL_FCINFO(fcinfo, 2);
2690 FmgrInfo eqproc;
2691 bool *hasmatch1;
2692 bool *hasmatch2;
2693 double nullfrac1 = stats1->stanullfrac;
2694 double matchfreq1,
2695 uncertainfrac,
2696 uncertain;
2697 int i,
2698 nmatches,
2699 clamped_nvalues2;
2700
2701 /*
2702 * The clamping above could have resulted in nd2 being less than
2703 * sslot2->nvalues; in which case, we assume that precisely the nd2
2704 * most common values in the relation will appear in the join input,
2705 * and so compare to only the first nd2 members of the MCV list. Of
2706 * course this is frequently wrong, but it's the best bet we can make.
2707 */
2708 clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2709
2710 fmgr_info(opfuncoid, &eqproc);
2711
2712 /*
2713 * Save a few cycles by setting up the fcinfo struct just once. Using
2714 * FunctionCallInvoke directly also avoids failure if the eqproc
2715 * returns NULL, though really equality functions should never do
2716 * that.
2717 */
2718 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2719 NULL, NULL);
2720 fcinfo->args[0].isnull = false;
2721 fcinfo->args[1].isnull = false;
2722
2723 hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2724 hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2725
2726 /*
2727 * Note we assume that each MCV will match at most one member of the
2728 * other MCV list. If the operator isn't really equality, there could
2729 * be multiple matches --- but we don't look for them, both for speed
2730 * and because the math wouldn't add up...
2731 */
2732 nmatches = 0;
2733 for (i = 0; i < sslot1->nvalues; i++)
2734 {
2735 int j;
2736
2737 fcinfo->args[0].value = sslot1->values[i];
2738
2739 for (j = 0; j < clamped_nvalues2; j++)
2740 {
2741 Datum fresult;
2742
2743 if (hasmatch2[j])
2744 continue;
2745 fcinfo->args[1].value = sslot2->values[j];
2746 fcinfo->isnull = false;
2747 fresult = FunctionCallInvoke(fcinfo);
2748 if (!fcinfo->isnull && DatumGetBool(fresult))
2749 {
2750 hasmatch1[i] = hasmatch2[j] = true;
2751 nmatches++;
2752 break;
2753 }
2754 }
2755 }
2756 /* Sum up frequencies of matched MCVs */
2757 matchfreq1 = 0.0;
2758 for (i = 0; i < sslot1->nvalues; i++)
2759 {
2760 if (hasmatch1[i])
2761 matchfreq1 += sslot1->numbers[i];
2762 }
2763 CLAMP_PROBABILITY(matchfreq1);
2764 pfree(hasmatch1);
2765 pfree(hasmatch2);
2766
2767 /*
2768 * Now we need to estimate the fraction of relation 1 that has at
2769 * least one join partner. We know for certain that the matched MCVs
2770 * do, so that gives us a lower bound, but we're really in the dark
2771 * about everything else. Our crude approach is: if nd1 <= nd2 then
2772 * assume all non-null rel1 rows have join partners, else assume for
2773 * the uncertain rows that a fraction nd2/nd1 have join partners. We
2774 * can discount the known-matched MCVs from the distinct-values counts
2775 * before doing the division.
2776 *
2777 * Crude as the above is, it's completely useless if we don't have
2778 * reliable ndistinct values for both sides. Hence, if either nd1 or
2779 * nd2 is default, punt and assume half of the uncertain rows have
2780 * join partners.
2781 */
2782 if (!isdefault1 && !isdefault2)
2783 {
2784 nd1 -= nmatches;
2785 nd2 -= nmatches;
2786 if (nd1 <= nd2 || nd2 < 0)
2787 uncertainfrac = 1.0;
2788 else
2789 uncertainfrac = nd2 / nd1;
2790 }
2791 else
2792 uncertainfrac = 0.5;
2793 uncertain = 1.0 - matchfreq1 - nullfrac1;
2794 CLAMP_PROBABILITY(uncertain);
2795 selec = matchfreq1 + uncertainfrac * uncertain;
2796 }
2797 else
2798 {
2799 /*
2800 * Without MCV lists for both sides, we can only use the heuristic
2801 * about nd1 vs nd2.
2802 */
2803 double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2804
2805 if (!isdefault1 && !isdefault2)
2806 {
2807 if (nd1 <= nd2 || nd2 < 0)
2808 selec = 1.0 - nullfrac1;
2809 else
2810 selec = (nd2 / nd1) * (1.0 - nullfrac1);
2811 }
2812 else
2813 selec = 0.5 * (1.0 - nullfrac1);
2814 }
2815
2816 return selec;
2817}
2818
2819/*
2820 * neqjoinsel - Join selectivity of "!="
2821 */
2822Datum
2824{
2826 Oid operator = PG_GETARG_OID(1);
2827 List *args = (List *) PG_GETARG_POINTER(2);
2828 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2830 Oid collation = PG_GET_COLLATION();
2831 float8 result;
2832
2833 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2834 {
2835 /*
2836 * For semi-joins, if there is more than one distinct value in the RHS
2837 * relation then every non-null LHS row must find a row to join since
2838 * it can only be equal to one of them. We'll assume that there is
2839 * always more than one distinct RHS value for the sake of stability,
2840 * though in theory we could have special cases for empty RHS
2841 * (selectivity = 0) and single-distinct-value RHS (selectivity =
2842 * fraction of LHS that has the same value as the single RHS value).
2843 *
2844 * For anti-joins, if we use the same assumption that there is more
2845 * than one distinct key in the RHS relation, then every non-null LHS
2846 * row must be suppressed by the anti-join.
2847 *
2848 * So either way, the selectivity estimate should be 1 - nullfrac.
2849 */
2850 VariableStatData leftvar;
2851 VariableStatData rightvar;
2852 bool reversed;
2853 HeapTuple statsTuple;
2854 double nullfrac;
2855
2856 get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
2857 statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
2858 if (HeapTupleIsValid(statsTuple))
2859 nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
2860 else
2861 nullfrac = 0.0;
2862 ReleaseVariableStats(leftvar);
2863 ReleaseVariableStats(rightvar);
2864
2865 result = 1.0 - nullfrac;
2866 }
2867 else
2868 {
2869 /*
2870 * We want 1 - eqjoinsel() where the equality operator is the one
2871 * associated with this != operator, that is, its negator.
2872 */
2873 Oid eqop = get_negator(operator);
2874
2875 if (eqop)
2876 {
2877 result =
2879 collation,
2881 ObjectIdGetDatum(eqop),
2883 Int16GetDatum(jointype),
2884 PointerGetDatum(sjinfo)));
2885 }
2886 else
2887 {
2888 /* Use default selectivity (should we raise an error instead?) */
2889 result = DEFAULT_EQ_SEL;
2890 }
2891 result = 1.0 - result;
2892 }
2893
2894 PG_RETURN_FLOAT8(result);
2895}
2896
2897/*
2898 * scalarltjoinsel - Join selectivity of "<" for scalars
2899 */
2900Datum
2902{
2904}
2905
2906/*
2907 * scalarlejoinsel - Join selectivity of "<=" for scalars
2908 */
2909Datum
2911{
2913}
2914
2915/*
2916 * scalargtjoinsel - Join selectivity of ">" for scalars
2917 */
2918Datum
2920{
2922}
2923
2924/*
2925 * scalargejoinsel - Join selectivity of ">=" for scalars
2926 */
2927Datum
2929{
2931}
2932
2933
2934/*
2935 * mergejoinscansel - Scan selectivity of merge join.
2936 *
2937 * A merge join will stop as soon as it exhausts either input stream.
2938 * Therefore, if we can estimate the ranges of both input variables,
2939 * we can estimate how much of the input will actually be read. This
2940 * can have a considerable impact on the cost when using indexscans.
2941 *
2942 * Also, we can estimate how much of each input has to be read before the
2943 * first join pair is found, which will affect the join's startup time.
2944 *
2945 * clause should be a clause already known to be mergejoinable. opfamily,
2946 * strategy, and nulls_first specify the sort ordering being used.
2947 *
2948 * The outputs are:
2949 * *leftstart is set to the fraction of the left-hand variable expected
2950 * to be scanned before the first join pair is found (0 to 1).
2951 * *leftend is set to the fraction of the left-hand variable expected
2952 * to be scanned before the join terminates (0 to 1).
2953 * *rightstart, *rightend similarly for the right-hand variable.
2954 */
2955void
2957 Oid opfamily, int strategy, bool nulls_first,
2958 Selectivity *leftstart, Selectivity *leftend,
2959 Selectivity *rightstart, Selectivity *rightend)
2960{
2961 Node *left,
2962 *right;
2963 VariableStatData leftvar,
2964 rightvar;
2965 int op_strategy;
2966 Oid op_lefttype;
2967 Oid op_righttype;
2968 Oid opno,
2969 collation,
2970 lsortop,
2971 rsortop,
2972 lstatop,
2973 rstatop,
2974 ltop,
2975 leop,
2976 revltop,
2977 revleop;
2978 bool isgt;
2979 Datum leftmin,
2980 leftmax,
2981 rightmin,
2982 rightmax;
2983 double selec;
2984
2985 /* Set default results if we can't figure anything out. */
2986 /* XXX should default "start" fraction be a bit more than 0? */
2987 *leftstart = *rightstart = 0.0;
2988 *leftend = *rightend = 1.0;
2989
2990 /* Deconstruct the merge clause */
2991 if (!is_opclause(clause))
2992 return; /* shouldn't happen */
2993 opno = ((OpExpr *) clause)->opno;
2994 collation = ((OpExpr *) clause)->inputcollid;
2995 left = get_leftop((Expr *) clause);
2996 right = get_rightop((Expr *) clause);
2997 if (!right)
2998 return; /* shouldn't happen */
2999
3000 /* Look for stats for the inputs */
3001 examine_variable(root, left, 0, &leftvar);
3002 examine_variable(root, right, 0, &rightvar);
3003
3004 /* Extract the operator's declared left/right datatypes */
3005 get_op_opfamily_properties(opno, opfamily, false,
3006 &op_strategy,
3007 &op_lefttype,
3008 &op_righttype);
3009 Assert(op_strategy == BTEqualStrategyNumber);
3010
3011 /*
3012 * Look up the various operators we need. If we don't find them all, it
3013 * probably means the opfamily is broken, but we just fail silently.
3014 *
3015 * Note: we expect that pg_statistic histograms will be sorted by the '<'
3016 * operator, regardless of which sort direction we are considering.
3017 */
3018 switch (strategy)
3019 {
3021 isgt = false;
3022 if (op_lefttype == op_righttype)
3023 {
3024 /* easy case */
3025 ltop = get_opfamily_member(opfamily,
3026 op_lefttype, op_righttype,
3028 leop = get_opfamily_member(opfamily,
3029 op_lefttype, op_righttype,
3031 lsortop = ltop;
3032 rsortop = ltop;
3033 lstatop = lsortop;
3034 rstatop = rsortop;
3035 revltop = ltop;
3036 revleop = leop;
3037 }
3038 else
3039 {
3040 ltop = get_opfamily_member(opfamily,
3041 op_lefttype, op_righttype,
3043 leop = get_opfamily_member(opfamily,
3044 op_lefttype, op_righttype,
3046 lsortop = get_opfamily_member(opfamily,
3047 op_lefttype, op_lefttype,
3049 rsortop = get_opfamily_member(opfamily,
3050 op_righttype, op_righttype,
3052 lstatop = lsortop;
3053 rstatop = rsortop;
3054 revltop = get_opfamily_member(opfamily,
3055 op_righttype, op_lefttype,
3057 revleop = get_opfamily_member(opfamily,
3058 op_righttype, op_lefttype,
3060 }
3061 break;
3063 /* descending-order case */
3064 isgt = true;
3065 if (op_lefttype == op_righttype)
3066 {
3067 /* easy case */
3068 ltop = get_opfamily_member(opfamily,
3069 op_lefttype, op_righttype,
3071 leop = get_opfamily_member(opfamily,
3072 op_lefttype, op_righttype,
3074 lsortop = ltop;
3075 rsortop = ltop;
3076 lstatop = get_opfamily_member(opfamily,
3077 op_lefttype, op_lefttype,
3079 rstatop = lstatop;
3080 revltop = ltop;
3081 revleop = leop;
3082 }
3083 else
3084 {
3085 ltop = get_opfamily_member(opfamily,
3086 op_lefttype, op_righttype,
3088 leop = get_opfamily_member(opfamily,
3089 op_lefttype, op_righttype,
3091 lsortop = get_opfamily_member(opfamily,
3092 op_lefttype, op_lefttype,
3094 rsortop = get_opfamily_member(opfamily,
3095 op_righttype, op_righttype,
3097 lstatop = get_opfamily_member(opfamily,
3098 op_lefttype, op_lefttype,
3100 rstatop = get_opfamily_member(opfamily,
3101 op_righttype, op_righttype,
3103 revltop = get_opfamily_member(opfamily,
3104 op_righttype, op_lefttype,
3106 revleop = get_opfamily_member(opfamily,
3107 op_righttype, op_lefttype,
3109 }
3110 break;
3111 default:
3112 goto fail; /* shouldn't get here */
3113 }
3114
3115 if (!OidIsValid(lsortop) ||
3116 !OidIsValid(rsortop) ||
3117 !OidIsValid(lstatop) ||
3118 !OidIsValid(rstatop) ||
3119 !OidIsValid(ltop) ||
3120 !OidIsValid(leop) ||
3121 !OidIsValid(revltop) ||
3122 !OidIsValid(revleop))
3123 goto fail; /* insufficient info in catalogs */
3124
3125 /* Try to get ranges of both inputs */
3126 if (!isgt)
3127 {
3128 if (!get_variable_range(root, &leftvar, lstatop, collation,
3129 &leftmin, &leftmax))
3130 goto fail; /* no range available from stats */
3131 if (!get_variable_range(root, &rightvar, rstatop, collation,
3132 &rightmin, &rightmax))
3133 goto fail; /* no range available from stats */
3134 }
3135 else
3136 {
3137 /* need to swap the max and min */
3138 if (!get_variable_range(root, &leftvar, lstatop, collation,
3139 &leftmax, &leftmin))
3140 goto fail; /* no range available from stats */
3141 if (!get_variable_range(root, &rightvar, rstatop, collation,
3142 &rightmax, &rightmin))
3143 goto fail; /* no range available from stats */
3144 }
3145
3146 /*
3147 * Now, the fraction of the left variable that will be scanned is the
3148 * fraction that's <= the right-side maximum value. But only believe
3149 * non-default estimates, else stick with our 1.0.
3150 */
3151 selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
3152 rightmax, op_righttype);
3153 if (selec != DEFAULT_INEQ_SEL)
3154 *leftend = selec;
3155
3156 /* And similarly for the right variable. */
3157 selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
3158 leftmax, op_lefttype);
3159 if (selec != DEFAULT_INEQ_SEL)
3160 *rightend = selec;
3161
3162 /*
3163 * Only one of the two "end" fractions can really be less than 1.0;
3164 * believe the smaller estimate and reset the other one to exactly 1.0. If
3165 * we get exactly equal estimates (as can easily happen with self-joins),
3166 * believe neither.
3167 */
3168 if (*leftend > *rightend)
3169 *leftend = 1.0;
3170 else if (*leftend < *rightend)
3171 *rightend = 1.0;
3172 else
3173 *leftend = *rightend = 1.0;
3174
3175 /*
3176 * Also, the fraction of the left variable that will be scanned before the
3177 * first join pair is found is the fraction that's < the right-side
3178 * minimum value. But only believe non-default estimates, else stick with
3179 * our own default.
3180 */
3181 selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
3182 rightmin, op_righttype);
3183 if (selec != DEFAULT_INEQ_SEL)
3184 *leftstart = selec;
3185
3186 /* And similarly for the right variable. */
3187 selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
3188 leftmin, op_lefttype);
3189 if (selec != DEFAULT_INEQ_SEL)
3190 *rightstart = selec;
3191
3192 /*
3193 * Only one of the two "start" fractions can really be more than zero;
3194 * believe the larger estimate and reset the other one to exactly 0.0. If
3195 * we get exactly equal estimates (as can easily happen with self-joins),
3196 * believe neither.
3197 */
3198 if (*leftstart < *rightstart)
3199 *leftstart = 0.0;
3200 else if (*leftstart > *rightstart)
3201 *rightstart = 0.0;
3202 else
3203 *leftstart = *rightstart = 0.0;
3204
3205 /*
3206 * If the sort order is nulls-first, we're going to have to skip over any
3207 * nulls too. These would not have been counted by scalarineqsel, and we
3208 * can safely add in this fraction regardless of whether we believe
3209 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3210 */
3211 if (nulls_first)
3212 {
3213 Form_pg_statistic stats;
3214
3215 if (HeapTupleIsValid(leftvar.statsTuple))
3216 {
3217 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3218 *leftstart += stats->stanullfrac;
3219 CLAMP_PROBABILITY(*leftstart);
3220 *leftend += stats->stanullfrac;
3221 CLAMP_PROBABILITY(*leftend);
3222 }
3223 if (HeapTupleIsValid(rightvar.statsTuple))
3224 {
3225 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3226 *rightstart += stats->stanullfrac;
3227 CLAMP_PROBABILITY(*rightstart);
3228 *rightend += stats->stanullfrac;
3229 CLAMP_PROBABILITY(*rightend);
3230 }
3231 }
3232
3233 /* Disbelieve start >= end, just in case that can happen */
3234 if (*leftstart >= *leftend)
3235 {
3236 *leftstart = 0.0;
3237 *leftend = 1.0;
3238 }
3239 if (*rightstart >= *rightend)
3240 {
3241 *rightstart = 0.0;
3242 *rightend = 1.0;
3243 }
3244
3245fail:
3246 ReleaseVariableStats(leftvar);
3247 ReleaseVariableStats(rightvar);
3248}
3249
3250
3251/*
3252 * matchingsel -- generic matching-operator selectivity support
3253 *
3254 * Use these for any operators that (a) are on data types for which we collect
3255 * standard statistics, and (b) have behavior for which the default estimate
3256 * (twice DEFAULT_EQ_SEL) is sane. Typically that is good for match-like
3257 * operators.
3258 */
3259
3260Datum
3262{
3264 Oid operator = PG_GETARG_OID(1);
3265 List *args = (List *) PG_GETARG_POINTER(2);
3266 int varRelid = PG_GETARG_INT32(3);
3267 Oid collation = PG_GET_COLLATION();
3268 double selec;
3269
3270 /* Use generic restriction selectivity logic. */
3271 selec = generic_restriction_selectivity(root, operator, collation,
3272 args, varRelid,
3274
3275 PG_RETURN_FLOAT8((float8) selec);
3276}
3277
3278Datum
3280{
3281 /* Just punt, for the moment. */
3283}
3284
3285
3286/*
3287 * Helper routine for estimate_num_groups: add an item to a list of
3288 * GroupVarInfos, but only if it's not known equal to any of the existing
3289 * entries.
3290 */
3291typedef struct
3292{
3293 Node *var; /* might be an expression, not just a Var */
3294 RelOptInfo *rel; /* relation it belongs to */
3295 double ndistinct; /* # distinct values */
3296 bool isdefault; /* true if DEFAULT_NUM_DISTINCT was used */
3297} GroupVarInfo;
3298
3299static List *
3301 Node *var, VariableStatData *vardata)
3302{
3303 GroupVarInfo *varinfo;
3304 double ndistinct;
3305 bool isdefault;
3306 ListCell *lc;
3307
3308 ndistinct = get_variable_numdistinct(vardata, &isdefault);
3309
3310 /*
3311 * The nullingrels bits within the var could cause the same var to be
3312 * counted multiple times if it's marked with different nullingrels. They
3313 * could also prevent us from matching the var to the expressions in
3314 * extended statistics (see estimate_multivariate_ndistinct). So strip
3315 * them out first.
3316 */
3317 var = remove_nulling_relids(var, root->outer_join_rels, NULL);
3318
3319 foreach(lc, varinfos)
3320 {
3321 varinfo = (GroupVarInfo *) lfirst(lc);
3322
3323 /* Drop exact duplicates */
3324 if (equal(var, varinfo->var))
3325 return varinfos;
3326
3327 /*
3328 * Drop known-equal vars, but only if they belong to different
3329 * relations (see comments for estimate_num_groups). We aren't too
3330 * fussy about the semantics of "equal" here.
3331 */
3332 if (vardata->rel != varinfo->rel &&
3333 exprs_known_equal(root, var, varinfo->var, InvalidOid))
3334 {
3335 if (varinfo->ndistinct <= ndistinct)
3336 {
3337 /* Keep older item, forget new one */
3338 return varinfos;
3339 }
3340 else
3341 {
3342 /* Delete the older item */
3343 varinfos = foreach_delete_current(varinfos, lc);
3344 }
3345 }
3346 }
3347
3348 varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3349
3350 varinfo->var = var;
3351 varinfo->rel = vardata->rel;
3352 varinfo->ndistinct = ndistinct;
3353 varinfo->isdefault = isdefault;
3354 varinfos = lappend(varinfos, varinfo);
3355 return varinfos;
3356}
3357
3358/*
3359 * estimate_num_groups - Estimate number of groups in a grouped query
3360 *
3361 * Given a query having a GROUP BY clause, estimate how many groups there
3362 * will be --- ie, the number of distinct combinations of the GROUP BY
3363 * expressions.
3364 *
3365 * This routine is also used to estimate the number of rows emitted by
3366 * a DISTINCT filtering step; that is an isomorphic problem. (Note:
3367 * actually, we only use it for DISTINCT when there's no grouping or
3368 * aggregation ahead of the DISTINCT.)
3369 *
3370 * Inputs:
3371 * root - the query
3372 * groupExprs - list of expressions being grouped by
3373 * input_rows - number of rows estimated to arrive at the group/unique
3374 * filter step
3375 * pgset - NULL, or a List** pointing to a grouping set to filter the
3376 * groupExprs against
3377 *
3378 * Outputs:
3379 * estinfo - When passed as non-NULL, the function will set bits in the
3380 * "flags" field in order to provide callers with additional information
3381 * about the estimation. Currently, we only set the SELFLAG_USED_DEFAULT
3382 * bit if we used any default values in the estimation.
3383 *
3384 * Given the lack of any cross-correlation statistics in the system, it's
3385 * impossible to do anything really trustworthy with GROUP BY conditions
3386 * involving multiple Vars. We should however avoid assuming the worst
3387 * case (all possible cross-product terms actually appear as groups) since
3388 * very often the grouped-by Vars are highly correlated. Our current approach
3389 * is as follows:
3390 * 1. Expressions yielding boolean are assumed to contribute two groups,
3391 * independently of their content, and are ignored in the subsequent
3392 * steps. This is mainly because tests like "col IS NULL" break the
3393 * heuristic used in step 2 especially badly.
3394 * 2. Reduce the given expressions to a list of unique Vars used. For
3395 * example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3396 * It is clearly correct not to count the same Var more than once.
3397 * It is also reasonable to treat f(x) the same as x: f() cannot
3398 * increase the number of distinct values (unless it is volatile,
3399 * which we consider unlikely for grouping), but it probably won't
3400 * reduce the number of distinct values much either.
3401 * As a special case, if a GROUP BY expression can be matched to an
3402 * expressional index for which we have statistics, then we treat the
3403 * whole expression as though it were just a Var.
3404 * 3. If the list contains Vars of different relations that are known equal
3405 * due to equivalence classes, then drop all but one of the Vars from each
3406 * known-equal set, keeping the one with smallest estimated # of values
3407 * (since the extra values of the others can't appear in joined rows).
3408 * Note the reason we only consider Vars of different relations is that
3409 * if we considered ones of the same rel, we'd be double-counting the
3410 * restriction selectivity of the equality in the next step.
3411 * 4. For Vars within a single source rel, we multiply together the numbers
3412 * of values, clamp to the number of rows in the rel (divided by 10 if
3413 * more than one Var), and then multiply by a factor based on the
3414 * selectivity of the restriction clauses for that rel. When there's
3415 * more than one Var, the initial product is probably too high (it's the
3416 * worst case) but clamping to a fraction of the rel's rows seems to be a
3417 * helpful heuristic for not letting the estimate get out of hand. (The
3418 * factor of 10 is derived from pre-Postgres-7.4 practice.) The factor
3419 * we multiply by to adjust for the restriction selectivity assumes that
3420 * the restriction clauses are independent of the grouping, which may not
3421 * be a valid assumption, but it's hard to do better.
3422 * 5. If there are Vars from multiple rels, we repeat step 4 for each such
3423 * rel, and multiply the results together.
3424 * Note that rels not containing grouped Vars are ignored completely, as are
3425 * join clauses. Such rels cannot increase the number of groups, and we
3426 * assume such clauses do not reduce the number either (somewhat bogus,
3427 * but we don't have the info to do better).
3428 */
3429double
3430estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3431 List **pgset, EstimationInfo *estinfo)
3432{
3433 List *varinfos = NIL;
3434 double srf_multiplier = 1.0;
3435 double numdistinct;
3436 ListCell *l;
3437 int i;
3438
3439 /* Zero the estinfo output parameter, if non-NULL */
3440 if (estinfo != NULL)
3441 memset(estinfo, 0, sizeof(EstimationInfo));
3442
3443 /*
3444 * We don't ever want to return an estimate of zero groups, as that tends
3445 * to lead to division-by-zero and other unpleasantness. The input_rows
3446 * estimate is usually already at least 1, but clamp it just in case it
3447 * isn't.
3448 */
3449 input_rows = clamp_row_est(input_rows);
3450
3451 /*
3452 * If no grouping columns, there's exactly one group. (This can't happen
3453 * for normal cases with GROUP BY or DISTINCT, but it is possible for
3454 * corner cases with set operations.)
3455 */
3456 if (groupExprs == NIL || (pgset && *pgset == NIL))
3457 return 1.0;
3458
3459 /*
3460 * Count groups derived from boolean grouping expressions. For other
3461 * expressions, find the unique Vars used, treating an expression as a Var
3462 * if we can find stats for it. For each one, record the statistical
3463 * estimate of number of distinct values (total in its table, without
3464 * regard for filtering).
3465 */
3466 numdistinct = 1.0;
3467
3468 i = 0;
3469 foreach(l, groupExprs)
3470 {
3471 Node *groupexpr = (Node *) lfirst(l);
3472 double this_srf_multiplier;
3473 VariableStatData vardata;
3474 List *varshere;
3475 ListCell *l2;
3476
3477 /* is expression in this grouping set? */
3478 if (pgset && !list_member_int(*pgset, i++))
3479 continue;
3480
3481 /*
3482 * Set-returning functions in grouping columns are a bit problematic.
3483 * The code below will effectively ignore their SRF nature and come up
3484 * with a numdistinct estimate as though they were scalar functions.
3485 * We compensate by scaling up the end result by the largest SRF
3486 * rowcount estimate. (This will be an overestimate if the SRF
3487 * produces multiple copies of any output value, but it seems best to
3488 * assume the SRF's outputs are distinct. In any case, it's probably
3489 * pointless to worry too much about this without much better
3490 * estimates for SRF output rowcounts than we have today.)
3491 */
3492 this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3493 if (srf_multiplier < this_srf_multiplier)
3494 srf_multiplier = this_srf_multiplier;
3495
3496 /* Short-circuit for expressions returning boolean */
3497 if (exprType(groupexpr) == BOOLOID)
3498 {
3499 numdistinct *= 2.0;
3500 continue;
3501 }
3502
3503 /*
3504 * If examine_variable is able to deduce anything about the GROUP BY
3505 * expression, treat it as a single variable even if it's really more
3506 * complicated.
3507 *
3508 * XXX This has the consequence that if there's a statistics object on
3509 * the expression, we don't split it into individual Vars. This
3510 * affects our selection of statistics in
3511 * estimate_multivariate_ndistinct, because it's probably better to
3512 * use more accurate estimate for each expression and treat them as
3513 * independent, than to combine estimates for the extracted variables
3514 * when we don't know how that relates to the expressions.
3515 */
3516 examine_variable(root, groupexpr, 0, &vardata);
3517 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3518 {
3519 varinfos = add_unique_group_var(root, varinfos,
3520 groupexpr, &vardata);
3521 ReleaseVariableStats(vardata);
3522 continue;
3523 }
3524 ReleaseVariableStats(vardata);
3525
3526 /*
3527 * Else pull out the component Vars. Handle PlaceHolderVars by
3528 * recursing into their arguments (effectively assuming that the
3529 * PlaceHolderVar doesn't change the number of groups, which boils
3530 * down to ignoring the possible addition of nulls to the result set).
3531 */
3532 varshere = pull_var_clause(groupexpr,
3536
3537 /*
3538 * If we find any variable-free GROUP BY item, then either it is a
3539 * constant (and we can ignore it) or it contains a volatile function;
3540 * in the latter case we punt and assume that each input row will
3541 * yield a distinct group.
3542 */
3543 if (varshere == NIL)
3544 {
3545 if (contain_volatile_functions(groupexpr))
3546 return input_rows;
3547 continue;
3548 }
3549
3550 /*
3551 * Else add variables to varinfos list
3552 */
3553 foreach(l2, varshere)
3554 {
3555 Node *var = (Node *) lfirst(l2);
3556
3557 examine_variable(root, var, 0, &vardata);
3558 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3559 ReleaseVariableStats(vardata);
3560 }
3561 }
3562
3563 /*
3564 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3565 * list.
3566 */
3567 if (varinfos == NIL)
3568 {
3569 /* Apply SRF multiplier as we would do in the long path */
3570 numdistinct *= srf_multiplier;
3571 /* Round off */
3572 numdistinct = ceil(numdistinct);
3573 /* Guard against out-of-range answers */
3574 if (numdistinct > input_rows)
3575 numdistinct = input_rows;
3576 if (numdistinct < 1.0)
3577 numdistinct = 1.0;
3578 return numdistinct;
3579 }
3580
3581 /*
3582 * Group Vars by relation and estimate total numdistinct.
3583 *
3584 * For each iteration of the outer loop, we process the frontmost Var in
3585 * varinfos, plus all other Vars in the same relation. We remove these
3586 * Vars from the newvarinfos list for the next iteration. This is the
3587 * easiest way to group Vars of same rel together.
3588 */
3589 do
3590 {
3591 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3592 RelOptInfo *rel = varinfo1->rel;
3593 double reldistinct = 1;
3594 double relmaxndistinct = reldistinct;
3595 int relvarcount = 0;
3596 List *newvarinfos = NIL;
3597 List *relvarinfos = NIL;
3598
3599 /*
3600 * Split the list of varinfos in two - one for the current rel, one
3601 * for remaining Vars on other rels.
3602 */
3603 relvarinfos = lappend(relvarinfos, varinfo1);
3604 for_each_from(l, varinfos, 1)
3605 {
3606 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3607
3608 if (varinfo2->rel == varinfo1->rel)
3609 {
3610 /* varinfos on current rel */
3611 relvarinfos = lappend(relvarinfos, varinfo2);
3612 }
3613 else
3614 {
3615 /* not time to process varinfo2 yet */
3616 newvarinfos = lappend(newvarinfos, varinfo2);
3617 }
3618 }
3619
3620 /*
3621 * Get the numdistinct estimate for the Vars of this rel. We
3622 * iteratively search for multivariate n-distinct with maximum number
3623 * of vars; assuming that each var group is independent of the others,
3624 * we multiply them together. Any remaining relvarinfos after no more
3625 * multivariate matches are found are assumed independent too, so
3626 * their individual ndistinct estimates are multiplied also.
3627 *
3628 * While iterating, count how many separate numdistinct values we
3629 * apply. We apply a fudge factor below, but only if we multiplied
3630 * more than one such values.
3631 */
3632 while (relvarinfos)
3633 {
3634 double mvndistinct;
3635
3636 if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3637 &mvndistinct))
3638 {
3639 reldistinct *= mvndistinct;
3640 if (relmaxndistinct < mvndistinct)
3641 relmaxndistinct = mvndistinct;
3642 relvarcount++;
3643 }
3644 else
3645 {
3646 foreach(l, relvarinfos)
3647 {
3648 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3649
3650 reldistinct *= varinfo2->ndistinct;
3651 if (relmaxndistinct < varinfo2->ndistinct)
3652 relmaxndistinct = varinfo2->ndistinct;
3653 relvarcount++;
3654
3655 /*
3656 * When varinfo2's isdefault is set then we'd better set
3657 * the SELFLAG_USED_DEFAULT bit in the EstimationInfo.
3658 */
3659 if (estinfo != NULL && varinfo2->isdefault)
3660 estinfo->flags |= SELFLAG_USED_DEFAULT;
3661 }
3662
3663 /* we're done with this relation */
3664 relvarinfos = NIL;
3665 }
3666 }
3667
3668 /*
3669 * Sanity check --- don't divide by zero if empty relation.
3670 */
3671 Assert(IS_SIMPLE_REL(rel));
3672 if (rel->tuples > 0)
3673 {
3674 /*
3675 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3676 * fudge factor is because the Vars are probably correlated but we
3677 * don't know by how much. We should never clamp to less than the
3678 * largest ndistinct value for any of the Vars, though, since
3679 * there will surely be at least that many groups.
3680 */
3681 double clamp = rel->tuples;
3682
3683 if (relvarcount > 1)
3684 {
3685 clamp *= 0.1;
3686 if (clamp < relmaxndistinct)
3687 {
3688 clamp = relmaxndistinct;
3689 /* for sanity in case some ndistinct is too large: */
3690 if (clamp > rel->tuples)
3691 clamp = rel->tuples;
3692 }
3693 }
3694 if (reldistinct > clamp)
3695 reldistinct = clamp;
3696
3697 /*
3698 * Update the estimate based on the restriction selectivity,
3699 * guarding against division by zero when reldistinct is zero.
3700 * Also skip this if we know that we are returning all rows.
3701 */
3702 if (reldistinct > 0 && rel->rows < rel->tuples)
3703 {
3704 /*
3705 * Given a table containing N rows with n distinct values in a
3706 * uniform distribution, if we select p rows at random then
3707 * the expected number of distinct values selected is
3708 *
3709 * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3710 *
3711 * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3712 *
3713 * See "Approximating block accesses in database
3714 * organizations", S. B. Yao, Communications of the ACM,
3715 * Volume 20 Issue 4, April 1977 Pages 260-261.
3716 *
3717 * Alternatively, re-arranging the terms from the factorials,
3718 * this may be written as
3719 *
3720 * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3721 *
3722 * This form of the formula is more efficient to compute in
3723 * the common case where p is larger than N/n. Additionally,
3724 * as pointed out by Dell'Era, if i << N for all terms in the
3725 * product, it can be approximated by
3726 *
3727 * n * (1 - ((N-p)/N)^(N/n))
3728 *
3729 * See "Expected distinct values when selecting from a bag
3730 * without replacement", Alberto Dell'Era,
3731 * http://www.adellera.it/investigations/distinct_balls/.
3732 *
3733 * The condition i << N is equivalent to n >> 1, so this is a
3734 * good approximation when the number of distinct values in
3735 * the table is large. It turns out that this formula also
3736 * works well even when n is small.
3737 */
3738 reldistinct *=
3739 (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3740 rel->tuples / reldistinct));
3741 }
3742 reldistinct = clamp_row_est(reldistinct);
3743
3744 /*
3745 * Update estimate of total distinct groups.
3746 */
3747 numdistinct *= reldistinct;
3748 }
3749
3750 varinfos = newvarinfos;
3751 } while (varinfos != NIL);
3752
3753 /* Now we can account for the effects of any SRFs */
3754 numdistinct *= srf_multiplier;
3755
3756 /* Round off */
3757 numdistinct = ceil(numdistinct);
3758
3759 /* Guard against out-of-range answers */
3760 if (numdistinct > input_rows)
3761 numdistinct = input_rows;
3762 if (numdistinct < 1.0)
3763 numdistinct = 1.0;
3764
3765 return numdistinct;
3766}
3767
3768/*
3769 * Estimate hash bucket statistics when the specified expression is used
3770 * as a hash key for the given number of buckets.
3771 *
3772 * This attempts to determine two values:
3773 *
3774 * 1. The frequency of the most common value of the expression (returns
3775 * zero into *mcv_freq if we can't get that).
3776 *
3777 * 2. The "bucketsize fraction", ie, average number of entries in a bucket
3778 * divided by total tuples in relation.
3779 *
3780 * XXX This is really pretty bogus since we're effectively assuming that the
3781 * distribution of hash keys will be the same after applying restriction
3782 * clauses as it was in the underlying relation. However, we are not nearly
3783 * smart enough to figure out how the restrict clauses might change the
3784 * distribution, so this will have to do for now.
3785 *
3786 * We are passed the number of buckets the executor will use for the given
3787 * input relation. If the data were perfectly distributed, with the same
3788 * number of tuples going into each available bucket, then the bucketsize
3789 * fraction would be 1/nbuckets. But this happy state of affairs will occur
3790 * only if (a) there are at least nbuckets distinct data values, and (b)
3791 * we have a not-too-skewed data distribution. Otherwise the buckets will
3792 * be nonuniformly occupied. If the other relation in the join has a key
3793 * distribution similar to this one's, then the most-loaded buckets are
3794 * exactly those that will be probed most often. Therefore, the "average"
3795 * bucket size for costing purposes should really be taken as something close
3796 * to the "worst case" bucket size. We try to estimate this by adjusting the
3797 * fraction if there are too few distinct data values, and then scaling up
3798 * by the ratio of the most common value's frequency to the average frequency.
3799 *
3800 * If no statistics are available, use a default estimate of 0.1. This will
3801 * discourage use of a hash rather strongly if the inner relation is large,
3802 * which is what we want. We do not want to hash unless we know that the
3803 * inner rel is well-dispersed (or the alternatives seem much worse).
3804 *
3805 * The caller should also check that the mcv_freq is not so large that the
3806 * most common value would by itself require an impractically large bucket.
3807 * In a hash join, the executor can split buckets if they get too big, but
3808 * obviously that doesn't help for a bucket that contains many duplicates of
3809 * the same value.
3810 */
3811void
3813 Selectivity *mcv_freq,
3814 Selectivity *bucketsize_frac)
3815{
3816 VariableStatData vardata;
3817 double estfract,
3818 ndistinct,
3819 stanullfrac,
3820 avgfreq;
3821 bool isdefault;
3822 AttStatsSlot sslot;
3823
3824 examine_variable(root, hashkey, 0, &vardata);
3825
3826 /* Look up the frequency of the most common value, if available */
3827 *mcv_freq = 0.0;
3828
3829 if (HeapTupleIsValid(vardata.statsTuple))
3830 {
3831 if (get_attstatsslot(&sslot, vardata.statsTuple,
3832 STATISTIC_KIND_MCV, InvalidOid,
3834 {
3835 /*
3836 * The first MCV stat is for the most common value.
3837 */
3838 if (sslot.nnumbers > 0)
3839 *mcv_freq = sslot.numbers[0];
3840 free_attstatsslot(&sslot);
3841 }
3842 }
3843
3844 /* Get number of distinct values */
3845 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3846
3847 /*
3848 * If ndistinct isn't real, punt. We normally return 0.1, but if the
3849 * mcv_freq is known to be even higher than that, use it instead.
3850 */
3851 if (isdefault)
3852 {
3853 *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3854 ReleaseVariableStats(vardata);
3855 return;
3856 }
3857
3858 /* Get fraction that are null */
3859 if (HeapTupleIsValid(vardata.statsTuple))
3860 {
3861 Form_pg_statistic stats;
3862
3863 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3864 stanullfrac = stats->stanullfrac;
3865 }
3866 else
3867 stanullfrac = 0.0;
3868
3869 /* Compute avg freq of all distinct data values in raw relation */
3870 avgfreq = (1.0 - stanullfrac) / ndistinct;
3871
3872 /*
3873 * Adjust ndistinct to account for restriction clauses. Observe we are
3874 * assuming that the data distribution is affected uniformly by the
3875 * restriction clauses!
3876 *
3877 * XXX Possibly better way, but much more expensive: multiply by
3878 * selectivity of rel's restriction clauses that mention the target Var.
3879 */
3880 if (vardata.rel && vardata.rel->tuples > 0)
3881 {
3882 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3883 ndistinct = clamp_row_est(ndistinct);
3884 }
3885
3886 /*
3887 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3888 * number of buckets is less than the expected number of distinct values;
3889 * otherwise it is 1/ndistinct.
3890 */
3891 if (ndistinct > nbuckets)
3892 estfract = 1.0 / nbuckets;
3893 else
3894 estfract = 1.0 / ndistinct;
3895
3896 /*
3897 * Adjust estimated bucketsize upward to account for skewed distribution.
3898 */
3899 if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3900 estfract *= *mcv_freq / avgfreq;
3901
3902 /*
3903 * Clamp bucketsize to sane range (the above adjustment could easily
3904 * produce an out-of-range result). We set the lower bound a little above
3905 * zero, since zero isn't a very sane result.
3906 */
3907 if (estfract < 1.0e-6)
3908 estfract = 1.0e-6;
3909 else if (estfract > 1.0)
3910 estfract = 1.0;
3911
3912 *bucketsize_frac = (Selectivity) estfract;
3913
3914 ReleaseVariableStats(vardata);
3915}
3916
3917/*
3918 * estimate_hashagg_tablesize
3919 * estimate the number of bytes that a hash aggregate hashtable will
3920 * require based on the agg_costs, path width and number of groups.
3921 *
3922 * We return the result as "double" to forestall any possible overflow
3923 * problem in the multiplication by dNumGroups.
3924 *
3925 * XXX this may be over-estimating the size now that hashagg knows to omit
3926 * unneeded columns from the hashtable. Also for mixed-mode grouping sets,
3927 * grouping columns not in the hashed set are counted here even though hashagg
3928 * won't store them. Is this a problem?
3929 */
3930double
3932 const AggClauseCosts *agg_costs, double dNumGroups)
3933{
3934 Size hashentrysize;
3935
3936 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
3937 path->pathtarget->width,
3938 agg_costs->transitionSpace);
3939
3940 /*
3941 * Note that this disregards the effect of fill-factor and growth policy
3942 * of the hash table. That's probably ok, given that the default
3943 * fill-factor is relatively high. It'd be hard to meaningfully factor in
3944 * "double-in-size" growth policies here.
3945 */
3946 return hashentrysize * dNumGroups;
3947}
3948
3949
3950/*-------------------------------------------------------------------------
3951 *
3952 * Support routines
3953 *
3954 *-------------------------------------------------------------------------
3955 */
3956
3957/*
3958 * Find applicable ndistinct statistics for the given list of VarInfos (which
3959 * must all belong to the given rel), and update *ndistinct to the estimate of
3960 * the MVNDistinctItem that best matches. If a match it found, *varinfos is
3961 * updated to remove the list of matched varinfos.
3962 *
3963 * Varinfos that aren't for simple Vars are ignored.
3964 *
3965 * Return true if we're able to find a match, false otherwise.
3966 */
3967static bool
3969 List **varinfos, double *ndistinct)
3970{
3971 ListCell *lc;
3972 int nmatches_vars;
3973 int nmatches_exprs;
3974 Oid statOid = InvalidOid;
3975 MVNDistinct *stats;
3976 StatisticExtInfo *matched_info = NULL;
3978
3979 /* bail out immediately if the table has no extended statistics */
3980 if (!rel->statlist)
3981 return false;
3982
3983 /* look for the ndistinct statistics object matching the most vars */
3984 nmatches_vars = 0; /* we require at least two matches */
3985 nmatches_exprs = 0;
3986 foreach(lc, rel->statlist)
3987 {
3988 ListCell *lc2;
3990 int nshared_vars = 0;
3991 int nshared_exprs = 0;
3992
3993 /* skip statistics of other kinds */
3994 if (info->kind != STATS_EXT_NDISTINCT)
3995 continue;
3996
3997 /* skip statistics with mismatching stxdinherit value */
3998 if (info->inherit != rte->inh)
3999 continue;
4000
4001 /*
4002 * Determine how many expressions (and variables in non-matched
4003 * expressions) match. We'll then use these numbers to pick the
4004 * statistics object that best matches the clauses.
4005 */
4006 foreach(lc2, *varinfos)
4007 {
4008 ListCell *lc3;
4009 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4011
4012 Assert(varinfo->rel == rel);
4013
4014 /* simple Var, search in statistics keys directly */
4015 if (IsA(varinfo->var, Var))
4016 {
4017 attnum = ((Var *) varinfo->var)->varattno;
4018
4019 /*
4020 * Ignore system attributes - we don't support statistics on
4021 * them, so can't match them (and it'd fail as the values are
4022 * negative).
4023 */
4025 continue;
4026
4027 if (bms_is_member(attnum, info->keys))
4028 nshared_vars++;
4029
4030 continue;
4031 }
4032
4033 /* expression - see if it's in the statistics object */
4034 foreach(lc3, info->exprs)
4035 {
4036 Node *expr = (Node *) lfirst(lc3);
4037
4038 if (equal(varinfo->var, expr))
4039 {
4040 nshared_exprs++;
4041 break;
4042 }
4043 }
4044 }
4045
4046 if (nshared_vars + nshared_exprs < 2)
4047 continue;
4048
4049 /*
4050 * Does this statistics object match more columns than the currently
4051 * best object? If so, use this one instead.
4052 *
4053 * XXX This should break ties using name of the object, or something
4054 * like that, to make the outcome stable.
4055 */
4056 if ((nshared_exprs > nmatches_exprs) ||
4057 (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
4058 {
4059 statOid = info->statOid;
4060 nmatches_vars = nshared_vars;
4061 nmatches_exprs = nshared_exprs;
4062 matched_info = info;
4063 }
4064 }
4065
4066 /* No match? */
4067 if (statOid == InvalidOid)
4068 return false;
4069
4070 Assert(nmatches_vars + nmatches_exprs > 1);
4071
4072 stats = statext_ndistinct_load(statOid, rte->inh);
4073
4074 /*
4075 * If we have a match, search it for the specific item that matches (there
4076 * must be one), and construct the output values.
4077 */
4078 if (stats)
4079 {
4080 int i;
4081 List *newlist = NIL;
4082 MVNDistinctItem *item = NULL;
4083 ListCell *lc2;
4084 Bitmapset *matched = NULL;
4085 AttrNumber attnum_offset;
4086
4087 /*
4088 * How much we need to offset the attnums? If there are no
4089 * expressions, no offset is needed. Otherwise offset enough to move
4090 * the lowest one (which is equal to number of expressions) to 1.
4091 */
4092 if (matched_info->exprs)
4093 attnum_offset = (list_length(matched_info->exprs) + 1);
4094 else
4095 attnum_offset = 0;
4096
4097 /* see what actually matched */
4098 foreach(lc2, *varinfos)
4099 {
4100 ListCell *lc3;
4101 int idx;
4102 bool found = false;
4103
4104 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4105
4106 /*
4107 * Process a simple Var expression, by matching it to keys
4108 * directly. If there's a matching expression, we'll try matching
4109 * it later.
4110 */
4111 if (IsA(varinfo->var, Var))
4112 {
4113 AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4114
4115 /*
4116 * Ignore expressions on system attributes. Can't rely on the
4117 * bms check for negative values.
4118 */
4120 continue;
4121
4122 /* Is the variable covered by the statistics object? */
4123 if (!bms_is_member(attnum, matched_info->keys))
4124 continue;
4125
4126 attnum = attnum + attnum_offset;
4127
4128 /* ensure sufficient offset */
4130
4131 matched = bms_add_member(matched, attnum);
4132
4133 found = true;
4134 }
4135
4136 /*
4137 * XXX Maybe we should allow searching the expressions even if we
4138 * found an attribute matching the expression? That would handle
4139 * trivial expressions like "(a)" but it seems fairly useless.
4140 */
4141 if (found)
4142 continue;
4143
4144 /* expression - see if it's in the statistics object */
4145 idx = 0;
4146 foreach(lc3, matched_info->exprs)
4147 {
4148 Node *expr = (Node *) lfirst(lc3);
4149
4150 if (equal(varinfo->var, expr))
4151 {
4152 AttrNumber attnum = -(idx + 1);
4153
4154 attnum = attnum + attnum_offset;
4155
4156 /* ensure sufficient offset */
4158
4159 matched = bms_add_member(matched, attnum);
4160
4161 /* there should be just one matching expression */
4162 break;
4163 }
4164
4165 idx++;
4166 }
4167 }
4168
4169 /* Find the specific item that exactly matches the combination */
4170 for (i = 0; i < stats->nitems; i++)
4171 {
4172 int j;
4173 MVNDistinctItem *tmpitem = &stats->items[i];
4174
4175 if (tmpitem->nattributes != bms_num_members(matched))
4176 continue;
4177
4178 /* assume it's the right item */
4179 item = tmpitem;
4180
4181 /* check that all item attributes/expressions fit the match */
4182 for (j = 0; j < tmpitem->nattributes; j++)
4183 {
4184 AttrNumber attnum = tmpitem->attributes[j];
4185
4186 /*
4187 * Thanks to how we constructed the matched bitmap above, we
4188 * can just offset all attnums the same way.
4189 */
4190 attnum = attnum + attnum_offset;
4191
4192 if (!bms_is_member(attnum, matched))
4193 {
4194 /* nah, it's not this item */
4195 item = NULL;
4196 break;
4197 }
4198 }
4199
4200 /*
4201 * If the item has all the matched attributes, we know it's the
4202 * right one - there can't be a better one. matching more.
4203 */
4204 if (item)
4205 break;
4206 }
4207
4208 /*
4209 * Make sure we found an item. There has to be one, because ndistinct
4210 * statistics includes all combinations of attributes.
4211 */
4212 if (!item)
4213 elog(ERROR, "corrupt MVNDistinct entry");
4214
4215 /* Form the output varinfo list, keeping only unmatched ones */
4216 foreach(lc, *varinfos)
4217 {
4218 GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
4219 ListCell *lc3;
4220 bool found = false;
4221
4222 /*
4223 * Let's look at plain variables first, because it's the most
4224 * common case and the check is quite cheap. We can simply get the
4225 * attnum and check (with an offset) matched bitmap.
4226 */
4227 if (IsA(varinfo->var, Var))
4228 {
4229 AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4230
4231 /*
4232 * If it's a system attribute, we're done. We don't support
4233 * extended statistics on system attributes, so it's clearly
4234 * not matched. Just keep the expression and continue.
4235 */
4237 {
4238 newlist = lappend(newlist, varinfo);
4239 continue;
4240 }
4241
4242 /* apply the same offset as above */
4243 attnum += attnum_offset;
4244
4245 /* if it's not matched, keep the varinfo */
4246 if (!bms_is_member(attnum, matched))
4247 newlist = lappend(newlist, varinfo);
4248
4249 /* The rest of the loop deals with complex expressions. */
4250 continue;
4251 }
4252
4253 /*
4254 * Process complex expressions, not just simple Vars.
4255 *
4256 * First, we search for an exact match of an expression. If we
4257 * find one, we can just discard the whole GroupVarInfo, with all
4258 * the variables we extracted from it.
4259 *
4260 * Otherwise we inspect the individual vars, and try matching it
4261 * to variables in the item.
4262 */
4263 foreach(lc3, matched_info->exprs)
4264 {
4265 Node *expr = (Node *) lfirst(lc3);
4266
4267 if (equal(varinfo->var, expr))
4268 {
4269 found = true;
4270 break;
4271 }
4272 }
4273
4274 /* found exact match, skip */
4275 if (found)
4276 continue;
4277
4278 newlist = lappend(newlist, varinfo);
4279 }
4280
4281 *varinfos = newlist;
4282 *ndistinct = item->ndistinct;
4283 return true;
4284 }
4285
4286 return false;
4287}
4288
4289/*
4290 * convert_to_scalar
4291 * Convert non-NULL values of the indicated types to the comparison
4292 * scale needed by scalarineqsel().
4293 * Returns "true" if successful.
4294 *
4295 * XXX this routine is a hack: ideally we should look up the conversion
4296 * subroutines in pg_type.
4297 *
4298 * All numeric datatypes are simply converted to their equivalent
4299 * "double" values. (NUMERIC values that are outside the range of "double"
4300 * are clamped to +/- HUGE_VAL.)
4301 *
4302 * String datatypes are converted by convert_string_to_scalar(),
4303 * which is explained below. The reason why this routine deals with
4304 * three values at a time, not just one, is that we need it for strings.
4305 *
4306 * The bytea datatype is just enough different from strings that it has
4307 * to be treated separately.
4308 *
4309 * The several datatypes representing absolute times are all converted
4310 * to Timestamp, which is actually an int64, and then we promote that to
4311 * a double. Note this will give correct results even for the "special"
4312 * values of Timestamp, since those are chosen to compare correctly;
4313 * see timestamp_cmp.
4314 *
4315 * The several datatypes representing relative times (intervals) are all
4316 * converted to measurements expressed in seconds.
4317 */
4318static bool
4319convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue,
4320 Datum lobound, Datum hibound, Oid boundstypid,
4321 double *scaledlobound, double *scaledhibound)
4322{
4323 bool failure = false;
4324
4325 /*
4326 * Both the valuetypid and the boundstypid should exactly match the
4327 * declared input type(s) of the operator we are invoked for. However,
4328 * extensions might try to use scalarineqsel as estimator for operators
4329 * with input type(s) we don't handle here; in such cases, we want to
4330 * return false, not fail. In any case, we mustn't assume that valuetypid
4331 * and boundstypid are identical.
4332 *
4333 * XXX The histogram we are interpolating between points of could belong
4334 * to a column that's only binary-compatible with the declared type. In
4335 * essence we are assuming that the semantics of binary-compatible types
4336 * are enough alike that we can use a histogram generated with one type's
4337 * operators to estimate selectivity for the other's. This is outright
4338 * wrong in some cases --- in particular signed versus unsigned
4339 * interpretation could trip us up. But it's useful enough in the
4340 * majority of cases that we do it anyway. Should think about more
4341 * rigorous ways to do it.
4342 */
4343 switch (valuetypid)
4344 {
4345 /*
4346 * Built-in numeric types
4347 */
4348 case BOOLOID:
4349 case INT2OID:
4350 case INT4OID:
4351 case INT8OID:
4352 case FLOAT4OID:
4353 case FLOAT8OID:
4354 case NUMERICOID:
4355 case OIDOID:
4356 case REGPROCOID:
4357 case REGPROCEDUREOID:
4358 case REGOPEROID:
4359 case REGOPERATOROID:
4360 case REGCLASSOID:
4361 case REGTYPEOID:
4362 case REGCOLLATIONOID:
4363 case REGCONFIGOID:
4364 case REGDICTIONARYOID:
4365 case REGROLEOID:
4366 case REGNAMESPACEOID:
4367 *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4368 &failure);
4369 *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4370 &failure);
4371 *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4372 &failure);
4373 return !failure;
4374
4375 /*
4376 * Built-in string types
4377 */
4378 case CHAROID:
4379 case BPCHAROID:
4380 case VARCHAROID:
4381 case TEXTOID:
4382 case NAMEOID:
4383 {
4384 char *valstr = convert_string_datum(value, valuetypid,
4385 collid, &failure);
4386 char *lostr = convert_string_datum(lobound, boundstypid,
4387 collid, &failure);
4388 char *histr = convert_string_datum(hibound, boundstypid,
4389 collid, &failure);
4390
4391 /*
4392 * Bail out if any of the values is not of string type. We
4393 * might leak converted strings for the other value(s), but
4394 * that's not worth troubling over.
4395 */
4396 if (failure)
4397 return false;
4398
4399 convert_string_to_scalar(valstr, scaledvalue,
4400 lostr, scaledlobound,
4401 histr, scaledhibound);
4402 pfree(valstr);
4403 pfree(lostr);
4404 pfree(histr);
4405 return true;
4406 }
4407
4408 /*
4409 * Built-in bytea type
4410 */
4411 case BYTEAOID:
4412 {
4413 /* We only support bytea vs bytea comparison */
4414 if (boundstypid != BYTEAOID)
4415 return false;
4416 convert_bytea_to_scalar(value, scaledvalue,
4417 lobound, scaledlobound,
4418 hibound, scaledhibound);
4419 return true;
4420 }
4421
4422 /*
4423 * Built-in time types
4424 */
4425 case TIMESTAMPOID:
4426 case TIMESTAMPTZOID:
4427 case DATEOID:
4428 case INTERVALOID:
4429 case TIMEOID:
4430 case TIMETZOID:
4431 *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
4432 &failure);
4433 *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
4434 &failure);
4435 *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
4436 &failure);
4437 return !failure;
4438
4439 /*
4440 * Built-in network types
4441 */
4442 case INETOID:
4443 case CIDROID:
4444 case MACADDROID:
4445 case MACADDR8OID:
4446 *scaledvalue = convert_network_to_scalar(value, valuetypid,
4447 &failure);
4448 *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
4449 &failure);
4450 *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
4451 &failure);
4452 return !failure;
4453 }
4454 /* Don't know how to convert */
4455 *scaledvalue = *scaledlobound = *scaledhibound = 0;
4456 return false;
4457}
4458
4459/*
4460 * Do convert_to_scalar()'s work for any numeric data type.
4461 *
4462 * On failure (e.g., unsupported typid), set *failure to true;
4463 * otherwise, that variable is not changed.
4464 */
4465static double
4467{
4468 switch (typid)
4469 {
4470 case BOOLOID:
4471 return (double) DatumGetBool(value);
4472 case INT2OID:
4473 return (double) DatumGetInt16(value);
4474 case INT4OID:
4475 return (double) DatumGetInt32(value);
4476 case INT8OID:
4477 return (double) DatumGetInt64(value);
4478 case FLOAT4OID:
4479 return (double) DatumGetFloat4(value);
4480 case FLOAT8OID:
4481 return (double) DatumGetFloat8(value);
4482 case NUMERICOID:
4483 /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4484 return (double)
4486 value));
4487 case OIDOID:
4488 case REGPROCOID:
4489 case REGPROCEDUREOID:
4490 case REGOPEROID:
4491 case REGOPERATOROID:
4492 case REGCLASSOID:
4493 case REGTYPEOID:
4494 case REGCOLLATIONOID:
4495 case REGCONFIGOID:
4496 case REGDICTIONARYOID:
4497 case REGROLEOID:
4498 case REGNAMESPACEOID:
4499 /* we can treat OIDs as integers... */
4500 return (double) DatumGetObjectId(value);
4501 }
4502
4503 *failure = true;
4504 return 0;
4505}
4506
4507/*
4508 * Do convert_to_scalar()'s work for any character-string data type.
4509 *
4510 * String datatypes are converted to a scale that ranges from 0 to 1,
4511 * where we visualize the bytes of the string as fractional digits.
4512 *
4513 * We do not want the base to be 256, however, since that tends to
4514 * generate inflated selectivity estimates; few databases will have
4515 * occurrences of all 256 possible byte values at each position.
4516 * Instead, use the smallest and largest byte values seen in the bounds
4517 * as the estimated range for each byte, after some fudging to deal with
4518 * the fact that we probably aren't going to see the full range that way.
4519 *
4520 * An additional refinement is that we discard any common prefix of the
4521 * three strings before computing the scaled values. This allows us to
4522 * "zoom in" when we encounter a narrow data range. An example is a phone
4523 * number database where all the values begin with the same area code.
4524 * (Actually, the bounds will be adjacent histogram-bin-boundary values,
4525 * so this is more likely to happen than you might think.)
4526 */
4527static void
4529 double *scaledvalue,
4530 char *lobound,
4531 double *scaledlobound,
4532 char *hibound,
4533 double *scaledhibound)
4534{
4535 int rangelo,
4536 rangehi;
4537 char *sptr;
4538
4539 rangelo = rangehi = (unsigned char) hibound[0];
4540 for (sptr = lobound; *sptr; sptr++)
4541 {
4542 if (rangelo > (unsigned char) *sptr)
4543 rangelo = (unsigned char) *sptr;
4544 if (rangehi < (unsigned char) *sptr)
4545 rangehi = (unsigned char) *sptr;
4546 }
4547 for (sptr = hibound; *sptr; sptr++)
4548 {
4549 if (rangelo > (unsigned char) *sptr)
4550 rangelo = (unsigned char) *sptr;
4551 if (rangehi < (unsigned char) *sptr)
4552 rangehi = (unsigned char) *sptr;
4553 }
4554 /* If range includes any upper-case ASCII chars, make it include all */
4555 if (rangelo <= 'Z' && rangehi >= 'A')
4556 {
4557 if (rangelo > 'A')
4558 rangelo = 'A';
4559 if (rangehi < 'Z')
4560 rangehi = 'Z';
4561 }
4562 /* Ditto lower-case */
4563 if (rangelo <= 'z' && rangehi >= 'a')
4564 {
4565 if (rangelo > 'a')
4566 rangelo = 'a';
4567 if (rangehi < 'z')
4568 rangehi = 'z';
4569 }
4570 /* Ditto digits */
4571 if (rangelo <= '9' && rangehi >= '0')
4572 {
4573 if (rangelo > '0')
4574 rangelo = '0';
4575 if (rangehi < '9')
4576 rangehi = '9';
4577 }
4578
4579 /*
4580 * If range includes less than 10 chars, assume we have not got enough
4581 * data, and make it include regular ASCII set.
4582 */
4583 if (rangehi - rangelo < 9)
4584 {
4585 rangelo = ' ';
4586 rangehi = 127;
4587 }
4588
4589 /*
4590 * Now strip any common prefix of the three strings.
4591 */
4592 while (*lobound)
4593 {
4594 if (*lobound != *hibound || *lobound != *value)
4595 break;
4596 lobound++, hibound++, value++;
4597 }
4598
4599 /*
4600 * Now we can do the conversions.
4601 */
4602 *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4603 *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4604 *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4605}
4606
4607static double
4608convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
4609{
4610 int slen = strlen(value);
4611 double num,
4612 denom,
4613 base;
4614
4615 if (slen <= 0)
4616 return 0.0; /* empty string has scalar value 0 */
4617
4618 /*
4619 * There seems little point in considering more than a dozen bytes from
4620 * the string. Since base is at least 10, that will give us nominal
4621 * resolution of at least 12 decimal digits, which is surely far more
4622 * precision than this estimation technique has got anyway (especially in
4623 * non-C locales). Also, even with the maximum possible base of 256, this
4624 * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4625 * overflow on any known machine.
4626 */
4627 if (slen > 12)
4628 slen = 12;
4629
4630 /* Convert initial characters to fraction */
4631 base = rangehi - rangelo + 1;
4632 num = 0.0;
4633 denom = base;
4634 while (slen-- > 0)
4635 {
4636 int ch = (unsigned char) *value++;
4637
4638 if (ch < rangelo)
4639 ch = rangelo - 1;
4640 else if (ch > rangehi)
4641 ch = rangehi + 1;
4642 num += ((double) (ch - rangelo)) / denom;
4643 denom *= base;
4644 }
4645
4646 return num;
4647}
4648
4649/*
4650 * Convert a string-type Datum into a palloc'd, null-terminated string.
4651 *
4652 * On failure (e.g., unsupported typid), set *failure to true;
4653 * otherwise, that variable is not changed. (We'll return NULL on failure.)
4654 *
4655 * When using a non-C locale, we must pass the string through pg_strxfrm()
4656 * before continuing, so as to generate correct locale-specific results.
4657 */
4658static char *
4660{
4661 char *val;
4662 pg_locale_t mylocale;
4663
4664 switch (typid)
4665 {
4666 case CHAROID:
4667 val = (char *) palloc(2);
4668 val[0] = DatumGetChar(value);
4669 val[1] = '\0';
4670 break;
4671 case BPCHAROID:
4672 case VARCHAROID:
4673 case TEXTOID:
4675 break;
4676 case NAMEOID:
4677 {
4679
4680 val = pstrdup(NameStr(*nm));
4681 break;
4682 }
4683 default:
4684 *failure = true;
4685 return NULL;
4686 }
4687
4689
4690 if (!mylocale->collate_is_c)
4691 {
4692 char *xfrmstr;
4693 size_t xfrmlen;
4694 size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4695
4696 /*
4697 * XXX: We could guess at a suitable output buffer size and only call
4698 * pg_strxfrm() twice if our guess is too small.
4699 *
4700 * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4701 * bogus data or set an error. This is not really a problem unless it
4702 * crashes since it will only give an estimation error and nothing
4703 * fatal.
4704 *
4705 * XXX: we do not check pg_strxfrm_enabled(). On some platforms and in
4706 * some cases, libc strxfrm() may return the wrong results, but that
4707 * will only lead to an estimation error.
4708 */
4709 xfrmlen = pg_strxfrm(NULL, val, 0, mylocale);
4710#ifdef WIN32
4711
4712 /*
4713 * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4714 * of trying to allocate this much memory (and fail), just return the
4715 * original string unmodified as if we were in the C locale.
4716 */
4717 if (xfrmlen == INT_MAX)
4718 return val;
4719#endif
4720 xfrmstr = (char *) palloc(xfrmlen + 1);
4721 xfrmlen2 = pg_strxfrm(xfrmstr, val, xfrmlen + 1, mylocale);
4722
4723 /*
4724 * Some systems (e.g., glibc) can return a smaller value from the
4725 * second call than the first; thus the Assert must be <= not ==.
4726 */
4727 Assert(xfrmlen2 <= xfrmlen);
4728 pfree(val);
4729 val = xfrmstr;
4730 }
4731
4732 return val;
4733}
4734
4735/*
4736 * Do convert_to_scalar()'s work for any bytea data type.
4737 *
4738 * Very similar to convert_string_to_scalar except we can't assume
4739 * null-termination and therefore pass explicit lengths around.
4740 *
4741 * Also, assumptions about likely "normal" ranges of characters have been
4742 * removed - a data range of 0..255 is always used, for now. (Perhaps
4743 * someday we will add information about actual byte data range to
4744 * pg_statistic.)
4745 */
4746static void
4748 double *scaledvalue,
4749 Datum lobound,
4750 double *scaledlobound,
4751 Datum hibound,
4752 double *scaledhibound)
4753{
4754 bytea *valuep = DatumGetByteaPP(value);
4755 bytea *loboundp = DatumGetByteaPP(lobound);
4756 bytea *hiboundp = DatumGetByteaPP(hibound);
4757 int rangelo,
4758 rangehi,
4759 valuelen = VARSIZE_ANY_EXHDR(valuep),
4760 loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4761 hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4762 i,
4763 minlen;
4764 unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4765 unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4766 unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4767
4768 /*
4769 * Assume bytea data is uniformly distributed across all byte values.
4770 */
4771 rangelo = 0;
4772 rangehi = 255;
4773
4774 /*
4775 * Now strip any common prefix of the three strings.
4776 */
4777 minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4778 for (i = 0; i < minlen; i++)
4779 {
4780 if (*lostr != *histr || *lostr != *valstr)
4781 break;
4782 lostr++, histr++, valstr++;
4783 loboundlen--, hiboundlen--, valuelen--;
4784 }
4785
4786 /*
4787 * Now we can do the conversions.
4788 */
4789 *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4790 *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4791 *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4792}
4793
4794static double
4795convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
4796 int rangelo, int rangehi)
4797{
4798 double num,
4799 denom,
4800 base;
4801
4802 if (valuelen <= 0)
4803 return 0.0; /* empty string has scalar value 0 */
4804
4805 /*
4806 * Since base is 256, need not consider more than about 10 chars (even
4807 * this many seems like overkill)
4808 */
4809 if (valuelen > 10)
4810 valuelen = 10;
4811
4812 /* Convert initial characters to fraction */
4813 base = rangehi - rangelo + 1;
4814 num = 0.0;
4815 denom = base;
4816 while (valuelen-- > 0)
4817 {
4818 int ch = *value++;
4819
4820 if (ch < rangelo)
4821 ch = rangelo - 1;
4822 else if (ch > rangehi)
4823 ch = rangehi + 1;
4824 num += ((double) (ch - rangelo)) / denom;
4825 denom *= base;
4826 }
4827
4828 return num;
4829}
4830
4831/*
4832 * Do convert_to_scalar()'s work for any timevalue data type.
4833 *
4834 * On failure (e.g., unsupported typid), set *failure to true;
4835 * otherwise, that variable is not changed.
4836 */
4837static double
4839{
4840 switch (typid)
4841 {
4842 case TIMESTAMPOID:
4843 return DatumGetTimestamp(value);
4844 case TIMESTAMPTZOID:
4845 return DatumGetTimestampTz(value);
4846 case DATEOID:
4848 case INTERVALOID:
4849 {
4851
4852 /*
4853 * Convert the month part of Interval to days using assumed
4854 * average month length of 365.25/12.0 days. Not too
4855 * accurate, but plenty good enough for our purposes.
4856 *
4857 * This also works for infinite intervals, which just have all
4858 * fields set to INT_MIN/INT_MAX, and so will produce a result
4859 * smaller/larger than any finite interval.
4860 */
4861 return interval->time + interval->day * (double) USECS_PER_DAY +
4863 }
4864 case TIMEOID:
4865 return DatumGetTimeADT(value);
4866 case TIMETZOID:
4867 {
4869
4870 /* use GMT-equivalent time */
4871 return (double) (timetz->time + (timetz->zone * 1000000.0));
4872 }
4873 }
4874
4875 *failure = true;
4876 return 0;
4877}
4878
4879
4880/*
4881 * get_restriction_variable
4882 * Examine the args of a restriction clause to see if it's of the
4883 * form (variable op pseudoconstant) or (pseudoconstant op variable),
4884 * where "variable" could be either a Var or an expression in vars of a
4885 * single relation. If so, extract information about the variable,
4886 * and also indicate which side it was on and the other argument.
4887 *
4888 * Inputs:
4889 * root: the planner info
4890 * args: clause argument list
4891 * varRelid: see specs for restriction selectivity functions
4892 *
4893 * Outputs: (these are valid only if true is returned)
4894 * *vardata: gets information about variable (see examine_variable)
4895 * *other: gets other clause argument, aggressively reduced to a constant
4896 * *varonleft: set true if variable is on the left, false if on the right
4897 *
4898 * Returns true if a variable is identified, otherwise false.
4899 *
4900 * Note: if there are Vars on both sides of the clause, we must fail, because
4901 * callers are expecting that the other side will act like a pseudoconstant.
4902 */
4903bool
4905 VariableStatData *vardata, Node **other,
4906 bool *varonleft)
4907{
4908 Node *left,
4909 *right;
4910 VariableStatData rdata;
4911
4912 /* Fail if not a binary opclause (probably shouldn't happen) */
4913 if (list_length(args) != 2)
4914 return false;
4915
4916 left = (Node *) linitial(args);
4917 right = (Node *) lsecond(args);
4918
4919 /*
4920 * Examine both sides. Note that when varRelid is nonzero, Vars of other
4921 * relations will be treated as pseudoconstants.
4922 */
4923 examine_variable(root, left, varRelid, vardata);
4924 examine_variable(root, right, varRelid, &rdata);
4925
4926 /*
4927 * If one side is a variable and the other not, we win.
4928 */
4929 if (vardata->rel && rdata.rel == NULL)
4930 {
4931 *varonleft = true;
4932 *other = estimate_expression_value(root, rdata.var);
4933 /* Assume we need no ReleaseVariableStats(rdata) here */
4934 return true;
4935 }
4936
4937 if (vardata->rel == NULL && rdata.rel)
4938 {
4939 *varonleft = false;
4940 *other = estimate_expression_value(root, vardata->var);
4941 /* Assume we need no ReleaseVariableStats(*vardata) here */
4942 *vardata = rdata;
4943 return true;
4944 }
4945
4946 /* Oops, clause has wrong structure (probably var op var) */
4947 ReleaseVariableStats(*vardata);
4948 ReleaseVariableStats(rdata);
4949
4950 return false;
4951}
4952
4953/*
4954 * get_join_variables
4955 * Apply examine_variable() to each side of a join clause.
4956 * Also, attempt to identify whether the join clause has the same
4957 * or reversed sense compared to the SpecialJoinInfo.
4958 *
4959 * We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4960 * or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4961 * where we can't tell for sure, we default to assuming it's normal.
4962 */
4963void
4965 VariableStatData *vardata1, VariableStatData *vardata2,
4966 bool *join_is_reversed)
4967{
4968 Node *left,
4969 *right;
4970
4971 if (list_length(args) != 2)
4972 elog(ERROR, "join operator should take two arguments");
4973
4974 left = (Node *) linitial(args);
4975 right = (Node *) lsecond(args);
4976
4977 examine_variable(root, left, 0, vardata1);
4978 examine_variable(root, right, 0, vardata2);
4979
4980 if (vardata1->rel &&
4981 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4982 *join_is_reversed = true; /* var1 is on RHS */
4983 else if (vardata2->rel &&
4984 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4985 *join_is_reversed = true; /* var2 is on LHS */
4986 else
4987 *join_is_reversed = false;
4988}
4989
4990/* statext_expressions_load copies the tuple, so just pfree it. */
4991static void
4993{
4994 pfree(tuple);
4995}
4996
4997/*
4998 * examine_variable
4999 * Try to look up statistical data about an expression.
5000 * Fill in a VariableStatData struct to describe the expression.
5001 *
5002 * Inputs:
5003 * root: the planner info
5004 * node: the expression tree to examine
5005 * varRelid: see specs for restriction selectivity functions
5006 *
5007 * Outputs: *vardata is filled as follows:
5008 * var: the input expression (with any binary relabeling stripped, if
5009 * it is or contains a variable; but otherwise the type is preserved)
5010 * rel: RelOptInfo for relation containing variable; NULL if expression
5011 * contains no Vars (NOTE this could point to a RelOptInfo of a
5012 * subquery, not one in the current query).
5013 * statsTuple: the pg_statistic entry for the variable, if one exists;
5014 * otherwise NULL.
5015 * freefunc: pointer to a function to release statsTuple with.
5016 * vartype: exposed type of the expression; this should always match
5017 * the declared input type of the operator we are estimating for.
5018 * atttype, atttypmod: actual type/typmod of the "var" expression. This is
5019 * commonly the same as the exposed type of the variable argument,
5020 * but can be different in binary-compatible-type cases.
5021 * isunique: true if we were able to match the var to a unique index or a
5022 * single-column DISTINCT clause, implying its values are unique for
5023 * this query. (Caution: this should be trusted for statistical
5024 * purposes only, since we do not check indimmediate nor verify that
5025 * the exact same definition of equality applies.)
5026 * acl_ok: true if current user has permission to read the column(s)
5027 * underlying the pg_statistic entry. This is consulted by
5028 * statistic_proc_security_check().
5029 *
5030 * Caller is responsible for doing ReleaseVariableStats() before exiting.
5031 */
5032void
5034 VariableStatData *vardata)
5035{
5036 Node *basenode;
5037 Relids varnos;
5038 Relids basevarnos;
5039 RelOptInfo *onerel;
5040
5041 /* Make sure we don't return dangling pointers in vardata */
5042 MemSet(vardata, 0, sizeof(VariableStatData));
5043
5044 /* Save the exposed type of the expression */
5045 vardata->vartype = exprType(node);
5046
5047 /* Look inside any binary-compatible relabeling */
5048
5049 if (IsA(node, RelabelType))
5050 basenode = (Node *) ((RelabelType *) node)->arg;
5051 else
5052 basenode = node;
5053
5054 /* Fast path for a simple Var */
5055
5056 if (IsA(basenode, Var) &&
5057 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5058 {
5059 Var *var = (Var *) basenode;
5060
5061 /* Set up result fields other than the stats tuple */
5062 vardata->var = basenode; /* return Var without relabeling */
5063 vardata->rel = find_base_rel(root, var->varno);
5064 vardata->atttype = var->vartype;
5065 vardata->atttypmod = var->vartypmod;
5066 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5067
5068 /* Try to locate some stats */
5069 examine_simple_variable(root, var, vardata);
5070
5071 return;
5072 }
5073
5074 /*
5075 * Okay, it's a more complicated expression. Determine variable
5076 * membership. Note that when varRelid isn't zero, only vars of that
5077 * relation are considered "real" vars.
5078 */
5079 varnos = pull_varnos(root, basenode);
5080 basevarnos = bms_difference(varnos, root->outer_join_rels);
5081
5082 onerel = NULL;
5083
5084 if (bms_is_empty(basevarnos))
5085 {
5086 /* No Vars at all ... must be pseudo-constant clause */
5087 }
5088 else
5089 {
5090 int relid;
5091
5092 /* Check if the expression is in vars of a single base relation */
5093 if (bms_get_singleton_member(basevarnos, &relid))
5094 {
5095 if (varRelid == 0 || varRelid == relid)
5096 {
5097 onerel = find_base_rel(root, relid);
5098 vardata->rel = onerel;
5099 node = basenode; /* strip any relabeling */
5100 }
5101 /* else treat it as a constant */
5102 }
5103 else
5104 {
5105 /* varnos has multiple relids */
5106 if (varRelid == 0)
5107 {
5108 /* treat it as a variable of a join relation */
5109 vardata->rel = find_join_rel(root, varnos);
5110 node = basenode; /* strip any relabeling */
5111 }
5112 else if (bms_is_member(varRelid, varnos))
5113 {
5114 /* ignore the vars belonging to other relations */
5115 vardata->rel = find_base_rel(root, varRelid);
5116 node = basenode; /* strip any relabeling */
5117 /* note: no point in expressional-index search here */
5118 }
5119 /* else treat it as a constant */
5120 }
5121 }
5122
5123 bms_free(basevarnos);
5124
5125 vardata->var = node;
5126 vardata->atttype = exprType(node);
5127 vardata->atttypmod = exprTypmod(node);
5128
5129 if (onerel)
5130 {
5131 /*
5132 * We have an expression in vars of a single relation. Try to match
5133 * it to expressional index columns, in hopes of finding some
5134 * statistics.
5135 *
5136 * Note that we consider all index columns including INCLUDE columns,
5137 * since there could be stats for such columns. But the test for
5138 * uniqueness needs to be warier.
5139 *
5140 * XXX it's conceivable that there are multiple matches with different
5141 * index opfamilies; if so, we need to pick one that matches the
5142 * operator we are estimating for. FIXME later.
5143 */
5144 ListCell *ilist;
5145 ListCell *slist;
5146 Oid userid;
5147
5148 /*
5149 * The nullingrels bits within the expression could prevent us from
5150 * matching it to expressional index columns or to the expressions in
5151 * extended statistics. So strip them out first.
5152 */
5153 if (bms_overlap(varnos, root->outer_join_rels))
5154 node = remove_nulling_relids(node, root->outer_join_rels, NULL);
5155
5156 /*
5157 * Determine the user ID to use for privilege checks: either
5158 * onerel->userid if it's set (e.g., in case we're accessing the table
5159 * via a view), or the current user otherwise.
5160 *
5161 * If we drill down to child relations, we keep using the same userid:
5162 * it's going to be the same anyway, due to how we set up the relation
5163 * tree (q.v. build_simple_rel).
5164 */
5165 userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
5166
5167 foreach(ilist, onerel->indexlist)
5168 {
5169 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5170 ListCell *indexpr_item;
5171 int pos;
5172
5173 indexpr_item = list_head(index->indexprs);
5174 if (indexpr_item == NULL)
5175 continue; /* no expressions here... */
5176
5177 for (pos = 0; pos < index->ncolumns; pos++)
5178 {
5179 if (index->indexkeys[pos] == 0)
5180 {
5181 Node *indexkey;
5182
5183 if (indexpr_item == NULL)
5184 elog(ERROR, "too few entries in indexprs list");
5185 indexkey = (Node *) lfirst(indexpr_item);
5186 if (indexkey && IsA(indexkey, RelabelType))
5187 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5188 if (equal(node, indexkey))
5189 {
5190 /*
5191 * Found a match ... is it a unique index? Tests here
5192 * should match has_unique_index().
5193 */
5194 if (index->unique &&
5195 index->nkeycolumns == 1 &&
5196 pos == 0 &&
5197 (index->indpred == NIL || index->predOK))
5198 vardata->isunique = true;
5199
5200 /*
5201 * Has it got stats? We only consider stats for
5202 * non-partial indexes, since partial indexes probably
5203 * don't reflect whole-relation statistics; the above
5204 * check for uniqueness is the only info we take from
5205 * a partial index.
5206 *
5207 * An index stats hook, however, must make its own
5208 * decisions about what to do with partial indexes.
5209 */
5211 (*get_index_stats_hook) (root, index->indexoid,
5212 pos + 1, vardata))
5213 {
5214 /*
5215 * The hook took control of acquiring a stats
5216 * tuple. If it did supply a tuple, it'd better
5217 * have supplied a freefunc.
5218 */
5219 if (HeapTupleIsValid(vardata->statsTuple) &&
5220 !vardata->freefunc)
5221 elog(ERROR, "no function provided to release variable stats with");
5222 }
5223 else if (index->indpred == NIL)
5224 {
5225 vardata->statsTuple =
5226 SearchSysCache3(STATRELATTINH,
5227 ObjectIdGetDatum(index->indexoid),
5228 Int16GetDatum(pos + 1),
5229 BoolGetDatum(false));
5230 vardata->freefunc = ReleaseSysCache;
5231
5232 if (HeapTupleIsValid(vardata->statsTuple))
5233 {
5234 /* Get index's table for permission check */
5235 RangeTblEntry *rte;
5236
5237 rte = planner_rt_fetch(index->rel->relid, root);
5238 Assert(rte->rtekind == RTE_RELATION);
5239
5240 /*
5241 * For simplicity, we insist on the whole
5242 * table being selectable, rather than trying
5243 * to identify which column(s) the index
5244 * depends on. Also require all rows to be
5245 * selectable --- there must be no
5246 * securityQuals from security barrier views
5247 * or RLS policies.
5248 */
5249 vardata->acl_ok =
5250 rte->securityQuals == NIL &&
5251 (pg_class_aclcheck(rte->relid, userid,
5253
5254 /*
5255 * If the user doesn't have permissions to
5256 * access an inheritance child relation, check
5257 * the permissions of the table actually
5258 * mentioned in the query, since most likely
5259 * the user does have that permission. Note
5260 * that whole-table select privilege on the
5261 * parent doesn't quite guarantee that the
5262 * user could read all columns of the child.
5263 * But in practice it's unlikely that any
5264 * interesting security violation could result
5265 * from allowing access to the expression
5266 * index's stats, so we allow it anyway. See
5267 * similar code in examine_simple_variable()
5268 * for additional comments.
5269 */
5270 if (!vardata->acl_ok &&
5271 root->append_rel_array != NULL)
5272 {
5273 AppendRelInfo *appinfo;
5274 Index varno = index->rel->relid;
5275
5276 appinfo = root->append_rel_array[varno];
5277 while (appinfo &&
5279 root)->rtekind == RTE_RELATION)
5280 {
5281 varno = appinfo->parent_relid;
5282 appinfo = root->append_rel_array[varno];
5283 }
5284 if (varno != index->rel->relid)
5285 {
5286 /* Repeat access check on this rel */
5287 rte = planner_rt_fetch(varno, root);
5288 Assert(rte->rtekind == RTE_RELATION);
5289
5290 vardata->acl_ok =
5291 rte->securityQuals == NIL &&
5293 userid,
5295 }
5296 }
5297 }
5298 else
5299 {
5300 /* suppress leakproofness checks later */
5301 vardata->acl_ok = true;
5302 }
5303 }
5304 if (vardata->statsTuple)
5305 break;
5306 }
5307 indexpr_item = lnext(index->indexprs, indexpr_item);
5308 }
5309 }
5310 if (vardata->statsTuple)
5311 break;
5312 }
5313
5314 /*
5315 * Search extended statistics for one with a matching expression.
5316 * There might be multiple ones, so just grab the first one. In the
5317 * future, we might consider the statistics target (and pick the most
5318 * accurate statistics) and maybe some other parameters.
5319 */
5320 foreach(slist, onerel->statlist)
5321 {
5322 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5323 RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5324 ListCell *expr_item;
5325 int pos;
5326
5327 /*
5328 * Stop once we've found statistics for the expression (either
5329 * from extended stats, or for an index in the preceding loop).
5330 */
5331 if (vardata->statsTuple)
5332 break;
5333
5334 /* skip stats without per-expression stats */
5335 if (info->kind != STATS_EXT_EXPRESSIONS)
5336 continue;
5337
5338 /* skip stats with mismatching stxdinherit value */
5339 if (info->inherit != rte->inh)
5340 continue;
5341
5342 pos = 0;
5343 foreach(expr_item, info->exprs)
5344 {
5345 Node *expr = (Node *) lfirst(expr_item);
5346
5347 Assert(expr);
5348
5349 /* strip RelabelType before comparing it */
5350 if (expr && IsA(expr, RelabelType))
5351 expr = (Node *) ((RelabelType *) expr)->arg;
5352
5353 /* found a match, see if we can extract pg_statistic row */
5354 if (equal(node, expr))
5355 {
5356 /*
5357 * XXX Not sure if we should cache the tuple somewhere.
5358 * Now we just create a new copy every time.
5359 */
5360 vardata->statsTuple =
5361 statext_expressions_load(info->statOid, rte->inh, pos);
5362
5363 vardata->freefunc = ReleaseDummy;
5364
5365 /*
5366 * For simplicity, we insist on the whole table being
5367 * selectable, rather than trying to identify which
5368 * column(s) the statistics object depends on. Also
5369 * require all rows to be selectable --- there must be no
5370 * securityQuals from security barrier views or RLS
5371 * policies.
5372 */
5373 vardata->acl_ok =
5374 rte->securityQuals == NIL &&
5375 (pg_class_aclcheck(rte->relid, userid,
5377
5378 /*
5379 * If the user doesn't have permissions to access an
5380 * inheritance child relation, check the permissions of
5381 * the table actually mentioned in the query, since most
5382 * likely the user does have that permission. Note that
5383 * whole-table select privilege on the parent doesn't
5384 * quite guarantee that the user could read all columns of
5385 * the child. But in practice it's unlikely that any
5386 * interesting security violation could result from
5387 * allowing access to the expression stats, so we allow it
5388 * anyway. See similar code in examine_simple_variable()
5389 * for additional comments.
5390 */
5391 if (!vardata->acl_ok &&
5392 root->append_rel_array != NULL)
5393 {
5394 AppendRelInfo *appinfo;
5395 Index varno = onerel->relid;
5396
5397 appinfo = root->append_rel_array[varno];
5398 while (appinfo &&
5400 root)->rtekind == RTE_RELATION)
5401 {
5402 varno = appinfo->parent_relid;
5403 appinfo = root->append_rel_array[varno];
5404 }
5405 if (varno != onerel->relid)
5406 {
5407 /* Repeat access check on this rel */
5408 rte = planner_rt_fetch(varno, root);
5409 Assert(rte->rtekind == RTE_RELATION);
5410
5411 vardata->acl_ok =
5412 rte->securityQuals == NIL &&
5414 userid,
5416 }
5417 }
5418
5419 break;
5420 }
5421
5422 pos++;
5423 }
5424 }
5425 }
5426
5427 bms_free(varnos);
5428}
5429
5430/*
5431 * examine_simple_variable
5432 * Handle a simple Var for examine_variable
5433 *
5434 * This is split out as a subroutine so that we can recurse to deal with
5435 * Vars referencing subqueries (either sub-SELECT-in-FROM or CTE style).
5436 *
5437 * We already filled in all the fields of *vardata except for the stats tuple.
5438 */
5439static void
5441 VariableStatData *vardata)
5442{
5443 RangeTblEntry *rte = root->simple_rte_array[var->varno];
5444
5445 Assert(IsA(rte, RangeTblEntry));
5446
5448 (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
5449 {
5450 /*
5451 * The hook took control of acquiring a stats tuple. If it did supply
5452 * a tuple, it'd better have supplied a freefunc.
5453 */
5454 if (HeapTupleIsValid(vardata->statsTuple) &&
5455 !vardata->freefunc)
5456 elog(ERROR, "no function provided to release variable stats with");
5457 }
5458 else if (rte->rtekind == RTE_RELATION)
5459 {
5460 /*
5461 * Plain table or parent of an inheritance appendrel, so look up the
5462 * column in pg_statistic
5463 */
5464 vardata->statsTuple = SearchSysCache3(STATRELATTINH,
5465 ObjectIdGetDatum(rte->relid),
5466 Int16GetDatum(var->varattno),
5467 BoolGetDatum(rte->inh));
5468 vardata->freefunc = ReleaseSysCache;
5469
5470 if (HeapTupleIsValid(vardata->statsTuple))
5471 {
5472 RelOptInfo *onerel = find_base_rel_noerr(root, var->varno);
5473 Oid userid;
5474
5475 /*
5476 * Check if user has permission to read this column. We require
5477 * all rows to be accessible, so there must be no securityQuals
5478 * from security barrier views or RLS policies.
5479 *
5480 * Normally the Var will have an associated RelOptInfo from which
5481 * we can find out which userid to do the check as; but it might
5482 * not if it's a RETURNING Var for an INSERT target relation. In
5483 * that case use the RTEPermissionInfo associated with the RTE.
5484 */
5485 if (onerel)
5486 userid = onerel->userid;
5487 else
5488 {
5489 RTEPermissionInfo *perminfo;
5490
5491 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
5492 userid = perminfo->checkAsUser;
5493 }
5494 if (!OidIsValid(userid))
5495 userid = GetUserId();
5496
5497 vardata->acl_ok =
5498 rte->securityQuals == NIL &&
5499 ((pg_class_aclcheck(rte->relid, userid,
5500 ACL_SELECT) == ACLCHECK_OK) ||
5501 (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
5502 ACL_SELECT) == ACLCHECK_OK));
5503
5504 /*
5505 * If the user doesn't have permissions to access an inheritance
5506 * child relation or specifically this attribute, check the
5507 * permissions of the table/column actually mentioned in the
5508 * query, since most likely the user does have that permission
5509 * (else the query will fail at runtime), and if the user can read
5510 * the column there then he can get the values of the child table
5511 * too. To do that, we must find out which of the root parent's
5512 * attributes the child relation's attribute corresponds to.
5513 */
5514 if (!vardata->acl_ok && var->varattno > 0 &&
5515 root->append_rel_array != NULL)
5516 {
5517 AppendRelInfo *appinfo;
5518 Index varno = var->varno;
5519 int varattno = var->varattno;
5520 bool found = false;
5521
5522 appinfo = root->append_rel_array[varno];
5523
5524 /*
5525 * Partitions are mapped to their immediate parent, not the
5526 * root parent, so must be ready to walk up multiple
5527 * AppendRelInfos. But stop if we hit a parent that is not
5528 * RTE_RELATION --- that's a flattened UNION ALL subquery, not
5529 * an inheritance parent.
5530 */
5531 while (appinfo &&
5533 root)->rtekind == RTE_RELATION)
5534 {
5535 int parent_varattno;
5536
5537 found = false;
5538 if (varattno <= 0 || varattno > appinfo->num_child_cols)
5539 break; /* safety check */
5540 parent_varattno = appinfo->parent_colnos[varattno - 1];
5541 if (parent_varattno == 0)
5542 break; /* Var is local to child */
5543
5544 varno = appinfo->parent_relid;
5545 varattno = parent_varattno;
5546 found = true;
5547
5548 /* If the parent is itself a child, continue up. */
5549 appinfo = root->append_rel_array[varno];
5550 }
5551
5552 /*
5553 * In rare cases, the Var may be local to the child table, in
5554 * which case, we've got to live with having no access to this
5555 * column's stats.
5556 */
5557 if (!found)
5558 return;
5559
5560 /* Repeat the access check on this parent rel & column */
5561 rte = planner_rt_fetch(varno, root);
5562 Assert(rte->rtekind == RTE_RELATION);
5563
5564 /*
5565 * Fine to use the same userid as it's the same in all
5566 * relations of a given inheritance tree.
5567 */
5568 vardata->acl_ok =
5569 rte->securityQuals == NIL &&
5570 ((pg_class_aclcheck(rte->relid, userid,
5571 ACL_SELECT) == ACLCHECK_OK) ||
5572 (pg_attribute_aclcheck(rte->relid, varattno, userid,
5573 ACL_SELECT) == ACLCHECK_OK));
5574 }
5575 }
5576 else
5577 {
5578 /* suppress any possible leakproofness checks later */
5579 vardata->acl_ok = true;
5580 }
5581 }
5582 else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
5583 (rte->rtekind == RTE_CTE && !rte->self_reference))
5584 {
5585 /*
5586 * Plain subquery (not one that was converted to an appendrel) or
5587 * non-recursive CTE. In either case, we can try to find out what the
5588 * Var refers to within the subquery. We skip this for appendrel and
5589 * recursive-CTE cases because any column stats we did find would
5590 * likely not be very relevant.
5591 */
5592 PlannerInfo *subroot;
5593 Query *subquery;
5594 List *subtlist;
5595 TargetEntry *ste;
5596
5597 /*
5598 * Punt if it's a whole-row var rather than a plain column reference.
5599 */
5600 if (var->varattno == InvalidAttrNumber)
5601 return;
5602
5603 /*
5604 * Otherwise, find the subquery's planner subroot.
5605 */
5606 if (rte->rtekind == RTE_SUBQUERY)
5607 {
5608 RelOptInfo *rel;
5609
5610 /*
5611 * Fetch RelOptInfo for subquery. Note that we don't change the
5612 * rel returned in vardata, since caller expects it to be a rel of
5613 * the caller's query level. Because we might already be
5614 * recursing, we can't use that rel pointer either, but have to
5615 * look up the Var's rel afresh.
5616 */
5617 rel = find_base_rel(root, var->varno);
5618
5619 subroot = rel->subroot;
5620 }
5621 else
5622 {
5623 /* CTE case is more difficult */
5624 PlannerInfo *cteroot;
5625 Index levelsup;
5626 int ndx;
5627 int plan_id;
5628 ListCell *lc;
5629
5630 /*
5631 * Find the referenced CTE, and locate the subroot previously made
5632 * for it.
5633 */
5634 levelsup = rte->ctelevelsup;
5635 cteroot = root;
5636 while (levelsup-- > 0)
5637 {
5638 cteroot = cteroot->parent_root;
5639 if (!cteroot) /* shouldn't happen */
5640 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
5641 }
5642
5643 /*
5644 * Note: cte_plan_ids can be shorter than cteList, if we are still
5645 * working on planning the CTEs (ie, this is a side-reference from
5646 * another CTE). So we mustn't use forboth here.
5647 */
5648 ndx = 0;
5649 foreach(lc, cteroot->parse->cteList)
5650 {
5651 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
5652
5653 if (strcmp(cte->ctename, rte->ctename) == 0)
5654 break;
5655 ndx++;
5656 }
5657 if (lc == NULL) /* shouldn't happen */
5658 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
5659 if (ndx >= list_length(cteroot->cte_plan_ids))
5660 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
5661 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
5662 if (plan_id <= 0)
5663 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
5664 subroot = list_nth(root->glob->subroots, plan_id - 1);</