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