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