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