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