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