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 560520 : eqsel(PG_FUNCTION_ARGS)
229 : {
230 560520 : PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
231 : }
232 :
233 : /*
234 : * Common code for eqsel() and neqsel()
235 : */
236 : static double
237 607574 : eqsel_internal(PG_FUNCTION_ARGS, bool negate)
238 : {
239 607574 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
240 607574 : Oid operator = PG_GETARG_OID(1);
241 607574 : List *args = (List *) PG_GETARG_POINTER(2);
242 607574 : int varRelid = PG_GETARG_INT32(3);
243 607574 : 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 607574 : if (negate)
254 : {
255 47054 : operator = get_negator(operator);
256 47054 : 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 607574 : if (!get_restriction_variable(root, args, varRelid,
268 : &vardata, &other, &varonleft))
269 3996 : 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 603578 : if (IsA(other, Const))
277 266312 : selec = var_eq_const(&vardata, operator, collation,
278 266312 : ((Const *) other)->constvalue,
279 266312 : ((Const *) other)->constisnull,
280 : varonleft, negate);
281 : else
282 337266 : selec = var_eq_non_const(&vardata, operator, collation, other,
283 : varonleft, negate);
284 :
285 603578 : ReleaseVariableStats(vardata);
286 :
287 603578 : 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 308950 : var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
297 : Datum constval, bool constisnull,
298 : bool varonleft, bool negate)
299 : {
300 : double selec;
301 308950 : 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 308950 : if (constisnull)
310 344 : 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 308606 : if (HeapTupleIsValid(vardata->statsTuple))
317 : {
318 : Form_pg_statistic stats;
319 :
320 225682 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
321 225682 : nullfrac = stats->stanullfrac;
322 : }
323 :
324 : /*
325 : * If we matched the var to a unique index or DISTINCT clause, assume
326 : * there is exactly one match regardless of anything else. (This is
327 : * slightly bogus, since the index or clause's equality operator might be
328 : * different from ours, but it's much more likely to be right than
329 : * ignoring the information.)
330 : */
331 308606 : if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
332 : {
333 77436 : selec = 1.0 / vardata->rel->tuples;
334 : }
335 395820 : else if (HeapTupleIsValid(vardata->statsTuple) &&
336 164650 : statistic_proc_security_check(vardata,
337 164650 : (opfuncoid = get_opcode(oproid))))
338 164650 : {
339 : AttStatsSlot sslot;
340 164650 : 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 164650 : if (get_attstatsslot(&sslot, vardata->statsTuple,
351 : STATISTIC_KIND_MCV, InvalidOid,
352 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
353 : {
354 151164 : LOCAL_FCINFO(fcinfo, 2);
355 : FmgrInfo eqproc;
356 :
357 151164 : 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 151164 : InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
366 : NULL, NULL);
367 151164 : fcinfo->args[0].isnull = false;
368 151164 : fcinfo->args[1].isnull = false;
369 : /* be careful to apply operator right way 'round */
370 151164 : if (varonleft)
371 151132 : fcinfo->args[1].value = constval;
372 : else
373 32 : fcinfo->args[0].value = constval;
374 :
375 2512924 : for (i = 0; i < sslot.nvalues; i++)
376 : {
377 : Datum fresult;
378 :
379 2436416 : if (varonleft)
380 2436360 : fcinfo->args[0].value = sslot.values[i];
381 : else
382 56 : fcinfo->args[1].value = sslot.values[i];
383 2436416 : fcinfo->isnull = false;
384 2436416 : fresult = FunctionCallInvoke(fcinfo);
385 2436416 : if (!fcinfo->isnull && DatumGetBool(fresult))
386 : {
387 74656 : match = true;
388 74656 : break;
389 : }
390 : }
391 : }
392 : else
393 : {
394 : /* no most-common-value info available */
395 13486 : i = 0; /* keep compiler quiet */
396 : }
397 :
398 164650 : 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 74656 : 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 89994 : double sumcommon = 0.0;
414 : double otherdistinct;
415 :
416 2181162 : for (i = 0; i < sslot.nnumbers; i++)
417 2091168 : sumcommon += sslot.numbers[i];
418 89994 : selec = 1.0 - sumcommon - nullfrac;
419 89994 : 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 89994 : otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
427 89994 : sslot.nnumbers;
428 89994 : if (otherdistinct > 1)
429 39964 : 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 89994 : if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
436 0 : selec = sslot.numbers[sslot.nnumbers - 1];
437 : }
438 :
439 164650 : 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 66520 : selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
449 : }
450 :
451 : /* now adjust if we wanted <> rather than = */
452 308606 : if (negate)
453 39498 : selec = 1.0 - selec - nullfrac;
454 :
455 : /* result should be in range, but make sure... */
456 308606 : CLAMP_PROBABILITY(selec);
457 :
458 308606 : 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 337266 : var_eq_non_const(VariableStatData *vardata, Oid oproid, Oid collation,
468 : Node *other,
469 : bool varonleft, bool negate)
470 : {
471 : double selec;
472 337266 : double nullfrac = 0.0;
473 : bool isdefault;
474 :
475 : /*
476 : * Grab the nullfrac for use below.
477 : */
478 337266 : if (HeapTupleIsValid(vardata->statsTuple))
479 : {
480 : Form_pg_statistic stats;
481 :
482 242634 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
483 242634 : nullfrac = stats->stanullfrac;
484 : }
485 :
486 : /*
487 : * If we matched the var to a unique index or DISTINCT clause, assume
488 : * there is exactly one match regardless of anything else. (This is
489 : * slightly bogus, since the index or clause's equality operator might be
490 : * different from ours, but it's much more likely to be right than
491 : * ignoring the information.)
492 : */
493 337266 : if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
494 : {
495 136450 : selec = 1.0 / vardata->rel->tuples;
496 : }
497 200816 : 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 119866 : selec = 1.0 - nullfrac;
513 119866 : ndistinct = get_variable_numdistinct(vardata, &isdefault);
514 119866 : if (ndistinct > 1)
515 115130 : selec /= ndistinct;
516 :
517 : /*
518 : * Cross-check: selectivity should never be estimated as more than the
519 : * most common value's.
520 : */
521 119866 : if (get_attstatsslot(&sslot, vardata->statsTuple,
522 : STATISTIC_KIND_MCV, InvalidOid,
523 : ATTSTATSSLOT_NUMBERS))
524 : {
525 101156 : if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
526 666 : selec = sslot.numbers[0];
527 101156 : 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 80950 : selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
538 : }
539 :
540 : /* now adjust if we wanted <> rather than = */
541 337266 : if (negate)
542 5824 : selec = 1.0 - selec - nullfrac;
543 :
544 : /* result should be in range, but make sure... */
545 337266 : CLAMP_PROBABILITY(selec);
546 :
547 337266 : 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 47054 : neqsel(PG_FUNCTION_ARGS)
559 : {
560 47054 : 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 278776 : 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 278776 : 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 19946 : if (vardata->var && IsA(vardata->var, Var) &&
600 15212 : ((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 54 : 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 19732 : return DEFAULT_INEQ_SEL;
671 : }
672 258830 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
673 :
674 258830 : 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 258830 : 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 258830 : 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 258830 : selec = 1.0 - stats->stanullfrac - sumcommon;
700 :
701 258830 : if (hist_selec >= 0.0)
702 191062 : 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 67768 : selec *= 0.5;
710 : }
711 :
712 258830 : selec += mcv_selec;
713 :
714 : /* result should be in range, but make sure... */
715 258830 : CLAMP_PROBABILITY(selec);
716 :
717 258830 : 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 263896 : 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 263896 : mcv_selec = 0.0;
743 263896 : sumcommon = 0.0;
744 :
745 525452 : if (HeapTupleIsValid(vardata->statsTuple) &&
746 523058 : statistic_proc_security_check(vardata, opproc->fn_oid) &&
747 261502 : get_attstatsslot(&sslot, vardata->statsTuple,
748 : STATISTIC_KIND_MCV, InvalidOid,
749 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
750 : {
751 122874 : 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 122874 : InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
761 : NULL, NULL);
762 122874 : fcinfo->args[0].isnull = false;
763 122874 : fcinfo->args[1].isnull = false;
764 : /* be careful to apply operator right way 'round */
765 122874 : if (varonleft)
766 122874 : fcinfo->args[1].value = constval;
767 : else
768 0 : fcinfo->args[0].value = constval;
769 :
770 3645386 : for (i = 0; i < sslot.nvalues; i++)
771 : {
772 : Datum fresult;
773 :
774 3522512 : if (varonleft)
775 3522512 : fcinfo->args[0].value = sslot.values[i];
776 : else
777 0 : fcinfo->args[1].value = sslot.values[i];
778 3522512 : fcinfo->isnull = false;
779 3522512 : fresult = FunctionCallInvoke(fcinfo);
780 3522512 : if (!fcinfo->isnull && DatumGetBool(fresult))
781 1260774 : mcv_selec += sslot.numbers[i];
782 3522512 : sumcommon += sslot.numbers[i];
783 : }
784 122874 : free_attstatsslot(&sslot);
785 : }
786 :
787 263896 : *sumcommonp = sumcommon;
788 263896 : 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 5066 : 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 7792 : if (HeapTupleIsValid(vardata->statsTuple) &&
838 5446 : statistic_proc_security_check(vardata, opproc->fn_oid) &&
839 2720 : get_attstatsslot(&sslot, vardata->statsTuple,
840 : STATISTIC_KIND_HISTOGRAM, InvalidOid,
841 : ATTSTATSSLOT_VALUES))
842 : {
843 2626 : *hist_size = sslot.nvalues;
844 2626 : if (sslot.nvalues >= min_hist_size)
845 : {
846 1634 : LOCAL_FCINFO(fcinfo, 2);
847 1634 : 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 1634 : InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
859 : NULL, NULL);
860 1634 : fcinfo->args[0].isnull = false;
861 1634 : fcinfo->args[1].isnull = false;
862 : /* be careful to apply operator right way 'round */
863 1634 : if (varonleft)
864 1634 : fcinfo->args[1].value = constval;
865 : else
866 0 : fcinfo->args[0].value = constval;
867 :
868 142592 : for (i = n_skip; i < sslot.nvalues - n_skip; i++)
869 : {
870 : Datum fresult;
871 :
872 140958 : if (varonleft)
873 140958 : fcinfo->args[0].value = sslot.values[i];
874 : else
875 0 : fcinfo->args[1].value = sslot.values[i];
876 140958 : fcinfo->isnull = false;
877 140958 : fresult = FunctionCallInvoke(fcinfo);
878 140958 : if (!fcinfo->isnull && DatumGetBool(fresult))
879 7730 : nmatch++;
880 : }
881 1634 : result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
882 : }
883 : else
884 992 : result = -1;
885 2626 : free_attstatsslot(&sslot);
886 : }
887 : else
888 : {
889 2440 : *hist_size = 0;
890 2440 : result = -1;
891 : }
892 :
893 5066 : 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 261888 : 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 261888 : 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 523144 : if (HeapTupleIsValid(vardata->statsTuple) &&
1066 522464 : statistic_proc_security_check(vardata, opproc->fn_oid) &&
1067 261208 : get_attstatsslot(&sslot, vardata->statsTuple,
1068 : STATISTIC_KIND_HISTOGRAM, InvalidOid,
1069 : ATTSTATSSLOT_VALUES))
1070 : {
1071 193486 : if (sslot.nvalues > 1 &&
1072 386896 : sslot.stacoll == collation &&
1073 193410 : comparison_ops_are_compatible(sslot.staop, opoid))
1074 193302 : {
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 193302 : int lobound = 0; /* first possible slot to search */
1095 193302 : int hibound = sslot.nvalues; /* last+1 slot to search */
1096 193302 : 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 193302 : if (sslot.nvalues == 2)
1105 2306 : have_end = get_actual_variable_range(root,
1106 : vardata,
1107 : sslot.staop,
1108 : collation,
1109 : &sslot.values[0],
1110 2306 : &sslot.values[1]);
1111 :
1112 1260148 : while (lobound < hibound)
1113 : {
1114 1066846 : 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 1066846 : if (probe == 0 && sslot.nvalues > 2)
1123 98542 : have_end = get_actual_variable_range(root,
1124 : vardata,
1125 : sslot.staop,
1126 : collation,
1127 : &sslot.values[0],
1128 : NULL);
1129 968304 : else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
1130 63214 : have_end = get_actual_variable_range(root,
1131 : vardata,
1132 : sslot.staop,
1133 : collation,
1134 : NULL,
1135 63214 : &sslot.values[probe]);
1136 :
1137 1066846 : ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
1138 : collation,
1139 1066846 : sslot.values[probe],
1140 : constval));
1141 1066846 : if (isgt)
1142 58272 : ltcmp = !ltcmp;
1143 1066846 : if (ltcmp)
1144 399602 : lobound = probe + 1;
1145 : else
1146 667244 : hibound = probe;
1147 : }
1148 :
1149 193302 : 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 84690 : histfrac = 0.0;
1160 : }
1161 108612 : else if (lobound >= sslot.nvalues)
1162 : {
1163 : /*
1164 : * Inverse case: constant is above upper histogram boundary.
1165 : */
1166 28062 : histfrac = 1.0;
1167 : }
1168 : else
1169 : {
1170 : /* We have values[i-1] <= constant <= values[i]. */
1171 80550 : int i = lobound;
1172 80550 : 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 80550 : if (i == 1 || isgt == iseq)
1195 : {
1196 : double otherdistinct;
1197 : bool isdefault;
1198 : AttStatsSlot mcvslot;
1199 :
1200 : /* Get estimated number of distinct values */
1201 32558 : otherdistinct = get_variable_numdistinct(vardata,
1202 : &isdefault);
1203 :
1204 : /* Subtract off the number of known MCVs */
1205 32558 : if (get_attstatsslot(&mcvslot, vardata->statsTuple,
1206 : STATISTIC_KIND_MCV, InvalidOid,
1207 : ATTSTATSSLOT_NUMBERS))
1208 : {
1209 3290 : otherdistinct -= mcvslot.nnumbers;
1210 3290 : free_attstatsslot(&mcvslot);
1211 : }
1212 :
1213 : /* If result doesn't seem sane, leave eq_selec at 0 */
1214 32558 : if (otherdistinct > 1)
1215 32516 : 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 80550 : if (convert_to_scalar(constval, consttype, collation,
1224 : &val,
1225 80550 : sslot.values[i - 1], sslot.values[i],
1226 : vardata->vartype,
1227 : &low, &high))
1228 : {
1229 80550 : if (high <= low)
1230 : {
1231 : /* cope if bin boundaries appear identical */
1232 0 : binfrac = 0.5;
1233 : }
1234 80550 : else if (val <= low)
1235 20010 : binfrac = 0.0;
1236 60540 : else if (val >= high)
1237 3940 : binfrac = 1.0;
1238 : else
1239 : {
1240 56600 : 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 56600 : if (isnan(binfrac) ||
1249 56600 : 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 80550 : histfrac = (double) (i - 1) + binfrac;
1272 80550 : 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 80550 : if (i == 1)
1307 15298 : 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 80550 : if (isgt == iseq)
1315 23636 : 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 193302 : 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 193302 : if (have_end)
1334 107338 : CLAMP_PROBABILITY(hist_selec);
1335 : else
1336 : {
1337 85964 : double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1338 :
1339 85964 : if (hist_selec < cutoff)
1340 31690 : hist_selec = cutoff;
1341 54274 : else if (hist_selec > 1.0 - cutoff)
1342 20176 : 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 962108 : for (int i = 0; i < sslot.nvalues; i++)
1363 : {
1364 : Datum fresult;
1365 :
1366 961924 : fcinfo->args[0].value = sslot.values[i];
1367 961924 : fcinfo->isnull = false;
1368 961924 : fresult = FunctionCallInvoke(fcinfo);
1369 961924 : if (!fcinfo->isnull && DatumGetBool(fresult))
1370 1940 : 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 193486 : free_attstatsslot(&sslot);
1391 : }
1392 :
1393 261888 : return hist_selec;
1394 : }
1395 :
1396 : /*
1397 : * Common wrapper function for the selectivity estimators that simply
1398 : * invoke scalarineqsel().
1399 : */
1400 : static Datum
1401 40116 : scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
1402 : {
1403 40116 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1404 40116 : Oid operator = PG_GETARG_OID(1);
1405 40116 : List *args = (List *) PG_GETARG_POINTER(2);
1406 40116 : int varRelid = PG_GETARG_INT32(3);
1407 40116 : 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 40116 : 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 39584 : 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 36898 : if (((Const *) other)->constisnull)
1437 : {
1438 66 : ReleaseVariableStats(vardata);
1439 66 : PG_RETURN_FLOAT8(0.0);
1440 : }
1441 36832 : constval = ((Const *) other)->constvalue;
1442 36832 : consttype = ((Const *) other)->consttype;
1443 :
1444 : /*
1445 : * Force the var to be on the left to simplify logic in scalarineqsel.
1446 : */
1447 36832 : 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 36832 : selec = scalarineqsel(root, operator, isgt, iseq, collation,
1461 : &vardata, constval, consttype);
1462 :
1463 36832 : ReleaseVariableStats(vardata);
1464 :
1465 36832 : PG_RETURN_FLOAT8((float8) selec);
1466 : }
1467 :
1468 : /*
1469 : * scalarltsel - Selectivity of "<" for scalars.
1470 : */
1471 : Datum
1472 13966 : scalarltsel(PG_FUNCTION_ARGS)
1473 : {
1474 13966 : 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 14450 : scalargtsel(PG_FUNCTION_ARGS)
1491 : {
1492 14450 : return scalarineqsel_wrapper(fcinfo, true, false);
1493 : }
1494 :
1495 : /*
1496 : * scalargesel - Selectivity of ">=" for scalars.
1497 : */
1498 : Datum
1499 7296 : scalargesel(PG_FUNCTION_ARGS)
1500 : {
1501 7296 : 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 42478 : boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
1514 : {
1515 : VariableStatData vardata;
1516 : double selec;
1517 :
1518 42478 : examine_variable(root, arg, varRelid, &vardata);
1519 42478 : 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 35120 : 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 7358 : selec = 0.5;
1532 : }
1533 42478 : ReleaseVariableStats(vardata);
1534 42478 : 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 15750 : nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1700 : int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1701 : {
1702 : VariableStatData vardata;
1703 : double selec;
1704 :
1705 15750 : examine_variable(root, arg, varRelid, &vardata);
1706 :
1707 15750 : if (HeapTupleIsValid(vardata.statsTuple))
1708 : {
1709 : Form_pg_statistic stats;
1710 : double freq_null;
1711 :
1712 8806 : stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1713 8806 : freq_null = stats->stanullfrac;
1714 :
1715 8806 : switch (nulltesttype)
1716 : {
1717 6754 : case IS_NULL:
1718 :
1719 : /*
1720 : * Use freq_null directly.
1721 : */
1722 6754 : selec = freq_null;
1723 6754 : break;
1724 2052 : case IS_NOT_NULL:
1725 :
1726 : /*
1727 : * Select not unknown (not null) values. Calculate from
1728 : * freq_null.
1729 : */
1730 2052 : selec = 1.0 - freq_null;
1731 2052 : break;
1732 0 : default:
1733 0 : elog(ERROR, "unrecognized nulltesttype: %d",
1734 : (int) nulltesttype);
1735 : return (Selectivity) 0; /* keep compiler quiet */
1736 : }
1737 : }
1738 6944 : else if (vardata.var && IsA(vardata.var, Var) &&
1739 6374 : ((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 6884 : switch (nulltesttype)
1753 : {
1754 2062 : case IS_NULL:
1755 2062 : selec = DEFAULT_UNK_SEL;
1756 2062 : break;
1757 4822 : case IS_NOT_NULL:
1758 4822 : selec = DEFAULT_NOT_UNK_SEL;
1759 4822 : 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 15750 : ReleaseVariableStats(vardata);
1768 :
1769 : /* result should be in range, but make sure... */
1770 15750 : CLAMP_PROBABILITY(selec);
1771 :
1772 15750 : 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 118208 : strip_array_coercion(Node *node)
1785 : {
1786 : for (;;)
1787 : {
1788 118208 : if (node && IsA(node, ArrayCoerceExpr))
1789 36 : {
1790 2800 : 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 2800 : 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 115408 : 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 118172 : return node;
1811 : }
1812 :
1813 : /*
1814 : * scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1815 : */
1816 : Selectivity
1817 20930 : scalararraysel(PlannerInfo *root,
1818 : ScalarArrayOpExpr *clause,
1819 : bool is_join_clause,
1820 : int varRelid,
1821 : JoinType jointype,
1822 : SpecialJoinInfo *sjinfo)
1823 : {
1824 20930 : Oid operator = clause->opno;
1825 20930 : bool useOr = clause->useOr;
1826 20930 : bool isEquality = false;
1827 20930 : 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 20930 : leftop = (Node *) linitial(clause->args);
1841 20930 : rightop = (Node *) lsecond(clause->args);
1842 :
1843 : /* aggressively reduce both sides to constants */
1844 20930 : leftop = estimate_expression_value(root, leftop);
1845 20930 : rightop = estimate_expression_value(root, rightop);
1846 :
1847 : /* get nominal (after relabeling) element type of rightop */
1848 20930 : nominal_element_type = get_base_element_type(exprType(rightop));
1849 20930 : if (!OidIsValid(nominal_element_type))
1850 0 : return (Selectivity) 0.5; /* probably shouldn't happen */
1851 : /* get nominal collation, too, for generating constants */
1852 20930 : nominal_element_collation = exprCollation(rightop);
1853 :
1854 : /* look through any binary-compatible relabeling of rightop */
1855 20930 : 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 20930 : typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1862 20930 : if (OidIsValid(typentry->eq_opr))
1863 : {
1864 20930 : if (operator == typentry->eq_opr)
1865 15756 : isEquality = true;
1866 5174 : else if (get_negator(operator) == typentry->eq_opr)
1867 4628 : 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 20930 : if ((isEquality || isInequality) && !is_join_clause)
1877 : {
1878 20384 : s1 = scalararraysel_containment(root, leftop, rightop,
1879 : nominal_element_type,
1880 : isEquality, useOr, varRelid);
1881 20384 : 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 20812 : if (is_join_clause)
1890 0 : oprsel = get_oprjoin(operator);
1891 : else
1892 20812 : oprsel = get_oprrest(operator);
1893 20812 : if (!oprsel)
1894 0 : return (Selectivity) 0.5;
1895 20812 : 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 20812 : if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1906 15820 : isEquality = true;
1907 4992 : else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1908 4518 : 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 20812 : if (rightop && IsA(rightop, Const))
1923 17086 : {
1924 17104 : Datum arraydatum = ((Const *) rightop)->constvalue;
1925 17104 : 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 17104 : if (arrayisnull) /* qual can't succeed if null array */
1936 18 : return (Selectivity) 0.0;
1937 17086 : arrayval = DatumGetArrayTypeP(arraydatum);
1938 17086 : get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1939 : &elmlen, &elmbyval, &elmalign);
1940 17086 : 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 17086 : s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1960 :
1961 65922 : for (i = 0; i < num_elems; i++)
1962 : {
1963 : List *args;
1964 : Selectivity s2;
1965 :
1966 48836 : 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 48836 : 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 48836 : s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1984 : clause->inputcollid,
1985 : PointerGetDatum(root),
1986 : ObjectIdGetDatum(operator),
1987 : PointerGetDatum(args),
1988 : Int32GetDatum(varRelid)));
1989 :
1990 48836 : if (useOr)
1991 : {
1992 37634 : s1 = s1 + s2 - s1 * s2;
1993 37634 : if (isEquality)
1994 36602 : s1disjoint += s2;
1995 : }
1996 : else
1997 : {
1998 11202 : s1 = s1 * s2;
1999 11202 : if (isInequality)
2000 10890 : s1disjoint += s2 - 1.0;
2001 : }
2002 : }
2003 :
2004 : /* accept disjoint-probability estimate if in range */
2005 17086 : if ((useOr ? isEquality : isInequality) &&
2006 16450 : s1disjoint >= 0.0 && s1disjoint <= 1.0)
2007 16420 : s1 = s1disjoint;
2008 : }
2009 3708 : else if (rightop && IsA(rightop, ArrayExpr) &&
2010 182 : !((ArrayExpr *) rightop)->multidims)
2011 182 : {
2012 182 : ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2013 : int16 elmlen;
2014 : bool elmbyval;
2015 : ListCell *l;
2016 :
2017 182 : 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 182 : s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2028 :
2029 680 : foreach(l, arrayexpr->elements)
2030 : {
2031 498 : 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 498 : args = list_make2(leftop, elem);
2041 498 : 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 498 : s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2051 : clause->inputcollid,
2052 : PointerGetDatum(root),
2053 : ObjectIdGetDatum(operator),
2054 : PointerGetDatum(args),
2055 : Int32GetDatum(varRelid)));
2056 :
2057 498 : if (useOr)
2058 : {
2059 498 : s1 = s1 + s2 - s1 * s2;
2060 498 : if (isEquality)
2061 498 : 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 182 : if ((useOr ? isEquality : isInequality) &&
2073 182 : s1disjoint >= 0.0 && s1disjoint <= 1.0)
2074 182 : 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 3526 : dummyexpr = makeNode(CaseTestExpr);
2089 3526 : dummyexpr->typeId = nominal_element_type;
2090 3526 : dummyexpr->typeMod = -1;
2091 3526 : dummyexpr->collation = clause->inputcollid;
2092 3526 : args = list_make2(leftop, dummyexpr);
2093 3526 : 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 3526 : s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2103 : clause->inputcollid,
2104 : PointerGetDatum(root),
2105 : ObjectIdGetDatum(operator),
2106 : PointerGetDatum(args),
2107 : Int32GetDatum(varRelid)));
2108 3526 : 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 38786 : for (i = 0; i < 10; i++)
2116 : {
2117 35260 : if (useOr)
2118 35260 : 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 20794 : CLAMP_PROBABILITY(s1);
2126 :
2127 20794 : 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 97242 : estimate_array_length(PlannerInfo *root, Node *arrayexpr)
2141 : {
2142 : /* look through any binary-compatible relabeling of arrayexpr */
2143 97242 : arrayexpr = strip_array_coercion(arrayexpr);
2144 :
2145 97242 : if (arrayexpr && IsA(arrayexpr, Const))
2146 : {
2147 44016 : Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2148 44016 : bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2149 : ArrayType *arrayval;
2150 :
2151 44016 : if (arrayisnull)
2152 42 : return 0;
2153 43974 : arrayval = DatumGetArrayTypeP(arraydatum);
2154 43974 : return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2155 : }
2156 53226 : else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2157 490 : !((ArrayExpr *) arrayexpr)->multidims)
2158 : {
2159 490 : return list_length(((ArrayExpr *) arrayexpr)->elements);
2160 : }
2161 52736 : else if (arrayexpr && root)
2162 : {
2163 : /* See if we can find any statistics about it */
2164 : VariableStatData vardata;
2165 : AttStatsSlot sslot;
2166 52736 : double nelem = 0;
2167 :
2168 52736 : examine_variable(root, arrayexpr, 0, &vardata);
2169 52736 : 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 7844 : if (get_attstatsslot(&sslot, vardata.statsTuple,
2178 : STATISTIC_KIND_DECHIST, InvalidOid,
2179 : ATTSTATSSLOT_NUMBERS))
2180 : {
2181 7730 : if (sslot.nnumbers > 0)
2182 7730 : nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2183 7730 : free_attstatsslot(&sslot);
2184 : }
2185 : }
2186 52736 : ReleaseVariableStats(vardata);
2187 :
2188 52736 : if (nelem > 0)
2189 7730 : return nelem;
2190 : }
2191 :
2192 : /* Else use a default guess --- this should match scalararraysel */
2193 45006 : 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 197580 : eqjoinsel(PG_FUNCTION_ARGS)
2274 : {
2275 197580 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2276 197580 : Oid operator = PG_GETARG_OID(1);
2277 197580 : List *args = (List *) PG_GETARG_POINTER(2);
2278 :
2279 : #ifdef NOT_USED
2280 : JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2281 : #endif
2282 197580 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2283 197580 : 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 197580 : Form_pg_statistic stats1 = NULL;
2296 197580 : Form_pg_statistic stats2 = NULL;
2297 197580 : bool have_mcvs1 = false;
2298 197580 : bool have_mcvs2 = false;
2299 : bool get_mcv_stats;
2300 : bool join_is_reversed;
2301 : RelOptInfo *inner_rel;
2302 :
2303 197580 : get_join_variables(root, args, sjinfo,
2304 : &vardata1, &vardata2, &join_is_reversed);
2305 :
2306 197580 : nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2307 197580 : nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2308 :
2309 197580 : opfuncoid = get_opcode(operator);
2310 :
2311 197580 : memset(&sslot1, 0, sizeof(sslot1));
2312 197580 : 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 553116 : get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
2319 282086 : HeapTupleIsValid(vardata2.statsTuple) &&
2320 124130 : get_attstatsslot(&sslot1, vardata1.statsTuple,
2321 : STATISTIC_KIND_MCV, InvalidOid,
2322 355536 : 0) &&
2323 48202 : get_attstatsslot(&sslot2, vardata2.statsTuple,
2324 : STATISTIC_KIND_MCV, InvalidOid,
2325 : 0));
2326 :
2327 197580 : if (HeapTupleIsValid(vardata1.statsTuple))
2328 : {
2329 : /* note we allow use of nullfrac regardless of security check */
2330 157956 : stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2331 170538 : if (get_mcv_stats &&
2332 12582 : statistic_proc_security_check(&vardata1, opfuncoid))
2333 12582 : have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2334 : STATISTIC_KIND_MCV, InvalidOid,
2335 : ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
2336 : }
2337 :
2338 197580 : if (HeapTupleIsValid(vardata2.statsTuple))
2339 : {
2340 : /* note we allow use of nullfrac regardless of security check */
2341 134532 : stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2342 147114 : if (get_mcv_stats &&
2343 12582 : statistic_proc_security_check(&vardata2, opfuncoid))
2344 12582 : 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 197580 : 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 197580 : switch (sjinfo->jointype)
2359 : {
2360 190482 : case JOIN_INNER:
2361 : case JOIN_LEFT:
2362 : case JOIN_FULL:
2363 190482 : selec = selec_inner;
2364 190482 : break;
2365 7098 : 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 7098 : inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2375 :
2376 7098 : if (!join_is_reversed)
2377 3432 : 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 3666 : Oid commop = get_commutator(operator);
2388 3666 : Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2389 :
2390 3666 : 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 7098 : selec = Min(selec, inner_rel->rows * selec_inner);
2411 7098 : 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 197580 : free_attstatsslot(&sslot1);
2421 197580 : free_attstatsslot(&sslot2);
2422 :
2423 197580 : ReleaseVariableStats(vardata1);
2424 197580 : ReleaseVariableStats(vardata2);
2425 :
2426 197580 : CLAMP_PROBABILITY(selec);
2427 :
2428 197580 : 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 197580 : 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 197580 : if (have_mcvs1 && have_mcvs2)
2449 12582 : {
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 12582 : LOCAL_FCINFO(fcinfo, 2);
2463 : FmgrInfo eqproc;
2464 : bool *hasmatch1;
2465 : bool *hasmatch2;
2466 12582 : double nullfrac1 = stats1->stanullfrac;
2467 12582 : 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 12582 : 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 12582 : InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2489 : NULL, NULL);
2490 12582 : fcinfo->args[0].isnull = false;
2491 12582 : fcinfo->args[1].isnull = false;
2492 :
2493 12582 : hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2494 12582 : 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 12582 : matchprodfreq = 0.0;
2503 12582 : nmatches = 0;
2504 525260 : for (i = 0; i < sslot1->nvalues; i++)
2505 : {
2506 : int j;
2507 :
2508 512678 : fcinfo->args[0].value = sslot1->values[i];
2509 :
2510 20039198 : for (j = 0; j < sslot2->nvalues; j++)
2511 : {
2512 : Datum fresult;
2513 :
2514 19702088 : if (hasmatch2[j])
2515 5324998 : continue;
2516 14377090 : fcinfo->args[1].value = sslot2->values[j];
2517 14377090 : fcinfo->isnull = false;
2518 14377090 : fresult = FunctionCallInvoke(fcinfo);
2519 14377090 : if (!fcinfo->isnull && DatumGetBool(fresult))
2520 : {
2521 175568 : hasmatch1[i] = hasmatch2[j] = true;
2522 175568 : matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2523 175568 : nmatches++;
2524 175568 : break;
2525 : }
2526 : }
2527 : }
2528 12582 : CLAMP_PROBABILITY(matchprodfreq);
2529 : /* Sum up frequencies of matched and unmatched MCVs */
2530 12582 : matchfreq1 = unmatchfreq1 = 0.0;
2531 525260 : for (i = 0; i < sslot1->nvalues; i++)
2532 : {
2533 512678 : if (hasmatch1[i])
2534 175568 : matchfreq1 += sslot1->numbers[i];
2535 : else
2536 337110 : unmatchfreq1 += sslot1->numbers[i];
2537 : }
2538 12582 : CLAMP_PROBABILITY(matchfreq1);
2539 12582 : CLAMP_PROBABILITY(unmatchfreq1);
2540 12582 : matchfreq2 = unmatchfreq2 = 0.0;
2541 357184 : for (i = 0; i < sslot2->nvalues; i++)
2542 : {
2543 344602 : if (hasmatch2[i])
2544 175568 : matchfreq2 += sslot2->numbers[i];
2545 : else
2546 169034 : unmatchfreq2 += sslot2->numbers[i];
2547 : }
2548 12582 : CLAMP_PROBABILITY(matchfreq2);
2549 12582 : CLAMP_PROBABILITY(unmatchfreq2);
2550 12582 : pfree(hasmatch1);
2551 12582 : pfree(hasmatch2);
2552 :
2553 : /*
2554 : * Compute total frequency of non-null values that are not in the MCV
2555 : * lists.
2556 : */
2557 12582 : otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2558 12582 : otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2559 12582 : CLAMP_PROBABILITY(otherfreq1);
2560 12582 : 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 12582 : totalsel1 = matchprodfreq;
2571 12582 : if (nd2 > sslot2->nvalues)
2572 5254 : totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2573 12582 : if (nd2 > nmatches)
2574 9656 : totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2575 9656 : (nd2 - nmatches);
2576 : /* Same estimate from the point of view of relation 2. */
2577 12582 : totalsel2 = matchprodfreq;
2578 12582 : if (nd1 > sslot1->nvalues)
2579 6164 : totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2580 12582 : if (nd1 > nmatches)
2581 8564 : totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2582 8564 : (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 12582 : 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 184998 : double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2615 184998 : double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2616 :
2617 184998 : selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2618 184998 : if (nd1 > nd2)
2619 94782 : selec /= nd1;
2620 : else
2621 90216 : selec /= nd2;
2622 : }
2623 :
2624 197580 : 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 7098 : 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 7098 : if (vardata2->rel)
2666 : {
2667 7092 : if (nd2 >= vardata2->rel->rows)
2668 : {
2669 5420 : nd2 = vardata2->rel->rows;
2670 5420 : isdefault2 = false;
2671 : }
2672 : }
2673 7098 : if (nd2 >= inner_rel->rows)
2674 : {
2675 5404 : nd2 = inner_rel->rows;
2676 5404 : isdefault2 = false;
2677 : }
2678 :
2679 7098 : if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2680 522 : {
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 522 : LOCAL_FCINFO(fcinfo, 2);
2690 : FmgrInfo eqproc;
2691 : bool *hasmatch1;
2692 : bool *hasmatch2;
2693 522 : 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 522 : clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2709 :
2710 522 : 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 522 : InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2719 : NULL, NULL);
2720 522 : fcinfo->args[0].isnull = false;
2721 522 : fcinfo->args[1].isnull = false;
2722 :
2723 522 : hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2724 522 : 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 522 : nmatches = 0;
2733 12448 : for (i = 0; i < sslot1->nvalues; i++)
2734 : {
2735 : int j;
2736 :
2737 11926 : fcinfo->args[0].value = sslot1->values[i];
2738 :
2739 497154 : for (j = 0; j < clamped_nvalues2; j++)
2740 : {
2741 : Datum fresult;
2742 :
2743 495404 : if (hasmatch2[j])
2744 381448 : continue;
2745 113956 : fcinfo->args[1].value = sslot2->values[j];
2746 113956 : fcinfo->isnull = false;
2747 113956 : fresult = FunctionCallInvoke(fcinfo);
2748 113956 : if (!fcinfo->isnull && DatumGetBool(fresult))
2749 : {
2750 10176 : hasmatch1[i] = hasmatch2[j] = true;
2751 10176 : nmatches++;
2752 10176 : break;
2753 : }
2754 : }
2755 : }
2756 : /* Sum up frequencies of matched MCVs */
2757 522 : matchfreq1 = 0.0;
2758 12448 : for (i = 0; i < sslot1->nvalues; i++)
2759 : {
2760 11926 : if (hasmatch1[i])
2761 10176 : matchfreq1 += sslot1->numbers[i];
2762 : }
2763 522 : CLAMP_PROBABILITY(matchfreq1);
2764 522 : pfree(hasmatch1);
2765 522 : 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 522 : if (!isdefault1 && !isdefault2)
2783 : {
2784 522 : nd1 -= nmatches;
2785 522 : nd2 -= nmatches;
2786 522 : if (nd1 <= nd2 || nd2 < 0)
2787 492 : uncertainfrac = 1.0;
2788 : else
2789 30 : uncertainfrac = nd2 / nd1;
2790 : }
2791 : else
2792 0 : uncertainfrac = 0.5;
2793 522 : uncertain = 1.0 - matchfreq1 - nullfrac1;
2794 522 : CLAMP_PROBABILITY(uncertain);
2795 522 : 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 6576 : double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2804 :
2805 6576 : if (!isdefault1 && !isdefault2)
2806 : {
2807 4658 : if (nd1 <= nd2 || nd2 < 0)
2808 2462 : selec = 1.0 - nullfrac1;
2809 : else
2810 2196 : selec = (nd2 / nd1) * (1.0 - nullfrac1);
2811 : }
2812 : else
2813 1918 : selec = 0.5 * (1.0 - nullfrac1);
2814 : }
2815 :
2816 7098 : return selec;
2817 : }
2818 :
2819 : /*
2820 : * neqjoinsel - Join selectivity of "!="
2821 : */
2822 : Datum
2823 3296 : neqjoinsel(PG_FUNCTION_ARGS)
2824 : {
2825 3296 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2826 3296 : Oid operator = PG_GETARG_OID(1);
2827 3296 : List *args = (List *) PG_GETARG_POINTER(2);
2828 3296 : JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2829 3296 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2830 3296 : Oid collation = PG_GET_COLLATION();
2831 : float8 result;
2832 :
2833 3296 : if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2834 1086 : {
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 1086 : get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
2857 1086 : statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
2858 1086 : if (HeapTupleIsValid(statsTuple))
2859 892 : nullfrac = ((Form_pg_statistic) GETSTRUCT(statsTuple))->stanullfrac;
2860 : else
2861 194 : nullfrac = 0.0;
2862 1086 : ReleaseVariableStats(leftvar);
2863 1086 : ReleaseVariableStats(rightvar);
2864 :
2865 1086 : 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 2210 : Oid eqop = get_negator(operator);
2874 :
2875 2210 : if (eqop)
2876 : {
2877 : result =
2878 2210 : 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 2210 : result = 1.0 - result;
2892 : }
2893 :
2894 3296 : 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 100360 : 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 100360 : *leftstart = *rightstart = 0.0;
2988 100360 : *leftend = *rightend = 1.0;
2989 :
2990 : /* Deconstruct the merge clause */
2991 100360 : if (!is_opclause(clause))
2992 0 : return; /* shouldn't happen */
2993 100360 : opno = ((OpExpr *) clause)->opno;
2994 100360 : collation = ((OpExpr *) clause)->inputcollid;
2995 100360 : left = get_leftop((Expr *) clause);
2996 100360 : right = get_rightop((Expr *) clause);
2997 100360 : if (!right)
2998 0 : return; /* shouldn't happen */
2999 :
3000 : /* Look for stats for the inputs */
3001 100360 : examine_variable(root, left, 0, &leftvar);
3002 100360 : examine_variable(root, right, 0, &rightvar);
3003 :
3004 : /* Extract the operator's declared left/right datatypes */
3005 100360 : 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 100360 : switch (strategy)
3019 : {
3020 100306 : case BTLessStrategyNumber:
3021 100306 : isgt = false;
3022 100306 : if (op_lefttype == op_righttype)
3023 : {
3024 : /* easy case */
3025 99006 : ltop = get_opfamily_member(opfamily,
3026 : op_lefttype, op_righttype,
3027 : BTLessStrategyNumber);
3028 99006 : leop = get_opfamily_member(opfamily,
3029 : op_lefttype, op_righttype,
3030 : BTLessEqualStrategyNumber);
3031 99006 : lsortop = ltop;
3032 99006 : rsortop = ltop;
3033 99006 : lstatop = lsortop;
3034 99006 : rstatop = rsortop;
3035 99006 : revltop = ltop;
3036 99006 : revleop = leop;
3037 : }
3038 : else
3039 : {
3040 1300 : ltop = get_opfamily_member(opfamily,
3041 : op_lefttype, op_righttype,
3042 : BTLessStrategyNumber);
3043 1300 : leop = get_opfamily_member(opfamily,
3044 : op_lefttype, op_righttype,
3045 : BTLessEqualStrategyNumber);
3046 1300 : lsortop = get_opfamily_member(opfamily,
3047 : op_lefttype, op_lefttype,
3048 : BTLessStrategyNumber);
3049 1300 : rsortop = get_opfamily_member(opfamily,
3050 : op_righttype, op_righttype,
3051 : BTLessStrategyNumber);
3052 1300 : lstatop = lsortop;
3053 1300 : rstatop = rsortop;
3054 1300 : revltop = get_opfamily_member(opfamily,
3055 : op_righttype, op_lefttype,
3056 : BTLessStrategyNumber);
3057 1300 : revleop = get_opfamily_member(opfamily,
3058 : op_righttype, op_lefttype,
3059 : BTLessEqualStrategyNumber);
3060 : }
3061 100306 : 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 100360 : if (!OidIsValid(lsortop) ||
3116 100360 : !OidIsValid(rsortop) ||
3117 100360 : !OidIsValid(lstatop) ||
3118 100360 : !OidIsValid(rstatop) ||
3119 100348 : !OidIsValid(ltop) ||
3120 100348 : !OidIsValid(leop) ||
3121 100348 : !OidIsValid(revltop) ||
3122 : !OidIsValid(revleop))
3123 12 : goto fail; /* insufficient info in catalogs */
3124 :
3125 : /* Try to get ranges of both inputs */
3126 100348 : if (!isgt)
3127 : {
3128 100294 : if (!get_variable_range(root, &leftvar, lstatop, collation,
3129 : &leftmin, &leftmax))
3130 21348 : goto fail; /* no range available from stats */
3131 78946 : if (!get_variable_range(root, &rightvar, rstatop, collation,
3132 : &rightmin, &rightmax))
3133 18484 : 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 60486 : selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
3152 : rightmax, op_righttype);
3153 60486 : if (selec != DEFAULT_INEQ_SEL)
3154 60480 : *leftend = selec;
3155 :
3156 : /* And similarly for the right variable. */
3157 60486 : selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
3158 : leftmax, op_lefttype);
3159 60486 : if (selec != DEFAULT_INEQ_SEL)
3160 60486 : *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 60486 : if (*leftend > *rightend)
3169 23570 : *leftend = 1.0;
3170 36916 : else if (*leftend < *rightend)
3171 30694 : *rightend = 1.0;
3172 : else
3173 6222 : *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 60486 : selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
3182 : rightmin, op_righttype);
3183 60486 : if (selec != DEFAULT_INEQ_SEL)
3184 60486 : *leftstart = selec;
3185 :
3186 : /* And similarly for the right variable. */
3187 60486 : selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
3188 : leftmin, op_lefttype);
3189 60486 : if (selec != DEFAULT_INEQ_SEL)
3190 60486 : *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 60486 : if (*leftstart < *rightstart)
3199 18762 : *leftstart = 0.0;
3200 41724 : else if (*leftstart > *rightstart)
3201 23318 : *rightstart = 0.0;
3202 : else
3203 18406 : *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 60486 : 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 60486 : if (*leftstart >= *leftend)
3235 : {
3236 204 : *leftstart = 0.0;
3237 204 : *leftend = 1.0;
3238 : }
3239 60486 : if (*rightstart >= *rightend)
3240 : {
3241 954 : *rightstart = 0.0;
3242 954 : *rightend = 1.0;
3243 : }
3244 :
3245 59532 : fail:
3246 100360 : ReleaseVariableStats(leftvar);
3247 100360 : 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 299738 : 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 299738 : 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 299738 : var = remove_nulling_relids(var, root->outer_join_rels, NULL);
3318 :
3319 384522 : foreach(lc, varinfos)
3320 : {
3321 85586 : varinfo = (GroupVarInfo *) lfirst(lc);
3322 :
3323 : /* Drop exact duplicates */
3324 85586 : if (equal(var, varinfo->var))
3325 802 : 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 90792 : if (vardata->rel != varinfo->rel &&
3333 5888 : 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 298936 : varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3349 :
3350 298936 : varinfo->var = var;
3351 298936 : varinfo->rel = vardata->rel;
3352 298936 : varinfo->ndistinct = ndistinct;
3353 298936 : varinfo->isdefault = isdefault;
3354 298936 : varinfos = lappend(varinfos, varinfo);
3355 298936 : 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 263228 : estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
3431 : List **pgset, EstimationInfo *estinfo)
3432 : {
3433 263228 : List *varinfos = NIL;
3434 263228 : 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 263228 : if (estinfo != NULL)
3441 233274 : 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 263228 : 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 263228 : if (groupExprs == NIL || (pgset && *pgset == NIL))
3457 1002 : 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 262226 : numdistinct = 1.0;
3467 :
3468 262226 : i = 0;
3469 560522 : foreach(l, groupExprs)
3470 : {
3471 298344 : 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 298344 : if (pgset && !list_member_int(*pgset, i++))
3479 251836 : 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 297556 : this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3493 297556 : if (srf_multiplier < this_srf_multiplier)
3494 132 : srf_multiplier = this_srf_multiplier;
3495 :
3496 : /* Short-circuit for expressions returning boolean */
3497 297556 : 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 297316 : examine_variable(root, groupexpr, 0, &vardata);
3517 297316 : if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3518 : {
3519 250184 : varinfos = add_unique_group_var(root, varinfos,
3520 : groupexpr, &vardata);
3521 250184 : ReleaseVariableStats(vardata);
3522 250184 : continue;
3523 : }
3524 47132 : 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 47132 : 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 47132 : 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 96014 : foreach(l2, varshere)
3554 : {
3555 49554 : Node *var = (Node *) lfirst(l2);
3556 :
3557 49554 : examine_variable(root, var, 0, &vardata);
3558 49554 : varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3559 49554 : 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 262178 : 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 263762 : GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3592 263762 : RelOptInfo *rel = varinfo1->rel;
3593 263762 : double reldistinct = 1;
3594 263762 : double relmaxndistinct = reldistinct;
3595 263762 : int relvarcount = 0;
3596 263762 : List *newvarinfos = NIL;
3597 263762 : 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 263762 : relvarinfos = lappend(relvarinfos, varinfo1);
3604 304062 : for_each_from(l, varinfos, 1)
3605 : {
3606 40300 : GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3607 :
3608 40300 : if (varinfo2->rel == varinfo1->rel)
3609 : {
3610 : /* varinfos on current rel */
3611 35174 : relvarinfos = lappend(relvarinfos, varinfo2);
3612 : }
3613 : else
3614 : {
3615 : /* not time to process varinfo2 yet */
3616 5126 : 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 527650 : while (relvarinfos)
3633 : {
3634 : double mvndistinct;
3635 :
3636 263888 : 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 561570 : foreach(l, relvarinfos)
3647 : {
3648 298084 : GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3649 :
3650 298084 : reldistinct *= varinfo2->ndistinct;
3651 298084 : if (relmaxndistinct < varinfo2->ndistinct)
3652 261684 : relmaxndistinct = varinfo2->ndistinct;
3653 298084 : 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 298084 : if (estinfo != NULL && varinfo2->isdefault)
3660 13412 : estinfo->flags |= SELFLAG_USED_DEFAULT;
3661 : }
3662 :
3663 : /* we're done with this relation */
3664 263486 : 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 263762 : 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 262570 : double clamp = rel->tuples;
3682 :
3683 262570 : if (relvarcount > 1)
3684 : {
3685 29352 : clamp *= 0.1;
3686 29352 : if (clamp < relmaxndistinct)
3687 : {
3688 27740 : clamp = relmaxndistinct;
3689 : /* for sanity in case some ndistinct is too large: */
3690 27740 : if (clamp > rel->tuples)
3691 78 : clamp = rel->tuples;
3692 : }
3693 : }
3694 262570 : if (reldistinct > clamp)
3695 27460 : 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 262570 : 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 76214 : reldistinct *=
3739 76214 : (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3740 76214 : rel->tuples / reldistinct));
3741 : }
3742 262570 : reldistinct = clamp_row_est(reldistinct);
3743 :
3744 : /*
3745 : * Update estimate of total distinct groups.
3746 : */
3747 262570 : numdistinct *= reldistinct;
3748 : }
3749 :
3750 263762 : varinfos = newvarinfos;
3751 263762 : } while (varinfos != NIL);
3752 :
3753 : /* Now we can account for the effects of any SRFs */
3754 261844 : numdistinct *= srf_multiplier;
3755 :
3756 : /* Round off */
3757 261844 : numdistinct = ceil(numdistinct);
3758 :
3759 : /* Guard against out-of-range answers */
3760 261844 : if (numdistinct > input_rows)
3761 52078 : numdistinct = input_rows;
3762 261844 : if (numdistinct < 1.0)
3763 0 : numdistinct = 1.0;
3764 :
3765 261844 : 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 141160 : 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 141160 : examine_variable(root, hashkey, 0, &vardata);
3825 :
3826 : /* Look up the frequency of the most common value, if available */
3827 141160 : *mcv_freq = 0.0;
3828 :
3829 141160 : if (HeapTupleIsValid(vardata.statsTuple))
3830 : {
3831 98798 : 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 46658 : if (sslot.nnumbers > 0)
3839 46658 : *mcv_freq = sslot.numbers[0];
3840 46658 : free_attstatsslot(&sslot);
3841 : }
3842 : }
3843 :
3844 : /* Get number of distinct values */
3845 141160 : 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 141160 : if (isdefault)
3852 : {
3853 19788 : *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3854 19788 : ReleaseVariableStats(vardata);
3855 19788 : return;
3856 : }
3857 :
3858 : /* Get fraction that are null */
3859 121372 : if (HeapTupleIsValid(vardata.statsTuple))
3860 : {
3861 : Form_pg_statistic stats;
3862 :
3863 98780 : stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3864 98780 : stanullfrac = stats->stanullfrac;
3865 : }
3866 : else
3867 22592 : stanullfrac = 0.0;
3868 :
3869 : /* Compute avg freq of all distinct data values in raw relation */
3870 121372 : 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 121372 : if (vardata.rel && vardata.rel->tuples > 0)
3881 : {
3882 121358 : ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3883 121358 : 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 121372 : if (ndistinct > nbuckets)
3892 84 : estfract = 1.0 / nbuckets;
3893 : else
3894 121288 : estfract = 1.0 / ndistinct;
3895 :
3896 : /*
3897 : * Adjust estimated bucketsize upward to account for skewed distribution.
3898 : */
3899 121372 : if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3900 41628 : 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 121372 : if (estfract < 1.0e-6)
3908 0 : estfract = 1.0e-6;
3909 121372 : else if (estfract > 1.0)
3910 30256 : estfract = 1.0;
3911 :
3912 121372 : *bucketsize_frac = (Selectivity) estfract;
3913 :
3914 121372 : 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 263888 : 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 263888 : Oid statOid = InvalidOid;
3975 : MVNDistinct *stats;
3976 263888 : StatisticExtInfo *matched_info = NULL;
3977 263888 : RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
3978 :
3979 : /* bail out immediately if the table has no extended statistics */
3980 263888 : if (!rel->statlist)
3981 263360 : 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 80550 : 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 80550 : 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 80550 : switch (valuetypid)
4344 : {
4345 : /*
4346 : * Built-in numeric types
4347 : */
4348 75744 : 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 75744 : *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4368 : &failure);
4369 75744 : *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4370 : &failure);
4371 75744 : *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4372 : &failure);
4373 75744 : return !failure;
4374 :
4375 : /*
4376 : * Built-in string types
4377 : */
4378 4806 : case CHAROID:
4379 : case BPCHAROID:
4380 : case VARCHAROID:
4381 : case TEXTOID:
4382 : case NAMEOID:
4383 : {
4384 4806 : char *valstr = convert_string_datum(value, valuetypid,
4385 : collid, &failure);
4386 4806 : char *lostr = convert_string_datum(lobound, boundstypid,
4387 : collid, &failure);
4388 4806 : 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 4806 : if (failure)
4397 0 : return false;
4398 :
4399 4806 : convert_string_to_scalar(valstr, scaledvalue,
4400 : lostr, scaledlobound,
4401 : histr, scaledhibound);
4402 4806 : pfree(valstr);
4403 4806 : pfree(lostr);
4404 4806 : pfree(histr);
4405 4806 : 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 227232 : convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
4467 : {
4468 227232 : switch (typid)
4469 : {
4470 0 : case BOOLOID:
4471 0 : return (double) DatumGetBool(value);
4472 12 : case INT2OID:
4473 12 : return (double) DatumGetInt16(value);
4474 30714 : case INT4OID:
4475 30714 : 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 36 : case FLOAT8OID:
4481 36 : 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 196470 : 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 196470 : 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 4806 : 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 4806 : rangelo = rangehi = (unsigned char) hibound[0];
4540 64316 : for (sptr = lobound; *sptr; sptr++)
4541 : {
4542 59510 : if (rangelo > (unsigned char) *sptr)
4543 12036 : rangelo = (unsigned char) *sptr;
4544 59510 : if (rangehi < (unsigned char) *sptr)
4545 6348 : rangehi = (unsigned char) *sptr;
4546 : }
4547 63466 : for (sptr = hibound; *sptr; sptr++)
4548 : {
4549 58660 : if (rangelo > (unsigned char) *sptr)
4550 788 : rangelo = (unsigned char) *sptr;
4551 58660 : if (rangehi < (unsigned char) *sptr)
4552 2232 : rangehi = (unsigned char) *sptr;
4553 : }
4554 : /* If range includes any upper-case ASCII chars, make it include all */
4555 4806 : if (rangelo <= 'Z' && rangehi >= 'A')
4556 : {
4557 1104 : if (rangelo > 'A')
4558 138 : rangelo = 'A';
4559 1104 : if (rangehi < 'Z')
4560 480 : rangehi = 'Z';
4561 : }
4562 : /* Ditto lower-case */
4563 4806 : if (rangelo <= 'z' && rangehi >= 'a')
4564 : {
4565 4304 : if (rangelo > 'a')
4566 6 : rangelo = 'a';
4567 4304 : if (rangehi < 'z')
4568 4250 : rangehi = 'z';
4569 : }
4570 : /* Ditto digits */
4571 4806 : if (rangelo <= '9' && rangehi >= '0')
4572 : {
4573 508 : if (rangelo > '0')
4574 414 : rangelo = '0';
4575 508 : 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 4806 : 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 8666 : while (*lobound)
4593 : {
4594 8666 : if (*lobound != *hibound || *lobound != *value)
4595 : break;
4596 3860 : lobound++, hibound++, value++;
4597 : }
4598 :
4599 : /*
4600 : * Now we can do the conversions.
4601 : */
4602 4806 : *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4603 4806 : *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4604 4806 : *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4605 4806 : }
4606 :
4607 : static double
4608 14418 : convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
4609 : {
4610 14418 : int slen = strlen(value);
4611 : double num,
4612 : denom,
4613 : base;
4614 :
4615 14418 : 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 14418 : if (slen > 12)
4628 4064 : slen = 12;
4629 :
4630 : /* Convert initial characters to fraction */
4631 14418 : base = rangehi - rangelo + 1;
4632 14418 : num = 0.0;
4633 14418 : denom = base;
4634 122432 : while (slen-- > 0)
4635 : {
4636 108014 : int ch = (unsigned char) *value++;
4637 :
4638 108014 : if (ch < rangelo)
4639 160 : ch = rangelo - 1;
4640 107854 : else if (ch > rangehi)
4641 0 : ch = rangehi + 1;
4642 108014 : num += ((double) (ch - rangelo)) / denom;
4643 108014 : denom *= base;
4644 : }
4645 :
4646 14418 : 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 14418 : convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
4660 : {
4661 : char *val;
4662 : pg_locale_t mylocale;
4663 :
4664 14418 : 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 4354 : case BPCHAROID:
4672 : case VARCHAROID:
4673 : case TEXTOID:
4674 4354 : val = TextDatumGetCString(value);
4675 4354 : break;
4676 10064 : case NAMEOID:
4677 : {
4678 10064 : NameData *nm = (NameData *) DatumGetPointer(value);
4679 :
4680 10064 : val = pstrdup(NameStr(*nm));
4681 10064 : break;
4682 : }
4683 0 : default:
4684 0 : *failure = true;
4685 0 : return NULL;
4686 : }
4687 :
4688 14418 : mylocale = pg_newlocale_from_collation(collid);
4689 :
4690 14418 : 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 14418 : 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 665696 : 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 665696 : if (list_length(args) != 2)
4914 0 : return false;
4915 :
4916 665696 : left = (Node *) linitial(args);
4917 665696 : 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 665696 : examine_variable(root, left, varRelid, vardata);
4924 665696 : examine_variable(root, right, varRelid, &rdata);
4925 :
4926 : /*
4927 : * If one side is a variable and the other not, we win.
4928 : */
4929 665696 : if (vardata->rel && rdata.rel == NULL)
4930 : {
4931 598724 : *varonleft = true;
4932 598724 : *other = estimate_expression_value(root, rdata.var);
4933 : /* Assume we need no ReleaseVariableStats(rdata) here */
4934 598724 : return true;
4935 : }
4936 :
4937 66972 : if (vardata->rel == NULL && rdata.rel)
4938 : {
4939 62248 : *varonleft = false;
4940 62248 : *other = estimate_expression_value(root, vardata->var);
4941 : /* Assume we need no ReleaseVariableStats(*vardata) here */
4942 62248 : *vardata = rdata;
4943 62248 : return true;
4944 : }
4945 :
4946 : /* Oops, clause has wrong structure (probably var op var) */
4947 4724 : ReleaseVariableStats(*vardata);
4948 4724 : ReleaseVariableStats(rdata);
4949 :
4950 4724 : 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 198666 : 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 198666 : if (list_length(args) != 2)
4972 0 : elog(ERROR, "join operator should take two arguments");
4973 :
4974 198666 : left = (Node *) linitial(args);
4975 198666 : right = (Node *) lsecond(args);
4976 :
4977 198666 : examine_variable(root, left, 0, vardata1);
4978 198666 : examine_variable(root, right, 0, vardata2);
4979 :
4980 397174 : if (vardata1->rel &&
4981 198508 : bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4982 74764 : *join_is_reversed = true; /* var1 is on RHS */
4983 247700 : else if (vardata2->rel &&
4984 123798 : bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4985 128 : *join_is_reversed = true; /* var2 is on LHS */
4986 : else
4987 123774 : *join_is_reversed = false;
4988 198666 : }
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 or a
5022 : * single-column DISTINCT clause, implying its values are unique for
5023 : * this query. (Caution: this should be trusted for statistical
5024 : * purposes only, since we do not check indimmediate nor verify that
5025 : * the exact same definition of equality applies.)
5026 : * acl_ok: true if current user has permission to read the column(s)
5027 : * underlying the pg_statistic entry. This is consulted by
5028 : * statistic_proc_security_check().
5029 : *
5030 : * Caller is responsible for doing ReleaseVariableStats() before exiting.
5031 : */
5032 : void
5033 2549660 : 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 17847620 : MemSet(vardata, 0, sizeof(VariableStatData));
5043 :
5044 : /* Save the exposed type of the expression */
5045 2549660 : vardata->vartype = exprType(node);
5046 :
5047 : /* Look inside any binary-compatible relabeling */
5048 :
5049 2549660 : if (IsA(node, RelabelType))
5050 24580 : basenode = (Node *) ((RelabelType *) node)->arg;
5051 : else
5052 2525080 : basenode = node;
5053 :
5054 : /* Fast path for a simple Var */
5055 :
5056 2549660 : if (IsA(basenode, Var) &&
5057 596250 : (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5058 : {
5059 1793064 : Var *var = (Var *) basenode;
5060 :
5061 : /* Set up result fields other than the stats tuple */
5062 1793064 : vardata->var = basenode; /* return Var without relabeling */
5063 1793064 : vardata->rel = find_base_rel(root, var->varno);
5064 1793064 : vardata->atttype = var->vartype;
5065 1793064 : vardata->atttypmod = var->vartypmod;
5066 1793064 : vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5067 :
5068 : /* Try to locate some stats */
5069 1793064 : examine_simple_variable(root, var, vardata);
5070 :
5071 1793064 : 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 756596 : varnos = pull_varnos(root, basenode);
5080 756596 : basevarnos = bms_difference(varnos, root->outer_join_rels);
5081 :
5082 756596 : onerel = NULL;
5083 :
5084 756596 : 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 356610 : if (bms_get_singleton_member(basevarnos, &relid))
5094 : {
5095 353790 : if (varRelid == 0 || varRelid == relid)
5096 : {
5097 55100 : onerel = find_base_rel(root, relid);
5098 55100 : vardata->rel = onerel;
5099 55100 : node = basenode; /* strip any relabeling */
5100 : }
5101 : /* else treat it as a constant */
5102 : }
5103 : else
5104 : {
5105 : /* varnos has multiple relids */
5106 2820 : if (varRelid == 0)
5107 : {
5108 : /* treat it as a variable of a join relation */
5109 2614 : vardata->rel = find_join_rel(root, varnos);
5110 2614 : node = basenode; /* strip any relabeling */
5111 : }
5112 206 : 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 756596 : bms_free(basevarnos);
5124 :
5125 756596 : vardata->var = node;
5126 756596 : vardata->atttype = exprType(node);
5127 756596 : vardata->atttypmod = exprTypmod(node);
5128 :
5129 756596 : 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 55100 : 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 55100 : userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
5166 :
5167 108264 : foreach(ilist, onerel->indexlist)
5168 : {
5169 55978 : IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5170 : ListCell *indexpr_item;
5171 : int pos;
5172 :
5173 55978 : indexpr_item = list_head(index->indexprs);
5174 55978 : if (indexpr_item == NULL)
5175 51310 : continue; /* no expressions here... */
5176 :
5177 6594 : for (pos = 0; pos < index->ncolumns; pos++)
5178 : {
5179 4740 : if (index->indexkeys[pos] == 0)
5180 : {
5181 : Node *indexkey;
5182 :
5183 4668 : if (indexpr_item == NULL)
5184 0 : elog(ERROR, "too few entries in indexprs list");
5185 4668 : indexkey = (Node *) lfirst(indexpr_item);
5186 4668 : if (indexkey && IsA(indexkey, RelabelType))
5187 0 : indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5188 4668 : 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 3402 : if (index->unique &&
5195 390 : index->nkeycolumns == 1 &&
5196 390 : pos == 0 &&
5197 390 : (index->indpred == NIL || index->predOK))
5198 390 : 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 3402 : 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 3402 : else if (index->indpred == NIL)
5224 : {
5225 3402 : vardata->statsTuple =
5226 6804 : SearchSysCache3(STATRELATTINH,
5227 : ObjectIdGetDatum(index->indexoid),
5228 3402 : Int16GetDatum(pos + 1),
5229 : BoolGetDatum(false));
5230 3402 : vardata->freefunc = ReleaseSysCache;
5231 :
5232 3402 : 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 588 : vardata->acl_ok = true;
5302 : }
5303 : }
5304 3402 : if (vardata->statsTuple)
5305 2814 : break;
5306 : }
5307 1854 : indexpr_item = lnext(index->indexprs, indexpr_item);
5308 : }
5309 : }
5310 4668 : 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 59126 : 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 756596 : 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 1797410 : examine_simple_variable(PlannerInfo *root, Var *var,
5441 : VariableStatData *vardata)
5442 : {
5443 1797410 : RangeTblEntry *rte = root->simple_rte_array[var->varno];
5444 :
5445 : Assert(IsA(rte, RangeTblEntry));
5446 :
5447 1797410 : 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 1797410 : 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 1726656 : vardata->statsTuple = SearchSysCache3(STATRELATTINH,
5465 : ObjectIdGetDatum(rte->relid),
5466 1726656 : Int16GetDatum(var->varattno),
5467 1726656 : BoolGetDatum(rte->inh));
5468 1726656 : vardata->freefunc = ReleaseSysCache;
5469 :
5470 1726656 : if (HeapTupleIsValid(vardata->statsTuple))
5471 : {
5472 1285274 : 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 1285274 : if (onerel)
5486 1285232 : 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 1285274 : if (!OidIsValid(userid))
5495 1203540 : userid = GetUserId();
5496 :
5497 1285274 : vardata->acl_ok =
5498 2570808 : rte->securityQuals == NIL &&
5499 1285274 : ((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 1285274 : 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 441382 : vardata->acl_ok = true;
5580 : }
5581 : }
5582 70754 : else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
5583 63138 : (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 12514 : if (var->varattno == InvalidAttrNumber)
5601 0 : return;
5602 :
5603 : /*
5604 : * Otherwise, find the subquery's planner subroot.
5605 : */
5606 12514 : 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 7616 : rel = find_base_rel(root, var->varno);
5618 :
5619 7616 : 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 4898 : levelsup = rte->ctelevelsup;
5635 4898 : cteroot = root;
5636 9484 : while (levelsup-- > 0)
5637 : {
5638 4586 : cteroot = cteroot->parent_root;
5639 4586 : 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 4898 : ndx = 0;
5649 7128 : foreach(lc, cteroot->parse->cteList)
5650 : {
5651 7128 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
5652 :
5653 7128 : if (strcmp(cte->ctename, rte->ctename) == 0)
5654 4898 : break;
5655 2230 : ndx++;
5656 : }
5657 4898 : if (lc == NULL) /* shouldn't happen */
5658 0 : elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
5659 4898 : if (ndx >= list_length(cteroot->cte_plan_ids))
5660 0 : elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
5661 4898 : plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
5662 4898 : if (plan_id <= 0)
5663 0 : elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
5664 4898 : 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 12514 : 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 12514 : subquery = subroot->parse;
5680 : Assert(IsA(subquery, Query));
5681 :
5682 : /*
5683 : * Punt if subquery uses set operations or GROUP BY, as these will
5684 : * mash underlying columns' stats beyond recognition. (Set ops are
5685 : * 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 12514 : if (subquery->setOperations ||
5691 11234 : subquery->groupClause ||
5692 10614 : subquery->groupingSets)
5693 1900 : return;
5694 :
5695 : /* Get the subquery output expression referenced by the upper Var */
5696 10614 : if (subquery->returningList)
5697 206 : subtlist = subquery->returningList;
5698 : else
5699 10408 : subtlist = subquery->targetList;
5700 10614 : ste = get_tle_by_resno(subtlist, var->varattno);
5701 10614 : if (ste == NULL || ste->resjunk)
5702 0 : elog(ERROR, "subquery %s does not have attribute %d",
5703 : rte->eref->aliasname, var->varattno);
5704 10614 : var = (Var *) ste->expr;
5705 :
5706 : /*
5707 : * If subquery uses DISTINCT, we can't make use of any stats for the
5708 : * variable ... but, if it's the only DISTINCT column, we are entitled
5709 : * to consider it unique. We do the test this way so that it works
5710 : * for cases involving DISTINCT ON.
5711 : */
5712 10614 : if (subquery->distinctClause)
5713 : {
5714 1810 : if (list_length(subquery->distinctClause) == 1 &&
5715 602 : targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5716 280 : vardata->isunique = true;
5717 : /* cannot go further */
5718 1208 : return;
5719 : }
5720 :
5721 : /*
5722 : * If the sub-query originated from a view with the security_barrier
5723 : * attribute, we must not look at the variable's statistics, though it
5724 : * seems all right to notice the existence of a DISTINCT clause. So
5725 : * stop here.
5726 : *
5727 : * This is probably a harsher restriction than necessary; it's
5728 : * certainly OK for the selectivity estimator (which is a C function,
5729 : * and therefore omnipotent anyway) to look at the statistics. But
5730 : * many selectivity estimators will happily *invoke the operator
5731 : * function* to try to work out a good estimate - and that's not OK.
5732 : * So for now, don't dig down for stats.
5733 : */
5734 9406 : if (rte->security_barrier)
5735 228 : return;
5736 :
5737 : /* Can only handle a simple Var of subquery's query level */
5738 9178 : if (var && IsA(var, Var) &&
5739 4346 : var->varlevelsup == 0)
5740 : {
5741 : /*
5742 : * OK, recurse into the subquery. Note that the original setting
5743 : * of vardata->isunique (which will surely be false) is left
5744 : * unchanged in this situation. That's what we want, since even
5745 : * if the underlying column is unique, the subquery may have
5746 : * joined to other tables in a way that creates duplicates.
5747 : */
5748 4346 : examine_simple_variable(subroot, var, vardata);
5749 : }
5750 : }
5751 : else
5752 : {
5753 : /*
5754 : * Otherwise, the Var comes from a FUNCTION or VALUES RTE. (We won't
5755 : * see RTE_JOIN here because join alias Vars have already been
5756 : * flattened.) There's not much we can do with function outputs, but
5757 : * maybe someday try to be smarter about VALUES.
5758 : */
5759 : }
5760 : }
5761 :
5762 : /*
5763 : * Check whether it is permitted to call func_oid passing some of the
5764 : * pg_statistic data in vardata. We allow this either if the user has SELECT
5765 : * privileges on the table or column underlying the pg_statistic data or if
5766 : * the function is marked leakproof.
5767 : */
5768 : bool
5769 862316 : statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
5770 : {
5771 862316 : if (vardata->acl_ok)
5772 861114 : return true;
5773 :
5774 1202 : if (!OidIsValid(func_oid))
5775 0 : return false;
5776 :
5777 1202 : if (get_func_leakproof(func_oid))
5778 550 : return true;
5779 :
5780 652 : ereport(DEBUG2,
5781 : (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
5782 : get_func_name(func_oid))));
5783 652 : return false;
5784 : }
5785 :
5786 : /*
5787 : * get_variable_numdistinct
5788 : * Estimate the number of distinct values of a variable.
5789 : *
5790 : * vardata: results of examine_variable
5791 : * *isdefault: set to true if the result is a default rather than based on
5792 : * anything meaningful.
5793 : *
5794 : * NB: be careful to produce a positive integral result, since callers may
5795 : * compare the result to exact integer counts, or might divide by it.
5796 : */
5797 : double
5798 1225946 : get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
5799 : {
5800 : double stadistinct;
5801 1225946 : double stanullfrac = 0.0;
5802 : double ntuples;
5803 :
5804 1225946 : *isdefault = false;
5805 :
5806 : /*
5807 : * Determine the stadistinct value to use. There are cases where we can
5808 : * get an estimate even without a pg_statistic entry, or can get a better
5809 : * value than is in pg_statistic. Grab stanullfrac too if we can find it
5810 : * (otherwise, assume no nulls, for lack of any better idea).
5811 : */
5812 1225946 : if (HeapTupleIsValid(vardata->statsTuple))
5813 : {
5814 : /* Use the pg_statistic entry */
5815 : Form_pg_statistic stats;
5816 :
5817 875460 : stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
5818 875460 : stadistinct = stats->stadistinct;
5819 875460 : stanullfrac = stats->stanullfrac;
5820 : }
5821 350486 : else if (vardata->vartype == BOOLOID)
5822 : {
5823 : /*
5824 : * Special-case boolean columns: presumably, two distinct values.
5825 : *
5826 : * Are there any other datatypes we should wire in special estimates
5827 : * for?
5828 : */
5829 468 : stadistinct = 2.0;
5830 : }
5831 350018 : else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5832 : {
5833 : /*
5834 : * If the Var represents a column of a VALUES RTE, assume it's unique.
5835 : * This could of course be very wrong, but it should tend to be true
5836 : * in well-written queries. We could consider examining the VALUES'
5837 : * contents to get some real statistics; but that only works if the
5838 : * entries are all constants, and it would be pretty expensive anyway.
5839 : */
5840 3258 : stadistinct = -1.0; /* unique (and all non null) */
5841 : }
5842 : else
5843 : {
5844 : /*
5845 : * We don't keep statistics for system columns, but in some cases we
5846 : * can infer distinctness anyway.
5847 : */
5848 346760 : if (vardata->var && IsA(vardata->var, Var))
5849 : {
5850 324618 : switch (((Var *) vardata->var)->varattno)
5851 : {
5852 1146 : case SelfItemPointerAttributeNumber:
5853 1146 : stadistinct = -1.0; /* unique (and all non null) */
5854 1146 : break;
5855 2518 : case TableOidAttributeNumber:
5856 2518 : stadistinct = 1.0; /* only 1 value */
5857 2518 : break;
5858 320954 : default:
5859 320954 : stadistinct = 0.0; /* means "unknown" */
5860 320954 : break;
5861 : }
5862 : }
5863 : else
5864 22142 : stadistinct = 0.0; /* means "unknown" */
5865 :
5866 : /*
5867 : * XXX consider using estimate_num_groups on expressions?
5868 : */
5869 : }
5870 :
5871 : /*
5872 : * If there is a unique index or DISTINCT clause for the variable, assume
5873 : * it is unique no matter what pg_statistic says; the statistics could be
5874 : * out of date, or we might have found a partial unique index that proves
5875 : * the var is unique for this query. However, we'd better still believe
5876 : * the null-fraction statistic.
5877 : */
5878 1225946 : if (vardata->isunique)
5879 333852 : stadistinct = -1.0 * (1.0 - stanullfrac);
5880 :
5881 : /*
5882 : * If we had an absolute estimate, use that.
5883 : */
5884 1225946 : if (stadistinct > 0.0)
5885 285682 : return clamp_row_est(stadistinct);
5886 :
5887 : /*
5888 : * Otherwise we need to get the relation size; punt if not available.
5889 : */
5890 940264 : if (vardata->rel == NULL)
5891 : {
5892 298 : *isdefault = true;
5893 298 : return DEFAULT_NUM_DISTINCT;
5894 : }
5895 939966 : ntuples = vardata->rel->tuples;
5896 939966 : if (ntuples <= 0.0)
5897 : {
5898 53764 : *isdefault = true;
5899 53764 : return DEFAULT_NUM_DISTINCT;
5900 : }
5901 :
5902 : /*
5903 : * If we had a relative estimate, use that.
5904 : */
5905 886202 : if (stadistinct < 0.0)
5906 629512 : return clamp_row_est(-stadistinct * ntuples);
5907 :
5908 : /*
5909 : * With no data, estimate ndistinct = ntuples if the table is small, else
5910 : * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
5911 : * that the behavior isn't discontinuous.
5912 : */
5913 256690 : if (ntuples < DEFAULT_NUM_DISTINCT)
5914 121912 : return clamp_row_est(ntuples);
5915 :
5916 134778 : *isdefault = true;
5917 134778 : return DEFAULT_NUM_DISTINCT;
5918 : }
5919 :
5920 : /*
5921 : * get_variable_range
5922 : * Estimate the minimum and maximum value of the specified variable.
5923 : * If successful, store values in *min and *max, and return true.
5924 : * If no data available, return false.
5925 : *
5926 : * sortop is the "<" comparison operator to use. This should generally
5927 : * be "<" not ">", as only the former is likely to be found in pg_statistic.
5928 : * The collation must be specified too.
5929 : */
5930 : static bool
5931 179318 : get_variable_range(PlannerInfo *root, VariableStatData *vardata,
5932 : Oid sortop, Oid collation,
5933 : Datum *min, Datum *max)
5934 : {
5935 179318 : Datum tmin = 0;
5936 179318 : Datum tmax = 0;
5937 179318 : bool have_data = false;
5938 : int16 typLen;
5939 : bool typByVal;
5940 : Oid opfuncoid;
5941 : FmgrInfo opproc;
5942 : AttStatsSlot sslot;
5943 :
5944 : /*
5945 : * XXX It's very tempting to try to use the actual column min and max, if
5946 : * we can get them relatively-cheaply with an index probe. However, since
5947 : * this function is called many times during join planning, that could
5948 : * have unpleasant effects on planning speed. Need more investigation
5949 : * before enabling this.
5950 : */
5951 : #ifdef NOT_USED
5952 : if (get_actual_variable_range(root, vardata, sortop, collation, min, max))
5953 : return true;
5954 : #endif
5955 :
5956 179318 : if (!HeapTupleIsValid(vardata->statsTuple))
5957 : {
5958 : /* no stats available, so default result */
5959 38090 : return false;
5960 : }
5961 :
5962 : /*
5963 : * If we can't apply the sortop to the stats data, just fail. In
5964 : * principle, if there's a histogram and no MCVs, we could return the
5965 : * histogram endpoints without ever applying the sortop ... but it's
5966 : * probably not worth trying, because whatever the caller wants to do with
5967 : * the endpoints would likely fail the security check too.
5968 : */
5969 141228 : if (!statistic_proc_security_check(vardata,
5970 141228 : (opfuncoid = get_opcode(sortop))))
5971 0 : return false;
5972 :
5973 141228 : opproc.fn_oid = InvalidOid; /* mark this as not looked up yet */
5974 :
5975 141228 : get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5976 :
5977 : /*
5978 : * If there is a histogram with the ordering we want, grab the first and
5979 : * last values.
5980 : */
5981 141228 : if (get_attstatsslot(&sslot, vardata->statsTuple,
5982 : STATISTIC_KIND_HISTOGRAM, sortop,
5983 : ATTSTATSSLOT_VALUES))
5984 : {
5985 105326 : if (sslot.stacoll == collation && sslot.nvalues > 0)
5986 : {
5987 105326 : tmin = datumCopy(sslot.values[0], typByVal, typLen);
5988 105326 : tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
5989 105326 : have_data = true;
5990 : }
5991 105326 : free_attstatsslot(&sslot);
5992 : }
5993 :
5994 : /*
5995 : * Otherwise, if there is a histogram with some other ordering, scan it
5996 : * and get the min and max values according to the ordering we want. This
5997 : * of course may not find values that are really extremal according to our
5998 : * ordering, but it beats ignoring available data.
5999 : */
6000 177130 : if (!have_data &&
6001 35902 : get_attstatsslot(&sslot, vardata->statsTuple,
6002 : STATISTIC_KIND_HISTOGRAM, InvalidOid,
6003 : ATTSTATSSLOT_VALUES))
6004 : {
6005 0 : get_stats_slot_range(&sslot, opfuncoid, &opproc,
6006 : collation, typLen, typByVal,
6007 : &tmin, &tmax, &have_data);
6008 0 : free_attstatsslot(&sslot);
6009 : }
6010 :
6011 : /*
6012 : * If we have most-common-values info, look for extreme MCVs. This is
6013 : * needed even if we also have a histogram, since the histogram excludes
6014 : * the MCVs. However, if we *only* have MCVs and no histogram, we should
6015 : * be pretty wary of deciding that that is a full representation of the
6016 : * data. Proceed only if the MCVs represent the whole table (to within
6017 : * roundoff error).
6018 : */
6019 141228 : if (get_attstatsslot(&sslot, vardata->statsTuple,
6020 : STATISTIC_KIND_MCV, InvalidOid,
6021 141228 : have_data ? ATTSTATSSLOT_VALUES :
6022 : (ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS)))
6023 : {
6024 66486 : bool use_mcvs = have_data;
6025 :
6026 66486 : if (!have_data)
6027 : {
6028 34680 : double sumcommon = 0.0;
6029 : double nullfrac;
6030 : int i;
6031 :
6032 252542 : for (i = 0; i < sslot.nnumbers; i++)
6033 217862 : sumcommon += sslot.numbers[i];
6034 34680 : nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata->statsTuple))->stanullfrac;
6035 34680 : if (sumcommon + nullfrac > 0.99999)
6036 34130 : use_mcvs = true;
6037 : }
6038 :
6039 66486 : if (use_mcvs)
6040 65936 : get_stats_slot_range(&sslot, opfuncoid, &opproc,
6041 : collation, typLen, typByVal,
6042 : &tmin, &tmax, &have_data);
6043 66486 : free_attstatsslot(&sslot);
6044 : }
6045 :
6046 141228 : *min = tmin;
6047 141228 : *max = tmax;
6048 141228 : return have_data;
6049 : }
6050 :
6051 : /*
6052 : * get_stats_slot_range: scan sslot for min/max values
6053 : *
6054 : * Subroutine for get_variable_range: update min/max/have_data according
6055 : * to what we find in the statistics array.
6056 : */
6057 : static void
6058 65936 : get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
6059 : Oid collation, int16 typLen, bool typByVal,
6060 : Datum *min, Datum *max, bool *p_have_data)
6061 : {
6062 65936 : Datum tmin = *min;
6063 65936 : Datum tmax = *max;
6064 65936 : bool have_data = *p_have_data;
6065 65936 : bool found_tmin = false;
6066 65936 : bool found_tmax = false;
6067 :
6068 : /* Look up the comparison function, if we didn't already do so */
6069 65936 : if (opproc->fn_oid != opfuncoid)
6070 65936 : fmgr_info(opfuncoid, opproc);
6071 :
6072 : /* Scan all the slot's values */
6073 2004478 : for (int i = 0; i < sslot->nvalues; i++)
6074 : {
6075 1938542 : if (!have_data)
6076 : {
6077 34130 : tmin = tmax = sslot->values[i];
6078 34130 : found_tmin = found_tmax = true;
6079 34130 : *p_have_data = have_data = true;
6080 34130 : continue;
6081 : }
6082 1904412 : if (DatumGetBool(FunctionCall2Coll(opproc,
6083 : collation,
6084 1904412 : sslot->values[i], tmin)))
6085 : {
6086 44074 : tmin = sslot->values[i];
6087 44074 : found_tmin = true;
6088 : }
6089 1904412 : if (DatumGetBool(FunctionCall2Coll(opproc,
6090 : collation,
6091 1904412 : tmax, sslot->values[i])))
6092 : {
6093 88432 : tmax = sslot->values[i];
6094 88432 : found_tmax = true;
6095 : }
6096 : }
6097 :
6098 : /*
6099 : * Copy the slot's values, if we found new extreme values.
6100 : */
6101 65936 : if (found_tmin)
6102 52646 : *min = datumCopy(tmin, typByVal, typLen);
6103 65936 : if (found_tmax)
6104 36148 : *max = datumCopy(tmax, typByVal, typLen);
6105 65936 : }
6106 :
6107 :
6108 : /*
6109 : * get_actual_variable_range
6110 : * Attempt to identify the current *actual* minimum and/or maximum
6111 : * of the specified variable, by looking for a suitable btree index
6112 : * and fetching its low and/or high values.
6113 : * If successful, store values in *min and *max, and return true.
6114 : * (Either pointer can be NULL if that endpoint isn't needed.)
6115 : * If unsuccessful, return false.
6116 : *
6117 : * sortop is the "<" comparison operator to use.
6118 : * collation is the required collation.
6119 : */
6120 : static bool
6121 164062 : get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
6122 : Oid sortop, Oid collation,
6123 : Datum *min, Datum *max)
6124 : {
6125 164062 : bool have_data = false;
6126 164062 : RelOptInfo *rel = vardata->rel;
6127 : RangeTblEntry *rte;
6128 : ListCell *lc;
6129 :
6130 : /* No hope if no relation or it doesn't have indexes */
6131 164062 : if (rel == NULL || rel->indexlist == NIL)
6132 12978 : return false;
6133 : /* If it has indexes it must be a plain relation */
6134 151084 : rte = root->simple_rte_array[rel->relid];
6135 : Assert(rte->rtekind == RTE_RELATION);
6136 :
6137 : /* ignore partitioned tables. Any indexes here are not real indexes */
6138 151084 : if (rte->relkind == RELKIND_PARTITIONED_TABLE)
6139 828 : return false;
6140 :
6141 : /* Search through the indexes to see if any match our problem */
6142 287936 : foreach(lc, rel->indexlist)
6143 : {
6144 245018 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
6145 : ScanDirection indexscandir;
6146 :
6147 : /* Ignore non-btree indexes */
6148 245018 : if (index->relam != BTREE_AM_OID)
6149 0 : continue;
6150 :
6151 : /*
6152 : * Ignore partial indexes --- we only want stats that cover the entire
6153 : * relation.
6154 : */
6155 245018 : if (index->indpred != NIL)
6156 288 : continue;
6157 :
6158 : /*
6159 : * The index list might include hypothetical indexes inserted by a
6160 : * get_relation_info hook --- don't try to access them.
6161 : */
6162 244730 : if (index->hypothetical)
6163 0 : continue;
6164 :
6165 : /*
6166 : * The first index column must match the desired variable, sortop, and
6167 : * collation --- but we can use a descending-order index.
6168 : */
6169 244730 : if (collation != index->indexcollations[0])
6170 29114 : continue; /* test first 'cause it's cheapest */
6171 215616 : if (!match_index_to_operand(vardata->var, 0, index))
6172 108278 : continue;
6173 107338 : switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
6174 : {
6175 107338 : case BTLessStrategyNumber:
6176 107338 : if (index->reverse_sort[0])
6177 0 : indexscandir = BackwardScanDirection;
6178 : else
6179 107338 : indexscandir = ForwardScanDirection;
6180 107338 : break;
6181 0 : case BTGreaterStrategyNumber:
6182 0 : if (index->reverse_sort[0])
6183 0 : indexscandir = ForwardScanDirection;
6184 : else
6185 0 : indexscandir = BackwardScanDirection;
6186 0 : break;
6187 0 : default:
6188 : /* index doesn't match the sortop */
6189 0 : continue;
6190 : }
6191 :
6192 : /*
6193 : * Found a suitable index to extract data from. Set up some data that
6194 : * can be used by both invocations of get_actual_variable_endpoint.
6195 : */
6196 : {
6197 : MemoryContext tmpcontext;
6198 : MemoryContext oldcontext;
6199 : Relation heapRel;
6200 : Relation indexRel;
6201 : TupleTableSlot *slot;
6202 : int16 typLen;
6203 : bool typByVal;
6204 : ScanKeyData scankeys[1];
6205 :
6206 : /* Make sure any cruft gets recycled when we're done */
6207 107338 : tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
6208 : "get_actual_variable_range workspace",
6209 : ALLOCSET_DEFAULT_SIZES);
6210 107338 : oldcontext = MemoryContextSwitchTo(tmpcontext);
6211 :
6212 : /*
6213 : * Open the table and index so we can read from them. We should
6214 : * already have some type of lock on each.
6215 : */
6216 107338 : heapRel = table_open(rte->relid, NoLock);
6217 107338 : indexRel = index_open(index->indexoid, NoLock);
6218 :
6219 : /* build some stuff needed for indexscan execution */
6220 107338 : slot = table_slot_create(heapRel, NULL);
6221 107338 : get_typlenbyval(vardata->atttype, &typLen, &typByVal);
6222 :
6223 : /* set up an IS NOT NULL scan key so that we ignore nulls */
6224 107338 : ScanKeyEntryInitialize(&scankeys[0],
6225 : SK_ISNULL | SK_SEARCHNOTNULL,
6226 : 1, /* index col to scan */
6227 : InvalidStrategy, /* no strategy */
6228 : InvalidOid, /* no strategy subtype */
6229 : InvalidOid, /* no collation */
6230 : InvalidOid, /* no reg proc for this */
6231 : (Datum) 0); /* constant */
6232 :
6233 : /* If min is requested ... */
6234 107338 : if (min)
6235 : {
6236 62808 : have_data = get_actual_variable_endpoint(heapRel,
6237 : indexRel,
6238 : indexscandir,
6239 : scankeys,
6240 : typLen,
6241 : typByVal,
6242 : slot,
6243 : oldcontext,
6244 : min);
6245 : }
6246 : else
6247 : {
6248 : /* If min not requested, still want to fetch max */
6249 44530 : have_data = true;
6250 : }
6251 :
6252 : /* If max is requested, and we didn't already fail ... */
6253 107338 : if (max && have_data)
6254 : {
6255 : /* scan in the opposite direction; all else is the same */
6256 45666 : have_data = get_actual_variable_endpoint(heapRel,
6257 : indexRel,
6258 45666 : -indexscandir,
6259 : scankeys,
6260 : typLen,
6261 : typByVal,
6262 : slot,
6263 : oldcontext,
6264 : max);
6265 : }
6266 :
6267 : /* Clean everything up */
6268 107338 : ExecDropSingleTupleTableSlot(slot);
6269 :
6270 107338 : index_close(indexRel, NoLock);
6271 107338 : table_close(heapRel, NoLock);
6272 :
6273 107338 : MemoryContextSwitchTo(oldcontext);
6274 107338 : MemoryContextDelete(tmpcontext);
6275 :
6276 : /* And we're done */
6277 107338 : break;
6278 : }
6279 : }
6280 :
6281 150256 : return have_data;
6282 : }
6283 :
6284 : /*
6285 : * Get one endpoint datum (min or max depending on indexscandir) from the
6286 : * specified index. Return true if successful, false if not.
6287 : * On success, endpoint value is stored to *endpointDatum (and copied into
6288 : * outercontext).
6289 : *
6290 : * scankeys is a 1-element scankey array set up to reject nulls.
6291 : * typLen/typByVal describe the datatype of the index's first column.
6292 : * tableslot is a slot suitable to hold table tuples, in case we need
6293 : * to probe the heap.
6294 : * (We could compute these values locally, but that would mean computing them
6295 : * twice when get_actual_variable_range needs both the min and the max.)
6296 : *
6297 : * Failure occurs either when the index is empty, or we decide that it's
6298 : * taking too long to find a suitable tuple.
6299 : */
6300 : static bool
6301 108474 : get_actual_variable_endpoint(Relation heapRel,
6302 : Relation indexRel,
6303 : ScanDirection indexscandir,
6304 : ScanKey scankeys,
6305 : int16 typLen,
6306 : bool typByVal,
6307 : TupleTableSlot *tableslot,
6308 : MemoryContext outercontext,
6309 : Datum *endpointDatum)
6310 : {
6311 108474 : bool have_data = false;
6312 : SnapshotData SnapshotNonVacuumable;
6313 : IndexScanDesc index_scan;
6314 108474 : Buffer vmbuffer = InvalidBuffer;
6315 108474 : BlockNumber last_heap_block = InvalidBlockNumber;
6316 108474 : int n_visited_heap_pages = 0;
6317 : ItemPointer tid;
6318 : Datum values[INDEX_MAX_KEYS];
6319 : bool isnull[INDEX_MAX_KEYS];
6320 : MemoryContext oldcontext;
6321 :
6322 : /*
6323 : * We use the index-only-scan machinery for this. With mostly-static
6324 : * tables that's a win because it avoids a heap visit. It's also a win
6325 : * for dynamic data, but the reason is less obvious; read on for details.
6326 : *
6327 : * In principle, we should scan the index with our current active
6328 : * snapshot, which is the best approximation we've got to what the query
6329 : * will see when executed. But that won't be exact if a new snap is taken
6330 : * before running the query, and it can be very expensive if a lot of
6331 : * recently-dead or uncommitted rows exist at the beginning or end of the
6332 : * index (because we'll laboriously fetch each one and reject it).
6333 : * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
6334 : * and uncommitted rows as well as normal visible rows. On the other
6335 : * hand, it will reject known-dead rows, and thus not give a bogus answer
6336 : * when the extreme value has been deleted (unless the deletion was quite
6337 : * recent); that case motivates not using SnapshotAny here.
6338 : *
6339 : * A crucial point here is that SnapshotNonVacuumable, with
6340 : * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
6341 : * condition that the indexscan will use to decide that index entries are
6342 : * killable (see heap_hot_search_buffer()). Therefore, if the snapshot
6343 : * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
6344 : * have to continue scanning past it, we know that the indexscan will mark
6345 : * that index entry killed. That means that the next
6346 : * get_actual_variable_endpoint() call will not have to re-consider that
6347 : * index entry. In this way we avoid repetitive work when this function
6348 : * is used a lot during planning.
6349 : *
6350 : * But using SnapshotNonVacuumable creates a hazard of its own. In a
6351 : * recently-created index, some index entries may point at "broken" HOT
6352 : * chains in which not all the tuple versions contain data matching the
6353 : * index entry. The live tuple version(s) certainly do match the index,
6354 : * but SnapshotNonVacuumable can accept recently-dead tuple versions that
6355 : * don't match. Hence, if we took data from the selected heap tuple, we
6356 : * might get a bogus answer that's not close to the index extremal value,
6357 : * or could even be NULL. We avoid this hazard because we take the data
6358 : * from the index entry not the heap.
6359 : *
6360 : * Despite all this care, there are situations where we might find many
6361 : * non-visible tuples near the end of the index. We don't want to expend
6362 : * a huge amount of time here, so we give up once we've read too many heap
6363 : * pages. When we fail for that reason, the caller will end up using
6364 : * whatever extremal value is recorded in pg_statistic.
6365 : */
6366 108474 : InitNonVacuumableSnapshot(SnapshotNonVacuumable,
6367 : GlobalVisTestFor(heapRel));
6368 :
6369 108474 : index_scan = index_beginscan(heapRel, indexRel,
6370 : &SnapshotNonVacuumable,
6371 : 1, 0);
6372 : /* Set it up for index-only scan */
6373 108474 : index_scan->xs_want_itup = true;
6374 108474 : index_rescan(index_scan, scankeys, 1, NULL, 0);
6375 :
6376 : /* Fetch first/next tuple in specified direction */
6377 136720 : while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
6378 : {
6379 136720 : BlockNumber block = ItemPointerGetBlockNumber(tid);
6380 :
6381 136720 : if (!VM_ALL_VISIBLE(heapRel,
6382 : block,
6383 : &vmbuffer))
6384 : {
6385 : /* Rats, we have to visit the heap to check visibility */
6386 103432 : if (!index_fetch_heap(index_scan, tableslot))
6387 : {
6388 : /*
6389 : * No visible tuple for this index entry, so we need to
6390 : * advance to the next entry. Before doing so, count heap
6391 : * page fetches and give up if we've done too many.
6392 : *
6393 : * We don't charge a page fetch if this is the same heap page
6394 : * as the previous tuple. This is on the conservative side,
6395 : * since other recently-accessed pages are probably still in
6396 : * buffers too; but it's good enough for this heuristic.
6397 : */
6398 : #define VISITED_PAGES_LIMIT 100
6399 :
6400 28246 : if (block != last_heap_block)
6401 : {
6402 2924 : last_heap_block = block;
6403 2924 : n_visited_heap_pages++;
6404 2924 : if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
6405 0 : break;
6406 : }
6407 :
6408 28246 : continue; /* no visible tuple, try next index entry */
6409 : }
6410 :
6411 : /* We don't actually need the heap tuple for anything */
6412 75186 : ExecClearTuple(tableslot);
6413 :
6414 : /*
6415 : * We don't care whether there's more than one visible tuple in
6416 : * the HOT chain; if any are visible, that's good enough.
6417 : */
6418 : }
6419 :
6420 : /*
6421 : * We expect that btree will return data in IndexTuple not HeapTuple
6422 : * format. It's not lossy either.
6423 : */
6424 108474 : if (!index_scan->xs_itup)
6425 0 : elog(ERROR, "no data returned for index-only scan");
6426 108474 : if (index_scan->xs_recheck)
6427 0 : elog(ERROR, "unexpected recheck indication from btree");
6428 :
6429 : /* OK to deconstruct the index tuple */
6430 108474 : index_deform_tuple(index_scan->xs_itup,
6431 : index_scan->xs_itupdesc,
6432 : values, isnull);
6433 :
6434 : /* Shouldn't have got a null, but be careful */
6435 108474 : if (isnull[0])
6436 0 : elog(ERROR, "found unexpected null value in index \"%s\"",
6437 : RelationGetRelationName(indexRel));
6438 :
6439 : /* Copy the index column value out to caller's context */
6440 108474 : oldcontext = MemoryContextSwitchTo(outercontext);
6441 108474 : *endpointDatum = datumCopy(values[0], typByVal, typLen);
6442 108474 : MemoryContextSwitchTo(oldcontext);
6443 108474 : have_data = true;
6444 108474 : break;
6445 : }
6446 :
6447 108474 : if (vmbuffer != InvalidBuffer)
6448 95808 : ReleaseBuffer(vmbuffer);
6449 108474 : index_endscan(index_scan);
6450 :
6451 108474 : return have_data;
6452 : }
6453 :
6454 : /*
6455 : * find_join_input_rel
6456 : * Look up the input relation for a join.
6457 : *
6458 : * We assume that the input relation's RelOptInfo must have been constructed
6459 : * already.
6460 : */
6461 : static RelOptInfo *
6462 7098 : find_join_input_rel(PlannerInfo *root, Relids relids)
6463 : {
6464 7098 : RelOptInfo *rel = NULL;
6465 :
6466 7098 : if (!bms_is_empty(relids))
6467 : {
6468 : int relid;
6469 :
6470 7098 : if (bms_get_singleton_member(relids, &relid))
6471 6836 : rel = find_base_rel(root, relid);
6472 : else
6473 262 : rel = find_join_rel(root, relids);
6474 : }
6475 :
6476 7098 : if (rel == NULL)
6477 0 : elog(ERROR, "could not find RelOptInfo for given relids");
6478 :
6479 7098 : return rel;
6480 : }
6481 :
6482 :
6483 : /*-------------------------------------------------------------------------
6484 : *
6485 : * Index cost estimation functions
6486 : *
6487 : *-------------------------------------------------------------------------
6488 : */
6489 :
6490 : /*
6491 : * Extract the actual indexquals (as RestrictInfos) from an IndexClause list
6492 : */
6493 : List *
6494 682122 : get_quals_from_indexclauses(List *indexclauses)
6495 : {
6496 682122 : List *result = NIL;
6497 : ListCell *lc;
6498 :
6499 1212666 : foreach(lc, indexclauses)
6500 : {
6501 530544 : IndexClause *iclause = lfirst_node(IndexClause, lc);
6502 : ListCell *lc2;
6503 :
6504 1063938 : foreach(lc2, iclause->indexquals)
6505 : {
6506 533394 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6507 :
6508 533394 : result = lappend(result, rinfo);
6509 : }
6510 : }
6511 682122 : return result;
6512 : }
6513 :
6514 : /*
6515 : * Compute the total evaluation cost of the comparison operands in a list
6516 : * of index qual expressions. Since we know these will be evaluated just
6517 : * once per scan, there's no need to distinguish startup from per-row cost.
6518 : *
6519 : * This can be used either on the result of get_quals_from_indexclauses(),
6520 : * or directly on an indexorderbys list. In both cases, we expect that the
6521 : * index key expression is on the left side of binary clauses.
6522 : */
6523 : Cost
6524 1351634 : index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
6525 : {
6526 1351634 : Cost qual_arg_cost = 0;
6527 : ListCell *lc;
6528 :
6529 1885490 : foreach(lc, indexquals)
6530 : {
6531 533856 : Expr *clause = (Expr *) lfirst(lc);
6532 : Node *other_operand;
6533 : QualCost index_qual_cost;
6534 :
6535 : /*
6536 : * Index quals will have RestrictInfos, indexorderbys won't. Look
6537 : * through RestrictInfo if present.
6538 : */
6539 533856 : if (IsA(clause, RestrictInfo))
6540 533382 : clause = ((RestrictInfo *) clause)->clause;
6541 :
6542 533856 : if (IsA(clause, OpExpr))
6543 : {
6544 521588 : OpExpr *op = (OpExpr *) clause;
6545 :
6546 521588 : other_operand = (Node *) lsecond(op->args);
6547 : }
6548 12268 : else if (IsA(clause, RowCompareExpr))
6549 : {
6550 300 : RowCompareExpr *rc = (RowCompareExpr *) clause;
6551 :
6552 300 : other_operand = (Node *) rc->rargs;
6553 : }
6554 11968 : else if (IsA(clause, ScalarArrayOpExpr))
6555 : {
6556 9564 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6557 :
6558 9564 : other_operand = (Node *) lsecond(saop->args);
6559 : }
6560 2404 : else if (IsA(clause, NullTest))
6561 : {
6562 2404 : other_operand = NULL;
6563 : }
6564 : else
6565 : {
6566 0 : elog(ERROR, "unsupported indexqual type: %d",
6567 : (int) nodeTag(clause));
6568 : other_operand = NULL; /* keep compiler quiet */
6569 : }
6570 :
6571 533856 : cost_qual_eval_node(&index_qual_cost, other_operand, root);
6572 533856 : qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6573 : }
6574 1351634 : return qual_arg_cost;
6575 : }
6576 :
6577 : void
6578 669524 : genericcostestimate(PlannerInfo *root,
6579 : IndexPath *path,
6580 : double loop_count,
6581 : GenericCosts *costs)
6582 : {
6583 669524 : IndexOptInfo *index = path->indexinfo;
6584 669524 : List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6585 669524 : List *indexOrderBys = path->indexorderbys;
6586 : Cost indexStartupCost;
6587 : Cost indexTotalCost;
6588 : Selectivity indexSelectivity;
6589 : double indexCorrelation;
6590 : double numIndexPages;
6591 : double numIndexTuples;
6592 : double spc_random_page_cost;
6593 : double num_sa_scans;
6594 : double num_outer_scans;
6595 : double num_scans;
6596 : double qual_op_cost;
6597 : double qual_arg_cost;
6598 : List *selectivityQuals;
6599 : ListCell *l;
6600 :
6601 : /*
6602 : * If the index is partial, AND the index predicate with the explicitly
6603 : * given indexquals to produce a more accurate idea of the index
6604 : * selectivity.
6605 : */
6606 669524 : selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6607 :
6608 : /*
6609 : * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
6610 : * just assume that the number of index descents is the number of distinct
6611 : * combinations of array elements from all of the scan's SAOP clauses.
6612 : */
6613 669524 : num_sa_scans = costs->num_sa_scans;
6614 669524 : if (num_sa_scans < 1)
6615 : {
6616 8190 : num_sa_scans = 1;
6617 17254 : foreach(l, indexQuals)
6618 : {
6619 9064 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6620 :
6621 9064 : if (IsA(rinfo->clause, ScalarArrayOpExpr))
6622 : {
6623 26 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6624 26 : double alength = estimate_array_length(root, lsecond(saop->args));
6625 :
6626 26 : if (alength > 1)
6627 26 : num_sa_scans *= alength;
6628 : }
6629 : }
6630 : }
6631 :
6632 : /* Estimate the fraction of main-table tuples that will be visited */
6633 669524 : indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6634 669524 : index->rel->relid,
6635 : JOIN_INNER,
6636 : NULL);
6637 :
6638 : /*
6639 : * If caller didn't give us an estimate, estimate the number of index
6640 : * tuples that will be visited. We do it in this rather peculiar-looking
6641 : * way in order to get the right answer for partial indexes.
6642 : */
6643 669524 : numIndexTuples = costs->numIndexTuples;
6644 669524 : if (numIndexTuples <= 0.0)
6645 : {
6646 76420 : numIndexTuples = indexSelectivity * index->rel->tuples;
6647 :
6648 : /*
6649 : * The above calculation counts all the tuples visited across all
6650 : * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6651 : * average per-indexscan number, so adjust. This is a handy place to
6652 : * round to integer, too. (If caller supplied tuple estimate, it's
6653 : * responsible for handling these considerations.)
6654 : */
6655 76420 : numIndexTuples = rint(numIndexTuples / num_sa_scans);
6656 : }
6657 :
6658 : /*
6659 : * We can bound the number of tuples by the index size in any case. Also,
6660 : * always estimate at least one tuple is touched, even when
6661 : * indexSelectivity estimate is tiny.
6662 : */
6663 669524 : if (numIndexTuples > index->tuples)
6664 6034 : numIndexTuples = index->tuples;
6665 669524 : if (numIndexTuples < 1.0)
6666 76404 : numIndexTuples = 1.0;
6667 :
6668 : /*
6669 : * Estimate the number of index pages that will be retrieved.
6670 : *
6671 : * We use the simplistic method of taking a pro-rata fraction of the total
6672 : * number of index pages. In effect, this counts only leaf pages and not
6673 : * any overhead such as index metapage or upper tree levels.
6674 : *
6675 : * In practice access to upper index levels is often nearly free because
6676 : * those tend to stay in cache under load; moreover, the cost involved is
6677 : * highly dependent on index type. We therefore ignore such costs here
6678 : * and leave it to the caller to add a suitable charge if needed.
6679 : */
6680 669524 : if (index->pages > 1 && index->tuples > 1)
6681 621732 : numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6682 : else
6683 47792 : numIndexPages = 1.0;
6684 :
6685 : /* fetch estimated page cost for tablespace containing index */
6686 669524 : get_tablespace_page_costs(index->reltablespace,
6687 : &spc_random_page_cost,
6688 : NULL);
6689 :
6690 : /*
6691 : * Now compute the disk access costs.
6692 : *
6693 : * The above calculations are all per-index-scan. However, if we are in a
6694 : * nestloop inner scan, we can expect the scan to be repeated (with
6695 : * different search keys) for each row of the outer relation. Likewise,
6696 : * ScalarArrayOpExpr quals result in multiple index scans. This creates
6697 : * the potential for cache effects to reduce the number of disk page
6698 : * fetches needed. We want to estimate the average per-scan I/O cost in
6699 : * the presence of caching.
6700 : *
6701 : * We use the Mackert-Lohman formula (see costsize.c for details) to
6702 : * estimate the total number of page fetches that occur. While this
6703 : * wasn't what it was designed for, it seems a reasonable model anyway.
6704 : * Note that we are counting pages not tuples anymore, so we take N = T =
6705 : * index size, as if there were one "tuple" per page.
6706 : */
6707 669524 : num_outer_scans = loop_count;
6708 669524 : num_scans = num_sa_scans * num_outer_scans;
6709 :
6710 669524 : if (num_scans > 1)
6711 : {
6712 : double pages_fetched;
6713 :
6714 : /* total page fetches ignoring cache effects */
6715 72646 : pages_fetched = numIndexPages * num_scans;
6716 :
6717 : /* use Mackert and Lohman formula to adjust for cache effects */
6718 72646 : pages_fetched = index_pages_fetched(pages_fetched,
6719 : index->pages,
6720 72646 : (double) index->pages,
6721 : root);
6722 :
6723 : /*
6724 : * Now compute the total disk access cost, and then report a pro-rated
6725 : * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6726 : * since that's internal to the indexscan.)
6727 : */
6728 72646 : indexTotalCost = (pages_fetched * spc_random_page_cost)
6729 : / num_outer_scans;
6730 : }
6731 : else
6732 : {
6733 : /*
6734 : * For a single index scan, we just charge spc_random_page_cost per
6735 : * page touched.
6736 : */
6737 596878 : indexTotalCost = numIndexPages * spc_random_page_cost;
6738 : }
6739 :
6740 : /*
6741 : * CPU cost: any complex expressions in the indexquals will need to be
6742 : * evaluated once at the start of the scan to reduce them to runtime keys
6743 : * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6744 : * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6745 : * indexqual operator. Because we have numIndexTuples as a per-scan
6746 : * number, we have to multiply by num_sa_scans to get the correct result
6747 : * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6748 : * ORDER BY expressions.
6749 : *
6750 : * Note: this neglects the possible costs of rechecking lossy operators.
6751 : * Detecting that that might be needed seems more expensive than it's
6752 : * worth, though, considering all the other inaccuracies here ...
6753 : */
6754 669524 : qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
6755 669524 : index_other_operands_eval_cost(root, indexOrderBys);
6756 669524 : qual_op_cost = cpu_operator_cost *
6757 669524 : (list_length(indexQuals) + list_length(indexOrderBys));
6758 :
6759 669524 : indexStartupCost = qual_arg_cost;
6760 669524 : indexTotalCost += qual_arg_cost;
6761 669524 : indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6762 :
6763 : /*
6764 : * Generic assumption about index correlation: there isn't any.
6765 : */
6766 669524 : indexCorrelation = 0.0;
6767 :
6768 : /*
6769 : * Return everything to caller.
6770 : */
6771 669524 : costs->indexStartupCost = indexStartupCost;
6772 669524 : costs->indexTotalCost = indexTotalCost;
6773 669524 : costs->indexSelectivity = indexSelectivity;
6774 669524 : costs->indexCorrelation = indexCorrelation;
6775 669524 : costs->numIndexPages = numIndexPages;
6776 669524 : costs->numIndexTuples = numIndexTuples;
6777 669524 : costs->spc_random_page_cost = spc_random_page_cost;
6778 669524 : costs->num_sa_scans = num_sa_scans;
6779 669524 : }
6780 :
6781 : /*
6782 : * If the index is partial, add its predicate to the given qual list.
6783 : *
6784 : * ANDing the index predicate with the explicitly given indexquals produces
6785 : * a more accurate idea of the index's selectivity. However, we need to be
6786 : * careful not to insert redundant clauses, because clauselist_selectivity()
6787 : * is easily fooled into computing a too-low selectivity estimate. Our
6788 : * approach is to add only the predicate clause(s) that cannot be proven to
6789 : * be implied by the given indexquals. This successfully handles cases such
6790 : * as a qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
6791 : * There are many other cases where we won't detect redundancy, leading to a
6792 : * too-low selectivity estimate, which will bias the system in favor of using
6793 : * partial indexes where possible. That is not necessarily bad though.
6794 : *
6795 : * Note that indexQuals contains RestrictInfo nodes while the indpred
6796 : * does not, so the output list will be mixed. This is OK for both
6797 : * predicate_implied_by() and clauselist_selectivity(), but might be
6798 : * problematic if the result were passed to other things.
6799 : */
6800 : List *
6801 1108718 : add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
6802 : {
6803 1108718 : List *predExtraQuals = NIL;
6804 : ListCell *lc;
6805 :
6806 1108718 : if (index->indpred == NIL)
6807 1106692 : return indexQuals;
6808 :
6809 4064 : foreach(lc, index->indpred)
6810 : {
6811 2038 : Node *predQual = (Node *) lfirst(lc);
6812 2038 : List *oneQual = list_make1(predQual);
6813 :
6814 2038 : if (!predicate_implied_by(oneQual, indexQuals, false))
6815 1836 : predExtraQuals = list_concat(predExtraQuals, oneQual);
6816 : }
6817 2026 : return list_concat(predExtraQuals, indexQuals);
6818 : }
6819 :
6820 :
6821 : void
6822 661334 : btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
6823 : Cost *indexStartupCost, Cost *indexTotalCost,
6824 : Selectivity *indexSelectivity, double *indexCorrelation,
6825 : double *indexPages)
6826 : {
6827 661334 : IndexOptInfo *index = path->indexinfo;
6828 661334 : GenericCosts costs = {0};
6829 : Oid relid;
6830 : AttrNumber colnum;
6831 661334 : VariableStatData vardata = {0};
6832 : double numIndexTuples;
6833 : Cost descentCost;
6834 : List *indexBoundQuals;
6835 : int indexcol;
6836 : bool eqQualHere;
6837 : bool found_saop;
6838 : bool found_is_null_op;
6839 : double num_sa_scans;
6840 : ListCell *lc;
6841 :
6842 : /*
6843 : * For a btree scan, only leading '=' quals plus inequality quals for the
6844 : * immediately next attribute contribute to index selectivity (these are
6845 : * the "boundary quals" that determine the starting and stopping points of
6846 : * the index scan). Additional quals can suppress visits to the heap, so
6847 : * it's OK to count them in indexSelectivity, but they should not count
6848 : * for estimating numIndexTuples. So we must examine the given indexquals
6849 : * to find out which ones count as boundary quals. We rely on the
6850 : * knowledge that they are given in index column order.
6851 : *
6852 : * For a RowCompareExpr, we consider only the first column, just as
6853 : * rowcomparesel() does.
6854 : *
6855 : * If there's a ScalarArrayOpExpr in the quals, we'll actually perform up
6856 : * to N index descents (not just one), but the ScalarArrayOpExpr's
6857 : * operator can be considered to act the same as it normally does.
6858 : */
6859 661334 : indexBoundQuals = NIL;
6860 661334 : indexcol = 0;
6861 661334 : eqQualHere = false;
6862 661334 : found_saop = false;
6863 661334 : found_is_null_op = false;
6864 661334 : num_sa_scans = 1;
6865 1140772 : foreach(lc, path->indexclauses)
6866 : {
6867 506690 : IndexClause *iclause = lfirst_node(IndexClause, lc);
6868 : ListCell *lc2;
6869 :
6870 506690 : if (indexcol != iclause->indexcol)
6871 : {
6872 : /* Beginning of a new column's quals */
6873 93102 : if (!eqQualHere)
6874 25940 : break; /* done if no '=' qual for indexcol */
6875 67162 : eqQualHere = false;
6876 67162 : indexcol++;
6877 67162 : if (indexcol != iclause->indexcol)
6878 1312 : break; /* no quals at all for indexcol */
6879 : }
6880 :
6881 : /* Examine each indexqual associated with this index clause */
6882 961548 : foreach(lc2, iclause->indexquals)
6883 : {
6884 482110 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6885 482110 : Expr *clause = rinfo->clause;
6886 482110 : Oid clause_op = InvalidOid;
6887 : int op_strategy;
6888 :
6889 482110 : if (IsA(clause, OpExpr))
6890 : {
6891 470776 : OpExpr *op = (OpExpr *) clause;
6892 :
6893 470776 : clause_op = op->opno;
6894 : }
6895 11334 : else if (IsA(clause, RowCompareExpr))
6896 : {
6897 300 : RowCompareExpr *rc = (RowCompareExpr *) clause;
6898 :
6899 300 : clause_op = linitial_oid(rc->opnos);
6900 : }
6901 11034 : else if (IsA(clause, ScalarArrayOpExpr))
6902 : {
6903 9248 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6904 9248 : Node *other_operand = (Node *) lsecond(saop->args);
6905 9248 : double alength = estimate_array_length(root, other_operand);
6906 :
6907 9248 : clause_op = saop->opno;
6908 9248 : found_saop = true;
6909 : /* estimate SA descents by indexBoundQuals only */
6910 9248 : if (alength > 1)
6911 9152 : num_sa_scans *= alength;
6912 : }
6913 1786 : else if (IsA(clause, NullTest))
6914 : {
6915 1786 : NullTest *nt = (NullTest *) clause;
6916 :
6917 1786 : if (nt->nulltesttype == IS_NULL)
6918 : {
6919 204 : found_is_null_op = true;
6920 : /* IS NULL is like = for selectivity purposes */
6921 204 : eqQualHere = true;
6922 : }
6923 : }
6924 : else
6925 0 : elog(ERROR, "unsupported indexqual type: %d",
6926 : (int) nodeTag(clause));
6927 :
6928 : /* check for equality operator */
6929 482110 : if (OidIsValid(clause_op))
6930 : {
6931 480324 : op_strategy = get_op_opfamily_strategy(clause_op,
6932 480324 : index->opfamily[indexcol]);
6933 : Assert(op_strategy != 0); /* not a member of opfamily?? */
6934 480324 : if (op_strategy == BTEqualStrategyNumber)
6935 455906 : eqQualHere = true;
6936 : }
6937 :
6938 482110 : indexBoundQuals = lappend(indexBoundQuals, rinfo);
6939 : }
6940 : }
6941 :
6942 : /*
6943 : * If index is unique and we found an '=' clause for each column, we can
6944 : * just assume numIndexTuples = 1 and skip the expensive
6945 : * clauselist_selectivity calculations. However, a ScalarArrayOp or
6946 : * NullTest invalidates that theory, even though it sets eqQualHere.
6947 : */
6948 661334 : if (index->unique &&
6949 544040 : indexcol == index->nkeycolumns - 1 &&
6950 229020 : eqQualHere &&
6951 229020 : !found_saop &&
6952 224074 : !found_is_null_op)
6953 224008 : numIndexTuples = 1.0;
6954 : else
6955 : {
6956 : List *selectivityQuals;
6957 : Selectivity btreeSelectivity;
6958 :
6959 : /*
6960 : * If the index is partial, AND the index predicate with the
6961 : * index-bound quals to produce a more accurate idea of the number of
6962 : * rows covered by the bound conditions.
6963 : */
6964 437326 : selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6965 :
6966 437326 : btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6967 437326 : index->rel->relid,
6968 : JOIN_INNER,
6969 : NULL);
6970 437326 : numIndexTuples = btreeSelectivity * index->rel->tuples;
6971 :
6972 : /*
6973 : * btree automatically combines individual ScalarArrayOpExpr primitive
6974 : * index scans whenever the tuples covered by the next set of array
6975 : * keys are close to tuples covered by the current set. That puts a
6976 : * natural ceiling on the worst case number of descents -- there
6977 : * cannot possibly be more than one descent per leaf page scanned.
6978 : *
6979 : * Clamp the number of descents to at most 1/3 the number of index
6980 : * pages. This avoids implausibly high estimates with low selectivity
6981 : * paths, where scans usually require only one or two descents. This
6982 : * is most likely to help when there are several SAOP clauses, where
6983 : * naively accepting the total number of distinct combinations of
6984 : * array elements as the number of descents would frequently lead to
6985 : * wild overestimates.
6986 : *
6987 : * We somewhat arbitrarily don't just make the cutoff the total number
6988 : * of leaf pages (we make it 1/3 the total number of pages instead) to
6989 : * give the btree code credit for its ability to continue on the leaf
6990 : * level with low selectivity scans.
6991 : */
6992 437326 : num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
6993 437326 : num_sa_scans = Max(num_sa_scans, 1);
6994 :
6995 : /*
6996 : * As in genericcostestimate(), we have to adjust for any
6997 : * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6998 : * to integer.
6999 : *
7000 : * It is tempting to make genericcostestimate behave as if SAOP
7001 : * clauses work in almost the same way as scalar operators during
7002 : * btree scans, making the top-level scan look like a continuous scan
7003 : * (as opposed to num_sa_scans-many primitive index scans). After
7004 : * all, btree scans mostly work like that at runtime. However, such a
7005 : * scheme would badly bias genericcostestimate's simplistic approach
7006 : * to calculating numIndexPages through prorating.
7007 : *
7008 : * Stick with the approach taken by non-native SAOP scans for now.
7009 : * genericcostestimate will use the Mackert-Lohman formula to
7010 : * compensate for repeat page fetches, even though that definitely
7011 : * won't happen during btree scans (not for leaf pages, at least).
7012 : * We're usually very pessimistic about the number of primitive index
7013 : * scans that will be required, but it's not clear how to do better.
7014 : */
7015 437326 : numIndexTuples = rint(numIndexTuples / num_sa_scans);
7016 : }
7017 :
7018 : /*
7019 : * Now do generic index cost estimation.
7020 : */
7021 661334 : costs.numIndexTuples = numIndexTuples;
7022 661334 : costs.num_sa_scans = num_sa_scans;
7023 :
7024 661334 : genericcostestimate(root, path, loop_count, &costs);
7025 :
7026 : /*
7027 : * Add a CPU-cost component to represent the costs of initial btree
7028 : * descent. We don't charge any I/O cost for touching upper btree levels,
7029 : * since they tend to stay in cache, but we still have to do about log2(N)
7030 : * comparisons to descend a btree of N leaf tuples. We charge one
7031 : * cpu_operator_cost per comparison.
7032 : *
7033 : * If there are ScalarArrayOpExprs, charge this once per estimated SA
7034 : * index descent. The ones after the first one are not startup cost so
7035 : * far as the overall plan goes, so just add them to "total" cost.
7036 : */
7037 661334 : if (index->tuples > 1) /* avoid computing log(0) */
7038 : {
7039 621964 : descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
7040 621964 : costs.indexStartupCost += descentCost;
7041 621964 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7042 : }
7043 :
7044 : /*
7045 : * Even though we're not charging I/O cost for touching upper btree pages,
7046 : * it's still reasonable to charge some CPU cost per page descended
7047 : * through. Moreover, if we had no such charge at all, bloated indexes
7048 : * would appear to have the same search cost as unbloated ones, at least
7049 : * in cases where only a single leaf page is expected to be visited. This
7050 : * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
7051 : * touched. The number of such pages is btree tree height plus one (ie,
7052 : * we charge for the leaf page too). As above, charge once per estimated
7053 : * SA index descent.
7054 : */
7055 661334 : descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7056 661334 : costs.indexStartupCost += descentCost;
7057 661334 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7058 :
7059 : /*
7060 : * If we can get an estimate of the first column's ordering correlation C
7061 : * from pg_statistic, estimate the index correlation as C for a
7062 : * single-column index, or C * 0.75 for multiple columns. (The idea here
7063 : * is that multiple columns dilute the importance of the first column's
7064 : * ordering, but don't negate it entirely. Before 8.0 we divided the
7065 : * correlation by the number of columns, but that seems too strong.)
7066 : */
7067 661334 : if (index->indexkeys[0] != 0)
7068 : {
7069 : /* Simple variable --- look to stats for the underlying table */
7070 659312 : RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
7071 :
7072 : Assert(rte->rtekind == RTE_RELATION);
7073 659312 : relid = rte->relid;
7074 : Assert(relid != InvalidOid);
7075 659312 : colnum = index->indexkeys[0];
7076 :
7077 659312 : if (get_relation_stats_hook &&
7078 0 : (*get_relation_stats_hook) (root, rte, colnum, &vardata))
7079 : {
7080 : /*
7081 : * The hook took control of acquiring a stats tuple. If it did
7082 : * supply a tuple, it'd better have supplied a freefunc.
7083 : */
7084 0 : if (HeapTupleIsValid(vardata.statsTuple) &&
7085 0 : !vardata.freefunc)
7086 0 : elog(ERROR, "no function provided to release variable stats with");
7087 : }
7088 : else
7089 : {
7090 659312 : vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7091 : ObjectIdGetDatum(relid),
7092 : Int16GetDatum(colnum),
7093 659312 : BoolGetDatum(rte->inh));
7094 659312 : vardata.freefunc = ReleaseSysCache;
7095 : }
7096 : }
7097 : else
7098 : {
7099 : /* Expression --- maybe there are stats for the index itself */
7100 2022 : relid = index->indexoid;
7101 2022 : colnum = 1;
7102 :
7103 2022 : if (get_index_stats_hook &&
7104 0 : (*get_index_stats_hook) (root, relid, colnum, &vardata))
7105 : {
7106 : /*
7107 : * The hook took control of acquiring a stats tuple. If it did
7108 : * supply a tuple, it'd better have supplied a freefunc.
7109 : */
7110 0 : if (HeapTupleIsValid(vardata.statsTuple) &&
7111 0 : !vardata.freefunc)
7112 0 : elog(ERROR, "no function provided to release variable stats with");
7113 : }
7114 : else
7115 : {
7116 2022 : vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7117 : ObjectIdGetDatum(relid),
7118 : Int16GetDatum(colnum),
7119 : BoolGetDatum(false));
7120 2022 : vardata.freefunc = ReleaseSysCache;
7121 : }
7122 : }
7123 :
7124 661334 : if (HeapTupleIsValid(vardata.statsTuple))
7125 : {
7126 : Oid sortop;
7127 : AttStatsSlot sslot;
7128 :
7129 492314 : sortop = get_opfamily_member(index->opfamily[0],
7130 492314 : index->opcintype[0],
7131 492314 : index->opcintype[0],
7132 : BTLessStrategyNumber);
7133 984628 : if (OidIsValid(sortop) &&
7134 492314 : get_attstatsslot(&sslot, vardata.statsTuple,
7135 : STATISTIC_KIND_CORRELATION, sortop,
7136 : ATTSTATSSLOT_NUMBERS))
7137 : {
7138 : double varCorrelation;
7139 :
7140 : Assert(sslot.nnumbers == 1);
7141 487024 : varCorrelation = sslot.numbers[0];
7142 :
7143 487024 : if (index->reverse_sort[0])
7144 0 : varCorrelation = -varCorrelation;
7145 :
7146 487024 : if (index->nkeycolumns > 1)
7147 162016 : costs.indexCorrelation = varCorrelation * 0.75;
7148 : else
7149 325008 : costs.indexCorrelation = varCorrelation;
7150 :
7151 487024 : free_attstatsslot(&sslot);
7152 : }
7153 : }
7154 :
7155 661334 : ReleaseVariableStats(vardata);
7156 :
7157 661334 : *indexStartupCost = costs.indexStartupCost;
7158 661334 : *indexTotalCost = costs.indexTotalCost;
7159 661334 : *indexSelectivity = costs.indexSelectivity;
7160 661334 : *indexCorrelation = costs.indexCorrelation;
7161 661334 : *indexPages = costs.numIndexPages;
7162 661334 : }
7163 :
7164 : void
7165 410 : hashcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7166 : Cost *indexStartupCost, Cost *indexTotalCost,
7167 : Selectivity *indexSelectivity, double *indexCorrelation,
7168 : double *indexPages)
7169 : {
7170 410 : GenericCosts costs = {0};
7171 :
7172 410 : genericcostestimate(root, path, loop_count, &costs);
7173 :
7174 : /*
7175 : * A hash index has no descent costs as such, since the index AM can go
7176 : * directly to the target bucket after computing the hash value. There
7177 : * are a couple of other hash-specific costs that we could conceivably add
7178 : * here, though:
7179 : *
7180 : * Ideally we'd charge spc_random_page_cost for each page in the target
7181 : * bucket, not just the numIndexPages pages that genericcostestimate
7182 : * thought we'd visit. However in most cases we don't know which bucket
7183 : * that will be. There's no point in considering the average bucket size
7184 : * because the hash AM makes sure that's always one page.
7185 : *
7186 : * Likewise, we could consider charging some CPU for each index tuple in
7187 : * the bucket, if we knew how many there were. But the per-tuple cost is
7188 : * just a hash value comparison, not a general datatype-dependent
7189 : * comparison, so any such charge ought to be quite a bit less than
7190 : * cpu_operator_cost; which makes it probably not worth worrying about.
7191 : *
7192 : * A bigger issue is that chance hash-value collisions will result in
7193 : * wasted probes into the heap. We don't currently attempt to model this
7194 : * cost on the grounds that it's rare, but maybe it's not rare enough.
7195 : * (Any fix for this ought to consider the generic lossy-operator problem,
7196 : * though; it's not entirely hash-specific.)
7197 : */
7198 :
7199 410 : *indexStartupCost = costs.indexStartupCost;
7200 410 : *indexTotalCost = costs.indexTotalCost;
7201 410 : *indexSelectivity = costs.indexSelectivity;
7202 410 : *indexCorrelation = costs.indexCorrelation;
7203 410 : *indexPages = costs.numIndexPages;
7204 410 : }
7205 :
7206 : void
7207 5184 : gistcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7208 : Cost *indexStartupCost, Cost *indexTotalCost,
7209 : Selectivity *indexSelectivity, double *indexCorrelation,
7210 : double *indexPages)
7211 : {
7212 5184 : IndexOptInfo *index = path->indexinfo;
7213 5184 : GenericCosts costs = {0};
7214 : Cost descentCost;
7215 :
7216 5184 : genericcostestimate(root, path, loop_count, &costs);
7217 :
7218 : /*
7219 : * We model index descent costs similarly to those for btree, but to do
7220 : * that we first need an idea of the tree height. We somewhat arbitrarily
7221 : * assume that the fanout is 100, meaning the tree height is at most
7222 : * log100(index->pages).
7223 : *
7224 : * Although this computation isn't really expensive enough to require
7225 : * caching, we might as well use index->tree_height to cache it.
7226 : */
7227 5184 : if (index->tree_height < 0) /* unknown? */
7228 : {
7229 5170 : if (index->pages > 1) /* avoid computing log(0) */
7230 2704 : index->tree_height = (int) (log(index->pages) / log(100.0));
7231 : else
7232 2466 : index->tree_height = 0;
7233 : }
7234 :
7235 : /*
7236 : * Add a CPU-cost component to represent the costs of initial descent. We
7237 : * just use log(N) here not log2(N) since the branching factor isn't
7238 : * necessarily two anyway. As for btree, charge once per SA scan.
7239 : */
7240 5184 : if (index->tuples > 1) /* avoid computing log(0) */
7241 : {
7242 5184 : descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7243 5184 : costs.indexStartupCost += descentCost;
7244 5184 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7245 : }
7246 :
7247 : /*
7248 : * Likewise add a per-page charge, calculated the same as for btrees.
7249 : */
7250 5184 : descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7251 5184 : costs.indexStartupCost += descentCost;
7252 5184 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7253 :
7254 5184 : *indexStartupCost = costs.indexStartupCost;
7255 5184 : *indexTotalCost = costs.indexTotalCost;
7256 5184 : *indexSelectivity = costs.indexSelectivity;
7257 5184 : *indexCorrelation = costs.indexCorrelation;
7258 5184 : *indexPages = costs.numIndexPages;
7259 5184 : }
7260 :
7261 : void
7262 1784 : spgcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7263 : Cost *indexStartupCost, Cost *indexTotalCost,
7264 : Selectivity *indexSelectivity, double *indexCorrelation,
7265 : double *indexPages)
7266 : {
7267 1784 : IndexOptInfo *index = path->indexinfo;
7268 1784 : GenericCosts costs = {0};
7269 : Cost descentCost;
7270 :
7271 1784 : genericcostestimate(root, path, loop_count, &costs);
7272 :
7273 : /*
7274 : * We model index descent costs similarly to those for btree, but to do
7275 : * that we first need an idea of the tree height. We somewhat arbitrarily
7276 : * assume that the fanout is 100, meaning the tree height is at most
7277 : * log100(index->pages).
7278 : *
7279 : * Although this computation isn't really expensive enough to require
7280 : * caching, we might as well use index->tree_height to cache it.
7281 : */
7282 1784 : if (index->tree_height < 0) /* unknown? */
7283 : {
7284 1778 : if (index->pages > 1) /* avoid computing log(0) */
7285 1778 : index->tree_height = (int) (log(index->pages) / log(100.0));
7286 : else
7287 0 : index->tree_height = 0;
7288 : }
7289 :
7290 : /*
7291 : * Add a CPU-cost component to represent the costs of initial descent. We
7292 : * just use log(N) here not log2(N) since the branching factor isn't
7293 : * necessarily two anyway. As for btree, charge once per SA scan.
7294 : */
7295 1784 : if (index->tuples > 1) /* avoid computing log(0) */
7296 : {
7297 1784 : descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7298 1784 : costs.indexStartupCost += descentCost;
7299 1784 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7300 : }
7301 :
7302 : /*
7303 : * Likewise add a per-page charge, calculated the same as for btrees.
7304 : */
7305 1784 : descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7306 1784 : costs.indexStartupCost += descentCost;
7307 1784 : costs.indexTotalCost += costs.num_sa_scans * descentCost;
7308 :
7309 1784 : *indexStartupCost = costs.indexStartupCost;
7310 1784 : *indexTotalCost = costs.indexTotalCost;
7311 1784 : *indexSelectivity = costs.indexSelectivity;
7312 1784 : *indexCorrelation = costs.indexCorrelation;
7313 1784 : *indexPages = costs.numIndexPages;
7314 1784 : }
7315 :
7316 :
7317 : /*
7318 : * Support routines for gincostestimate
7319 : */
7320 :
7321 : typedef struct
7322 : {
7323 : bool attHasFullScan[INDEX_MAX_KEYS];
7324 : bool attHasNormalScan[INDEX_MAX_KEYS];
7325 : double partialEntries;
7326 : double exactEntries;
7327 : double searchEntries;
7328 : double arrayScans;
7329 : } GinQualCounts;
7330 :
7331 : /*
7332 : * Estimate the number of index terms that need to be searched for while
7333 : * testing the given GIN query, and increment the counts in *counts
7334 : * appropriately. If the query is unsatisfiable, return false.
7335 : */
7336 : static bool
7337 2072 : gincost_pattern(IndexOptInfo *index, int indexcol,
7338 : Oid clause_op, Datum query,
7339 : GinQualCounts *counts)
7340 : {
7341 : FmgrInfo flinfo;
7342 : Oid extractProcOid;
7343 : Oid collation;
7344 : int strategy_op;
7345 : Oid lefttype,
7346 : righttype;
7347 2072 : int32 nentries = 0;
7348 2072 : bool *partial_matches = NULL;
7349 2072 : Pointer *extra_data = NULL;
7350 2072 : bool *nullFlags = NULL;
7351 2072 : int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
7352 : int32 i;
7353 :
7354 : Assert(indexcol < index->nkeycolumns);
7355 :
7356 : /*
7357 : * Get the operator's strategy number and declared input data types within
7358 : * the index opfamily. (We don't need the latter, but we use
7359 : * get_op_opfamily_properties because it will throw error if it fails to
7360 : * find a matching pg_amop entry.)
7361 : */
7362 2072 : get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
7363 : &strategy_op, &lefttype, &righttype);
7364 :
7365 : /*
7366 : * GIN always uses the "default" support functions, which are those with
7367 : * lefttype == righttype == the opclass' opcintype (see
7368 : * IndexSupportInitialize in relcache.c).
7369 : */
7370 2072 : extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
7371 2072 : index->opcintype[indexcol],
7372 2072 : index->opcintype[indexcol],
7373 : GIN_EXTRACTQUERY_PROC);
7374 :
7375 2072 : if (!OidIsValid(extractProcOid))
7376 : {
7377 : /* should not happen; throw same error as index_getprocinfo */
7378 0 : elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
7379 : GIN_EXTRACTQUERY_PROC, indexcol + 1,
7380 : get_rel_name(index->indexoid));
7381 : }
7382 :
7383 : /*
7384 : * Choose collation to pass to extractProc (should match initGinState).
7385 : */
7386 2072 : if (OidIsValid(index->indexcollations[indexcol]))
7387 364 : collation = index->indexcollations[indexcol];
7388 : else
7389 1708 : collation = DEFAULT_COLLATION_OID;
7390 :
7391 2072 : fmgr_info(extractProcOid, &flinfo);
7392 :
7393 2072 : set_fn_opclass_options(&flinfo, index->opclassoptions[indexcol]);
7394 :
7395 2072 : FunctionCall7Coll(&flinfo,
7396 : collation,
7397 : query,
7398 : PointerGetDatum(&nentries),
7399 : UInt16GetDatum(strategy_op),
7400 : PointerGetDatum(&partial_matches),
7401 : PointerGetDatum(&extra_data),
7402 : PointerGetDatum(&nullFlags),
7403 : PointerGetDatum(&searchMode));
7404 :
7405 2072 : if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
7406 : {
7407 : /* No match is possible */
7408 12 : return false;
7409 : }
7410 :
7411 8796 : for (i = 0; i < nentries; i++)
7412 : {
7413 : /*
7414 : * For partial match we haven't any information to estimate number of
7415 : * matched entries in index, so, we just estimate it as 100
7416 : */
7417 6736 : if (partial_matches && partial_matches[i])
7418 316 : counts->partialEntries += 100;
7419 : else
7420 6420 : counts->exactEntries++;
7421 :
7422 6736 : counts->searchEntries++;
7423 : }
7424 :
7425 2060 : if (searchMode == GIN_SEARCH_MODE_DEFAULT)
7426 : {
7427 1588 : counts->attHasNormalScan[indexcol] = true;
7428 : }
7429 472 : else if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
7430 : {
7431 : /* Treat "include empty" like an exact-match item */
7432 44 : counts->attHasNormalScan[indexcol] = true;
7433 44 : counts->exactEntries++;
7434 44 : counts->searchEntries++;
7435 : }
7436 : else
7437 : {
7438 : /* It's GIN_SEARCH_MODE_ALL */
7439 428 : counts->attHasFullScan[indexcol] = true;
7440 : }
7441 :
7442 2060 : return true;
7443 : }
7444 :
7445 : /*
7446 : * Estimate the number of index terms that need to be searched for while
7447 : * testing the given GIN index clause, and increment the counts in *counts
7448 : * appropriately. If the query is unsatisfiable, return false.
7449 : */
7450 : static bool
7451 2060 : gincost_opexpr(PlannerInfo *root,
7452 : IndexOptInfo *index,
7453 : int indexcol,
7454 : OpExpr *clause,
7455 : GinQualCounts *counts)
7456 : {
7457 2060 : Oid clause_op = clause->opno;
7458 2060 : Node *operand = (Node *) lsecond(clause->args);
7459 :
7460 : /* aggressively reduce to a constant, and look through relabeling */
7461 2060 : operand = estimate_expression_value(root, operand);
7462 :
7463 2060 : if (IsA(operand, RelabelType))
7464 0 : operand = (Node *) ((RelabelType *) operand)->arg;
7465 :
7466 : /*
7467 : * It's impossible to call extractQuery method for unknown operand. So
7468 : * unless operand is a Const we can't do much; just assume there will be
7469 : * one ordinary search entry from the operand at runtime.
7470 : */
7471 2060 : if (!IsA(operand, Const))
7472 : {
7473 0 : counts->exactEntries++;
7474 0 : counts->searchEntries++;
7475 0 : return true;
7476 : }
7477 :
7478 : /* If Const is null, there can be no matches */
7479 2060 : if (((Const *) operand)->constisnull)
7480 0 : return false;
7481 :
7482 : /* Otherwise, apply extractQuery and get the actual term counts */
7483 2060 : return gincost_pattern(index, indexcol, clause_op,
7484 : ((Const *) operand)->constvalue,
7485 : counts);
7486 : }
7487 :
7488 : /*
7489 : * Estimate the number of index terms that need to be searched for while
7490 : * testing the given GIN index clause, and increment the counts in *counts
7491 : * appropriately. If the query is unsatisfiable, return false.
7492 : *
7493 : * A ScalarArrayOpExpr will give rise to N separate indexscans at runtime,
7494 : * each of which involves one value from the RHS array, plus all the
7495 : * non-array quals (if any). To model this, we average the counts across
7496 : * the RHS elements, and add the averages to the counts in *counts (which
7497 : * correspond to per-indexscan costs). We also multiply counts->arrayScans
7498 : * by N, causing gincostestimate to scale up its estimates accordingly.
7499 : */
7500 : static bool
7501 6 : gincost_scalararrayopexpr(PlannerInfo *root,
7502 : IndexOptInfo *index,
7503 : int indexcol,
7504 : ScalarArrayOpExpr *clause,
7505 : double numIndexEntries,
7506 : GinQualCounts *counts)
7507 : {
7508 6 : Oid clause_op = clause->opno;
7509 6 : Node *rightop = (Node *) lsecond(clause->args);
7510 : ArrayType *arrayval;
7511 : int16 elmlen;
7512 : bool elmbyval;
7513 : char elmalign;
7514 : int numElems;
7515 : Datum *elemValues;
7516 : bool *elemNulls;
7517 : GinQualCounts arraycounts;
7518 6 : int numPossible = 0;
7519 : int i;
7520 :
7521 : Assert(clause->useOr);
7522 :
7523 : /* aggressively reduce to a constant, and look through relabeling */
7524 6 : rightop = estimate_expression_value(root, rightop);
7525 :
7526 6 : if (IsA(rightop, RelabelType))
7527 0 : rightop = (Node *) ((RelabelType *) rightop)->arg;
7528 :
7529 : /*
7530 : * It's impossible to call extractQuery method for unknown operand. So
7531 : * unless operand is a Const we can't do much; just assume there will be
7532 : * one ordinary search entry from each array entry at runtime, and fall
7533 : * back on a probably-bad estimate of the number of array entries.
7534 : */
7535 6 : if (!IsA(rightop, Const))
7536 : {
7537 0 : counts->exactEntries++;
7538 0 : counts->searchEntries++;
7539 0 : counts->arrayScans *= estimate_array_length(root, rightop);
7540 0 : return true;
7541 : }
7542 :
7543 : /* If Const is null, there can be no matches */
7544 6 : if (((Const *) rightop)->constisnull)
7545 0 : return false;
7546 :
7547 : /* Otherwise, extract the array elements and iterate over them */
7548 6 : arrayval = DatumGetArrayTypeP(((Const *) rightop)->constvalue);
7549 6 : get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
7550 : &elmlen, &elmbyval, &elmalign);
7551 6 : deconstruct_array(arrayval,
7552 : ARR_ELEMTYPE(arrayval),
7553 : elmlen, elmbyval, elmalign,
7554 : &elemValues, &elemNulls, &numElems);
7555 :
7556 6 : memset(&arraycounts, 0, sizeof(arraycounts));
7557 :
7558 18 : for (i = 0; i < numElems; i++)
7559 : {
7560 : GinQualCounts elemcounts;
7561 :
7562 : /* NULL can't match anything, so ignore, as the executor will */
7563 12 : if (elemNulls[i])
7564 0 : continue;
7565 :
7566 : /* Otherwise, apply extractQuery and get the actual term counts */
7567 12 : memset(&elemcounts, 0, sizeof(elemcounts));
7568 :
7569 12 : if (gincost_pattern(index, indexcol, clause_op, elemValues[i],
7570 : &elemcounts))
7571 : {
7572 : /* We ignore array elements that are unsatisfiable patterns */
7573 12 : numPossible++;
7574 :
7575 12 : if (elemcounts.attHasFullScan[indexcol] &&
7576 0 : !elemcounts.attHasNormalScan[indexcol])
7577 : {
7578 : /*
7579 : * Full index scan will be required. We treat this as if
7580 : * every key in the index had been listed in the query; is
7581 : * that reasonable?
7582 : */
7583 0 : elemcounts.partialEntries = 0;
7584 0 : elemcounts.exactEntries = numIndexEntries;
7585 0 : elemcounts.searchEntries = numIndexEntries;
7586 : }
7587 12 : arraycounts.partialEntries += elemcounts.partialEntries;
7588 12 : arraycounts.exactEntries += elemcounts.exactEntries;
7589 12 : arraycounts.searchEntries += elemcounts.searchEntries;
7590 : }
7591 : }
7592 :
7593 6 : if (numPossible == 0)
7594 : {
7595 : /* No satisfiable patterns in the array */
7596 0 : return false;
7597 : }
7598 :
7599 : /*
7600 : * Now add the averages to the global counts. This will give us an
7601 : * estimate of the average number of terms searched for in each indexscan,
7602 : * including contributions from both array and non-array quals.
7603 : */
7604 6 : counts->partialEntries += arraycounts.partialEntries / numPossible;
7605 6 : counts->exactEntries += arraycounts.exactEntries / numPossible;
7606 6 : counts->searchEntries += arraycounts.searchEntries / numPossible;
7607 :
7608 6 : counts->arrayScans *= numPossible;
7609 :
7610 6 : return true;
7611 : }
7612 :
7613 : /*
7614 : * GIN has search behavior completely different from other index types
7615 : */
7616 : void
7617 1868 : gincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
7618 : Cost *indexStartupCost, Cost *indexTotalCost,
7619 : Selectivity *indexSelectivity, double *indexCorrelation,
7620 : double *indexPages)
7621 : {
7622 1868 : IndexOptInfo *index = path->indexinfo;
7623 1868 : List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7624 : List *selectivityQuals;
7625 1868 : double numPages = index->pages,
7626 1868 : numTuples = index->tuples;
7627 : double numEntryPages,
7628 : numDataPages,
7629 : numPendingPages,
7630 : numEntries;
7631 : GinQualCounts counts;
7632 : bool matchPossible;
7633 : bool fullIndexScan;
7634 : double partialScale;
7635 : double entryPagesFetched,
7636 : dataPagesFetched,
7637 : dataPagesFetchedBySel;
7638 : double qual_op_cost,
7639 : qual_arg_cost,
7640 : spc_random_page_cost,
7641 : outer_scans;
7642 : Cost descentCost;
7643 : Relation indexRel;
7644 : GinStatsData ginStats;
7645 : ListCell *lc;
7646 : int i;
7647 :
7648 : /*
7649 : * Obtain statistical information from the meta page, if possible. Else
7650 : * set ginStats to zeroes, and we'll cope below.
7651 : */
7652 1868 : if (!index->hypothetical)
7653 : {
7654 : /* Lock should have already been obtained in plancat.c */
7655 1868 : indexRel = index_open(index->indexoid, NoLock);
7656 1868 : ginGetStats(indexRel, &ginStats);
7657 1868 : index_close(indexRel, NoLock);
7658 : }
7659 : else
7660 : {
7661 0 : memset(&ginStats, 0, sizeof(ginStats));
7662 : }
7663 :
7664 : /*
7665 : * Assuming we got valid (nonzero) stats at all, nPendingPages can be
7666 : * trusted, but the other fields are data as of the last VACUUM. We can
7667 : * scale them up to account for growth since then, but that method only
7668 : * goes so far; in the worst case, the stats might be for a completely
7669 : * empty index, and scaling them will produce pretty bogus numbers.
7670 : * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
7671 : * it's grown more than that, fall back to estimating things only from the
7672 : * assumed-accurate index size. But we'll trust nPendingPages in any case
7673 : * so long as it's not clearly insane, ie, more than the index size.
7674 : */
7675 1868 : if (ginStats.nPendingPages < numPages)
7676 1868 : numPendingPages = ginStats.nPendingPages;
7677 : else
7678 0 : numPendingPages = 0;
7679 :
7680 1868 : if (numPages > 0 && ginStats.nTotalPages <= numPages &&
7681 1868 : ginStats.nTotalPages > numPages / 4 &&
7682 1816 : ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
7683 1558 : {
7684 : /*
7685 : * OK, the stats seem close enough to sane to be trusted. But we
7686 : * still need to scale them by the ratio numPages / nTotalPages to
7687 : * account for growth since the last VACUUM.
7688 : */
7689 1558 : double scale = numPages / ginStats.nTotalPages;
7690 :
7691 1558 : numEntryPages = ceil(ginStats.nEntryPages * scale);
7692 1558 : numDataPages = ceil(ginStats.nDataPages * scale);
7693 1558 : numEntries = ceil(ginStats.nEntries * scale);
7694 : /* ensure we didn't round up too much */
7695 1558 : numEntryPages = Min(numEntryPages, numPages - numPendingPages);
7696 1558 : numDataPages = Min(numDataPages,
7697 : numPages - numPendingPages - numEntryPages);
7698 : }
7699 : else
7700 : {
7701 : /*
7702 : * We might get here because it's a hypothetical index, or an index
7703 : * created pre-9.1 and never vacuumed since upgrading (in which case
7704 : * its stats would read as zeroes), or just because it's grown too
7705 : * much since the last VACUUM for us to put our faith in scaling.
7706 : *
7707 : * Invent some plausible internal statistics based on the index page
7708 : * count (and clamp that to at least 10 pages, just in case). We
7709 : * estimate that 90% of the index is entry pages, and the rest is data
7710 : * pages. Estimate 100 entries per entry page; this is rather bogus
7711 : * since it'll depend on the size of the keys, but it's more robust
7712 : * than trying to predict the number of entries per heap tuple.
7713 : */
7714 310 : numPages = Max(numPages, 10);
7715 310 : numEntryPages = floor((numPages - numPendingPages) * 0.90);
7716 310 : numDataPages = numPages - numPendingPages - numEntryPages;
7717 310 : numEntries = floor(numEntryPages * 100);
7718 : }
7719 :
7720 : /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
7721 1868 : if (numEntries < 1)
7722 0 : numEntries = 1;
7723 :
7724 : /*
7725 : * If the index is partial, AND the index predicate with the index-bound
7726 : * quals to produce a more accurate idea of the number of rows covered by
7727 : * the bound conditions.
7728 : */
7729 1868 : selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7730 :
7731 : /* Estimate the fraction of main-table tuples that will be visited */
7732 3736 : *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7733 1868 : index->rel->relid,
7734 : JOIN_INNER,
7735 : NULL);
7736 :
7737 : /* fetch estimated page cost for tablespace containing index */
7738 1868 : get_tablespace_page_costs(index->reltablespace,
7739 : &spc_random_page_cost,
7740 : NULL);
7741 :
7742 : /*
7743 : * Generic assumption about index correlation: there isn't any.
7744 : */
7745 1868 : *indexCorrelation = 0.0;
7746 :
7747 : /*
7748 : * Examine quals to estimate number of search entries & partial matches
7749 : */
7750 1868 : memset(&counts, 0, sizeof(counts));
7751 1868 : counts.arrayScans = 1;
7752 1868 : matchPossible = true;
7753 :
7754 3934 : foreach(lc, path->indexclauses)
7755 : {
7756 2066 : IndexClause *iclause = lfirst_node(IndexClause, lc);
7757 : ListCell *lc2;
7758 :
7759 4120 : foreach(lc2, iclause->indexquals)
7760 : {
7761 2066 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7762 2066 : Expr *clause = rinfo->clause;
7763 :
7764 2066 : if (IsA(clause, OpExpr))
7765 : {
7766 2060 : matchPossible = gincost_opexpr(root,
7767 : index,
7768 2060 : iclause->indexcol,
7769 : (OpExpr *) clause,
7770 : &counts);
7771 2060 : if (!matchPossible)
7772 12 : break;
7773 : }
7774 6 : else if (IsA(clause, ScalarArrayOpExpr))
7775 : {
7776 6 : matchPossible = gincost_scalararrayopexpr(root,
7777 : index,
7778 6 : iclause->indexcol,
7779 : (ScalarArrayOpExpr *) clause,
7780 : numEntries,
7781 : &counts);
7782 6 : if (!matchPossible)
7783 0 : break;
7784 : }
7785 : else
7786 : {
7787 : /* shouldn't be anything else for a GIN index */
7788 0 : elog(ERROR, "unsupported GIN indexqual type: %d",
7789 : (int) nodeTag(clause));
7790 : }
7791 : }
7792 : }
7793 :
7794 : /* Fall out if there were any provably-unsatisfiable quals */
7795 1868 : if (!matchPossible)
7796 : {
7797 12 : *indexStartupCost = 0;
7798 12 : *indexTotalCost = 0;
7799 12 : *indexSelectivity = 0;
7800 12 : return;
7801 : }
7802 :
7803 : /*
7804 : * If attribute has a full scan and at the same time doesn't have normal
7805 : * scan, then we'll have to scan all non-null entries of that attribute.
7806 : * Currently, we don't have per-attribute statistics for GIN. Thus, we
7807 : * must assume the whole GIN index has to be scanned in this case.
7808 : */
7809 1856 : fullIndexScan = false;
7810 3602 : for (i = 0; i < index->nkeycolumns; i++)
7811 : {
7812 2084 : if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
7813 : {
7814 338 : fullIndexScan = true;
7815 338 : break;
7816 : }
7817 : }
7818 :
7819 1856 : if (fullIndexScan || indexQuals == NIL)
7820 : {
7821 : /*
7822 : * Full index scan will be required. We treat this as if every key in
7823 : * the index had been listed in the query; is that reasonable?
7824 : */
7825 338 : counts.partialEntries = 0;
7826 338 : counts.exactEntries = numEntries;
7827 338 : counts.searchEntries = numEntries;
7828 : }
7829 :
7830 : /* Will we have more than one iteration of a nestloop scan? */
7831 1856 : outer_scans = loop_count;
7832 :
7833 : /*
7834 : * Compute cost to begin scan, first of all, pay attention to pending
7835 : * list.
7836 : */
7837 1856 : entryPagesFetched = numPendingPages;
7838 :
7839 : /*
7840 : * Estimate number of entry pages read. We need to do
7841 : * counts.searchEntries searches. Use a power function as it should be,
7842 : * but tuples on leaf pages usually is much greater. Here we include all
7843 : * searches in entry tree, including search of first entry in partial
7844 : * match algorithm
7845 : */
7846 1856 : entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
7847 :
7848 : /*
7849 : * Add an estimate of entry pages read by partial match algorithm. It's a
7850 : * scan over leaf pages in entry tree. We haven't any useful stats here,
7851 : * so estimate it as proportion. Because counts.partialEntries is really
7852 : * pretty bogus (see code above), it's possible that it is more than
7853 : * numEntries; clamp the proportion to ensure sanity.
7854 : */
7855 1856 : partialScale = counts.partialEntries / numEntries;
7856 1856 : partialScale = Min(partialScale, 1.0);
7857 :
7858 1856 : entryPagesFetched += ceil(numEntryPages * partialScale);
7859 :
7860 : /*
7861 : * Partial match algorithm reads all data pages before doing actual scan,
7862 : * so it's a startup cost. Again, we haven't any useful stats here, so
7863 : * estimate it as proportion.
7864 : */
7865 1856 : dataPagesFetched = ceil(numDataPages * partialScale);
7866 :
7867 1856 : *indexStartupCost = 0;
7868 1856 : *indexTotalCost = 0;
7869 :
7870 : /*
7871 : * Add a CPU-cost component to represent the costs of initial entry btree
7872 : * descent. We don't charge any I/O cost for touching upper btree levels,
7873 : * since they tend to stay in cache, but we still have to do about log2(N)
7874 : * comparisons to descend a btree of N leaf tuples. We charge one
7875 : * cpu_operator_cost per comparison.
7876 : *
7877 : * If there are ScalarArrayOpExprs, charge this once per SA scan. The
7878 : * ones after the first one are not startup cost so far as the overall
7879 : * plan is concerned, so add them only to "total" cost.
7880 : */
7881 1856 : if (numEntries > 1) /* avoid computing log(0) */
7882 : {
7883 1856 : descentCost = ceil(log(numEntries) / log(2.0)) * cpu_operator_cost;
7884 1856 : *indexStartupCost += descentCost * counts.searchEntries;
7885 1856 : *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
7886 : }
7887 :
7888 : /*
7889 : * Add a cpu cost per entry-page fetched. This is not amortized over a
7890 : * loop.
7891 : */
7892 1856 : *indexStartupCost += entryPagesFetched * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7893 1856 : *indexTotalCost += entryPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7894 :
7895 : /*
7896 : * Add a cpu cost per data-page fetched. This is also not amortized over a
7897 : * loop. Since those are the data pages from the partial match algorithm,
7898 : * charge them as startup cost.
7899 : */
7900 1856 : *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * dataPagesFetched;
7901 :
7902 : /*
7903 : * Since we add the startup cost to the total cost later on, remove the
7904 : * initial arrayscan from the total.
7905 : */
7906 1856 : *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7907 :
7908 : /*
7909 : * Calculate cache effects if more than one scan due to nestloops or array
7910 : * quals. The result is pro-rated per nestloop scan, but the array qual
7911 : * factor shouldn't be pro-rated (compare genericcostestimate).
7912 : */
7913 1856 : if (outer_scans > 1 || counts.arrayScans > 1)
7914 : {
7915 6 : entryPagesFetched *= outer_scans * counts.arrayScans;
7916 6 : entryPagesFetched = index_pages_fetched(entryPagesFetched,
7917 : (BlockNumber) numEntryPages,
7918 : numEntryPages, root);
7919 6 : entryPagesFetched /= outer_scans;
7920 6 : dataPagesFetched *= outer_scans * counts.arrayScans;
7921 6 : dataPagesFetched = index_pages_fetched(dataPagesFetched,
7922 : (BlockNumber) numDataPages,
7923 : numDataPages, root);
7924 6 : dataPagesFetched /= outer_scans;
7925 : }
7926 :
7927 : /*
7928 : * Here we use random page cost because logically-close pages could be far
7929 : * apart on disk.
7930 : */
7931 1856 : *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
7932 :
7933 : /*
7934 : * Now compute the number of data pages fetched during the scan.
7935 : *
7936 : * We assume every entry to have the same number of items, and that there
7937 : * is no overlap between them. (XXX: tsvector and array opclasses collect
7938 : * statistics on the frequency of individual keys; it would be nice to use
7939 : * those here.)
7940 : */
7941 1856 : dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
7942 :
7943 : /*
7944 : * If there is a lot of overlap among the entries, in particular if one of
7945 : * the entries is very frequent, the above calculation can grossly
7946 : * under-estimate. As a simple cross-check, calculate a lower bound based
7947 : * on the overall selectivity of the quals. At a minimum, we must read
7948 : * one item pointer for each matching entry.
7949 : *
7950 : * The width of each item pointer varies, based on the level of
7951 : * compression. We don't have statistics on that, but an average of
7952 : * around 3 bytes per item is fairly typical.
7953 : */
7954 1856 : dataPagesFetchedBySel = ceil(*indexSelectivity *
7955 1856 : (numTuples / (BLCKSZ / 3)));
7956 1856 : if (dataPagesFetchedBySel > dataPagesFetched)
7957 1476 : dataPagesFetched = dataPagesFetchedBySel;
7958 :
7959 : /* Add one page cpu-cost to the startup cost */
7960 1856 : *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
7961 :
7962 : /*
7963 : * Add once again a CPU-cost for those data pages, before amortizing for
7964 : * cache.
7965 : */
7966 1856 : *indexTotalCost += dataPagesFetched * counts.arrayScans * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7967 :
7968 : /* Account for cache effects, the same as above */
7969 1856 : if (outer_scans > 1 || counts.arrayScans > 1)
7970 : {
7971 6 : dataPagesFetched *= outer_scans * counts.arrayScans;
7972 6 : dataPagesFetched = index_pages_fetched(dataPagesFetched,
7973 : (BlockNumber) numDataPages,
7974 : numDataPages, root);
7975 6 : dataPagesFetched /= outer_scans;
7976 : }
7977 :
7978 : /* And apply random_page_cost as the cost per page */
7979 1856 : *indexTotalCost += *indexStartupCost +
7980 1856 : dataPagesFetched * spc_random_page_cost;
7981 :
7982 : /*
7983 : * Add on index qual eval costs, much as in genericcostestimate. We charge
7984 : * cpu but we can disregard indexorderbys, since GIN doesn't support
7985 : * those.
7986 : */
7987 1856 : qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7988 1856 : qual_op_cost = cpu_operator_cost * list_length(indexQuals);
7989 :
7990 1856 : *indexStartupCost += qual_arg_cost;
7991 1856 : *indexTotalCost += qual_arg_cost;
7992 :
7993 : /*
7994 : * Add a cpu cost per search entry, corresponding to the actual visited
7995 : * entries.
7996 : */
7997 1856 : *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
7998 : /* Now add a cpu cost per tuple in the posting lists / trees */
7999 1856 : *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
8000 1856 : *indexPages = dataPagesFetched;
8001 : }
8002 :
8003 : /*
8004 : * BRIN has search behavior completely different from other index types
8005 : */
8006 : void
8007 10730 : brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
8008 : Cost *indexStartupCost, Cost *indexTotalCost,
8009 : Selectivity *indexSelectivity, double *indexCorrelation,
8010 : double *indexPages)
8011 : {
8012 10730 : IndexOptInfo *index = path->indexinfo;
8013 10730 : List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
8014 10730 : double numPages = index->pages;
8015 10730 : RelOptInfo *baserel = index->rel;
8016 10730 : RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
8017 : Cost spc_seq_page_cost;
8018 : Cost spc_random_page_cost;
8019 : double qual_arg_cost;
8020 : double qualSelectivity;
8021 : BrinStatsData statsData;
8022 : double indexRanges;
8023 : double minimalRanges;
8024 : double estimatedRanges;
8025 : double selec;
8026 : Relation indexRel;
8027 : ListCell *l;
8028 : VariableStatData vardata;
8029 :
8030 : Assert(rte->rtekind == RTE_RELATION);
8031 :
8032 : /* fetch estimated page cost for the tablespace containing the index */
8033 10730 : get_tablespace_page_costs(index->reltablespace,
8034 : &spc_random_page_cost,
8035 : &spc_seq_page_cost);
8036 :
8037 : /*
8038 : * Obtain some data from the index itself, if possible. Otherwise invent
8039 : * some plausible internal statistics based on the relation page count.
8040 : */
8041 10730 : if (!index->hypothetical)
8042 : {
8043 : /*
8044 : * A lock should have already been obtained on the index in plancat.c.
8045 : */
8046 10730 : indexRel = index_open(index->indexoid, NoLock);
8047 10730 : brinGetStats(indexRel, &statsData);
8048 10730 : index_close(indexRel, NoLock);
8049 :
8050 : /* work out the actual number of ranges in the index */
8051 10730 : indexRanges = Max(ceil((double) baserel->pages /
8052 : statsData.pagesPerRange), 1.0);
8053 : }
8054 : else
8055 : {
8056 : /*
8057 : * Assume default number of pages per range, and estimate the number
8058 : * of ranges based on that.
8059 : */
8060 0 : indexRanges = Max(ceil((double) baserel->pages /
8061 : BRIN_DEFAULT_PAGES_PER_RANGE), 1.0);
8062 :
8063 0 : statsData.pagesPerRange = BRIN_DEFAULT_PAGES_PER_RANGE;
8064 0 : statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
8065 : }
8066 :
8067 : /*
8068 : * Compute index correlation
8069 : *
8070 : * Because we can use all index quals equally when scanning, we can use
8071 : * the largest correlation (in absolute value) among columns used by the
8072 : * query. Start at zero, the worst possible case. If we cannot find any
8073 : * correlation statistics, we will keep it as 0.
8074 : */
8075 10730 : *indexCorrelation = 0;
8076 :
8077 21462 : foreach(l, path->indexclauses)
8078 : {
8079 10732 : IndexClause *iclause = lfirst_node(IndexClause, l);
8080 10732 : AttrNumber attnum = index->indexkeys[iclause->indexcol];
8081 :
8082 : /* attempt to lookup stats in relation for this index column */
8083 10732 : if (attnum != 0)
8084 : {
8085 : /* Simple variable -- look to stats for the underlying table */
8086 10732 : if (get_relation_stats_hook &&
8087 0 : (*get_relation_stats_hook) (root, rte, attnum, &vardata))
8088 : {
8089 : /*
8090 : * The hook took control of acquiring a stats tuple. If it
8091 : * did supply a tuple, it'd better have supplied a freefunc.
8092 : */
8093 0 : if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
8094 0 : elog(ERROR,
8095 : "no function provided to release variable stats with");
8096 : }
8097 : else
8098 : {
8099 10732 : vardata.statsTuple =
8100 10732 : SearchSysCache3(STATRELATTINH,
8101 : ObjectIdGetDatum(rte->relid),
8102 : Int16GetDatum(attnum),
8103 : BoolGetDatum(false));
8104 10732 : vardata.freefunc = ReleaseSysCache;
8105 : }
8106 : }
8107 : else
8108 : {
8109 : /*
8110 : * Looks like we've found an expression column in the index. Let's
8111 : * see if there's any stats for it.
8112 : */
8113 :
8114 : /* get the attnum from the 0-based index. */
8115 0 : attnum = iclause->indexcol + 1;
8116 :
8117 0 : if (get_index_stats_hook &&
8118 0 : (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
8119 : {
8120 : /*
8121 : * The hook took control of acquiring a stats tuple. If it
8122 : * did supply a tuple, it'd better have supplied a freefunc.
8123 : */
8124 0 : if (HeapTupleIsValid(vardata.statsTuple) &&
8125 0 : !vardata.freefunc)
8126 0 : elog(ERROR, "no function provided to release variable stats with");
8127 : }
8128 : else
8129 : {
8130 0 : vardata.statsTuple = SearchSysCache3(STATRELATTINH,
8131 : ObjectIdGetDatum(index->indexoid),
8132 : Int16GetDatum(attnum),
8133 : BoolGetDatum(false));
8134 0 : vardata.freefunc = ReleaseSysCache;
8135 : }
8136 : }
8137 :
8138 10732 : if (HeapTupleIsValid(vardata.statsTuple))
8139 : {
8140 : AttStatsSlot sslot;
8141 :
8142 36 : if (get_attstatsslot(&sslot, vardata.statsTuple,
8143 : STATISTIC_KIND_CORRELATION, InvalidOid,
8144 : ATTSTATSSLOT_NUMBERS))
8145 : {
8146 36 : double varCorrelation = 0.0;
8147 :
8148 36 : if (sslot.nnumbers > 0)
8149 36 : varCorrelation = fabs(sslot.numbers[0]);
8150 :
8151 36 : if (varCorrelation > *indexCorrelation)
8152 36 : *indexCorrelation = varCorrelation;
8153 :
8154 36 : free_attstatsslot(&sslot);
8155 : }
8156 : }
8157 :
8158 10732 : ReleaseVariableStats(vardata);
8159 : }
8160 :
8161 10730 : qualSelectivity = clauselist_selectivity(root, indexQuals,
8162 10730 : baserel->relid,
8163 : JOIN_INNER, NULL);
8164 :
8165 : /*
8166 : * Now calculate the minimum possible ranges we could match with if all of
8167 : * the rows were in the perfect order in the table's heap.
8168 : */
8169 10730 : minimalRanges = ceil(indexRanges * qualSelectivity);
8170 :
8171 : /*
8172 : * Now estimate the number of ranges that we'll touch by using the
8173 : * indexCorrelation from the stats. Careful not to divide by zero (note
8174 : * we're using the absolute value of the correlation).
8175 : */
8176 10730 : if (*indexCorrelation < 1.0e-10)
8177 10694 : estimatedRanges = indexRanges;
8178 : else
8179 36 : estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8180 :
8181 : /* we expect to visit this portion of the table */
8182 10730 : selec = estimatedRanges / indexRanges;
8183 :
8184 10730 : CLAMP_PROBABILITY(selec);
8185 :
8186 10730 : *indexSelectivity = selec;
8187 :
8188 : /*
8189 : * Compute the index qual costs, much as in genericcostestimate, to add to
8190 : * the index costs. We can disregard indexorderbys, since BRIN doesn't
8191 : * support those.
8192 : */
8193 10730 : qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
8194 :
8195 : /*
8196 : * Compute the startup cost as the cost to read the whole revmap
8197 : * sequentially, including the cost to execute the index quals.
8198 : */
8199 10730 : *indexStartupCost =
8200 10730 : spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8201 10730 : *indexStartupCost += qual_arg_cost;
8202 :
8203 : /*
8204 : * To read a BRIN index there might be a bit of back and forth over
8205 : * regular pages, as revmap might point to them out of sequential order;
8206 : * calculate the total cost as reading the whole index in random order.
8207 : */
8208 10730 : *indexTotalCost = *indexStartupCost +
8209 10730 : spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8210 :
8211 : /*
8212 : * Charge a small amount per range tuple which we expect to match to. This
8213 : * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8214 : * will set a bit for each page in the range when we find a matching
8215 : * range, so we must multiply the charge by the number of pages in the
8216 : * range.
8217 : */
8218 10730 : *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8219 10730 : statsData.pagesPerRange;
8220 :
8221 10730 : *indexPages = index->pages;
8222 10730 : }
|