Line data Source code
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"
110 : #include "catalog/pg_statistic_ext.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"
122 : #include "parser/parse_relation.h"
123 : #include "parser/parsetree.h"
124 : #include "rewrite/rewriteManip.h"
125 : #include "statistics/statistics.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 */
148 : get_relation_stats_hook_type get_relation_stats_hook = NULL;
149 : get_index_stats_hook_type get_index_stats_hook = NULL;
150 :
151 : static double eqsel_internal(PG_FUNCTION_ARGS, bool negate);
152 : static 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,
157 : Form_pg_statistic stats1, Form_pg_statistic stats2,
158 : bool have_mcvs1, bool have_mcvs2);
159 : static 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,
164 : Form_pg_statistic stats1, Form_pg_statistic stats2,
165 : bool have_mcvs1, bool have_mcvs2,
166 : RelOptInfo *inner_rel);
167 : static bool estimate_multivariate_ndistinct(PlannerInfo *root,
168 : RelOptInfo *rel, List **varinfos, double *ndistinct);
169 : static 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);
173 : static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure);
174 : static void convert_string_to_scalar(char *value,
175 : double *scaledvalue,
176 : char *lobound,
177 : double *scaledlobound,
178 : char *hibound,
179 : double *scaledhibound);
180 : static void convert_bytea_to_scalar(Datum value,
181 : double *scaledvalue,
182 : Datum lobound,
183 : double *scaledlobound,
184 : Datum hibound,
185 : double *scaledhibound);
186 : static double convert_one_string_to_scalar(char *value,
187 : int rangelo, int rangehi);
188 : static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
189 : int rangelo, int rangehi);
190 : static char *convert_string_datum(Datum value, Oid typid, Oid collid,
191 : bool *failure);
192 : static double convert_timevalue_to_scalar(Datum value, Oid typid,
193 : bool *failure);
194 : static void examine_simple_variable(PlannerInfo *root, Var *var,
195 : VariableStatData *vardata);
196 : static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
197 : Oid sortop, Oid collation,
198 : Datum *min, Datum *max);
199 : static 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);
203 : static bool get_actual_variable_range(PlannerInfo *root,
204 : VariableStatData *vardata,
205 : Oid sortop, Oid collation,
206 : Datum *min, Datum *max);
207 : static 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);
216 : static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
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 : */
227 : Datum
228 1074254 : eqsel(PG_FUNCTION_ARGS)
229 : {
230 1074254 : PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
231 : }
232 :
233 : /*
234 : * Common code for eqsel() and neqsel()
235 : */
236 : static double
237 1121802 : eqsel_internal(PG_FUNCTION_ARGS, bool negate)
238 : {
239 1121802 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
240 1121802 : Oid operator = PG_GETARG_OID(1);
241 1121802 : List *args = (List *) PG_GETARG_POINTER(2);
242 1121802 : int varRelid = PG_GETARG_INT32(3);
243 1121802 : 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 1121802 : if (negate)
254 : {
255 47548 : operator = get_negator(operator);
256 47548 : if (!OidIsValid(operator))
257 : {
258 : /* Use default selectivity (should we raise an error instead?) */
259 0 : 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 1121802 : if (!get_restriction_variable(root, args, varRelid,
268 : &vardata, &other, &varonleft))
269 4120 : 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 1117682 : if (IsA(other, Const))
277 340952 : selec = var_eq_const(&vardata, operator, collation,
278 340952 : ((Const *) other)->constvalue,
279 340952 : ((Const *) other)->constisnull,
280 : varonleft, negate);
281 : else
282 776730 : selec = var_eq_non_const(&vardata, operator, collation, other,
283 : varonleft, negate);
284 :
285 1117682 : ReleaseVariableStats(vardata);
286 :
287 1117682 : 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 : */
295 : double
296 406814 : var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
297 : Datum constval, bool constisnull,
298 : bool varonleft, bool negate)
299 : {
300 : double selec;
301 406814 : 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 406814 : if (constisnull)
310 346 : 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 406468 : if (HeapTupleIsValid(vardata->statsTuple))
317 : {
318 : Form_pg_statistic stats;
319 :
320 319808 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
321 319808 : nullfrac = stats->stanullfrac;
322 : }
323 :
324 : /*
325 : * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
326 : * assume there is exactly one match regardless of anything else. (This
327 : * is slightly bogus, since the index or clause's equality operator might
328 : * be different from ours, but it's much more likely to be right than
329 : * ignoring the information.)
330 : */
331 406468 : if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
332 : {
333 113710 : selec = 1.0 / vardata->rel->tuples;
334 : }
335 515566 : else if (HeapTupleIsValid(vardata->statsTuple) &&
336 222808 : statistic_proc_security_check(vardata,
337 222808 : (opfuncoid = get_opcode(oproid))))
338 222808 : {
339 : AttStatsSlot sslot;
340 222808 : 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 222808 : if (get_attstatsslot(&sslot, vardata->statsTuple,
351 : STATISTIC_KIND_MCV, InvalidOid,
352 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
353 : {
354 173298 : LOCAL_FCINFO(fcinfo, 2);
355 : FmgrInfo eqproc;
356 :
357 173298 : 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 173298 : InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
366 : NULL, NULL);
367 173298 : fcinfo->args[0].isnull = false;
368 173298 : fcinfo->args[1].isnull = false;
369 : /* be careful to apply operator right way 'round */
370 173298 : if (varonleft)
371 173266 : fcinfo->args[1].value = constval;
372 : else
373 32 : fcinfo->args[0].value = constval;
374 :
375 2557774 : for (i = 0; i < sslot.nvalues; i++)
376 : {
377 : Datum fresult;
378 :
379 2455952 : if (varonleft)
380 2455896 : fcinfo->args[0].value = sslot.values[i];
381 : else
382 56 : fcinfo->args[1].value = sslot.values[i];
383 2455952 : fcinfo->isnull = false;
384 2455952 : fresult = FunctionCallInvoke(fcinfo);
385 2455952 : if (!fcinfo->isnull && DatumGetBool(fresult))
386 : {
387 71476 : match = true;
388 71476 : break;
389 : }
390 : }
391 : }
392 : else
393 : {
394 : /* no most-common-value info available */
395 49510 : i = 0; /* keep compiler quiet */
396 : }
397 :
398 222808 : 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 71476 : 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 151332 : double sumcommon = 0.0;
414 : double otherdistinct;
415 :
416 2266680 : for (i = 0; i < sslot.nnumbers; i++)
417 2115348 : sumcommon += sslot.numbers[i];
418 151332 : selec = 1.0 - sumcommon - nullfrac;
419 151332 : 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 151332 : otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
427 151332 : sslot.nnumbers;
428 151332 : if (otherdistinct > 1)
429 74922 : 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 151332 : if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
436 0 : selec = sslot.numbers[sslot.nnumbers - 1];
437 : }
438 :
439 222808 : 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 69950 : selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
449 : }
450 :
451 : /* now adjust if we wanted <> rather than = */
452 406468 : if (negate)
453 39706 : selec = 1.0 - selec - nullfrac;
454 :
455 : /* result should be in range, but make sure... */
456 406468 : CLAMP_PROBABILITY(selec);
457 :
458 406468 : 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 : */
466 : double
467 776730 : var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
468 : Node *other,
469 : bool varonleft, bool negate)
470 : {
471 : double selec;
472 776730 : double nullfrac = 0.0;
473 : bool isdefault;
474 :
475 : /*
476 : * Grab the nullfrac for use below.
477 : */
478 776730 : if (HeapTupleIsValid(vardata->statsTuple))
479 : {
480 : Form_pg_statistic stats;
481 :
482 565786 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
483 565786 : nullfrac = stats->stanullfrac;
484 : }
485 :
486 : /*
487 : * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
488 : * assume there is exactly one match regardless of anything else. (This
489 : * is slightly bogus, since the index or clause's equality operator might
490 : * be different from ours, but it's much more likely to be right than
491 : * ignoring the information.)
492 : */
493 776730 : if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
494 : {
495 259324 : selec = 1.0 / vardata->rel->tuples;
496 : }
497 517406 : 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 321816 : selec = 1.0 - nullfrac;
513 321816 : ndistinct = get_variable_numdistinct(vardata, &isdefault);
514 321816 : if (ndistinct > 1)
515 317028 : selec /= ndistinct;
516 :
517 : /*
518 : * Cross-check: selectivity should never be estimated as more than the
519 : * most common value's.
520 : */
521 321816 : if (get_attstatsslot(&sslot, vardata->statsTuple,
522 : STATISTIC_KIND_MCV, InvalidOid,
523 : ATTSTATSSLOT_NUMBERS))
524 : {
525 302346 : if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
526 558 : selec = sslot.numbers[0];
527 302346 : 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 195590 : selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
538 : }
539 :
540 : /* now adjust if we wanted <> rather than = */
541 776730 : if (negate)
542 6076 : selec = 1.0 - selec - nullfrac;
543 :
544 : /* result should be in range, but make sure... */
545 776730 : CLAMP_PROBABILITY(selec);
546 :
547 776730 : 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 : */
557 : Datum
558 47548 : neqsel(PG_FUNCTION_ARGS)
559 : {
560 47548 : 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 : */
580 : static double
581 469366 : scalarineqsel(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 469366 : 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 19964 : if (vardata->var && IsA(vardata->var, Var) &&
600 15220 : ((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 214 : if (vardata->rel->pages == 0)
611 0 : return 1.0;
612 :
613 214 : itemptr = (ItemPointer) DatumGetPointer(constval);
614 214 : 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 214 : density = vardata->rel->tuples / (vardata->rel->pages - 0.5);
624 :
625 : /* If target is the last page, use half the density. */
626 214 : if (block >= vardata->rel->pages - 1)
627 30 : 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 214 : if (density > 0.0)
638 : {
639 214 : OffsetNumber offset = ItemPointerGetOffsetNumberNoCheck(itemptr);
640 :
641 214 : 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 214 : 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 214 : if (iseq == isgt && vardata->rel->tuples >= 1.0)
659 102 : selec -= (1.0 / vardata->rel->tuples);
660 :
661 : /* Finally, reverse the selectivity for the ">", ">=" cases. */
662 214 : if (isgt)
663 100 : selec = 1.0 - selec;
664 :
665 214 : CLAMP_PROBABILITY(selec);
666 214 : return selec;
667 : }
668 :
669 : /* no stats available, so default result */
670 19750 : return DEFAULT_INEQ_SEL;
671 : }
672 449402 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
673 :
674 449402 : 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 449402 : 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 449402 : 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 449402 : selec = 1.0 - stats->stanullfrac - sumcommon;
700 :
701 449402 : if (hist_selec >= 0.0)
702 307942 : 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 141460 : selec *= 0.5;
710 : }
711 :
712 449402 : selec += mcv_selec;
713 :
714 : /* result should be in range, but make sure... */
715 449402 : CLAMP_PROBABILITY(selec);
716 :
717 449402 : 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 : */
732 : double
733 454494 : mcv_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 454494 : mcv_selec = 0.0;
743 454494 : sumcommon = 0.0;
744 :
745 906628 : if (HeapTupleIsValid(vardata->statsTuple) &&
746 904214 : statistic_proc_security_check(vardata, opproc->fn_oid) &&
747 452080 : get_attstatsslot(&sslot, vardata->statsTuple,
748 : STATISTIC_KIND_MCV, InvalidOid,
749 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
750 : {
751 217928 : 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 217928 : InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
761 : NULL, NULL);
762 217928 : fcinfo->args[0].isnull = false;
763 217928 : fcinfo->args[1].isnull = false;
764 : /* be careful to apply operator right way 'round */
765 217928 : if (varonleft)
766 217928 : fcinfo->args[1].value = constval;
767 : else
768 0 : fcinfo->args[0].value = constval;
769 :
770 6305198 : for (i = 0; i < sslot.nvalues; i++)
771 : {
772 : Datum fresult;
773 :
774 6087270 : if (varonleft)
775 6087270 : fcinfo->args[0].value = sslot.values[i];
776 : else
777 0 : fcinfo->args[1].value = sslot.values[i];
778 6087270 : fcinfo->isnull = false;
779 6087270 : fresult = FunctionCallInvoke(fcinfo);
780 6087270 : if (!fcinfo->isnull && DatumGetBool(fresult))
781 2523710 : mcv_selec += sslot.numbers[i];
782 6087270 : sumcommon += sslot.numbers[i];
783 : }
784 217928 : free_attstatsslot(&sslot);
785 : }
786 :
787 454494 : *sumcommonp = sumcommon;
788 454494 : 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 : */
823 : double
824 5092 : histogram_selectivity(VariableStatData *vardata,
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 7824 : if (HeapTupleIsValid(vardata->statsTuple) &&
838 5458 : statistic_proc_security_check(vardata, opproc->fn_oid) &&
839 2726 : get_attstatsslot(&sslot, vardata->statsTuple,
840 : STATISTIC_KIND_HISTOGRAM, InvalidOid,
841 : ATTSTATSSLOT_VALUES))
842 : {
843 2632 : *hist_size = sslot.nvalues;
844 2632 : if (sslot.nvalues >= min_hist_size)
845 : {
846 1580 : LOCAL_FCINFO(fcinfo, 2);
847 1580 : 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 1580 : InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
859 : NULL, NULL);
860 1580 : fcinfo->args[0].isnull = false;
861 1580 : fcinfo->args[1].isnull = false;
862 : /* be careful to apply operator right way 'round */
863 1580 : if (varonleft)
864 1580 : fcinfo->args[1].value = constval;
865 : else
866 0 : fcinfo->args[0].value = constval;
867 :
868 137156 : for (i = n_skip; i < sslot.nvalues - n_skip; i++)
869 : {
870 : Datum fresult;
871 :
872 135576 : if (varonleft)
873 135576 : fcinfo->args[0].value = sslot.values[i];
874 : else
875 0 : fcinfo->args[1].value = sslot.values[i];
876 135576 : fcinfo->isnull = false;
877 135576 : fresult = FunctionCallInvoke(fcinfo);
878 135576 : if (!fcinfo->isnull && DatumGetBool(fresult))
879 5032 : nmatch++;
880 : }
881 1580 : result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
882 : }
883 : else
884 1052 : result = -1;
885 2632 : free_attstatsslot(&sslot);
886 : }
887 : else
888 : {
889 2460 : *hist_size = 0;
890 2460 : result = -1;
891 : }
892 :
893 5092 : 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 : */
914 : double
915 1106 : generic_restriction_selectivity(PlannerInfo *root, Oid oproid, Oid collation,
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 1106 : if (!get_restriction_variable(root, args, varRelid,
929 : &vardata, &other, &varonleft))
930 0 : 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 1106 : if (IsA(other, Const) &&
937 1106 : ((Const *) other)->constisnull)
938 : {
939 0 : ReleaseVariableStats(vardata);
940 0 : return 0.0;
941 : }
942 :
943 1106 : if (IsA(other, Const))
944 : {
945 : /* Variable is being compared to a known non-null constant */
946 1106 : Datum constval = ((Const *) other)->constvalue;
947 : FmgrInfo opproc;
948 : double mcvsum;
949 : double mcvsel;
950 : double nullfrac;
951 : int hist_size;
952 :
953 1106 : fmgr_info(get_opcode(oproid), &opproc);
954 :
955 : /*
956 : * Calculate the selectivity for the column's most common values.
957 : */
958 1106 : 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 1106 : selec = histogram_selectivity(&vardata, &opproc, collation,
969 : constval, varonleft,
970 : 10, 1, &hist_size);
971 1106 : if (selec < 0)
972 : {
973 : /* Nope, fall back on default */
974 1106 : selec = default_selectivity;
975 : }
976 0 : 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 0 : double hist_weight = hist_size / 100.0;
984 :
985 0 : selec = selec * hist_weight +
986 0 : default_selectivity * (1.0 - hist_weight);
987 : }
988 :
989 : /* In any case, don't believe extremely small or large estimates. */
990 1106 : if (selec < 0.0001)
991 0 : selec = 0.0001;
992 1106 : else if (selec > 0.9999)
993 0 : selec = 0.9999;
994 :
995 : /* Don't forget to account for nulls. */
996 1106 : if (HeapTupleIsValid(vardata.statsTuple))
997 84 : nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
998 : else
999 1022 : 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 1106 : selec *= 1.0 - nullfrac - mcvsum;
1007 1106 : selec += mcvsel;
1008 : }
1009 : else
1010 : {
1011 : /* Comparison value is not constant, so we can't do anything */
1012 0 : selec = default_selectivity;
1013 : }
1014 :
1015 1106 : ReleaseVariableStats(vardata);
1016 :
1017 : /* result should be in range, but make sure... */
1018 1106 : CLAMP_PROBABILITY(selec);
1019 :
1020 1106 : 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 : */
1041 : double
1042 452598 : ineq_histogram_selectivity(PlannerInfo *root,
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 452598 : 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 904546 : if (HeapTupleIsValid(vardata->statsTuple) &&
1066 903848 : statistic_proc_security_check(vardata, opproc->fn_oid) &&
1067 451900 : get_attstatsslot(&sslot, vardata->statsTuple,
1068 : STATISTIC_KIND_HISTOGRAM, InvalidOid,
1069 : ATTSTATSSLOT_VALUES))
1070 : {
1071 310486 : if (sslot.nvalues > 1 &&
1072 620896 : sslot.stacoll == collation &&
1073 310410 : comparison_ops_are_compatible(sslot.staop, opoid))
1074 310302 : {
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 310302 : int lobound = 0; /* first possible slot to search */
1095 310302 : int hibound = sslot.nvalues; /* last+1 slot to search */
1096 310302 : 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 310302 : if (sslot.nvalues == 2)
1105 1506 : have_end = get_actual_variable_range(root,
1106 : vardata,
1107 : sslot.staop,
1108 : collation,
1109 : &sslot.values[0],
1110 1506 : &sslot.values[1]);
1111 :
1112 1859582 : while (lobound < hibound)
1113 : {
1114 1549280 : 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 1549280 : if (probe == 0 && sslot.nvalues > 2)
1123 158288 : have_end = get_actual_variable_range(root,
1124 : vardata,
1125 : sslot.staop,
1126 : collation,
1127 : &sslot.values[0],
1128 : NULL);
1129 1390992 : else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
1130 121260 : have_end = get_actual_variable_range(root,
1131 : vardata,
1132 : sslot.staop,
1133 : collation,
1134 : NULL,
1135 121260 : &sslot.values[probe]);
1136 :
1137 1549280 : ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
1138 : collation,
1139 1549280 : sslot.values[probe],
1140 : constval));
1141 1549280 : if (isgt)
1142 59480 : ltcmp = !ltcmp;
1143 1549280 : if (ltcmp)
1144 570762 : lobound = probe + 1;
1145 : else
1146 978518 : hibound = probe;
1147 : }
1148 :
1149 310302 : 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 144076 : histfrac = 0.0;
1160 : }
1161 166226 : else if (lobound >= sslot.nvalues)
1162 : {
1163 : /*
1164 : * Inverse case: constant is above upper histogram boundary.
1165 : */
1166 38946 : histfrac = 1.0;
1167 : }
1168 : else
1169 : {
1170 : /* We have values[i-1] <= constant <= values[i]. */
1171 127280 : int i = lobound;
1172 127280 : 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 127280 : if (i == 1 || isgt == iseq)
1195 : {
1196 : double otherdistinct;
1197 : bool isdefault;
1198 : AttStatsSlot mcvslot;
1199 :
1200 : /* Get estimated number of distinct values */
1201 31942 : otherdistinct = get_variable_numdistinct(vardata,
1202 : &isdefault);
1203 :
1204 : /* Subtract off the number of known MCVs */
1205 31942 : if (get_attstatsslot(&mcvslot, vardata->statsTuple,
1206 : STATISTIC_KIND_MCV, InvalidOid,
1207 : ATTSTATSSLOT_NUMBERS))
1208 : {
1209 3002 : otherdistinct -= mcvslot.nnumbers;
1210 3002 : free_attstatsslot(&mcvslot);
1211 : }
1212 :
1213 : /* If result doesn't seem sane, leave eq_selec at 0 */
1214 31942 : if (otherdistinct > 1)
1215 31900 : 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 127280 : if (convert_to_scalar(constval, consttype, collation,
1224 : &val,
1225 127280 : sslot.values[i - 1], sslot.values[i],
1226 : vardata->vartype,
1227 : &low, &high))
1228 : {
1229 127280 : if (high <= low)
1230 : {
1231 : /* cope if bin boundaries appear identical */
1232 0 : binfrac = 0.5;
1233 : }
1234 127280 : else if (val <= low)
1235 21006 : binfrac = 0.0;
1236 106274 : else if (val >= high)
1237 3606 : binfrac = 1.0;
1238 : else
1239 : {
1240 102668 : 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 102668 : if (isnan(binfrac) ||
1249 102668 : binfrac < 0.0 || binfrac > 1.0)
1250 0 : 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 0 : 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 127280 : histfrac = (double) (i - 1) + binfrac;
1272 127280 : 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 127280 : if (i == 1)
1307 15270 : 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 127280 : if (isgt == iseq)
1315 22954 : 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 310302 : 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 310302 : if (have_end)
1334 224398 : CLAMP_PROBABILITY(hist_selec);
1335 : else
1336 : {
1337 85904 : double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1338 :
1339 85904 : if (hist_selec < cutoff)
1340 31388 : hist_selec = cutoff;
1341 54516 : else if (hist_selec > 1.0 - cutoff)
1342 20278 : hist_selec = 1.0 - cutoff;
1343 : }
1344 : }
1345 184 : 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 184 : LOCAL_FCINFO(fcinfo, 2);
1355 184 : int nmatch = 0;
1356 :
1357 184 : InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
1358 : NULL, NULL);
1359 184 : fcinfo->args[0].isnull = false;
1360 184 : fcinfo->args[1].isnull = false;
1361 184 : fcinfo->args[1].value = constval;
1362 962100 : for (int i = 0; i < sslot.nvalues; i++)
1363 : {
1364 : Datum fresult;
1365 :
1366 961916 : fcinfo->args[0].value = sslot.values[i];
1367 961916 : fcinfo->isnull = false;
1368 961916 : fresult = FunctionCallInvoke(fcinfo);
1369 961916 : if (!fcinfo->isnull && DatumGetBool(fresult))
1370 1932 : nmatch++;
1371 : }
1372 184 : 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 184 : double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1382 :
1383 184 : if (hist_selec < cutoff)
1384 12 : hist_selec = cutoff;
1385 172 : else if (hist_selec > 1.0 - cutoff)
1386 12 : hist_selec = 1.0 - cutoff;
1387 : }
1388 : }
1389 :
1390 310486 : free_attstatsslot(&sslot);
1391 : }
1392 :
1393 452598 : return hist_selec;
1394 : }
1395 :
1396 : /*
1397 : * Common wrapper function for the selectivity estimators that simply
1398 : * invoke scalarineqsel().
1399 : */
1400 : static Datum
1401 40386 : scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
1402 : {
1403 40386 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1404 40386 : Oid operator = PG_GETARG_OID(1);
1405 40386 : List *args = (List *) PG_GETARG_POINTER(2);
1406 40386 : int varRelid = PG_GETARG_INT32(3);
1407 40386 : 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 40386 : if (!get_restriction_variable(root, args, varRelid,
1420 : &vardata, &other, &varonleft))
1421 532 : PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1422 :
1423 : /*
1424 : * Can't do anything useful if the something is not a constant, either.
1425 : */
1426 39854 : if (!IsA(other, Const))
1427 : {
1428 2686 : ReleaseVariableStats(vardata);
1429 2686 : PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
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 37168 : if (((Const *) other)->constisnull)
1437 : {
1438 66 : ReleaseVariableStats(vardata);
1439 66 : PG_RETURN_FLOAT8(0.0);
1440 : }
1441 37102 : constval = ((Const *) other)->constvalue;
1442 37102 : consttype = ((Const *) other)->consttype;
1443 :
1444 : /*
1445 : * Force the var to be on the left to simplify logic in scalarineqsel.
1446 : */
1447 37102 : if (!varonleft)
1448 : {
1449 366 : operator = get_commutator(operator);
1450 366 : if (!operator)
1451 : {
1452 : /* Use default selectivity (should we raise an error instead?) */
1453 0 : ReleaseVariableStats(vardata);
1454 0 : PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1455 : }
1456 366 : isgt = !isgt;
1457 : }
1458 :
1459 : /* The rest of the work is done by scalarineqsel(). */
1460 37102 : selec = scalarineqsel(root, operator, isgt, iseq, collation,
1461 : &vardata, constval, consttype);
1462 :
1463 37102 : ReleaseVariableStats(vardata);
1464 :
1465 37102 : PG_RETURN_FLOAT8((float8) selec);
1466 : }
1467 :
1468 : /*
1469 : * scalarltsel - Selectivity of "<" for scalars.
1470 : */
1471 : Datum
1472 13938 : scalarltsel(PG_FUNCTION_ARGS)
1473 : {
1474 13938 : return scalarineqsel_wrapper(fcinfo, false, false);
1475 : }
1476 :
1477 : /*
1478 : * scalarlesel - Selectivity of "<=" for scalars.
1479 : */
1480 : Datum
1481 4404 : scalarlesel(PG_FUNCTION_ARGS)
1482 : {
1483 4404 : return scalarineqsel_wrapper(fcinfo, false, true);
1484 : }
1485 :
1486 : /*
1487 : * scalargtsel - Selectivity of ">" for scalars.
1488 : */
1489 : Datum
1490 14714 : scalargtsel(PG_FUNCTION_ARGS)
1491 : {
1492 14714 : return scalarineqsel_wrapper(fcinfo, true, false);
1493 : }
1494 :
1495 : /*
1496 : * scalargesel - Selectivity of ">=" for scalars.
1497 : */
1498 : Datum
1499 7330 : scalargesel(PG_FUNCTION_ARGS)
1500 : {
1501 7330 : 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 : */
1512 : Selectivity
1513 66144 : boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
1514 : {
1515 : VariableStatData vardata;
1516 : double selec;
1517 :
1518 66144 : examine_variable(root, arg, varRelid, &vardata);
1519 66144 : 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 58098 : 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 8046 : selec = 0.5;
1532 : }
1533 66144 : ReleaseVariableStats(vardata);
1534 66144 : return selec;
1535 : }
1536 :
1537 : /*
1538 : * booltestsel - Selectivity of BooleanTest Node.
1539 : */
1540 : Selectivity
1541 838 : booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
1542 : int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1543 : {
1544 : VariableStatData vardata;
1545 : double selec;
1546 :
1547 838 : examine_variable(root, arg, varRelid, &vardata);
1548 :
1549 838 : if (HeapTupleIsValid(vardata.statsTuple))
1550 : {
1551 : Form_pg_statistic stats;
1552 : double freq_null;
1553 : AttStatsSlot sslot;
1554 :
1555 0 : stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1556 0 : freq_null = stats->stanullfrac;
1557 :
1558 0 : if (get_attstatsslot(&sslot, vardata.statsTuple,
1559 : STATISTIC_KIND_MCV, InvalidOid,
1560 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)
1561 0 : && sslot.nnumbers > 0)
1562 0 : {
1563 : double freq_true;
1564 : double freq_false;
1565 :
1566 : /*
1567 : * Get first MCV frequency and derive frequency for true.
1568 : */
1569 0 : if (DatumGetBool(sslot.values[0]))
1570 0 : freq_true = sslot.numbers[0];
1571 : else
1572 0 : 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 0 : freq_false = 1.0 - freq_true - freq_null;
1579 :
1580 0 : switch (booltesttype)
1581 : {
1582 0 : case IS_UNKNOWN:
1583 : /* select only NULL values */
1584 0 : selec = freq_null;
1585 0 : break;
1586 0 : case IS_NOT_UNKNOWN:
1587 : /* select non-NULL values */
1588 0 : selec = 1.0 - freq_null;
1589 0 : break;
1590 0 : case IS_TRUE:
1591 : /* select only TRUE values */
1592 0 : selec = freq_true;
1593 0 : break;
1594 0 : case IS_NOT_TRUE:
1595 : /* select non-TRUE values */
1596 0 : selec = 1.0 - freq_true;
1597 0 : break;
1598 0 : case IS_FALSE:
1599 : /* select only FALSE values */
1600 0 : selec = freq_false;
1601 0 : break;
1602 0 : case IS_NOT_FALSE:
1603 : /* select non-FALSE values */
1604 0 : selec = 1.0 - freq_false;
1605 0 : break;
1606 0 : default:
1607 0 : elog(ERROR, "unrecognized booltesttype: %d",
1608 : (int) booltesttype);
1609 : selec = 0.0; /* Keep compiler quiet */
1610 : break;
1611 : }
1612 :
1613 0 : 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 0 : switch (booltesttype)
1623 : {
1624 0 : case IS_UNKNOWN:
1625 : /* select only NULL values */
1626 0 : selec = freq_null;
1627 0 : break;
1628 0 : case IS_NOT_UNKNOWN:
1629 : /* select non-NULL values */
1630 0 : selec = 1.0 - freq_null;
1631 0 : break;
1632 0 : case IS_TRUE:
1633 : case IS_FALSE:
1634 : /* Assume we select half of the non-NULL values */
1635 0 : selec = (1.0 - freq_null) / 2.0;
1636 0 : break;
1637 0 : 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 0 : selec = (freq_null + 1.0) / 2.0;
1642 0 : break;
1643 0 : default:
1644 0 : 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 838 : switch (booltesttype)
1660 : {
1661 48 : case IS_UNKNOWN:
1662 48 : selec = DEFAULT_UNK_SEL;
1663 48 : break;
1664 108 : case IS_NOT_UNKNOWN:
1665 108 : selec = DEFAULT_NOT_UNK_SEL;
1666 108 : break;
1667 252 : case IS_TRUE:
1668 : case IS_NOT_FALSE:
1669 252 : selec = (double) clause_selectivity(root, arg,
1670 : varRelid,
1671 : jointype, sjinfo);
1672 252 : break;
1673 430 : case IS_FALSE:
1674 : case IS_NOT_TRUE:
1675 430 : selec = 1.0 - (double) clause_selectivity(root, arg,
1676 : varRelid,
1677 : jointype, sjinfo);
1678 430 : break;
1679 0 : default:
1680 0 : elog(ERROR, "unrecognized booltesttype: %d",
1681 : (int) booltesttype);
1682 : selec = 0.0; /* Keep compiler quiet */
1683 : break;
1684 : }
1685 : }
1686 :
1687 838 : ReleaseVariableStats(vardata);
1688 :
1689 : /* result should be in range, but make sure... */
1690 838 : CLAMP_PROBABILITY(selec);
1691 :
1692 838 : return (Selectivity) selec;
1693 : }
1694 :
1695 : /*
1696 : * nulltestsel - Selectivity of NullTest Node.
1697 : */
1698 : Selectivity
1699 16236 : nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1700 : int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1701 : {
1702 : VariableStatData vardata;
1703 : double selec;
1704 :
1705 16236 : examine_variable(root, arg, varRelid, &vardata);
1706 :
1707 16236 : if (HeapTupleIsValid(vardata.statsTuple))
1708 : {
1709 : Form_pg_statistic stats;
1710 : double freq_null;
1711 :
1712 9100 : stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1713 9100 : freq_null = stats->stanullfrac;
1714 :
1715 9100 : switch (nulltesttype)
1716 : {
1717 6784 : case IS_NULL:
1718 :
1719 : /*
1720 : * Use freq_null directly.
1721 : */
1722 6784 : selec = freq_null;
1723 6784 : break;
1724 2316 : case IS_NOT_NULL:
1725 :
1726 : /*
1727 : * Select not unknown (not null) values. Calculate from
1728 : * freq_null.
1729 : */
1730 2316 : selec = 1.0 - freq_null;
1731 2316 : break;
1732 0 : default:
1733 0 : elog(ERROR, "unrecognized nulltesttype: %d",
1734 : (int) nulltesttype);
1735 : return (Selectivity) 0; /* keep compiler quiet */
1736 : }
1737 : }
1738 7136 : else if (vardata.var && IsA(vardata.var, Var) &&
1739 6542 : ((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 60 : selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
1746 : }
1747 : else
1748 : {
1749 : /*
1750 : * No ANALYZE stats available, so make a guess
1751 : */
1752 7076 : switch (nulltesttype)
1753 : {
1754 2068 : case IS_NULL:
1755 2068 : selec = DEFAULT_UNK_SEL;
1756 2068 : break;
1757 5008 : case IS_NOT_NULL:
1758 5008 : selec = DEFAULT_NOT_UNK_SEL;
1759 5008 : break;
1760 0 : default:
1761 0 : elog(ERROR, "unrecognized nulltesttype: %d",
1762 : (int) nulltesttype);
1763 : return (Selectivity) 0; /* keep compiler quiet */
1764 : }
1765 : }
1766 :
1767 16236 : ReleaseVariableStats(vardata);
1768 :
1769 : /* result should be in range, but make sure... */
1770 16236 : CLAMP_PROBABILITY(selec);
1771 :
1772 16236 : 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 : */
1783 : static Node *
1784 122028 : strip_array_coercion(Node *node)
1785 : {
1786 : for (;;)
1787 : {
1788 122028 : if (node && IsA(node, ArrayCoerceExpr))
1789 36 : {
1790 2812 : 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 2812 : if (IsA(acoerce->elemexpr, RelabelType) &&
1797 36 : IsA(((RelabelType *) acoerce->elemexpr)->arg, CaseTestExpr))
1798 36 : node = (Node *) acoerce->arg;
1799 : else
1800 : break;
1801 : }
1802 119216 : else if (node && IsA(node, RelabelType))
1803 : {
1804 : /* We don't really expect this case, but may as well cope */
1805 0 : node = (Node *) ((RelabelType *) node)->arg;
1806 : }
1807 : else
1808 : break;
1809 : }
1810 121992 : return node;
1811 : }
1812 :
1813 : /*
1814 : * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1815 : */
1816 : Selectivity
1817 21306 : scalararraysel(PlannerInfo *root,
1818 : ScalarArrayOpExpr *clause,
1819 : bool is_join_clause,
1820 : int varRelid,
1821 : JoinType jointype,
1822 : SpecialJoinInfo *sjinfo)
1823 : {
1824 21306 : Oid operator = clause->opno;
1825 21306 : bool useOr = clause->useOr;
1826 21306 : bool isEquality = false;
1827 21306 : 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;
1835 : Selectivity s1;
1836 : Selectivity s1disjoint;
1837 :
1838 : /* First, deconstruct the expression */
1839 : Assert(list_length(clause->args) == 2);
1840 21306 : leftop = (Node *) linitial(clause->args);
1841 21306 : rightop = (Node *) lsecond(clause->args);
1842 :
1843 : /* aggressively reduce both sides to constants */
1844 21306 : leftop = estimate_expression_value(root, leftop);
1845 21306 : rightop = estimate_expression_value(root, rightop);
1846 :
1847 : /* get nominal (after relabeling) element type of rightop */
1848 21306 : nominal_element_type = get_base_element_type(exprType(rightop));
1849 21306 : if (!OidIsValid(nominal_element_type))
1850 0 : return (Selectivity) 0.5; /* probably shouldn't happen */
1851 : /* get nominal collation, too, for generating constants */
1852 21306 : nominal_element_collation = exprCollation(rightop);
1853 :
1854 : /* look through any binary-compatible relabeling of rightop */
1855 21306 : 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 21306 : typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1862 21306 : if (OidIsValid(typentry->eq_opr))
1863 : {
1864 21306 : if (operator == typentry->eq_opr)
1865 16048 : isEquality = true;
1866 5258 : else if (get_negator(operator) == typentry->eq_opr)
1867 4712 : 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 21306 : if ((isEquality || isInequality) && !is_join_clause)
1877 : {
1878 20760 : s1 = scalararraysel_containment(root, leftop, rightop,
1879 : nominal_element_type,
1880 : isEquality, useOr, varRelid);
1881 20760 : if (s1 >= 0.0)
1882 118 : return s1;
1883 : }
1884 :
1885 : /*
1886 : * Look up the underlying operator's selectivity estimator. Punt if it
1887 : * hasn't got one.
1888 : */
1889 21188 : if (is_join_clause)
1890 0 : oprsel = get_oprjoin(operator);
1891 : else
1892 21188 : oprsel = get_oprrest(operator);
1893 21188 : if (!oprsel)
1894 0 : return (Selectivity) 0.5;
1895 21188 : 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 21188 : if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1906 16112 : isEquality = true;
1907 5076 : else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1908 4602 : 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 21188 : if (rightop && IsA(rightop, Const))
1923 17150 : {
1924 17168 : Datum arraydatum = ((Const *) rightop)->constvalue;
1925 17168 : 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 17168 : if (arrayisnull) /* qual can't succeed if null array */
1936 18 : return (Selectivity) 0.0;
1937 17150 : arrayval = DatumGetArrayTypeP(arraydatum);
1938 17150 : get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1939 : &elmlen, &elmbyval, &elmalign);
1940 17150 : 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 17150 : s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1960 :
1961 66378 : for (i = 0; i < num_elems; i++)
1962 : {
1963 : List *args;
1964 : Selectivity s2;
1965 :
1966 49228 : 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 49228 : if (is_join_clause)
1975 0 : s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1976 : clause->inputcollid,
1977 : PointerGetDatum(root),
1978 : ObjectIdGetDatum(operator),
1979 : PointerGetDatum(args),
1980 : Int16GetDatum(jointype),
1981 : PointerGetDatum(sjinfo)));
1982 : else
1983 49228 : s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1984 : clause->inputcollid,
1985 : PointerGetDatum(root),
1986 : ObjectIdGetDatum(operator),
1987 : PointerGetDatum(args),
1988 : Int32GetDatum(varRelid)));
1989 :
1990 49228 : if (useOr)
1991 : {
1992 37830 : s1 = s1 + s2 - s1 * s2;
1993 37830 : if (isEquality)
1994 36798 : s1disjoint += s2;
1995 : }
1996 : else
1997 : {
1998 11398 : s1 = s1 * s2;
1999 11398 : if (isInequality)
2000 11086 : s1disjoint += s2 - 1.0;
2001 : }
2002 : }
2003 :
2004 : /* accept disjoint-probability estimate if in range */
2005 17150 : if ((useOr ? isEquality : isInequality) &&
2006 16502 : s1disjoint >= 0.0 && s1disjoint <= 1.0)
2007 16472 : s1 = s1disjoint;
2008 : }
2009 4020 : else if (rightop && IsA(rightop, ArrayExpr) &&
2010 290 : !((ArrayExpr *) rightop)->multidims)
2011 290 : {
2012 290 : ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2013 : int16 elmlen;
2014 : bool elmbyval;
2015 : ListCell *l;
2016 :
2017 290 : 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 290 : s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2028 :
2029 1016 : foreach(l, arrayexpr->elements)
2030 : {
2031 726 : Node *elem = (Node *) lfirst(l);
2032 : List *args;
2033 : Selectivity s2;
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 726 : args = list_make2(leftop, elem);
2041 726 : if (is_join_clause)
2042 0 : s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2043 : clause->inputcollid,
2044 : PointerGetDatum(root),
2045 : ObjectIdGetDatum(operator),
2046 : PointerGetDatum(args),
2047 : Int16GetDatum(jointype),
2048 : PointerGetDatum(sjinfo)));
2049 : else
2050 726 : s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2051 : clause->inputcollid,
2052 : PointerGetDatum(root),
2053 : ObjectIdGetDatum(operator),
2054 : PointerGetDatum(args),
2055 : Int32GetDatum(varRelid)));
2056 :
2057 726 : if (useOr)
2058 : {
2059 726 : s1 = s1 + s2 - s1 * s2;
2060 726 : if (isEquality)
2061 726 : s1disjoint += s2;
2062 : }
2063 : else
2064 : {
2065 0 : s1 = s1 * s2;
2066 0 : if (isInequality)
2067 0 : s1disjoint += s2 - 1.0;
2068 : }
2069 : }
2070 :
2071 : /* accept disjoint-probability estimate if in range */
2072 290 : if ((useOr ? isEquality : isInequality) &&
2073 290 : s1disjoint >= 0.0 && s1disjoint <= 1.0)
2074 290 : s1 = s1disjoint;
2075 : }
2076 : else
2077 : {
2078 : CaseTestExpr *dummyexpr;
2079 : List *args;
2080 : Selectivity s2;
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 3730 : dummyexpr = makeNode(CaseTestExpr);
2089 3730 : dummyexpr->typeId = nominal_element_type;
2090 3730 : dummyexpr->typeMod = -1;
2091 3730 : dummyexpr->collation = clause->inputcollid;
2092 3730 : args = list_make2(leftop, dummyexpr);
2093 3730 : if (is_join_clause)
2094 0 : s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2095 : clause->inputcollid,
2096 : PointerGetDatum(root),
2097 : ObjectIdGetDatum(operator),
2098 : PointerGetDatum(args),
2099 : Int16GetDatum(jointype),
2100 : PointerGetDatum(sjinfo)));
2101 : else
2102 3730 : s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2103 : clause->inputcollid,
2104 : PointerGetDatum(root),
2105 : ObjectIdGetDatum(operator),
2106 : PointerGetDatum(args),
2107 : Int32GetDatum(varRelid)));
2108 3730 : 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 41030 : for (i = 0; i < 10; i++)
2116 : {
2117 37300 : if (useOr)
2118 37300 : s1 = s1 + s2 - s1 * s2;
2119 : else
2120 0 : s1 = s1 * s2;
2121 : }
2122 : }
2123 :
2124 : /* result should be in range, but make sure... */
2125 21170 : CLAMP_PROBABILITY(s1);
2126 :
2127 21170 : 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 : */
2139 : double
2140 100686 : estimate_array_length(PlannerInfo *root, Node *arrayexpr)
2141 : {
2142 : /* look through any binary-compatible relabeling of arrayexpr */
2143 100686 : arrayexpr = strip_array_coercion(arrayexpr);
2144 :
2145 100686 : if (arrayexpr && IsA(arrayexpr, Const))
2146 : {
2147 44436 : Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2148 44436 : bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2149 : ArrayType *arrayval;
2150 :
2151 44436 : if (arrayisnull)
2152 42 : return 0;
2153 44394 : arrayval = DatumGetArrayTypeP(arraydatum);
2154 44394 : return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2155 : }
2156 56250 : else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2157 506 : !((ArrayExpr *) arrayexpr)->multidims)
2158 : {
2159 506 : return list_length(((ArrayExpr *) arrayexpr)->elements);
2160 : }
2161 55744 : else if (arrayexpr && root)
2162 : {
2163 : /* See if we can find any statistics about it */
2164 : VariableStatData vardata;
2165 : AttStatsSlot sslot;
2166 55744 : double nelem = 0;
2167 :
2168 55744 : examine_variable(root, arrayexpr, 0, &vardata);
2169 55744 : 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 3378 : if (get_attstatsslot(&sslot, vardata.statsTuple,
2178 : STATISTIC_KIND_DECHIST, InvalidOid,
2179 : ATTSTATSSLOT_NUMBERS))
2180 : {
2181 3258 : if (sslot.nnumbers > 0)
2182 3258 : nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2183 3258 : free_attstatsslot(&sslot);
2184 : }
2185 : }
2186 55744 : ReleaseVariableStats(vardata);
2187 :
2188 55744 : if (nelem > 0)
2189 3258 : return nelem;
2190 : }
2191 :
2192 : /* Else use a default guess --- this should match scalararraysel */
2193 52486 : 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 : */
2205 : Selectivity
2206 216 : rowcomparesel(PlannerInfo *root,
2207 : RowCompareExpr *clause,
2208 : int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
2209 : {
2210 : Selectivity s1;
2211 216 : Oid opno = linitial_oid(clause->opnos);
2212 216 : Oid inputcollid = linitial_oid(clause->inputcollids);
2213 : List *opargs;
2214 : bool is_join_clause;
2215 :
2216 : /* Build equivalent arg list for single operator */
2217 216 : 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 216 : if (varRelid != 0)
2225 : {
2226 : /*
2227 : * Caller is forcing restriction mode (eg, because we are examining an
2228 : * inner indexscan qual).
2229 : */
2230 54 : is_join_clause = false;
2231 : }
2232 162 : 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 150 : 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 12 : is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2246 : }
2247 :
2248 216 : if (is_join_clause)
2249 : {
2250 : /* Estimate selectivity for a join clause. */
2251 12 : s1 = join_selectivity(root, opno,
2252 : opargs,
2253 : inputcollid,
2254 : jointype,
2255 : sjinfo);
2256 : }
2257 : else
2258 : {
2259 : /* Estimate selectivity for a restriction clause. */
2260 204 : s1 = restriction_selectivity(root, opno,
2261 : opargs,
2262 : inputcollid,
2263 : varRelid);
2264 : }
2265 :
2266 216 : return s1;
2267 : }
2268 :
2269 : /*
2270 : * eqjoinsel - Join selectivity of "="
2271 : */
2272 : Datum
2273 369084 : eqjoinsel(PG_FUNCTION_ARGS)
2274 : {
2275 369084 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2276 369084 : Oid operator = PG_GETARG_OID(1);
2277 369084 : List *args = (List *) PG_GETARG_POINTER(2);
2278 :
2279 : #ifdef NOT_USED
2280 : JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2281 : #endif
2282 369084 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2283 369084 : 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 369084 : Form_pg_statistic stats1 = NULL;
2296 369084 : Form_pg_statistic stats2 = NULL;
2297 369084 : bool have_mcvs1 = false;
2298 369084 : bool have_mcvs2 = false;
2299 : bool get_mcv_stats;
2300 : bool join_is_reversed;
2301 : RelOptInfo *inner_rel;
2302 :
2303 369084 : get_join_variables(root, args, sjinfo,
2304 : &vardata1, &vardata2, &join_is_reversed);
2305 :
2306 369084 : nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2307 369084 : nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2308 :
2309 369084 : opfuncoid = get_opcode(operator);
2310 :
2311 369084 : memset(&sslot1, 0, sizeof(sslot1));
2312 369084 : 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 994502 : get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
2319 475496 : HeapTupleIsValid(vardata2.statsTuple) &&
2320 219162 : get_attstatsslot(&sslot1, vardata1.statsTuple,
2321 : STATISTIC_KIND_MCV, InvalidOid,
2322 625418 : 0) &&
2323 97058 : get_attstatsslot(&sslot2, vardata2.statsTuple,
2324 : STATISTIC_KIND_MCV, InvalidOid,
2325 : 0));
2326 :
2327 369084 : if (HeapTupleIsValid(vardata1.statsTuple))
2328 : {
2329 : /* note we allow use of nullfrac regardless of security check */
2330 256334 : stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2331 269070 : if (get_mcv_stats &&
2332 12736 : statistic_proc_security_check(&vardata1, opfuncoid))
2333 12736 : have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2334 : STATISTIC_KIND_MCV, InvalidOid,
2335 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
2336 : }
2337 :
2338 369084 : if (HeapTupleIsValid(vardata2.statsTuple))
2339 : {
2340 : /* note we allow use of nullfrac regardless of security check */
2341 301410 : stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2342 314146 : if (get_mcv_stats &&
2343 12736 : statistic_proc_security_check(&vardata2, opfuncoid))
2344 12736 : have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2345 : STATISTIC_KIND_MCV, InvalidOid,
2346 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
2347 : }
2348 :
2349 : /* We need to compute the inner-join selectivity in all cases */
2350 369084 : 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 369084 : switch (sjinfo->jointype)
2359 : {
2360 361758 : case JOIN_INNER:
2361 : case JOIN_LEFT:
2362 : case JOIN_FULL:
2363 361758 : selec = selec_inner;
2364 361758 : break;
2365 7326 : 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 7326 : inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2375 :
2376 7326 : if (!join_is_reversed)
2377 3550 : 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 3776 : Oid commop = get_commutator(operator);
2388 3776 : Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2389 :
2390 3776 : 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 7326 : selec = Min(selec, inner_rel->rows * selec_inner);
2411 7326 : break;
2412 0 : default:
2413 : /* other values not expected here */
2414 0 : elog(ERROR, "unrecognized join type: %d",
2415 : (int) sjinfo->jointype);
2416 : selec = 0; /* keep compiler quiet */
2417 : break;
2418 : }
2419 :
2420 369084 : free_attstatsslot(&sslot1);
2421 369084 : free_attstatsslot(&sslot2);
2422 :
2423 369084 : ReleaseVariableStats(vardata1);
2424 369084 : ReleaseVariableStats(vardata2);
2425 :
2426 369084 : CLAMP_PROBABILITY(selec);
2427 :
2428 369084 : 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 : */
2437 : static double
2438 369084 : eqjoinsel_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 369084 : if (have_mcvs1 && have_mcvs2)
2449 12736 : {
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 12736 : LOCAL_FCINFO(fcinfo, 2);
2463 : FmgrInfo eqproc;
2464 : bool *hasmatch1;
2465 : bool *hasmatch2;
2466 12736 : double nullfrac1 = stats1->stanullfrac;
2467 12736 : 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 12736 : 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 12736 : InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2489 : NULL, NULL);
2490 12736 : fcinfo->args[0].isnull = false;
2491 12736 : fcinfo->args[1].isnull = false;
2492 :
2493 12736 : hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2494 12736 : 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 12736 : matchprodfreq = 0.0;
2503 12736 : nmatches = 0;
2504 536500 : for (i = 0; i < sslot1->nvalues; i++)
2505 : {
2506 : int j;
2507 :
2508 523764 : fcinfo->args[0].value = sslot1->values[i];
2509 :
2510 20525218 : for (j = 0; j < sslot2->nvalues; j++)
2511 : {
2512 : Datum fresult;
2513 :
2514 20185594 : if (hasmatch2[j])
2515 5574394 : continue;
2516 14611200 : fcinfo->args[1].value = sslot2->values[j];
2517 14611200 : fcinfo->isnull = false;
2518 14611200 : fresult = FunctionCallInvoke(fcinfo);
2519 14611200 : if (!fcinfo->isnull && DatumGetBool(fresult))
2520 : {
2521 184140 : hasmatch1[i] = hasmatch2[j] = true;
2522 184140 : matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2523 184140 : nmatches++;
2524 184140 : break;
2525 : }
2526 : }
2527 : }
2528 12736 : CLAMP_PROBABILITY(matchprodfreq);
2529 : /* Sum up frequencies of matched and unmatched MCVs */
2530 12736 : matchfreq1 = unmatchfreq1 = 0.0;
2531 536500 : for (i = 0; i < sslot1->nvalues; i++)
2532 : {
2533 523764 : if (hasmatch1[i])
2534 184140 : matchfreq1 += sslot1->numbers[i];
2535 : else
2536 339624 : unmatchfreq1 += sslot1->numbers[i];
2537 : }
2538 12736 : CLAMP_PROBABILITY(matchfreq1);
2539 12736 : CLAMP_PROBABILITY(unmatchfreq1);
2540 12736 : matchfreq2 = unmatchfreq2 = 0.0;
2541 364518 : for (i = 0; i < sslot2->nvalues; i++)
2542 : {
2543 351782 : if (hasmatch2[i])
2544 184140 : matchfreq2 += sslot2->numbers[i];
2545 : else
2546 167642 : unmatchfreq2 += sslot2->numbers[i];
2547 : }
2548 12736 : CLAMP_PROBABILITY(matchfreq2);
2549 12736 : CLAMP_PROBABILITY(unmatchfreq2);
2550 12736 : pfree(hasmatch1);
2551 12736 : pfree(hasmatch2);
2552 :
2553 : /*
2554 : * Compute total frequency of non-null values that are not in the MCV
2555 : * lists.
2556 : */
2557 12736 : otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2558 12736 : otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2559 12736 : CLAMP_PROBABILITY(otherfreq1);
2560 12736 : 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 12736 : totalsel1 = matchprodfreq;
2571 12736 : if (nd2 > sslot2->nvalues)
2572 5378 : totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2573 12736 : if (nd2 > nmatches)
2574 9846 : totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2575 9846 : (nd2 - nmatches);
2576 : /* Same estimate from the point of view of relation 2. */
2577 12736 : totalsel2 = matchprodfreq;
2578 12736 : if (nd1 > sslot1->nvalues)
2579 6334 : totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2580 12736 : if (nd1 > nmatches)
2581 8722 : totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2582 8722 : (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 12736 : 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 356348 : double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2615 356348 : double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2616 :
2617 356348 : selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2618 356348 : if (nd1 > nd2)
2619 160298 : selec /= nd1;
2620 : else
2621 196050 : selec /= nd2;
2622 : }
2623 :
2624 369084 : 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 : */
2634 : static double
2635 7326 : eqjoinsel_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 7326 : if (vardata2->rel)
2666 : {
2667 7320 : if (nd2 >= vardata2->rel->rows)
2668 : {
2669 5580 : nd2 = vardata2->rel->rows;
2670 5580 : isdefault2 = false;
2671 : }
2672 : }
2673 7326 : if (nd2 >= inner_rel->rows)
2674 : {
2675 5520 : nd2 = inner_rel->rows;
2676 5520 : isdefault2 = false;
2677 : }
2678 :
2679 7326 : if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2680 510 : {
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 510 : LOCAL_FCINFO(fcinfo, 2);
2690 : FmgrInfo eqproc;
2691 : bool *hasmatch1;
2692 : bool *hasmatch2;
2693 510 : 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 510 : clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2709 :
2710 510 : 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 510 : InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2719 : NULL, NULL);
2720 510 : fcinfo->args[0].isnull = false;
2721 510 : fcinfo->args[1].isnull = false;
2722 :
2723 510 : hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2724 510 : 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 510 : nmatches = 0;
2733 11894 : for (i = 0; i < sslot1->nvalues; i++)
2734 : {
2735 : int j;
2736 :
2737 11384 : fcinfo->args[0].value = sslot1->values[i];
2738 :
2739 440972 : for (j = 0; j < clamped_nvalues2; j++)
2740 : {
2741 : Datum fresult;
2742 :
2743 439814 : if (hasmatch2[j])
2744 378242 : continue;
2745 61572 : fcinfo->args[1].value = sslot2->values[j];
2746 61572 : fcinfo->isnull = false;
2747 61572 : fresult = FunctionCallInvoke(fcinfo);
2748 61572 : if (!fcinfo->isnull && DatumGetBool(fresult))
2749 : {
2750 10226 : hasmatch1[i] = hasmatch2[j] = true;
2751 10226 : nmatches++;
2752 10226 : break;
2753 : }
2754 : }
2755 : }
2756 : /* Sum up frequencies of matched MCVs */
2757 510 : matchfreq1 = 0.0;
2758 11894 : for (i = 0; i < sslot1->nvalues; i++)
2759 : {
2760 11384 : if (hasmatch1[i])
2761 10226 : matchfreq1 += sslot1->numbers[i];
2762 : }
2763 510 : CLAMP_PROBABILITY(matchfreq1);
2764 510 : pfree(hasmatch1);
2765 510 : 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 510 : if (!isdefault1 && !isdefault2)
2783 : {
2784 510 : nd1 -= nmatches;
2785 510 : nd2 -= nmatches;
2786 510 : if (nd1 <= nd2 || nd2 < 0)
2787 480 : uncertainfrac = 1.0;
2788 : else
2789 30 : uncertainfrac = nd2 / nd1;
2790 : }
2791 : else
2792 0 : uncertainfrac = 0.5;
2793 510 : uncertain = 1.0 - matchfreq1 - nullfrac1;
2794 510 : CLAMP_PROBABILITY(uncertain);
2795 510 : 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 6816 : double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2804 :
2805 6816 : if (!isdefault1 && !isdefault2)
2806 : {
2807 4782 : if (nd1 <= nd2 || nd2 < 0)
2808 2542 : selec = 1.0 - nullfrac1;
2809 : else
2810 2240 : selec = (nd2 / nd1) * (1.0 - nullfrac1);
2811 : }
2812 : else
2813 2034 : selec = 0.5 * (1.0 - nullfrac1);
2814 : }
2815 :
2816 7326 : return selec;
2817 : }
2818 :
2819 : /*
2820 : * neqjoinsel - Join selectivity of "!="
2821 : */
2822 : Datum
2823 3380 : neqjoinsel(PG_FUNCTION_ARGS)
2824 : {
2825 3380 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2826 3380 : Oid operator = PG_GETARG_OID(1);
2827 3380 : List *args = (List *) PG_GETARG_POINTER(2);
2828 3380 : JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2829 3380 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2830 3380 : Oid collation = PG_GET_COLLATION();
2831 : float8 result;
2832 :
2833 3380 : if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2834 1120 : {
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 1120 : get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
2857 1120 : statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
2858 1120 : if (HeapTupleIsValid(statsTuple))
2859 926 : nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
2860 : else
2861 194 : nullfrac = 0.0;
2862 1120 : ReleaseVariableStats(leftvar);
2863 1120 : ReleaseVariableStats(rightvar);
2864 :
2865 1120 : 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 2260 : Oid eqop = get_negator(operator);
2874 :
2875 2260 : if (eqop)
2876 : {
2877 : result =
2878 2260 : DatumGetFloat8(DirectFunctionCall5Coll(eqjoinsel,
2879 : collation,
2880 : PointerGetDatum(root),
2881 : ObjectIdGetDatum(eqop),
2882 : PointerGetDatum(args),
2883 : Int16GetDatum(jointype),
2884 : PointerGetDatum(sjinfo)));
2885 : }
2886 : else
2887 : {
2888 : /* Use default selectivity (should we raise an error instead?) */
2889 0 : result = DEFAULT_EQ_SEL;
2890 : }
2891 2260 : result = 1.0 - result;
2892 : }
2893 :
2894 3380 : PG_RETURN_FLOAT8(result);
2895 : }
2896 :
2897 : /*
2898 : * scalarltjoinsel - Join selectivity of "<" for scalars
2899 : */
2900 : Datum
2901 318 : scalarltjoinsel(PG_FUNCTION_ARGS)
2902 : {
2903 318 : PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2904 : }
2905 :
2906 : /*
2907 : * scalarlejoinsel - Join selectivity of "<=" for scalars
2908 : */
2909 : Datum
2910 276 : scalarlejoinsel(PG_FUNCTION_ARGS)
2911 : {
2912 276 : PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2913 : }
2914 :
2915 : /*
2916 : * scalargtjoinsel - Join selectivity of ">" for scalars
2917 : */
2918 : Datum
2919 240 : scalargtjoinsel(PG_FUNCTION_ARGS)
2920 : {
2921 240 : PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2922 : }
2923 :
2924 : /*
2925 : * scalargejoinsel - Join selectivity of ">=" for scalars
2926 : */
2927 : Datum
2928 184 : scalargejoinsel(PG_FUNCTION_ARGS)
2929 : {
2930 184 : PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
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 : */
2955 : void
2956 185856 : mergejoinscansel(PlannerInfo *root, Node *clause,
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 185856 : *leftstart = *rightstart = 0.0;
2988 185856 : *leftend = *rightend = 1.0;
2989 :
2990 : /* Deconstruct the merge clause */
2991 185856 : if (!is_opclause(clause))
2992 0 : return; /* shouldn't happen */
2993 185856 : opno = ((OpExpr *) clause)->opno;
2994 185856 : collation = ((OpExpr *) clause)->inputcollid;
2995 185856 : left = get_leftop((Expr *) clause);
2996 185856 : right = get_rightop((Expr *) clause);
2997 185856 : if (!right)
2998 0 : return; /* shouldn't happen */
2999 :
3000 : /* Look for stats for the inputs */
3001 185856 : examine_variable(root, left, 0, &leftvar);
3002 185856 : examine_variable(root, right, 0, &rightvar);
3003 :
3004 : /* Extract the operator's declared left/right datatypes */
3005 185856 : 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 185856 : switch (strategy)
3019 : {
3020 185802 : case BTLessStrategyNumber:
3021 185802 : isgt = false;
3022 185802 : if (op_lefttype == op_righttype)
3023 : {
3024 : /* easy case */
3025 184480 : ltop = get_opfamily_member(opfamily,
3026 : op_lefttype, op_righttype,
3027 : BTLessStrategyNumber);
3028 184480 : leop = get_opfamily_member(opfamily,
3029 : op_lefttype, op_righttype,
3030 : BTLessEqualStrategyNumber);
3031 184480 : lsortop = ltop;
3032 184480 : rsortop = ltop;
3033 184480 : lstatop = lsortop;
3034 184480 : rstatop = rsortop;
3035 184480 : revltop = ltop;
3036 184480 : revleop = leop;
3037 : }
3038 : else
3039 : {
3040 1322 : ltop = get_opfamily_member(opfamily,
3041 : op_lefttype, op_righttype,
3042 : BTLessStrategyNumber);
3043 1322 : leop = get_opfamily_member(opfamily,
3044 : op_lefttype, op_righttype,
3045 : BTLessEqualStrategyNumber);
3046 1322 : lsortop = get_opfamily_member(opfamily,
3047 : op_lefttype, op_lefttype,
3048 : BTLessStrategyNumber);
3049 1322 : rsortop = get_opfamily_member(opfamily,
3050 : op_righttype, op_righttype,
3051 : BTLessStrategyNumber);
3052 1322 : lstatop = lsortop;
3053 1322 : rstatop = rsortop;
3054 1322 : revltop = get_opfamily_member(opfamily,
3055 : op_righttype, op_lefttype,
3056 : BTLessStrategyNumber);
3057 1322 : revleop = get_opfamily_member(opfamily,
3058 : op_righttype, op_lefttype,
3059 : BTLessEqualStrategyNumber);
3060 : }
3061 185802 : break;
3062 54 : case BTGreaterStrategyNumber:
3063 : /* descending-order case */
3064 54 : isgt = true;
3065 54 : if (op_lefttype == op_righttype)
3066 : {
3067 : /* easy case */
3068 54 : ltop = get_opfamily_member(opfamily,
3069 : op_lefttype, op_righttype,
3070 : BTGreaterStrategyNumber);
3071 54 : leop = get_opfamily_member(opfamily,
3072 : op_lefttype, op_righttype,
3073 : BTGreaterEqualStrategyNumber);
3074 54 : lsortop = ltop;
3075 54 : rsortop = ltop;
3076 54 : lstatop = get_opfamily_member(opfamily,
3077 : op_lefttype, op_lefttype,
3078 : BTLessStrategyNumber);
3079 54 : rstatop = lstatop;
3080 54 : revltop = ltop;
3081 54 : revleop = leop;
3082 : }
3083 : else
3084 : {
3085 0 : ltop = get_opfamily_member(opfamily,
3086 : op_lefttype, op_righttype,
3087 : BTGreaterStrategyNumber);
3088 0 : leop = get_opfamily_member(opfamily,
3089 : op_lefttype, op_righttype,
3090 : BTGreaterEqualStrategyNumber);
3091 0 : lsortop = get_opfamily_member(opfamily,
3092 : op_lefttype, op_lefttype,
3093 : BTGreaterStrategyNumber);
3094 0 : rsortop = get_opfamily_member(opfamily,
3095 : op_righttype, op_righttype,
3096 : BTGreaterStrategyNumber);
3097 0 : lstatop = get_opfamily_member(opfamily,
3098 : op_lefttype, op_lefttype,
3099 : BTLessStrategyNumber);
3100 0 : rstatop = get_opfamily_member(opfamily,
3101 : op_righttype, op_righttype,
3102 : BTLessStrategyNumber);
3103 0 : revltop = get_opfamily_member(opfamily,
3104 : op_righttype, op_lefttype,
3105 : BTGreaterStrategyNumber);
3106 0 : revleop = get_opfamily_member(opfamily,
3107 : op_righttype, op_lefttype,
3108 : BTGreaterEqualStrategyNumber);
3109 : }
3110 54 : break;
3111 0 : default:
3112 0 : goto fail; /* shouldn't get here */
3113 : }
3114 :
3115 185856 : if (!OidIsValid(lsortop) ||
3116 185856 : !OidIsValid(rsortop) ||
3117 185856 : !OidIsValid(lstatop) ||
3118 185856 : !OidIsValid(rstatop) ||
3119 185844 : !OidIsValid(ltop) ||
3120 185844 : !OidIsValid(leop) ||
3121 185844 : !OidIsValid(revltop) ||
3122 : !OidIsValid(revleop))
3123 12 : goto fail; /* insufficient info in catalogs */
3124 :
3125 : /* Try to get ranges of both inputs */
3126 185844 : if (!isgt)
3127 : {
3128 185790 : if (!get_variable_range(root, &leftvar, lstatop, collation,
3129 : &leftmin, &leftmax))
3130 57772 : goto fail; /* no range available from stats */
3131 128018 : if (!get_variable_range(root, &rightvar, rstatop, collation,
3132 : &rightmin, &rightmax))
3133 19976 : goto fail; /* no range available from stats */
3134 : }
3135 : else
3136 : {
3137 : /* need to swap the max and min */
3138 54 : if (!get_variable_range(root, &leftvar, lstatop, collation,
3139 : &leftmax, &leftmin))
3140 30 : goto fail; /* no range available from stats */
3141 24 : if (!get_variable_range(root, &rightvar, rstatop, collation,
3142 : &rightmax, &rightmin))
3143 0 : 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 108066 : selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
3152 : rightmax, op_righttype);
3153 108066 : if (selec != DEFAULT_INEQ_SEL)
3154 108060 : *leftend = selec;
3155 :
3156 : /* And similarly for the right variable. */
3157 108066 : selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
3158 : leftmax, op_lefttype);
3159 108066 : if (selec != DEFAULT_INEQ_SEL)
3160 108066 : *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 108066 : if (*leftend > *rightend)
3169 45408 : *leftend = 1.0;
3170 62658 : else if (*leftend < *rightend)
3171 54226 : *rightend = 1.0;
3172 : else
3173 8432 : *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 108066 : selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
3182 : rightmin, op_righttype);
3183 108066 : if (selec != DEFAULT_INEQ_SEL)
3184 108066 : *leftstart = selec;
3185 :
3186 : /* And similarly for the right variable. */
3187 108066 : selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
3188 : leftmin, op_lefttype);
3189 108066 : if (selec != DEFAULT_INEQ_SEL)
3190 108066 : *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 108066 : if (*leftstart < *rightstart)
3199 29518 : *leftstart = 0.0;
3200 78548 : else if (*leftstart > *rightstart)
3201 42738 : *rightstart = 0.0;
3202 : else
3203 35810 : *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 108066 : if (nulls_first)
3212 : {
3213 : Form_pg_statistic stats;
3214 :
3215 24 : if (HeapTupleIsValid(leftvar.statsTuple))
3216 : {
3217 24 : stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3218 24 : *leftstart += stats->stanullfrac;
3219 24 : CLAMP_PROBABILITY(*leftstart);
3220 24 : *leftend += stats->stanullfrac;
3221 24 : CLAMP_PROBABILITY(*leftend);
3222 : }
3223 24 : if (HeapTupleIsValid(rightvar.statsTuple))
3224 : {
3225 24 : stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3226 24 : *rightstart += stats->stanullfrac;
3227 24 : CLAMP_PROBABILITY(*rightstart);
3228 24 : *rightend += stats->stanullfrac;
3229 24 : CLAMP_PROBABILITY(*rightend);
3230 : }
3231 : }
3232 :
3233 : /* Disbelieve start >= end, just in case that can happen */
3234 108066 : if (*leftstart >= *leftend)
3235 : {
3236 216 : *leftstart = 0.0;
3237 216 : *leftend = 1.0;
3238 : }
3239 108066 : if (*rightstart >= *rightend)
3240 : {
3241 924 : *rightstart = 0.0;
3242 924 : *rightend = 1.0;
3243 : }
3244 :
3245 107142 : fail:
3246 185856 : ReleaseVariableStats(leftvar);
3247 185856 : 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 :
3260 : Datum
3261 1106 : matchingsel(PG_FUNCTION_ARGS)
3262 : {
3263 1106 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
3264 1106 : Oid operator = PG_GETARG_OID(1);
3265 1106 : List *args = (List *) PG_GETARG_POINTER(2);
3266 1106 : int varRelid = PG_GETARG_INT32(3);
3267 1106 : Oid collation = PG_GET_COLLATION();
3268 : double selec;
3269 :
3270 : /* Use generic restriction selectivity logic. */
3271 1106 : selec = generic_restriction_selectivity(root, operator, collation,
3272 : args, varRelid,
3273 : DEFAULT_MATCHING_SEL);
3274 :
3275 1106 : PG_RETURN_FLOAT8((float8) selec);
3276 : }
3277 :
3278 : Datum
3279 6 : matchingjoinsel(PG_FUNCTION_ARGS)
3280 : {
3281 : /* Just punt, for the moment. */
3282 6 : PG_RETURN_FLOAT8(DEFAULT_MATCHING_SEL);
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 : */
3291 : typedef 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 :
3299 : static List *
3300 494716 : add_unique_group_var(PlannerInfo *root, List *varinfos,
3301 : Node *var, VariableStatData *vardata)
3302 : {
3303 : GroupVarInfo *varinfo;
3304 : double ndistinct;
3305 : bool isdefault;
3306 : ListCell *lc;
3307 :
3308 494716 : 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 494716 : var = remove_nulling_relids(var, root->outer_join_rels, NULL);
3318 :
3319 649718 : foreach(lc, varinfos)
3320 : {
3321 155810 : varinfo = (GroupVarInfo *) lfirst(lc);
3322 :
3323 : /* Drop exact duplicates */
3324 155810 : if (equal(var, varinfo->var))
3325 808 : 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 161046 : if (vardata->rel != varinfo->rel &&
3333 5924 : exprs_known_equal(root, var, varinfo->var, InvalidOid))
3334 : {
3335 120 : if (varinfo->ndistinct <= ndistinct)
3336 : {
3337 : /* Keep older item, forget new one */
3338 120 : return varinfos;
3339 : }
3340 : else
3341 : {
3342 : /* Delete the older item */
3343 0 : varinfos = foreach_delete_current(varinfos, lc);
3344 : }
3345 : }
3346 : }
3347 :
3348 493908 : varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3349 :
3350 493908 : varinfo->var = var;
3351 493908 : varinfo->rel = vardata->rel;
3352 493908 : varinfo->ndistinct = ndistinct;
3353 493908 : varinfo->isdefault = isdefault;
3354 493908 : varinfos = lappend(varinfos, varinfo);
3355 493908 : 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 : */
3429 : double
3430 387890 : estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3431 : List **pgset, EstimationInfo *estinfo)
3432 : {
3433 387890 : List *varinfos = NIL;
3434 387890 : 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 387890 : if (estinfo != NULL)
3441 357286 : 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 387890 : 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 387890 : if (groupExprs == NIL || (pgset && *pgset == NIL))
3457 1006 : 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 386884 : numdistinct = 1.0;
3467 :
3468 386884 : i = 0;
3469 880152 : foreach(l, groupExprs)
3470 : {
3471 493316 : 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 493316 : if (pgset && !list_member_int(*pgset, i++))
3479 373306 : 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 492528 : this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3493 492528 : if (srf_multiplier < this_srf_multiplier)
3494 132 : srf_multiplier = this_srf_multiplier;
3495 :
3496 : /* Short-circuit for expressions returning boolean */
3497 492528 : if (exprType(groupexpr) == BOOLOID)
3498 : {
3499 240 : numdistinct *= 2.0;
3500 240 : 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 492288 : examine_variable(root, groupexpr, 0, &vardata);
3517 492288 : if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3518 : {
3519 371654 : varinfos = add_unique_group_var(root, varinfos,
3520 : groupexpr, &vardata);
3521 371654 : ReleaseVariableStats(vardata);
3522 371654 : continue;
3523 : }
3524 120634 : 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 120634 : varshere = pull_var_clause(groupexpr,
3533 : PVC_RECURSE_AGGREGATES |
3534 : PVC_RECURSE_WINDOWFUNCS |
3535 : PVC_RECURSE_PLACEHOLDERS);
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 120634 : if (varshere == NIL)
3544 : {
3545 672 : if (contain_volatile_functions(groupexpr))
3546 48 : return input_rows;
3547 624 : continue;
3548 : }
3549 :
3550 : /*
3551 : * Else add variables to varinfos list
3552 : */
3553 243024 : foreach(l2, varshere)
3554 : {
3555 123062 : Node *var = (Node *) lfirst(l2);
3556 :
3557 123062 : examine_variable(root, var, 0, &vardata);
3558 123062 : varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3559 123062 : 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 386836 : if (varinfos == NIL)
3568 : {
3569 : /* Apply SRF multiplier as we would do in the long path */
3570 334 : numdistinct *= srf_multiplier;
3571 : /* Round off */
3572 334 : numdistinct = ceil(numdistinct);
3573 : /* Guard against out-of-range answers */
3574 334 : if (numdistinct > input_rows)
3575 38 : numdistinct = input_rows;
3576 334 : if (numdistinct < 1.0)
3577 0 : numdistinct = 1.0;
3578 334 : 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 388444 : GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3592 388444 : RelOptInfo *rel = varinfo1->rel;
3593 388444 : double reldistinct = 1;
3594 388444 : double relmaxndistinct = reldistinct;
3595 388444 : int relvarcount = 0;
3596 388444 : List *newvarinfos = NIL;
3597 388444 : 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 388444 : relvarinfos = lappend(relvarinfos, varinfo1);
3604 499070 : for_each_from(l, varinfos, 1)
3605 : {
3606 110626 : GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3607 :
3608 110626 : if (varinfo2->rel == varinfo1->rel)
3609 : {
3610 : /* varinfos on current rel */
3611 105464 : relvarinfos = lappend(relvarinfos, varinfo2);
3612 : }
3613 : else
3614 : {
3615 : /* not time to process varinfo2 yet */
3616 5162 : 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 777014 : while (relvarinfos)
3633 : {
3634 : double mvndistinct;
3635 :
3636 388570 : if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3637 : &mvndistinct))
3638 : {
3639 402 : reldistinct *= mvndistinct;
3640 402 : if (relmaxndistinct < mvndistinct)
3641 390 : relmaxndistinct = mvndistinct;
3642 402 : relvarcount++;
3643 : }
3644 : else
3645 : {
3646 881224 : foreach(l, relvarinfos)
3647 : {
3648 493056 : GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3649 :
3650 493056 : reldistinct *= varinfo2->ndistinct;
3651 493056 : if (relmaxndistinct < varinfo2->ndistinct)
3652 386764 : relmaxndistinct = varinfo2->ndistinct;
3653 493056 : 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 493056 : if (estinfo != NULL && varinfo2->isdefault)
3660 86464 : estinfo->flags |= SELFLAG_USED_DEFAULT;
3661 : }
3662 :
3663 : /* we're done with this relation */
3664 388168 : 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 388444 : 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 387420 : double clamp = rel->tuples;
3682 :
3683 387420 : if (relvarcount > 1)
3684 : {
3685 99714 : clamp *= 0.1;
3686 99714 : if (clamp < relmaxndistinct)
3687 : {
3688 98102 : clamp = relmaxndistinct;
3689 : /* for sanity in case some ndistinct is too large: */
3690 98102 : if (clamp > rel->tuples)
3691 78 : clamp = rel->tuples;
3692 : }
3693 : }
3694 387420 : if (reldistinct > clamp)
3695 97798 : 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 387420 : 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 116228 : reldistinct *=
3739 116228 : (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3740 116228 : rel->tuples / reldistinct));
3741 : }
3742 387420 : reldistinct = clamp_row_est(reldistinct);
3743 :
3744 : /*
3745 : * Update estimate of total distinct groups.
3746 : */
3747 387420 : numdistinct *= reldistinct;
3748 : }
3749 :
3750 388444 : varinfos = newvarinfos;
3751 388444 : } while (varinfos != NIL);
3752 :
3753 : /* Now we can account for the effects of any SRFs */
3754 386502 : numdistinct *= srf_multiplier;
3755 :
3756 : /* Round off */
3757 386502 : numdistinct = ceil(numdistinct);
3758 :
3759 : /* Guard against out-of-range answers */
3760 386502 : if (numdistinct > input_rows)
3761 77182 : numdistinct = input_rows;
3762 386502 : if (numdistinct < 1.0)
3763 0 : numdistinct = 1.0;
3764 :
3765 386502 : 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 : */
3811 : void
3812 274854 : estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets,
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 274854 : examine_variable(root, hashkey, 0, &vardata);
3825 :
3826 : /* Look up the frequency of the most common value, if available */
3827 274854 : *mcv_freq = 0.0;
3828 :
3829 274854 : if (HeapTupleIsValid(vardata.statsTuple))
3830 : {
3831 206782 : if (get_attstatsslot(&sslot, vardata.statsTuple,
3832 : STATISTIC_KIND_MCV, InvalidOid,
3833 : ATTSTATSSLOT_NUMBERS))
3834 : {
3835 : /*
3836 : * The first MCV stat is for the most common value.
3837 : */
3838 106438 : if (sslot.nnumbers > 0)
3839 106438 : *mcv_freq = sslot.numbers[0];
3840 106438 : free_attstatsslot(&sslot);
3841 : }
3842 : }
3843 :
3844 : /* Get number of distinct values */
3845 274854 : 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 274854 : if (isdefault)
3852 : {
3853 43278 : *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3854 43278 : ReleaseVariableStats(vardata);
3855 43278 : return;
3856 : }
3857 :
3858 : /* Get fraction that are null */
3859 231576 : if (HeapTupleIsValid(vardata.statsTuple))
3860 : {
3861 : Form_pg_statistic stats;
3862 :
3863 206764 : stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3864 206764 : stanullfrac = stats->stanullfrac;
3865 : }
3866 : else
3867 24812 : stanullfrac = 0.0;
3868 :
3869 : /* Compute avg freq of all distinct data values in raw relation */
3870 231576 : 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 231576 : if (vardata.rel && vardata.rel->tuples > 0)
3881 : {
3882 231562 : ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3883 231562 : 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 231576 : if (ndistinct > nbuckets)
3892 92 : estfract = 1.0 / nbuckets;
3893 : else
3894 231484 : estfract = 1.0 / ndistinct;
3895 :
3896 : /*
3897 : * Adjust estimated bucketsize upward to account for skewed distribution.
3898 : */
3899 231576 : if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3900 101314 : 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 231576 : if (estfract < 1.0e-6)
3908 0 : estfract = 1.0e-6;
3909 231576 : else if (estfract > 1.0)
3910 66504 : estfract = 1.0;
3911 :
3912 231576 : *bucketsize_frac = (Selectivity) estfract;
3913 :
3914 231576 : 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 : */
3930 : double
3931 2242 : estimate_hashagg_tablesize(PlannerInfo *root, Path *path,
3932 : const AggClauseCosts *agg_costs, double dNumGroups)
3933 : {
3934 : Size hashentrysize;
3935 :
3936 2242 : hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
3937 2242 : 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 2242 : 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 : */
3967 : static bool
3968 388570 : estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel,
3969 : List **varinfos, double *ndistinct)
3970 : {
3971 : ListCell *lc;
3972 : int nmatches_vars;
3973 : int nmatches_exprs;
3974 388570 : Oid statOid = InvalidOid;
3975 : MVNDistinct *stats;
3976 388570 : StatisticExtInfo *matched_info = NULL;
3977 388570 : RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
3978 :
3979 : /* bail out immediately if the table has no extended statistics */
3980 388570 : if (!rel->statlist)
3981 388042 : return false;
3982 :
3983 : /* look for the ndistinct statistics object matching the most vars */
3984 528 : nmatches_vars = 0; /* we require at least two matches */
3985 528 : nmatches_exprs = 0;
3986 2124 : foreach(lc, rel->statlist)
3987 : {
3988 : ListCell *lc2;
3989 1596 : StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3990 1596 : int nshared_vars = 0;
3991 1596 : int nshared_exprs = 0;
3992 :
3993 : /* skip statistics of other kinds */
3994 1596 : if (info->kind != STATS_EXT_NDISTINCT)
3995 750 : continue;
3996 :
3997 : /* skip statistics with mismatching stxdinherit value */
3998 846 : if (info->inherit != rte->inh)
3999 24 : 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 2628 : foreach(lc2, *varinfos)
4007 : {
4008 : ListCell *lc3;
4009 1806 : GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4010 : AttrNumber attnum;
4011 :
4012 : Assert(varinfo->rel == rel);
4013 :
4014 : /* simple Var, search in statistics keys directly */
4015 1806 : if (IsA(varinfo->var, Var))
4016 : {
4017 1440 : 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 : */
4024 1440 : if (!AttrNumberIsForUserDefinedAttr(attnum))
4025 12 : continue;
4026 :
4027 1428 : if (bms_is_member(attnum, info->keys))
4028 822 : nshared_vars++;
4029 :
4030 1428 : continue;
4031 : }
4032 :
4033 : /* expression - see if it's in the statistics object */
4034 660 : foreach(lc3, info->exprs)
4035 : {
4036 528 : Node *expr = (Node *) lfirst(lc3);
4037 :
4038 528 : if (equal(varinfo->var, expr))
4039 : {
4040 234 : nshared_exprs++;
4041 234 : break;
4042 : }
4043 : }
4044 : }
4045 :
4046 822 : if (nshared_vars + nshared_exprs < 2)
4047 384 : 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 438 : if ((nshared_exprs > nmatches_exprs) ||
4057 330 : (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
4058 : {
4059 414 : statOid = info->statOid;
4060 414 : nmatches_vars = nshared_vars;
4061 414 : nmatches_exprs = nshared_exprs;
4062 414 : matched_info = info;
4063 : }
4064 : }
4065 :
4066 : /* No match? */
4067 528 : if (statOid == InvalidOid)
4068 126 : return false;
4069 :
4070 : Assert(nmatches_vars + nmatches_exprs > 1);
4071 :
4072 402 : 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 402 : if (stats)
4079 : {
4080 : int i;
4081 402 : List *newlist = NIL;
4082 402 : MVNDistinctItem *item = NULL;
4083 : ListCell *lc2;
4084 402 : 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 402 : if (matched_info->exprs)
4093 144 : attnum_offset = (list_length(matched_info->exprs) + 1);
4094 : else
4095 258 : attnum_offset = 0;
4096 :
4097 : /* see what actually matched */
4098 1410 : foreach(lc2, *varinfos)
4099 : {
4100 : ListCell *lc3;
4101 : int idx;
4102 1008 : bool found = false;
4103 :
4104 1008 : 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 1008 : if (IsA(varinfo->var, Var))
4112 : {
4113 822 : 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 : */
4119 822 : if (!AttrNumberIsForUserDefinedAttr(attnum))
4120 6 : continue;
4121 :
4122 : /* Is the variable covered by the statistics object? */
4123 816 : if (!bms_is_member(attnum, matched_info->keys))
4124 120 : continue;
4125 :
4126 696 : attnum = attnum + attnum_offset;
4127 :
4128 : /* ensure sufficient offset */
4129 : Assert(AttrNumberIsForUserDefinedAttr(attnum));
4130 :
4131 696 : matched = bms_add_member(matched, attnum);
4132 :
4133 696 : 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 882 : if (found)
4142 696 : continue;
4143 :
4144 : /* expression - see if it's in the statistics object */
4145 186 : idx = 0;
4146 306 : foreach(lc3, matched_info->exprs)
4147 : {
4148 276 : Node *expr = (Node *) lfirst(lc3);
4149 :
4150 276 : if (equal(varinfo->var, expr))
4151 : {
4152 156 : AttrNumber attnum = -(idx + 1);
4153 :
4154 156 : attnum = attnum + attnum_offset;
4155 :
4156 : /* ensure sufficient offset */
4157 : Assert(AttrNumberIsForUserDefinedAttr(attnum));
4158 :
4159 156 : matched = bms_add_member(matched, attnum);
4160 :
4161 : /* there should be just one matching expression */
4162 156 : break;
4163 : }
4164 :
4165 120 : idx++;
4166 : }
4167 : }
4168 :
4169 : /* Find the specific item that exactly matches the combination */
4170 822 : for (i = 0; i < stats->nitems; i++)
4171 : {
4172 : int j;
4173 822 : MVNDistinctItem *tmpitem = &stats->items[i];
4174 :
4175 822 : if (tmpitem->nattributes != bms_num_members(matched))
4176 144 : continue;
4177 :
4178 : /* assume it's the right item */
4179 678 : item = tmpitem;
4180 :
4181 : /* check that all item attributes/expressions fit the match */
4182 1614 : for (j = 0; j < tmpitem->nattributes; j++)
4183 : {
4184 1212 : 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 1212 : attnum = attnum + attnum_offset;
4191 :
4192 1212 : if (!bms_is_member(attnum, matched))
4193 : {
4194 : /* nah, it's not this item */
4195 276 : item = NULL;
4196 276 : 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 678 : if (item)
4205 402 : 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 402 : if (!item)
4213 0 : elog(ERROR, "corrupt MVNDistinct entry");
4214 :
4215 : /* Form the output varinfo list, keeping only unmatched ones */
4216 1410 : foreach(lc, *varinfos)
4217 : {
4218 1008 : GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
4219 : ListCell *lc3;
4220 1008 : 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 1008 : if (IsA(varinfo->var, Var))
4228 : {
4229 822 : 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 : */
4236 822 : if (!AttrNumberIsForUserDefinedAttr(attnum))
4237 : {
4238 6 : newlist = lappend(newlist, varinfo);
4239 6 : continue;
4240 : }
4241 :
4242 : /* apply the same offset as above */
4243 816 : attnum += attnum_offset;
4244 :
4245 : /* if it's not matched, keep the varinfo */
4246 816 : if (!bms_is_member(attnum, matched))
4247 120 : newlist = lappend(newlist, varinfo);
4248 :
4249 : /* The rest of the loop deals with complex expressions. */
4250 816 : 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 306 : foreach(lc3, matched_info->exprs)
4264 : {
4265 276 : Node *expr = (Node *) lfirst(lc3);
4266 :
4267 276 : if (equal(varinfo->var, expr))
4268 : {
4269 156 : found = true;
4270 156 : break;
4271 : }
4272 : }
4273 :
4274 : /* found exact match, skip */
4275 186 : if (found)
4276 156 : continue;
4277 :
4278 30 : newlist = lappend(newlist, varinfo);
4279 : }
4280 :
4281 402 : *varinfos = newlist;
4282 402 : *ndistinct = item->ndistinct;
4283 402 : return true;
4284 : }
4285 :
4286 0 : 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 : */
4318 : static bool
4319 127280 : convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue,
4320 : Datum lobound, Datum hibound, Oid boundstypid,
4321 : double *scaledlobound, double *scaledhibound)
4322 : {
4323 127280 : 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 127280 : switch (valuetypid)
4344 : {
4345 : /*
4346 : * Built-in numeric types
4347 : */
4348 122352 : 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 122352 : *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4368 : &failure);
4369 122352 : *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4370 : &failure);
4371 122352 : *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4372 : &failure);
4373 122352 : return !failure;
4374 :
4375 : /*
4376 : * Built-in string types
4377 : */
4378 4928 : case CHAROID:
4379 : case BPCHAROID:
4380 : case VARCHAROID:
4381 : case TEXTOID:
4382 : case NAMEOID:
4383 : {
4384 4928 : char *valstr = convert_string_datum(value, valuetypid,
4385 : collid, &failure);
4386 4928 : char *lostr = convert_string_datum(lobound, boundstypid,
4387 : collid, &failure);
4388 4928 : 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 4928 : if (failure)
4397 0 : return false;
4398 :
4399 4928 : convert_string_to_scalar(valstr, scaledvalue,
4400 : lostr, scaledlobound,
4401 : histr, scaledhibound);
4402 4928 : pfree(valstr);
4403 4928 : pfree(lostr);
4404 4928 : pfree(histr);
4405 4928 : return true;
4406 : }
4407 :
4408 : /*
4409 : * Built-in bytea type
4410 : */
4411 0 : case BYTEAOID:
4412 : {
4413 : /* We only support bytea vs bytea comparison */
4414 0 : if (boundstypid != BYTEAOID)
4415 0 : return false;
4416 0 : convert_bytea_to_scalar(value, scaledvalue,
4417 : lobound, scaledlobound,
4418 : hibound, scaledhibound);
4419 0 : return true;
4420 : }
4421 :
4422 : /*
4423 : * Built-in time types
4424 : */
4425 0 : case TIMESTAMPOID:
4426 : case TIMESTAMPTZOID:
4427 : case DATEOID:
4428 : case INTERVALOID:
4429 : case TIMEOID:
4430 : case TIMETZOID:
4431 0 : *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
4432 : &failure);
4433 0 : *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
4434 : &failure);
4435 0 : *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
4436 : &failure);
4437 0 : return !failure;
4438 :
4439 : /*
4440 : * Built-in network types
4441 : */
4442 0 : case INETOID:
4443 : case CIDROID:
4444 : case MACADDROID:
4445 : case MACADDR8OID:
4446 0 : *scaledvalue = convert_network_to_scalar(value, valuetypid,
4447 : &failure);
4448 0 : *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
4449 : &failure);
4450 0 : *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
4451 : &failure);
4452 0 : return !failure;
4453 : }
4454 : /* Don't know how to convert */
4455 0 : *scaledvalue = *scaledlobound = *scaledhibound = 0;
4456 0 : 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 : */
4465 : static double
4466 367056 : convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
4467 : {
4468 367056 : switch (typid)
4469 : {
4470 0 : case BOOLOID:
4471 0 : return (double) DatumGetBool(value);
4472 12 : case INT2OID:
4473 12 : return (double) DatumGetInt16(value);
4474 30528 : case INT4OID:
4475 30528 : return (double) DatumGetInt32(value);
4476 0 : case INT8OID:
4477 0 : return (double) DatumGetInt64(value);
4478 0 : case FLOAT4OID:
4479 0 : return (double) DatumGetFloat4(value);
4480 54 : case FLOAT8OID:
4481 54 : return (double) DatumGetFloat8(value);
4482 0 : case NUMERICOID:
4483 : /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4484 0 : return (double)
4485 0 : DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
4486 : value));
4487 336462 : 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 336462 : return (double) DatumGetObjectId(value);
4501 : }
4502 :
4503 0 : *failure = true;
4504 0 : 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 : */
4527 : static void
4528 4928 : convert_string_to_scalar(char *value,
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 4928 : rangelo = rangehi = (unsigned char) hibound[0];
4540 65752 : for (sptr = lobound; *sptr; sptr++)
4541 : {
4542 60824 : if (rangelo > (unsigned char) *sptr)
4543 12188 : rangelo = (unsigned char) *sptr;
4544 60824 : if (rangehi < (unsigned char) *sptr)
4545 6650 : rangehi = (unsigned char) *sptr;
4546 : }
4547 69640 : for (sptr = hibound; *sptr; sptr++)
4548 : {
4549 64712 : if (rangelo > (unsigned char) *sptr)
4550 938 : rangelo = (unsigned char) *sptr;
4551 64712 : if (rangehi < (unsigned char) *sptr)
4552 2368 : rangehi = (unsigned char) *sptr;
4553 : }
4554 : /* If range includes any upper-case ASCII chars, make it include all */
4555 4928 : if (rangelo <= 'Z' && rangehi >= 'A')
4556 : {
4557 904 : if (rangelo > 'A')
4558 138 : rangelo = 'A';
4559 904 : if (rangehi < 'Z')
4560 480 : rangehi = 'Z';
4561 : }
4562 : /* Ditto lower-case */
4563 4928 : if (rangelo <= 'z' && rangehi >= 'a')
4564 : {
4565 4426 : if (rangelo > 'a')
4566 0 : rangelo = 'a';
4567 4426 : if (rangehi < 'z')
4568 4376 : rangehi = 'z';
4569 : }
4570 : /* Ditto digits */
4571 4928 : if (rangelo <= '9' && rangehi >= '0')
4572 : {
4573 308 : if (rangelo > '0')
4574 214 : rangelo = '0';
4575 308 : if (rangehi < '9')
4576 14 : 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 4928 : if (rangehi - rangelo < 9)
4584 : {
4585 0 : rangelo = ' ';
4586 0 : rangehi = 127;
4587 : }
4588 :
4589 : /*
4590 : * Now strip any common prefix of the three strings.
4591 : */
4592 8848 : while (*lobound)
4593 : {
4594 8848 : if (*lobound != *hibound || *lobound != *value)
4595 : break;
4596 3920 : lobound++, hibound++, value++;
4597 : }
4598 :
4599 : /*
4600 : * Now we can do the conversions.
4601 : */
4602 4928 : *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4603 4928 : *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4604 4928 : *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4605 4928 : }
4606 :
4607 : static double
4608 14784 : convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
4609 : {
4610 14784 : int slen = strlen(value);
4611 : double num,
4612 : denom,
4613 : base;
4614 :
4615 14784 : if (slen <= 0)
4616 0 : 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 14784 : if (slen > 12)
4628 4384 : slen = 12;
4629 :
4630 : /* Convert initial characters to fraction */
4631 14784 : base = rangehi - rangelo + 1;
4632 14784 : num = 0.0;
4633 14784 : denom = base;
4634 126388 : while (slen-- > 0)
4635 : {
4636 111604 : int ch = (unsigned char) *value++;
4637 :
4638 111604 : if (ch < rangelo)
4639 256 : ch = rangelo - 1;
4640 111348 : else if (ch > rangehi)
4641 0 : ch = rangehi + 1;
4642 111604 : num += ((double) (ch - rangelo)) / denom;
4643 111604 : denom *= base;
4644 : }
4645 :
4646 14784 : 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 : */
4658 : static char *
4659 14784 : convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
4660 : {
4661 : char *val;
4662 : pg_locale_t mylocale;
4663 :
4664 14784 : switch (typid)
4665 : {
4666 0 : case CHAROID:
4667 0 : val = (char *) palloc(2);
4668 0 : val[0] = DatumGetChar(value);
4669 0 : val[1] = '\0';
4670 0 : break;
4671 4476 : case BPCHAROID:
4672 : case VARCHAROID:
4673 : case TEXTOID:
4674 4476 : val = TextDatumGetCString(value);
4675 4476 : break;
4676 10308 : case NAMEOID:
4677 : {
4678 10308 : NameData *nm = (NameData *) DatumGetPointer(value);
4679 :
4680 10308 : val = pstrdup(NameStr(*nm));
4681 10308 : break;
4682 : }
4683 0 : default:
4684 0 : *failure = true;
4685 0 : return NULL;
4686 : }
4687 :
4688 14784 : mylocale = pg_newlocale_from_collation(collid);
4689 :
4690 14784 : 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 72 : 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 72 : xfrmstr = (char *) palloc(xfrmlen + 1);
4721 72 : 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 72 : pfree(val);
4729 72 : val = xfrmstr;
4730 : }
4731 :
4732 14784 : 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 : */
4746 : static void
4747 0 : convert_bytea_to_scalar(Datum value,
4748 : double *scaledvalue,
4749 : Datum lobound,
4750 : double *scaledlobound,
4751 : Datum hibound,
4752 : double *scaledhibound)
4753 : {
4754 0 : bytea *valuep = DatumGetByteaPP(value);
4755 0 : bytea *loboundp = DatumGetByteaPP(lobound);
4756 0 : bytea *hiboundp = DatumGetByteaPP(hibound);
4757 : int rangelo,
4758 : rangehi,
4759 0 : valuelen = VARSIZE_ANY_EXHDR(valuep),
4760 0 : loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4761 0 : hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4762 : i,
4763 : minlen;
4764 0 : unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4765 0 : unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4766 0 : unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4767 :
4768 : /*
4769 : * Assume bytea data is uniformly distributed across all byte values.
4770 : */
4771 0 : rangelo = 0;
4772 0 : rangehi = 255;
4773 :
4774 : /*
4775 : * Now strip any common prefix of the three strings.
4776 : */
4777 0 : minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4778 0 : for (i = 0; i < minlen; i++)
4779 : {
4780 0 : if (*lostr != *histr || *lostr != *valstr)
4781 : break;
4782 0 : lostr++, histr++, valstr++;
4783 0 : loboundlen--, hiboundlen--, valuelen--;
4784 : }
4785 :
4786 : /*
4787 : * Now we can do the conversions.
4788 : */
4789 0 : *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4790 0 : *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4791 0 : *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4792 0 : }
4793 :
4794 : static double
4795 0 : convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
4796 : int rangelo, int rangehi)
4797 : {
4798 : double num,
4799 : denom,
4800 : base;
4801 :
4802 0 : if (valuelen <= 0)
4803 0 : 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 0 : if (valuelen > 10)
4810 0 : valuelen = 10;
4811 :
4812 : /* Convert initial characters to fraction */
4813 0 : base = rangehi - rangelo + 1;
4814 0 : num = 0.0;
4815 0 : denom = base;
4816 0 : while (valuelen-- > 0)
4817 : {
4818 0 : int ch = *value++;
4819 :
4820 0 : if (ch < rangelo)
4821 0 : ch = rangelo - 1;
4822 0 : else if (ch > rangehi)
4823 0 : ch = rangehi + 1;
4824 0 : num += ((double) (ch - rangelo)) / denom;
4825 0 : denom *= base;
4826 : }
4827 :
4828 0 : 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 : */
4837 : static double
4838 0 : convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
4839 : {
4840 0 : switch (typid)
4841 : {
4842 0 : case TIMESTAMPOID:
4843 0 : return DatumGetTimestamp(value);
4844 0 : case TIMESTAMPTZOID:
4845 0 : return DatumGetTimestampTz(value);
4846 0 : case DATEOID:
4847 0 : return date2timestamp_no_overflow(DatumGetDateADT(value));
4848 0 : case INTERVALOID:
4849 : {
4850 0 : Interval *interval = DatumGetIntervalP(value);
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 0 : return interval->time + interval->day * (double) USECS_PER_DAY +
4862 0 : interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4863 : }
4864 0 : case TIMEOID:
4865 0 : return DatumGetTimeADT(value);
4866 0 : case TIMETZOID:
4867 : {
4868 0 : TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4869 :
4870 : /* use GMT-equivalent time */
4871 0 : return (double) (timetz->time + (timetz->zone * 1000000.0));
4872 : }
4873 : }
4874 :
4875 0 : *failure = true;
4876 0 : 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 : */
4903 : bool
4904 1180274 : get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
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 1180274 : if (list_length(args) != 2)
4914 0 : return false;
4915 :
4916 1180274 : left = (Node *) linitial(args);
4917 1180274 : 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 1180274 : examine_variable(root, left, varRelid, vardata);
4924 1180274 : examine_variable(root, right, varRelid, &rdata);
4925 :
4926 : /*
4927 : * If one side is a variable and the other not, we win.
4928 : */
4929 1180274 : if (vardata->rel && rdata.rel == NULL)
4930 : {
4931 1027480 : *varonleft = true;
4932 1027480 : *other = estimate_expression_value(root, rdata.var);
4933 : /* Assume we need no ReleaseVariableStats(rdata) here */
4934 1027480 : return true;
4935 : }
4936 :
4937 152794 : if (vardata->rel == NULL && rdata.rel)
4938 : {
4939 147946 : *varonleft = false;
4940 147946 : *other = estimate_expression_value(root, vardata->var);
4941 : /* Assume we need no ReleaseVariableStats(*vardata) here */
4942 147946 : *vardata = rdata;
4943 147946 : return true;
4944 : }
4945 :
4946 : /* Oops, clause has wrong structure (probably var op var) */
4947 4848 : ReleaseVariableStats(*vardata);
4948 4848 : ReleaseVariableStats(rdata);
4949 :
4950 4848 : 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 : */
4963 : void
4964 370204 : get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
4965 : VariableStatData *vardata1, VariableStatData *vardata2,
4966 : bool *join_is_reversed)
4967 : {
4968 : Node *left,
4969 : *right;
4970 :
4971 370204 : if (list_length(args) != 2)
4972 0 : elog(ERROR, "join operator should take two arguments");
4973 :
4974 370204 : left = (Node *) linitial(args);
4975 370204 : right = (Node *) lsecond(args);
4976 :
4977 370204 : examine_variable(root, left, 0, vardata1);
4978 370204 : examine_variable(root, right, 0, vardata2);
4979 :
4980 740250 : if (vardata1->rel &&
4981 370046 : bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4982 76112 : *join_is_reversed = true; /* var1 is on RHS */
4983 588080 : else if (vardata2->rel &&
4984 293988 : bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4985 126 : *join_is_reversed = true; /* var2 is on LHS */
4986 : else
4987 293966 : *join_is_reversed = false;
4988 370204 : }
4989 :
4990 : /* statext_expressions_load copies the tuple, so just pfree it. */
4991 : static void
4992 1644 : ReleaseDummy(HeapTuple tuple)
4993 : {
4994 1644 : pfree(tuple);
4995 1644 : }
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, a
5022 : * single-column DISTINCT or GROUP-BY clause, implying its values are
5023 : * unique for this query. (Caution: this should be trusted for
5024 : * statistical purposes only, since we do not check indimmediate nor
5025 : * verify that 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 : */
5032 : void
5033 4522594 : examine_variable(PlannerInfo *root, Node *node, int varRelid,
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 31658158 : MemSet(vardata, 0, sizeof(VariableStatData));
5043 :
5044 : /* Save the exposed type of the expression */
5045 4522594 : vardata->vartype = exprType(node);
5046 :
5047 : /* Look inside any binary-compatible relabeling */
5048 :
5049 4522594 : if (IsA(node, RelabelType))
5050 24816 : basenode = (Node *) ((RelabelType *) node)->arg;
5051 : else
5052 4497778 : basenode = node;
5053 :
5054 : /* Fast path for a simple Var */
5055 :
5056 4522594 : if (IsA(basenode, Var) &&
5057 1471528 : (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5058 : {
5059 3248998 : Var *var = (Var *) basenode;
5060 :
5061 : /* Set up result fields other than the stats tuple */
5062 3248998 : vardata->var = basenode; /* return Var without relabeling */
5063 3248998 : vardata->rel = find_base_rel(root, var->varno);
5064 3248998 : vardata->atttype = var->vartype;
5065 3248998 : vardata->atttypmod = var->vartypmod;
5066 3248998 : vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5067 :
5068 : /* Try to locate some stats */
5069 3248998 : examine_simple_variable(root, var, vardata);
5070 :
5071 3248998 : 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 1273596 : varnos = pull_varnos(root, basenode);
5080 1273596 : basevarnos = bms_difference(varnos, root->outer_join_rels);
5081 :
5082 1273596 : onerel = NULL;
5083 :
5084 1273596 : 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 796048 : if (bms_get_singleton_member(basevarnos, &relid))
5094 : {
5095 793188 : if (varRelid == 0 || varRelid == relid)
5096 : {
5097 56522 : onerel = find_base_rel(root, relid);
5098 56522 : vardata->rel = onerel;
5099 56522 : node = basenode; /* strip any relabeling */
5100 : }
5101 : /* else treat it as a constant */
5102 : }
5103 : else
5104 : {
5105 : /* varnos has multiple relids */
5106 2860 : if (varRelid == 0)
5107 : {
5108 : /* treat it as a variable of a join relation */
5109 2630 : vardata->rel = find_join_rel(root, varnos);
5110 2630 : node = basenode; /* strip any relabeling */
5111 : }
5112 230 : else if (bms_is_member(varRelid, varnos))
5113 : {
5114 : /* ignore the vars belonging to other relations */
5115 68 : vardata->rel = find_base_rel(root, varRelid);
5116 68 : 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 1273596 : bms_free(basevarnos);
5124 :
5125 1273596 : vardata->var = node;
5126 1273596 : vardata->atttype = exprType(node);
5127 1273596 : vardata->atttypmod = exprTypmod(node);
5128 :
5129 1273596 : 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 56522 : if (bms_overlap(varnos, root->outer_join_rels))
5154 2964 : 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 56522 : userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
5166 :
5167 111230 : foreach(ilist, onerel->indexlist)
5168 : {
5169 57522 : IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5170 : ListCell *indexpr_item;
5171 : int pos;
5172 :
5173 57522 : indexpr_item = list_head(index->indexprs);
5174 57522 : if (indexpr_item == NULL)
5175 52776 : continue; /* no expressions here... */
5176 :
5177 6750 : for (pos = 0; pos < index->ncolumns; pos++)
5178 : {
5179 4818 : if (index->indexkeys[pos] == 0)
5180 : {
5181 : Node *indexkey;
5182 :
5183 4746 : if (indexpr_item == NULL)
5184 0 : elog(ERROR, "too few entries in indexprs list");
5185 4746 : indexkey = (Node *) lfirst(indexpr_item);
5186 4746 : if (indexkey && IsA(indexkey, RelabelType))
5187 0 : indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5188 4746 : 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 3450 : if (index->unique &&
5195 438 : index->nkeycolumns == 1 &&
5196 438 : pos == 0 &&
5197 438 : (index->indpred == NIL || index->predOK))
5198 438 : 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 : */
5210 3450 : if (get_index_stats_hook &&
5211 0 : (*get_index_stats_hook) (root, index->indexoid,
5212 0 : 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 0 : if (HeapTupleIsValid(vardata->statsTuple) &&
5220 0 : !vardata->freefunc)
5221 0 : elog(ERROR, "no function provided to release variable stats with");
5222 : }
5223 3450 : else if (index->indpred == NIL)
5224 : {
5225 3450 : vardata->statsTuple =
5226 6900 : SearchSysCache3(STATRELATTINH,
5227 : ObjectIdGetDatum(index->indexoid),
5228 3450 : Int16GetDatum(pos + 1),
5229 : BoolGetDatum(false));
5230 3450 : vardata->freefunc = ReleaseSysCache;
5231 :
5232 3450 : if (HeapTupleIsValid(vardata->statsTuple))
5233 : {
5234 : /* Get index's table for permission check */
5235 : RangeTblEntry *rte;
5236 :
5237 2814 : 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 2814 : vardata->acl_ok =
5250 5628 : rte->securityQuals == NIL &&
5251 2814 : (pg_class_aclcheck(rte->relid, userid,
5252 : ACL_SELECT) == ACLCHECK_OK);
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 2814 : if (!vardata->acl_ok &&
5271 18 : root->append_rel_array != NULL)
5272 : {
5273 : AppendRelInfo *appinfo;
5274 12 : Index varno = index->rel->relid;
5275 :
5276 12 : appinfo = root->append_rel_array[varno];
5277 36 : while (appinfo &&
5278 24 : planner_rt_fetch(appinfo->parent_relid,
5279 24 : root)->rtekind == RTE_RELATION)
5280 : {
5281 24 : varno = appinfo->parent_relid;
5282 24 : appinfo = root->append_rel_array[varno];
5283 : }
5284 12 : if (varno != index->rel->relid)
5285 : {
5286 : /* Repeat access check on this rel */
5287 12 : rte = planner_rt_fetch(varno, root);
5288 : Assert(rte->rtekind == RTE_RELATION);
5289 :
5290 12 : vardata->acl_ok =
5291 24 : rte->securityQuals == NIL &&
5292 12 : (pg_class_aclcheck(rte->relid,
5293 : userid,
5294 : ACL_SELECT) == ACLCHECK_OK);
5295 : }
5296 : }
5297 : }
5298 : else
5299 : {
5300 : /* suppress leakproofness checks later */
5301 636 : vardata->acl_ok = true;
5302 : }
5303 : }
5304 3450 : if (vardata->statsTuple)
5305 2814 : break;
5306 : }
5307 1932 : indexpr_item = lnext(index->indexprs, indexpr_item);
5308 : }
5309 : }
5310 4746 : if (vardata->statsTuple)
5311 2814 : 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 60548 : foreach(slist, onerel->statlist)
5321 : {
5322 4314 : StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5323 4314 : 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 4314 : if (vardata->statsTuple)
5332 288 : break;
5333 :
5334 : /* skip stats without per-expression stats */
5335 4026 : if (info->kind != STATS_EXT_EXPRESSIONS)
5336 2022 : continue;
5337 :
5338 : /* skip stats with mismatching stxdinherit value */
5339 2004 : if (info->inherit != rte->inh)
5340 6 : continue;
5341 :
5342 1998 : pos = 0;
5343 3300 : foreach(expr_item, info->exprs)
5344 : {
5345 2946 : Node *expr = (Node *) lfirst(expr_item);
5346 :
5347 : Assert(expr);
5348 :
5349 : /* strip RelabelType before comparing it */
5350 2946 : if (expr && IsA(expr, RelabelType))
5351 0 : expr = (Node *) ((RelabelType *) expr)->arg;
5352 :
5353 : /* found a match, see if we can extract pg_statistic row */
5354 2946 : 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 1644 : vardata->statsTuple =
5361 1644 : statext_expressions_load(info->statOid, rte->inh, pos);
5362 :
5363 1644 : 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 1644 : vardata->acl_ok =
5374 3288 : rte->securityQuals == NIL &&
5375 1644 : (pg_class_aclcheck(rte->relid, userid,
5376 : ACL_SELECT) == ACLCHECK_OK);
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 1644 : if (!vardata->acl_ok &&
5392 0 : root->append_rel_array != NULL)
5393 : {
5394 : AppendRelInfo *appinfo;
5395 0 : Index varno = onerel->relid;
5396 :
5397 0 : appinfo = root->append_rel_array[varno];
5398 0 : while (appinfo &&
5399 0 : planner_rt_fetch(appinfo->parent_relid,
5400 0 : root)->rtekind == RTE_RELATION)
5401 : {
5402 0 : varno = appinfo->parent_relid;
5403 0 : appinfo = root->append_rel_array[varno];
5404 : }
5405 0 : if (varno != onerel->relid)
5406 : {
5407 : /* Repeat access check on this rel */
5408 0 : rte = planner_rt_fetch(varno, root);
5409 : Assert(rte->rtekind == RTE_RELATION);
5410 :
5411 0 : vardata->acl_ok =
5412 0 : rte->securityQuals == NIL &&
5413 0 : (pg_class_aclcheck(rte->relid,
5414 : userid,
5415 : ACL_SELECT) == ACLCHECK_OK);
5416 : }
5417 : }
5418 :
5419 1644 : break;
5420 : }
5421 :
5422 1302 : pos++;
5423 : }
5424 : }
5425 : }
5426 :
5427 1273596 : 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 : */
5439 : static void
5440 3253316 : examine_simple_variable(PlannerInfo *root, Var *var,
5441 : VariableStatData *vardata)
5442 : {
5443 3253316 : RangeTblEntry *rte = root->simple_rte_array[var->varno];
5444 :
5445 : Assert(IsA(rte, RangeTblEntry));
5446 :
5447 3253316 : if (get_relation_stats_hook &&
5448 0 : (*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 0 : if (HeapTupleIsValid(vardata->statsTuple) &&
5455 0 : !vardata->freefunc)
5456 0 : elog(ERROR, "no function provided to release variable stats with");
5457 : }
5458 3253316 : 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 3181858 : vardata->statsTuple = SearchSysCache3(STATRELATTINH,
5465 : ObjectIdGetDatum(rte->relid),
5466 3181858 : Int16GetDatum(var->varattno),
5467 3181858 : BoolGetDatum(rte->inh));
5468 3181858 : vardata->freefunc = ReleaseSysCache;
5469 :
5470 3181858 : if (HeapTupleIsValid(vardata->statsTuple))
5471 : {
5472 2323344 : 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 2323344 : if (onerel)
5486 2323302 : userid = onerel->userid;
5487 : else
5488 : {
5489 : RTEPermissionInfo *perminfo;
5490 :
5491 42 : perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
5492 42 : userid = perminfo->checkAsUser;
5493 : }
5494 2323344 : if (!OidIsValid(userid))
5495 1541256 : userid = GetUserId();
5496 :
5497 2323344 : vardata->acl_ok =
5498 4646948 : rte->securityQuals == NIL &&
5499 2323344 : ((pg_class_aclcheck(rte->relid, userid,
5500 260 : ACL_SELECT) == ACLCHECK_OK) ||
5501 260 : (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 2323344 : if (!vardata->acl_ok && var->varattno > 0 &&
5515 60 : root->append_rel_array != NULL)
5516 : {
5517 : AppendRelInfo *appinfo;
5518 12 : Index varno = var->varno;
5519 12 : int varattno = var->varattno;
5520 12 : bool found = false;
5521 :
5522 12 : 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 36 : while (appinfo &&
5532 24 : planner_rt_fetch(appinfo->parent_relid,
5533 24 : root)->rtekind == RTE_RELATION)
5534 : {
5535 : int parent_varattno;
5536 :
5537 24 : found = false;
5538 24 : if (varattno <= 0 || varattno > appinfo->num_child_cols)
5539 : break; /* safety check */
5540 24 : parent_varattno = appinfo->parent_colnos[varattno - 1];
5541 24 : if (parent_varattno == 0)
5542 0 : break; /* Var is local to child */
5543 :
5544 24 : varno = appinfo->parent_relid;
5545 24 : varattno = parent_varattno;
5546 24 : found = true;
5547 :
5548 : /* If the parent is itself a child, continue up. */
5549 24 : 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 12 : if (!found)
5558 0 : return;
5559 :
5560 : /* Repeat the access check on this parent rel & column */
5561 12 : 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 12 : vardata->acl_ok =
5569 30 : rte->securityQuals == NIL &&
5570 12 : ((pg_class_aclcheck(rte->relid, userid,
5571 6 : ACL_SELECT) == ACLCHECK_OK) ||
5572 6 : (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 858514 : vardata->acl_ok = true;
5580 : }
5581 : }
5582 71458 : else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
5583 63822 : (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 12504 : if (var->varattno == InvalidAttrNumber)
5601 0 : return;
5602 :
5603 : /*
5604 : * Otherwise, find the subquery's planner subroot.
5605 : */
5606 12504 : 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 7636 : rel = find_base_rel(root, var->varno);
5618 :
5619 7636 : 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 4868 : levelsup = rte->ctelevelsup;
5635 4868 : cteroot = root;
5636 9402 : while (levelsup-- > 0)
5637 : {
5638 4534 : cteroot = cteroot->parent_root;
5639 4534 : if (!cteroot) /* shouldn't happen */
5640 0 : 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 4868 : ndx = 0;
5649 7090 : foreach(lc, cteroot->parse->cteList)
5650 : {
5651 7090 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
5652 :
5653 7090 : if (strcmp(cte->ctename, rte->ctename) == 0)
5654 4868 : break;
5655 2222 : ndx++;
5656 : }
5657 4868 : if (lc == NULL) /* shouldn't happen */
5658 0 : elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
5659 4868 : if (ndx >= list_length(cteroot->cte_plan_ids))
5660 0 : elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
5661 4868 : plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
5662 4868 : if (plan_id <= 0)
5663 0 : elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
5664 4868 : subroot = list_nth(root->glob->subroots, plan_id - 1);
5665 : }
5666 :
5667 : /* If the subquery hasn't been planned yet, we have to punt */
5668 12504 : if (subroot == NULL)
5669 0 : return;
5670 : Assert(IsA(subroot, PlannerInfo));
5671 :
5672 : /*
5673 : * We must use the subquery parsetree as mangled by the planner, not
5674 : * the raw version from the RTE, because we need a Var that will refer
5675 : * to the subroot's live RelOptInfos. For instance, if any subquery
5676 : * pullup happened during planning, Vars in the targetlist might have
5677 : * gotten replaced, and we need to see the replacement expressions.
5678 : */
5679 12504 : subquery = subroot->parse;
5680 : Assert(IsA(subquery, Query));
5681 :
5682 : /*
5683 : * Punt if subquery uses set operations or grouping sets, as these
5684 : * will mash underlying columns' stats beyond recognition. (Set ops
5685 : * are particularly nasty; if we forged ahead, we would return stats
5686 : * relevant to only the leftmost subselect...) DISTINCT is also
5687 : * problematic, but we check that later because there is a possibility
5688 : * of learning something even with it.
5689 : */
5690 12504 : if (subquery->setOperations ||
5691 11220 : subquery->groupingSets)
5692 1308 : return;
5693 :
5694 : /* Get the subquery output expression referenced by the upper Var */
5695 11196 : if (subquery->returningList)
5696 206 : subtlist = subquery->returningList;
5697 : else
5698 10990 : subtlist = subquery->targetList;
5699 11196 : ste = get_tle_by_resno(subtlist, var->varattno);
5700 11196 : if (ste == NULL || ste->resjunk)
5701 0 : elog(ERROR, "subquery %s does not have attribute %d",
5702 : rte->eref->aliasname, var->varattno);
5703 11196 : var = (Var *) ste->expr;
5704 :
5705 : /*
5706 : * If subquery uses DISTINCT, we can't make use of any stats for the
5707 : * variable ... but, if it's the only DISTINCT column, we are entitled
5708 : * to consider it unique. We do the test this way so that it works
5709 : * for cases involving DISTINCT ON.
5710 : */
5711 11196 : if (subquery->distinctClause)
5712 : {
5713 1766 : if (list_length(subquery->distinctClause) == 1 &&
5714 580 : targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5715 272 : vardata->isunique = true;
5716 : /* cannot go further */
5717 1186 : return;
5718 : }
5719 :
5720 : /* The same idea as with DISTINCT clause works for a GROUP-BY too */
5721 10010 : if (subquery->groupClause)
5722 : {
5723 1024 : if (list_length(subquery->groupClause) == 1 &&
5724 422 : targetIsInSortList(ste, InvalidOid, subquery->groupClause))
5725 334 : vardata->isunique = true;
5726 : /* cannot go further */
5727 602 : return;
5728 : }
5729 :
5730 : /*
5731 : * If the sub-query originated from a view with the security_barrier
5732 : * attribute, we must not look at the variable's statistics, though it
5733 : * seems all right to notice the existence of a DISTINCT clause. So
5734 : * stop here.
5735 : *
5736 : * This is probably a harsher restriction than necessary; it's
5737 : * certainly OK for the selectivity estimator (which is a C function,
5738 : * and therefore omnipotent anyway) to look at the statistics. But
5739 : * many selectivity estimators will happily *invoke the operator
5740 : * function* to try to work out a good estimate - and that's not OK.
5741 : * So for now, don't dig down for stats.
5742 : */
5743 9408 : if (rte->security_barrier)
5744 228 : return;
5745 :
5746 : /* Can only handle a simple Var of subquery's query level */
5747 9180 : if (var && IsA(var, Var) &&
5748 4318 : var->varlevelsup == 0)
5749 : {
5750 : /*
5751 : * OK, recurse into the subquery. Note that the original setting
5752 : * of vardata->isunique (which will surely be false) is left
5753 : * unchanged in this situation. That's what we want, since even
5754 : * if the underlying column is unique, the subquery may have
5755 : * joined to other tables in a way that creates duplicates.
5756 : */
5757 4318 : examine_simple_variable(subroot, var, vardata);
5758 : }
5759 : }
5760 : else
5761 : {
5762 : /*
5763 : * Otherwise, the Var comes from a FUNCTION or VALUES RTE. (We won't
5764 : * see RTE_JOIN here because join alias Vars have already been
5765 : * flattened.) There's not much we can do with function outputs, but
5766 : * maybe someday try to be smarter about VALUES.
5767 : */
5768 : }
5769 : }
5770 :
5771 : /*
5772 : * Check whether it is permitted to call func_oid passing some of the
5773 : * pg_statistic data in vardata. We allow this either if the user has SELECT
5774 : * privileges on the table or column underlying the pg_statistic data or if
5775 : * the function is marked leakproof.
5776 : */
5777 : bool
5778 1398248 : statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
5779 : {
5780 1398248 : if (vardata->acl_ok)
5781 1397502 : return true;
5782 :
5783 746 : if (!OidIsValid(func_oid))
5784 0 : return false;
5785 :
5786 746 : if (get_func_leakproof(func_oid))
5787 322 : return true;
5788 :
5789 424 : ereport(DEBUG2,
5790 : (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
5791 : get_func_name(func_oid))));
5792 424 : return false;
5793 : }
5794 :
5795 : /*
5796 : * get_variable_numdistinct
5797 : * Estimate the number of distinct values of a variable.
5798 : *
5799 : * vardata: results of examine_variable
5800 : * *isdefault: set to true if the result is a default rather than based on
5801 : * anything meaningful.
5802 : *
5803 : * NB: be careful to produce a positive integral result, since callers may
5804 : * compare the result to exact integer counts, or might divide by it.
5805 : */
5806 : double
5807 2278368 : get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
5808 : {
5809 : double stadistinct;
5810 2278368 : double stanullfrac = 0.0;
5811 : double ntuples;
5812 :
5813 2278368 : *isdefault = false;
5814 :
5815 : /*
5816 : * Determine the stadistinct value to use. There are cases where we can
5817 : * get an estimate even without a pg_statistic entry, or can get a better
5818 : * value than is in pg_statistic. Grab stanullfrac too if we can find it
5819 : * (otherwise, assume no nulls, for lack of any better idea).
5820 : */
5821 2278368 : if (HeapTupleIsValid(vardata->statsTuple))
5822 : {
5823 : /* Use the pg_statistic entry */
5824 : Form_pg_statistic stats;
5825 :
5826 1630390 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
5827 1630390 : stadistinct = stats->stadistinct;
5828 1630390 : stanullfrac = stats->stanullfrac;
5829 : }
5830 647978 : else if (vardata->vartype == BOOLOID)
5831 : {
5832 : /*
5833 : * Special-case boolean columns: presumably, two distinct values.
5834 : *
5835 : * Are there any other datatypes we should wire in special estimates
5836 : * for?
5837 : */
5838 468 : stadistinct = 2.0;
5839 : }
5840 647510 : else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5841 : {
5842 : /*
5843 : * If the Var represents a column of a VALUES RTE, assume it's unique.
5844 : * This could of course be very wrong, but it should tend to be true
5845 : * in well-written queries. We could consider examining the VALUES'
5846 : * contents to get some real statistics; but that only works if the
5847 : * entries are all constants, and it would be pretty expensive anyway.
5848 : */
5849 3284 : stadistinct = -1.0; /* unique (and all non null) */
5850 : }
5851 : else
5852 : {
5853 : /*
5854 : * We don't keep statistics for system columns, but in some cases we
5855 : * can infer distinctness anyway.
5856 : */
5857 644226 : if (vardata->var && IsA(vardata->var, Var))
5858 : {
5859 621490 : switch (((Var *) vardata->var)->varattno)
5860 : {
5861 1146 : case SelfItemPointerAttributeNumber:
5862 1146 : stadistinct = -1.0; /* unique (and all non null) */
5863 1146 : break;
5864 2518 : case TableOidAttributeNumber:
5865 2518 : stadistinct = 1.0; /* only 1 value */
5866 2518 : break;
5867 617826 : default:
5868 617826 : stadistinct = 0.0; /* means "unknown" */
5869 617826 : break;
5870 : }
5871 : }
5872 : else
5873 22736 : stadistinct = 0.0; /* means "unknown" */
5874 :
5875 : /*
5876 : * XXX consider using estimate_num_groups on expressions?
5877 : */
5878 : }
5879 :
5880 : /*
5881 : * If there is a unique index, DISTINCT or GROUP-BY clause for the
5882 : * variable, assume it is unique no matter what pg_statistic says; the
5883 : * statistics could be out of date, or we might have found a partial
5884 : * unique index that proves the var is unique for this query. However,
5885 : * we'd better still believe the null-fraction statistic.
5886 : */
5887 2278368 : if (vardata->isunique)
5888 528712 : stadistinct = -1.0 * (1.0 - stanullfrac);
5889 :
5890 : /*
5891 : * If we had an absolute estimate, use that.
5892 : */
5893 2278368 : if (stadistinct > 0.0)
5894 603726 : return clamp_row_est(stadistinct);
5895 :
5896 : /*
5897 : * Otherwise we need to get the relation size; punt if not available.
5898 : */
5899 1674642 : if (vardata->rel == NULL)
5900 : {
5901 298 : *isdefault = true;
5902 298 : return DEFAULT_NUM_DISTINCT;
5903 : }
5904 1674344 : ntuples = vardata->rel->tuples;
5905 1674344 : if (ntuples <= 0.0)
5906 : {
5907 45774 : *isdefault = true;
5908 45774 : return DEFAULT_NUM_DISTINCT;
5909 : }
5910 :
5911 : /*
5912 : * If we had a relative estimate, use that.
5913 : */
5914 1628570 : if (stadistinct < 0.0)
5915 1071462 : return clamp_row_est(-stadistinct * ntuples);
5916 :
5917 : /*
5918 : * With no data, estimate ndistinct = ntuples if the table is small, else
5919 : * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
5920 : * that the behavior isn't discontinuous.
5921 : */
5922 557108 : if (ntuples < DEFAULT_NUM_DISTINCT)
5923 136408 : return clamp_row_est(ntuples);
5924 :
5925 420700 : *isdefault = true;
5926 420700 : return DEFAULT_NUM_DISTINCT;
5927 : }
5928 :
5929 : /*
5930 : * get_variable_range
5931 : * Estimate the minimum and maximum value of the specified variable.
5932 : * If successful, store values in *min and *max, and return true.
5933 : * If no data available, return false.
5934 : *
5935 : * sortop is the "<" comparison operator to use. This should generally
5936 : * be "<" not ">", as only the former is likely to be found in pg_statistic.
5937 : * The collation must be specified too.
5938 : */
5939 : static bool
5940 313886 : get_variable_range(PlannerInfo *root, VariableStatData *vardata,
5941 : Oid sortop, Oid collation,
5942 : Datum *min, Datum *max)
5943 : {
5944 313886 : Datum tmin = 0;
5945 313886 : Datum tmax = 0;
5946 313886 : bool have_data = false;
5947 : int16 typLen;
5948 : bool typByVal;
5949 : Oid opfuncoid;
5950 : FmgrInfo opproc;
5951 : AttStatsSlot sslot;
5952 :
5953 : /*
5954 : * XXX It's very tempting to try to use the actual column min and max, if
5955 : * we can get them relatively-cheaply with an index probe. However, since
5956 : * this function is called many times during join planning, that could
5957 : * have unpleasant effects on planning speed. Need more investigation
5958 : * before enabling this.
5959 : */
5960 : #ifdef NOT_USED
5961 : if (get_actual_variable_range(root, vardata, sortop, collation, min, max))
5962 : return true;
5963 : #endif
5964 :
5965 313886 : if (!HeapTupleIsValid(vardata->statsTuple))
5966 : {
5967 : /* no stats available, so default result */
5968 76204 : return false;
5969 : }
5970 :
5971 : /*
5972 : * If we can't apply the sortop to the stats data, just fail. In
5973 : * principle, if there's a histogram and no MCVs, we could return the
5974 : * histogram endpoints without ever applying the sortop ... but it's
5975 : * probably not worth trying, because whatever the caller wants to do with
5976 : * the endpoints would likely fail the security check too.
5977 : */
5978 237682 : if (!statistic_proc_security_check(vardata,
5979 237682 : (opfuncoid = get_opcode(sortop))))
5980 0 : return false;
5981 :
5982 237682 : opproc.fn_oid = InvalidOid; /* mark this as not looked up yet */
5983 :
5984 237682 : get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5985 :
5986 : /*
5987 : * If there is a histogram with the ordering we want, grab the first and
5988 : * last values.
5989 : */
5990 237682 : if (get_attstatsslot(&sslot, vardata->statsTuple,
5991 : STATISTIC_KIND_HISTOGRAM, sortop,
5992 : ATTSTATSSLOT_VALUES))
5993 : {
5994 164916 : if (sslot.stacoll == collation && sslot.nvalues > 0)
5995 : {
5996 164916 : tmin = datumCopy(sslot.values[0], typByVal, typLen);
5997 164916 : tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
5998 164916 : have_data = true;
5999 : }
6000 164916 : free_attstatsslot(&sslot);
6001 : }
6002 :
6003 : /*
6004 : * Otherwise, if there is a histogram with some other ordering, scan it
6005 : * and get the min and max values according to the ordering we want. This
6006 : * of course may not find values that are really extremal according to our
6007 : * ordering, but it beats ignoring available data.
6008 : */
6009 310448 : if (!have_data &&
6010 72766 : get_attstatsslot(&sslot, vardata->statsTuple,
6011 : STATISTIC_KIND_HISTOGRAM, InvalidOid,
6012 : ATTSTATSSLOT_VALUES))
6013 : {
6014 0 : get_stats_slot_range(&sslot, opfuncoid, &opproc,
6015 : collation, typLen, typByVal,
6016 : &tmin, &tmax, &have_data);
6017 0 : free_attstatsslot(&sslot);
6018 : }
6019 :
6020 : /*
6021 : * If we have most-common-values info, look for extreme MCVs. This is
6022 : * needed even if we also have a histogram, since the histogram excludes
6023 : * the MCVs. However, if we *only* have MCVs and no histogram, we should
6024 : * be pretty wary of deciding that that is a full representation of the
6025 : * data. Proceed only if the MCVs represent the whole table (to within
6026 : * roundoff error).
6027 : */
6028 237682 : if (get_attstatsslot(&sslot, vardata->statsTuple,
6029 : STATISTIC_KIND_MCV, InvalidOid,
6030 237682 : have_data ? ATTSTATSSLOT_VALUES :
6031 : (ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)))
6032 : {
6033 114254 : bool use_mcvs = have_data;
6034 :
6035 114254 : if (!have_data)
6036 : {
6037 71530 : double sumcommon = 0.0;
6038 : double nullfrac;
6039 : int i;
6040 :
6041 414548 : for (i = 0; i < sslot.nnumbers; i++)
6042 343018 : sumcommon += sslot.numbers[i];
6043 71530 : nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata->statsTuple))->stanullfrac;
6044 71530 : if (sumcommon + nullfrac > 0.99999)
6045 71192 : use_mcvs = true;
6046 : }
6047 :
6048 114254 : if (use_mcvs)
6049 113916 : get_stats_slot_range(&sslot, opfuncoid, &opproc,
6050 : collation, typLen, typByVal,
6051 : &tmin, &tmax, &have_data);
6052 114254 : free_attstatsslot(&sslot);
6053 : }
6054 :
6055 237682 : *min = tmin;
6056 237682 : *max = tmax;
6057 237682 : return have_data;
6058 : }
6059 :
6060 : /*
6061 : * get_stats_slot_range: scan sslot for min/max values
6062 : *
6063 : * Subroutine for get_variable_range: update min/max/have_data according
6064 : * to what we find in the statistics array.
6065 : */
6066 : static void
6067 113916 : get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
6068 : Oid collation, int16 typLen, bool typByVal,
6069 : Datum *min, Datum *max, bool *p_have_data)
6070 : {
6071 113916 : Datum tmin = *min;
6072 113916 : Datum tmax = *max;
6073 113916 : bool have_data = *p_have_data;
6074 113916 : bool found_tmin = false;
6075 113916 : bool found_tmax = false;
6076 :
6077 : /* Look up the comparison function, if we didn't already do so */
6078 113916 : if (opproc->fn_oid != opfuncoid)
6079 113916 : fmgr_info(opfuncoid, opproc);
6080 :
6081 : /* Scan all the slot's values */
6082 3339098 : for (int i = 0; i < sslot->nvalues; i++)
6083 : {
6084 3225182 : if (!have_data)
6085 : {
6086 71192 : tmin = tmax = sslot->values[i];
6087 71192 : found_tmin = found_tmax = true;
6088 71192 : *p_have_data = have_data = true;
6089 71192 : continue;
6090 : }
6091 3153990 : if (DatumGetBool(FunctionCall2Coll(opproc,
6092 : collation,
6093 3153990 : sslot->values[i], tmin)))
6094 : {
6095 43338 : tmin = sslot->values[i];
6096 43338 : found_tmin = true;
6097 : }
6098 3153990 : if (DatumGetBool(FunctionCall2Coll(opproc,
6099 : collation,
6100 3153990 : tmax, sslot->values[i])))
6101 : {
6102 168940 : tmax = sslot->values[i];
6103 168940 : found_tmax = true;
6104 : }
6105 : }
6106 :
6107 : /*
6108 : * Copy the slot's values, if we found new extreme values.
6109 : */
6110 113916 : if (found_tmin)
6111 88972 : *min = datumCopy(tmin, typByVal, typLen);
6112 113916 : if (found_tmax)
6113 72470 : *max = datumCopy(tmax, typByVal, typLen);
6114 113916 : }
6115 :
6116 :
6117 : /*
6118 : * get_actual_variable_range
6119 : * Attempt to identify the current *actual* minimum and/or maximum
6120 : * of the specified variable, by looking for a suitable btree index
6121 : * and fetching its low and/or high values.
6122 : * If successful, store values in *min and *max, and return true.
6123 : * (Either pointer can be NULL if that endpoint isn't needed.)
6124 : * If unsuccessful, return false.
6125 : *
6126 : * sortop is the "<" comparison operator to use.
6127 : * collation is the required collation.
6128 : */
6129 : static bool
6130 281054 : get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
6131 : Oid sortop, Oid collation,
6132 : Datum *min, Datum *max)
6133 : {
6134 281054 : bool have_data = false;
6135 281054 : RelOptInfo *rel = vardata->rel;
6136 : RangeTblEntry *rte;
6137 : ListCell *lc;
6138 :
6139 : /* No hope if no relation or it doesn't have indexes */
6140 281054 : if (rel == NULL || rel->indexlist == NIL)
6141 13030 : return false;
6142 : /* If it has indexes it must be a plain relation */
6143 268024 : rte = root->simple_rte_array[rel->relid];
6144 : Assert(rte->rtekind == RTE_RELATION);
6145 :
6146 : /* ignore partitioned tables. Any indexes here are not real indexes */
6147 268024 : if (rte->relkind == RELKIND_PARTITIONED_TABLE)
6148 828 : return false;
6149 :
6150 : /* Search through the indexes to see if any match our problem */
6151 449530 : foreach(lc, rel->indexlist)
6152 : {
6153 406732 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
6154 : ScanDirection indexscandir;
6155 :
6156 : /* Ignore non-btree indexes */
6157 406732 : if (index->relam != BTREE_AM_OID)
6158 0 : continue;
6159 :
6160 : /*
6161 : * Ignore partial indexes --- we only want stats that cover the entire
6162 : * relation.
6163 : */
6164 406732 : if (index->indpred != NIL)
6165 288 : continue;
6166 :
6167 : /*
6168 : * The index list might include hypothetical indexes inserted by a
6169 : * get_relation_info hook --- don't try to access them.
6170 : */
6171 406444 : if (index->hypothetical)
6172 0 : continue;
6173 :
6174 : /*
6175 : * The first index column must match the desired variable, sortop, and
6176 : * collation --- but we can use a descending-order index.
6177 : */
6178 406444 : if (collation != index->indexcollations[0])
6179 51750 : continue; /* test first 'cause it's cheapest */
6180 354694 : if (!match_index_to_operand(vardata->var, 0, index))
6181 130296 : continue;
6182 224398 : switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
6183 : {
6184 224398 : case BTLessStrategyNumber:
6185 224398 : if (index->reverse_sort[0])
6186 0 : indexscandir = BackwardScanDirection;
6187 : else
6188 224398 : indexscandir = ForwardScanDirection;
6189 224398 : break;
6190 0 : case BTGreaterStrategyNumber:
6191 0 : if (index->reverse_sort[0])
6192 0 : indexscandir = ForwardScanDirection;
6193 : else
6194 0 : indexscandir = BackwardScanDirection;
6195 0 : break;
6196 0 : default:
6197 : /* index doesn't match the sortop */
6198 0 : continue;
6199 : }
6200 :
6201 : /*
6202 : * Found a suitable index to extract data from. Set up some data that
6203 : * can be used by both invocations of get_actual_variable_endpoint.
6204 : */
6205 : {
6206 : MemoryContext tmpcontext;
6207 : MemoryContext oldcontext;
6208 : Relation heapRel;
6209 : Relation indexRel;
6210 : TupleTableSlot *slot;
6211 : int16 typLen;
6212 : bool typByVal;
6213 : ScanKeyData scankeys[1];
6214 :
6215 : /* Make sure any cruft gets recycled when we're done */
6216 224398 : tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
6217 : "get_actual_variable_range workspace",
6218 : ALLOCSET_DEFAULT_SIZES);
6219 224398 : oldcontext = MemoryContextSwitchTo(tmpcontext);
6220 :
6221 : /*
6222 : * Open the table and index so we can read from them. We should
6223 : * already have some type of lock on each.
6224 : */
6225 224398 : heapRel = table_open(rte->relid, NoLock);
6226 224398 : indexRel = index_open(index->indexoid, NoLock);
6227 :
6228 : /* build some stuff needed for indexscan execution */
6229 224398 : slot = table_slot_create(heapRel, NULL);
6230 224398 : get_typlenbyval(vardata->atttype, &typLen, &typByVal);
6231 :
6232 : /* set up an IS NOT NULL scan key so that we ignore nulls */
6233 224398 : ScanKeyEntryInitialize(&scankeys[0],
6234 : SK_ISNULL | SK_SEARCHNOTNULL,
6235 : 1, /* index col to scan */
6236 : InvalidStrategy, /* no strategy */
6237 : InvalidOid, /* no strategy subtype */
6238 : InvalidOid, /* no collation */
6239 : InvalidOid, /* no reg proc for this */
6240 : (Datum) 0); /* constant */
6241 :
6242 : /* If min is requested ... */
6243 224398 : if (min)
6244 : {
6245 121936 : have_data = get_actual_variable_endpoint(heapRel,
6246 : indexRel,
6247 : indexscandir,
6248 : scankeys,
6249 : typLen,
6250 : typByVal,
6251 : slot,
6252 : oldcontext,
6253 : min);
6254 : }
6255 : else
6256 : {
6257 : /* If min not requested, still want to fetch max */
6258 102462 : have_data = true;
6259 : }
6260 :
6261 : /* If max is requested, and we didn't already fail ... */
6262 224398 : if (max && have_data)
6263 : {
6264 : /* scan in the opposite direction; all else is the same */
6265 103638 : have_data = get_actual_variable_endpoint(heapRel,
6266 : indexRel,
6267 103638 : -indexscandir,
6268 : scankeys,
6269 : typLen,
6270 : typByVal,
6271 : slot,
6272 : oldcontext,
6273 : max);
6274 : }
6275 :
6276 : /* Clean everything up */
6277 224398 : ExecDropSingleTupleTableSlot(slot);
6278 :
6279 224398 : index_close(indexRel, NoLock);
6280 224398 : table_close(heapRel, NoLock);
6281 :
6282 224398 : MemoryContextSwitchTo(oldcontext);
6283 224398 : MemoryContextDelete(tmpcontext);
6284 :
6285 : /* And we're done */
6286 224398 : break;
6287 : }
6288 : }
6289 :
6290 267196 : return have_data;
6291 : }
6292 :
6293 : /*
6294 : * Get one endpoint datum (min or max depending on indexscandir) from the
6295 : * specified index. Return true if successful, false if not.
6296 : * On success, endpoint value is stored to *endpointDatum (and copied into
6297 : * outercontext).
6298 : *
6299 : * scankeys is a 1-element scankey array set up to reject nulls.
6300 : * typLen/typByVal describe the datatype of the index's first column.
6301 : * tableslot is a slot suitable to hold table tuples, in case we need
6302 : * to probe the heap.
6303 : * (We could compute these values locally, but that would mean computing them
6304 : * twice when get_actual_variable_range needs both the min and the max.)
6305 : *
6306 : * Failure occurs either when the index is empty, or we decide that it's
6307 : * taking too long to find a suitable tuple.
6308 : */
6309 : static bool
6310 225574 : get_actual_variable_endpoint(Relation heapRel,
6311 : Relation indexRel,
6312 : ScanDirection indexscandir,
6313 : ScanKey scankeys,
6314 : int16 typLen,
6315 : bool typByVal,
6316 : TupleTableSlot *tableslot,
6317 : MemoryContext outercontext,
6318 : Datum *endpointDatum)
6319 : {
6320 225574 : bool have_data = false;
6321 : SnapshotData SnapshotNonVacuumable;
6322 : IndexScanDesc index_scan;
6323 225574 : Buffer vmbuffer = InvalidBuffer;
6324 225574 : BlockNumber last_heap_block = InvalidBlockNumber;
6325 225574 : int n_visited_heap_pages = 0;
6326 : ItemPointer tid;
6327 : Datum values[INDEX_MAX_KEYS];
6328 : bool isnull[INDEX_MAX_KEYS];
6329 : MemoryContext oldcontext;
6330 :
6331 : /*
6332 : * We use the index-only-scan machinery for this. With mostly-static
6333 : * tables that's a win because it avoids a heap visit. It's also a win
6334 : * for dynamic data, but the reason is less obvious; read on for details.
6335 : *
6336 : * In principle, we should scan the index with our current active
6337 : * snapshot, which is the best approximation we've got to what the query
6338 : * will see when executed. But that won't be exact if a new snap is taken
6339 : * before running the query, and it can be very expensive if a lot of
6340 : * recently-dead or uncommitted rows exist at the beginning or end of the
6341 : * index (because we'll laboriously fetch each one and reject it).
6342 : * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
6343 : * and uncommitted rows as well as normal visible rows. On the other
6344 : * hand, it will reject known-dead rows, and thus not give a bogus answer
6345 : * when the extreme value has been deleted (unless the deletion was quite
6346 : * recent); that case motivates not using SnapshotAny here.
6347 : *
6348 : * A crucial point here is that SnapshotNonVacuumable, with
6349 : * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
6350 : * condition that the indexscan will use to decide that index entries are
6351 : * killable (see heap_hot_search_buffer()). Therefore, if the snapshot
6352 : * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
6353 : * have to continue scanning past it, we know that the indexscan will mark
6354 : * that index entry killed. That means that the next
6355 : * get_actual_variable_endpoint() call will not have to re-consider that
6356 : * index entry. In this way we avoid repetitive work when this function
6357 : * is used a lot during planning.
6358 : *
6359 : * But using SnapshotNonVacuumable creates a hazard of its own. In a
6360 : * recently-created index, some index entries may point at "broken" HOT
6361 : * chains in which not all the tuple versions contain data matching the
6362 : * index entry. The live tuple version(s) certainly do match the index,
6363 : * but SnapshotNonVacuumable can accept recently-dead tuple versions that
6364 : * don't match. Hence, if we took data from the selected heap tuple, we
6365 : * might get a bogus answer that's not close to the index extremal value,
6366 : * or could even be NULL. We avoid this hazard because we take the data
6367 : * from the index entry not the heap.
6368 : *
6369 : * Despite all this care, there are situations where we might find many
6370 : * non-visible tuples near the end of the index. We don't want to expend
6371 : * a huge amount of time here, so we give up once we've read too many heap
6372 : * pages. When we fail for that reason, the caller will end up using
6373 : * whatever extremal value is recorded in pg_statistic.
6374 : */
6375 225574 : InitNonVacuumableSnapshot(SnapshotNonVacuumable,
6376 : GlobalVisTestFor(heapRel));
6377 :
6378 225574 : index_scan = index_beginscan(heapRel, indexRel,
6379 : &SnapshotNonVacuumable,
6380 : 1, 0);
6381 : /* Set it up for index-only scan */
6382 225574 : index_scan->xs_want_itup = true;
6383 225574 : index_rescan(index_scan, scankeys, 1, NULL, 0);
6384 :
6385 : /* Fetch first/next tuple in specified direction */
6386 417022 : while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
6387 : {
6388 417022 : BlockNumber block = ItemPointerGetBlockNumber(tid);
6389 :
6390 417022 : if (!VM_ALL_VISIBLE(heapRel,
6391 : block,
6392 : &vmbuffer))
6393 : {
6394 : /* Rats, we have to visit the heap to check visibility */
6395 358048 : if (!index_fetch_heap(index_scan, tableslot))
6396 : {
6397 : /*
6398 : * No visible tuple for this index entry, so we need to
6399 : * advance to the next entry. Before doing so, count heap
6400 : * page fetches and give up if we've done too many.
6401 : *
6402 : * We don't charge a page fetch if this is the same heap page
6403 : * as the previous tuple. This is on the conservative side,
6404 : * since other recently-accessed pages are probably still in
6405 : * buffers too; but it's good enough for this heuristic.
6406 : */
6407 : #define VISITED_PAGES_LIMIT 100
6408 :
6409 191448 : if (block != last_heap_block)
6410 : {
6411 9466 : last_heap_block = block;
6412 9466 : n_visited_heap_pages++;
6413 9466 : if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
6414 0 : break;
6415 : }
6416 :
6417 191448 : continue; /* no visible tuple, try next index entry */
6418 : }
6419 :
6420 : /* We don't actually need the heap tuple for anything */
6421 166600 : ExecClearTuple(tableslot);
6422 :
6423 : /*
6424 : * We don't care whether there's more than one visible tuple in
6425 : * the HOT chain; if any are visible, that's good enough.
6426 : */
6427 : }
6428 :
6429 : /*
6430 : * We expect that btree will return data in IndexTuple not HeapTuple
6431 : * format. It's not lossy either.
6432 : */
6433 225574 : if (!index_scan->xs_itup)
6434 0 : elog(ERROR, "no data returned for index-only scan");
6435 225574 : if (index_scan->xs_recheck)
6436 0 : elog(ERROR, "unexpected recheck indication from btree");
6437 :
6438 : /* OK to deconstruct the index tuple */
6439 225574 : index_deform_tuple(index_scan->xs_itup,
6440 : index_scan->xs_itupdesc,
6441 : values, isnull);
6442 :
6443 : /* Shouldn't have got a null, but be careful */
6444 225574 : if (isnull[0])
6445 0 : elog(ERROR, "found unexpected null value in index \"%s\"",
6446 : RelationGetRelationName(indexRel));
6447 :
6448 : /* Copy the index column value out to caller's context */
6449 225574 : oldcontext = MemoryContextSwitchTo(outercontext);
6450 225574 : *endpointDatum = datumCopy(values[0], typByVal, typLen);
6451 225574 : MemoryContextSwitchTo(oldcontext);
6452 225574 : have_data = true;
6453 225574 : break;
6454 : }
6455 :
6456 225574 : if (vmbuffer != InvalidBuffer)
6457 213348 : ReleaseBuffer(vmbuffer);
6458 225574 : index_endscan(index_scan);
6459 :
6460 225574 : return have_data;
6461 : }
6462 :
6463 : /*
6464 : * find_join_input_rel
6465 : * Look up the input relation for a join.
6466 : *
6467 : * We assume that the input relation's RelOptInfo must have been constructed
6468 : * already.
6469 : */
6470 : static RelOptInfo *
6471 7326 : find_join_input_rel(PlannerInfo *root, Relids relids)
6472 : {
6473 7326 : RelOptInfo *rel = NULL;
6474 :
6475 7326 : if (!bms_is_empty(relids))
6476 : {
6477 : int relid;
6478 :
6479 7326 : if (bms_get_singleton_member(relids, &relid))
6480 7022 : rel = find_base_rel(root, relid);
6481 : else
6482 304 : rel = find_join_rel(root, relids);
6483 : }
6484 :
6485 7326 : if (rel == NULL)
6486 0 : elog(ERROR, "could not find RelOptInfo for given relids");
6487 :
6488 7326 : return rel;
6489 : }
6490 :
6491 :
6492 : /*-------------------------------------------------------------------------
6493 : *
6494 : * Index cost estimation functions
6495 : *
6496 : *-------------------------------------------------------------------------
6497 : */
6498 :
6499 : /*
6500 : * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
6501 : */
6502 : List *
6503 1175090 : get_quals_from_indexclauses(List *indexclauses)
6504 : {
6505 1175090 : List *result = NIL;
6506 : ListCell *lc;
6507 :
6508 2086200 : foreach(lc, indexclauses)
6509 : {
6510 911110 : IndexClause *iclause = lfirst_node(IndexClause, lc);
6511 : ListCell *lc2;
6512 :
6513 1825082 : foreach(lc2, iclause->indexquals)
6514 : {
6515 913972 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6516 :
6517 913972 : result = lappend(result, rinfo);
6518 : }
6519 : }
6520 1175090 : return result;
6521 : }
6522 :
6523 : /*
6524 : * Compute the total evaluation cost of the comparison operands in a list
6525 : * of index qual expressions. Since we know these will be evaluated just
6526 : * once per scan, there's no need to distinguish startup from per-row cost.
6527 : *
6528 : * This can be used either on the result of get_quals_from_indexclauses(),
6529 : * or directly on an indexorderbys list. In both cases, we expect that the
6530 : * index key expression is on the left side of binary clauses.
6531 : */
6532 : Cost
6533 2337570 : index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
6534 : {
6535 2337570 : Cost qual_arg_cost = 0;
6536 : ListCell *lc;
6537 :
6538 3252004 : foreach(lc, indexquals)
6539 : {
6540 914434 : Expr *clause = (Expr *) lfirst(lc);
6541 : Node *other_operand;
6542 : QualCost index_qual_cost;
6543 :
6544 : /*
6545 : * Index quals will have RestrictInfos, indexorderbys won't. Look
6546 : * through RestrictInfo if present.
6547 : */
6548 914434 : if (IsA(clause, RestrictInfo))
6549 913960 : clause = ((RestrictInfo *) clause)->clause;
6550 :
6551 914434 : if (IsA(clause, OpExpr))
6552 : {
6553 901454 : OpExpr *op = (OpExpr *) clause;
6554 :
6555 901454 : other_operand = (Node *) lsecond(op->args);
6556 : }
6557 12980 : else if (IsA(clause, RowCompareExpr))
6558 : {
6559 300 : RowCompareExpr *rc = (RowCompareExpr *) clause;
6560 :
6561 300 : other_operand = (Node *) rc->rargs;
6562 : }
6563 12680 : else if (IsA(clause, ScalarArrayOpExpr))
6564 : {
6565 9784 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6566 :
6567 9784 : other_operand = (Node *) lsecond(saop->args);
6568 : }
6569 2896 : else if (IsA(clause, NullTest))
6570 : {
6571 2896 : other_operand = NULL;
6572 : }
6573 : else
6574 : {
6575 0 : elog(ERROR, "unsupported indexqual type: %d",
6576 : (int) nodeTag(clause));
6577 : other_operand = NULL; /* keep compiler quiet */
6578 : }
6579 :
6580 914434 : cost_qual_eval_node(&index_qual_cost, other_operand, root);
6581 914434 : qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6582 : }
6583 2337570 : return qual_arg_cost;
6584 : }
6585 :
6586 : void
6587 1162492 : genericcostestimate(PlannerInfo *root,
6588 : IndexPath *path,
6589 : double loop_count,
6590 : GenericCosts *costs)
6591 : {
6592 1162492 : IndexOptInfo *index = path->indexinfo;
6593 1162492 : List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6594 1162492 : List *indexOrderBys = path->indexorderbys;
6595 : Cost indexStartupCost;
6596 : Cost indexTotalCost;
6597 : Selectivity indexSelectivity;
6598 : double indexCorrelation;
6599 : double numIndexPages;
6600 : double numIndexTuples;
6601 : double spc_random_page_cost;
6602 : double num_sa_scans;
6603 : double num_outer_scans;
6604 : double num_scans;
6605 : double qual_op_cost;
6606 : double qual_arg_cost;
6607 : List *selectivityQuals;
6608 : ListCell *l;
6609 :
6610 : /*
6611 : * If the index is partial, AND the index predicate with the explicitly
6612 : * given indexquals to produce a more accurate idea of the index
6613 : * selectivity.
6614 : */
6615 1162492 : selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6616 :
6617 : /*
6618 : * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
6619 : * just assume that the number of index descents is the number of distinct
6620 : * combinations of array elements from all of the scan's SAOP clauses.
6621 : */
6622 1162492 : num_sa_scans = costs->num_sa_scans;
6623 1162492 : if (num_sa_scans < 1)
6624 : {
6625 8318 : num_sa_scans = 1;
6626 17594 : foreach(l, indexQuals)
6627 : {
6628 9276 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6629 :
6630 9276 : if (IsA(rinfo->clause, ScalarArrayOpExpr))
6631 : {
6632 26 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6633 26 : double alength = estimate_array_length(root, lsecond(saop->args));
6634 :
6635 26 : if (alength > 1)
6636 26 : num_sa_scans *= alength;
6637 : }
6638 : }
6639 : }
6640 :
6641 : /* Estimate the fraction of main-table tuples that will be visited */
6642 1162492 : indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6643 1162492 : index->rel->relid,
6644 : JOIN_INNER,
6645 : NULL);
6646 :
6647 : /*
6648 : * If caller didn't give us an estimate, estimate the number of index
6649 : * tuples that will be visited. We do it in this rather peculiar-looking
6650 : * way in order to get the right answer for partial indexes.
6651 : */
6652 1162492 : numIndexTuples = costs->numIndexTuples;
6653 1162492 : if (numIndexTuples <= 0.0)
6654 : {
6655 85460 : numIndexTuples = indexSelectivity * index->rel->tuples;
6656 :
6657 : /*
6658 : * The above calculation counts all the tuples visited across all
6659 : * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6660 : * average per-indexscan number, so adjust. This is a handy place to
6661 : * round to integer, too. (If caller supplied tuple estimate, it's
6662 : * responsible for handling these considerations.)
6663 : */
6664 85460 : numIndexTuples = rint(numIndexTuples / num_sa_scans);
6665 : }
6666 :
6667 : /*
6668 : * We can bound the number of tuples by the index size in any case. Also,
6669 : * always estimate at least one tuple is touched, even when
6670 : * indexSelectivity estimate is tiny.
6671 : */
6672 1162492 : if (numIndexTuples > index->tuples)
6673 5250 : numIndexTuples = index->tuples;
6674 1162492 : if (numIndexTuples < 1.0)
6675 84624 : numIndexTuples = 1.0;
6676 :
6677 : /*
6678 : * Estimate the number of index pages that will be retrieved.
6679 : *
6680 : * We use the simplistic method of taking a pro-rata fraction of the total
6681 : * number of index pages. In effect, this counts only leaf pages and not
6682 : * any overhead such as index metapage or upper tree levels.
6683 : *
6684 : * In practice access to upper index levels is often nearly free because
6685 : * those tend to stay in cache under load; moreover, the cost involved is
6686 : * highly dependent on index type. We therefore ignore such costs here
6687 : * and leave it to the caller to add a suitable charge if needed.
6688 : */
6689 1162492 : if (index->pages > 1 && index->tuples > 1)
6690 1118466 : numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6691 : else
6692 44026 : numIndexPages = 1.0;
6693 :
6694 : /* fetch estimated page cost for tablespace containing index */
6695 1162492 : get_tablespace_page_costs(index->reltablespace,
6696 : &spc_random_page_cost,
6697 : NULL);
6698 :
6699 : /*
6700 : * Now compute the disk access costs.
6701 : *
6702 : * The above calculations are all per-index-scan. However, if we are in a
6703 : * nestloop inner scan, we can expect the scan to be repeated (with
6704 : * different search keys) for each row of the outer relation. Likewise,
6705 : * ScalarArrayOpExpr quals result in multiple index scans. This creates
6706 : * the potential for cache effects to reduce the number of disk page
6707 : * fetches needed. We want to estimate the average per-scan I/O cost in
6708 : * the presence of caching.
6709 : *
6710 : * We use the Mackert-Lohman formula (see costsize.c for details) to
6711 : * estimate the total number of page fetches that occur. While this
6712 : * wasn't what it was designed for, it seems a reasonable model anyway.
6713 : * Note that we are counting pages not tuples anymore, so we take N = T =
6714 : * index size, as if there were one "tuple" per page.
6715 : */
6716 1162492 : num_outer_scans = loop_count;
6717 1162492 : num_scans = num_sa_scans * num_outer_scans;
6718 :
6719 1162492 : if (num_scans > 1)
6720 : {
6721 : double pages_fetched;
6722 :
6723 : /* total page fetches ignoring cache effects */
6724 135522 : pages_fetched = numIndexPages * num_scans;
6725 :
6726 : /* use Mackert and Lohman formula to adjust for cache effects */
6727 135522 : pages_fetched = index_pages_fetched(pages_fetched,
6728 : index->pages,
6729 135522 : (double) index->pages,
6730 : root);
6731 :
6732 : /*
6733 : * Now compute the total disk access cost, and then report a pro-rated
6734 : * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6735 : * since that's internal to the indexscan.)
6736 : */
6737 135522 : indexTotalCost = (pages_fetched * spc_random_page_cost)
6738 : / num_outer_scans;
6739 : }
6740 : else
6741 : {
6742 : /*
6743 : * For a single index scan, we just charge spc_random_page_cost per
6744 : * page touched.
6745 : */
6746 1026970 : indexTotalCost = numIndexPages * spc_random_page_cost;
6747 : }
6748 :
6749 : /*
6750 : * CPU cost: any complex expressions in the indexquals will need to be
6751 : * evaluated once at the start of the scan to reduce them to runtime keys
6752 : * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6753 : * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6754 : * indexqual operator. Because we have numIndexTuples as a per-scan
6755 : * number, we have to multiply by num_sa_scans to get the correct result
6756 : * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6757 : * ORDER BY expressions.
6758 : *
6759 : * Note: this neglects the possible costs of rechecking lossy operators.
6760 : * Detecting that that might be needed seems more expensive than it's
6761 : * worth, though, considering all the other inaccuracies here ...
6762 : */
6763 1162492 : qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
6764 1162492 : index_other_operands_eval_cost(root, indexOrderBys);
6765 1162492 : qual_op_cost = cpu_operator_cost *
6766 1162492 : (list_length(indexQuals) + list_length(indexOrderBys));
6767 :
6768 1162492 : indexStartupCost = qual_arg_cost;
6769 1162492 : indexTotalCost += qual_arg_cost;
6770 1162492 : indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6771 :
6772 : /*
6773 : * Generic assumption about index correlation: there isn't any.
6774 : */
6775 1162492 : indexCorrelation = 0.0;
6776 :
6777 : /*
6778 : * Return everything to caller.
6779 : */
6780 1162492 : costs->indexStartupCost = indexStartupCost;
6781 1162492 : costs->indexTotalCost = indexTotalCost;
6782 1162492 : costs->indexSelectivity = indexSelectivity;
6783 1162492 : costs->indexCorrelation = indexCorrelation;
6784 1162492 : costs->numIndexPages = numIndexPages;
6785 1162492 : costs->numIndexTuples = numIndexTuples;
6786 1162492 : costs->spc_random_page_cost = spc_random_page_cost;
6787 1162492 : costs->num_sa_scans = num_sa_scans;
6788 1162492 : }
6789 :
6790 : /*
6791 : * If the index is partial, add its predicate to the given qual list.
6792 : *
6793 : * ANDing the index predicate with the explicitly given indexquals produces
6794 : * a more accurate idea of the index's selectivity. However, we need to be
6795 : * careful not to insert redundant clauses, because clauselist_selectivity()
6796 : * is easily fooled into computing a too-low selectivity estimate. Our
6797 : * approach is to add only the predicate clause(s) that cannot be proven to
6798 : * be implied by the given indexquals. This successfully handles cases such
6799 : * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
6800 : * There are many other cases where we won't detect redundancy, leading to a
6801 : * too-low selectivity estimate, which will bias the system in favor of using
6802 : * partial indexes where possible. That is not necessarily bad though.
6803 : *
6804 : * Note that indexQuals contains RestrictInfo nodes while the indpred
6805 : * does not, so the output list will be mixed. This is OK for both
6806 : * predicate_implied_by() and clauselist_selectivity(), but might be
6807 : * problematic if the result were passed to other things.
6808 : */
6809 : List *
6810 1912374 : add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
6811 : {
6812 1912374 : List *predExtraQuals = NIL;
6813 : ListCell *lc;
6814 :
6815 1912374 : if (index->indpred == NIL)
6816 1910348 : return indexQuals;
6817 :
6818 4064 : foreach(lc, index->indpred)
6819 : {
6820 2038 : Node *predQual = (Node *) lfirst(lc);
6821 2038 : List *oneQual = list_make1(predQual);
6822 :
6823 2038 : if (!predicate_implied_by(oneQual, indexQuals, false))
6824 1836 : predExtraQuals = list_concat(predExtraQuals, oneQual);
6825 : }
6826 2026 : return list_concat(predExtraQuals, indexQuals);
6827 : }
6828 :
6829 :
6830 : void
6831 1154174 : btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
6832 : Cost *indexStartupCost, Cost *indexTotalCost,
6833 : Selectivity *indexSelectivity, double *indexCorrelation,
6834 : double *indexPages)
6835 : {
6836 1154174 : IndexOptInfo *index = path->indexinfo;
6837 1154174 : GenericCosts costs = {0};
6838 : Oid relid;
6839 : AttrNumber colnum;
6840 1154174 : VariableStatData vardata = {0};
6841 : double numIndexTuples;
6842 : Cost descentCost;
6843 : List *indexBoundQuals;
6844 : int indexcol;
6845 : bool eqQualHere;
6846 : bool found_saop;
6847 : bool found_is_null_op;
6848 : double num_sa_scans;
6849 : ListCell *lc;
6850 :
6851 : /*
6852 : * For a btree scan, only leading '=' quals plus inequality quals for the
6853 : * immediately next attribute contribute to index selectivity (these are
6854 : * the "boundary quals" that determine the starting and stopping points of
6855 : * the index scan). Additional quals can suppress visits to the heap, so
6856 : * it's OK to count them in indexSelectivity, but they should not count
6857 : * for estimating numIndexTuples. So we must examine the given indexquals
6858 : * to find out which ones count as boundary quals. We rely on the
6859 : * knowledge that they are given in index column order.
6860 : *
6861 : * For a RowCompareExpr, we consider only the first column, just as
6862 : * rowcomparesel() does.
6863 : *
6864 : * If there's a ScalarArrayOpExpr in the quals, we'll actually perform up
6865 : * to N index descents (not just one), but the ScalarArrayOpExpr's
6866 : * operator can be considered to act the same as it normally does.
6867 : */
6868 1154174 : indexBoundQuals = NIL;
6869 1154174 : indexcol = 0;
6870 1154174 : eqQualHere = false;
6871 1154174 : found_saop = false;
6872 1154174 : found_is_null_op = false;
6873 1154174 : num_sa_scans = 1;
6874 2013140 : foreach(lc, path->indexclauses)
6875 : {
6876 886980 : IndexClause *iclause = lfirst_node(IndexClause, lc);
6877 : ListCell *lc2;
6878 :
6879 886980 : if (indexcol != iclause->indexcol)
6880 : {
6881 : /* Beginning of a new column's quals */
6882 155168 : if (!eqQualHere)
6883 26638 : break; /* done if no '=' qual for indexcol */
6884 128530 : eqQualHere = false;
6885 128530 : indexcol++;
6886 128530 : if (indexcol != iclause->indexcol)
6887 1376 : break; /* no quals at all for indexcol */
6888 : }
6889 :
6890 : /* Examine each indexqual associated with this index clause */
6891 1720616 : foreach(lc2, iclause->indexquals)
6892 : {
6893 861650 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6894 861650 : Expr *clause = rinfo->clause;
6895 861650 : Oid clause_op = InvalidOid;
6896 : int op_strategy;
6897 :
6898 861650 : if (IsA(clause, OpExpr))
6899 : {
6900 849628 : OpExpr *op = (OpExpr *) clause;
6901 :
6902 849628 : clause_op = op->opno;
6903 : }
6904 12022 : else if (IsA(clause, RowCompareExpr))
6905 : {
6906 300 : RowCompareExpr *rc = (RowCompareExpr *) clause;
6907 :
6908 300 : clause_op = linitial_oid(rc->opnos);
6909 : }
6910 11722 : else if (IsA(clause, ScalarArrayOpExpr))
6911 : {
6912 9468 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6913 9468 : Node *other_operand = (Node *) lsecond(saop->args);
6914 9468 : double alength = estimate_array_length(root, other_operand);
6915 :
6916 9468 : clause_op = saop->opno;
6917 9468 : found_saop = true;
6918 : /* estimate SA descents by indexBoundQuals only */
6919 9468 : if (alength > 1)
6920 9372 : num_sa_scans *= alength;
6921 : }
6922 2254 : else if (IsA(clause, NullTest))
6923 : {
6924 2254 : NullTest *nt = (NullTest *) clause;
6925 :
6926 2254 : if (nt->nulltesttype == IS_NULL)
6927 : {
6928 210 : found_is_null_op = true;
6929 : /* IS NULL is like = for selectivity purposes */
6930 210 : eqQualHere = true;
6931 : }
6932 : }
6933 : else
6934 0 : elog(ERROR, "unsupported indexqual type: %d",
6935 : (int) nodeTag(clause));
6936 :
6937 : /* check for equality operator */
6938 861650 : if (OidIsValid(clause_op))
6939 : {
6940 859396 : op_strategy = get_op_opfamily_strategy(clause_op,
6941 859396 : index->opfamily[indexcol]);
6942 : Assert(op_strategy != 0); /* not a member of opfamily?? */
6943 859396 : if (op_strategy == BTEqualStrategyNumber)
6944 834806 : eqQualHere = true;
6945 : }
6946 :
6947 861650 : indexBoundQuals = lappend(indexBoundQuals, rinfo);
6948 : }
6949 : }
6950 :
6951 : /*
6952 : * If index is unique and we found an '=' clause for each column, we can
6953 : * just assume numIndexTuples = 1 and skip the expensive
6954 : * clauselist_selectivity calculations. However, a ScalarArrayOp or
6955 : * NullTest invalidates that theory, even though it sets eqQualHere.
6956 : */
6957 1154174 : if (index->unique &&
6958 1034416 : indexcol == index->nkeycolumns - 1 &&
6959 411404 : eqQualHere &&
6960 411404 : !found_saop &&
6961 406226 : !found_is_null_op)
6962 406160 : numIndexTuples = 1.0;
6963 : else
6964 : {
6965 : List *selectivityQuals;
6966 : Selectivity btreeSelectivity;
6967 :
6968 : /*
6969 : * If the index is partial, AND the index predicate with the
6970 : * index-bound quals to produce a more accurate idea of the number of
6971 : * rows covered by the bound conditions.
6972 : */
6973 748014 : selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6974 :
6975 748014 : btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6976 748014 : index->rel->relid,
6977 : JOIN_INNER,
6978 : NULL);
6979 748014 : numIndexTuples = btreeSelectivity * index->rel->tuples;
6980 :
6981 : /*
6982 : * btree automatically combines individual ScalarArrayOpExpr primitive
6983 : * index scans whenever the tuples covered by the next set of array
6984 : * keys are close to tuples covered by the current set. That puts a
6985 : * natural ceiling on the worst case number of descents -- there
6986 : * cannot possibly be more than one descent per leaf page scanned.
6987 : *
6988 : * Clamp the number of descents to at most 1/3 the number of index
6989 : * pages. This avoids implausibly high estimates with low selectivity
6990 : * paths, where scans usually require only one or two descents. This
6991 : * is most likely to help when there are several SAOP clauses, where
6992 : * naively accepting the total number of distinct combinations of
6993 : * array elements as the number of descents would frequently lead to
6994 : * wild overestimates.
6995 : *
6996 : * We somewhat arbitrarily don't just make the cutoff the total number
6997 : * of leaf pages (we make it 1/3 the total number of pages instead) to
6998 : * give the btree code credit for its ability to continue on the leaf
6999 : * level with low selectivity scans.
7000 : */
7001 748014 : num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
7002 748014 : num_sa_scans = Max(num_sa_scans, 1);
7003 :
7004 : /*
7005 : * As in genericcostestimate(), we have to adjust for any
7006 : * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
7007 : * to integer.
7008 : *
7009 : * It is tempting to make genericcostestimate behave as if SAOP
7010 : * clauses work in almost the same way as scalar operators during
7011 : * btree scans, making the top-level scan look like a continuous scan
7012 : * (as opposed to num_sa_scans-many primitive index scans). After
7013 : * all, btree scans mostly work like that at runtime. However, such a
7014 : * scheme would badly bias genericcostestimate's simplistic approach
7015 : * to calculating numIndexPages through prorating.
7016 : *
7017 : * Stick with the approach taken by non-native SAOP scans for now.
7018 : * genericcostestimate will use the Mackert-Lohman formula to
7019 : * compensate for repeat page fetches, even though that definitely
7020 : * won't happen during btree scans (not for leaf pages, at least).
7021 : * We're usually very pessimistic about the number of primitive index
7022 : * scans that will be required, but it's not clear how to do better.
7023 : */
7024 748014 : numIndexTuples = rint(numIndexTuples / num_sa_scans);
7025 : }
7026 :
7027 : /*
7028 : * Now do generic index cost estimation.
7029 : */
7030 1154174 : costs.numIndexTuples = numIndexTuples;
7031 1154174 : costs.num_sa_scans = num_sa_scans;
7032 :
7033 1154174 : genericcostestimate(root, path, loop_count, &costs);
7034 :
7035 : /*
7036 : * Add a CPU-cost component to represent the costs of initial btree
7037 : * descent. We don't charge any I/O cost for touching upper btree levels,
7038 : * since they tend to stay in cache, but we still have to do about log2(N)
7039 : * comparisons to descend a btree of N leaf tuples. We charge one
7040 : * cpu_operator_cost per comparison.
7041 : *
7042 : * If there are ScalarArrayOpExprs, charge this once per estimated SA
7043 : * index descent. The ones after the first one are not startup cost so
7044 : * far as the overall plan goes, so just add them to "total" cost.
7045 : */
7046 1154174 : if (index->tuples > 1) /* avoid computing log(0) */
7047 : {
7048 1119172 : descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
7049 1119172 : costs.indexStartupCost += descentCost;
7050 1119172 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7051 : }
7052 :
7053 : /*
7054 : * Even though we're not charging I/O cost for touching upper btree pages,
7055 : * it's still reasonable to charge some CPU cost per page descended
7056 : * through. Moreover, if we had no such charge at all, bloated indexes
7057 : * would appear to have the same search cost as unbloated ones, at least
7058 : * in cases where only a single leaf page is expected to be visited. This
7059 : * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
7060 : * touched. The number of such pages is btree tree height plus one (ie,
7061 : * we charge for the leaf page too). As above, charge once per estimated
7062 : * SA index descent.
7063 : */
7064 1154174 : descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7065 1154174 : costs.indexStartupCost += descentCost;
7066 1154174 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7067 :
7068 : /*
7069 : * If we can get an estimate of the first column's ordering correlation C
7070 : * from pg_statistic, estimate the index correlation as C for a
7071 : * single-column index, or C * 0.75 for multiple columns. (The idea here
7072 : * is that multiple columns dilute the importance of the first column's
7073 : * ordering, but don't negate it entirely. Before 8.0 we divided the
7074 : * correlation by the number of columns, but that seems too strong.)
7075 : */
7076 1154174 : if (index->indexkeys[0] != 0)
7077 : {
7078 : /* Simple variable --- look to stats for the underlying table */
7079 1151984 : RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
7080 :
7081 : Assert(rte->rtekind == RTE_RELATION);
7082 1151984 : relid = rte->relid;
7083 : Assert(relid != InvalidOid);
7084 1151984 : colnum = index->indexkeys[0];
7085 :
7086 1151984 : if (get_relation_stats_hook &&
7087 0 : (*get_relation_stats_hook) (root, rte, colnum, &vardata))
7088 : {
7089 : /*
7090 : * The hook took control of acquiring a stats tuple. If it did
7091 : * supply a tuple, it'd better have supplied a freefunc.
7092 : */
7093 0 : if (HeapTupleIsValid(vardata.statsTuple) &&
7094 0 : !vardata.freefunc)
7095 0 : elog(ERROR, "no function provided to release variable stats with");
7096 : }
7097 : else
7098 : {
7099 1151984 : vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7100 : ObjectIdGetDatum(relid),
7101 : Int16GetDatum(colnum),
7102 1151984 : BoolGetDatum(rte->inh));
7103 1151984 : vardata.freefunc = ReleaseSysCache;
7104 : }
7105 : }
7106 : else
7107 : {
7108 : /* Expression --- maybe there are stats for the index itself */
7109 2190 : relid = index->indexoid;
7110 2190 : colnum = 1;
7111 :
7112 2190 : if (get_index_stats_hook &&
7113 0 : (*get_index_stats_hook) (root, relid, colnum, &vardata))
7114 : {
7115 : /*
7116 : * The hook took control of acquiring a stats tuple. If it did
7117 : * supply a tuple, it'd better have supplied a freefunc.
7118 : */
7119 0 : if (HeapTupleIsValid(vardata.statsTuple) &&
7120 0 : !vardata.freefunc)
7121 0 : elog(ERROR, "no function provided to release variable stats with");
7122 : }
7123 : else
7124 : {
7125 2190 : vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7126 : ObjectIdGetDatum(relid),
7127 : Int16GetDatum(colnum),
7128 : BoolGetDatum(false));
7129 2190 : vardata.freefunc = ReleaseSysCache;
7130 : }
7131 : }
7132 :
7133 1154174 : if (HeapTupleIsValid(vardata.statsTuple))
7134 : {
7135 : Oid sortop;
7136 : AttStatsSlot sslot;
7137 :
7138 921674 : sortop = get_opfamily_member(index->opfamily[0],
7139 921674 : index->opcintype[0],
7140 921674 : index->opcintype[0],
7141 : BTLessStrategyNumber);
7142 1843348 : if (OidIsValid(sortop) &&
7143 921674 : get_attstatsslot(&sslot, vardata.statsTuple,
7144 : STATISTIC_KIND_CORRELATION, sortop,
7145 : ATTSTATSSLOT_NUMBERS))
7146 : {
7147 : double varCorrelation;
7148 :
7149 : Assert(sslot.nnumbers == 1);
7150 916348 : varCorrelation = sslot.numbers[0];
7151 :
7152 916348 : if (index->reverse_sort[0])
7153 0 : varCorrelation = -varCorrelation;
7154 :
7155 916348 : if (index->nkeycolumns > 1)
7156 363856 : costs.indexCorrelation = varCorrelation * 0.75;
7157 : else
7158 552492 : costs.indexCorrelation = varCorrelation;
7159 :
7160 916348 : free_attstatsslot(&sslot);
7161 : }
7162 : }
7163 :
7164 1154174 : ReleaseVariableStats(vardata);
7165 :
7166 1154174 : *indexStartupCost = costs.indexStartupCost;
7167 1154174 : *indexTotalCost = costs.indexTotalCost;
7168 1154174 : *indexSelectivity = costs.indexSelectivity;
7169 1154174 : *indexCorrelation = costs.indexCorrelation;
7170 1154174 : *indexPages = costs.numIndexPages;
7171 1154174 : }
7172 :
7173 : void
7174 410 : hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7175 : Cost *indexStartupCost, Cost *indexTotalCost,
7176 : Selectivity *indexSelectivity, double *indexCorrelation,
7177 : double *indexPages)
7178 : {
7179 410 : GenericCosts costs = {0};
7180 :
7181 410 : genericcostestimate(root, path, loop_count, &costs);
7182 :
7183 : /*
7184 : * A hash index has no descent costs as such, since the index AM can go
7185 : * directly to the target bucket after computing the hash value. There
7186 : * are a couple of other hash-specific costs that we could conceivably add
7187 : * here, though:
7188 : *
7189 : * Ideally we'd charge spc_random_page_cost for each page in the target
7190 : * bucket, not just the numIndexPages pages that genericcostestimate
7191 : * thought we'd visit. However in most cases we don't know which bucket
7192 : * that will be. There's no point in considering the average bucket size
7193 : * because the hash AM makes sure that's always one page.
7194 : *
7195 : * Likewise, we could consider charging some CPU for each index tuple in
7196 : * the bucket, if we knew how many there were. But the per-tuple cost is
7197 : * just a hash value comparison, not a general datatype-dependent
7198 : * comparison, so any such charge ought to be quite a bit less than
7199 : * cpu_operator_cost; which makes it probably not worth worrying about.
7200 : *
7201 : * A bigger issue is that chance hash-value collisions will result in
7202 : * wasted probes into the heap. We don't currently attempt to model this
7203 : * cost on the grounds that it's rare, but maybe it's not rare enough.
7204 : * (Any fix for this ought to consider the generic lossy-operator problem,
7205 : * though; it's not entirely hash-specific.)
7206 : */
7207 :
7208 410 : *indexStartupCost = costs.indexStartupCost;
7209 410 : *indexTotalCost = costs.indexTotalCost;
7210 410 : *indexSelectivity = costs.indexSelectivity;
7211 410 : *indexCorrelation = costs.indexCorrelation;
7212 410 : *indexPages = costs.numIndexPages;
7213 410 : }
7214 :
7215 : void
7216 5312 : gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7217 : Cost *indexStartupCost, Cost *indexTotalCost,
7218 : Selectivity *indexSelectivity, double *indexCorrelation,
7219 : double *indexPages)
7220 : {
7221 5312 : IndexOptInfo *index = path->indexinfo;
7222 5312 : GenericCosts costs = {0};
7223 : Cost descentCost;
7224 :
7225 5312 : genericcostestimate(root, path, loop_count, &costs);
7226 :
7227 : /*
7228 : * We model index descent costs similarly to those for btree, but to do
7229 : * that we first need an idea of the tree height. We somewhat arbitrarily
7230 : * assume that the fanout is 100, meaning the tree height is at most
7231 : * log100(index->pages).
7232 : *
7233 : * Although this computation isn't really expensive enough to require
7234 : * caching, we might as well use index->tree_height to cache it.
7235 : */
7236 5312 : if (index->tree_height < 0) /* unknown? */
7237 : {
7238 5298 : if (index->pages > 1) /* avoid computing log(0) */
7239 2704 : index->tree_height = (int) (log(index->pages) / log(100.0));
7240 : else
7241 2594 : index->tree_height = 0;
7242 : }
7243 :
7244 : /*
7245 : * Add a CPU-cost component to represent the costs of initial descent. We
7246 : * just use log(N) here not log2(N) since the branching factor isn't
7247 : * necessarily two anyway. As for btree, charge once per SA scan.
7248 : */
7249 5312 : if (index->tuples > 1) /* avoid computing log(0) */
7250 : {
7251 5312 : descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7252 5312 : costs.indexStartupCost += descentCost;
7253 5312 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7254 : }
7255 :
7256 : /*
7257 : * Likewise add a per-page charge, calculated the same as for btrees.
7258 : */
7259 5312 : descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7260 5312 : costs.indexStartupCost += descentCost;
7261 5312 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7262 :
7263 5312 : *indexStartupCost = costs.indexStartupCost;
7264 5312 : *indexTotalCost = costs.indexTotalCost;
7265 5312 : *indexSelectivity = costs.indexSelectivity;
7266 5312 : *indexCorrelation = costs.indexCorrelation;
7267 5312 : *indexPages = costs.numIndexPages;
7268 5312 : }
7269 :
7270 : void
7271 1784 : spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7272 : Cost *indexStartupCost, Cost *indexTotalCost,
7273 : Selectivity *indexSelectivity, double *indexCorrelation,
7274 : double *indexPages)
7275 : {
7276 1784 : IndexOptInfo *index = path->indexinfo;
7277 1784 : GenericCosts costs = {0};
7278 : Cost descentCost;
7279 :
7280 1784 : genericcostestimate(root, path, loop_count, &costs);
7281 :
7282 : /*
7283 : * We model index descent costs similarly to those for btree, but to do
7284 : * that we first need an idea of the tree height. We somewhat arbitrarily
7285 : * assume that the fanout is 100, meaning the tree height is at most
7286 : * log100(index->pages).
7287 : *
7288 : * Although this computation isn't really expensive enough to require
7289 : * caching, we might as well use index->tree_height to cache it.
7290 : */
7291 1784 : if (index->tree_height < 0) /* unknown? */
7292 : {
7293 1778 : if (index->pages > 1) /* avoid computing log(0) */
7294 1778 : index->tree_height = (int) (log(index->pages) / log(100.0));
7295 : else
7296 0 : index->tree_height = 0;
7297 : }
7298 :
7299 : /*
7300 : * Add a CPU-cost component to represent the costs of initial descent. We
7301 : * just use log(N) here not log2(N) since the branching factor isn't
7302 : * necessarily two anyway. As for btree, charge once per SA scan.
7303 : */
7304 1784 : if (index->tuples > 1) /* avoid computing log(0) */
7305 : {
7306 1784 : descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7307 1784 : costs.indexStartupCost += descentCost;
7308 1784 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7309 : }
7310 :
7311 : /*
7312 : * Likewise add a per-page charge, calculated the same as for btrees.
7313 : */
7314 1784 : descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7315 1784 : costs.indexStartupCost += descentCost;
7316 1784 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7317 :
7318 1784 : *indexStartupCost = costs.indexStartupCost;
7319 1784 : *indexTotalCost = costs.indexTotalCost;
7320 1784 : *indexSelectivity = costs.indexSelectivity;
7321 1784 : *indexCorrelation = costs.indexCorrelation;
7322 1784 : *indexPages = costs.numIndexPages;
7323 1784 : }
7324 :
7325 :
7326 : /*
7327 : * Support routines for gincostestimate
7328 : */
7329 :
7330 : typedef struct
7331 : {
7332 : bool attHasFullScan[INDEX_MAX_KEYS];
7333 : bool attHasNormalScan[INDEX_MAX_KEYS];
7334 : double partialEntries;
7335 : double exactEntries;
7336 : double searchEntries;
7337 : double arrayScans;
7338 : } GinQualCounts;
7339 :
7340 : /*
7341 : * Estimate the number of index terms that need to be searched for while
7342 : * testing the given GIN query, and increment the counts in *counts
7343 : * appropriately. If the query is unsatisfiable, return false.
7344 : */
7345 : static bool
7346 2072 : gincost_pattern(IndexOptInfo *index, int indexcol,
7347 : Oid clause_op, Datum query,
7348 : GinQualCounts *counts)
7349 : {
7350 : FmgrInfo flinfo;
7351 : Oid extractProcOid;
7352 : Oid collation;
7353 : int strategy_op;
7354 : Oid lefttype,
7355 : righttype;
7356 2072 : int32 nentries = 0;
7357 2072 : bool *partial_matches = NULL;
7358 2072 : Pointer *extra_data = NULL;
7359 2072 : bool *nullFlags = NULL;
7360 2072 : int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
7361 : int32 i;
7362 :
7363 : Assert(indexcol < index->nkeycolumns);
7364 :
7365 : /*
7366 : * Get the operator's strategy number and declared input data types within
7367 : * the index opfamily. (We don't need the latter, but we use
7368 : * get_op_opfamily_properties because it will throw error if it fails to
7369 : * find a matching pg_amop entry.)
7370 : */
7371 2072 : get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
7372 : &strategy_op, &lefttype, &righttype);
7373 :
7374 : /*
7375 : * GIN always uses the "default" support functions, which are those with
7376 : * lefttype == righttype == the opclass' opcintype (see
7377 : * IndexSupportInitialize in relcache.c).
7378 : */
7379 2072 : extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
7380 2072 : index->opcintype[indexcol],
7381 2072 : index->opcintype[indexcol],
7382 : GIN_EXTRACTQUERY_PROC);
7383 :
7384 2072 : if (!OidIsValid(extractProcOid))
7385 : {
7386 : /* should not happen; throw same error as index_getprocinfo */
7387 0 : elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
7388 : GIN_EXTRACTQUERY_PROC, indexcol + 1,
7389 : get_rel_name(index->indexoid));
7390 : }
7391 :
7392 : /*
7393 : * Choose collation to pass to extractProc (should match initGinState).
7394 : */
7395 2072 : if (OidIsValid(index->indexcollations[indexcol]))
7396 364 : collation = index->indexcollations[indexcol];
7397 : else
7398 1708 : collation = DEFAULT_COLLATION_OID;
7399 :
7400 2072 : fmgr_info(extractProcOid, &flinfo);
7401 :
7402 2072 : set_fn_opclass_options(&flinfo, index->opclassoptions[indexcol]);
7403 :
7404 2072 : FunctionCall7Coll(&flinfo,
7405 : collation,
7406 : query,
7407 : PointerGetDatum(&nentries),
7408 : UInt16GetDatum(strategy_op),
7409 : PointerGetDatum(&partial_matches),
7410 : PointerGetDatum(&extra_data),
7411 : PointerGetDatum(&nullFlags),
7412 : PointerGetDatum(&searchMode));
7413 :
7414 2072 : if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
7415 : {
7416 : /* No match is possible */
7417 12 : return false;
7418 : }
7419 :
7420 8796 : for (i = 0; i < nentries; i++)
7421 : {
7422 : /*
7423 : * For partial match we haven't any information to estimate number of
7424 : * matched entries in index, so, we just estimate it as 100
7425 : */
7426 6736 : if (partial_matches && partial_matches[i])
7427 316 : counts->partialEntries += 100;
7428 : else
7429 6420 : counts->exactEntries++;
7430 :
7431 6736 : counts->searchEntries++;
7432 : }
7433 :
7434 2060 : if (searchMode == GIN_SEARCH_MODE_DEFAULT)
7435 : {
7436 1588 : counts->attHasNormalScan[indexcol] = true;
7437 : }
7438 472 : else if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
7439 : {
7440 : /* Treat "include empty" like an exact-match item */
7441 44 : counts->attHasNormalScan[indexcol] = true;
7442 44 : counts->exactEntries++;
7443 44 : counts->searchEntries++;
7444 : }
7445 : else
7446 : {
7447 : /* It's GIN_SEARCH_MODE_ALL */
7448 428 : counts->attHasFullScan[indexcol] = true;
7449 : }
7450 :
7451 2060 : return true;
7452 : }
7453 :
7454 : /*
7455 : * Estimate the number of index terms that need to be searched for while
7456 : * testing the given GIN index clause, and increment the counts in *counts
7457 : * appropriately. If the query is unsatisfiable, return false.
7458 : */
7459 : static bool
7460 2060 : gincost_opexpr(PlannerInfo *root,
7461 : IndexOptInfo *index,
7462 : int indexcol,
7463 : OpExpr *clause,
7464 : GinQualCounts *counts)
7465 : {
7466 2060 : Oid clause_op = clause->opno;
7467 2060 : Node *operand = (Node *) lsecond(clause->args);
7468 :
7469 : /* aggressively reduce to a constant, and look through relabeling */
7470 2060 : operand = estimate_expression_value(root, operand);
7471 :
7472 2060 : if (IsA(operand, RelabelType))
7473 0 : operand = (Node *) ((RelabelType *) operand)->arg;
7474 :
7475 : /*
7476 : * It's impossible to call extractQuery method for unknown operand. So
7477 : * unless operand is a Const we can't do much; just assume there will be
7478 : * one ordinary search entry from the operand at runtime.
7479 : */
7480 2060 : if (!IsA(operand, Const))
7481 : {
7482 0 : counts->exactEntries++;
7483 0 : counts->searchEntries++;
7484 0 : return true;
7485 : }
7486 :
7487 : /* If Const is null, there can be no matches */
7488 2060 : if (((Const *) operand)->constisnull)
7489 0 : return false;
7490 :
7491 : /* Otherwise, apply extractQuery and get the actual term counts */
7492 2060 : return gincost_pattern(index, indexcol, clause_op,
7493 : ((Const *) operand)->constvalue,
7494 : counts);
7495 : }
7496 :
7497 : /*
7498 : * Estimate the number of index terms that need to be searched for while
7499 : * testing the given GIN index clause, and increment the counts in *counts
7500 : * appropriately. If the query is unsatisfiable, return false.
7501 : *
7502 : * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
7503 : * each of which involves one value from the RHS array, plus all the
7504 : * non-array quals (if any). To model this, we average the counts across
7505 : * the RHS elements, and add the averages to the counts in *counts (which
7506 : * correspond to per-indexscan costs). We also multiply counts->arrayScans
7507 : * by N, causing gincostestimate to scale up its estimates accordingly.
7508 : */
7509 : static bool
7510 6 : gincost_scalararrayopexpr(PlannerInfo *root,
7511 : IndexOptInfo *index,
7512 : int indexcol,
7513 : ScalarArrayOpExpr *clause,
7514 : double numIndexEntries,
7515 : GinQualCounts *counts)
7516 : {
7517 6 : Oid clause_op = clause->opno;
7518 6 : Node *rightop = (Node *) lsecond(clause->args);
7519 : ArrayType *arrayval;
7520 : int16 elmlen;
7521 : bool elmbyval;
7522 : char elmalign;
7523 : int numElems;
7524 : Datum *elemValues;
7525 : bool *elemNulls;
7526 : GinQualCounts arraycounts;
7527 6 : int numPossible = 0;
7528 : int i;
7529 :
7530 : Assert(clause->useOr);
7531 :
7532 : /* aggressively reduce to a constant, and look through relabeling */
7533 6 : rightop = estimate_expression_value(root, rightop);
7534 :
7535 6 : if (IsA(rightop, RelabelType))
7536 0 : rightop = (Node *) ((RelabelType *) rightop)->arg;
7537 :
7538 : /*
7539 : * It's impossible to call extractQuery method for unknown operand. So
7540 : * unless operand is a Const we can't do much; just assume there will be
7541 : * one ordinary search entry from each array entry at runtime, and fall
7542 : * back on a probably-bad estimate of the number of array entries.
7543 : */
7544 6 : if (!IsA(rightop, Const))
7545 : {
7546 0 : counts->exactEntries++;
7547 0 : counts->searchEntries++;
7548 0 : counts->arrayScans *= estimate_array_length(root, rightop);
7549 0 : return true;
7550 : }
7551 :
7552 : /* If Const is null, there can be no matches */
7553 6 : if (((Const *) rightop)->constisnull)
7554 0 : return false;
7555 :
7556 : /* Otherwise, extract the array elements and iterate over them */
7557 6 : arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
7558 6 : get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
7559 : &elmlen, &elmbyval, &elmalign);
7560 6 : deconstruct_array(arrayval,
7561 : ARR_ELEMTYPE(arrayval),
7562 : elmlen, elmbyval, elmalign,
7563 : &elemValues, &elemNulls, &numElems);
7564 :
7565 6 : memset(&arraycounts, 0, sizeof(arraycounts));
7566 :
7567 18 : for (i = 0; i < numElems; i++)
7568 : {
7569 : GinQualCounts elemcounts;
7570 :
7571 : /* NULL can't match anything, so ignore, as the executor will */
7572 12 : if (elemNulls[i])
7573 0 : continue;
7574 :
7575 : /* Otherwise, apply extractQuery and get the actual term counts */
7576 12 : memset(&elemcounts, 0, sizeof(elemcounts));
7577 :
7578 12 : if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
7579 : &elemcounts))
7580 : {
7581 : /* We ignore array elements that are unsatisfiable patterns */
7582 12 : numPossible++;
7583 :
7584 12 : if (elemcounts.attHasFullScan[indexcol] &&
7585 0 : !elemcounts.attHasNormalScan[indexcol])
7586 : {
7587 : /*
7588 : * Full index scan will be required. We treat this as if
7589 : * every key in the index had been listed in the query; is
7590 : * that reasonable?
7591 : */
7592 0 : elemcounts.partialEntries = 0;
7593 0 : elemcounts.exactEntries = numIndexEntries;
7594 0 : elemcounts.searchEntries = numIndexEntries;
7595 : }
7596 12 : arraycounts.partialEntries += elemcounts.partialEntries;
7597 12 : arraycounts.exactEntries += elemcounts.exactEntries;
7598 12 : arraycounts.searchEntries += elemcounts.searchEntries;
7599 : }
7600 : }
7601 :
7602 6 : if (numPossible == 0)
7603 : {
7604 : /* No satisfiable patterns in the array */
7605 0 : return false;
7606 : }
7607 :
7608 : /*
7609 : * Now add the averages to the global counts. This will give us an
7610 : * estimate of the average number of terms searched for in each indexscan,
7611 : * including contributions from both array and non-array quals.
7612 : */
7613 6 : counts->partialEntries += arraycounts.partialEntries / numPossible;
7614 6 : counts->exactEntries += arraycounts.exactEntries / numPossible;
7615 6 : counts->searchEntries += arraycounts.searchEntries / numPossible;
7616 :
7617 6 : counts->arrayScans *= numPossible;
7618 :
7619 6 : return true;
7620 : }
7621 :
7622 : /*
7623 : * GIN has search behavior completely different from other index types
7624 : */
7625 : void
7626 1868 : gincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7627 : Cost *indexStartupCost, Cost *indexTotalCost,
7628 : Selectivity *indexSelectivity, double *indexCorrelation,
7629 : double *indexPages)
7630 : {
7631 1868 : IndexOptInfo *index = path->indexinfo;
7632 1868 : List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7633 : List *selectivityQuals;
7634 1868 : double numPages = index->pages,
7635 1868 : numTuples = index->tuples;
7636 : double numEntryPages,
7637 : numDataPages,
7638 : numPendingPages,
7639 : numEntries;
7640 : GinQualCounts counts;
7641 : bool matchPossible;
7642 : bool fullIndexScan;
7643 : double partialScale;
7644 : double entryPagesFetched,
7645 : dataPagesFetched,
7646 : dataPagesFetchedBySel;
7647 : double qual_op_cost,
7648 : qual_arg_cost,
7649 : spc_random_page_cost,
7650 : outer_scans;
7651 : Cost descentCost;
7652 : Relation indexRel;
7653 : GinStatsData ginStats;
7654 : ListCell *lc;
7655 : int i;
7656 :
7657 : /*
7658 : * Obtain statistical information from the meta page, if possible. Else
7659 : * set ginStats to zeroes, and we'll cope below.
7660 : */
7661 1868 : if (!index->hypothetical)
7662 : {
7663 : /* Lock should have already been obtained in plancat.c */
7664 1868 : indexRel = index_open(index->indexoid, NoLock);
7665 1868 : ginGetStats(indexRel, &ginStats);
7666 1868 : index_close(indexRel, NoLock);
7667 : }
7668 : else
7669 : {
7670 0 : memset(&ginStats, 0, sizeof(ginStats));
7671 : }
7672 :
7673 : /*
7674 : * Assuming we got valid (nonzero) stats at all, nPendingPages can be
7675 : * trusted, but the other fields are data as of the last VACUUM. We can
7676 : * scale them up to account for growth since then, but that method only
7677 : * goes so far; in the worst case, the stats might be for a completely
7678 : * empty index, and scaling them will produce pretty bogus numbers.
7679 : * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
7680 : * it's grown more than that, fall back to estimating things only from the
7681 : * assumed-accurate index size. But we'll trust nPendingPages in any case
7682 : * so long as it's not clearly insane, ie, more than the index size.
7683 : */
7684 1868 : if (ginStats.nPendingPages < numPages)
7685 1868 : numPendingPages = ginStats.nPendingPages;
7686 : else
7687 0 : numPendingPages = 0;
7688 :
7689 1868 : if (numPages > 0 && ginStats.nTotalPages <= numPages &&
7690 1868 : ginStats.nTotalPages > numPages / 4 &&
7691 1816 : ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
7692 1558 : {
7693 : /*
7694 : * OK, the stats seem close enough to sane to be trusted. But we
7695 : * still need to scale them by the ratio numPages / nTotalPages to
7696 : * account for growth since the last VACUUM.
7697 : */
7698 1558 : double scale = numPages / ginStats.nTotalPages;
7699 :
7700 1558 : numEntryPages = ceil(ginStats.nEntryPages * scale);
7701 1558 : numDataPages = ceil(ginStats.nDataPages * scale);
7702 1558 : numEntries = ceil(ginStats.nEntries * scale);
7703 : /* ensure we didn't round up too much */
7704 1558 : numEntryPages = Min(numEntryPages, numPages - numPendingPages);
7705 1558 : numDataPages = Min(numDataPages,
7706 : numPages - numPendingPages - numEntryPages);
7707 : }
7708 : else
7709 : {
7710 : /*
7711 : * We might get here because it's a hypothetical index, or an index
7712 : * created pre-9.1 and never vacuumed since upgrading (in which case
7713 : * its stats would read as zeroes), or just because it's grown too
7714 : * much since the last VACUUM for us to put our faith in scaling.
7715 : *
7716 : * Invent some plausible internal statistics based on the index page
7717 : * count (and clamp that to at least 10 pages, just in case). We
7718 : * estimate that 90% of the index is entry pages, and the rest is data
7719 : * pages. Estimate 100 entries per entry page; this is rather bogus
7720 : * since it'll depend on the size of the keys, but it's more robust
7721 : * than trying to predict the number of entries per heap tuple.
7722 : */
7723 310 : numPages = Max(numPages, 10);
7724 310 : numEntryPages = floor((numPages - numPendingPages) * 0.90);
7725 310 : numDataPages = numPages - numPendingPages - numEntryPages;
7726 310 : numEntries = floor(numEntryPages * 100);
7727 : }
7728 :
7729 : /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
7730 1868 : if (numEntries < 1)
7731 0 : numEntries = 1;
7732 :
7733 : /*
7734 : * If the index is partial, AND the index predicate with the index-bound
7735 : * quals to produce a more accurate idea of the number of rows covered by
7736 : * the bound conditions.
7737 : */
7738 1868 : selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7739 :
7740 : /* Estimate the fraction of main-table tuples that will be visited */
7741 3736 : *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7742 1868 : index->rel->relid,
7743 : JOIN_INNER,
7744 : NULL);
7745 :
7746 : /* fetch estimated page cost for tablespace containing index */
7747 1868 : get_tablespace_page_costs(index->reltablespace,
7748 : &spc_random_page_cost,
7749 : NULL);
7750 :
7751 : /*
7752 : * Generic assumption about index correlation: there isn't any.
7753 : */
7754 1868 : *indexCorrelation = 0.0;
7755 :
7756 : /*
7757 : * Examine quals to estimate number of search entries & partial matches
7758 : */
7759 1868 : memset(&counts, 0, sizeof(counts));
7760 1868 : counts.arrayScans = 1;
7761 1868 : matchPossible = true;
7762 :
7763 3934 : foreach(lc, path->indexclauses)
7764 : {
7765 2066 : IndexClause *iclause = lfirst_node(IndexClause, lc);
7766 : ListCell *lc2;
7767 :
7768 4120 : foreach(lc2, iclause->indexquals)
7769 : {
7770 2066 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7771 2066 : Expr *clause = rinfo->clause;
7772 :
7773 2066 : if (IsA(clause, OpExpr))
7774 : {
7775 2060 : matchPossible = gincost_opexpr(root,
7776 : index,
7777 2060 : iclause->indexcol,
7778 : (OpExpr *) clause,
7779 : &counts);
7780 2060 : if (!matchPossible)
7781 12 : break;
7782 : }
7783 6 : else if (IsA(clause, ScalarArrayOpExpr))
7784 : {
7785 6 : matchPossible = gincost_scalararrayopexpr(root,
7786 : index,
7787 6 : iclause->indexcol,
7788 : (ScalarArrayOpExpr *) clause,
7789 : numEntries,
7790 : &counts);
7791 6 : if (!matchPossible)
7792 0 : break;
7793 : }
7794 : else
7795 : {
7796 : /* shouldn't be anything else for a GIN index */
7797 0 : elog(ERROR, "unsupported GIN indexqual type: %d",
7798 : (int) nodeTag(clause));
7799 : }
7800 : }
7801 : }
7802 :
7803 : /* Fall out if there were any provably-unsatisfiable quals */
7804 1868 : if (!matchPossible)
7805 : {
7806 12 : *indexStartupCost = 0;
7807 12 : *indexTotalCost = 0;
7808 12 : *indexSelectivity = 0;
7809 12 : return;
7810 : }
7811 :
7812 : /*
7813 : * If attribute has a full scan and at the same time doesn't have normal
7814 : * scan, then we'll have to scan all non-null entries of that attribute.
7815 : * Currently, we don't have per-attribute statistics for GIN. Thus, we
7816 : * must assume the whole GIN index has to be scanned in this case.
7817 : */
7818 1856 : fullIndexScan = false;
7819 3602 : for (i = 0; i < index->nkeycolumns; i++)
7820 : {
7821 2084 : if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
7822 : {
7823 338 : fullIndexScan = true;
7824 338 : break;
7825 : }
7826 : }
7827 :
7828 1856 : if (fullIndexScan || indexQuals == NIL)
7829 : {
7830 : /*
7831 : * Full index scan will be required. We treat this as if every key in
7832 : * the index had been listed in the query; is that reasonable?
7833 : */
7834 338 : counts.partialEntries = 0;
7835 338 : counts.exactEntries = numEntries;
7836 338 : counts.searchEntries = numEntries;
7837 : }
7838 :
7839 : /* Will we have more than one iteration of a nestloop scan? */
7840 1856 : outer_scans = loop_count;
7841 :
7842 : /*
7843 : * Compute cost to begin scan, first of all, pay attention to pending
7844 : * list.
7845 : */
7846 1856 : entryPagesFetched = numPendingPages;
7847 :
7848 : /*
7849 : * Estimate number of entry pages read. We need to do
7850 : * counts.searchEntries searches. Use a power function as it should be,
7851 : * but tuples on leaf pages usually is much greater. Here we include all
7852 : * searches in entry tree, including search of first entry in partial
7853 : * match algorithm
7854 : */
7855 1856 : entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
7856 :
7857 : /*
7858 : * Add an estimate of entry pages read by partial match algorithm. It's a
7859 : * scan over leaf pages in entry tree. We haven't any useful stats here,
7860 : * so estimate it as proportion. Because counts.partialEntries is really
7861 : * pretty bogus (see code above), it's possible that it is more than
7862 : * numEntries; clamp the proportion to ensure sanity.
7863 : */
7864 1856 : partialScale = counts.partialEntries / numEntries;
7865 1856 : partialScale = Min(partialScale, 1.0);
7866 :
7867 1856 : entryPagesFetched += ceil(numEntryPages * partialScale);
7868 :
7869 : /*
7870 : * Partial match algorithm reads all data pages before doing actual scan,
7871 : * so it's a startup cost. Again, we haven't any useful stats here, so
7872 : * estimate it as proportion.
7873 : */
7874 1856 : dataPagesFetched = ceil(numDataPages * partialScale);
7875 :
7876 1856 : *indexStartupCost = 0;
7877 1856 : *indexTotalCost = 0;
7878 :
7879 : /*
7880 : * Add a CPU-cost component to represent the costs of initial entry btree
7881 : * descent. We don't charge any I/O cost for touching upper btree levels,
7882 : * since they tend to stay in cache, but we still have to do about log2(N)
7883 : * comparisons to descend a btree of N leaf tuples. We charge one
7884 : * cpu_operator_cost per comparison.
7885 : *
7886 : * If there are ScalarArrayOpExprs, charge this once per SA scan. The
7887 : * ones after the first one are not startup cost so far as the overall
7888 : * plan is concerned, so add them only to "total" cost.
7889 : */
7890 1856 : if (numEntries > 1) /* avoid computing log(0) */
7891 : {
7892 1856 : descentCost = ceil(log(numEntries) / log(2.0)) * cpu_operator_cost;
7893 1856 : *indexStartupCost += descentCost * counts.searchEntries;
7894 1856 : *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
7895 : }
7896 :
7897 : /*
7898 : * Add a cpu cost per entry-page fetched. This is not amortized over a
7899 : * loop.
7900 : */
7901 1856 : *indexStartupCost += entryPagesFetched * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7902 1856 : *indexTotalCost += entryPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7903 :
7904 : /*
7905 : * Add a cpu cost per data-page fetched. This is also not amortized over a
7906 : * loop. Since those are the data pages from the partial match algorithm,
7907 : * charge them as startup cost.
7908 : */
7909 1856 : *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * dataPagesFetched;
7910 :
7911 : /*
7912 : * Since we add the startup cost to the total cost later on, remove the
7913 : * initial arrayscan from the total.
7914 : */
7915 1856 : *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7916 :
7917 : /*
7918 : * Calculate cache effects if more than one scan due to nestloops or array
7919 : * quals. The result is pro-rated per nestloop scan, but the array qual
7920 : * factor shouldn't be pro-rated (compare genericcostestimate).
7921 : */
7922 1856 : if (outer_scans > 1 || counts.arrayScans > 1)
7923 : {
7924 6 : entryPagesFetched *= outer_scans * counts.arrayScans;
7925 6 : entryPagesFetched = index_pages_fetched(entryPagesFetched,
7926 : (BlockNumber) numEntryPages,
7927 : numEntryPages, root);
7928 6 : entryPagesFetched /= outer_scans;
7929 6 : dataPagesFetched *= outer_scans * counts.arrayScans;
7930 6 : dataPagesFetched = index_pages_fetched(dataPagesFetched,
7931 : (BlockNumber) numDataPages,
7932 : numDataPages, root);
7933 6 : dataPagesFetched /= outer_scans;
7934 : }
7935 :
7936 : /*
7937 : * Here we use random page cost because logically-close pages could be far
7938 : * apart on disk.
7939 : */
7940 1856 : *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
7941 :
7942 : /*
7943 : * Now compute the number of data pages fetched during the scan.
7944 : *
7945 : * We assume every entry to have the same number of items, and that there
7946 : * is no overlap between them. (XXX: tsvector and array opclasses collect
7947 : * statistics on the frequency of individual keys; it would be nice to use
7948 : * those here.)
7949 : */
7950 1856 : dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
7951 :
7952 : /*
7953 : * If there is a lot of overlap among the entries, in particular if one of
7954 : * the entries is very frequent, the above calculation can grossly
7955 : * under-estimate. As a simple cross-check, calculate a lower bound based
7956 : * on the overall selectivity of the quals. At a minimum, we must read
7957 : * one item pointer for each matching entry.
7958 : *
7959 : * The width of each item pointer varies, based on the level of
7960 : * compression. We don't have statistics on that, but an average of
7961 : * around 3 bytes per item is fairly typical.
7962 : */
7963 1856 : dataPagesFetchedBySel = ceil(*indexSelectivity *
7964 1856 : (numTuples / (BLCKSZ / 3)));
7965 1856 : if (dataPagesFetchedBySel > dataPagesFetched)
7966 1476 : dataPagesFetched = dataPagesFetchedBySel;
7967 :
7968 : /* Add one page cpu-cost to the startup cost */
7969 1856 : *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
7970 :
7971 : /*
7972 : * Add once again a CPU-cost for those data pages, before amortizing for
7973 : * cache.
7974 : */
7975 1856 : *indexTotalCost += dataPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7976 :
7977 : /* Account for cache effects, the same as above */
7978 1856 : if (outer_scans > 1 || counts.arrayScans > 1)
7979 : {
7980 6 : dataPagesFetched *= outer_scans * counts.arrayScans;
7981 6 : dataPagesFetched = index_pages_fetched(dataPagesFetched,
7982 : (BlockNumber) numDataPages,
7983 : numDataPages, root);
7984 6 : dataPagesFetched /= outer_scans;
7985 : }
7986 :
7987 : /* And apply random_page_cost as the cost per page */
7988 1856 : *indexTotalCost += *indexStartupCost +
7989 1856 : dataPagesFetched * spc_random_page_cost;
7990 :
7991 : /*
7992 : * Add on index qual eval costs, much as in genericcostestimate. We charge
7993 : * cpu but we can disregard indexorderbys, since GIN doesn't support
7994 : * those.
7995 : */
7996 1856 : qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7997 1856 : qual_op_cost = cpu_operator_cost * list_length(indexQuals);
7998 :
7999 1856 : *indexStartupCost += qual_arg_cost;
8000 1856 : *indexTotalCost += qual_arg_cost;
8001 :
8002 : /*
8003 : * Add a cpu cost per search entry, corresponding to the actual visited
8004 : * entries.
8005 : */
8006 1856 : *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
8007 : /* Now add a cpu cost per tuple in the posting lists / trees */
8008 1856 : *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
8009 1856 : *indexPages = dataPagesFetched;
8010 : }
8011 :
8012 : /*
8013 : * BRIN has search behavior completely different from other index types
8014 : */
8015 : void
8016 10730 : brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
8017 : Cost *indexStartupCost, Cost *indexTotalCost,
8018 : Selectivity *indexSelectivity, double *indexCorrelation,
8019 : double *indexPages)
8020 : {
8021 10730 : IndexOptInfo *index = path->indexinfo;
8022 10730 : List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
8023 10730 : double numPages = index->pages;
8024 10730 : RelOptInfo *baserel = index->rel;
8025 10730 : RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
8026 : Cost spc_seq_page_cost;
8027 : Cost spc_random_page_cost;
8028 : double qual_arg_cost;
8029 : double qualSelectivity;
8030 : BrinStatsData statsData;
8031 : double indexRanges;
8032 : double minimalRanges;
8033 : double estimatedRanges;
8034 : double selec;
8035 : Relation indexRel;
8036 : ListCell *l;
8037 : VariableStatData vardata;
8038 :
8039 : Assert(rte->rtekind == RTE_RELATION);
8040 :
8041 : /* fetch estimated page cost for the tablespace containing the index */
8042 10730 : get_tablespace_page_costs(index->reltablespace,
8043 : &spc_random_page_cost,
8044 : &spc_seq_page_cost);
8045 :
8046 : /*
8047 : * Obtain some data from the index itself, if possible. Otherwise invent
8048 : * some plausible internal statistics based on the relation page count.
8049 : */
8050 10730 : if (!index->hypothetical)
8051 : {
8052 : /*
8053 : * A lock should have already been obtained on the index in plancat.c.
8054 : */
8055 10730 : indexRel = index_open(index->indexoid, NoLock);
8056 10730 : brinGetStats(indexRel, &statsData);
8057 10730 : index_close(indexRel, NoLock);
8058 :
8059 : /* work out the actual number of ranges in the index */
8060 10730 : indexRanges = Max(ceil((double) baserel->pages /
8061 : statsData.pagesPerRange), 1.0);
8062 : }
8063 : else
8064 : {
8065 : /*
8066 : * Assume default number of pages per range, and estimate the number
8067 : * of ranges based on that.
8068 : */
8069 0 : indexRanges = Max(ceil((double) baserel->pages /
8070 : BRIN_DEFAULT_PAGES_PER_RANGE), 1.0);
8071 :
8072 0 : statsData.pagesPerRange = BRIN_DEFAULT_PAGES_PER_RANGE;
8073 0 : statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
8074 : }
8075 :
8076 : /*
8077 : * Compute index correlation
8078 : *
8079 : * Because we can use all index quals equally when scanning, we can use
8080 : * the largest correlation (in absolute value) among columns used by the
8081 : * query. Start at zero, the worst possible case. If we cannot find any
8082 : * correlation statistics, we will keep it as 0.
8083 : */
8084 10730 : *indexCorrelation = 0;
8085 :
8086 21462 : foreach(l, path->indexclauses)
8087 : {
8088 10732 : IndexClause *iclause = lfirst_node(IndexClause, l);
8089 10732 : AttrNumber attnum = index->indexkeys[iclause->indexcol];
8090 :
8091 : /* attempt to lookup stats in relation for this index column */
8092 10732 : if (attnum != 0)
8093 : {
8094 : /* Simple variable -- look to stats for the underlying table */
8095 10732 : if (get_relation_stats_hook &&
8096 0 : (*get_relation_stats_hook) (root, rte, attnum, &vardata))
8097 : {
8098 : /*
8099 : * The hook took control of acquiring a stats tuple. If it
8100 : * did supply a tuple, it'd better have supplied a freefunc.
8101 : */
8102 0 : if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
8103 0 : elog(ERROR,
8104 : "no function provided to release variable stats with");
8105 : }
8106 : else
8107 : {
8108 10732 : vardata.statsTuple =
8109 10732 : SearchSysCache3(STATRELATTINH,
8110 : ObjectIdGetDatum(rte->relid),
8111 : Int16GetDatum(attnum),
8112 : BoolGetDatum(false));
8113 10732 : vardata.freefunc = ReleaseSysCache;
8114 : }
8115 : }
8116 : else
8117 : {
8118 : /*
8119 : * Looks like we've found an expression column in the index. Let's
8120 : * see if there's any stats for it.
8121 : */
8122 :
8123 : /* get the attnum from the 0-based index. */
8124 0 : attnum = iclause->indexcol + 1;
8125 :
8126 0 : if (get_index_stats_hook &&
8127 0 : (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
8128 : {
8129 : /*
8130 : * The hook took control of acquiring a stats tuple. If it
8131 : * did supply a tuple, it'd better have supplied a freefunc.
8132 : */
8133 0 : if (HeapTupleIsValid(vardata.statsTuple) &&
8134 0 : !vardata.freefunc)
8135 0 : elog(ERROR, "no function provided to release variable stats with");
8136 : }
8137 : else
8138 : {
8139 0 : vardata.statsTuple = SearchSysCache3(STATRELATTINH,
8140 : ObjectIdGetDatum(index->indexoid),
8141 : Int16GetDatum(attnum),
8142 : BoolGetDatum(false));
8143 0 : vardata.freefunc = ReleaseSysCache;
8144 : }
8145 : }
8146 :
8147 10732 : if (HeapTupleIsValid(vardata.statsTuple))
8148 : {
8149 : AttStatsSlot sslot;
8150 :
8151 36 : if (get_attstatsslot(&sslot, vardata.statsTuple,
8152 : STATISTIC_KIND_CORRELATION, InvalidOid,
8153 : ATTSTATSSLOT_NUMBERS))
8154 : {
8155 36 : double varCorrelation = 0.0;
8156 :
8157 36 : if (sslot.nnumbers > 0)
8158 36 : varCorrelation = fabs(sslot.numbers[0]);
8159 :
8160 36 : if (varCorrelation > *indexCorrelation)
8161 36 : *indexCorrelation = varCorrelation;
8162 :
8163 36 : free_attstatsslot(&sslot);
8164 : }
8165 : }
8166 :
8167 10732 : ReleaseVariableStats(vardata);
8168 : }
8169 :
8170 10730 : qualSelectivity = clauselist_selectivity(root, indexQuals,
8171 10730 : baserel->relid,
8172 : JOIN_INNER, NULL);
8173 :
8174 : /*
8175 : * Now calculate the minimum possible ranges we could match with if all of
8176 : * the rows were in the perfect order in the table's heap.
8177 : */
8178 10730 : minimalRanges = ceil(indexRanges * qualSelectivity);
8179 :
8180 : /*
8181 : * Now estimate the number of ranges that we'll touch by using the
8182 : * indexCorrelation from the stats. Careful not to divide by zero (note
8183 : * we're using the absolute value of the correlation).
8184 : */
8185 10730 : if (*indexCorrelation < 1.0e-10)
8186 10694 : estimatedRanges = indexRanges;
8187 : else
8188 36 : estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8189 :
8190 : /* we expect to visit this portion of the table */
8191 10730 : selec = estimatedRanges / indexRanges;
8192 :
8193 10730 : CLAMP_PROBABILITY(selec);
8194 :
8195 10730 : *indexSelectivity = selec;
8196 :
8197 : /*
8198 : * Compute the index qual costs, much as in genericcostestimate, to add to
8199 : * the index costs. We can disregard indexorderbys, since BRIN doesn't
8200 : * support those.
8201 : */
8202 10730 : qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
8203 :
8204 : /*
8205 : * Compute the startup cost as the cost to read the whole revmap
8206 : * sequentially, including the cost to execute the index quals.
8207 : */
8208 10730 : *indexStartupCost =
8209 10730 : spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8210 10730 : *indexStartupCost += qual_arg_cost;
8211 :
8212 : /*
8213 : * To read a BRIN index there might be a bit of back and forth over
8214 : * regular pages, as revmap might point to them out of sequential order;
8215 : * calculate the total cost as reading the whole index in random order.
8216 : */
8217 10730 : *indexTotalCost = *indexStartupCost +
8218 10730 : spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8219 :
8220 : /*
8221 : * Charge a small amount per range tuple which we expect to match to. This
8222 : * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8223 : * will set a bit for each page in the range when we find a matching
8224 : * range, so we must multiply the charge by the number of pages in the
8225 : * range.
8226 : */
8227 10730 : *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8228 10730 : statsData.pagesPerRange;
8229 :
8230 10730 : *indexPages = index->pages;
8231 10730 : }
|