Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * costsize.c
4 : : * Routines to compute (and set) relation sizes and path costs
5 : : *
6 : : * Path costs are measured in arbitrary units established by these basic
7 : : * parameters:
8 : : *
9 : : * seq_page_cost Cost of a sequential page fetch
10 : : * random_page_cost Cost of a non-sequential page fetch
11 : : * cpu_tuple_cost Cost of typical CPU time to process a tuple
12 : : * cpu_index_tuple_cost Cost of typical CPU time to process an index tuple
13 : : * cpu_operator_cost Cost of CPU time to execute an operator or function
14 : : * parallel_tuple_cost Cost of CPU time to pass a tuple from worker to leader backend
15 : : * parallel_setup_cost Cost of setting up shared memory for parallelism
16 : : *
17 : : * We expect that the kernel will typically do some amount of read-ahead
18 : : * optimization; this in conjunction with seek costs means that seq_page_cost
19 : : * is normally considerably less than random_page_cost. (However, if the
20 : : * database is fully cached in RAM, it is reasonable to set them equal.)
21 : : *
22 : : * We also use a rough estimate "effective_cache_size" of the number of
23 : : * disk pages in Postgres + OS-level disk cache. (We can't simply use
24 : : * NBuffers for this purpose because that would ignore the effects of
25 : : * the kernel's disk cache.)
26 : : *
27 : : * Obviously, taking constants for these values is an oversimplification,
28 : : * but it's tough enough to get any useful estimates even at this level of
29 : : * detail. Note that all of these parameters are user-settable, in case
30 : : * the default values are drastically off for a particular platform.
31 : : *
32 : : * seq_page_cost and random_page_cost can also be overridden for an individual
33 : : * tablespace, in case some data is on a fast disk and other data is on a slow
34 : : * disk. Per-tablespace overrides never apply to temporary work files such as
35 : : * an external sort or a materialize node that overflows work_mem.
36 : : *
37 : : * We compute two separate costs for each path:
38 : : * total_cost: total estimated cost to fetch all tuples
39 : : * startup_cost: cost that is expended before first tuple is fetched
40 : : * In some scenarios, such as when there is a LIMIT or we are implementing
41 : : * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
42 : : * path's result. A caller can estimate the cost of fetching a partial
43 : : * result by interpolating between startup_cost and total_cost. In detail:
44 : : * actual_cost = startup_cost +
45 : : * (total_cost - startup_cost) * tuples_to_fetch / path->rows;
46 : : * Note that a base relation's rows count (and, by extension, plan_rows for
47 : : * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
48 : : * that this equation works properly. (Note: while path->rows is never zero
49 : : * for ordinary relations, it is zero for paths for provably-empty relations,
50 : : * so beware of division-by-zero.) The LIMIT is applied as a top-level
51 : : * plan node.
52 : : *
53 : : * Each path stores the total number of disabled nodes that exist at or
54 : : * below that point in the plan tree. This is regarded as a component of
55 : : * the cost, and paths with fewer disabled nodes should be regarded as
56 : : * cheaper than those with more. Disabled nodes occur when the user sets
57 : : * a GUC like enable_seqscan=false. We can't necessarily respect such a
58 : : * setting in every part of the plan tree, but we want to respect in as many
59 : : * parts of the plan tree as possible. Simpler schemes like storing a Boolean
60 : : * here rather than a count fail to do that. We used to disable nodes by
61 : : * adding a large constant to the startup cost, but that distorted planning
62 : : * in other ways.
63 : : *
64 : : * For largely historical reasons, most of the routines in this module use
65 : : * the passed result Path only to store their results (rows, startup_cost and
66 : : * total_cost) into. All the input data they need is passed as separate
67 : : * parameters, even though much of it could be extracted from the Path.
68 : : * An exception is made for the cost_XXXjoin() routines, which expect all
69 : : * the other fields of the passed XXXPath to be filled in, and similarly
70 : : * cost_index() assumes the passed IndexPath is valid except for its output
71 : : * values.
72 : : *
73 : : *
74 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
75 : : * Portions Copyright (c) 1994, Regents of the University of California
76 : : *
77 : : * IDENTIFICATION
78 : : * src/backend/optimizer/path/costsize.c
79 : : *
80 : : *-------------------------------------------------------------------------
81 : : */
82 : :
83 : : #include "postgres.h"
84 : :
85 : : #include <limits.h>
86 : : #include <math.h>
87 : :
88 : : #include "access/amapi.h"
89 : : #include "access/htup_details.h"
90 : : #include "access/tsmapi.h"
91 : : #include "executor/executor.h"
92 : : #include "executor/nodeAgg.h"
93 : : #include "executor/nodeHash.h"
94 : : #include "executor/nodeMemoize.h"
95 : : #include "miscadmin.h"
96 : : #include "nodes/makefuncs.h"
97 : : #include "nodes/nodeFuncs.h"
98 : : #include "optimizer/clauses.h"
99 : : #include "optimizer/cost.h"
100 : : #include "optimizer/optimizer.h"
101 : : #include "optimizer/pathnode.h"
102 : : #include "optimizer/paths.h"
103 : : #include "optimizer/placeholder.h"
104 : : #include "optimizer/plancat.h"
105 : : #include "optimizer/restrictinfo.h"
106 : : #include "parser/parsetree.h"
107 : : #include "utils/lsyscache.h"
108 : : #include "utils/selfuncs.h"
109 : : #include "utils/spccache.h"
110 : : #include "utils/tuplesort.h"
111 : :
112 : :
113 : : #define LOG2(x) (log(x) / 0.693147180559945)
114 : :
115 : : /*
116 : : * Append and MergeAppend nodes are less expensive than some other operations
117 : : * which use cpu_tuple_cost; instead of adding a separate GUC, estimate the
118 : : * per-tuple cost as cpu_tuple_cost multiplied by this value.
119 : : */
120 : : #define APPEND_CPU_COST_MULTIPLIER 0.5
121 : :
122 : : /*
123 : : * Maximum value for row estimates. We cap row estimates to this to help
124 : : * ensure that costs based on these estimates remain within the range of what
125 : : * double can represent. add_path() wouldn't act sanely given infinite or NaN
126 : : * cost values.
127 : : */
128 : : #define MAXIMUM_ROWCOUNT 1e100
129 : :
130 : : double seq_page_cost = DEFAULT_SEQ_PAGE_COST;
131 : : double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
132 : : double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
133 : : double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
134 : : double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
135 : : double parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST;
136 : : double parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST;
137 : : double recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR;
138 : :
139 : : int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
140 : :
141 : : Cost disable_cost = 1.0e10;
142 : :
143 : : int max_parallel_workers_per_gather = 2;
144 : :
145 : : bool enable_seqscan = true;
146 : : bool enable_indexscan = true;
147 : : bool enable_indexonlyscan = true;
148 : : bool enable_bitmapscan = true;
149 : : bool enable_tidscan = true;
150 : : bool enable_sort = true;
151 : : bool enable_incremental_sort = true;
152 : : bool enable_hashagg = true;
153 : : bool enable_nestloop = true;
154 : : bool enable_material = true;
155 : : bool enable_memoize = true;
156 : : bool enable_mergejoin = true;
157 : : bool enable_hashjoin = true;
158 : : bool enable_gathermerge = true;
159 : : bool enable_partitionwise_join = false;
160 : : bool enable_partitionwise_aggregate = false;
161 : : bool enable_parallel_append = true;
162 : : bool enable_parallel_hash = true;
163 : : bool enable_partition_pruning = true;
164 : : bool enable_presorted_aggregate = true;
165 : : bool enable_async_append = true;
166 : :
167 : : typedef struct
168 : : {
169 : : PlannerInfo *root;
170 : : QualCost total;
171 : : } cost_qual_eval_context;
172 : :
173 : : static List *extract_nonindex_conditions(List *qual_clauses, List *indexclauses);
174 : : static MergeScanSelCache *cached_scansel(PlannerInfo *root,
175 : : RestrictInfo *rinfo,
176 : : PathKey *pathkey);
177 : : static void cost_rescan(PlannerInfo *root, Path *path,
178 : : Cost *rescan_startup_cost, Cost *rescan_total_cost);
179 : : static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
180 : : static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
181 : : ParamPathInfo *param_info,
182 : : QualCost *qpqual_cost);
183 : : static bool has_indexed_join_quals(NestPath *path);
184 : : static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
185 : : List *quals);
186 : : static double calc_joinrel_size_estimate(PlannerInfo *root,
187 : : RelOptInfo *joinrel,
188 : : RelOptInfo *outer_rel,
189 : : RelOptInfo *inner_rel,
190 : : double outer_rows,
191 : : double inner_rows,
192 : : SpecialJoinInfo *sjinfo,
193 : : List *restrictlist);
194 : : static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root,
195 : : Relids outer_relids,
196 : : Relids inner_relids,
197 : : SpecialJoinInfo *sjinfo,
198 : : List **restrictlist);
199 : : static Cost append_nonpartial_cost(List *subpaths, int numpaths,
200 : : int parallel_workers);
201 : : static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
202 : : static int32 get_expr_width(PlannerInfo *root, const Node *expr);
203 : : static double relation_byte_size(double tuples, int width);
204 : : static double page_size(double tuples, int width);
205 : : static double get_parallel_divisor(Path *path);
206 : :
207 : :
208 : : /*
209 : : * clamp_row_est
210 : : * Force a row-count estimate to a sane value.
211 : : */
212 : : double
213 : 2972748 : clamp_row_est(double nrows)
214 : : {
215 : : /*
216 : : * Avoid infinite and NaN row estimates. Costs derived from such values
217 : : * are going to be useless. Also force the estimate to be at least one
218 : : * row, to make explain output look better and to avoid possible
219 : : * divide-by-zero when interpolating costs. Make it an integer, too.
220 : : */
221 [ + + - + : 2972748 : if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
+ + + - ]
222 : 3963664 : nrows = MAXIMUM_ROWCOUNT;
223 [ + + ]: 990916 : else if (nrows <= 1.0)
224 : 290807 : nrows = 1.0;
225 : : else
226 : 700109 : nrows = rint(nrows);
227 : :
228 : 990916 : return nrows;
229 : : }
230 : :
231 : : /*
232 : : * clamp_width_est
233 : : * Force a tuple-width estimate to a sane value.
234 : : *
235 : : * The planner represents datatype width and tuple width estimates as int32.
236 : : * When summing column width estimates to create a tuple width estimate,
237 : : * it's possible to reach integer overflow in edge cases. To ensure sane
238 : : * behavior, we form such sums in int64 arithmetic and then apply this routine
239 : : * to clamp to int32 range.
240 : : */
241 : : int32
242 : 194517 : clamp_width_est(int64 tuple_width)
243 : : {
244 : : /*
245 : : * Anything more than MaxAllocSize is clearly bogus, since we could not
246 : : * create a tuple that large.
247 : : */
248 [ - + ]: 194517 : if (tuple_width > MaxAllocSize)
249 : 0 : return (int32) MaxAllocSize;
250 : :
251 : : /*
252 : : * Unlike clamp_row_est, we just Assert that the value isn't negative,
253 : : * rather than masking such errors.
254 : : */
255 [ + - ]: 194517 : Assert(tuple_width >= 0);
256 : :
257 : 194517 : return (int32) tuple_width;
258 : 194517 : }
259 : :
260 : :
261 : : /*
262 : : * cost_seqscan
263 : : * Determines and returns the cost of scanning a relation sequentially.
264 : : *
265 : : * 'baserel' is the relation to be scanned
266 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
267 : : */
268 : : void
269 : 47397 : cost_seqscan(Path *path, PlannerInfo *root,
270 : : RelOptInfo *baserel, ParamPathInfo *param_info)
271 : : {
272 : 47397 : Cost startup_cost = 0;
273 : 47397 : Cost cpu_run_cost;
274 : 47397 : Cost disk_run_cost;
275 : 47397 : double spc_seq_page_cost;
276 : 47397 : QualCost qpqual_cost;
277 : 47397 : Cost cpu_per_tuple;
278 : 47397 : uint64 enable_mask = PGS_SEQSCAN;
279 : :
280 : : /* Should only be applied to base relations */
281 [ + - ]: 47397 : Assert(baserel->relid > 0);
282 [ + - ]: 47397 : Assert(baserel->rtekind == RTE_RELATION);
283 : :
284 : : /* Mark the path with the correct row estimate */
285 [ + + ]: 47397 : if (param_info)
286 : 139 : path->rows = param_info->ppi_rows;
287 : : else
288 : 47258 : path->rows = baserel->rows;
289 : :
290 : : /* fetch estimated page cost for tablespace containing table */
291 : 47397 : get_tablespace_page_costs(baserel->reltablespace,
292 : : NULL,
293 : : &spc_seq_page_cost);
294 : :
295 : : /*
296 : : * disk costs
297 : : */
298 : 47397 : disk_run_cost = spc_seq_page_cost * baserel->pages;
299 : :
300 : : /* CPU costs */
301 : 47397 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
302 : :
303 : 47397 : startup_cost += qpqual_cost.startup;
304 : 47397 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
305 : 47397 : cpu_run_cost = cpu_per_tuple * baserel->tuples;
306 : : /* tlist eval costs are paid per output row, not per tuple scanned */
307 : 47397 : startup_cost += path->pathtarget->cost.startup;
308 : 47397 : cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
309 : :
310 : : /* Adjust costing for parallelism, if used. */
311 [ + + ]: 47397 : if (path->parallel_workers > 0)
312 : : {
313 : 4206 : double parallel_divisor = get_parallel_divisor(path);
314 : :
315 : : /* The CPU cost is divided among all the workers. */
316 : 4206 : cpu_run_cost /= parallel_divisor;
317 : :
318 : : /*
319 : : * It may be possible to amortize some of the I/O cost, but probably
320 : : * not very much, because most operating systems already do aggressive
321 : : * prefetching. For now, we assume that the disk run cost can't be
322 : : * amortized at all.
323 : : */
324 : :
325 : : /*
326 : : * In the case of a parallel plan, the row count needs to represent
327 : : * the number of tuples processed per worker.
328 : : */
329 : 4206 : path->rows = clamp_row_est(path->rows / parallel_divisor);
330 : 4206 : }
331 : : else
332 : 43191 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
333 : :
334 : 47397 : path->disabled_nodes =
335 : 47397 : (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
336 : 47397 : path->startup_cost = startup_cost;
337 : 47397 : path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
338 : 47397 : }
339 : :
340 : : /*
341 : : * cost_samplescan
342 : : * Determines and returns the cost of scanning a relation using sampling.
343 : : *
344 : : * 'baserel' is the relation to be scanned
345 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
346 : : */
347 : : void
348 : 45 : cost_samplescan(Path *path, PlannerInfo *root,
349 : : RelOptInfo *baserel, ParamPathInfo *param_info)
350 : : {
351 : 45 : Cost startup_cost = 0;
352 : 45 : Cost run_cost = 0;
353 : 45 : RangeTblEntry *rte;
354 : 45 : TableSampleClause *tsc;
355 : 45 : TsmRoutine *tsm;
356 : 45 : double spc_seq_page_cost,
357 : : spc_random_page_cost,
358 : : spc_page_cost;
359 : 45 : QualCost qpqual_cost;
360 : 45 : Cost cpu_per_tuple;
361 : 45 : uint64 enable_mask = 0;
362 : :
363 : : /* Should only be applied to base relations with tablesample clauses */
364 [ + - ]: 45 : Assert(baserel->relid > 0);
365 [ + - ]: 45 : rte = planner_rt_fetch(baserel->relid, root);
366 [ + - ]: 45 : Assert(rte->rtekind == RTE_RELATION);
367 : 45 : tsc = rte->tablesample;
368 [ + - ]: 45 : Assert(tsc != NULL);
369 : 45 : tsm = GetTsmRoutine(tsc->tsmhandler);
370 : :
371 : : /* Mark the path with the correct row estimate */
372 [ + + ]: 45 : if (param_info)
373 : 12 : path->rows = param_info->ppi_rows;
374 : : else
375 : 33 : path->rows = baserel->rows;
376 : :
377 : : /* fetch estimated page cost for tablespace containing table */
378 : 45 : get_tablespace_page_costs(baserel->reltablespace,
379 : : &spc_random_page_cost,
380 : : &spc_seq_page_cost);
381 : :
382 : : /* if NextSampleBlock is used, assume random access, else sequential */
383 [ + + ]: 45 : spc_page_cost = (tsm->NextSampleBlock != NULL) ?
384 : 45 : spc_random_page_cost : spc_seq_page_cost;
385 : :
386 : : /*
387 : : * disk costs (recall that baserel->pages has already been set to the
388 : : * number of pages the sampling method will visit)
389 : : */
390 : 45 : run_cost += spc_page_cost * baserel->pages;
391 : :
392 : : /*
393 : : * CPU costs (recall that baserel->tuples has already been set to the
394 : : * number of tuples the sampling method will select). Note that we ignore
395 : : * execution cost of the TABLESAMPLE parameter expressions; they will be
396 : : * evaluated only once per scan, and in most usages they'll likely be
397 : : * simple constants anyway. We also don't charge anything for the
398 : : * calculations the sampling method might do internally.
399 : : */
400 : 45 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
401 : :
402 : 45 : startup_cost += qpqual_cost.startup;
403 : 45 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
404 : 45 : run_cost += cpu_per_tuple * baserel->tuples;
405 : : /* tlist eval costs are paid per output row, not per tuple scanned */
406 : 45 : startup_cost += path->pathtarget->cost.startup;
407 : 45 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
408 : :
409 [ - + ]: 45 : if (path->parallel_workers == 0)
410 : 45 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
411 : :
412 : 45 : path->disabled_nodes =
413 : 45 : (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
414 : 45 : path->startup_cost = startup_cost;
415 : 45 : path->total_cost = startup_cost + run_cost;
416 : 45 : }
417 : :
418 : : /*
419 : : * cost_gather
420 : : * Determines and returns the cost of gather path.
421 : : *
422 : : * 'rel' is the relation to be operated upon
423 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
424 : : * 'rows' may be used to point to a row estimate; if non-NULL, it overrides
425 : : * both 'rel' and 'param_info'. This is useful when the path doesn't exactly
426 : : * correspond to any particular RelOptInfo.
427 : : */
428 : : void
429 : 3645 : cost_gather(GatherPath *path, PlannerInfo *root,
430 : : RelOptInfo *rel, ParamPathInfo *param_info,
431 : : double *rows)
432 : : {
433 : 3645 : Cost startup_cost = 0;
434 : 3645 : Cost run_cost = 0;
435 : :
436 : : /* Mark the path with the correct row estimate */
437 [ + + ]: 3645 : if (rows)
438 : 1027 : path->path.rows = *rows;
439 [ - + ]: 2618 : else if (param_info)
440 : 0 : path->path.rows = param_info->ppi_rows;
441 : : else
442 : 2618 : path->path.rows = rel->rows;
443 : :
444 : 3645 : startup_cost = path->subpath->startup_cost;
445 : :
446 : 3645 : run_cost = path->subpath->total_cost - path->subpath->startup_cost;
447 : :
448 : : /* Parallel setup and communication cost. */
449 : 3645 : startup_cost += parallel_setup_cost;
450 : 3645 : run_cost += parallel_tuple_cost * path->path.rows;
451 : :
452 : 7290 : path->path.disabled_nodes = path->subpath->disabled_nodes
453 : 3645 : + ((rel->pgs_mask & PGS_GATHER) != 0 ? 0 : 1);
454 : 3645 : path->path.startup_cost = startup_cost;
455 : 3645 : path->path.total_cost = (startup_cost + run_cost);
456 : 3645 : }
457 : :
458 : : /*
459 : : * cost_gather_merge
460 : : * Determines and returns the cost of gather merge path.
461 : : *
462 : : * GatherMerge merges several pre-sorted input streams, using a heap that at
463 : : * any given instant holds the next tuple from each stream. If there are N
464 : : * streams, we need about N*log2(N) tuple comparisons to construct the heap at
465 : : * startup, and then for each output tuple, about log2(N) comparisons to
466 : : * replace the top heap entry with the next tuple from the same stream.
467 : : */
468 : : void
469 : 2999 : cost_gather_merge(GatherMergePath *path, PlannerInfo *root,
470 : : RelOptInfo *rel, ParamPathInfo *param_info,
471 : : int input_disabled_nodes,
472 : : Cost input_startup_cost, Cost input_total_cost,
473 : : double *rows)
474 : : {
475 : 2999 : Cost startup_cost = 0;
476 : 2999 : Cost run_cost = 0;
477 : 2999 : Cost comparison_cost;
478 : 2999 : double N;
479 : 2999 : double logN;
480 : :
481 : : /* Mark the path with the correct row estimate */
482 [ + + ]: 2999 : if (rows)
483 : 1790 : path->path.rows = *rows;
484 [ - + ]: 1209 : else if (param_info)
485 : 0 : path->path.rows = param_info->ppi_rows;
486 : : else
487 : 1209 : path->path.rows = rel->rows;
488 : :
489 : : /*
490 : : * Add one to the number of workers to account for the leader. This might
491 : : * be overgenerous since the leader will do less work than other workers
492 : : * in typical cases, but we'll go with it for now.
493 : : */
494 [ + - ]: 2999 : Assert(path->num_workers > 0);
495 : 2999 : N = (double) path->num_workers + 1;
496 : 2999 : logN = LOG2(N);
497 : :
498 : : /* Assumed cost per tuple comparison */
499 : 2999 : comparison_cost = 2.0 * cpu_operator_cost;
500 : :
501 : : /* Heap creation cost */
502 : 2999 : startup_cost += comparison_cost * N * logN;
503 : :
504 : : /* Per-tuple heap maintenance cost */
505 : 2999 : run_cost += path->path.rows * comparison_cost * logN;
506 : :
507 : : /* small cost for heap management, like cost_merge_append */
508 : 2999 : run_cost += cpu_operator_cost * path->path.rows;
509 : :
510 : : /*
511 : : * Parallel setup and communication cost. Since Gather Merge, unlike
512 : : * Gather, requires us to block until a tuple is available from every
513 : : * worker, we bump the IPC cost up a little bit as compared with Gather.
514 : : * For lack of a better idea, charge an extra 5%.
515 : : */
516 : 2999 : startup_cost += parallel_setup_cost;
517 : 2999 : run_cost += parallel_tuple_cost * path->path.rows * 1.05;
518 : :
519 : 5998 : path->path.disabled_nodes = path->subpath->disabled_nodes
520 : 2999 : + ((rel->pgs_mask & PGS_GATHER_MERGE) != 0 ? 0 : 1);
521 : 2999 : path->path.startup_cost = startup_cost + input_startup_cost;
522 : 2999 : path->path.total_cost = (startup_cost + run_cost + input_total_cost);
523 : 2999 : }
524 : :
525 : : /*
526 : : * cost_index
527 : : * Determines and returns the cost of scanning a relation using an index.
528 : : *
529 : : * 'path' describes the indexscan under consideration, and is complete
530 : : * except for the fields to be set by this routine
531 : : * 'loop_count' is the number of repetitions of the indexscan to factor into
532 : : * estimates of caching behavior
533 : : *
534 : : * In addition to rows, startup_cost and total_cost, cost_index() sets the
535 : : * path's indextotalcost and indexselectivity fields. These values will be
536 : : * needed if the IndexPath is used in a BitmapIndexScan.
537 : : *
538 : : * NOTE: path->indexquals must contain only clauses usable as index
539 : : * restrictions. Any additional quals evaluated as qpquals may reduce the
540 : : * number of returned tuples, but they won't reduce the number of tuples
541 : : * we have to fetch from the table, so they don't reduce the scan cost.
542 : : */
543 : : void
544 : 75698 : cost_index(IndexPath *path, PlannerInfo *root, double loop_count,
545 : : bool partial_path)
546 : : {
547 : 75698 : IndexOptInfo *index = path->indexinfo;
548 : 75698 : RelOptInfo *baserel = index->rel;
549 : 75698 : bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
550 : 75698 : amcostestimate_function amcostestimate;
551 : 75698 : List *qpquals;
552 : 75698 : Cost startup_cost = 0;
553 : 75698 : Cost run_cost = 0;
554 : 75698 : Cost cpu_run_cost = 0;
555 : 75698 : Cost indexStartupCost;
556 : 75698 : Cost indexTotalCost;
557 : 75698 : Selectivity indexSelectivity;
558 : 75698 : double indexCorrelation,
559 : : csquared;
560 : 75698 : double spc_seq_page_cost,
561 : : spc_random_page_cost;
562 : 75698 : Cost min_IO_cost,
563 : : max_IO_cost;
564 : 75698 : QualCost qpqual_cost;
565 : 75698 : Cost cpu_per_tuple;
566 : 75698 : double tuples_fetched;
567 : 75698 : double pages_fetched;
568 : 75698 : double rand_heap_pages;
569 : 75698 : double index_pages;
570 : 75698 : uint64 enable_mask;
571 : :
572 : : /* Should only be applied to base relations */
573 [ + - ]: 75698 : Assert(IsA(baserel, RelOptInfo) &&
574 : : IsA(index, IndexOptInfo));
575 [ + - ]: 75698 : Assert(baserel->relid > 0);
576 [ + - ]: 75698 : Assert(baserel->rtekind == RTE_RELATION);
577 : :
578 : : /*
579 : : * Mark the path with the correct row estimate, and identify which quals
580 : : * will need to be enforced as qpquals. We need not check any quals that
581 : : * are implied by the index's predicate, so we can use indrestrictinfo not
582 : : * baserestrictinfo as the list of relevant restriction clauses for the
583 : : * rel.
584 : : */
585 [ + + ]: 75698 : if (path->path.param_info)
586 : : {
587 : 14778 : path->path.rows = path->path.param_info->ppi_rows;
588 : : /* qpquals come from the rel's restriction clauses and ppi_clauses */
589 : 44334 : qpquals = list_concat(extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
590 : 14778 : path->indexclauses),
591 : 29556 : extract_nonindex_conditions(path->path.param_info->ppi_clauses,
592 : 14778 : path->indexclauses));
593 : 14778 : }
594 : : else
595 : : {
596 : 60920 : path->path.rows = baserel->rows;
597 : : /* qpquals come from just the rel's restriction clauses */
598 : 121840 : qpquals = extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
599 : 60920 : path->indexclauses);
600 : : }
601 : :
602 : : /* is this scan type disabled? */
603 : 151396 : enable_mask = (indexonly ? PGS_INDEXONLYSCAN : PGS_INDEXSCAN)
604 : 75698 : | (partial_path ? 0 : PGS_CONSIDER_NONPARTIAL);
605 : 75698 : path->path.disabled_nodes =
606 : 75698 : (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
607 : :
608 : : /*
609 : : * Call index-access-method-specific code to estimate the processing cost
610 : : * for scanning the index, as well as the selectivity of the index (ie,
611 : : * the fraction of main-table tuples we will have to retrieve) and its
612 : : * correlation to the main-table tuple order. We need a cast here because
613 : : * pathnodes.h uses a weak function type to avoid including amapi.h.
614 : : */
615 : 75698 : amcostestimate = (amcostestimate_function) index->amcostestimate;
616 : 75698 : amcostestimate(root, path, loop_count,
617 : : &indexStartupCost, &indexTotalCost,
618 : : &indexSelectivity, &indexCorrelation,
619 : : &index_pages);
620 : :
621 : : /*
622 : : * Save amcostestimate's results for possible use in bitmap scan planning.
623 : : * We don't bother to save indexStartupCost or indexCorrelation, because a
624 : : * bitmap scan doesn't care about either.
625 : : */
626 : 75698 : path->indextotalcost = indexTotalCost;
627 : 75698 : path->indexselectivity = indexSelectivity;
628 : :
629 : : /* all costs for touching index itself included here */
630 : 75698 : startup_cost += indexStartupCost;
631 : 75698 : run_cost += indexTotalCost - indexStartupCost;
632 : :
633 : : /* estimate number of main-table tuples fetched */
634 : 75698 : tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
635 : :
636 : : /* fetch estimated page costs for tablespace containing table */
637 : 75698 : get_tablespace_page_costs(baserel->reltablespace,
638 : : &spc_random_page_cost,
639 : : &spc_seq_page_cost);
640 : :
641 : : /*----------
642 : : * Estimate number of main-table pages fetched, and compute I/O cost.
643 : : *
644 : : * When the index ordering is uncorrelated with the table ordering,
645 : : * we use an approximation proposed by Mackert and Lohman (see
646 : : * index_pages_fetched() for details) to compute the number of pages
647 : : * fetched, and then charge spc_random_page_cost per page fetched.
648 : : *
649 : : * When the index ordering is exactly correlated with the table ordering
650 : : * (just after a CLUSTER, for example), the number of pages fetched should
651 : : * be exactly selectivity * table_size. What's more, all but the first
652 : : * will be sequential fetches, not the random fetches that occur in the
653 : : * uncorrelated case. So if the number of pages is more than 1, we
654 : : * ought to charge
655 : : * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
656 : : * For partially-correlated indexes, we ought to charge somewhere between
657 : : * these two estimates. We currently interpolate linearly between the
658 : : * estimates based on the correlation squared (XXX is that appropriate?).
659 : : *
660 : : * If it's an index-only scan, then we will not need to fetch any heap
661 : : * pages for which the visibility map shows all tuples are visible.
662 : : * Hence, reduce the estimated number of heap fetches accordingly.
663 : : * We use the measured fraction of the entire heap that is all-visible,
664 : : * which might not be particularly relevant to the subset of the heap
665 : : * that this query will fetch; but it's not clear how to do better.
666 : : *----------
667 : : */
668 [ + + ]: 75698 : if (loop_count > 1)
669 : : {
670 : : /*
671 : : * For repeated indexscans, the appropriate estimate for the
672 : : * uncorrelated case is to scale up the number of tuples fetched in
673 : : * the Mackert and Lohman formula by the number of scans, so that we
674 : : * estimate the number of pages fetched by all the scans; then
675 : : * pro-rate the costs for one scan. In this case we assume all the
676 : : * fetches are random accesses.
677 : : */
678 : 15618 : pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
679 : 7809 : baserel->pages,
680 : 7809 : (double) index->pages,
681 : 7809 : root);
682 : :
683 [ + + ]: 7809 : if (indexonly)
684 : 1258 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
685 : :
686 : 7809 : rand_heap_pages = pages_fetched;
687 : :
688 : 7809 : max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
689 : :
690 : : /*
691 : : * In the perfectly correlated case, the number of pages touched by
692 : : * each scan is selectivity * table_size, and we can use the Mackert
693 : : * and Lohman formula at the page level to estimate how much work is
694 : : * saved by caching across scans. We still assume all the fetches are
695 : : * random, though, which is an overestimate that's hard to correct for
696 : : * without double-counting the cache effects. (But in most cases
697 : : * where such a plan is actually interesting, only one page would get
698 : : * fetched per scan anyway, so it shouldn't matter much.)
699 : : */
700 : 7809 : pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
701 : :
702 : 15618 : pages_fetched = index_pages_fetched(pages_fetched * loop_count,
703 : 7809 : baserel->pages,
704 : 7809 : (double) index->pages,
705 : 7809 : root);
706 : :
707 [ + + ]: 7809 : if (indexonly)
708 : 1258 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
709 : :
710 : 7809 : min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
711 : 7809 : }
712 : : else
713 : : {
714 : : /*
715 : : * Normal case: apply the Mackert and Lohman formula, and then
716 : : * interpolate between that and the correlation-derived result.
717 : : */
718 : 135778 : pages_fetched = index_pages_fetched(tuples_fetched,
719 : 67889 : baserel->pages,
720 : 67889 : (double) index->pages,
721 : 67889 : root);
722 : :
723 [ + + ]: 67889 : if (indexonly)
724 : 7931 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
725 : :
726 : 67889 : rand_heap_pages = pages_fetched;
727 : :
728 : : /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
729 : 67889 : max_IO_cost = pages_fetched * spc_random_page_cost;
730 : :
731 : : /* min_IO_cost is for the perfectly correlated case (csquared=1) */
732 : 67889 : pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
733 : :
734 [ + + ]: 67889 : if (indexonly)
735 : 7931 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
736 : :
737 [ + + ]: 67889 : if (pages_fetched > 0)
738 : : {
739 : 62101 : min_IO_cost = spc_random_page_cost;
740 [ + + ]: 62101 : if (pages_fetched > 1)
741 : 20866 : min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
742 : 62101 : }
743 : : else
744 : 5788 : min_IO_cost = 0;
745 : : }
746 : :
747 [ + + ]: 75698 : if (partial_path)
748 : : {
749 : : /*
750 : : * For index only scans compute workers based on number of index pages
751 : : * fetched; the number of heap pages we fetch might be so small as to
752 : : * effectively rule out parallelism, which we don't want to do.
753 : : */
754 [ + + ]: 25382 : if (indexonly)
755 : 2722 : rand_heap_pages = -1;
756 : :
757 : : /*
758 : : * Estimate the number of parallel workers required to scan index. Use
759 : : * the number of heap pages computed considering heap fetches won't be
760 : : * sequential as for parallel scans the pages are accessed in random
761 : : * order.
762 : : */
763 : 50764 : path->path.parallel_workers = compute_parallel_worker(baserel,
764 : 25382 : rand_heap_pages,
765 : 25382 : index_pages,
766 : 25382 : max_parallel_workers_per_gather);
767 : :
768 : : /*
769 : : * Fall out if workers can't be assigned for parallel scan, because in
770 : : * such a case this path will be rejected. So there is no benefit in
771 : : * doing extra computation.
772 : : */
773 [ + + ]: 25382 : if (path->path.parallel_workers <= 0)
774 : 24122 : return;
775 : :
776 : 1260 : path->path.parallel_aware = true;
777 : 1260 : }
778 : :
779 : : /*
780 : : * Now interpolate based on estimated index order correlation to get total
781 : : * disk I/O cost for main table accesses.
782 : : */
783 : 51576 : csquared = indexCorrelation * indexCorrelation;
784 : :
785 : 51576 : run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
786 : :
787 : : /*
788 : : * Estimate CPU costs per tuple.
789 : : *
790 : : * What we want here is cpu_tuple_cost plus the evaluation costs of any
791 : : * qual clauses that we have to evaluate as qpquals.
792 : : */
793 : 51576 : cost_qual_eval(&qpqual_cost, qpquals, root);
794 : :
795 : 51576 : startup_cost += qpqual_cost.startup;
796 : 51576 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
797 : :
798 : 51576 : cpu_run_cost += cpu_per_tuple * tuples_fetched;
799 : :
800 : : /* tlist eval costs are paid per output row, not per tuple scanned */
801 : 51576 : startup_cost += path->path.pathtarget->cost.startup;
802 : 51576 : cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
803 : :
804 : : /* Adjust costing for parallelism, if used. */
805 [ + + ]: 51576 : if (path->path.parallel_workers > 0)
806 : : {
807 : 1260 : double parallel_divisor = get_parallel_divisor(&path->path);
808 : :
809 : 1260 : path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
810 : :
811 : : /* The CPU cost is divided among all the workers. */
812 : 1260 : cpu_run_cost /= parallel_divisor;
813 : 1260 : }
814 : :
815 : 51576 : run_cost += cpu_run_cost;
816 : :
817 : 51576 : path->path.startup_cost = startup_cost;
818 : 51576 : path->path.total_cost = startup_cost + run_cost;
819 [ - + ]: 75698 : }
820 : :
821 : : /*
822 : : * extract_nonindex_conditions
823 : : *
824 : : * Given a list of quals to be enforced in an indexscan, extract the ones that
825 : : * will have to be applied as qpquals (ie, the index machinery won't handle
826 : : * them). Here we detect only whether a qual clause is directly redundant
827 : : * with some indexclause. If the index path is chosen for use, createplan.c
828 : : * will try a bit harder to get rid of redundant qual conditions; specifically
829 : : * it will see if quals can be proven to be implied by the indexquals. But
830 : : * it does not seem worth the cycles to try to factor that in at this stage,
831 : : * since we're only trying to estimate qual eval costs. Otherwise this must
832 : : * match the logic in create_indexscan_plan().
833 : : *
834 : : * qual_clauses, and the result, are lists of RestrictInfos.
835 : : * indexclauses is a list of IndexClauses.
836 : : */
837 : : static List *
838 : 90476 : extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
839 : : {
840 : 90476 : List *result = NIL;
841 : 90476 : ListCell *lc;
842 : :
843 [ + + + + : 181914 : foreach(lc, qual_clauses)
+ + ]
844 : : {
845 : 91438 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
846 : :
847 [ + + ]: 91438 : if (rinfo->pseudoconstant)
848 : 1682 : continue; /* we may drop pseudoconstants here */
849 [ + + ]: 89756 : if (is_redundant_with_indexclauses(rinfo, indexclauses))
850 : 53151 : continue; /* dup or derived from same EquivalenceClass */
851 : : /* ... skip the predicate proof attempt createplan.c will try ... */
852 : 36605 : result = lappend(result, rinfo);
853 [ - + + ]: 91438 : }
854 : 180952 : return result;
855 : 90476 : }
856 : :
857 : : /*
858 : : * index_pages_fetched
859 : : * Estimate the number of pages actually fetched after accounting for
860 : : * cache effects.
861 : : *
862 : : * We use an approximation proposed by Mackert and Lohman, "Index Scans
863 : : * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
864 : : * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
865 : : * The Mackert and Lohman approximation is that the number of pages
866 : : * fetched is
867 : : * PF =
868 : : * min(2TNs/(2T+Ns), T) when T <= b
869 : : * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
870 : : * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
871 : : * where
872 : : * T = # pages in table
873 : : * N = # tuples in table
874 : : * s = selectivity = fraction of table to be scanned
875 : : * b = # buffer pages available (we include kernel space here)
876 : : *
877 : : * We assume that effective_cache_size is the total number of buffer pages
878 : : * available for the whole query, and pro-rate that space across all the
879 : : * tables in the query and the index currently under consideration. (This
880 : : * ignores space needed for other indexes used by the query, but since we
881 : : * don't know which indexes will get used, we can't estimate that very well;
882 : : * and in any case counting all the tables may well be an overestimate, since
883 : : * depending on the join plan not all the tables may be scanned concurrently.)
884 : : *
885 : : * The product Ns is the number of tuples fetched; we pass in that
886 : : * product rather than calculating it here. "pages" is the number of pages
887 : : * in the object under consideration (either an index or a table).
888 : : * "index_pages" is the amount to add to the total table space, which was
889 : : * computed for us by make_one_rel.
890 : : *
891 : : * Caller is expected to have ensured that tuples_fetched is greater than zero
892 : : * and rounded to integer (see clamp_row_est). The result will likewise be
893 : : * greater than zero and integral.
894 : : */
895 : : double
896 : 106023 : index_pages_fetched(double tuples_fetched, BlockNumber pages,
897 : : double index_pages, PlannerInfo *root)
898 : : {
899 : 106023 : double pages_fetched;
900 : 106023 : double total_pages;
901 : 106023 : double T,
902 : : b;
903 : :
904 : : /* T is # pages in table, but don't allow it to be zero */
905 [ + + ]: 106023 : T = (pages > 1) ? (double) pages : 1.0;
906 : :
907 : : /* Compute number of pages assumed to be competing for cache space */
908 : 106023 : total_pages = root->total_table_pages + index_pages;
909 [ + + ]: 106023 : total_pages = Max(total_pages, 1.0);
910 [ + - ]: 106023 : Assert(T <= total_pages);
911 : :
912 : : /* b is pro-rated share of effective_cache_size */
913 : 106023 : b = (double) effective_cache_size * T / total_pages;
914 : :
915 : : /* force it positive and integral */
916 [ - + ]: 106023 : if (b <= 1.0)
917 : 0 : b = 1.0;
918 : : else
919 : 106023 : b = ceil(b);
920 : :
921 : : /* This part is the Mackert and Lohman formula */
922 [ + - ]: 106023 : if (T <= b)
923 : : {
924 : 106023 : pages_fetched =
925 : 106023 : (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
926 [ + + ]: 106023 : if (pages_fetched >= T)
927 : 64818 : pages_fetched = T;
928 : : else
929 : 41205 : pages_fetched = ceil(pages_fetched);
930 : 106023 : }
931 : : else
932 : : {
933 : 0 : double lim;
934 : :
935 : 0 : lim = (2.0 * T * b) / (2.0 * T - b);
936 [ # # ]: 0 : if (tuples_fetched <= lim)
937 : : {
938 : 0 : pages_fetched =
939 : 0 : (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
940 : 0 : }
941 : : else
942 : : {
943 : 0 : pages_fetched =
944 : 0 : b + (tuples_fetched - lim) * (T - b) / T;
945 : : }
946 : 0 : pages_fetched = ceil(pages_fetched);
947 : 0 : }
948 : 212046 : return pages_fetched;
949 : 106023 : }
950 : :
951 : : /*
952 : : * get_indexpath_pages
953 : : * Determine the total size of the indexes used in a bitmap index path.
954 : : *
955 : : * Note: if the same index is used more than once in a bitmap tree, we will
956 : : * count it multiple times, which perhaps is the wrong thing ... but it's
957 : : * not completely clear, and detecting duplicates is difficult, so ignore it
958 : : * for now.
959 : : */
960 : : static double
961 : 19366 : get_indexpath_pages(Path *bitmapqual)
962 : : {
963 : 19366 : double result = 0;
964 : 19366 : ListCell *l;
965 : :
966 [ + + ]: 19366 : if (IsA(bitmapqual, BitmapAndPath))
967 : : {
968 : 2620 : BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
969 : :
970 [ + - + + : 7860 : foreach(l, apath->bitmapquals)
+ + ]
971 : : {
972 : 5240 : result += get_indexpath_pages((Path *) lfirst(l));
973 : 5240 : }
974 : 2620 : }
975 [ + + ]: 16746 : else if (IsA(bitmapqual, BitmapOrPath))
976 : : {
977 : 11 : BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
978 : :
979 [ + - + + : 35 : foreach(l, opath->bitmapquals)
+ + ]
980 : : {
981 : 24 : result += get_indexpath_pages((Path *) lfirst(l));
982 : 24 : }
983 : 11 : }
984 [ + - ]: 16735 : else if (IsA(bitmapqual, IndexPath))
985 : : {
986 : 16735 : IndexPath *ipath = (IndexPath *) bitmapqual;
987 : :
988 : 16735 : result = (double) ipath->indexinfo->pages;
989 : 16735 : }
990 : : else
991 [ # # # # ]: 0 : elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
992 : :
993 : 38732 : return result;
994 : 19366 : }
995 : :
996 : : /*
997 : : * cost_bitmap_heap_scan
998 : : * Determines and returns the cost of scanning a relation using a bitmap
999 : : * index-then-heap plan.
1000 : : *
1001 : : * 'baserel' is the relation to be scanned
1002 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1003 : : * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
1004 : : * 'loop_count' is the number of repetitions of the indexscan to factor into
1005 : : * estimates of caching behavior
1006 : : *
1007 : : * Note: the component IndexPaths in bitmapqual should have been costed
1008 : : * using the same loop_count.
1009 : : */
1010 : : void
1011 : 50395 : cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
1012 : : ParamPathInfo *param_info,
1013 : : Path *bitmapqual, double loop_count)
1014 : : {
1015 : 50395 : Cost startup_cost = 0;
1016 : 50395 : Cost run_cost = 0;
1017 : 50395 : Cost indexTotalCost;
1018 : 50395 : QualCost qpqual_cost;
1019 : 50395 : Cost cpu_per_tuple;
1020 : 50395 : Cost cost_per_page;
1021 : 50395 : Cost cpu_run_cost;
1022 : 50395 : double tuples_fetched;
1023 : 50395 : double pages_fetched;
1024 : 50395 : double spc_seq_page_cost,
1025 : : spc_random_page_cost;
1026 : 50395 : double T;
1027 : 50395 : uint64 enable_mask = PGS_BITMAPSCAN;
1028 : :
1029 : : /* Should only be applied to base relations */
1030 [ + - ]: 50395 : Assert(IsA(baserel, RelOptInfo));
1031 [ + - ]: 50395 : Assert(baserel->relid > 0);
1032 [ + - ]: 50395 : Assert(baserel->rtekind == RTE_RELATION);
1033 : :
1034 : : /* Mark the path with the correct row estimate */
1035 [ + + ]: 50395 : if (param_info)
1036 : 23457 : path->rows = param_info->ppi_rows;
1037 : : else
1038 : 26938 : path->rows = baserel->rows;
1039 : :
1040 : 100790 : pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
1041 : 50395 : loop_count, &indexTotalCost,
1042 : : &tuples_fetched);
1043 : :
1044 : 50395 : startup_cost += indexTotalCost;
1045 [ + + ]: 50395 : T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1046 : :
1047 : : /* Fetch estimated page costs for tablespace containing table. */
1048 : 50395 : get_tablespace_page_costs(baserel->reltablespace,
1049 : : &spc_random_page_cost,
1050 : : &spc_seq_page_cost);
1051 : :
1052 : : /*
1053 : : * For small numbers of pages we should charge spc_random_page_cost
1054 : : * apiece, while if nearly all the table's pages are being read, it's more
1055 : : * appropriate to charge spc_seq_page_cost apiece. The effect is
1056 : : * nonlinear, too. For lack of a better idea, interpolate like this to
1057 : : * determine the cost per page.
1058 : : */
1059 [ + + ]: 50395 : if (pages_fetched >= 2.0)
1060 : 24502 : cost_per_page = spc_random_page_cost -
1061 : 12251 : (spc_random_page_cost - spc_seq_page_cost)
1062 : 12251 : * sqrt(pages_fetched / T);
1063 : : else
1064 : 38144 : cost_per_page = spc_random_page_cost;
1065 : :
1066 : 50395 : run_cost += pages_fetched * cost_per_page;
1067 : :
1068 : : /*
1069 : : * Estimate CPU costs per tuple.
1070 : : *
1071 : : * Often the indexquals don't need to be rechecked at each tuple ... but
1072 : : * not always, especially not if there are enough tuples involved that the
1073 : : * bitmaps become lossy. For the moment, just assume they will be
1074 : : * rechecked always. This means we charge the full freight for all the
1075 : : * scan clauses.
1076 : : */
1077 : 50395 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1078 : :
1079 : 50395 : startup_cost += qpqual_cost.startup;
1080 : 50395 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1081 : 50395 : cpu_run_cost = cpu_per_tuple * tuples_fetched;
1082 : :
1083 : : /* Adjust costing for parallelism, if used. */
1084 [ + + ]: 50395 : if (path->parallel_workers > 0)
1085 : : {
1086 : 291 : double parallel_divisor = get_parallel_divisor(path);
1087 : :
1088 : : /* The CPU cost is divided among all the workers. */
1089 : 291 : cpu_run_cost /= parallel_divisor;
1090 : :
1091 : 291 : path->rows = clamp_row_est(path->rows / parallel_divisor);
1092 : 291 : }
1093 : : else
1094 : 50104 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1095 : :
1096 : :
1097 : 50395 : run_cost += cpu_run_cost;
1098 : :
1099 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1100 : 50395 : startup_cost += path->pathtarget->cost.startup;
1101 : 50395 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1102 : :
1103 : 50395 : path->disabled_nodes =
1104 : 50395 : (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
1105 : 50395 : path->startup_cost = startup_cost;
1106 : 50395 : path->total_cost = startup_cost + run_cost;
1107 : 50395 : }
1108 : :
1109 : : /*
1110 : : * cost_bitmap_tree_node
1111 : : * Extract cost and selectivity from a bitmap tree node (index/and/or)
1112 : : */
1113 : : void
1114 : 93338 : cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
1115 : : {
1116 [ + + ]: 93338 : if (IsA(path, IndexPath))
1117 : : {
1118 : 88743 : *cost = ((IndexPath *) path)->indextotalcost;
1119 : 88743 : *selec = ((IndexPath *) path)->indexselectivity;
1120 : :
1121 : : /*
1122 : : * Charge a small amount per retrieved tuple to reflect the costs of
1123 : : * manipulating the bitmap. This is mostly to make sure that a bitmap
1124 : : * scan doesn't look to be the same cost as an indexscan to retrieve a
1125 : : * single tuple.
1126 : : */
1127 : 88743 : *cost += 0.1 * cpu_operator_cost * path->rows;
1128 : 88743 : }
1129 [ + + ]: 4595 : else if (IsA(path, BitmapAndPath))
1130 : : {
1131 : 4386 : *cost = path->total_cost;
1132 : 4386 : *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1133 : 4386 : }
1134 [ + - ]: 209 : else if (IsA(path, BitmapOrPath))
1135 : : {
1136 : 209 : *cost = path->total_cost;
1137 : 209 : *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1138 : 209 : }
1139 : : else
1140 : : {
1141 [ # # # # ]: 0 : elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1142 : 0 : *cost = *selec = 0; /* keep compiler quiet */
1143 : : }
1144 : 93338 : }
1145 : :
1146 : : /*
1147 : : * cost_bitmap_and_node
1148 : : * Estimate the cost of a BitmapAnd node
1149 : : *
1150 : : * Note that this considers only the costs of index scanning and bitmap
1151 : : * creation, not the eventual heap access. In that sense the object isn't
1152 : : * truly a Path, but it has enough path-like properties (costs in particular)
1153 : : * to warrant treating it as one. We don't bother to set the path rows field,
1154 : : * however.
1155 : : */
1156 : : void
1157 : 4375 : cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
1158 : : {
1159 : 4375 : Cost totalCost;
1160 : 4375 : Selectivity selec;
1161 : 4375 : ListCell *l;
1162 : :
1163 : : /*
1164 : : * We estimate AND selectivity on the assumption that the inputs are
1165 : : * independent. This is probably often wrong, but we don't have the info
1166 : : * to do better.
1167 : : *
1168 : : * The runtime cost of the BitmapAnd itself is estimated at 100x
1169 : : * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1170 : : * definitely too simplistic?
1171 : : */
1172 : 4375 : totalCost = 0.0;
1173 : 4375 : selec = 1.0;
1174 [ + - + + : 13125 : foreach(l, path->bitmapquals)
+ + ]
1175 : : {
1176 : 8750 : Path *subpath = (Path *) lfirst(l);
1177 : 8750 : Cost subCost;
1178 : 8750 : Selectivity subselec;
1179 : :
1180 : 8750 : cost_bitmap_tree_node(subpath, &subCost, &subselec);
1181 : :
1182 : 8750 : selec *= subselec;
1183 : :
1184 : 8750 : totalCost += subCost;
1185 [ + + ]: 8750 : if (l != list_head(path->bitmapquals))
1186 : 4375 : totalCost += 100.0 * cpu_operator_cost;
1187 : 8750 : }
1188 : 4375 : path->bitmapselectivity = selec;
1189 : 4375 : path->path.rows = 0; /* per above, not used */
1190 : 4375 : path->path.disabled_nodes = 0;
1191 : 4375 : path->path.startup_cost = totalCost;
1192 : 4375 : path->path.total_cost = totalCost;
1193 : 4375 : }
1194 : :
1195 : : /*
1196 : : * cost_bitmap_or_node
1197 : : * Estimate the cost of a BitmapOr node
1198 : : *
1199 : : * See comments for cost_bitmap_and_node.
1200 : : */
1201 : : void
1202 : 98 : cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
1203 : : {
1204 : 98 : Cost totalCost;
1205 : 98 : Selectivity selec;
1206 : 98 : ListCell *l;
1207 : :
1208 : : /*
1209 : : * We estimate OR selectivity on the assumption that the inputs are
1210 : : * non-overlapping, since that's often the case in "x IN (list)" type
1211 : : * situations. Of course, we clamp to 1.0 at the end.
1212 : : *
1213 : : * The runtime cost of the BitmapOr itself is estimated at 100x
1214 : : * cpu_operator_cost for each tbm_union needed. Probably too small,
1215 : : * definitely too simplistic? We are aware that the tbm_unions are
1216 : : * optimized out when the inputs are BitmapIndexScans.
1217 : : */
1218 : 98 : totalCost = 0.0;
1219 : 98 : selec = 0.0;
1220 [ + - + + : 261 : foreach(l, path->bitmapquals)
+ + ]
1221 : : {
1222 : 163 : Path *subpath = (Path *) lfirst(l);
1223 : 163 : Cost subCost;
1224 : 163 : Selectivity subselec;
1225 : :
1226 : 163 : cost_bitmap_tree_node(subpath, &subCost, &subselec);
1227 : :
1228 : 163 : selec += subselec;
1229 : :
1230 : 163 : totalCost += subCost;
1231 [ + + + - ]: 163 : if (l != list_head(path->bitmapquals) &&
1232 : 65 : !IsA(subpath, IndexPath))
1233 : 0 : totalCost += 100.0 * cpu_operator_cost;
1234 : 163 : }
1235 [ + - ]: 98 : path->bitmapselectivity = Min(selec, 1.0);
1236 : 98 : path->path.rows = 0; /* per above, not used */
1237 : 98 : path->path.startup_cost = totalCost;
1238 : 98 : path->path.total_cost = totalCost;
1239 : 98 : }
1240 : :
1241 : : /*
1242 : : * cost_tidscan
1243 : : * Determines and returns the cost of scanning a relation using TIDs.
1244 : : *
1245 : : * 'baserel' is the relation to be scanned
1246 : : * 'tidquals' is the list of TID-checkable quals
1247 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1248 : : */
1249 : : void
1250 : 104 : cost_tidscan(Path *path, PlannerInfo *root,
1251 : : RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
1252 : : {
1253 : 104 : Cost startup_cost = 0;
1254 : 104 : Cost run_cost = 0;
1255 : 104 : QualCost qpqual_cost;
1256 : 104 : Cost cpu_per_tuple;
1257 : 104 : QualCost tid_qual_cost;
1258 : 104 : double ntuples;
1259 : 104 : ListCell *l;
1260 : 104 : double spc_random_page_cost;
1261 : 104 : uint64 enable_mask = 0;
1262 : :
1263 : : /* Should only be applied to base relations */
1264 [ + - ]: 104 : Assert(baserel->relid > 0);
1265 [ + - ]: 104 : Assert(baserel->rtekind == RTE_RELATION);
1266 [ + - ]: 104 : Assert(tidquals != NIL);
1267 : :
1268 : : /* Mark the path with the correct row estimate */
1269 [ + + ]: 104 : if (param_info)
1270 : 21 : path->rows = param_info->ppi_rows;
1271 : : else
1272 : 83 : path->rows = baserel->rows;
1273 : :
1274 : : /* Count how many tuples we expect to retrieve */
1275 : 104 : ntuples = 0;
1276 [ + - + + : 212 : foreach(l, tidquals)
+ + ]
1277 : : {
1278 : 108 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1279 : 108 : Expr *qual = rinfo->clause;
1280 : :
1281 : : /*
1282 : : * We must use a TID scan for CurrentOfExpr; in any other case, we
1283 : : * should be generating a TID scan only if TID scans are allowed.
1284 : : * Also, if CurrentOfExpr is the qual, there should be only one.
1285 : : */
1286 [ - + # # ]: 108 : Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0 || IsA(qual, CurrentOfExpr));
1287 [ + + + - ]: 108 : Assert(list_length(tidquals) == 1 || !IsA(qual, CurrentOfExpr));
1288 : :
1289 [ + + ]: 108 : if (IsA(qual, ScalarArrayOpExpr))
1290 : : {
1291 : : /* Each element of the array yields 1 tuple */
1292 : 8 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1293 : 8 : Node *arraynode = (Node *) lsecond(saop->args);
1294 : :
1295 : 8 : ntuples += estimate_array_length(root, arraynode);
1296 : 8 : }
1297 [ + + ]: 100 : else if (IsA(qual, CurrentOfExpr))
1298 : : {
1299 : : /* CURRENT OF yields 1 tuple */
1300 : 66 : ntuples++;
1301 : 66 : }
1302 : : else
1303 : : {
1304 : : /* It's just CTID = something, count 1 tuple */
1305 : 34 : ntuples++;
1306 : : }
1307 : 108 : }
1308 : :
1309 : : /*
1310 : : * The TID qual expressions will be computed once, any other baserestrict
1311 : : * quals once per retrieved tuple.
1312 : : */
1313 : 104 : cost_qual_eval(&tid_qual_cost, tidquals, root);
1314 : :
1315 : : /* fetch estimated page cost for tablespace containing table */
1316 : 104 : get_tablespace_page_costs(baserel->reltablespace,
1317 : : &spc_random_page_cost,
1318 : : NULL);
1319 : :
1320 : : /* disk costs --- assume each tuple on a different page */
1321 : 104 : run_cost += spc_random_page_cost * ntuples;
1322 : :
1323 : : /* Add scanning CPU costs */
1324 : 104 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1325 : :
1326 : : /* XXX currently we assume TID quals are a subset of qpquals */
1327 : 104 : startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1328 : 208 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1329 : 104 : tid_qual_cost.per_tuple;
1330 : 104 : run_cost += cpu_per_tuple * ntuples;
1331 : :
1332 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1333 : 104 : startup_cost += path->pathtarget->cost.startup;
1334 : 104 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1335 : :
1336 : : /*
1337 : : * There are assertions above verifying that we only reach this function
1338 : : * either when baserel->pgs_mask includes PGS_TIDSCAN or when the TID scan
1339 : : * is the only legal path, so we only need to consider the effects of
1340 : : * PGS_CONSIDER_NONPARTIAL here.
1341 : : */
1342 [ - + ]: 104 : if (path->parallel_workers == 0)
1343 : 104 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1344 : 104 : path->disabled_nodes =
1345 : 104 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1346 : 104 : path->startup_cost = startup_cost;
1347 : 104 : path->total_cost = startup_cost + run_cost;
1348 : 104 : }
1349 : :
1350 : : /*
1351 : : * cost_tidrangescan
1352 : : * Determines and sets the costs of scanning a relation using a range of
1353 : : * TIDs for 'path'
1354 : : *
1355 : : * 'baserel' is the relation to be scanned
1356 : : * 'tidrangequals' is the list of TID-checkable range quals
1357 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1358 : : */
1359 : : void
1360 : 342 : cost_tidrangescan(Path *path, PlannerInfo *root,
1361 : : RelOptInfo *baserel, List *tidrangequals,
1362 : : ParamPathInfo *param_info)
1363 : : {
1364 : 342 : Selectivity selectivity;
1365 : 342 : double pages;
1366 : 342 : Cost startup_cost;
1367 : 342 : Cost cpu_run_cost;
1368 : 342 : Cost disk_run_cost;
1369 : 342 : QualCost qpqual_cost;
1370 : 342 : Cost cpu_per_tuple;
1371 : 342 : QualCost tid_qual_cost;
1372 : 342 : double ntuples;
1373 : 342 : double nseqpages;
1374 : 342 : double spc_random_page_cost;
1375 : 342 : double spc_seq_page_cost;
1376 : 342 : uint64 enable_mask = PGS_TIDSCAN;
1377 : :
1378 : : /* Should only be applied to base relations */
1379 [ + - ]: 342 : Assert(baserel->relid > 0);
1380 [ + - ]: 342 : Assert(baserel->rtekind == RTE_RELATION);
1381 : :
1382 : : /* Mark the path with the correct row estimate */
1383 [ - + ]: 342 : if (param_info)
1384 : 0 : path->rows = param_info->ppi_rows;
1385 : : else
1386 : 342 : path->rows = baserel->rows;
1387 : :
1388 : : /* Count how many tuples and pages we expect to scan */
1389 : 342 : selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1390 : : JOIN_INNER, NULL);
1391 : 342 : pages = ceil(selectivity * baserel->pages);
1392 : :
1393 [ + + ]: 342 : if (pages <= 0.0)
1394 : 7 : pages = 1.0;
1395 : :
1396 : : /*
1397 : : * The first page in a range requires a random seek, but each subsequent
1398 : : * page is just a normal sequential page read. NOTE: it's desirable for
1399 : : * TID Range Scans to cost more than the equivalent Sequential Scans,
1400 : : * because Seq Scans have some performance advantages such as scan
1401 : : * synchronization, and we'd prefer one of them to be picked unless a TID
1402 : : * Range Scan really is better.
1403 : : */
1404 : 342 : ntuples = selectivity * baserel->tuples;
1405 : 342 : nseqpages = pages - 1.0;
1406 : :
1407 : : /*
1408 : : * The TID qual expressions will be computed once, any other baserestrict
1409 : : * quals once per retrieved tuple.
1410 : : */
1411 : 342 : cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1412 : :
1413 : : /* fetch estimated page cost for tablespace containing table */
1414 : 342 : get_tablespace_page_costs(baserel->reltablespace,
1415 : : &spc_random_page_cost,
1416 : : &spc_seq_page_cost);
1417 : :
1418 : : /* disk costs; 1 random page and the remainder as seq pages */
1419 : 342 : disk_run_cost = spc_random_page_cost + spc_seq_page_cost * nseqpages;
1420 : :
1421 : : /* Add scanning CPU costs */
1422 : 342 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1423 : :
1424 : : /*
1425 : : * XXX currently we assume TID quals are a subset of qpquals at this
1426 : : * point; they will be removed (if possible) when we create the plan, so
1427 : : * we subtract their cost from the total qpqual cost. (If the TID quals
1428 : : * can't be removed, this is a mistake and we're going to underestimate
1429 : : * the CPU cost a bit.)
1430 : : */
1431 : 342 : startup_cost = qpqual_cost.startup + tid_qual_cost.per_tuple;
1432 : 684 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1433 : 342 : tid_qual_cost.per_tuple;
1434 : 342 : cpu_run_cost = cpu_per_tuple * ntuples;
1435 : :
1436 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1437 : 342 : startup_cost += path->pathtarget->cost.startup;
1438 : 342 : cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
1439 : :
1440 : : /* Adjust costing for parallelism, if used. */
1441 [ + + ]: 342 : if (path->parallel_workers > 0)
1442 : : {
1443 : 8 : double parallel_divisor = get_parallel_divisor(path);
1444 : :
1445 : : /* The CPU cost is divided among all the workers. */
1446 : 8 : cpu_run_cost /= parallel_divisor;
1447 : :
1448 : : /*
1449 : : * In the case of a parallel plan, the row count needs to represent
1450 : : * the number of tuples processed per worker.
1451 : : */
1452 : 8 : path->rows = clamp_row_est(path->rows / parallel_divisor);
1453 : 8 : }
1454 : :
1455 : : /*
1456 : : * We should not generate this path type when PGS_TIDSCAN is unset, but we
1457 : : * might need to disable this path due to PGS_CONSIDER_NONPARTIAL.
1458 : : */
1459 [ + - ]: 342 : Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0);
1460 [ + + ]: 342 : if (path->parallel_workers == 0)
1461 : 334 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1462 : 342 : path->disabled_nodes =
1463 : 342 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1464 : 342 : path->disabled_nodes = 0;
1465 : 342 : path->startup_cost = startup_cost;
1466 : 342 : path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
1467 : 342 : }
1468 : :
1469 : : /*
1470 : : * cost_subqueryscan
1471 : : * Determines and returns the cost of scanning a subquery RTE.
1472 : : *
1473 : : * 'baserel' is the relation to be scanned
1474 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1475 : : * 'trivial_pathtarget' is true if the pathtarget is believed to be trivial.
1476 : : */
1477 : : void
1478 : 7026 : cost_subqueryscan(SubqueryScanPath *path, PlannerInfo *root,
1479 : : RelOptInfo *baserel, ParamPathInfo *param_info,
1480 : : bool trivial_pathtarget)
1481 : : {
1482 : 7026 : Cost startup_cost;
1483 : 7026 : Cost run_cost;
1484 : 7026 : List *qpquals;
1485 : 7026 : QualCost qpqual_cost;
1486 : 7026 : Cost cpu_per_tuple;
1487 : 7026 : uint64 enable_mask = 0;
1488 : :
1489 : : /* Should only be applied to base relations that are subqueries */
1490 [ + - ]: 7026 : Assert(baserel->relid > 0);
1491 [ + - ]: 7026 : Assert(baserel->rtekind == RTE_SUBQUERY);
1492 : :
1493 : : /*
1494 : : * We compute the rowcount estimate as the subplan's estimate times the
1495 : : * selectivity of relevant restriction clauses. In simple cases this will
1496 : : * come out the same as baserel->rows; but when dealing with parallelized
1497 : : * paths we must do it like this to get the right answer.
1498 : : */
1499 [ + + ]: 7026 : if (param_info)
1500 : 202 : qpquals = list_concat_copy(param_info->ppi_clauses,
1501 : 101 : baserel->baserestrictinfo);
1502 : : else
1503 : 6925 : qpquals = baserel->baserestrictinfo;
1504 : :
1505 : 14052 : path->path.rows = clamp_row_est(path->subpath->rows *
1506 : 14052 : clauselist_selectivity(root,
1507 : 7026 : qpquals,
1508 : : 0,
1509 : : JOIN_INNER,
1510 : : NULL));
1511 : :
1512 : : /*
1513 : : * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1514 : : * any restriction clauses and tlist that will be attached to the
1515 : : * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1516 : : * projection overhead.
1517 : : */
1518 [ + + ]: 7026 : if (path->path.parallel_workers == 0)
1519 : 7017 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1520 : 14052 : path->path.disabled_nodes = path->subpath->disabled_nodes
1521 : 7026 : + (((baserel->pgs_mask & enable_mask) != enable_mask) ? 1 : 0);
1522 : 7026 : path->path.startup_cost = path->subpath->startup_cost;
1523 : 7026 : path->path.total_cost = path->subpath->total_cost;
1524 : :
1525 : : /*
1526 : : * However, if there are no relevant restriction clauses and the
1527 : : * pathtarget is trivial, then we expect that setrefs.c will optimize away
1528 : : * the SubqueryScan plan node altogether, so we should just make its cost
1529 : : * and rowcount equal to the input path's.
1530 : : *
1531 : : * Note: there are some edge cases where createplan.c will apply a
1532 : : * different targetlist to the SubqueryScan node, thus falsifying our
1533 : : * current estimate of whether the target is trivial, and making the cost
1534 : : * estimate (though not the rowcount) wrong. It does not seem worth the
1535 : : * extra complication to try to account for that exactly, especially since
1536 : : * that behavior falsifies other cost estimates as well.
1537 : : */
1538 [ + + + + ]: 7026 : if (qpquals == NIL && trivial_pathtarget)
1539 : 3401 : return;
1540 : :
1541 : 3625 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1542 : :
1543 : 3625 : startup_cost = qpqual_cost.startup;
1544 : 3625 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1545 : 3625 : run_cost = cpu_per_tuple * path->subpath->rows;
1546 : :
1547 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1548 : 3625 : startup_cost += path->path.pathtarget->cost.startup;
1549 : 3625 : run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1550 : :
1551 : 3625 : path->path.startup_cost += startup_cost;
1552 : 3625 : path->path.total_cost += startup_cost + run_cost;
1553 [ - + ]: 7026 : }
1554 : :
1555 : : /*
1556 : : * cost_functionscan
1557 : : * Determines and returns the cost of scanning a function RTE.
1558 : : *
1559 : : * 'baserel' is the relation to be scanned
1560 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1561 : : */
1562 : : void
1563 : 3642 : cost_functionscan(Path *path, PlannerInfo *root,
1564 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1565 : : {
1566 : 3642 : Cost startup_cost = 0;
1567 : 3642 : Cost run_cost = 0;
1568 : 3642 : QualCost qpqual_cost;
1569 : 3642 : Cost cpu_per_tuple;
1570 : 3642 : RangeTblEntry *rte;
1571 : 3642 : QualCost exprcost;
1572 : 3642 : uint64 enable_mask = 0;
1573 : :
1574 : : /* Should only be applied to base relations that are functions */
1575 [ + - ]: 3642 : Assert(baserel->relid > 0);
1576 [ + - ]: 3642 : rte = planner_rt_fetch(baserel->relid, root);
1577 [ + - ]: 3642 : Assert(rte->rtekind == RTE_FUNCTION);
1578 : :
1579 : : /* Mark the path with the correct row estimate */
1580 [ + + ]: 3642 : if (param_info)
1581 : 98 : path->rows = param_info->ppi_rows;
1582 : : else
1583 : 3544 : path->rows = baserel->rows;
1584 : :
1585 : : /*
1586 : : * Estimate costs of executing the function expression(s).
1587 : : *
1588 : : * Currently, nodeFunctionscan.c always executes the functions to
1589 : : * completion before returning any rows, and caches the results in a
1590 : : * tuplestore. So the function eval cost is all startup cost, and per-row
1591 : : * costs are minimal.
1592 : : *
1593 : : * XXX in principle we ought to charge tuplestore spill costs if the
1594 : : * number of rows is large. However, given how phony our rowcount
1595 : : * estimates for functions tend to be, there's not a lot of point in that
1596 : : * refinement right now.
1597 : : */
1598 : 3642 : cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1599 : :
1600 : 3642 : startup_cost += exprcost.startup + exprcost.per_tuple;
1601 : :
1602 : : /* Add scanning CPU costs */
1603 : 3642 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1604 : :
1605 : 3642 : startup_cost += qpqual_cost.startup;
1606 : 3642 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1607 : 3642 : run_cost += cpu_per_tuple * baserel->tuples;
1608 : :
1609 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1610 : 3642 : startup_cost += path->pathtarget->cost.startup;
1611 : 3642 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1612 : :
1613 [ - + ]: 3642 : if (path->parallel_workers == 0)
1614 : 3642 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1615 : 3642 : path->disabled_nodes =
1616 : 3642 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1617 : 3642 : path->startup_cost = startup_cost;
1618 : 3642 : path->total_cost = startup_cost + run_cost;
1619 : 3642 : }
1620 : :
1621 : : /*
1622 : : * cost_tablefuncscan
1623 : : * Determines and returns the cost of scanning a table function.
1624 : : *
1625 : : * 'baserel' is the relation to be scanned
1626 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1627 : : */
1628 : : void
1629 : 103 : cost_tablefuncscan(Path *path, PlannerInfo *root,
1630 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1631 : : {
1632 : 103 : Cost startup_cost = 0;
1633 : 103 : Cost run_cost = 0;
1634 : 103 : QualCost qpqual_cost;
1635 : 103 : Cost cpu_per_tuple;
1636 : 103 : RangeTblEntry *rte;
1637 : 103 : QualCost exprcost;
1638 : 103 : uint64 enable_mask = 0;
1639 : :
1640 : : /* Should only be applied to base relations that are functions */
1641 [ + - ]: 103 : Assert(baserel->relid > 0);
1642 [ + - ]: 103 : rte = planner_rt_fetch(baserel->relid, root);
1643 [ + - ]: 103 : Assert(rte->rtekind == RTE_TABLEFUNC);
1644 : :
1645 : : /* Mark the path with the correct row estimate */
1646 [ + + ]: 103 : if (param_info)
1647 : 39 : path->rows = param_info->ppi_rows;
1648 : : else
1649 : 64 : path->rows = baserel->rows;
1650 : :
1651 : : /*
1652 : : * Estimate costs of executing the table func expression(s).
1653 : : *
1654 : : * XXX in principle we ought to charge tuplestore spill costs if the
1655 : : * number of rows is large. However, given how phony our rowcount
1656 : : * estimates for tablefuncs tend to be, there's not a lot of point in that
1657 : : * refinement right now.
1658 : : */
1659 : 103 : cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1660 : :
1661 : 103 : startup_cost += exprcost.startup + exprcost.per_tuple;
1662 : :
1663 : : /* Add scanning CPU costs */
1664 : 103 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1665 : :
1666 : 103 : startup_cost += qpqual_cost.startup;
1667 : 103 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1668 : 103 : run_cost += cpu_per_tuple * baserel->tuples;
1669 : :
1670 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1671 : 103 : startup_cost += path->pathtarget->cost.startup;
1672 : 103 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1673 : :
1674 [ - + ]: 103 : if (path->parallel_workers == 0)
1675 : 103 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1676 : 103 : path->disabled_nodes =
1677 : 103 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1678 : 103 : path->startup_cost = startup_cost;
1679 : 103 : path->total_cost = startup_cost + run_cost;
1680 : 103 : }
1681 : :
1682 : : /*
1683 : : * cost_valuesscan
1684 : : * Determines and returns the cost of scanning a VALUES RTE.
1685 : : *
1686 : : * 'baserel' is the relation to be scanned
1687 : : * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1688 : : */
1689 : : void
1690 : 1114 : cost_valuesscan(Path *path, PlannerInfo *root,
1691 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1692 : : {
1693 : 1114 : Cost startup_cost = 0;
1694 : 1114 : Cost run_cost = 0;
1695 : 1114 : QualCost qpqual_cost;
1696 : 1114 : Cost cpu_per_tuple;
1697 : 1114 : uint64 enable_mask = 0;
1698 : :
1699 : : /* Should only be applied to base relations that are values lists */
1700 [ + - ]: 1114 : Assert(baserel->relid > 0);
1701 [ + - ]: 1114 : Assert(baserel->rtekind == RTE_VALUES);
1702 : :
1703 : : /* Mark the path with the correct row estimate */
1704 [ + + ]: 1114 : if (param_info)
1705 : 11 : path->rows = param_info->ppi_rows;
1706 : : else
1707 : 1103 : path->rows = baserel->rows;
1708 : :
1709 : : /*
1710 : : * For now, estimate list evaluation cost at one operator eval per list
1711 : : * (probably pretty bogus, but is it worth being smarter?)
1712 : : */
1713 : 1114 : cpu_per_tuple = cpu_operator_cost;
1714 : :
1715 : : /* Add scanning CPU costs */
1716 : 1114 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1717 : :
1718 : 1114 : startup_cost += qpqual_cost.startup;
1719 : 1114 : cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1720 : 1114 : run_cost += cpu_per_tuple * baserel->tuples;
1721 : :
1722 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1723 : 1114 : startup_cost += path->pathtarget->cost.startup;
1724 : 1114 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1725 : :
1726 [ - + ]: 1114 : if (path->parallel_workers == 0)
1727 : 1114 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1728 : 1114 : path->disabled_nodes =
1729 : 1114 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1730 : 1114 : path->startup_cost = startup_cost;
1731 : 1114 : path->total_cost = startup_cost + run_cost;
1732 : 1114 : }
1733 : :
1734 : : /*
1735 : : * cost_ctescan
1736 : : * Determines and returns the cost of scanning a CTE RTE.
1737 : : *
1738 : : * Note: this is used for both self-reference and regular CTEs; the
1739 : : * possible cost differences are below the threshold of what we could
1740 : : * estimate accurately anyway. Note that the costs of evaluating the
1741 : : * referenced CTE query are added into the final plan as initplan costs,
1742 : : * and should NOT be counted here.
1743 : : */
1744 : : void
1745 : 286 : cost_ctescan(Path *path, PlannerInfo *root,
1746 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1747 : : {
1748 : 286 : Cost startup_cost = 0;
1749 : 286 : Cost run_cost = 0;
1750 : 286 : QualCost qpqual_cost;
1751 : 286 : Cost cpu_per_tuple;
1752 : 286 : uint64 enable_mask = 0;
1753 : :
1754 : : /* Should only be applied to base relations that are CTEs */
1755 [ + - ]: 286 : Assert(baserel->relid > 0);
1756 [ + - ]: 286 : Assert(baserel->rtekind == RTE_CTE);
1757 : :
1758 : : /* Mark the path with the correct row estimate */
1759 [ - + ]: 286 : if (param_info)
1760 : 0 : path->rows = param_info->ppi_rows;
1761 : : else
1762 : 286 : path->rows = baserel->rows;
1763 : :
1764 : : /* Charge one CPU tuple cost per row for tuplestore manipulation */
1765 : 286 : cpu_per_tuple = cpu_tuple_cost;
1766 : :
1767 : : /* Add scanning CPU costs */
1768 : 286 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1769 : :
1770 : 286 : startup_cost += qpqual_cost.startup;
1771 : 286 : cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1772 : 286 : run_cost += cpu_per_tuple * baserel->tuples;
1773 : :
1774 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1775 : 286 : startup_cost += path->pathtarget->cost.startup;
1776 : 286 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1777 : :
1778 [ - + ]: 286 : if (path->parallel_workers == 0)
1779 : 286 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1780 : 286 : path->disabled_nodes =
1781 : 286 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1782 : 286 : path->startup_cost = startup_cost;
1783 : 286 : path->total_cost = startup_cost + run_cost;
1784 : 286 : }
1785 : :
1786 : : /*
1787 : : * cost_namedtuplestorescan
1788 : : * Determines and returns the cost of scanning a named tuplestore.
1789 : : */
1790 : : void
1791 : 77 : cost_namedtuplestorescan(Path *path, PlannerInfo *root,
1792 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1793 : : {
1794 : 77 : Cost startup_cost = 0;
1795 : 77 : Cost run_cost = 0;
1796 : 77 : QualCost qpqual_cost;
1797 : 77 : Cost cpu_per_tuple;
1798 : 77 : uint64 enable_mask = 0;
1799 : :
1800 : : /* Should only be applied to base relations that are Tuplestores */
1801 [ + - ]: 77 : Assert(baserel->relid > 0);
1802 [ + - ]: 77 : Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1803 : :
1804 : : /* Mark the path with the correct row estimate */
1805 [ - + ]: 77 : if (param_info)
1806 : 0 : path->rows = param_info->ppi_rows;
1807 : : else
1808 : 77 : path->rows = baserel->rows;
1809 : :
1810 : : /* Charge one CPU tuple cost per row for tuplestore manipulation */
1811 : 77 : cpu_per_tuple = cpu_tuple_cost;
1812 : :
1813 : : /* Add scanning CPU costs */
1814 : 77 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1815 : :
1816 : 77 : startup_cost += qpqual_cost.startup;
1817 : 77 : cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1818 : 77 : run_cost += cpu_per_tuple * baserel->tuples;
1819 : :
1820 [ - + ]: 77 : if (path->parallel_workers == 0)
1821 : 77 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1822 : 77 : path->disabled_nodes =
1823 : 77 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1824 : 77 : path->startup_cost = startup_cost;
1825 : 77 : path->total_cost = startup_cost + run_cost;
1826 : 77 : }
1827 : :
1828 : : /*
1829 : : * cost_resultscan
1830 : : * Determines and returns the cost of scanning an RTE_RESULT relation.
1831 : : */
1832 : : void
1833 : 686 : cost_resultscan(Path *path, PlannerInfo *root,
1834 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1835 : : {
1836 : 686 : Cost startup_cost = 0;
1837 : 686 : Cost run_cost = 0;
1838 : 686 : QualCost qpqual_cost;
1839 : 686 : Cost cpu_per_tuple;
1840 : 686 : uint64 enable_mask = 0;
1841 : :
1842 : : /* Should only be applied to RTE_RESULT base relations */
1843 [ + - ]: 686 : Assert(baserel->relid > 0);
1844 [ + - ]: 686 : Assert(baserel->rtekind == RTE_RESULT);
1845 : :
1846 : : /* Mark the path with the correct row estimate */
1847 [ + + ]: 686 : if (param_info)
1848 : 26 : path->rows = param_info->ppi_rows;
1849 : : else
1850 : 660 : path->rows = baserel->rows;
1851 : :
1852 : : /* We charge qual cost plus cpu_tuple_cost */
1853 : 686 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1854 : :
1855 : 686 : startup_cost += qpqual_cost.startup;
1856 : 686 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1857 : 686 : run_cost += cpu_per_tuple * baserel->tuples;
1858 : :
1859 [ - + ]: 686 : if (path->parallel_workers == 0)
1860 : 686 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1861 : 686 : path->disabled_nodes =
1862 : 686 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1863 : 686 : path->startup_cost = startup_cost;
1864 : 686 : path->total_cost = startup_cost + run_cost;
1865 : 686 : }
1866 : :
1867 : : /*
1868 : : * cost_recursive_union
1869 : : * Determines and returns the cost of performing a recursive union,
1870 : : * and also the estimated output size.
1871 : : *
1872 : : * We are given Paths for the nonrecursive and recursive terms.
1873 : : */
1874 : : void
1875 : 73 : cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
1876 : : {
1877 : 73 : Cost startup_cost;
1878 : 73 : Cost total_cost;
1879 : 73 : double total_rows;
1880 : 73 : uint64 enable_mask = 0;
1881 : :
1882 : : /* We probably have decent estimates for the non-recursive term */
1883 : 73 : startup_cost = nrterm->startup_cost;
1884 : 73 : total_cost = nrterm->total_cost;
1885 : 73 : total_rows = nrterm->rows;
1886 : :
1887 : : /*
1888 : : * We arbitrarily assume that about 10 recursive iterations will be
1889 : : * needed, and that we've managed to get a good fix on the cost and output
1890 : : * size of each one of them. These are mighty shaky assumptions but it's
1891 : : * hard to see how to do better.
1892 : : */
1893 : 73 : total_cost += 10 * rterm->total_cost;
1894 : 73 : total_rows += 10 * rterm->rows;
1895 : :
1896 : : /*
1897 : : * Also charge cpu_tuple_cost per row to account for the costs of
1898 : : * manipulating the tuplestores. (We don't worry about possible
1899 : : * spill-to-disk costs.)
1900 : : */
1901 : 73 : total_cost += cpu_tuple_cost * total_rows;
1902 : :
1903 [ - + ]: 73 : if (runion->parallel_workers == 0)
1904 : 73 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1905 : 73 : runion->disabled_nodes =
1906 : 73 : (runion->parent->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1907 : 73 : runion->startup_cost = startup_cost;
1908 : 73 : runion->total_cost = total_cost;
1909 : 73 : runion->rows = total_rows;
1910 [ - + ]: 73 : runion->pathtarget->width = Max(nrterm->pathtarget->width,
1911 : : rterm->pathtarget->width);
1912 : 73 : }
1913 : :
1914 : : /*
1915 : : * cost_tuplesort
1916 : : * Determines and returns the cost of sorting a relation using tuplesort,
1917 : : * not including the cost of reading the input data.
1918 : : *
1919 : : * If the total volume of data to sort is less than sort_mem, we will do
1920 : : * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1921 : : * comparisons for t tuples.
1922 : : *
1923 : : * If the total volume exceeds sort_mem, we switch to a tape-style merge
1924 : : * algorithm. There will still be about t*log2(t) tuple comparisons in
1925 : : * total, but we will also need to write and read each tuple once per
1926 : : * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1927 : : * number of initial runs formed and M is the merge order used by tuplesort.c.
1928 : : * Since the average initial run should be about sort_mem, we have
1929 : : * disk traffic = 2 * relsize * ceil(logM(p / sort_mem))
1930 : : * cpu = comparison_cost * t * log2(t)
1931 : : *
1932 : : * If the sort is bounded (i.e., only the first k result tuples are needed)
1933 : : * and k tuples can fit into sort_mem, we use a heap method that keeps only
1934 : : * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1935 : : *
1936 : : * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1937 : : * accesses (XXX can't we refine that guess?)
1938 : : *
1939 : : * By default, we charge two operator evals per tuple comparison, which should
1940 : : * be in the right ballpark in most cases. The caller can tweak this by
1941 : : * specifying nonzero comparison_cost; typically that's used for any extra
1942 : : * work that has to be done to prepare the inputs to the comparison operators.
1943 : : *
1944 : : * 'tuples' is the number of tuples in the relation
1945 : : * 'width' is the average tuple width in bytes
1946 : : * 'comparison_cost' is the extra cost per comparison, if any
1947 : : * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1948 : : * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1949 : : */
1950 : : static void
1951 : 188787 : cost_tuplesort(Cost *startup_cost, Cost *run_cost,
1952 : : double tuples, int width,
1953 : : Cost comparison_cost, int sort_mem,
1954 : : double limit_tuples)
1955 : : {
1956 : 188787 : double input_bytes = relation_byte_size(tuples, width);
1957 : 188787 : double output_bytes;
1958 : 188787 : double output_tuples;
1959 : 188787 : int64 sort_mem_bytes = sort_mem * (int64) 1024;
1960 : :
1961 : : /*
1962 : : * We want to be sure the cost of a sort is never estimated as zero, even
1963 : : * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1964 : : */
1965 [ + + ]: 188787 : if (tuples < 2.0)
1966 : 54885 : tuples = 2.0;
1967 : :
1968 : : /* Include the default cost-per-comparison */
1969 : 188787 : comparison_cost += 2.0 * cpu_operator_cost;
1970 : :
1971 : : /* Do we have a useful LIMIT? */
1972 [ + + + + ]: 188787 : if (limit_tuples > 0 && limit_tuples < tuples)
1973 : : {
1974 : 196 : output_tuples = limit_tuples;
1975 : 196 : output_bytes = relation_byte_size(output_tuples, width);
1976 : 196 : }
1977 : : else
1978 : : {
1979 : 188591 : output_tuples = tuples;
1980 : 188591 : output_bytes = input_bytes;
1981 : : }
1982 : :
1983 [ + + ]: 188787 : if (output_bytes > sort_mem_bytes)
1984 : : {
1985 : : /*
1986 : : * We'll have to use a disk-based sort of all the tuples
1987 : : */
1988 : 1257 : double npages = ceil(input_bytes / BLCKSZ);
1989 : 1257 : double nruns = input_bytes / sort_mem_bytes;
1990 : 1257 : double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1991 : 1257 : double log_runs;
1992 : 1257 : double npageaccesses;
1993 : :
1994 : : /*
1995 : : * CPU costs
1996 : : *
1997 : : * Assume about N log2 N comparisons
1998 : : */
1999 : 1257 : *startup_cost = comparison_cost * tuples * LOG2(tuples);
2000 : :
2001 : : /* Disk costs */
2002 : :
2003 : : /* Compute logM(r) as log(r) / log(M) */
2004 [ + + ]: 1257 : if (nruns > mergeorder)
2005 : 406 : log_runs = ceil(log(nruns) / log(mergeorder));
2006 : : else
2007 : 851 : log_runs = 1.0;
2008 : 1257 : npageaccesses = 2.0 * npages * log_runs;
2009 : : /* Assume 3/4ths of accesses are sequential, 1/4th are not */
2010 : 2514 : *startup_cost += npageaccesses *
2011 : 1257 : (seq_page_cost * 0.75 + random_page_cost * 0.25);
2012 : 1257 : }
2013 [ + + - + ]: 187530 : else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
2014 : : {
2015 : : /*
2016 : : * We'll use a bounded heap-sort keeping just K tuples in memory, for
2017 : : * a total number of tuple comparisons of N log2 K; but the constant
2018 : : * factor is a bit higher than for quicksort. Tweak it so that the
2019 : : * cost curve is continuous at the crossover point.
2020 : : */
2021 : 132 : *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
2022 : 132 : }
2023 : : else
2024 : : {
2025 : : /* We'll use plain quicksort on all the input tuples */
2026 : 187398 : *startup_cost = comparison_cost * tuples * LOG2(tuples);
2027 : : }
2028 : :
2029 : : /*
2030 : : * Also charge a small amount (arbitrarily set equal to operator cost) per
2031 : : * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
2032 : : * doesn't do qual-checking or projection, so it has less overhead than
2033 : : * most plan nodes. Note it's correct to use tuples not output_tuples
2034 : : * here --- the upper LIMIT will pro-rate the run cost so we'd be double
2035 : : * counting the LIMIT otherwise.
2036 : : */
2037 : 188787 : *run_cost = cpu_operator_cost * tuples;
2038 : 188787 : }
2039 : :
2040 : : /*
2041 : : * cost_incremental_sort
2042 : : * Determines and returns the cost of sorting a relation incrementally, when
2043 : : * the input path is presorted by a prefix of the pathkeys.
2044 : : *
2045 : : * 'presorted_keys' is the number of leading pathkeys by which the input path
2046 : : * is sorted.
2047 : : *
2048 : : * We estimate the number of groups into which the relation is divided by the
2049 : : * leading pathkeys, and then calculate the cost of sorting a single group
2050 : : * with tuplesort using cost_tuplesort().
2051 : : */
2052 : : void
2053 : 1409 : cost_incremental_sort(Path *path,
2054 : : PlannerInfo *root, List *pathkeys, int presorted_keys,
2055 : : int input_disabled_nodes,
2056 : : Cost input_startup_cost, Cost input_total_cost,
2057 : : double input_tuples, int width, Cost comparison_cost, int sort_mem,
2058 : : double limit_tuples)
2059 : : {
2060 : 1409 : Cost startup_cost,
2061 : : run_cost,
2062 : 1409 : input_run_cost = input_total_cost - input_startup_cost;
2063 : 1409 : double group_tuples,
2064 : : input_groups;
2065 : 1409 : Cost group_startup_cost,
2066 : : group_run_cost,
2067 : : group_input_run_cost;
2068 : 1409 : List *presortedExprs = NIL;
2069 : 1409 : ListCell *l;
2070 : 1409 : bool unknown_varno = false;
2071 : :
2072 [ + - ]: 1409 : Assert(presorted_keys > 0 && presorted_keys < list_length(pathkeys));
2073 : :
2074 : : /*
2075 : : * We want to be sure the cost of a sort is never estimated as zero, even
2076 : : * if passed-in tuple count is zero. Besides, mustn't do log(0)...
2077 : : */
2078 [ + + ]: 1409 : if (input_tuples < 2.0)
2079 : 972 : input_tuples = 2.0;
2080 : :
2081 : : /* Default estimate of number of groups, capped to one group per row. */
2082 [ + + ]: 1409 : input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
2083 : :
2084 : : /*
2085 : : * Extract presorted keys as list of expressions.
2086 : : *
2087 : : * We need to be careful about Vars containing "varno 0" which might have
2088 : : * been introduced by generate_append_tlist, which would confuse
2089 : : * estimate_num_groups (in fact it'd fail for such expressions). See
2090 : : * recurse_set_operations which has to deal with the same issue.
2091 : : *
2092 : : * Unlike recurse_set_operations we can't access the original target list
2093 : : * here, and even if we could it's not very clear how useful would that be
2094 : : * for a set operation combining multiple tables. So we simply detect if
2095 : : * there are any expressions with "varno 0" and use the default
2096 : : * DEFAULT_NUM_DISTINCT in that case.
2097 : : *
2098 : : * We might also use either 1.0 (a single group) or input_tuples (each row
2099 : : * being a separate group), pretty much the worst and best case for
2100 : : * incremental sort. But those are extreme cases and using something in
2101 : : * between seems reasonable. Furthermore, generate_append_tlist is used
2102 : : * for set operations, which are likely to produce mostly unique output
2103 : : * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2104 : : * while maintaining lower startup cost.
2105 : : */
2106 [ + - - + : 2834 : foreach(l, pathkeys)
+ - ]
2107 : : {
2108 : 1425 : PathKey *key = (PathKey *) lfirst(l);
2109 : 2850 : EquivalenceMember *member = (EquivalenceMember *)
2110 : 1425 : linitial(key->pk_eclass->ec_members);
2111 : :
2112 : : /*
2113 : : * Check if the expression contains Var with "varno 0" so that we
2114 : : * don't call estimate_num_groups in that case.
2115 : : */
2116 [ + + ]: 1425 : if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2117 : : {
2118 : 1 : unknown_varno = true;
2119 : 1 : break;
2120 : : }
2121 : :
2122 : : /* expression not containing any Vars with "varno 0" */
2123 : 1424 : presortedExprs = lappend(presortedExprs, member->em_expr);
2124 : :
2125 [ + + ]: 1424 : if (foreach_current_index(l) + 1 >= presorted_keys)
2126 : 1408 : break;
2127 [ + + ]: 1425 : }
2128 : :
2129 : : /* Estimate the number of groups with equal presorted keys. */
2130 [ + + ]: 1409 : if (!unknown_varno)
2131 : 1408 : input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2132 : : NULL, NULL);
2133 : :
2134 : 1409 : group_tuples = input_tuples / input_groups;
2135 : 1409 : group_input_run_cost = input_run_cost / input_groups;
2136 : :
2137 : : /*
2138 : : * Estimate the average cost of sorting of one group where presorted keys
2139 : : * are equal.
2140 : : */
2141 : 1409 : cost_tuplesort(&group_startup_cost, &group_run_cost,
2142 : 1409 : group_tuples, width, comparison_cost, sort_mem,
2143 : 1409 : limit_tuples);
2144 : :
2145 : : /*
2146 : : * Startup cost of incremental sort is the startup cost of its first group
2147 : : * plus the cost of its input.
2148 : : */
2149 : 2818 : startup_cost = group_startup_cost + input_startup_cost +
2150 : 1409 : group_input_run_cost;
2151 : :
2152 : : /*
2153 : : * After we started producing tuples from the first group, the cost of
2154 : : * producing all the tuples is given by the cost to finish processing this
2155 : : * group, plus the total cost to process the remaining groups, plus the
2156 : : * remaining cost of input.
2157 : : */
2158 : 4227 : run_cost = group_run_cost + (group_run_cost + group_startup_cost) *
2159 : 2818 : (input_groups - 1) + group_input_run_cost * (input_groups - 1);
2160 : :
2161 : : /*
2162 : : * Incremental sort adds some overhead by itself. Firstly, it has to
2163 : : * detect the sort groups. This is roughly equal to one extra copy and
2164 : : * comparison per tuple.
2165 : : */
2166 : 1409 : run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2167 : :
2168 : : /*
2169 : : * Additionally, we charge double cpu_tuple_cost for each input group to
2170 : : * account for the tuplesort_reset that's performed after each group.
2171 : : */
2172 : 1409 : run_cost += 2.0 * cpu_tuple_cost * input_groups;
2173 : :
2174 : 1409 : path->rows = input_tuples;
2175 : :
2176 : : /*
2177 : : * We should not generate these paths when enable_incremental_sort=false.
2178 : : * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
2179 : : * it will have already affected the input path.
2180 : : */
2181 [ + - ]: 1409 : Assert(enable_incremental_sort);
2182 : 1409 : path->disabled_nodes = input_disabled_nodes;
2183 : :
2184 : 1409 : path->startup_cost = startup_cost;
2185 : 1409 : path->total_cost = startup_cost + run_cost;
2186 : 1409 : }
2187 : :
2188 : : /*
2189 : : * cost_sort
2190 : : * Determines and returns the cost of sorting a relation, including
2191 : : * the cost of reading the input data.
2192 : : *
2193 : : * NOTE: some callers currently pass NIL for pathkeys because they
2194 : : * can't conveniently supply the sort keys. Since this routine doesn't
2195 : : * currently do anything with pathkeys anyway, that doesn't matter...
2196 : : * but if it ever does, it should react gracefully to lack of key data.
2197 : : * (Actually, the thing we'd most likely be interested in is just the number
2198 : : * of sort keys, which all callers *could* supply.)
2199 : : */
2200 : : void
2201 : 187378 : cost_sort(Path *path, PlannerInfo *root,
2202 : : List *pathkeys, int input_disabled_nodes,
2203 : : Cost input_cost, double tuples, int width,
2204 : : Cost comparison_cost, int sort_mem,
2205 : : double limit_tuples)
2206 : :
2207 : : {
2208 : 187378 : Cost startup_cost;
2209 : 187378 : Cost run_cost;
2210 : :
2211 : 187378 : cost_tuplesort(&startup_cost, &run_cost,
2212 : 187378 : tuples, width,
2213 : 187378 : comparison_cost, sort_mem,
2214 : 187378 : limit_tuples);
2215 : :
2216 : 187378 : startup_cost += input_cost;
2217 : :
2218 : : /*
2219 : : * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
2220 : : * it will have already affected the input path.
2221 : : */
2222 : 187378 : path->rows = tuples;
2223 : 187378 : path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
2224 : 187378 : path->startup_cost = startup_cost;
2225 : 187378 : path->total_cost = startup_cost + run_cost;
2226 : 187378 : }
2227 : :
2228 : : /*
2229 : : * append_nonpartial_cost
2230 : : * Estimate the cost of the non-partial paths in a Parallel Append.
2231 : : * The non-partial paths are assumed to be the first "numpaths" paths
2232 : : * from the subpaths list, and to be in order of decreasing cost.
2233 : : */
2234 : : static Cost
2235 : 4107 : append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
2236 : : {
2237 : 4107 : Cost *costarr;
2238 : 4107 : int arrlen;
2239 : 4107 : ListCell *l;
2240 : 4107 : ListCell *cell;
2241 : 4107 : int path_index;
2242 : 4107 : int min_index;
2243 : 4107 : int max_index;
2244 : :
2245 [ + + ]: 4107 : if (numpaths == 0)
2246 : 3395 : return 0;
2247 : :
2248 : : /*
2249 : : * Array length is number of workers or number of relevant paths,
2250 : : * whichever is less.
2251 : : */
2252 [ + + ]: 712 : arrlen = Min(parallel_workers, numpaths);
2253 : 712 : costarr = palloc_array(Cost, arrlen);
2254 : :
2255 : : /* The first few paths will each be claimed by a different worker. */
2256 : 712 : path_index = 0;
2257 [ + - + + : 2211 : foreach(cell, subpaths)
+ + ]
2258 : : {
2259 : 1499 : Path *subpath = (Path *) lfirst(cell);
2260 : :
2261 [ + + ]: 1499 : if (path_index == arrlen)
2262 : 151 : break;
2263 : 1348 : costarr[path_index++] = subpath->total_cost;
2264 [ + + ]: 1499 : }
2265 : :
2266 : : /*
2267 : : * Since subpaths are sorted by decreasing cost, the last one will have
2268 : : * the minimum cost.
2269 : : */
2270 : 712 : min_index = arrlen - 1;
2271 : :
2272 : : /*
2273 : : * For each of the remaining subpaths, add its cost to the array element
2274 : : * with minimum cost.
2275 : : */
2276 [ + - + + : 902 : for_each_cell(l, subpaths, cell)
+ + ]
2277 : : {
2278 : 190 : Path *subpath = (Path *) lfirst(l);
2279 : :
2280 : : /* Consider only the non-partial paths */
2281 [ + + ]: 190 : if (path_index++ == numpaths)
2282 : 88 : break;
2283 : :
2284 : 102 : costarr[min_index] += subpath->total_cost;
2285 : :
2286 : : /* Update the new min cost array index */
2287 : 102 : min_index = 0;
2288 [ + + ]: 312 : for (int i = 0; i < arrlen; i++)
2289 : : {
2290 [ + + ]: 210 : if (costarr[i] < costarr[min_index])
2291 : 38 : min_index = i;
2292 : 210 : }
2293 [ + + ]: 190 : }
2294 : :
2295 : : /* Return the highest cost from the array */
2296 : 712 : max_index = 0;
2297 [ + + ]: 2060 : for (int i = 0; i < arrlen; i++)
2298 : : {
2299 [ + + ]: 1348 : if (costarr[i] > costarr[max_index])
2300 : 41 : max_index = i;
2301 : 1348 : }
2302 : :
2303 : 712 : return costarr[max_index];
2304 : 4107 : }
2305 : :
2306 : : /*
2307 : : * cost_append
2308 : : * Determines and returns the cost of an Append node.
2309 : : */
2310 : : void
2311 : 10951 : cost_append(AppendPath *apath, PlannerInfo *root)
2312 : : {
2313 : 10951 : RelOptInfo *rel = apath->path.parent;
2314 : 10951 : ListCell *l;
2315 : 10951 : uint64 enable_mask = PGS_APPEND;
2316 : :
2317 [ + + ]: 10951 : if (apath->path.parallel_workers == 0)
2318 : 6836 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
2319 : :
2320 : 10951 : apath->path.disabled_nodes =
2321 : 10951 : (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
2322 : 10951 : apath->path.startup_cost = 0;
2323 : 10951 : apath->path.total_cost = 0;
2324 : 10951 : apath->path.rows = 0;
2325 : :
2326 [ + + ]: 10951 : if (apath->subpaths == NIL)
2327 : 316 : return;
2328 : :
2329 [ + + ]: 10635 : if (!apath->path.parallel_aware)
2330 : : {
2331 : 6528 : List *pathkeys = apath->path.pathkeys;
2332 : :
2333 [ + + ]: 6528 : if (pathkeys == NIL)
2334 : : {
2335 : 6182 : Path *firstsubpath = (Path *) linitial(apath->subpaths);
2336 : :
2337 : : /*
2338 : : * For an unordered, non-parallel-aware Append we take the startup
2339 : : * cost as the startup cost of the first subpath.
2340 : : */
2341 : 6182 : apath->path.startup_cost = firstsubpath->startup_cost;
2342 : :
2343 : : /*
2344 : : * Compute rows, number of disabled nodes, and total cost as sums
2345 : : * of underlying subplan values.
2346 : : */
2347 [ + - + + : 23802 : foreach(l, apath->subpaths)
+ + ]
2348 : : {
2349 : 17620 : Path *subpath = (Path *) lfirst(l);
2350 : :
2351 : 17620 : apath->path.rows += subpath->rows;
2352 : 17620 : apath->path.disabled_nodes += subpath->disabled_nodes;
2353 : 17620 : apath->path.total_cost += subpath->total_cost;
2354 : 17620 : }
2355 : 6182 : }
2356 : : else
2357 : : {
2358 : : /*
2359 : : * For an ordered, non-parallel-aware Append we take the startup
2360 : : * cost as the sum of the subpath startup costs. This ensures
2361 : : * that we don't underestimate the startup cost when a query's
2362 : : * LIMIT is such that several of the children have to be run to
2363 : : * satisfy it. This might be overkill --- another plausible hack
2364 : : * would be to take the Append's startup cost as the maximum of
2365 : : * the child startup costs. But we don't want to risk believing
2366 : : * that an ORDER BY LIMIT query can be satisfied at small cost
2367 : : * when the first child has small startup cost but later ones
2368 : : * don't. (If we had the ability to deal with nonlinear cost
2369 : : * interpolation for partial retrievals, we would not need to be
2370 : : * so conservative about this.)
2371 : : *
2372 : : * This case is also different from the above in that we have to
2373 : : * account for possibly injecting sorts into subpaths that aren't
2374 : : * natively ordered.
2375 : : */
2376 [ + - + + : 1365 : foreach(l, apath->subpaths)
+ + ]
2377 : : {
2378 : 1019 : Path *subpath = (Path *) lfirst(l);
2379 : 1019 : int presorted_keys;
2380 : 1019 : Path sort_path; /* dummy for result of
2381 : : * cost_sort/cost_incremental_sort */
2382 : :
2383 [ + + ]: 1019 : if (!pathkeys_count_contained_in(pathkeys, subpath->pathkeys,
2384 : : &presorted_keys))
2385 : : {
2386 : : /*
2387 : : * We'll need to insert a Sort node, so include costs for
2388 : : * that. We choose to use incremental sort if it is
2389 : : * enabled and there are presorted keys; otherwise we use
2390 : : * full sort.
2391 : : *
2392 : : * We can use the parent's LIMIT if any, since we
2393 : : * certainly won't pull more than that many tuples from
2394 : : * any child.
2395 : : */
2396 [ + - + + ]: 4 : if (enable_incremental_sort && presorted_keys > 0)
2397 : : {
2398 : 2 : cost_incremental_sort(&sort_path,
2399 : 2 : root,
2400 : 2 : pathkeys,
2401 : 2 : presorted_keys,
2402 : 2 : subpath->disabled_nodes,
2403 : 2 : subpath->startup_cost,
2404 : 2 : subpath->total_cost,
2405 : 2 : subpath->rows,
2406 : 2 : subpath->pathtarget->width,
2407 : : 0.0,
2408 : 2 : work_mem,
2409 : 2 : apath->limit_tuples);
2410 : 2 : }
2411 : : else
2412 : : {
2413 : 2 : cost_sort(&sort_path,
2414 : 2 : root,
2415 : 2 : pathkeys,
2416 : 2 : subpath->disabled_nodes,
2417 : 2 : subpath->total_cost,
2418 : 2 : subpath->rows,
2419 : 2 : subpath->pathtarget->width,
2420 : : 0.0,
2421 : 2 : work_mem,
2422 : 2 : apath->limit_tuples);
2423 : : }
2424 : :
2425 : 4 : subpath = &sort_path;
2426 : 4 : }
2427 : :
2428 : 1019 : apath->path.rows += subpath->rows;
2429 : 1019 : apath->path.disabled_nodes += subpath->disabled_nodes;
2430 : 1019 : apath->path.startup_cost += subpath->startup_cost;
2431 : 1019 : apath->path.total_cost += subpath->total_cost;
2432 : 1019 : }
2433 : : }
2434 : 6528 : }
2435 : : else /* parallel-aware */
2436 : : {
2437 : 4107 : int i = 0;
2438 : 4107 : double parallel_divisor = get_parallel_divisor(&apath->path);
2439 : :
2440 : : /* Parallel-aware Append never produces ordered output. */
2441 [ + - ]: 4107 : Assert(apath->path.pathkeys == NIL);
2442 : :
2443 : : /* Calculate startup cost. */
2444 [ + - + + : 15788 : foreach(l, apath->subpaths)
+ + ]
2445 : : {
2446 : 11681 : Path *subpath = (Path *) lfirst(l);
2447 : :
2448 : : /*
2449 : : * Append will start returning tuples when the child node having
2450 : : * lowest startup cost is done setting up. We consider only the
2451 : : * first few subplans that immediately get a worker assigned.
2452 : : */
2453 [ + + ]: 11681 : if (i == 0)
2454 : 4107 : apath->path.startup_cost = subpath->startup_cost;
2455 [ + + ]: 7574 : else if (i < apath->path.parallel_workers)
2456 [ + + ]: 4012 : apath->path.startup_cost = Min(apath->path.startup_cost,
2457 : : subpath->startup_cost);
2458 : :
2459 : : /*
2460 : : * Apply parallel divisor to subpaths. Scale the number of rows
2461 : : * for each partial subpath based on the ratio of the parallel
2462 : : * divisor originally used for the subpath to the one we adopted.
2463 : : * Also add the cost of partial paths to the total cost, but
2464 : : * ignore non-partial paths for now.
2465 : : */
2466 [ + + ]: 11681 : if (i < apath->first_partial_path)
2467 : 1450 : apath->path.rows += subpath->rows / parallel_divisor;
2468 : : else
2469 : : {
2470 : 10231 : double subpath_parallel_divisor;
2471 : :
2472 : 10231 : subpath_parallel_divisor = get_parallel_divisor(subpath);
2473 : 20462 : apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2474 : 10231 : parallel_divisor);
2475 : 10231 : apath->path.total_cost += subpath->total_cost;
2476 : 10231 : }
2477 : :
2478 : 11681 : apath->path.disabled_nodes += subpath->disabled_nodes;
2479 : 11681 : apath->path.rows = clamp_row_est(apath->path.rows);
2480 : :
2481 : 11681 : i++;
2482 : 11681 : }
2483 : :
2484 : : /* Add cost for non-partial subpaths. */
2485 : 4107 : apath->path.total_cost +=
2486 : 8214 : append_nonpartial_cost(apath->subpaths,
2487 : 4107 : apath->first_partial_path,
2488 : 4107 : apath->path.parallel_workers);
2489 : 4107 : }
2490 : :
2491 : : /*
2492 : : * Although Append does not do any selection or projection, it's not free;
2493 : : * add a small per-tuple overhead.
2494 : : */
2495 : 10635 : apath->path.total_cost +=
2496 : 10635 : cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * apath->path.rows;
2497 [ - + ]: 10951 : }
2498 : :
2499 : : /*
2500 : : * cost_merge_append
2501 : : * Determines and returns the cost of a MergeAppend node.
2502 : : *
2503 : : * MergeAppend merges several pre-sorted input streams, using a heap that
2504 : : * at any given instant holds the next tuple from each stream. If there
2505 : : * are N streams, we need about N*log2(N) tuple comparisons to construct
2506 : : * the heap at startup, and then for each output tuple, about log2(N)
2507 : : * comparisons to replace the top entry.
2508 : : *
2509 : : * (The effective value of N will drop once some of the input streams are
2510 : : * exhausted, but it seems unlikely to be worth trying to account for that.)
2511 : : *
2512 : : * The heap is never spilled to disk, since we assume N is not very large.
2513 : : * So this is much simpler than cost_sort.
2514 : : *
2515 : : * As in cost_sort, we charge two operator evals per tuple comparison.
2516 : : *
2517 : : * 'pathkeys' is a list of sort keys
2518 : : * 'n_streams' is the number of input streams
2519 : : * 'input_disabled_nodes' is the sum of the input streams' disabled node counts
2520 : : * 'input_startup_cost' is the sum of the input streams' startup costs
2521 : : * 'input_total_cost' is the sum of the input streams' total costs
2522 : : * 'tuples' is the number of tuples in all the streams
2523 : : */
2524 : : void
2525 : 1635 : cost_merge_append(Path *path, PlannerInfo *root,
2526 : : List *pathkeys, int n_streams,
2527 : : int input_disabled_nodes,
2528 : : Cost input_startup_cost, Cost input_total_cost,
2529 : : double tuples)
2530 : : {
2531 : 1635 : RelOptInfo *rel = path->parent;
2532 : 1635 : Cost startup_cost = 0;
2533 : 1635 : Cost run_cost = 0;
2534 : 1635 : Cost comparison_cost;
2535 : 1635 : double N;
2536 : 1635 : double logN;
2537 : 1635 : uint64 enable_mask = PGS_MERGE_APPEND;
2538 : :
2539 [ - + ]: 1635 : if (path->parallel_workers == 0)
2540 : 1635 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
2541 : :
2542 : : /*
2543 : : * Avoid log(0)...
2544 : : */
2545 [ - + ]: 1635 : N = (n_streams < 2) ? 2.0 : (double) n_streams;
2546 : 1635 : logN = LOG2(N);
2547 : :
2548 : : /* Assumed cost per tuple comparison */
2549 : 1635 : comparison_cost = 2.0 * cpu_operator_cost;
2550 : :
2551 : : /* Heap creation cost */
2552 : 1635 : startup_cost += comparison_cost * N * logN;
2553 : :
2554 : : /* Per-tuple heap maintenance cost */
2555 : 1635 : run_cost += tuples * comparison_cost * logN;
2556 : :
2557 : : /*
2558 : : * Although MergeAppend does not do any selection or projection, it's not
2559 : : * free; add a small per-tuple overhead.
2560 : : */
2561 : 1635 : run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2562 : :
2563 : 1635 : path->disabled_nodes =
2564 : 1635 : (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
2565 : 1635 : path->disabled_nodes += input_disabled_nodes;
2566 : 1635 : path->startup_cost = startup_cost + input_startup_cost;
2567 : 1635 : path->total_cost = startup_cost + run_cost + input_total_cost;
2568 : 1635 : }
2569 : :
2570 : : /*
2571 : : * cost_material
2572 : : * Determines and returns the cost of materializing a relation, including
2573 : : * the cost of reading the input data.
2574 : : *
2575 : : * If the total volume of data to materialize exceeds work_mem, we will need
2576 : : * to write it to disk, so the cost is much higher in that case.
2577 : : *
2578 : : * Note that here we are estimating the costs for the first scan of the
2579 : : * relation, so the materialization is all overhead --- any savings will
2580 : : * occur only on rescan, which is estimated in cost_rescan.
2581 : : */
2582 : : void
2583 : 68711 : cost_material(Path *path,
2584 : : bool enabled, int input_disabled_nodes,
2585 : : Cost input_startup_cost, Cost input_total_cost,
2586 : : double tuples, int width)
2587 : : {
2588 : 68711 : Cost startup_cost = input_startup_cost;
2589 : 68711 : Cost run_cost = input_total_cost - input_startup_cost;
2590 : 68711 : double nbytes = relation_byte_size(tuples, width);
2591 : 68711 : double work_mem_bytes = work_mem * (Size) 1024;
2592 : :
2593 [ + + ]: 68711 : if (path->parallel_workers == 0 &&
2594 [ + + + + ]: 68704 : path->parent != NULL &&
2595 : 68699 : (path->parent->pgs_mask & PGS_CONSIDER_NONPARTIAL) == 0)
2596 : 8 : enabled = false;
2597 : :
2598 : 68711 : path->rows = tuples;
2599 : :
2600 : : /*
2601 : : * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2602 : : * reflect bookkeeping overhead. (This rate must be more than what
2603 : : * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2604 : : * if it is exactly the same then there will be a cost tie between
2605 : : * nestloop with A outer, materialized B inner and nestloop with B outer,
2606 : : * materialized A inner. The extra cost ensures we'll prefer
2607 : : * materializing the smaller rel.) Note that this is normally a good deal
2608 : : * less than cpu_tuple_cost; which is OK because a Material plan node
2609 : : * doesn't do qual-checking or projection, so it's got less overhead than
2610 : : * most plan nodes.
2611 : : */
2612 : 68711 : run_cost += 2 * cpu_operator_cost * tuples;
2613 : :
2614 : : /*
2615 : : * If we will spill to disk, charge at the rate of seq_page_cost per page.
2616 : : * This cost is assumed to be evenly spread through the plan run phase,
2617 : : * which isn't exactly accurate but our cost model doesn't allow for
2618 : : * nonuniform costs within the run phase.
2619 : : */
2620 [ + + ]: 68711 : if (nbytes > work_mem_bytes)
2621 : : {
2622 : 423 : double npages = ceil(nbytes / BLCKSZ);
2623 : :
2624 : 423 : run_cost += seq_page_cost * npages;
2625 : 423 : }
2626 : :
2627 : 68711 : path->disabled_nodes = input_disabled_nodes + (enabled ? 0 : 1);
2628 : 68711 : path->startup_cost = startup_cost;
2629 : 68711 : path->total_cost = startup_cost + run_cost;
2630 : 68711 : }
2631 : :
2632 : : /*
2633 : : * cost_memoize_rescan
2634 : : * Determines the estimated cost of rescanning a Memoize node.
2635 : : *
2636 : : * In order to estimate this, we must gain knowledge of how often we expect to
2637 : : * be called and how many distinct sets of parameters we are likely to be
2638 : : * called with. If we expect a good cache hit ratio, then we can set our
2639 : : * costs to account for that hit ratio, plus a little bit of cost for the
2640 : : * caching itself. Caching will not work out well if we expect to be called
2641 : : * with too many distinct parameter values. The worst-case here is that we
2642 : : * never see any parameter value twice, in which case we'd never get a cache
2643 : : * hit and caching would be a complete waste of effort.
2644 : : */
2645 : : static void
2646 : 18403 : cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath,
2647 : : Cost *rescan_startup_cost, Cost *rescan_total_cost)
2648 : : {
2649 : 18403 : EstimationInfo estinfo;
2650 : 18403 : ListCell *lc;
2651 : 18403 : Cost input_startup_cost = mpath->subpath->startup_cost;
2652 : 18403 : Cost input_total_cost = mpath->subpath->total_cost;
2653 : 18403 : double tuples = mpath->subpath->rows;
2654 : 18403 : Cardinality est_calls = mpath->est_calls;
2655 : 18403 : int width = mpath->subpath->pathtarget->width;
2656 : :
2657 : 18403 : double hash_mem_bytes;
2658 : 18403 : double est_entry_bytes;
2659 : 18403 : Cardinality est_cache_entries;
2660 : 18403 : Cardinality ndistinct;
2661 : 18403 : double evict_ratio;
2662 : 18403 : double hit_ratio;
2663 : 18403 : Cost startup_cost;
2664 : 18403 : Cost total_cost;
2665 : :
2666 : : /* available cache space */
2667 : 18403 : hash_mem_bytes = get_hash_memory_limit();
2668 : :
2669 : : /*
2670 : : * Set the number of bytes each cache entry should consume in the cache.
2671 : : * To provide us with better estimations on how many cache entries we can
2672 : : * store at once, we make a call to the executor here to ask it what
2673 : : * memory overheads there are for a single cache entry.
2674 : : */
2675 : 36806 : est_entry_bytes = relation_byte_size(tuples, width) +
2676 : 18403 : ExecEstimateCacheEntryOverheadBytes(tuples);
2677 : :
2678 : : /* include the estimated width for the cache keys */
2679 [ + - + + : 38232 : foreach(lc, mpath->param_exprs)
+ + ]
2680 : 19829 : est_entry_bytes += get_expr_width(root, (Node *) lfirst(lc));
2681 : :
2682 : : /* estimate on the upper limit of cache entries we can hold at once */
2683 : 18403 : est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2684 : :
2685 : : /* estimate on the distinct number of parameter values */
2686 : 18403 : ndistinct = estimate_num_groups(root, mpath->param_exprs, est_calls, NULL,
2687 : : &estinfo);
2688 : :
2689 : : /*
2690 : : * When the estimation fell back on using a default value, it's a bit too
2691 : : * risky to assume that it's ok to use a Memoize node. The use of a
2692 : : * default could cause us to use a Memoize node when it's really
2693 : : * inappropriate to do so. If we see that this has been done, then we'll
2694 : : * assume that every call will have unique parameters, which will almost
2695 : : * certainly mean a MemoizePath will never survive add_path().
2696 : : */
2697 [ + + ]: 18403 : if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2698 : 2310 : ndistinct = est_calls;
2699 : :
2700 : : /* Remember the ndistinct estimate for EXPLAIN */
2701 : 18403 : mpath->est_unique_keys = ndistinct;
2702 : :
2703 : : /*
2704 : : * Since we've already estimated the maximum number of entries we can
2705 : : * store at once and know the estimated number of distinct values we'll be
2706 : : * called with, we'll take this opportunity to set the path's est_entries.
2707 : : * This will ultimately determine the hash table size that the executor
2708 : : * will use. If we leave this at zero, the executor will just choose the
2709 : : * size itself. Really this is not the right place to do this, but it's
2710 : : * convenient since everything is already calculated.
2711 : : */
2712 [ + + + - : 18403 : mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
+ + ]
2713 : : PG_UINT32_MAX);
2714 : :
2715 : : /*
2716 : : * When the number of distinct parameter values is above the amount we can
2717 : : * store in the cache, then we'll have to evict some entries from the
2718 : : * cache. This is not free. Here we estimate how often we'll incur the
2719 : : * cost of that eviction.
2720 : : */
2721 [ + + ]: 18403 : evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2722 : :
2723 : : /*
2724 : : * In order to estimate how costly a single scan will be, we need to
2725 : : * attempt to estimate what the cache hit ratio will be. To do that we
2726 : : * must look at how many scans are estimated in total for this node and
2727 : : * how many of those scans we expect to get a cache hit.
2728 : : */
2729 : 36806 : hit_ratio = ((est_calls - ndistinct) / est_calls) *
2730 [ + + ]: 18403 : (est_cache_entries / Max(ndistinct, est_cache_entries));
2731 : :
2732 : : /* Remember the hit ratio estimate for EXPLAIN */
2733 : 18403 : mpath->est_hit_ratio = hit_ratio;
2734 : :
2735 [ + - ]: 18403 : Assert(hit_ratio >= 0 && hit_ratio <= 1.0);
2736 : :
2737 : : /*
2738 : : * Set the total_cost accounting for the expected cache hit ratio. We
2739 : : * also add on a cpu_operator_cost to account for a cache lookup. This
2740 : : * will happen regardless of whether it's a cache hit or not.
2741 : : */
2742 : 18403 : total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2743 : :
2744 : : /* Now adjust the total cost to account for cache evictions */
2745 : :
2746 : : /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2747 : 18403 : total_cost += cpu_tuple_cost * evict_ratio;
2748 : :
2749 : : /*
2750 : : * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2751 : : * The per-tuple eviction is really just a pfree, so charging a whole
2752 : : * cpu_operator_cost seems a little excessive.
2753 : : */
2754 : 18403 : total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2755 : :
2756 : : /*
2757 : : * Now adjust for storing things in the cache, since that's not free
2758 : : * either. Everything must go in the cache. We don't proportion this
2759 : : * over any ratio, just apply it once for the scan. We charge a
2760 : : * cpu_tuple_cost for the creation of the cache entry and also a
2761 : : * cpu_operator_cost for each tuple we expect to cache.
2762 : : */
2763 : 18403 : total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2764 : :
2765 : : /*
2766 : : * Getting the first row must be also be proportioned according to the
2767 : : * expected cache hit ratio.
2768 : : */
2769 : 18403 : startup_cost = input_startup_cost * (1.0 - hit_ratio);
2770 : :
2771 : : /*
2772 : : * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2773 : : * which we'll do regardless of whether it was a cache hit or not.
2774 : : */
2775 : 18403 : startup_cost += cpu_tuple_cost;
2776 : :
2777 : 18403 : *rescan_startup_cost = startup_cost;
2778 : 18403 : *rescan_total_cost = total_cost;
2779 : 18403 : }
2780 : :
2781 : : /*
2782 : : * cost_agg
2783 : : * Determines and returns the cost of performing an Agg plan node,
2784 : : * including the cost of its input.
2785 : : *
2786 : : * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
2787 : : * we are using a hashed Agg node just to do grouping).
2788 : : *
2789 : : * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
2790 : : * are for appropriately-sorted input.
2791 : : */
2792 : : void
2793 : 12265 : cost_agg(Path *path, PlannerInfo *root,
2794 : : AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
2795 : : int numGroupCols, double numGroups,
2796 : : List *quals,
2797 : : int disabled_nodes,
2798 : : Cost input_startup_cost, Cost input_total_cost,
2799 : : double input_tuples, double input_width)
2800 : : {
2801 : 12265 : double output_tuples;
2802 : 12265 : Cost startup_cost;
2803 : 12265 : Cost total_cost;
2804 : 12265 : const AggClauseCosts dummy_aggcosts = {0};
2805 : :
2806 : : /* Use all-zero per-aggregate costs if NULL is passed */
2807 [ + + ]: 12265 : if (aggcosts == NULL)
2808 : : {
2809 [ + - ]: 2670 : Assert(aggstrategy == AGG_HASHED);
2810 : 2670 : aggcosts = &dummy_aggcosts;
2811 : 2670 : }
2812 : :
2813 : : /*
2814 : : * The transCost.per_tuple component of aggcosts should be charged once
2815 : : * per input tuple, corresponding to the costs of evaluating the aggregate
2816 : : * transfns and their input expressions. The finalCost.per_tuple component
2817 : : * is charged once per output tuple, corresponding to the costs of
2818 : : * evaluating the finalfns. Startup costs are of course charged but once.
2819 : : *
2820 : : * If we are grouping, we charge an additional cpu_operator_cost per
2821 : : * grouping column per input tuple for grouping comparisons.
2822 : : *
2823 : : * We will produce a single output tuple if not grouping, and a tuple per
2824 : : * group otherwise. We charge cpu_tuple_cost for each output tuple.
2825 : : *
2826 : : * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2827 : : * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2828 : : * input path is already sorted appropriately, AGG_SORTED should be
2829 : : * preferred (since it has no risk of memory overflow). This will happen
2830 : : * as long as the computed total costs are indeed exactly equal --- but if
2831 : : * there's roundoff error we might do the wrong thing. So be sure that
2832 : : * the computations below form the same intermediate values in the same
2833 : : * order.
2834 : : */
2835 [ + + ]: 12265 : if (aggstrategy == AGG_PLAIN)
2836 : : {
2837 : 4679 : startup_cost = input_total_cost;
2838 : 4679 : startup_cost += aggcosts->transCost.startup;
2839 : 4679 : startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2840 : 4679 : startup_cost += aggcosts->finalCost.startup;
2841 : 4679 : startup_cost += aggcosts->finalCost.per_tuple;
2842 : : /* we aren't grouping */
2843 : 4679 : total_cost = startup_cost + cpu_tuple_cost;
2844 : 4679 : output_tuples = 1;
2845 : 4679 : }
2846 [ + + + + ]: 7586 : else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2847 : : {
2848 : : /* Here we are able to deliver output on-the-fly */
2849 : 2904 : startup_cost = input_startup_cost;
2850 : 2904 : total_cost = input_total_cost;
2851 [ + + + + ]: 2904 : if (aggstrategy == AGG_MIXED && !enable_hashagg)
2852 : 90 : ++disabled_nodes;
2853 : : /* calcs phrased this way to match HASHED case, see note above */
2854 : 2904 : total_cost += aggcosts->transCost.startup;
2855 : 2904 : total_cost += aggcosts->transCost.per_tuple * input_tuples;
2856 : 2904 : total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2857 : 2904 : total_cost += aggcosts->finalCost.startup;
2858 : 2904 : total_cost += aggcosts->finalCost.per_tuple * numGroups;
2859 : 2904 : total_cost += cpu_tuple_cost * numGroups;
2860 : 2904 : output_tuples = numGroups;
2861 : 2904 : }
2862 : : else
2863 : : {
2864 : : /* must be AGG_HASHED */
2865 : 4682 : startup_cost = input_total_cost;
2866 [ + + ]: 4682 : if (!enable_hashagg)
2867 : 312 : ++disabled_nodes;
2868 : 4682 : startup_cost += aggcosts->transCost.startup;
2869 : 4682 : startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2870 : : /* cost of computing hash value */
2871 : 4682 : startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2872 : 4682 : startup_cost += aggcosts->finalCost.startup;
2873 : :
2874 : 4682 : total_cost = startup_cost;
2875 : 4682 : total_cost += aggcosts->finalCost.per_tuple * numGroups;
2876 : : /* cost of retrieving from hash table */
2877 : 4682 : total_cost += cpu_tuple_cost * numGroups;
2878 : 4682 : output_tuples = numGroups;
2879 : : }
2880 : :
2881 : : /*
2882 : : * Add the disk costs of hash aggregation that spills to disk.
2883 : : *
2884 : : * Groups that go into the hash table stay in memory until finalized, so
2885 : : * spilling and reprocessing tuples doesn't incur additional invocations
2886 : : * of transCost or finalCost. Furthermore, the computed hash value is
2887 : : * stored with the spilled tuples, so we don't incur extra invocations of
2888 : : * the hash function.
2889 : : *
2890 : : * Hash Agg begins returning tuples after the first batch is complete.
2891 : : * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2892 : : * accrue reads only to total_cost.
2893 : : */
2894 [ + + + + ]: 12265 : if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2895 : : {
2896 : 4849 : double pages;
2897 : 4849 : double pages_written = 0.0;
2898 : 4849 : double pages_read = 0.0;
2899 : 4849 : double spill_cost;
2900 : 4849 : double hashentrysize;
2901 : 4849 : double nbatches;
2902 : 4849 : Size mem_limit;
2903 : 4849 : uint64 ngroups_limit;
2904 : 4849 : int num_partitions;
2905 : 4849 : int depth;
2906 : :
2907 : : /*
2908 : : * Estimate number of batches based on the computed limits. If less
2909 : : * than or equal to one, all groups are expected to fit in memory;
2910 : : * otherwise we expect to spill.
2911 : : */
2912 : 9698 : hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2913 : 4849 : input_width,
2914 : 4849 : aggcosts->transitionSpace);
2915 : 4849 : hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2916 : : &ngroups_limit, &num_partitions);
2917 : :
2918 [ - + ]: 4849 : nbatches = Max((numGroups * hashentrysize) / mem_limit,
2919 : : numGroups / ngroups_limit);
2920 : :
2921 [ + + ]: 4849 : nbatches = Max(ceil(nbatches), 1.0);
2922 [ + + ]: 4849 : num_partitions = Max(num_partitions, 2);
2923 : :
2924 : : /*
2925 : : * The number of partitions can change at different levels of
2926 : : * recursion; but for the purposes of this calculation assume it stays
2927 : : * constant.
2928 : : */
2929 : 4849 : depth = ceil(log(nbatches) / log(num_partitions));
2930 : :
2931 : : /*
2932 : : * Estimate number of pages read and written. For each level of
2933 : : * recursion, a tuple must be written and then later read.
2934 : : */
2935 : 4849 : pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2936 : 4849 : pages_written = pages_read = pages * depth;
2937 : :
2938 : : /*
2939 : : * HashAgg has somewhat worse IO behavior than Sort on typical
2940 : : * hardware/OS combinations. Account for this with a generic penalty.
2941 : : */
2942 : 4849 : pages_read *= 2.0;
2943 : 4849 : pages_written *= 2.0;
2944 : :
2945 : 4849 : startup_cost += pages_written * random_page_cost;
2946 : 4849 : total_cost += pages_written * random_page_cost;
2947 : 4849 : total_cost += pages_read * seq_page_cost;
2948 : :
2949 : : /* account for CPU cost of spilling a tuple and reading it back */
2950 : 4849 : spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2951 : 4849 : startup_cost += spill_cost;
2952 : 4849 : total_cost += spill_cost;
2953 : 4849 : }
2954 : :
2955 : : /*
2956 : : * If there are quals (HAVING quals), account for their cost and
2957 : : * selectivity.
2958 : : */
2959 [ + + ]: 12265 : if (quals)
2960 : : {
2961 : 724 : QualCost qual_cost;
2962 : :
2963 : 724 : cost_qual_eval(&qual_cost, quals, root);
2964 : 724 : startup_cost += qual_cost.startup;
2965 : 724 : total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2966 : :
2967 : 1448 : output_tuples = clamp_row_est(output_tuples *
2968 : 1448 : clauselist_selectivity(root,
2969 : 724 : quals,
2970 : : 0,
2971 : : JOIN_INNER,
2972 : : NULL));
2973 : 724 : }
2974 : :
2975 : 12265 : path->rows = output_tuples;
2976 : 12265 : path->disabled_nodes = disabled_nodes;
2977 : 12265 : path->startup_cost = startup_cost;
2978 : 12265 : path->total_cost = total_cost;
2979 : 12265 : }
2980 : :
2981 : : /*
2982 : : * get_windowclause_startup_tuples
2983 : : * Estimate how many tuples we'll need to fetch from a WindowAgg's
2984 : : * subnode before we can output the first WindowAgg tuple.
2985 : : *
2986 : : * How many tuples need to be read depends on the WindowClause. For example,
2987 : : * a WindowClause with no PARTITION BY and no ORDER BY requires that all
2988 : : * subnode tuples are read and aggregated before the WindowAgg can output
2989 : : * anything. If there's a PARTITION BY, then we only need to look at tuples
2990 : : * in the first partition. Here we attempt to estimate just how many
2991 : : * 'input_tuples' the WindowAgg will need to read for the given WindowClause
2992 : : * before the first tuple can be output.
2993 : : */
2994 : : static double
2995 : 492 : get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc,
2996 : : double input_tuples)
2997 : : {
2998 : 492 : int frameOptions = wc->frameOptions;
2999 : 492 : double partition_tuples;
3000 : 492 : double return_tuples;
3001 : 492 : double peer_tuples;
3002 : :
3003 : : /*
3004 : : * First, figure out how many partitions there are likely to be and set
3005 : : * partition_tuples according to that estimate.
3006 : : */
3007 [ + + ]: 492 : if (wc->partitionClause != NIL)
3008 : : {
3009 : 119 : double num_partitions;
3010 : 238 : List *partexprs = get_sortgrouplist_exprs(wc->partitionClause,
3011 : 119 : root->parse->targetList);
3012 : :
3013 : 119 : num_partitions = estimate_num_groups(root, partexprs, input_tuples,
3014 : : NULL, NULL);
3015 : 119 : list_free(partexprs);
3016 : :
3017 : 119 : partition_tuples = input_tuples / num_partitions;
3018 : 119 : }
3019 : : else
3020 : : {
3021 : : /* all tuples belong to the same partition */
3022 : 373 : partition_tuples = input_tuples;
3023 : : }
3024 : :
3025 : : /* estimate the number of tuples in each peer group */
3026 [ + + ]: 492 : if (wc->orderClause != NIL)
3027 : : {
3028 : 393 : double num_groups;
3029 : 393 : List *orderexprs;
3030 : :
3031 : 786 : orderexprs = get_sortgrouplist_exprs(wc->orderClause,
3032 : 393 : root->parse->targetList);
3033 : :
3034 : : /* estimate out how many peer groups there are in the partition */
3035 : 786 : num_groups = estimate_num_groups(root, orderexprs,
3036 : 393 : partition_tuples, NULL,
3037 : : NULL);
3038 : 393 : list_free(orderexprs);
3039 : 393 : peer_tuples = partition_tuples / num_groups;
3040 : 393 : }
3041 : : else
3042 : : {
3043 : : /* no ORDER BY so only 1 tuple belongs in each peer group */
3044 : 99 : peer_tuples = 1.0;
3045 : : }
3046 : :
3047 [ + + ]: 492 : if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
3048 : : {
3049 : : /* include all partition rows */
3050 : 60 : return_tuples = partition_tuples;
3051 : 60 : }
3052 [ + + ]: 432 : else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
3053 : : {
3054 [ + + ]: 259 : if (frameOptions & FRAMEOPTION_ROWS)
3055 : : {
3056 : : /* just count the current row */
3057 : 119 : return_tuples = 1.0;
3058 : 119 : }
3059 [ + - ]: 140 : else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
3060 : : {
3061 : : /*
3062 : : * When in RANGE/GROUPS mode, it's more complex. If there's no
3063 : : * ORDER BY, then all rows in the partition are peers, otherwise
3064 : : * we'll need to read the first group of peers.
3065 : : */
3066 [ + + ]: 140 : if (wc->orderClause == NIL)
3067 : 53 : return_tuples = partition_tuples;
3068 : : else
3069 : 87 : return_tuples = peer_tuples;
3070 : 140 : }
3071 : : else
3072 : : {
3073 : : /*
3074 : : * Something new we don't support yet? This needs attention.
3075 : : * We'll just return 1.0 in the meantime.
3076 : : */
3077 : 0 : Assert(false);
3078 : 0 : return_tuples = 1.0;
3079 : : }
3080 : 259 : }
3081 [ + + ]: 173 : else if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
3082 : : {
3083 : : /*
3084 : : * BETWEEN ... AND N PRECEDING will only need to read the WindowAgg's
3085 : : * subnode after N ROWS/RANGES/GROUPS. N can be 0, but not negative,
3086 : : * so we'll just assume only the current row needs to be read to fetch
3087 : : * the first WindowAgg row.
3088 : : */
3089 : 18 : return_tuples = 1.0;
3090 : 18 : }
3091 [ + - ]: 155 : else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
3092 : : {
3093 : 155 : Const *endOffset = (Const *) wc->endOffset;
3094 : 155 : double end_offset_value;
3095 : :
3096 : : /* try and figure out the value specified in the endOffset. */
3097 [ + - ]: 155 : if (IsA(endOffset, Const))
3098 : : {
3099 [ - + ]: 155 : if (endOffset->constisnull)
3100 : : {
3101 : : /*
3102 : : * NULLs are not allowed, but currently, there's no code to
3103 : : * error out if there's a NULL Const. We'll only discover
3104 : : * this during execution. For now, just pretend everything is
3105 : : * fine and assume that just the first row/range/group will be
3106 : : * needed.
3107 : : */
3108 : 0 : end_offset_value = 1.0;
3109 : 0 : }
3110 : : else
3111 : : {
3112 [ + + + + ]: 155 : switch (endOffset->consttype)
3113 : : {
3114 : : case INT2OID:
3115 : 4 : end_offset_value =
3116 : 4 : (double) DatumGetInt16(endOffset->constvalue);
3117 : 4 : break;
3118 : : case INT4OID:
3119 : 22 : end_offset_value =
3120 : 22 : (double) DatumGetInt32(endOffset->constvalue);
3121 : 22 : break;
3122 : : case INT8OID:
3123 : 72 : end_offset_value =
3124 : 72 : (double) DatumGetInt64(endOffset->constvalue);
3125 : 72 : break;
3126 : : default:
3127 : 57 : end_offset_value =
3128 : 57 : partition_tuples / peer_tuples *
3129 : : DEFAULT_INEQ_SEL;
3130 : 57 : break;
3131 : : }
3132 : : }
3133 : 155 : }
3134 : : else
3135 : : {
3136 : : /*
3137 : : * When the end bound is not a Const, we'll just need to guess. We
3138 : : * just make use of DEFAULT_INEQ_SEL.
3139 : : */
3140 : 0 : end_offset_value =
3141 : 0 : partition_tuples / peer_tuples * DEFAULT_INEQ_SEL;
3142 : : }
3143 : :
3144 [ + + ]: 155 : if (frameOptions & FRAMEOPTION_ROWS)
3145 : : {
3146 : : /* include the N FOLLOWING and the current row */
3147 : 45 : return_tuples = end_offset_value + 1.0;
3148 : 45 : }
3149 [ + - ]: 110 : else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
3150 : : {
3151 : : /* include N FOLLOWING ranges/group and the initial range/group */
3152 : 110 : return_tuples = peer_tuples * (end_offset_value + 1.0);
3153 : 110 : }
3154 : : else
3155 : : {
3156 : : /*
3157 : : * Something new we don't support yet? This needs attention.
3158 : : * We'll just return 1.0 in the meantime.
3159 : : */
3160 : 0 : Assert(false);
3161 : 0 : return_tuples = 1.0;
3162 : : }
3163 : 155 : }
3164 : : else
3165 : : {
3166 : : /*
3167 : : * Something new we don't support yet? This needs attention. We'll
3168 : : * just return 1.0 in the meantime.
3169 : : */
3170 : 0 : Assert(false);
3171 : 0 : return_tuples = 1.0;
3172 : : }
3173 : :
3174 [ + + + + ]: 492 : if (wc->partitionClause != NIL || wc->orderClause != NIL)
3175 : : {
3176 : : /*
3177 : : * Cap the return value to the estimated partition tuples and account
3178 : : * for the extra tuple WindowAgg will need to read to confirm the next
3179 : : * tuple does not belong to the same partition or peer group.
3180 : : */
3181 [ + + ]: 427 : return_tuples = Min(return_tuples + 1.0, partition_tuples);
3182 : 427 : }
3183 : : else
3184 : : {
3185 : : /*
3186 : : * Cap the return value so it's never higher than the expected tuples
3187 : : * in the partition.
3188 : : */
3189 [ + + ]: 65 : return_tuples = Min(return_tuples, partition_tuples);
3190 : : }
3191 : :
3192 : : /*
3193 : : * We needn't worry about any EXCLUDE options as those only exclude rows
3194 : : * from being aggregated, not from being read from the WindowAgg's
3195 : : * subnode.
3196 : : */
3197 : :
3198 : 984 : return clamp_row_est(return_tuples);
3199 : 492 : }
3200 : :
3201 : : /*
3202 : : * cost_windowagg
3203 : : * Determines and returns the cost of performing a WindowAgg plan node,
3204 : : * including the cost of its input.
3205 : : *
3206 : : * Input is assumed already properly sorted.
3207 : : */
3208 : : void
3209 : 492 : cost_windowagg(Path *path, PlannerInfo *root,
3210 : : List *windowFuncs, WindowClause *winclause,
3211 : : int input_disabled_nodes,
3212 : : Cost input_startup_cost, Cost input_total_cost,
3213 : : double input_tuples)
3214 : : {
3215 : 492 : Cost startup_cost;
3216 : 492 : Cost total_cost;
3217 : 492 : double startup_tuples;
3218 : 492 : int numPartCols;
3219 : 492 : int numOrderCols;
3220 : 492 : ListCell *lc;
3221 : :
3222 : 492 : numPartCols = list_length(winclause->partitionClause);
3223 : 492 : numOrderCols = list_length(winclause->orderClause);
3224 : :
3225 : 492 : startup_cost = input_startup_cost;
3226 : 492 : total_cost = input_total_cost;
3227 : :
3228 : : /*
3229 : : * Window functions are assumed to cost their stated execution cost, plus
3230 : : * the cost of evaluating their input expressions, per tuple. Since they
3231 : : * may in fact evaluate their inputs at multiple rows during each cycle,
3232 : : * this could be a drastic underestimate; but without a way to know how
3233 : : * many rows the window function will fetch, it's hard to do better. In
3234 : : * any case, it's a good estimate for all the built-in window functions,
3235 : : * so we'll just do this for now.
3236 : : */
3237 [ + - + + : 1131 : foreach(lc, windowFuncs)
+ + ]
3238 : : {
3239 : 639 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3240 : 639 : Cost wfunccost;
3241 : 639 : QualCost argcosts;
3242 : :
3243 : 639 : argcosts.startup = argcosts.per_tuple = 0;
3244 : 639 : add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3245 : : &argcosts);
3246 : 639 : startup_cost += argcosts.startup;
3247 : 639 : wfunccost = argcosts.per_tuple;
3248 : :
3249 : : /* also add the input expressions' cost to per-input-row costs */
3250 : 639 : cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3251 : 639 : startup_cost += argcosts.startup;
3252 : 639 : wfunccost += argcosts.per_tuple;
3253 : :
3254 : : /*
3255 : : * Add the filter's cost to per-input-row costs. XXX We should reduce
3256 : : * input expression costs according to filter selectivity.
3257 : : */
3258 : 639 : cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3259 : 639 : startup_cost += argcosts.startup;
3260 : 639 : wfunccost += argcosts.per_tuple;
3261 : :
3262 : 639 : total_cost += wfunccost * input_tuples;
3263 : 639 : }
3264 : :
3265 : : /*
3266 : : * We also charge cpu_operator_cost per grouping column per tuple for
3267 : : * grouping comparisons, plus cpu_tuple_cost per tuple for general
3268 : : * overhead.
3269 : : *
3270 : : * XXX this neglects costs of spooling the data to disk when it overflows
3271 : : * work_mem. Sooner or later that should get accounted for.
3272 : : */
3273 : 492 : total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3274 : 492 : total_cost += cpu_tuple_cost * input_tuples;
3275 : :
3276 : 492 : path->rows = input_tuples;
3277 : 492 : path->disabled_nodes = input_disabled_nodes;
3278 : 492 : path->startup_cost = startup_cost;
3279 : 492 : path->total_cost = total_cost;
3280 : :
3281 : : /*
3282 : : * Also, take into account how many tuples we need to read from the
3283 : : * subnode in order to produce the first tuple from the WindowAgg. To do
3284 : : * this we proportion the run cost (total cost not including startup cost)
3285 : : * over the estimated startup tuples. We already included the startup
3286 : : * cost of the subnode, so we only need to do this when the estimated
3287 : : * startup tuples is above 1.0.
3288 : : */
3289 : 984 : startup_tuples = get_windowclause_startup_tuples(root, winclause,
3290 : 492 : input_tuples);
3291 : :
3292 [ + + ]: 492 : if (startup_tuples > 1.0)
3293 : 856 : path->startup_cost += (total_cost - startup_cost) / input_tuples *
3294 : 428 : (startup_tuples - 1.0);
3295 : 492 : }
3296 : :
3297 : : /*
3298 : : * cost_group
3299 : : * Determines and returns the cost of performing a Group plan node,
3300 : : * including the cost of its input.
3301 : : *
3302 : : * Note: caller must ensure that input costs are for appropriately-sorted
3303 : : * input.
3304 : : */
3305 : : void
3306 : 192 : cost_group(Path *path, PlannerInfo *root,
3307 : : int numGroupCols, double numGroups,
3308 : : List *quals,
3309 : : int input_disabled_nodes,
3310 : : Cost input_startup_cost, Cost input_total_cost,
3311 : : double input_tuples)
3312 : : {
3313 : 192 : double output_tuples;
3314 : 192 : Cost startup_cost;
3315 : 192 : Cost total_cost;
3316 : :
3317 : 192 : output_tuples = numGroups;
3318 : 192 : startup_cost = input_startup_cost;
3319 : 192 : total_cost = input_total_cost;
3320 : :
3321 : : /*
3322 : : * Charge one cpu_operator_cost per comparison per input tuple. We assume
3323 : : * all columns get compared at most of the tuples.
3324 : : */
3325 : 192 : total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3326 : :
3327 : : /*
3328 : : * If there are quals (HAVING quals), account for their cost and
3329 : : * selectivity.
3330 : : */
3331 [ + - ]: 192 : if (quals)
3332 : : {
3333 : 0 : QualCost qual_cost;
3334 : :
3335 : 0 : cost_qual_eval(&qual_cost, quals, root);
3336 : 0 : startup_cost += qual_cost.startup;
3337 : 0 : total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3338 : :
3339 : 0 : output_tuples = clamp_row_est(output_tuples *
3340 : 0 : clauselist_selectivity(root,
3341 : 0 : quals,
3342 : : 0,
3343 : : JOIN_INNER,
3344 : : NULL));
3345 : 0 : }
3346 : :
3347 : 192 : path->rows = output_tuples;
3348 : 192 : path->disabled_nodes = input_disabled_nodes;
3349 : 192 : path->startup_cost = startup_cost;
3350 : 192 : path->total_cost = total_cost;
3351 : 192 : }
3352 : :
3353 : : /*
3354 : : * initial_cost_nestloop
3355 : : * Preliminary estimate of the cost of a nestloop join path.
3356 : : *
3357 : : * This must quickly produce lower-bound estimates of the path's startup and
3358 : : * total costs. If we are unable to eliminate the proposed path from
3359 : : * consideration using the lower bounds, final_cost_nestloop will be called
3360 : : * to obtain the final estimates.
3361 : : *
3362 : : * The exact division of labor between this function and final_cost_nestloop
3363 : : * is private to them, and represents a tradeoff between speed of the initial
3364 : : * estimate and getting a tight lower bound. We choose to not examine the
3365 : : * join quals here, since that's by far the most expensive part of the
3366 : : * calculations. The end result is that CPU-cost considerations must be
3367 : : * left for the second phase; and for SEMI/ANTI joins, we must also postpone
3368 : : * incorporation of the inner path's run cost.
3369 : : *
3370 : : * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
3371 : : * other data to be used by final_cost_nestloop
3372 : : * 'jointype' is the type of join to be performed
3373 : : * 'outer_path' is the outer input to the join
3374 : : * 'inner_path' is the inner input to the join
3375 : : * 'extra' contains miscellaneous information about the join
3376 : : */
3377 : : void
3378 : 284672 : initial_cost_nestloop(PlannerInfo *root, JoinCostWorkspace *workspace,
3379 : : JoinType jointype, uint64 enable_mask,
3380 : : Path *outer_path, Path *inner_path,
3381 : : JoinPathExtraData *extra)
3382 : : {
3383 : 284672 : int disabled_nodes;
3384 : 284672 : Cost startup_cost = 0;
3385 : 284672 : Cost run_cost = 0;
3386 : 284672 : double outer_path_rows = outer_path->rows;
3387 : 284672 : Cost inner_rescan_start_cost;
3388 : 284672 : Cost inner_rescan_total_cost;
3389 : 284672 : Cost inner_run_cost;
3390 : 284672 : Cost inner_rescan_run_cost;
3391 : :
3392 : : /* Count up disabled nodes. */
3393 : 284672 : disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
3394 : 284672 : disabled_nodes += inner_path->disabled_nodes;
3395 : 284672 : disabled_nodes += outer_path->disabled_nodes;
3396 : :
3397 : : /* estimate costs to rescan the inner relation */
3398 : 284672 : cost_rescan(root, inner_path,
3399 : : &inner_rescan_start_cost,
3400 : : &inner_rescan_total_cost);
3401 : :
3402 : : /* cost of source data */
3403 : :
3404 : : /*
3405 : : * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3406 : : * before we can start returning tuples, so the join's startup cost is
3407 : : * their sum. We'll also pay the inner path's rescan startup cost
3408 : : * multiple times.
3409 : : */
3410 : 284672 : startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3411 : 284672 : run_cost += outer_path->total_cost - outer_path->startup_cost;
3412 [ + + ]: 284672 : if (outer_path_rows > 1)
3413 : 190906 : run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3414 : :
3415 : 284672 : inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3416 : 284672 : inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3417 : :
3418 [ + + + + : 284672 : if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
+ + ]
3419 : 277858 : extra->inner_unique)
3420 : : {
3421 : : /*
3422 : : * With a SEMI or ANTI join, or if the innerrel is known unique, the
3423 : : * executor will stop after the first match.
3424 : : *
3425 : : * Getting decent estimates requires inspection of the join quals,
3426 : : * which we choose to postpone to final_cost_nestloop.
3427 : : */
3428 : :
3429 : : /* Save private data for final_cost_nestloop */
3430 : 101090 : workspace->inner_run_cost = inner_run_cost;
3431 : 101090 : workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3432 : 101090 : }
3433 : : else
3434 : : {
3435 : : /* Normal case; we'll scan whole input rel for each outer row */
3436 : 183582 : run_cost += inner_run_cost;
3437 [ + + ]: 183582 : if (outer_path_rows > 1)
3438 : 139928 : run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3439 : : }
3440 : :
3441 : : /* CPU costs left for later */
3442 : :
3443 : : /* Public result fields */
3444 : 284672 : workspace->disabled_nodes = disabled_nodes;
3445 : 284672 : workspace->startup_cost = startup_cost;
3446 : 284672 : workspace->total_cost = startup_cost + run_cost;
3447 : : /* Save private data for final_cost_nestloop */
3448 : 284672 : workspace->run_cost = run_cost;
3449 : 284672 : }
3450 : :
3451 : : /*
3452 : : * final_cost_nestloop
3453 : : * Final estimate of the cost and result size of a nestloop join path.
3454 : : *
3455 : : * 'path' is already filled in except for the rows and cost fields
3456 : : * 'workspace' is the result from initial_cost_nestloop
3457 : : * 'extra' contains miscellaneous information about the join
3458 : : */
3459 : : void
3460 : 127517 : final_cost_nestloop(PlannerInfo *root, NestPath *path,
3461 : : JoinCostWorkspace *workspace,
3462 : : JoinPathExtraData *extra)
3463 : : {
3464 : 127517 : Path *outer_path = path->jpath.outerjoinpath;
3465 : 127517 : Path *inner_path = path->jpath.innerjoinpath;
3466 : 127517 : double outer_path_rows = outer_path->rows;
3467 : 127517 : double inner_path_rows = inner_path->rows;
3468 : 127517 : Cost startup_cost = workspace->startup_cost;
3469 : 127517 : Cost run_cost = workspace->run_cost;
3470 : 127517 : Cost cpu_per_tuple;
3471 : 127517 : QualCost restrict_qual_cost;
3472 : 127517 : double ntuples;
3473 : :
3474 : : /* Set the number of disabled nodes. */
3475 : 127517 : path->jpath.path.disabled_nodes = workspace->disabled_nodes;
3476 : :
3477 : : /* Protect some assumptions below that rowcounts aren't zero */
3478 [ + - ]: 127517 : if (outer_path_rows <= 0)
3479 : 0 : outer_path_rows = 1;
3480 [ + + ]: 127517 : if (inner_path_rows <= 0)
3481 : 107 : inner_path_rows = 1;
3482 : : /* Mark the path with the correct row estimate */
3483 [ + + ]: 127517 : if (path->jpath.path.param_info)
3484 : 1602 : path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3485 : : else
3486 : 125915 : path->jpath.path.rows = path->jpath.path.parent->rows;
3487 : :
3488 : : /* For partial paths, scale row estimate. */
3489 [ + + ]: 127517 : if (path->jpath.path.parallel_workers > 0)
3490 : : {
3491 : 7335 : double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3492 : :
3493 : 7335 : path->jpath.path.rows =
3494 : 7335 : clamp_row_est(path->jpath.path.rows / parallel_divisor);
3495 : 7335 : }
3496 : :
3497 : : /* cost of inner-relation source data (we already dealt with outer rel) */
3498 : :
3499 [ + + + + : 127517 : if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
+ + ]
3500 : 122125 : extra->inner_unique)
3501 : : {
3502 : : /*
3503 : : * With a SEMI or ANTI join, or if the innerrel is known unique, the
3504 : : * executor will stop after the first match.
3505 : : */
3506 : 69247 : Cost inner_run_cost = workspace->inner_run_cost;
3507 : 69247 : Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3508 : 69247 : double outer_matched_rows;
3509 : 69247 : double outer_unmatched_rows;
3510 : 69247 : Selectivity inner_scan_frac;
3511 : :
3512 : : /*
3513 : : * For an outer-rel row that has at least one match, we can expect the
3514 : : * inner scan to stop after a fraction 1/(match_count+1) of the inner
3515 : : * rows, if the matches are evenly distributed. Since they probably
3516 : : * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3517 : : * that fraction. (If we used a larger fuzz factor, we'd have to
3518 : : * clamp inner_scan_frac to at most 1.0; but since match_count is at
3519 : : * least 1, no such clamp is needed now.)
3520 : : */
3521 : 69247 : outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3522 : 69247 : outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3523 : 69247 : inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3524 : :
3525 : : /*
3526 : : * Compute number of tuples processed (not number emitted!). First,
3527 : : * account for successfully-matched outer rows.
3528 : : */
3529 : 69247 : ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3530 : :
3531 : : /*
3532 : : * Now we need to estimate the actual costs of scanning the inner
3533 : : * relation, which may be quite a bit less than N times inner_run_cost
3534 : : * due to early scan stops. We consider two cases. If the inner path
3535 : : * is an indexscan using all the joinquals as indexquals, then an
3536 : : * unmatched outer row results in an indexscan returning no rows,
3537 : : * which is probably quite cheap. Otherwise, the executor will have
3538 : : * to scan the whole inner rel for an unmatched row; not so cheap.
3539 : : */
3540 [ + + ]: 69247 : if (has_indexed_join_quals(path))
3541 : : {
3542 : : /*
3543 : : * Successfully-matched outer rows will only require scanning
3544 : : * inner_scan_frac of the inner relation. In this case, we don't
3545 : : * need to charge the full inner_run_cost even when that's more
3546 : : * than inner_rescan_run_cost, because we can assume that none of
3547 : : * the inner scans ever scan the whole inner relation. So it's
3548 : : * okay to assume that all the inner scan executions can be
3549 : : * fractions of the full cost, even if materialization is reducing
3550 : : * the rescan cost. At this writing, it's impossible to get here
3551 : : * for a materialized inner scan, so inner_run_cost and
3552 : : * inner_rescan_run_cost will be the same anyway; but just in
3553 : : * case, use inner_run_cost for the first matched tuple and
3554 : : * inner_rescan_run_cost for additional ones.
3555 : : */
3556 : 12891 : run_cost += inner_run_cost * inner_scan_frac;
3557 [ + + ]: 12891 : if (outer_matched_rows > 1)
3558 : 784 : run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3559 : :
3560 : : /*
3561 : : * Add the cost of inner-scan executions for unmatched outer rows.
3562 : : * We estimate this as the same cost as returning the first tuple
3563 : : * of a nonempty scan. We consider that these are all rescans,
3564 : : * since we used inner_run_cost once already.
3565 : : */
3566 : 38673 : run_cost += outer_unmatched_rows *
3567 : 25782 : inner_rescan_run_cost / inner_path_rows;
3568 : :
3569 : : /*
3570 : : * We won't be evaluating any quals at all for unmatched rows, so
3571 : : * don't add them to ntuples.
3572 : : */
3573 : 12891 : }
3574 : : else
3575 : : {
3576 : : /*
3577 : : * Here, a complicating factor is that rescans may be cheaper than
3578 : : * first scans. If we never scan all the way to the end of the
3579 : : * inner rel, it might be (depending on the plan type) that we'd
3580 : : * never pay the whole inner first-scan run cost. However it is
3581 : : * difficult to estimate whether that will happen (and it could
3582 : : * not happen if there are any unmatched outer rows!), so be
3583 : : * conservative and always charge the whole first-scan cost once.
3584 : : * We consider this charge to correspond to the first unmatched
3585 : : * outer row, unless there isn't one in our estimate, in which
3586 : : * case blame it on the first matched row.
3587 : : */
3588 : :
3589 : : /* First, count all unmatched join tuples as being processed */
3590 : 56356 : ntuples += outer_unmatched_rows * inner_path_rows;
3591 : :
3592 : : /* Now add the forced full scan, and decrement appropriate count */
3593 : 56356 : run_cost += inner_run_cost;
3594 [ + + ]: 56356 : if (outer_unmatched_rows >= 1)
3595 : 50414 : outer_unmatched_rows -= 1;
3596 : : else
3597 : 5942 : outer_matched_rows -= 1;
3598 : :
3599 : : /* Add inner run cost for additional outer tuples having matches */
3600 [ + + ]: 56356 : if (outer_matched_rows > 0)
3601 : 14150 : run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3602 : :
3603 : : /* Add inner run cost for additional unmatched outer tuples */
3604 [ + + ]: 56356 : if (outer_unmatched_rows > 0)
3605 : 24804 : run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3606 : : }
3607 : 69247 : }
3608 : : else
3609 : : {
3610 : : /* Normal-case source costs were included in preliminary estimate */
3611 : :
3612 : : /* Compute number of tuples processed (not number emitted!) */
3613 : 58270 : ntuples = outer_path_rows * inner_path_rows;
3614 : : }
3615 : :
3616 : : /* CPU costs */
3617 : 127517 : cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3618 : 127517 : startup_cost += restrict_qual_cost.startup;
3619 : 127517 : cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3620 : 127517 : run_cost += cpu_per_tuple * ntuples;
3621 : :
3622 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3623 : 127517 : startup_cost += path->jpath.path.pathtarget->cost.startup;
3624 : 127517 : run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3625 : :
3626 : 127517 : path->jpath.path.startup_cost = startup_cost;
3627 : 127517 : path->jpath.path.total_cost = startup_cost + run_cost;
3628 : 127517 : }
3629 : :
3630 : : /*
3631 : : * initial_cost_mergejoin
3632 : : * Preliminary estimate of the cost of a mergejoin path.
3633 : : *
3634 : : * This must quickly produce lower-bound estimates of the path's startup and
3635 : : * total costs. If we are unable to eliminate the proposed path from
3636 : : * consideration using the lower bounds, final_cost_mergejoin will be called
3637 : : * to obtain the final estimates.
3638 : : *
3639 : : * The exact division of labor between this function and final_cost_mergejoin
3640 : : * is private to them, and represents a tradeoff between speed of the initial
3641 : : * estimate and getting a tight lower bound. We choose to not examine the
3642 : : * join quals here, except for obtaining the scan selectivity estimate which
3643 : : * is really essential (but fortunately, use of caching keeps the cost of
3644 : : * getting that down to something reasonable).
3645 : : * We also assume that cost_sort/cost_incremental_sort is cheap enough to use
3646 : : * here.
3647 : : *
3648 : : * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
3649 : : * other data to be used by final_cost_mergejoin
3650 : : * 'jointype' is the type of join to be performed
3651 : : * 'mergeclauses' is the list of joinclauses to be used as merge clauses
3652 : : * 'outer_path' is the outer input to the join
3653 : : * 'inner_path' is the inner input to the join
3654 : : * 'outersortkeys' is the list of sort keys for the outer path
3655 : : * 'innersortkeys' is the list of sort keys for the inner path
3656 : : * 'outer_presorted_keys' is the number of presorted keys of the outer path
3657 : : * 'extra' contains miscellaneous information about the join
3658 : : *
3659 : : * Note: outersortkeys and innersortkeys should be NIL if no explicit
3660 : : * sort is needed because the respective source path is already ordered.
3661 : : */
3662 : : void
3663 : 123669 : initial_cost_mergejoin(PlannerInfo *root, JoinCostWorkspace *workspace,
3664 : : JoinType jointype,
3665 : : List *mergeclauses,
3666 : : Path *outer_path, Path *inner_path,
3667 : : List *outersortkeys, List *innersortkeys,
3668 : : int outer_presorted_keys,
3669 : : JoinPathExtraData *extra)
3670 : : {
3671 : 123669 : int disabled_nodes;
3672 : 123669 : Cost startup_cost = 0;
3673 : 123669 : Cost run_cost = 0;
3674 : 123669 : double outer_path_rows = outer_path->rows;
3675 : 123669 : double inner_path_rows = inner_path->rows;
3676 : 123669 : Cost inner_run_cost;
3677 : 123669 : double outer_rows,
3678 : : inner_rows,
3679 : : outer_skip_rows,
3680 : : inner_skip_rows;
3681 : 123669 : Selectivity outerstartsel,
3682 : : outerendsel,
3683 : : innerstartsel,
3684 : : innerendsel;
3685 : 123669 : Path sort_path; /* dummy for result of
3686 : : * cost_sort/cost_incremental_sort */
3687 : :
3688 : : /* Protect some assumptions below that rowcounts aren't zero */
3689 [ + + ]: 123669 : if (outer_path_rows <= 0)
3690 : 16 : outer_path_rows = 1;
3691 [ + + ]: 123669 : if (inner_path_rows <= 0)
3692 : 21 : inner_path_rows = 1;
3693 : :
3694 : : /*
3695 : : * A merge join will stop as soon as it exhausts either input stream
3696 : : * (unless it's an outer join, in which case the outer side has to be
3697 : : * scanned all the way anyway). Estimate fraction of the left and right
3698 : : * inputs that will actually need to be scanned. Likewise, we can
3699 : : * estimate the number of rows that will be skipped before the first join
3700 : : * pair is found, which should be factored into startup cost. We use only
3701 : : * the first (most significant) merge clause for this purpose. Since
3702 : : * mergejoinscansel() is a fairly expensive computation, we cache the
3703 : : * results in the merge clause RestrictInfo.
3704 : : */
3705 [ + + + + ]: 123669 : if (mergeclauses && jointype != JOIN_FULL)
3706 : : {
3707 : 122781 : RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3708 : 122781 : List *opathkeys;
3709 : 122781 : List *ipathkeys;
3710 : 122781 : PathKey *opathkey;
3711 : 122781 : PathKey *ipathkey;
3712 : 122781 : MergeScanSelCache *cache;
3713 : :
3714 : : /* Get the input pathkeys to determine the sort-order details */
3715 [ + + ]: 122781 : opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3716 [ + + ]: 122781 : ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3717 [ + - ]: 122781 : Assert(opathkeys);
3718 [ + - ]: 122781 : Assert(ipathkeys);
3719 : 122781 : opathkey = (PathKey *) linitial(opathkeys);
3720 : 122781 : ipathkey = (PathKey *) linitial(ipathkeys);
3721 : : /* debugging check */
3722 [ + - ]: 122781 : if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3723 : 122781 : opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3724 : 122781 : opathkey->pk_cmptype != ipathkey->pk_cmptype ||
3725 : 122781 : opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3726 [ # # # # ]: 0 : elog(ERROR, "left and right pathkeys do not match in mergejoin");
3727 : :
3728 : : /* Get the selectivity with caching */
3729 : 122781 : cache = cached_scansel(root, firstclause, opathkey);
3730 : :
3731 [ + + + + ]: 245562 : if (bms_is_subset(firstclause->left_relids,
3732 : 122781 : outer_path->parent->relids))
3733 : : {
3734 : : /* left side of clause is outer */
3735 : 62798 : outerstartsel = cache->leftstartsel;
3736 : 62798 : outerendsel = cache->leftendsel;
3737 : 62798 : innerstartsel = cache->rightstartsel;
3738 : 62798 : innerendsel = cache->rightendsel;
3739 : 62798 : }
3740 : : else
3741 : : {
3742 : : /* left side of clause is inner */
3743 : 59983 : outerstartsel = cache->rightstartsel;
3744 : 59983 : outerendsel = cache->rightendsel;
3745 : 59983 : innerstartsel = cache->leftstartsel;
3746 : 59983 : innerendsel = cache->leftendsel;
3747 : : }
3748 [ + + + + ]: 122781 : if (jointype == JOIN_LEFT ||
3749 : 113505 : jointype == JOIN_ANTI)
3750 : : {
3751 : 10297 : outerstartsel = 0.0;
3752 : 10297 : outerendsel = 1.0;
3753 : 10297 : }
3754 [ + + + + ]: 112484 : else if (jointype == JOIN_RIGHT ||
3755 : 102532 : jointype == JOIN_RIGHT_ANTI)
3756 : : {
3757 : 11081 : innerstartsel = 0.0;
3758 : 11081 : innerendsel = 1.0;
3759 : 11081 : }
3760 : 122781 : }
3761 : : else
3762 : : {
3763 : : /* cope with clauseless or full mergejoin */
3764 : 888 : outerstartsel = innerstartsel = 0.0;
3765 : 888 : outerendsel = innerendsel = 1.0;
3766 : : }
3767 : :
3768 : : /*
3769 : : * Convert selectivities to row counts. We force outer_rows and
3770 : : * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3771 : : */
3772 : 123669 : outer_skip_rows = rint(outer_path_rows * outerstartsel);
3773 : 123669 : inner_skip_rows = rint(inner_path_rows * innerstartsel);
3774 : 123669 : outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3775 : 123669 : inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3776 : :
3777 [ + - ]: 123669 : Assert(outer_skip_rows <= outer_rows);
3778 [ + - ]: 123669 : Assert(inner_skip_rows <= inner_rows);
3779 : :
3780 : : /*
3781 : : * Readjust scan selectivities to account for above rounding. This is
3782 : : * normally an insignificant effect, but when there are only a few rows in
3783 : : * the inputs, failing to do this makes for a large percentage error.
3784 : : */
3785 : 123669 : outerstartsel = outer_skip_rows / outer_path_rows;
3786 : 123669 : innerstartsel = inner_skip_rows / inner_path_rows;
3787 : 123669 : outerendsel = outer_rows / outer_path_rows;
3788 : 123669 : innerendsel = inner_rows / inner_path_rows;
3789 : :
3790 [ + - ]: 123669 : Assert(outerstartsel <= outerendsel);
3791 [ + - ]: 123669 : Assert(innerstartsel <= innerendsel);
3792 : :
3793 : : /*
3794 : : * We don't decide whether to materialize the inner path until we get to
3795 : : * final_cost_mergejoin(), so we don't know whether to check the pgs_mask
3796 : : * again PGS_MERGEJOIN_PLAIN or PGS_MERGEJOIN_MATERIALIZE. Instead, we
3797 : : * just account for any child nodes here and assume that this node is not
3798 : : * itslef disabled; we can sort out the details in final_cost_mergejoin().
3799 : : *
3800 : : * (We could be more precise here by setting disabled_nodes to 1 at this
3801 : : * stage if both PGS_MERGEJOIN_PLAIN and PGS_MERGEJOIN_MATERIALIZE are
3802 : : * disabled, but that seems to against the idea of making this function
3803 : : * produce a quick, optimistic approximation of the final cost.)
3804 : : */
3805 : 123669 : disabled_nodes = 0;
3806 : :
3807 : : /* cost of source data */
3808 : :
3809 [ + + ]: 123669 : if (outersortkeys) /* do we need to sort outer? */
3810 : : {
3811 : : /*
3812 : : * We can assert that the outer path is not already ordered
3813 : : * appropriately for the mergejoin; otherwise, outersortkeys would
3814 : : * have been set to NIL.
3815 : : */
3816 [ + - ]: 67994 : Assert(!pathkeys_contained_in(outersortkeys, outer_path->pathkeys));
3817 : :
3818 : : /*
3819 : : * We choose to use incremental sort if it is enabled and there are
3820 : : * presorted keys; otherwise we use full sort.
3821 : : */
3822 [ + + + + ]: 67994 : if (enable_incremental_sort && outer_presorted_keys > 0)
3823 : : {
3824 : 203 : cost_incremental_sort(&sort_path,
3825 : 203 : root,
3826 : 203 : outersortkeys,
3827 : 203 : outer_presorted_keys,
3828 : 203 : outer_path->disabled_nodes,
3829 : 203 : outer_path->startup_cost,
3830 : 203 : outer_path->total_cost,
3831 : 203 : outer_path_rows,
3832 : 203 : outer_path->pathtarget->width,
3833 : : 0.0,
3834 : 203 : work_mem,
3835 : : -1.0);
3836 : 203 : }
3837 : : else
3838 : : {
3839 : 67791 : cost_sort(&sort_path,
3840 : 67791 : root,
3841 : 67791 : outersortkeys,
3842 : 67791 : outer_path->disabled_nodes,
3843 : 67791 : outer_path->total_cost,
3844 : 67791 : outer_path_rows,
3845 : 67791 : outer_path->pathtarget->width,
3846 : : 0.0,
3847 : 67791 : work_mem,
3848 : : -1.0);
3849 : : }
3850 : :
3851 : 67994 : disabled_nodes += sort_path.disabled_nodes;
3852 : 67994 : startup_cost += sort_path.startup_cost;
3853 : 135988 : startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3854 : 67994 : * outerstartsel;
3855 : 135988 : run_cost += (sort_path.total_cost - sort_path.startup_cost)
3856 : 67994 : * (outerendsel - outerstartsel);
3857 : 67994 : }
3858 : : else
3859 : : {
3860 : 55675 : disabled_nodes += outer_path->disabled_nodes;
3861 : 55675 : startup_cost += outer_path->startup_cost;
3862 : 111350 : startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3863 : 55675 : * outerstartsel;
3864 : 111350 : run_cost += (outer_path->total_cost - outer_path->startup_cost)
3865 : 55675 : * (outerendsel - outerstartsel);
3866 : : }
3867 : :
3868 [ + + ]: 123669 : if (innersortkeys) /* do we need to sort inner? */
3869 : : {
3870 : : /*
3871 : : * We can assert that the inner path is not already ordered
3872 : : * appropriately for the mergejoin; otherwise, innersortkeys would
3873 : : * have been set to NIL.
3874 : : */
3875 [ + - ]: 102979 : Assert(!pathkeys_contained_in(innersortkeys, inner_path->pathkeys));
3876 : :
3877 : : /*
3878 : : * We do not consider incremental sort for inner path, because
3879 : : * incremental sort does not support mark/restore.
3880 : : */
3881 : :
3882 : 102979 : cost_sort(&sort_path,
3883 : 102979 : root,
3884 : 102979 : innersortkeys,
3885 : 102979 : inner_path->disabled_nodes,
3886 : 102979 : inner_path->total_cost,
3887 : 102979 : inner_path_rows,
3888 : 102979 : inner_path->pathtarget->width,
3889 : : 0.0,
3890 : 102979 : work_mem,
3891 : : -1.0);
3892 : 102979 : disabled_nodes += sort_path.disabled_nodes;
3893 : 102979 : startup_cost += sort_path.startup_cost;
3894 : 205958 : startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3895 : 102979 : * innerstartsel;
3896 : 205958 : inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3897 : 102979 : * (innerendsel - innerstartsel);
3898 : 102979 : }
3899 : : else
3900 : : {
3901 : 20690 : disabled_nodes += inner_path->disabled_nodes;
3902 : 20690 : startup_cost += inner_path->startup_cost;
3903 : 41380 : startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3904 : 20690 : * innerstartsel;
3905 : 41380 : inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3906 : 20690 : * (innerendsel - innerstartsel);
3907 : : }
3908 : :
3909 : : /*
3910 : : * We can't yet determine whether rescanning occurs, or whether
3911 : : * materialization of the inner input should be done. The minimum
3912 : : * possible inner input cost, regardless of rescan and materialization
3913 : : * considerations, is inner_run_cost. We include that in
3914 : : * workspace->total_cost, but not yet in run_cost.
3915 : : */
3916 : :
3917 : : /* CPU costs left for later */
3918 : :
3919 : : /* Public result fields */
3920 : 123669 : workspace->disabled_nodes = disabled_nodes;
3921 : 123669 : workspace->startup_cost = startup_cost;
3922 : 123669 : workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3923 : : /* Save private data for final_cost_mergejoin */
3924 : 123669 : workspace->run_cost = run_cost;
3925 : 123669 : workspace->inner_run_cost = inner_run_cost;
3926 : 123669 : workspace->outer_rows = outer_rows;
3927 : 123669 : workspace->inner_rows = inner_rows;
3928 : 123669 : workspace->outer_skip_rows = outer_skip_rows;
3929 : 123669 : workspace->inner_skip_rows = inner_skip_rows;
3930 : 123669 : }
3931 : :
3932 : : /*
3933 : : * final_cost_mergejoin
3934 : : * Final estimate of the cost and result size of a mergejoin path.
3935 : : *
3936 : : * Unlike other costsize functions, this routine makes two actual decisions:
3937 : : * whether the executor will need to do mark/restore, and whether we should
3938 : : * materialize the inner path. It would be logically cleaner to build
3939 : : * separate paths testing these alternatives, but that would require repeating
3940 : : * most of the cost calculations, which are not all that cheap. Since the
3941 : : * choice will not affect output pathkeys or startup cost, only total cost,
3942 : : * there is no possibility of wanting to keep more than one path. So it seems
3943 : : * best to make the decisions here and record them in the path's
3944 : : * skip_mark_restore and materialize_inner fields.
3945 : : *
3946 : : * Mark/restore overhead is usually required, but can be skipped if we know
3947 : : * that the executor need find only one match per outer tuple, and that the
3948 : : * mergeclauses are sufficient to identify a match.
3949 : : *
3950 : : * We materialize the inner path if we need mark/restore and either the inner
3951 : : * path can't support mark/restore, or it's cheaper to use an interposed
3952 : : * Material node to handle mark/restore.
3953 : : *
3954 : : * 'path' is already filled in except for the rows and cost fields and
3955 : : * skip_mark_restore and materialize_inner
3956 : : * 'workspace' is the result from initial_cost_mergejoin
3957 : : * 'extra' contains miscellaneous information about the join
3958 : : */
3959 : : void
3960 : 48719 : final_cost_mergejoin(PlannerInfo *root, MergePath *path,
3961 : : JoinCostWorkspace *workspace,
3962 : : JoinPathExtraData *extra)
3963 : : {
3964 : 48719 : Path *outer_path = path->jpath.outerjoinpath;
3965 : 48719 : Path *inner_path = path->jpath.innerjoinpath;
3966 : 48719 : double inner_path_rows = inner_path->rows;
3967 : 48719 : List *mergeclauses = path->path_mergeclauses;
3968 : 48719 : List *innersortkeys = path->innersortkeys;
3969 : 48719 : Cost startup_cost = workspace->startup_cost;
3970 : 48719 : Cost run_cost = workspace->run_cost;
3971 : 48719 : Cost inner_run_cost = workspace->inner_run_cost;
3972 : 48719 : double outer_rows = workspace->outer_rows;
3973 : 48719 : double inner_rows = workspace->inner_rows;
3974 : 48719 : double outer_skip_rows = workspace->outer_skip_rows;
3975 : 48719 : double inner_skip_rows = workspace->inner_skip_rows;
3976 : 48719 : Cost cpu_per_tuple,
3977 : : bare_inner_cost,
3978 : : mat_inner_cost;
3979 : 48719 : QualCost merge_qual_cost;
3980 : 48719 : QualCost qp_qual_cost;
3981 : 48719 : double mergejointuples,
3982 : : rescannedtuples;
3983 : 48719 : double rescanratio;
3984 : 48719 : uint64 enable_mask = 0;
3985 : :
3986 : : /* Protect some assumptions below that rowcounts aren't zero */
3987 [ + + ]: 48719 : if (inner_path_rows <= 0)
3988 : 15 : inner_path_rows = 1;
3989 : :
3990 : : /* Mark the path with the correct row estimate */
3991 [ + + ]: 48719 : if (path->jpath.path.param_info)
3992 : 98 : path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3993 : : else
3994 : 48621 : path->jpath.path.rows = path->jpath.path.parent->rows;
3995 : :
3996 : : /* For partial paths, scale row estimate. */
3997 [ + + ]: 48719 : if (path->jpath.path.parallel_workers > 0)
3998 : : {
3999 : 10960 : double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4000 : :
4001 : 10960 : path->jpath.path.rows =
4002 : 10960 : clamp_row_est(path->jpath.path.rows / parallel_divisor);
4003 : 10960 : }
4004 : :
4005 : : /*
4006 : : * Compute cost of the mergequals and qpquals (other restriction clauses)
4007 : : * separately.
4008 : : */
4009 : 48719 : cost_qual_eval(&merge_qual_cost, mergeclauses, root);
4010 : 48719 : cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4011 : 48719 : qp_qual_cost.startup -= merge_qual_cost.startup;
4012 : 48719 : qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
4013 : :
4014 : : /*
4015 : : * With a SEMI or ANTI join, or if the innerrel is known unique, the
4016 : : * executor will stop scanning for matches after the first match. When
4017 : : * all the joinclauses are merge clauses, this means we don't ever need to
4018 : : * back up the merge, and so we can skip mark/restore overhead.
4019 : : */
4020 [ + + ]: 48719 : if ((path->jpath.jointype == JOIN_SEMI ||
4021 [ + + ]: 47777 : path->jpath.jointype == JOIN_ANTI ||
4022 [ + + ]: 48719 : extra->inner_unique) &&
4023 : 97438 : (list_length(path->jpath.joinrestrictinfo) ==
4024 : 48719 : list_length(path->path_mergeclauses)))
4025 : 11644 : path->skip_mark_restore = true;
4026 : : else
4027 : 37075 : path->skip_mark_restore = false;
4028 : :
4029 : : /*
4030 : : * Get approx # tuples passing the mergequals. We use approx_tuple_count
4031 : : * here because we need an estimate done with JOIN_INNER semantics.
4032 : : */
4033 : 48719 : mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
4034 : :
4035 : : /*
4036 : : * When there are equal merge keys in the outer relation, the mergejoin
4037 : : * must rescan any matching tuples in the inner relation. This means
4038 : : * re-fetching inner tuples; we have to estimate how often that happens.
4039 : : *
4040 : : * For regular inner and outer joins, the number of re-fetches can be
4041 : : * estimated approximately as size of merge join output minus size of
4042 : : * inner relation. Assume that the distinct key values are 1, 2, ..., and
4043 : : * denote the number of values of each key in the outer relation as m1,
4044 : : * m2, ...; in the inner relation, n1, n2, ... Then we have
4045 : : *
4046 : : * size of join = m1 * n1 + m2 * n2 + ...
4047 : : *
4048 : : * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
4049 : : * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
4050 : : * relation
4051 : : *
4052 : : * This equation works correctly for outer tuples having no inner match
4053 : : * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
4054 : : * are effectively subtracting those from the number of rescanned tuples,
4055 : : * when we should not. Can we do better without expensive selectivity
4056 : : * computations?
4057 : : *
4058 : : * The whole issue is moot if we know we don't need to mark/restore at
4059 : : * all, or if we are working from a unique-ified outer input.
4060 : : */
4061 [ + + + + ]: 49686 : if (path->skip_mark_restore ||
4062 [ + + + + ]: 37075 : RELATION_WAS_MADE_UNIQUE(outer_path->parent, extra->sjinfo,
4063 : : path->jpath.jointype))
4064 : 12541 : rescannedtuples = 0;
4065 : : else
4066 : : {
4067 : 36178 : rescannedtuples = mergejointuples - inner_path_rows;
4068 : : /* Must clamp because of possible underestimate */
4069 [ + + ]: 36178 : if (rescannedtuples < 0)
4070 : 5007 : rescannedtuples = 0;
4071 : : }
4072 : :
4073 : : /*
4074 : : * We'll inflate various costs this much to account for rescanning. Note
4075 : : * that this is to be multiplied by something involving inner_rows, or
4076 : : * another number related to the portion of the inner rel we'll scan.
4077 : : */
4078 : 48719 : rescanratio = 1.0 + (rescannedtuples / inner_rows);
4079 : :
4080 : : /*
4081 : : * Decide whether we want to materialize the inner input to shield it from
4082 : : * mark/restore and performing re-fetches. Our cost model for regular
4083 : : * re-fetches is that a re-fetch costs the same as an original fetch,
4084 : : * which is probably an overestimate; but on the other hand we ignore the
4085 : : * bookkeeping costs of mark/restore. Not clear if it's worth developing
4086 : : * a more refined model. So we just need to inflate the inner run cost by
4087 : : * rescanratio.
4088 : : */
4089 : 48719 : bare_inner_cost = inner_run_cost * rescanratio;
4090 : :
4091 : : /*
4092 : : * When we interpose a Material node the re-fetch cost is assumed to be
4093 : : * just cpu_operator_cost per tuple, independently of the underlying
4094 : : * plan's cost; and we charge an extra cpu_operator_cost per original
4095 : : * fetch as well. Note that we're assuming the materialize node will
4096 : : * never spill to disk, since it only has to remember tuples back to the
4097 : : * last mark. (If there are a huge number of duplicates, our other cost
4098 : : * factors will make the path so expensive that it probably won't get
4099 : : * chosen anyway.) So we don't use cost_rescan here.
4100 : : *
4101 : : * Note: keep this estimate in sync with create_mergejoin_plan's labeling
4102 : : * of the generated Material node.
4103 : : */
4104 : 97438 : mat_inner_cost = inner_run_cost +
4105 : 48719 : cpu_operator_cost * inner_rows * rescanratio;
4106 : :
4107 : : /*
4108 : : * If we don't need mark/restore at all, we don't need materialization.
4109 : : */
4110 [ + + ]: 48719 : if (path->skip_mark_restore)
4111 : 11644 : path->materialize_inner = false;
4112 : :
4113 : : /*
4114 : : * If merge joins with materialization are enabled, then choose
4115 : : * materialization if either (a) it looks cheaper or (b) merge joins
4116 : : * without materialization are disabled.
4117 : : */
4118 [ + + + + ]: 73781 : else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
4119 [ + + ]: 37058 : (mat_inner_cost < bare_inner_cost ||
4120 : 36706 : (extra->pgs_mask & PGS_MERGEJOIN_PLAIN) == 0))
4121 : 355 : path->materialize_inner = true;
4122 : :
4123 : : /*
4124 : : * Regardless of what plan shapes are enabled and what the costs seem to
4125 : : * be, we *must* materialize it if the inner path is to be used directly
4126 : : * (without sorting) and it doesn't support mark/restore. Planner failure
4127 : : * is not an option!
4128 : : *
4129 : : * Since the inner side must be ordered, and only Sorts and IndexScans can
4130 : : * create order to begin with, and they both support mark/restore, you
4131 : : * might think there's no problem --- but you'd be wrong. Nestloop and
4132 : : * merge joins can *preserve* the order of their inputs, so they can be
4133 : : * selected as the input of a mergejoin, and they don't support
4134 : : * mark/restore at present.
4135 : : */
4136 [ + + + + ]: 36720 : else if (innersortkeys == NIL &&
4137 : 339 : !ExecSupportsMarkRestore(inner_path))
4138 : 179 : path->materialize_inner = true;
4139 : :
4140 : : /*
4141 : : * Also, force materializing if the inner path is to be sorted and the
4142 : : * sort is expected to spill to disk. This is because the final merge
4143 : : * pass can be done on-the-fly if it doesn't have to support mark/restore.
4144 : : * We don't try to adjust the cost estimates for this consideration,
4145 : : * though.
4146 : : *
4147 : : * Since materialization is a performance optimization in this case,
4148 : : * rather than necessary for correctness, we skip it if materialization is
4149 : : * switched off.
4150 : : */
4151 [ + + ]: 36541 : else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
4152 [ + + + + ]: 36524 : innersortkeys != NIL &&
4153 : 72730 : relation_byte_size(inner_path_rows,
4154 : 72730 : inner_path->pathtarget->width) >
4155 : 36365 : work_mem * (Size) 1024)
4156 : 22 : path->materialize_inner = true;
4157 : : else
4158 : 36519 : path->materialize_inner = false;
4159 : :
4160 : : /* Get the number of disabled nodes, not yet including this one. */
4161 : 48719 : path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4162 : :
4163 : : /*
4164 : : * Charge the right incremental cost for the chosen case, and update
4165 : : * enable_mask as appropriate.
4166 : : */
4167 [ + + ]: 48719 : if (path->materialize_inner)
4168 : : {
4169 : 556 : run_cost += mat_inner_cost;
4170 : 556 : enable_mask |= PGS_MERGEJOIN_MATERIALIZE;
4171 : 556 : }
4172 : : else
4173 : : {
4174 : 48163 : run_cost += bare_inner_cost;
4175 : 48163 : enable_mask |= PGS_MERGEJOIN_PLAIN;
4176 : : }
4177 : :
4178 : : /* Incremental count of disabled nodes if this node is disabled. */
4179 [ + + ]: 48719 : if (path->jpath.path.parallel_workers == 0)
4180 : 37759 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
4181 [ + + ]: 48719 : if ((extra->pgs_mask & enable_mask) != enable_mask)
4182 : 27 : ++path->jpath.path.disabled_nodes;
4183 : :
4184 : : /* CPU costs */
4185 : :
4186 : : /*
4187 : : * The number of tuple comparisons needed is approximately number of outer
4188 : : * rows plus number of inner rows plus number of rescanned tuples (can we
4189 : : * refine this?). At each one, we need to evaluate the mergejoin quals.
4190 : : */
4191 : 48719 : startup_cost += merge_qual_cost.startup;
4192 : 97438 : startup_cost += merge_qual_cost.per_tuple *
4193 : 48719 : (outer_skip_rows + inner_skip_rows * rescanratio);
4194 : 97438 : run_cost += merge_qual_cost.per_tuple *
4195 : 97438 : ((outer_rows - outer_skip_rows) +
4196 : 48719 : (inner_rows - inner_skip_rows) * rescanratio);
4197 : :
4198 : : /*
4199 : : * For each tuple that gets through the mergejoin proper, we charge
4200 : : * cpu_tuple_cost plus the cost of evaluating additional restriction
4201 : : * clauses that are to be applied at the join. (This is pessimistic since
4202 : : * not all of the quals may get evaluated at each tuple.)
4203 : : *
4204 : : * Note: we could adjust for SEMI/ANTI joins skipping some qual
4205 : : * evaluations here, but it's probably not worth the trouble.
4206 : : */
4207 : 48719 : startup_cost += qp_qual_cost.startup;
4208 : 48719 : cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4209 : 48719 : run_cost += cpu_per_tuple * mergejointuples;
4210 : :
4211 : : /* tlist eval costs are paid per output row, not per tuple scanned */
4212 : 48719 : startup_cost += path->jpath.path.pathtarget->cost.startup;
4213 : 48719 : run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4214 : :
4215 : 48719 : path->jpath.path.startup_cost = startup_cost;
4216 : 48719 : path->jpath.path.total_cost = startup_cost + run_cost;
4217 : 48719 : }
4218 : :
4219 : : /*
4220 : : * run mergejoinscansel() with caching
4221 : : */
4222 : : static MergeScanSelCache *
4223 : 122781 : cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
4224 : : {
4225 : 122781 : MergeScanSelCache *cache;
4226 : 122781 : ListCell *lc;
4227 : 122781 : Selectivity leftstartsel,
4228 : : leftendsel,
4229 : : rightstartsel,
4230 : : rightendsel;
4231 : 122781 : MemoryContext oldcontext;
4232 : :
4233 : : /* Do we have this result already? */
4234 [ + + + + : 231763 : foreach(lc, rinfo->scansel_cache)
+ + + + ]
4235 : : {
4236 : 108982 : cache = (MergeScanSelCache *) lfirst(lc);
4237 [ + - ]: 108982 : if (cache->opfamily == pathkey->pk_opfamily &&
4238 [ + - ]: 108982 : cache->collation == pathkey->pk_eclass->ec_collation &&
4239 [ + + - + ]: 108982 : cache->cmptype == pathkey->pk_cmptype &&
4240 : 108981 : cache->nulls_first == pathkey->pk_nulls_first)
4241 : 108981 : return cache;
4242 : 1 : }
4243 : :
4244 : : /* Nope, do the computation */
4245 : 27600 : mergejoinscansel(root,
4246 : 13800 : (Node *) rinfo->clause,
4247 : 13800 : pathkey->pk_opfamily,
4248 : 13800 : pathkey->pk_cmptype,
4249 : 13800 : pathkey->pk_nulls_first,
4250 : : &leftstartsel,
4251 : : &leftendsel,
4252 : : &rightstartsel,
4253 : : &rightendsel);
4254 : :
4255 : : /* Cache the result in suitably long-lived workspace */
4256 : 13800 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4257 : :
4258 : 13800 : cache = palloc_object(MergeScanSelCache);
4259 : 13800 : cache->opfamily = pathkey->pk_opfamily;
4260 : 13800 : cache->collation = pathkey->pk_eclass->ec_collation;
4261 : 13800 : cache->cmptype = pathkey->pk_cmptype;
4262 : 13800 : cache->nulls_first = pathkey->pk_nulls_first;
4263 : 13800 : cache->leftstartsel = leftstartsel;
4264 : 13800 : cache->leftendsel = leftendsel;
4265 : 13800 : cache->rightstartsel = rightstartsel;
4266 : 13800 : cache->rightendsel = rightendsel;
4267 : :
4268 : 13800 : rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4269 : :
4270 : 13800 : MemoryContextSwitchTo(oldcontext);
4271 : :
4272 : 13800 : return cache;
4273 : 122781 : }
4274 : :
4275 : : /*
4276 : : * initial_cost_hashjoin
4277 : : * Preliminary estimate of the cost of a hashjoin path.
4278 : : *
4279 : : * This must quickly produce lower-bound estimates of the path's startup and
4280 : : * total costs. If we are unable to eliminate the proposed path from
4281 : : * consideration using the lower bounds, final_cost_hashjoin will be called
4282 : : * to obtain the final estimates.
4283 : : *
4284 : : * The exact division of labor between this function and final_cost_hashjoin
4285 : : * is private to them, and represents a tradeoff between speed of the initial
4286 : : * estimate and getting a tight lower bound. We choose to not examine the
4287 : : * join quals here (other than by counting the number of hash clauses),
4288 : : * so we can't do much with CPU costs. We do assume that
4289 : : * ExecChooseHashTableSize is cheap enough to use here.
4290 : : *
4291 : : * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
4292 : : * other data to be used by final_cost_hashjoin
4293 : : * 'jointype' is the type of join to be performed
4294 : : * 'hashclauses' is the list of joinclauses to be used as hash clauses
4295 : : * 'outer_path' is the outer input to the join
4296 : : * 'inner_path' is the inner input to the join
4297 : : * 'extra' contains miscellaneous information about the join
4298 : : * 'parallel_hash' indicates that inner_path is partial and that a shared
4299 : : * hash table will be built in parallel
4300 : : */
4301 : : void
4302 : 82310 : initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
4303 : : JoinType jointype,
4304 : : List *hashclauses,
4305 : : Path *outer_path, Path *inner_path,
4306 : : JoinPathExtraData *extra,
4307 : : bool parallel_hash)
4308 : : {
4309 : 82310 : int disabled_nodes;
4310 : 82310 : Cost startup_cost = 0;
4311 : 82310 : Cost run_cost = 0;
4312 : 82310 : double outer_path_rows = outer_path->rows;
4313 : 82310 : double inner_path_rows = inner_path->rows;
4314 : 82310 : double inner_path_rows_total = inner_path_rows;
4315 : 82310 : int num_hashclauses = list_length(hashclauses);
4316 : 82310 : int numbuckets;
4317 : 82310 : int numbatches;
4318 : 82310 : int num_skew_mcvs;
4319 : 82310 : size_t space_allowed; /* unused */
4320 : 82310 : uint64 enable_mask = PGS_HASHJOIN;
4321 : :
4322 [ + + ]: 82310 : if (outer_path->parallel_workers == 0)
4323 : 57664 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
4324 : :
4325 : : /* Count up disabled nodes. */
4326 : 82310 : disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
4327 : 82310 : disabled_nodes += inner_path->disabled_nodes;
4328 : 82310 : disabled_nodes += outer_path->disabled_nodes;
4329 : :
4330 : : /* cost of source data */
4331 : 82310 : startup_cost += outer_path->startup_cost;
4332 : 82310 : run_cost += outer_path->total_cost - outer_path->startup_cost;
4333 : 82310 : startup_cost += inner_path->total_cost;
4334 : :
4335 : : /*
4336 : : * Cost of computing hash function: must do it once per input tuple. We
4337 : : * charge one cpu_operator_cost for each column's hash function. Also,
4338 : : * tack on one cpu_tuple_cost per inner row, to model the costs of
4339 : : * inserting the row into the hashtable.
4340 : : *
4341 : : * XXX when a hashclause is more complex than a single operator, we really
4342 : : * should charge the extra eval costs of the left or right side, as
4343 : : * appropriate, here. This seems more work than it's worth at the moment.
4344 : : */
4345 : 164620 : startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
4346 : 82310 : * inner_path_rows;
4347 : 82310 : run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
4348 : :
4349 : : /*
4350 : : * If this is a parallel hash build, then the value we have for
4351 : : * inner_rows_total currently refers only to the rows returned by each
4352 : : * participant. For shared hash table size estimation, we need the total
4353 : : * number, so we need to undo the division.
4354 : : */
4355 [ + + ]: 82310 : if (parallel_hash)
4356 : 12559 : inner_path_rows_total *= get_parallel_divisor(inner_path);
4357 : :
4358 : : /*
4359 : : * Get hash table size that executor would use for inner relation.
4360 : : *
4361 : : * XXX for the moment, always assume that skew optimization will be
4362 : : * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
4363 : : * trying to determine that for sure.
4364 : : *
4365 : : * XXX at some point it might be interesting to try to account for skew
4366 : : * optimization in the cost estimate, but for now, we don't.
4367 : : */
4368 : 164620 : ExecChooseHashTableSize(inner_path_rows_total,
4369 : 82310 : inner_path->pathtarget->width,
4370 : : true, /* useskew */
4371 : 82310 : parallel_hash, /* try_combined_hash_mem */
4372 : 82310 : outer_path->parallel_workers,
4373 : : &space_allowed,
4374 : : &numbuckets,
4375 : : &numbatches,
4376 : : &num_skew_mcvs);
4377 : :
4378 : : /*
4379 : : * If inner relation is too big then we will need to "batch" the join,
4380 : : * which implies writing and reading most of the tuples to disk an extra
4381 : : * time. Charge seq_page_cost per page, since the I/O should be nice and
4382 : : * sequential. Writing the inner rel counts as startup cost, all the rest
4383 : : * as run cost.
4384 : : */
4385 [ + + ]: 82310 : if (numbatches > 1)
4386 : : {
4387 : 696 : double outerpages = page_size(outer_path_rows,
4388 : 348 : outer_path->pathtarget->width);
4389 : 696 : double innerpages = page_size(inner_path_rows,
4390 : 348 : inner_path->pathtarget->width);
4391 : :
4392 : 348 : startup_cost += seq_page_cost * innerpages;
4393 : 348 : run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4394 : 348 : }
4395 : :
4396 : : /* CPU costs left for later */
4397 : :
4398 : : /* Public result fields */
4399 : 82310 : workspace->disabled_nodes = disabled_nodes;
4400 : 82310 : workspace->startup_cost = startup_cost;
4401 : 82310 : workspace->total_cost = startup_cost + run_cost;
4402 : : /* Save private data for final_cost_hashjoin */
4403 : 82310 : workspace->run_cost = run_cost;
4404 : 82310 : workspace->numbuckets = numbuckets;
4405 : 82310 : workspace->numbatches = numbatches;
4406 : 82310 : workspace->inner_rows_total = inner_path_rows_total;
4407 : 82310 : }
4408 : :
4409 : : /*
4410 : : * final_cost_hashjoin
4411 : : * Final estimate of the cost and result size of a hashjoin path.
4412 : : *
4413 : : * Note: the numbatches estimate is also saved into 'path' for use later
4414 : : *
4415 : : * 'path' is already filled in except for the rows and cost fields and
4416 : : * num_batches
4417 : : * 'workspace' is the result from initial_cost_hashjoin
4418 : : * 'extra' contains miscellaneous information about the join
4419 : : */
4420 : : void
4421 : 52877 : final_cost_hashjoin(PlannerInfo *root, HashPath *path,
4422 : : JoinCostWorkspace *workspace,
4423 : : JoinPathExtraData *extra)
4424 : : {
4425 : 52877 : Path *outer_path = path->jpath.outerjoinpath;
4426 : 52877 : Path *inner_path = path->jpath.innerjoinpath;
4427 : 52877 : double outer_path_rows = outer_path->rows;
4428 : 52877 : double inner_path_rows = inner_path->rows;
4429 : 52877 : double inner_path_rows_total = workspace->inner_rows_total;
4430 : 52877 : List *hashclauses = path->path_hashclauses;
4431 : 52877 : Cost startup_cost = workspace->startup_cost;
4432 : 52877 : Cost run_cost = workspace->run_cost;
4433 : 52877 : int numbuckets = workspace->numbuckets;
4434 : 52877 : int numbatches = workspace->numbatches;
4435 : 52877 : Cost cpu_per_tuple;
4436 : 52877 : QualCost hash_qual_cost;
4437 : 52877 : QualCost qp_qual_cost;
4438 : 52877 : double hashjointuples;
4439 : 52877 : double virtualbuckets;
4440 : 52877 : Selectivity innerbucketsize;
4441 : 52877 : Selectivity innermcvfreq;
4442 : 52877 : ListCell *hcl;
4443 : :
4444 : : /* Set the number of disabled nodes. */
4445 : 52877 : path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4446 : :
4447 : : /* Mark the path with the correct row estimate */
4448 [ + + ]: 52877 : if (path->jpath.path.param_info)
4449 : 179 : path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4450 : : else
4451 : 52698 : path->jpath.path.rows = path->jpath.path.parent->rows;
4452 : :
4453 : : /* For partial paths, scale row estimate. */
4454 [ + + ]: 52877 : if (path->jpath.path.parallel_workers > 0)
4455 : : {
4456 : 17884 : double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4457 : :
4458 : 17884 : path->jpath.path.rows =
4459 : 17884 : clamp_row_est(path->jpath.path.rows / parallel_divisor);
4460 : 17884 : }
4461 : :
4462 : : /* mark the path with estimated # of batches */
4463 : 52877 : path->num_batches = numbatches;
4464 : :
4465 : : /* store the total number of tuples (sum of partial row estimates) */
4466 : 52877 : path->inner_rows_total = inner_path_rows_total;
4467 : :
4468 : : /* and compute the number of "virtual" buckets in the whole join */
4469 : 52877 : virtualbuckets = (double) numbuckets * (double) numbatches;
4470 : :
4471 : : /*
4472 : : * Determine bucketsize fraction and MCV frequency for the inner relation.
4473 : : * We use the smallest bucketsize or MCV frequency estimated for any
4474 : : * individual hashclause; this is undoubtedly conservative.
4475 : : *
4476 : : * BUT: if inner relation has been unique-ified, we can assume it's good
4477 : : * for hashing. This is important both because it's the right answer, and
4478 : : * because we avoid contaminating the cache with a value that's wrong for
4479 : : * non-unique-ified paths.
4480 : : */
4481 [ + + + + : 52877 : if (RELATION_WAS_MADE_UNIQUE(inner_path->parent, extra->sjinfo,
+ + ]
4482 : : path->jpath.jointype))
4483 : : {
4484 : 474 : innerbucketsize = 1.0 / virtualbuckets;
4485 : 474 : innermcvfreq = 1.0 / inner_path_rows_total;
4486 : 474 : }
4487 : : else
4488 : : {
4489 : 52403 : List *otherclauses;
4490 : :
4491 : 52403 : innerbucketsize = 1.0;
4492 : 52403 : innermcvfreq = 1.0;
4493 : :
4494 : : /* At first, try to estimate bucket size using extended statistics. */
4495 : 104806 : otherclauses = estimate_multivariate_bucketsize(root,
4496 : 52403 : inner_path->parent,
4497 : 52403 : hashclauses,
4498 : : &innerbucketsize);
4499 : :
4500 : : /* Pass through the remaining clauses */
4501 [ + + + + : 107412 : foreach(hcl, otherclauses)
+ + ]
4502 : : {
4503 : 55009 : RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
4504 : 55009 : Selectivity thisbucketsize;
4505 : 55009 : Selectivity thismcvfreq;
4506 : :
4507 : : /*
4508 : : * First we have to figure out which side of the hashjoin clause
4509 : : * is the inner side.
4510 : : *
4511 : : * Since we tend to visit the same clauses over and over when
4512 : : * planning a large query, we cache the bucket stats estimates in
4513 : : * the RestrictInfo node to avoid repeated lookups of statistics.
4514 : : */
4515 [ + + + + ]: 110018 : if (bms_is_subset(restrictinfo->right_relids,
4516 : 55009 : inner_path->parent->relids))
4517 : : {
4518 : : /* righthand side is inner */
4519 : 28882 : thisbucketsize = restrictinfo->right_bucketsize;
4520 [ + + ]: 28882 : if (thisbucketsize < 0)
4521 : : {
4522 : : /* not cached yet */
4523 : 23642 : estimate_hash_bucket_stats(root,
4524 : 11821 : get_rightop(restrictinfo->clause),
4525 : 11821 : virtualbuckets,
4526 : 11821 : &restrictinfo->right_mcvfreq,
4527 : 11821 : &restrictinfo->right_bucketsize);
4528 : 11821 : thisbucketsize = restrictinfo->right_bucketsize;
4529 : 11821 : }
4530 : 28882 : thismcvfreq = restrictinfo->right_mcvfreq;
4531 : 28882 : }
4532 : : else
4533 : : {
4534 [ - + ]: 26127 : Assert(bms_is_subset(restrictinfo->left_relids,
4535 : : inner_path->parent->relids));
4536 : : /* lefthand side is inner */
4537 : 26127 : thisbucketsize = restrictinfo->left_bucketsize;
4538 [ + + ]: 26127 : if (thisbucketsize < 0)
4539 : : {
4540 : : /* not cached yet */
4541 : 19732 : estimate_hash_bucket_stats(root,
4542 : 9866 : get_leftop(restrictinfo->clause),
4543 : 9866 : virtualbuckets,
4544 : 9866 : &restrictinfo->left_mcvfreq,
4545 : 9866 : &restrictinfo->left_bucketsize);
4546 : 9866 : thisbucketsize = restrictinfo->left_bucketsize;
4547 : 9866 : }
4548 : 26127 : thismcvfreq = restrictinfo->left_mcvfreq;
4549 : : }
4550 : :
4551 [ + + ]: 55009 : if (innerbucketsize > thisbucketsize)
4552 : 41196 : innerbucketsize = thisbucketsize;
4553 : : /* Disregard zero for MCV freq, it means we have no data */
4554 [ + + + + ]: 55009 : if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq)
4555 : 41734 : innermcvfreq = thismcvfreq;
4556 : 55009 : }
4557 : 52403 : }
4558 : :
4559 : : /*
4560 : : * If the bucket holding the inner MCV would exceed hash_mem, we don't
4561 : : * want to hash unless there is really no other alternative, so apply
4562 : : * disable_cost. (The executor normally copes with excessive memory usage
4563 : : * by splitting batches, but obviously it cannot separate equal values
4564 : : * that way, so it will be unable to drive the batch size below hash_mem
4565 : : * when this is true.)
4566 : : */
4567 : 105754 : if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4568 [ + + + + ]: 105754 : inner_path->pathtarget->width) > get_hash_memory_limit())
4569 : 8 : startup_cost += disable_cost;
4570 : :
4571 : : /*
4572 : : * Compute cost of the hashquals and qpquals (other restriction clauses)
4573 : : * separately.
4574 : : */
4575 : 52877 : cost_qual_eval(&hash_qual_cost, hashclauses, root);
4576 : 52877 : cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4577 : 52877 : qp_qual_cost.startup -= hash_qual_cost.startup;
4578 : 52877 : qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4579 : :
4580 : : /* CPU costs */
4581 : :
4582 [ + + ]: 52877 : if (path->jpath.jointype == JOIN_SEMI ||
4583 [ + + + + ]: 52090 : path->jpath.jointype == JOIN_ANTI ||
4584 : 51701 : extra->inner_unique)
4585 : : {
4586 : 10356 : double outer_matched_rows;
4587 : 10356 : Selectivity inner_scan_frac;
4588 : :
4589 : : /*
4590 : : * With a SEMI or ANTI join, or if the innerrel is known unique, the
4591 : : * executor will stop after the first match.
4592 : : *
4593 : : * For an outer-rel row that has at least one match, we can expect the
4594 : : * bucket scan to stop after a fraction 1/(match_count+1) of the
4595 : : * bucket's rows, if the matches are evenly distributed. Since they
4596 : : * probably aren't quite evenly distributed, we apply a fuzz factor of
4597 : : * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4598 : : * to clamp inner_scan_frac to at most 1.0; but since match_count is
4599 : : * at least 1, no such clamp is needed now.)
4600 : : */
4601 : 10356 : outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4602 : 10356 : inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4603 : :
4604 : 10356 : startup_cost += hash_qual_cost.startup;
4605 : 20712 : run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4606 : 10356 : clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4607 : :
4608 : : /*
4609 : : * For unmatched outer-rel rows, the picture is quite a lot different.
4610 : : * In the first place, there is no reason to assume that these rows
4611 : : * preferentially hit heavily-populated buckets; instead assume they
4612 : : * are uncorrelated with the inner distribution and so they see an
4613 : : * average bucket size of inner_path_rows / virtualbuckets. In the
4614 : : * second place, it seems likely that they will have few if any exact
4615 : : * hash-code matches and so very few of the tuples in the bucket will
4616 : : * actually require eval of the hash quals. We don't have any good
4617 : : * way to estimate how many will, but for the moment assume that the
4618 : : * effective cost per bucket entry is one-tenth what it is for
4619 : : * matchable tuples.
4620 : : */
4621 : 31068 : run_cost += hash_qual_cost.per_tuple *
4622 : 20712 : (outer_path_rows - outer_matched_rows) *
4623 : 10356 : clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4624 : :
4625 : : /* Get # of tuples that will pass the basic join */
4626 [ + + ]: 10356 : if (path->jpath.jointype == JOIN_ANTI)
4627 : 389 : hashjointuples = outer_path_rows - outer_matched_rows;
4628 : : else
4629 : 9967 : hashjointuples = outer_matched_rows;
4630 : 10356 : }
4631 : : else
4632 : : {
4633 : : /*
4634 : : * The number of tuple comparisons needed is the number of outer
4635 : : * tuples times the typical number of tuples in a hash bucket, which
4636 : : * is the inner relation size times its bucketsize fraction. At each
4637 : : * one, we need to evaluate the hashjoin quals. But actually,
4638 : : * charging the full qual eval cost at each tuple is pessimistic,
4639 : : * since we don't evaluate the quals unless the hash values match
4640 : : * exactly. For lack of a better idea, halve the cost estimate to
4641 : : * allow for that.
4642 : : */
4643 : 42521 : startup_cost += hash_qual_cost.startup;
4644 : 85042 : run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4645 : 42521 : clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4646 : :
4647 : : /*
4648 : : * Get approx # tuples passing the hashquals. We use
4649 : : * approx_tuple_count here because we need an estimate done with
4650 : : * JOIN_INNER semantics.
4651 : : */
4652 : 42521 : hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4653 : : }
4654 : :
4655 : : /*
4656 : : * For each tuple that gets through the hashjoin proper, we charge
4657 : : * cpu_tuple_cost plus the cost of evaluating additional restriction
4658 : : * clauses that are to be applied at the join. (This is pessimistic since
4659 : : * not all of the quals may get evaluated at each tuple.)
4660 : : */
4661 : 52877 : startup_cost += qp_qual_cost.startup;
4662 : 52877 : cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4663 : 52877 : run_cost += cpu_per_tuple * hashjointuples;
4664 : :
4665 : : /* tlist eval costs are paid per output row, not per tuple scanned */
4666 : 52877 : startup_cost += path->jpath.path.pathtarget->cost.startup;
4667 : 52877 : run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4668 : :
4669 : 52877 : path->jpath.path.startup_cost = startup_cost;
4670 : 52877 : path->jpath.path.total_cost = startup_cost + run_cost;
4671 : 52877 : }
4672 : :
4673 : :
4674 : : /*
4675 : : * cost_subplan
4676 : : * Figure the costs for a SubPlan (or initplan).
4677 : : *
4678 : : * Note: we could dig the subplan's Plan out of the root list, but in practice
4679 : : * all callers have it handy already, so we make them pass it.
4680 : : */
4681 : : void
4682 : 4383 : cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
4683 : : {
4684 : 4383 : QualCost sp_cost;
4685 : :
4686 : : /*
4687 : : * Figure any cost for evaluating the testexpr.
4688 : : *
4689 : : * Usually, SubPlan nodes are built very early, before we have constructed
4690 : : * any RelOptInfos for the parent query level, which means the parent root
4691 : : * does not yet contain enough information to safely consult statistics.
4692 : : * Therefore, we pass root as NULL here. cost_qual_eval() is already
4693 : : * well-equipped to handle a NULL root.
4694 : : *
4695 : : * One exception is SubPlan nodes built for the initplans of MIN/MAX
4696 : : * aggregates from indexes (cf. SS_make_initplan_from_plan). In this
4697 : : * case, having a NULL root is safe because testexpr will be NULL.
4698 : : * Besides, an initplan will by definition not consult anything from the
4699 : : * parent plan.
4700 : : */
4701 : 4383 : cost_qual_eval(&sp_cost,
4702 : 4383 : make_ands_implicit((Expr *) subplan->testexpr),
4703 : : NULL);
4704 : :
4705 [ + + ]: 4383 : if (subplan->useHashTable)
4706 : : {
4707 : : /*
4708 : : * If we are using a hash table for the subquery outputs, then the
4709 : : * cost of evaluating the query is a one-time cost. We charge one
4710 : : * cpu_operator_cost per tuple for the work of loading the hashtable,
4711 : : * too.
4712 : : */
4713 : 530 : sp_cost.startup += plan->total_cost +
4714 : 265 : cpu_operator_cost * plan->plan_rows;
4715 : :
4716 : : /*
4717 : : * The per-tuple costs include the cost of evaluating the lefthand
4718 : : * expressions, plus the cost of probing the hashtable. We already
4719 : : * accounted for the lefthand expressions as part of the testexpr, and
4720 : : * will also have counted one cpu_operator_cost for each comparison
4721 : : * operator. That is probably too low for the probing cost, but it's
4722 : : * hard to make a better estimate, so live with it for now.
4723 : : */
4724 : 265 : }
4725 : : else
4726 : : {
4727 : : /*
4728 : : * Otherwise we will be rescanning the subplan output on each
4729 : : * evaluation. We need to estimate how much of the output we will
4730 : : * actually need to scan. NOTE: this logic should agree with the
4731 : : * tuple_fraction estimates used by make_subplan() in
4732 : : * plan/subselect.c.
4733 : : */
4734 : 4118 : Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4735 : :
4736 [ + + ]: 4118 : if (subplan->subLinkType == EXISTS_SUBLINK)
4737 : : {
4738 : : /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4739 : 227 : sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4740 : 227 : }
4741 [ + + + + ]: 3891 : else if (subplan->subLinkType == ALL_SUBLINK ||
4742 : 3888 : subplan->subLinkType == ANY_SUBLINK)
4743 : : {
4744 : : /* assume we need 50% of the tuples */
4745 : 19 : sp_cost.per_tuple += 0.50 * plan_run_cost;
4746 : : /* also charge a cpu_operator_cost per row examined */
4747 : 19 : sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4748 : 19 : }
4749 : : else
4750 : : {
4751 : : /* assume we need all tuples */
4752 : 3872 : sp_cost.per_tuple += plan_run_cost;
4753 : : }
4754 : :
4755 : : /*
4756 : : * Also account for subplan's startup cost. If the subplan is
4757 : : * uncorrelated or undirect correlated, AND its topmost node is one
4758 : : * that materializes its output, assume that we'll only need to pay
4759 : : * its startup cost once; otherwise assume we pay the startup cost
4760 : : * every time.
4761 : : */
4762 [ + + + + ]: 4118 : if (subplan->parParam == NIL &&
4763 : 951 : ExecMaterializesOutput(nodeTag(plan)))
4764 : 59 : sp_cost.startup += plan->startup_cost;
4765 : : else
4766 : 4059 : sp_cost.per_tuple += plan->startup_cost;
4767 : 4118 : }
4768 : :
4769 : 4383 : subplan->startup_cost = sp_cost.startup;
4770 : 4383 : subplan->per_call_cost = sp_cost.per_tuple;
4771 : 4383 : }
4772 : :
4773 : :
4774 : : /*
4775 : : * cost_rescan
4776 : : * Given a finished Path, estimate the costs of rescanning it after
4777 : : * having done so the first time. For some Path types a rescan is
4778 : : * cheaper than an original scan (if no parameters change), and this
4779 : : * function embodies knowledge about that. The default is to return
4780 : : * the same costs stored in the Path. (Note that the cost estimates
4781 : : * actually stored in Paths are always for first scans.)
4782 : : *
4783 : : * This function is not currently intended to model effects such as rescans
4784 : : * being cheaper due to disk block caching; what we are concerned with is
4785 : : * plan types wherein the executor caches results explicitly, or doesn't
4786 : : * redo startup calculations, etc.
4787 : : */
4788 : : static void
4789 : 284672 : cost_rescan(PlannerInfo *root, Path *path,
4790 : : Cost *rescan_startup_cost, /* output parameters */
4791 : : Cost *rescan_total_cost)
4792 : : {
4793 [ + + + + : 284672 : switch (path->pathtype)
+ + ]
4794 : : {
4795 : : case T_FunctionScan:
4796 : :
4797 : : /*
4798 : : * Currently, nodeFunctionscan.c always executes the function to
4799 : : * completion before returning any rows, and caches the results in
4800 : : * a tuplestore. So the function eval cost is all startup cost
4801 : : * and isn't paid over again on rescans. However, all run costs
4802 : : * will be paid over again.
4803 : : */
4804 : 1646 : *rescan_startup_cost = 0;
4805 : 1646 : *rescan_total_cost = path->total_cost - path->startup_cost;
4806 : 1646 : break;
4807 : : case T_HashJoin:
4808 : :
4809 : : /*
4810 : : * If it's a single-batch join, we don't need to rebuild the hash
4811 : : * table during a rescan.
4812 : : */
4813 [ + - ]: 8133 : if (((HashPath *) path)->num_batches == 1)
4814 : : {
4815 : : /* Startup cost is exactly the cost of hash table building */
4816 : 8133 : *rescan_startup_cost = 0;
4817 : 8133 : *rescan_total_cost = path->total_cost - path->startup_cost;
4818 : 8133 : }
4819 : : else
4820 : : {
4821 : : /* Otherwise, no special treatment */
4822 : 0 : *rescan_startup_cost = path->startup_cost;
4823 : 0 : *rescan_total_cost = path->total_cost;
4824 : : }
4825 : 8133 : break;
4826 : : case T_CteScan:
4827 : : case T_WorkTableScan:
4828 : : {
4829 : : /*
4830 : : * These plan types materialize their final result in a
4831 : : * tuplestore or tuplesort object. So the rescan cost is only
4832 : : * cpu_tuple_cost per tuple, unless the result is large enough
4833 : : * to spill to disk.
4834 : : */
4835 : 117 : Cost run_cost = cpu_tuple_cost * path->rows;
4836 : 234 : double nbytes = relation_byte_size(path->rows,
4837 : 117 : path->pathtarget->width);
4838 : 117 : double work_mem_bytes = work_mem * (Size) 1024;
4839 : :
4840 [ + - ]: 117 : if (nbytes > work_mem_bytes)
4841 : : {
4842 : : /* It will spill, so account for re-read cost */
4843 : 0 : double npages = ceil(nbytes / BLCKSZ);
4844 : :
4845 : 0 : run_cost += seq_page_cost * npages;
4846 : 0 : }
4847 : 117 : *rescan_startup_cost = 0;
4848 : 117 : *rescan_total_cost = run_cost;
4849 : 117 : }
4850 : 117 : break;
4851 : : case T_Material:
4852 : : case T_Sort:
4853 : : {
4854 : : /*
4855 : : * These plan types not only materialize their results, but do
4856 : : * not implement qual filtering or projection. So they are
4857 : : * even cheaper to rescan than the ones above. We charge only
4858 : : * cpu_operator_cost per tuple. (Note: keep that in sync with
4859 : : * the run_cost charge in cost_sort, and also see comments in
4860 : : * cost_material before you change it.)
4861 : : */
4862 : 111580 : Cost run_cost = cpu_operator_cost * path->rows;
4863 : 223160 : double nbytes = relation_byte_size(path->rows,
4864 : 111580 : path->pathtarget->width);
4865 : 111580 : double work_mem_bytes = work_mem * (Size) 1024;
4866 : :
4867 [ + + ]: 111580 : if (nbytes > work_mem_bytes)
4868 : : {
4869 : : /* It will spill, so account for re-read cost */
4870 : 602 : double npages = ceil(nbytes / BLCKSZ);
4871 : :
4872 : 602 : run_cost += seq_page_cost * npages;
4873 : 602 : }
4874 : 111580 : *rescan_startup_cost = 0;
4875 : 111580 : *rescan_total_cost = run_cost;
4876 : 111580 : }
4877 : 111580 : break;
4878 : : case T_Memoize:
4879 : : /* All the hard work is done by cost_memoize_rescan */
4880 : 36806 : cost_memoize_rescan(root, (MemoizePath *) path,
4881 : 18403 : rescan_startup_cost, rescan_total_cost);
4882 : 18403 : break;
4883 : : default:
4884 : 144793 : *rescan_startup_cost = path->startup_cost;
4885 : 144793 : *rescan_total_cost = path->total_cost;
4886 : 144793 : break;
4887 : : }
4888 : 284672 : }
4889 : :
4890 : :
4891 : : /*
4892 : : * cost_qual_eval
4893 : : * Estimate the CPU costs of evaluating a WHERE clause.
4894 : : * The input can be either an implicitly-ANDed list of boolean
4895 : : * expressions, or a list of RestrictInfo nodes. (The latter is
4896 : : * preferred since it allows caching of the results.)
4897 : : * The result includes both a one-time (startup) component,
4898 : : * and a per-evaluation component.
4899 : : *
4900 : : * Note: in some code paths root can be passed as NULL, resulting in
4901 : : * slightly worse estimates.
4902 : : */
4903 : : void
4904 : 464549 : cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
4905 : : {
4906 : 464549 : cost_qual_eval_context context;
4907 : 464549 : ListCell *l;
4908 : :
4909 : 464549 : context.root = root;
4910 : 464549 : context.total.startup = 0;
4911 : 464549 : context.total.per_tuple = 0;
4912 : :
4913 : : /* We don't charge any cost for the implicit ANDing at top level ... */
4914 : :
4915 [ + + + + : 876316 : foreach(l, quals)
+ + ]
4916 : : {
4917 : 411767 : Node *qual = (Node *) lfirst(l);
4918 : :
4919 : 411767 : cost_qual_eval_walker(qual, &context);
4920 : 411767 : }
4921 : :
4922 : 464549 : *cost = context.total;
4923 : 464549 : }
4924 : :
4925 : : /*
4926 : : * cost_qual_eval_node
4927 : : * As above, for a single RestrictInfo or expression.
4928 : : */
4929 : : void
4930 : 181587 : cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
4931 : : {
4932 : 181587 : cost_qual_eval_context context;
4933 : :
4934 : 181587 : context.root = root;
4935 : 181587 : context.total.startup = 0;
4936 : 181587 : context.total.per_tuple = 0;
4937 : :
4938 : 181587 : cost_qual_eval_walker(qual, &context);
4939 : :
4940 : 181587 : *cost = context.total;
4941 : 181587 : }
4942 : :
4943 : : static bool
4944 : 950352 : cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
4945 : : {
4946 [ + + ]: 950352 : if (node == NULL)
4947 : 11425 : return false;
4948 : :
4949 : : /*
4950 : : * RestrictInfo nodes contain an eval_cost field reserved for this
4951 : : * routine's use, so that it's not necessary to evaluate the qual clause's
4952 : : * cost more than once. If the clause's cost hasn't been computed yet,
4953 : : * the field's startup value will contain -1.
4954 : : */
4955 [ + + ]: 938927 : if (IsA(node, RestrictInfo))
4956 : : {
4957 : 429807 : RestrictInfo *rinfo = (RestrictInfo *) node;
4958 : :
4959 [ + + ]: 429807 : if (rinfo->eval_cost.startup < 0)
4960 : : {
4961 : 57130 : cost_qual_eval_context locContext;
4962 : :
4963 : 57130 : locContext.root = context->root;
4964 : 57130 : locContext.total.startup = 0;
4965 : 57130 : locContext.total.per_tuple = 0;
4966 : :
4967 : : /*
4968 : : * For an OR clause, recurse into the marked-up tree so that we
4969 : : * set the eval_cost for contained RestrictInfos too.
4970 : : */
4971 [ + + ]: 57130 : if (rinfo->orclause)
4972 : 827 : cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4973 : : else
4974 : 56303 : cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4975 : :
4976 : : /*
4977 : : * If the RestrictInfo is marked pseudoconstant, it will be tested
4978 : : * only once, so treat its cost as all startup cost.
4979 : : */
4980 [ + + ]: 57130 : if (rinfo->pseudoconstant)
4981 : : {
4982 : : /* count one execution during startup */
4983 : 1657 : locContext.total.startup += locContext.total.per_tuple;
4984 : 1657 : locContext.total.per_tuple = 0;
4985 : 1657 : }
4986 : 57130 : rinfo->eval_cost = locContext.total;
4987 : 57130 : }
4988 : 429807 : context->total.startup += rinfo->eval_cost.startup;
4989 : 429807 : context->total.per_tuple += rinfo->eval_cost.per_tuple;
4990 : : /* do NOT recurse into children */
4991 : 429807 : return false;
4992 : 429807 : }
4993 : :
4994 : : /*
4995 : : * For each operator or function node in the given tree, we charge the
4996 : : * estimated execution cost given by pg_proc.procost (remember to multiply
4997 : : * this by cpu_operator_cost).
4998 : : *
4999 : : * Vars and Consts are charged zero, and so are boolean operators (AND,
5000 : : * OR, NOT). Simplistic, but a lot better than no model at all.
5001 : : *
5002 : : * Should we try to account for the possibility of short-circuit
5003 : : * evaluation of AND/OR? Probably *not*, because that would make the
5004 : : * results depend on the clause ordering, and we are not in any position
5005 : : * to expect that the current ordering of the clauses is the one that's
5006 : : * going to end up being used. The above per-RestrictInfo caching would
5007 : : * not mix well with trying to re-order clauses anyway.
5008 : : *
5009 : : * Another issue that is entirely ignored here is that if a set-returning
5010 : : * function is below top level in the tree, the functions/operators above
5011 : : * it will need to be evaluated multiple times. In practical use, such
5012 : : * cases arise so seldom as to not be worth the added complexity needed;
5013 : : * moreover, since our rowcount estimates for functions tend to be pretty
5014 : : * phony, the results would also be pretty phony.
5015 : : */
5016 [ + + ]: 509120 : if (IsA(node, FuncExpr))
5017 : : {
5018 : 68254 : add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
5019 : 34127 : &context->total);
5020 : 34127 : }
5021 [ + + ]: 474993 : else if (IsA(node, OpExpr) ||
5022 [ + + + + ]: 407329 : IsA(node, DistinctExpr) ||
5023 : 407293 : IsA(node, NullIfExpr))
5024 : : {
5025 : : /* rely on struct equivalence to treat these all alike */
5026 : 67720 : set_opfuncid((OpExpr *) node);
5027 : 135440 : add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
5028 : 67720 : &context->total);
5029 : 67720 : }
5030 [ + + ]: 407273 : else if (IsA(node, ScalarArrayOpExpr))
5031 : : {
5032 : 5459 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
5033 : 5459 : Node *arraynode = (Node *) lsecond(saop->args);
5034 : 5459 : QualCost sacosts;
5035 : 5459 : QualCost hcosts;
5036 : 5459 : double estarraylen = estimate_array_length(context->root, arraynode);
5037 : :
5038 : 5459 : set_sa_opfuncid(saop);
5039 : 5459 : sacosts.startup = sacosts.per_tuple = 0;
5040 : 5459 : add_function_cost(context->root, saop->opfuncid, NULL,
5041 : : &sacosts);
5042 : :
5043 [ + + ]: 5459 : if (OidIsValid(saop->hashfuncid))
5044 : : {
5045 : : /* Handle costs for hashed ScalarArrayOpExpr */
5046 : 21 : hcosts.startup = hcosts.per_tuple = 0;
5047 : :
5048 : 21 : add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
5049 : 21 : context->total.startup += sacosts.startup + hcosts.startup;
5050 : :
5051 : : /* Estimate the cost of building the hashtable. */
5052 : 21 : context->total.startup += estarraylen * hcosts.per_tuple;
5053 : :
5054 : : /*
5055 : : * XXX should we charge a little bit for sacosts.per_tuple when
5056 : : * building the table, or is it ok to assume there will be zero
5057 : : * hash collision?
5058 : : */
5059 : :
5060 : : /*
5061 : : * Charge for hashtable lookups. Charge a single hash and a
5062 : : * single comparison.
5063 : : */
5064 : 21 : context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
5065 : 21 : }
5066 : : else
5067 : : {
5068 : : /*
5069 : : * Estimate that the operator will be applied to about half of the
5070 : : * array elements before the answer is determined.
5071 : : */
5072 : 5438 : context->total.startup += sacosts.startup;
5073 : 10876 : context->total.per_tuple += sacosts.per_tuple *
5074 : 5438 : estimate_array_length(context->root, arraynode) * 0.5;
5075 : : }
5076 : 5459 : }
5077 [ + + + + ]: 401814 : else if (IsA(node, Aggref) ||
5078 : 393031 : IsA(node, WindowFunc))
5079 : : {
5080 : : /*
5081 : : * Aggref and WindowFunc nodes are (and should be) treated like Vars,
5082 : : * ie, zero execution cost in the current model, because they behave
5083 : : * essentially like Vars at execution. We disregard the costs of
5084 : : * their input expressions for the same reason. The actual execution
5085 : : * costs of the aggregate/window functions and their arguments have to
5086 : : * be factored into plan-node-specific costing of the Agg or WindowAgg
5087 : : * plan node.
5088 : : */
5089 : 9424 : return false; /* don't recurse into children */
5090 : : }
5091 [ + + ]: 392390 : else if (IsA(node, GroupingFunc))
5092 : : {
5093 : : /* Treat this as having cost 1 */
5094 : 69 : context->total.per_tuple += cpu_operator_cost;
5095 : 69 : return false; /* don't recurse into children */
5096 : : }
5097 [ + + ]: 392321 : else if (IsA(node, CoerceViaIO))
5098 : : {
5099 : 2915 : CoerceViaIO *iocoerce = (CoerceViaIO *) node;
5100 : 2915 : Oid iofunc;
5101 : 2915 : Oid typioparam;
5102 : 2915 : bool typisvarlena;
5103 : :
5104 : : /* check the result type's input function */
5105 : 2915 : getTypeInputInfo(iocoerce->resulttype,
5106 : : &iofunc, &typioparam);
5107 : 5830 : add_function_cost(context->root, iofunc, NULL,
5108 : 2915 : &context->total);
5109 : : /* check the input type's output function */
5110 : 2915 : getTypeOutputInfo(exprType((Node *) iocoerce->arg),
5111 : : &iofunc, &typisvarlena);
5112 : 5830 : add_function_cost(context->root, iofunc, NULL,
5113 : 2915 : &context->total);
5114 : 2915 : }
5115 [ + + ]: 389406 : else if (IsA(node, ArrayCoerceExpr))
5116 : : {
5117 : 608 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
5118 : 608 : QualCost perelemcost;
5119 : :
5120 : 1216 : cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
5121 : 608 : context->root);
5122 : 608 : context->total.startup += perelemcost.startup;
5123 [ + + ]: 608 : if (perelemcost.per_tuple > 0)
5124 : 10 : context->total.per_tuple += perelemcost.per_tuple *
5125 : 5 : estimate_array_length(context->root, (Node *) acoerce->arg);
5126 : 608 : }
5127 [ + + ]: 388798 : else if (IsA(node, RowCompareExpr))
5128 : : {
5129 : : /* Conservatively assume we will check all the columns */
5130 : 42 : RowCompareExpr *rcexpr = (RowCompareExpr *) node;
5131 : 42 : ListCell *lc;
5132 : :
5133 [ + - + + : 135 : foreach(lc, rcexpr->opnos)
+ + ]
5134 : : {
5135 : 93 : Oid opid = lfirst_oid(lc);
5136 : :
5137 : 186 : add_function_cost(context->root, get_opcode(opid), NULL,
5138 : 93 : &context->total);
5139 : 93 : }
5140 : 42 : }
5141 [ + + ]: 388756 : else if (IsA(node, MinMaxExpr) ||
5142 [ + + ]: 388714 : IsA(node, SQLValueFunction) ||
5143 [ + + ]: 388157 : IsA(node, XmlExpr) ||
5144 [ + + ]: 388040 : IsA(node, CoerceToDomain) ||
5145 [ + + + + ]: 387495 : IsA(node, NextValueExpr) ||
5146 : 387430 : IsA(node, JsonExpr))
5147 : : {
5148 : : /* Treat all these as having cost 1 */
5149 : 1752 : context->total.per_tuple += cpu_operator_cost;
5150 : 1752 : }
5151 [ + - ]: 387004 : else if (IsA(node, SubLink))
5152 : : {
5153 : : /* This routine should not be applied to un-planned expressions */
5154 [ # # # # ]: 0 : elog(ERROR, "cannot handle unplanned sub-select");
5155 : 0 : }
5156 [ + + ]: 387004 : else if (IsA(node, SubPlan))
5157 : : {
5158 : : /*
5159 : : * A subplan node in an expression typically indicates that the
5160 : : * subplan will be executed on each evaluation, so charge accordingly.
5161 : : * (Sub-selects that can be executed as InitPlans have already been
5162 : : * removed from the expression.)
5163 : : */
5164 : 5118 : SubPlan *subplan = (SubPlan *) node;
5165 : :
5166 : 5118 : context->total.startup += subplan->startup_cost;
5167 : 5118 : context->total.per_tuple += subplan->per_call_cost;
5168 : :
5169 : : /*
5170 : : * We don't want to recurse into the testexpr, because it was already
5171 : : * counted in the SubPlan node's costs. So we're done.
5172 : : */
5173 : 5118 : return false;
5174 : 5118 : }
5175 [ + + ]: 381886 : else if (IsA(node, AlternativeSubPlan))
5176 : : {
5177 : : /*
5178 : : * Arbitrarily use the first alternative plan for costing. (We should
5179 : : * certainly only include one alternative, and we don't yet have
5180 : : * enough information to know which one the executor is most likely to
5181 : : * use.)
5182 : : */
5183 : 221 : AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
5184 : :
5185 : 442 : return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
5186 : 221 : context);
5187 : 221 : }
5188 [ + + ]: 381665 : else if (IsA(node, PlaceHolderVar))
5189 : : {
5190 : : /*
5191 : : * A PlaceHolderVar should be given cost zero when considering general
5192 : : * expression evaluation costs. The expense of doing the contained
5193 : : * expression is charged as part of the tlist eval costs of the scan
5194 : : * or join where the PHV is first computed (see set_rel_width and
5195 : : * add_placeholders_to_joinrel). If we charged it again here, we'd be
5196 : : * double-counting the cost for each level of plan that the PHV
5197 : : * bubbles up through. Hence, return without recursing into the
5198 : : * phexpr.
5199 : : */
5200 : 876 : return false;
5201 : : }
5202 : :
5203 : : /* recurse into children */
5204 : 493412 : return expression_tree_walker(node, cost_qual_eval_walker, context);
5205 : 950352 : }
5206 : :
5207 : : /*
5208 : : * get_restriction_qual_cost
5209 : : * Compute evaluation costs of a baserel's restriction quals, plus any
5210 : : * movable join quals that have been pushed down to the scan.
5211 : : * Results are returned into *qpqual_cost.
5212 : : *
5213 : : * This is a convenience subroutine that works for seqscans and other cases
5214 : : * where all the given quals will be evaluated the hard way. It's not useful
5215 : : * for cost_index(), for example, where the index machinery takes care of
5216 : : * some of the quals. We assume baserestrictcost was previously set by
5217 : : * set_baserel_size_estimates().
5218 : : */
5219 : : static void
5220 : 107816 : get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
5221 : : ParamPathInfo *param_info,
5222 : : QualCost *qpqual_cost)
5223 : : {
5224 [ + + ]: 107816 : if (param_info)
5225 : : {
5226 : : /* Include costs of pushed-down clauses */
5227 : 23841 : cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
5228 : :
5229 : 23841 : qpqual_cost->startup += baserel->baserestrictcost.startup;
5230 : 23841 : qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
5231 : 23841 : }
5232 : : else
5233 : 83975 : *qpqual_cost = baserel->baserestrictcost;
5234 : 107816 : }
5235 : :
5236 : :
5237 : : /*
5238 : : * compute_semi_anti_join_factors
5239 : : * Estimate how much of the inner input a SEMI, ANTI, or inner_unique join
5240 : : * can be expected to scan.
5241 : : *
5242 : : * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
5243 : : * inner rows as soon as it finds a match to the current outer row.
5244 : : * The same happens if we have detected the inner rel is unique.
5245 : : * We should therefore adjust some of the cost components for this effect.
5246 : : * This function computes some estimates needed for these adjustments.
5247 : : * These estimates will be the same regardless of the particular paths used
5248 : : * for the outer and inner relation, so we compute these once and then pass
5249 : : * them to all the join cost estimation functions.
5250 : : *
5251 : : * Input parameters:
5252 : : * joinrel: join relation under consideration
5253 : : * outerrel: outer relation under consideration
5254 : : * innerrel: inner relation under consideration
5255 : : * jointype: if not JOIN_SEMI or JOIN_ANTI, we assume it's inner_unique
5256 : : * sjinfo: SpecialJoinInfo relevant to this join
5257 : : * restrictlist: join quals
5258 : : * Output parameters:
5259 : : * *semifactors is filled in (see pathnodes.h for field definitions)
5260 : : */
5261 : : void
5262 : 18559 : compute_semi_anti_join_factors(PlannerInfo *root,
5263 : : RelOptInfo *joinrel,
5264 : : RelOptInfo *outerrel,
5265 : : RelOptInfo *innerrel,
5266 : : JoinType jointype,
5267 : : SpecialJoinInfo *sjinfo,
5268 : : List *restrictlist,
5269 : : SemiAntiJoinFactors *semifactors)
5270 : : {
5271 : 18559 : Selectivity jselec;
5272 : 18559 : Selectivity nselec;
5273 : 18559 : Selectivity avgmatch;
5274 : 18559 : SpecialJoinInfo norm_sjinfo;
5275 : 18559 : List *joinquals;
5276 : 18559 : ListCell *l;
5277 : :
5278 : : /*
5279 : : * In an ANTI join, we must ignore clauses that are "pushed down", since
5280 : : * those won't affect the match logic. In a SEMI join, we do not
5281 : : * distinguish joinquals from "pushed down" quals, so just use the whole
5282 : : * restrictinfo list. For other outer join types, we should consider only
5283 : : * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5284 : : */
5285 [ + + ]: 18559 : if (IS_OUTER_JOIN(jointype))
5286 : : {
5287 : 5160 : joinquals = NIL;
5288 [ + + + + : 10867 : foreach(l, restrictlist)
+ + ]
5289 : : {
5290 : 5707 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5291 : :
5292 [ + + - + ]: 5707 : if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5293 : 5630 : joinquals = lappend(joinquals, rinfo);
5294 : 5707 : }
5295 : 5160 : }
5296 : : else
5297 : 13399 : joinquals = restrictlist;
5298 : :
5299 : : /*
5300 : : * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5301 : : */
5302 : 37118 : jselec = clauselist_selectivity(root,
5303 : 18559 : joinquals,
5304 : : 0,
5305 : 18559 : (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5306 : 18559 : sjinfo);
5307 : :
5308 : : /*
5309 : : * Also get the normal inner-join selectivity of the join clauses.
5310 : : */
5311 : 18559 : init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
5312 : :
5313 : 37118 : nselec = clauselist_selectivity(root,
5314 : 18559 : joinquals,
5315 : : 0,
5316 : : JOIN_INNER,
5317 : : &norm_sjinfo);
5318 : :
5319 : : /* Avoid leaking a lot of ListCells */
5320 [ + + ]: 18559 : if (IS_OUTER_JOIN(jointype))
5321 : 5160 : list_free(joinquals);
5322 : :
5323 : : /*
5324 : : * jselec can be interpreted as the fraction of outer-rel rows that have
5325 : : * any matches (this is true for both SEMI and ANTI cases). And nselec is
5326 : : * the fraction of the Cartesian product that matches. So, the average
5327 : : * number of matches for each outer-rel row that has at least one match is
5328 : : * nselec * inner_rows / jselec.
5329 : : *
5330 : : * Note: it is correct to use the inner rel's "rows" count here, even
5331 : : * though we might later be considering a parameterized inner path with
5332 : : * fewer rows. This is because we have included all the join clauses in
5333 : : * the selectivity estimate.
5334 : : */
5335 [ + - ]: 18559 : if (jselec > 0) /* protect against zero divide */
5336 : : {
5337 : 18559 : avgmatch = nselec * innerrel->rows / jselec;
5338 : : /* Clamp to sane range */
5339 [ + + ]: 18559 : avgmatch = Max(1.0, avgmatch);
5340 : 18559 : }
5341 : : else
5342 : 0 : avgmatch = 1.0;
5343 : :
5344 : 18559 : semifactors->outer_match_frac = jselec;
5345 : 18559 : semifactors->match_count = avgmatch;
5346 : 18559 : }
5347 : :
5348 : : /*
5349 : : * has_indexed_join_quals
5350 : : * Check whether all the joinquals of a nestloop join are used as
5351 : : * inner index quals.
5352 : : *
5353 : : * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
5354 : : * indexscan) that uses all the joinquals as indexquals, we can assume that an
5355 : : * unmatched outer tuple is cheap to process, whereas otherwise it's probably
5356 : : * expensive.
5357 : : */
5358 : : static bool
5359 : 69247 : has_indexed_join_quals(NestPath *path)
5360 : : {
5361 : 69247 : JoinPath *joinpath = &path->jpath;
5362 : 69247 : Relids joinrelids = joinpath->path.parent->relids;
5363 : 69247 : Path *innerpath = joinpath->innerjoinpath;
5364 : 69247 : List *indexclauses;
5365 : 69247 : bool found_one;
5366 : 69247 : ListCell *lc;
5367 : :
5368 : : /* If join still has quals to evaluate, it's not fast */
5369 [ + + ]: 69247 : if (joinpath->joinrestrictinfo != NIL)
5370 : 49997 : return false;
5371 : : /* Nor if the inner path isn't parameterized at all */
5372 [ + + ]: 19250 : if (innerpath->param_info == NULL)
5373 : 550 : return false;
5374 : :
5375 : : /* Find the indexclauses list for the inner scan */
5376 [ + + + ]: 18700 : switch (innerpath->pathtype)
5377 : : {
5378 : : case T_IndexScan:
5379 : : case T_IndexOnlyScan:
5380 : 13227 : indexclauses = ((IndexPath *) innerpath)->indexclauses;
5381 : 13227 : break;
5382 : : case T_BitmapHeapScan:
5383 : : {
5384 : : /* Accept only a simple bitmap scan, not AND/OR cases */
5385 : 45 : Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
5386 : :
5387 [ + + ]: 45 : if (IsA(bmqual, IndexPath))
5388 : 37 : indexclauses = ((IndexPath *) bmqual)->indexclauses;
5389 : : else
5390 : 8 : return false;
5391 : 37 : break;
5392 [ + + ]: 45 : }
5393 : : default:
5394 : :
5395 : : /*
5396 : : * If it's not a simple indexscan, it probably doesn't run quickly
5397 : : * for zero rows out, even if it's a parameterized path using all
5398 : : * the joinquals.
5399 : : */
5400 : 5428 : return false;
5401 : : }
5402 : :
5403 : : /*
5404 : : * Examine the inner path's param clauses. Any that are from the outer
5405 : : * path must be found in the indexclauses list, either exactly or in an
5406 : : * equivalent form generated by equivclass.c. Also, we must find at least
5407 : : * one such clause, else it's a clauseless join which isn't fast.
5408 : : */
5409 : 13264 : found_one = false;
5410 [ + - + + : 26960 : foreach(lc, innerpath->param_info->ppi_clauses)
+ + + + ]
5411 : : {
5412 : 13696 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
5413 : :
5414 [ + + + + ]: 27392 : if (join_clause_is_movable_into(rinfo,
5415 : 13696 : innerpath->parent->relids,
5416 : 13696 : joinrelids))
5417 : : {
5418 [ + + ]: 13604 : if (!is_redundant_with_indexclauses(rinfo, indexclauses))
5419 : 281 : return false;
5420 : 13323 : found_one = true;
5421 : 13323 : }
5422 [ + + ]: 13696 : }
5423 : 12983 : return found_one;
5424 : 69247 : }
5425 : :
5426 : :
5427 : : /*
5428 : : * approx_tuple_count
5429 : : * Quick-and-dirty estimation of the number of join rows passing
5430 : : * a set of qual conditions.
5431 : : *
5432 : : * The quals can be either an implicitly-ANDed list of boolean expressions,
5433 : : * or a list of RestrictInfo nodes (typically the latter).
5434 : : *
5435 : : * We intentionally compute the selectivity under JOIN_INNER rules, even
5436 : : * if it's some type of outer join. This is appropriate because we are
5437 : : * trying to figure out how many tuples pass the initial merge or hash
5438 : : * join step.
5439 : : *
5440 : : * This is quick-and-dirty because we bypass clauselist_selectivity, and
5441 : : * simply multiply the independent clause selectivities together. Now
5442 : : * clauselist_selectivity often can't do any better than that anyhow, but
5443 : : * for some situations (such as range constraints) it is smarter. However,
5444 : : * we can't effectively cache the results of clauselist_selectivity, whereas
5445 : : * the individual clause selectivities can be and are cached.
5446 : : *
5447 : : * Since we are only using the results to estimate how many potential
5448 : : * output tuples are generated and passed through qpqual checking, it
5449 : : * seems OK to live with the approximation.
5450 : : */
5451 : : static double
5452 : 91240 : approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
5453 : : {
5454 : 91240 : double tuples;
5455 : 91240 : double outer_tuples = path->outerjoinpath->rows;
5456 : 91240 : double inner_tuples = path->innerjoinpath->rows;
5457 : 91240 : SpecialJoinInfo sjinfo;
5458 : 91240 : Selectivity selec = 1.0;
5459 : 91240 : ListCell *l;
5460 : :
5461 : : /*
5462 : : * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5463 : : */
5464 : 182480 : init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
5465 : 91240 : path->innerjoinpath->parent->relids);
5466 : :
5467 : : /* Get the approximate selectivity */
5468 [ + + + + : 188903 : foreach(l, quals)
+ + ]
5469 : : {
5470 : 97663 : Node *qual = (Node *) lfirst(l);
5471 : :
5472 : : /* Note that clause_selectivity will be able to cache its result */
5473 : 97663 : selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5474 : 97663 : }
5475 : :
5476 : : /* Apply it to the input relation sizes */
5477 : 91240 : tuples = selec * outer_tuples * inner_tuples;
5478 : :
5479 : 182480 : return clamp_row_est(tuples);
5480 : 91240 : }
5481 : :
5482 : :
5483 : : /*
5484 : : * set_baserel_size_estimates
5485 : : * Set the size estimates for the given base relation.
5486 : : *
5487 : : * The rel's targetlist and restrictinfo list must have been constructed
5488 : : * already, and rel->tuples must be set.
5489 : : *
5490 : : * We set the following fields of the rel node:
5491 : : * rows: the estimated number of output tuples (after applying
5492 : : * restriction clauses).
5493 : : * width: the estimated average output tuple width in bytes.
5494 : : * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
5495 : : */
5496 : : void
5497 : 52740 : set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
5498 : : {
5499 : 52740 : double nrows;
5500 : :
5501 : : /* Should only be applied to base relations */
5502 [ + - ]: 52740 : Assert(rel->relid > 0);
5503 : :
5504 : 105480 : nrows = rel->tuples *
5505 : 105480 : clauselist_selectivity(root,
5506 : 52740 : rel->baserestrictinfo,
5507 : : 0,
5508 : : JOIN_INNER,
5509 : : NULL);
5510 : :
5511 : 52740 : rel->rows = clamp_row_est(nrows);
5512 : :
5513 : 52740 : cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
5514 : :
5515 : 52740 : set_rel_width(root, rel);
5516 : 52740 : }
5517 : :
5518 : : /*
5519 : : * get_parameterized_baserel_size
5520 : : * Make a size estimate for a parameterized scan of a base relation.
5521 : : *
5522 : : * 'param_clauses' lists the additional join clauses to be used.
5523 : : *
5524 : : * set_baserel_size_estimates must have been applied already.
5525 : : */
5526 : : double
5527 : 14689 : get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel,
5528 : : List *param_clauses)
5529 : : {
5530 : 14689 : List *allclauses;
5531 : 14689 : double nrows;
5532 : :
5533 : : /*
5534 : : * Estimate the number of rows returned by the parameterized scan, knowing
5535 : : * that it will apply all the extra join clauses as well as the rel's own
5536 : : * restriction clauses. Note that we force the clauses to be treated as
5537 : : * non-join clauses during selectivity estimation.
5538 : : */
5539 : 14689 : allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5540 : 29378 : nrows = rel->tuples *
5541 : 29378 : clauselist_selectivity(root,
5542 : 14689 : allclauses,
5543 : 14689 : rel->relid, /* do not use 0! */
5544 : : JOIN_INNER,
5545 : : NULL);
5546 : 14689 : nrows = clamp_row_est(nrows);
5547 : : /* For safety, make sure result is not more than the base estimate */
5548 [ + - ]: 14689 : if (nrows > rel->rows)
5549 : 0 : nrows = rel->rows;
5550 : 29378 : return nrows;
5551 : 14689 : }
5552 : :
5553 : : /*
5554 : : * set_joinrel_size_estimates
5555 : : * Set the size estimates for the given join relation.
5556 : : *
5557 : : * The rel's targetlist must have been constructed already, and a
5558 : : * restriction clause list that matches the given component rels must
5559 : : * be provided.
5560 : : *
5561 : : * Since there is more than one way to make a joinrel for more than two
5562 : : * base relations, the results we get here could depend on which component
5563 : : * rel pair is provided. In theory we should get the same answers no matter
5564 : : * which pair is provided; in practice, since the selectivity estimation
5565 : : * routines don't handle all cases equally well, we might not. But there's
5566 : : * not much to be done about it. (Would it make sense to repeat the
5567 : : * calculations for each pair of input rels that's encountered, and somehow
5568 : : * average the results? Probably way more trouble than it's worth, and
5569 : : * anyway we must keep the rowcount estimate the same for all paths for the
5570 : : * joinrel.)
5571 : : *
5572 : : * We set only the rows field here. The reltarget field was already set by
5573 : : * build_joinrel_tlist, and baserestrictcost is not used for join rels.
5574 : : */
5575 : : void
5576 : 24661 : set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
5577 : : RelOptInfo *outer_rel,
5578 : : RelOptInfo *inner_rel,
5579 : : SpecialJoinInfo *sjinfo,
5580 : : List *restrictlist)
5581 : : {
5582 : 49322 : rel->rows = calc_joinrel_size_estimate(root,
5583 : 24661 : rel,
5584 : 24661 : outer_rel,
5585 : 24661 : inner_rel,
5586 : 24661 : outer_rel->rows,
5587 : 24661 : inner_rel->rows,
5588 : 24661 : sjinfo,
5589 : 24661 : restrictlist);
5590 : 24661 : }
5591 : :
5592 : : /*
5593 : : * get_parameterized_joinrel_size
5594 : : * Make a size estimate for a parameterized scan of a join relation.
5595 : : *
5596 : : * 'rel' is the joinrel under consideration.
5597 : : * 'outer_path', 'inner_path' are (probably also parameterized) Paths that
5598 : : * produce the relations being joined.
5599 : : * 'sjinfo' is any SpecialJoinInfo relevant to this join.
5600 : : * 'restrict_clauses' lists the join clauses that need to be applied at the
5601 : : * join node (including any movable clauses that were moved down to this join,
5602 : : * and not including any movable clauses that were pushed down into the
5603 : : * child paths).
5604 : : *
5605 : : * set_joinrel_size_estimates must have been applied already.
5606 : : */
5607 : : double
5608 : 488 : get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel,
5609 : : Path *outer_path,
5610 : : Path *inner_path,
5611 : : SpecialJoinInfo *sjinfo,
5612 : : List *restrict_clauses)
5613 : : {
5614 : 488 : double nrows;
5615 : :
5616 : : /*
5617 : : * Estimate the number of rows returned by the parameterized join as the
5618 : : * sizes of the input paths times the selectivity of the clauses that have
5619 : : * ended up at this join node.
5620 : : *
5621 : : * As with set_joinrel_size_estimates, the rowcount estimate could depend
5622 : : * on the pair of input paths provided, though ideally we'd get the same
5623 : : * estimate for any pair with the same parameterization.
5624 : : */
5625 : 976 : nrows = calc_joinrel_size_estimate(root,
5626 : 488 : rel,
5627 : 488 : outer_path->parent,
5628 : 488 : inner_path->parent,
5629 : 488 : outer_path->rows,
5630 : 488 : inner_path->rows,
5631 : 488 : sjinfo,
5632 : 488 : restrict_clauses);
5633 : : /* For safety, make sure result is not more than the base estimate */
5634 [ + + ]: 488 : if (nrows > rel->rows)
5635 : 2 : nrows = rel->rows;
5636 : 976 : return nrows;
5637 : 488 : }
5638 : :
5639 : : /*
5640 : : * calc_joinrel_size_estimate
5641 : : * Workhorse for set_joinrel_size_estimates and
5642 : : * get_parameterized_joinrel_size.
5643 : : *
5644 : : * outer_rel/inner_rel are the relations being joined, but they should be
5645 : : * assumed to have sizes outer_rows/inner_rows; those numbers might be less
5646 : : * than what rel->rows says, when we are considering parameterized paths.
5647 : : */
5648 : : static double
5649 : 25149 : calc_joinrel_size_estimate(PlannerInfo *root,
5650 : : RelOptInfo *joinrel,
5651 : : RelOptInfo *outer_rel,
5652 : : RelOptInfo *inner_rel,
5653 : : double outer_rows,
5654 : : double inner_rows,
5655 : : SpecialJoinInfo *sjinfo,
5656 : : List *restrictlist)
5657 : : {
5658 : 25149 : JoinType jointype = sjinfo->jointype;
5659 : 25149 : Selectivity fkselec;
5660 : 25149 : Selectivity jselec;
5661 : 25149 : Selectivity pselec;
5662 : 25149 : double nrows;
5663 : :
5664 : : /*
5665 : : * Compute joinclause selectivity. Note that we are only considering
5666 : : * clauses that become restriction clauses at this join level; we are not
5667 : : * double-counting them because they were not considered in estimating the
5668 : : * sizes of the component rels.
5669 : : *
5670 : : * First, see whether any of the joinclauses can be matched to known FK
5671 : : * constraints. If so, drop those clauses from the restrictlist, and
5672 : : * instead estimate their selectivity using FK semantics. (We do this
5673 : : * without regard to whether said clauses are local or "pushed down".
5674 : : * Probably, an FK-matching clause could never be seen as pushed down at
5675 : : * an outer join, since it would be strict and hence would be grounds for
5676 : : * join strength reduction.) fkselec gets the net selectivity for
5677 : : * FK-matching clauses, or 1.0 if there are none.
5678 : : */
5679 : 50298 : fkselec = get_foreign_key_join_selectivity(root,
5680 : 25149 : outer_rel->relids,
5681 : 25149 : inner_rel->relids,
5682 : 25149 : sjinfo,
5683 : : &restrictlist);
5684 : :
5685 : : /*
5686 : : * For an outer join, we have to distinguish the selectivity of the join's
5687 : : * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5688 : : * down". For inner joins we just count them all as joinclauses.
5689 : : */
5690 [ + + ]: 25149 : if (IS_OUTER_JOIN(jointype))
5691 : : {
5692 : 5288 : List *joinquals = NIL;
5693 : 5288 : List *pushedquals = NIL;
5694 : 5288 : ListCell *l;
5695 : :
5696 : : /* Grovel through the clauses to separate into two lists */
5697 [ + + + + : 11761 : foreach(l, restrictlist)
+ + ]
5698 : : {
5699 : 6473 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5700 : :
5701 [ + + + + ]: 6473 : if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5702 : 283 : pushedquals = lappend(pushedquals, rinfo);
5703 : : else
5704 : 6190 : joinquals = lappend(joinquals, rinfo);
5705 : 6473 : }
5706 : :
5707 : : /* Get the separate selectivities */
5708 : 10576 : jselec = clauselist_selectivity(root,
5709 : 5288 : joinquals,
5710 : : 0,
5711 : 5288 : jointype,
5712 : 5288 : sjinfo);
5713 : 10576 : pselec = clauselist_selectivity(root,
5714 : 5288 : pushedquals,
5715 : : 0,
5716 : 5288 : jointype,
5717 : 5288 : sjinfo);
5718 : :
5719 : : /* Avoid leaking a lot of ListCells */
5720 : 5288 : list_free(joinquals);
5721 : 5288 : list_free(pushedquals);
5722 : 5288 : }
5723 : : else
5724 : : {
5725 : 39722 : jselec = clauselist_selectivity(root,
5726 : 19861 : restrictlist,
5727 : : 0,
5728 : 19861 : jointype,
5729 : 19861 : sjinfo);
5730 : 19861 : pselec = 0.0; /* not used, keep compiler quiet */
5731 : : }
5732 : :
5733 : : /*
5734 : : * Basically, we multiply size of Cartesian product by selectivity.
5735 : : *
5736 : : * If we are doing an outer join, take that into account: the joinqual
5737 : : * selectivity has to be clamped using the knowledge that the output must
5738 : : * be at least as large as the non-nullable input. However, any
5739 : : * pushed-down quals are applied after the outer join, so their
5740 : : * selectivity applies fully.
5741 : : *
5742 : : * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5743 : : * of LHS rows that have matches, and we apply that straightforwardly.
5744 : : */
5745 [ + + + + : 25149 : switch (jointype)
+ - ]
5746 : : {
5747 : : case JOIN_INNER:
5748 : 18758 : nrows = outer_rows * inner_rows * fkselec * jselec;
5749 : : /* pselec not used */
5750 : 18758 : break;
5751 : : case JOIN_LEFT:
5752 : 4549 : nrows = outer_rows * inner_rows * fkselec * jselec;
5753 [ + + ]: 4549 : if (nrows < outer_rows)
5754 : 1344 : nrows = outer_rows;
5755 : 4549 : nrows *= pselec;
5756 : 4549 : break;
5757 : : case JOIN_FULL:
5758 : 254 : nrows = outer_rows * inner_rows * fkselec * jselec;
5759 [ + + ]: 254 : if (nrows < outer_rows)
5760 : 170 : nrows = outer_rows;
5761 [ + + ]: 254 : if (nrows < inner_rows)
5762 : 15 : nrows = inner_rows;
5763 : 254 : nrows *= pselec;
5764 : 254 : break;
5765 : : case JOIN_SEMI:
5766 : 1103 : nrows = outer_rows * fkselec * jselec;
5767 : : /* pselec not used */
5768 : 1103 : break;
5769 : : case JOIN_ANTI:
5770 : 485 : nrows = outer_rows * (1.0 - fkselec * jselec);
5771 : 485 : nrows *= pselec;
5772 : 485 : break;
5773 : : default:
5774 : : /* other values not expected here */
5775 [ # # # # ]: 0 : elog(ERROR, "unrecognized join type: %d", (int) jointype);
5776 : 0 : nrows = 0; /* keep compiler quiet */
5777 : 0 : break;
5778 : : }
5779 : :
5780 : 50298 : return clamp_row_est(nrows);
5781 : 25149 : }
5782 : :
5783 : : /*
5784 : : * get_foreign_key_join_selectivity
5785 : : * Estimate join selectivity for foreign-key-related clauses.
5786 : : *
5787 : : * Remove any clauses that can be matched to FK constraints from *restrictlist,
5788 : : * and return a substitute estimate of their selectivity. 1.0 is returned
5789 : : * when there are no such clauses.
5790 : : *
5791 : : * The reason for treating such clauses specially is that we can get better
5792 : : * estimates this way than by relying on clauselist_selectivity(), especially
5793 : : * for multi-column FKs where that function's assumption that the clauses are
5794 : : * independent falls down badly. But even with single-column FKs, we may be
5795 : : * able to get a better answer when the pg_statistic stats are missing or out
5796 : : * of date.
5797 : : */
5798 : : static Selectivity
5799 : 25111 : get_foreign_key_join_selectivity(PlannerInfo *root,
5800 : : Relids outer_relids,
5801 : : Relids inner_relids,
5802 : : SpecialJoinInfo *sjinfo,
5803 : : List **restrictlist)
5804 : : {
5805 : 25111 : Selectivity fkselec = 1.0;
5806 : 25111 : JoinType jointype = sjinfo->jointype;
5807 : 25111 : List *worklist = *restrictlist;
5808 : 25111 : ListCell *lc;
5809 : :
5810 : : /* Consider each FK constraint that is known to match the query */
5811 [ + + + + : 25479 : foreach(lc, root->fkey_list)
+ + ]
5812 : : {
5813 : 330 : ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
5814 : 330 : bool ref_is_outer;
5815 : 330 : List *removedlist;
5816 : 330 : ListCell *cell;
5817 : :
5818 : : /*
5819 : : * This FK is not relevant unless it connects a baserel on one side of
5820 : : * this join to a baserel on the other side.
5821 : : */
5822 [ + + + + ]: 330 : if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5823 : 293 : bms_is_member(fkinfo->ref_relid, inner_relids))
5824 : 464 : ref_is_outer = false;
5825 [ + + + + ]: 208 : else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5826 : 73 : bms_is_member(fkinfo->con_relid, inner_relids))
5827 : 18 : ref_is_outer = true;
5828 : : else
5829 : 116 : continue;
5830 : :
5831 : : /*
5832 : : * If we're dealing with a semi/anti join, and the FK's referenced
5833 : : * relation is on the outside, then knowledge of the FK doesn't help
5834 : : * us figure out what we need to know (which is the fraction of outer
5835 : : * rows that have matches). On the other hand, if the referenced rel
5836 : : * is on the inside, then all outer rows must have matches in the
5837 : : * referenced table (ignoring nulls). But any restriction or join
5838 : : * clauses that filter that table will reduce the fraction of matches.
5839 : : * We can account for restriction clauses, but it's too hard to guess
5840 : : * how many table rows would get through a join that's inside the RHS.
5841 : : * Hence, if either case applies, punt and ignore the FK.
5842 : : */
5843 [ + + + + ]: 599 : if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
5844 [ + + ]: 232 : (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
5845 : 232 : continue;
5846 : :
5847 : : /*
5848 : : * Modify the restrictlist by removing clauses that match the FK (and
5849 : : * putting them into removedlist instead). It seems unsafe to modify
5850 : : * the originally-passed List structure, so we make a shallow copy the
5851 : : * first time through.
5852 : : */
5853 [ + + ]: 250 : if (worklist == *restrictlist)
5854 : 215 : worklist = list_copy(worklist);
5855 : :
5856 : 250 : removedlist = NIL;
5857 [ + + + + : 529 : foreach(cell, worklist)
+ + ]
5858 : : {
5859 : 279 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5860 : 279 : bool remove_it = false;
5861 : 279 : int i;
5862 : :
5863 : : /* Drop this clause if it matches any column of the FK */
5864 [ + + ]: 349 : for (i = 0; i < fkinfo->nkeys; i++)
5865 : : {
5866 [ + + ]: 344 : if (rinfo->parent_ec)
5867 : : {
5868 : : /*
5869 : : * EC-derived clauses can only match by EC. It is okay to
5870 : : * consider any clause derived from the same EC as
5871 : : * matching the FK: even if equivclass.c chose to generate
5872 : : * a clause equating some other pair of Vars, it could
5873 : : * have generated one equating the FK's Vars. So for
5874 : : * purposes of estimation, we can act as though it did so.
5875 : : *
5876 : : * Note: checking parent_ec is a bit of a cheat because
5877 : : * there are EC-derived clauses that don't have parent_ec
5878 : : * set; but such clauses must compare expressions that
5879 : : * aren't just Vars, so they cannot match the FK anyway.
5880 : : */
5881 [ + + ]: 107 : if (fkinfo->eclass[i] == rinfo->parent_ec)
5882 : : {
5883 : 106 : remove_it = true;
5884 : 106 : break;
5885 : : }
5886 : 1 : }
5887 : : else
5888 : : {
5889 : : /*
5890 : : * Otherwise, see if rinfo was previously matched to FK as
5891 : : * a "loose" clause.
5892 : : */
5893 [ + + ]: 237 : if (list_member_ptr(fkinfo->rinfos[i], rinfo))
5894 : : {
5895 : 168 : remove_it = true;
5896 : 168 : break;
5897 : : }
5898 : : }
5899 : 70 : }
5900 [ + + ]: 279 : if (remove_it)
5901 : : {
5902 : 274 : worklist = foreach_delete_current(worklist, cell);
5903 : 274 : removedlist = lappend(removedlist, rinfo);
5904 : 274 : }
5905 : 279 : }
5906 : :
5907 : : /*
5908 : : * If we failed to remove all the matching clauses we expected to
5909 : : * find, chicken out and ignore this FK; applying its selectivity
5910 : : * might result in double-counting. Put any clauses we did manage to
5911 : : * remove back into the worklist.
5912 : : *
5913 : : * Since the matching clauses are known not outerjoin-delayed, they
5914 : : * would normally have appeared in the initial joinclause list. If we
5915 : : * didn't find them, there are two possibilities:
5916 : : *
5917 : : * 1. If the FK match is based on an EC that is ec_has_const, it won't
5918 : : * have generated any join clauses at all. We discount such ECs while
5919 : : * checking to see if we have "all" the clauses. (Below, we'll adjust
5920 : : * the selectivity estimate for this case.)
5921 : : *
5922 : : * 2. The clauses were matched to some other FK in a previous
5923 : : * iteration of this loop, and thus removed from worklist. (A likely
5924 : : * case is that two FKs are matched to the same EC; there will be only
5925 : : * one EC-derived clause in the initial list, so the first FK will
5926 : : * consume it.) Applying both FKs' selectivity independently risks
5927 : : * underestimating the join size; in particular, this would undo one
5928 : : * of the main things that ECs were invented for, namely to avoid
5929 : : * double-counting the selectivity of redundant equality conditions.
5930 : : * Later we might think of a reasonable way to combine the estimates,
5931 : : * but for now, just punt, since this is a fairly uncommon situation.
5932 : : */
5933 [ + + - + ]: 250 : if (removedlist == NIL ||
5934 : 426 : list_length(removedlist) !=
5935 : 213 : (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
5936 : : {
5937 : 37 : worklist = list_concat(worklist, removedlist);
5938 : 37 : continue;
5939 : : }
5940 : :
5941 : : /*
5942 : : * Finally we get to the payoff: estimate selectivity using the
5943 : : * knowledge that each referencing row will match exactly one row in
5944 : : * the referenced table.
5945 : : *
5946 : : * XXX that's not true in the presence of nulls in the referencing
5947 : : * column(s), so in principle we should derate the estimate for those.
5948 : : * However (1) if there are any strict restriction clauses for the
5949 : : * referencing column(s) elsewhere in the query, derating here would
5950 : : * be double-counting the null fraction, and (2) it's not very clear
5951 : : * how to combine null fractions for multiple referencing columns. So
5952 : : * we do nothing for now about correcting for nulls.
5953 : : *
5954 : : * XXX another point here is that if either side of an FK constraint
5955 : : * is an inheritance parent, we estimate as though the constraint
5956 : : * covers all its children as well. This is not an unreasonable
5957 : : * assumption for a referencing table, ie the user probably applied
5958 : : * identical constraints to all child tables (though perhaps we ought
5959 : : * to check that). But it's not possible to have done that for a
5960 : : * referenced table. Fortunately, precisely because that doesn't
5961 : : * work, it is uncommon in practice to have an FK referencing a parent
5962 : : * table. So, at least for now, disregard inheritance here.
5963 : : */
5964 [ + - + + ]: 213 : if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
5965 : : {
5966 : : /*
5967 : : * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
5968 : : * referenced table is exactly the inside of the join. The join
5969 : : * selectivity is defined as the fraction of LHS rows that have
5970 : : * matches. The FK implies that every LHS row has a match *in the
5971 : : * referenced table*; but any restriction clauses on it will
5972 : : * reduce the number of matches. Hence we take the join
5973 : : * selectivity as equal to the selectivity of the table's
5974 : : * restriction clauses, which is rows / tuples; but we must guard
5975 : : * against tuples == 0.
5976 : : */
5977 : 82 : RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5978 [ + + ]: 82 : double ref_tuples = Max(ref_rel->tuples, 1.0);
5979 : :
5980 : 82 : fkselec *= ref_rel->rows / ref_tuples;
5981 : 82 : }
5982 : : else
5983 : : {
5984 : : /*
5985 : : * Otherwise, selectivity is exactly 1/referenced-table-size; but
5986 : : * guard against tuples == 0. Note we should use the raw table
5987 : : * tuple count, not any estimate of its filtered or joined size.
5988 : : */
5989 : 131 : RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5990 [ + - ]: 131 : double ref_tuples = Max(ref_rel->tuples, 1.0);
5991 : :
5992 : 131 : fkselec *= 1.0 / ref_tuples;
5993 : 131 : }
5994 : :
5995 : : /*
5996 : : * If any of the FK columns participated in ec_has_const ECs, then
5997 : : * equivclass.c will have generated "var = const" restrictions for
5998 : : * each side of the join, thus reducing the sizes of both input
5999 : : * relations. Taking the fkselec at face value would amount to
6000 : : * double-counting the selectivity of the constant restriction for the
6001 : : * referencing Var. Hence, look for the restriction clause(s) that
6002 : : * were applied to the referencing Var(s), and divide out their
6003 : : * selectivity to correct for this.
6004 : : */
6005 [ + + ]: 213 : if (fkinfo->nconst_ec > 0)
6006 : : {
6007 [ + + ]: 4 : for (int i = 0; i < fkinfo->nkeys; i++)
6008 : : {
6009 : 3 : EquivalenceClass *ec = fkinfo->eclass[i];
6010 : :
6011 [ + - + + ]: 3 : if (ec && ec->ec_has_const)
6012 : : {
6013 : 1 : EquivalenceMember *em = fkinfo->fk_eclass_member[i];
6014 : 2 : RestrictInfo *rinfo = find_derived_clause_for_ec_member(root,
6015 : 1 : ec,
6016 : 1 : em);
6017 : :
6018 [ - + ]: 1 : if (rinfo)
6019 : : {
6020 : 1 : Selectivity s0;
6021 : :
6022 : 2 : s0 = clause_selectivity(root,
6023 : 1 : (Node *) rinfo,
6024 : : 0,
6025 : 1 : jointype,
6026 : 1 : sjinfo);
6027 [ - + ]: 1 : if (s0 > 0)
6028 : 1 : fkselec /= s0;
6029 : 1 : }
6030 : 1 : }
6031 : 3 : }
6032 : 1 : }
6033 [ - + + ]: 368 : }
6034 : :
6035 : 25149 : *restrictlist = worklist;
6036 [ - + + - ]: 50298 : CLAMP_PROBABILITY(fkselec);
6037 : 50298 : return fkselec;
6038 : 25149 : }
6039 : :
6040 : : /*
6041 : : * set_subquery_size_estimates
6042 : : * Set the size estimates for a base relation that is a subquery.
6043 : : *
6044 : : * The rel's targetlist and restrictinfo list must have been constructed
6045 : : * already, and the Paths for the subquery must have been completed.
6046 : : * We look at the subquery's PlannerInfo to extract data.
6047 : : *
6048 : : * We set the same fields as set_baserel_size_estimates.
6049 : : */
6050 : : void
6051 : 3600 : set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6052 : : {
6053 : 3600 : PlannerInfo *subroot = rel->subroot;
6054 : 3600 : RelOptInfo *sub_final_rel;
6055 : 3600 : ListCell *lc;
6056 : :
6057 : : /* Should only be applied to base relations that are subqueries */
6058 [ + - ]: 3600 : Assert(rel->relid > 0);
6059 [ + - + - ]: 3600 : Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
6060 : :
6061 : : /*
6062 : : * Copy raw number of output rows from subquery. All of its paths should
6063 : : * have the same output rowcount, so just look at cheapest-total.
6064 : : */
6065 : 3600 : sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
6066 : 3600 : rel->tuples = sub_final_rel->cheapest_total_path->rows;
6067 : :
6068 : : /*
6069 : : * Compute per-output-column width estimates by examining the subquery's
6070 : : * targetlist. For any output that is a plain Var, get the width estimate
6071 : : * that was made while planning the subquery. Otherwise, we leave it to
6072 : : * set_rel_width to fill in a datatype-based default estimate.
6073 : : */
6074 [ + + + + : 14706 : foreach(lc, subroot->parse->targetList)
+ + ]
6075 : : {
6076 : 11106 : TargetEntry *te = lfirst_node(TargetEntry, lc);
6077 : 11106 : Node *texpr = (Node *) te->expr;
6078 : 11106 : int32 item_width = 0;
6079 : :
6080 : : /* junk columns aren't visible to upper query */
6081 [ + + ]: 11106 : if (te->resjunk)
6082 : 175 : continue;
6083 : :
6084 : : /*
6085 : : * The subquery could be an expansion of a view that's had columns
6086 : : * added to it since the current query was parsed, so that there are
6087 : : * non-junk tlist columns in it that don't correspond to any column
6088 : : * visible at our query level. Ignore such columns.
6089 : : */
6090 [ + - - + ]: 10931 : if (te->resno < rel->min_attr || te->resno > rel->max_attr)
6091 : 0 : continue;
6092 : :
6093 : : /*
6094 : : * XXX This currently doesn't work for subqueries containing set
6095 : : * operations, because the Vars in their tlists are bogus references
6096 : : * to the first leaf subquery, which wouldn't give the right answer
6097 : : * even if we could still get to its PlannerInfo.
6098 : : *
6099 : : * Also, the subquery could be an appendrel for which all branches are
6100 : : * known empty due to constraint exclusion, in which case
6101 : : * set_append_rel_pathlist will have left the attr_widths set to zero.
6102 : : *
6103 : : * In either case, we just leave the width estimate zero until
6104 : : * set_rel_width fixes it.
6105 : : */
6106 [ + + + + ]: 10931 : if (IsA(texpr, Var) &&
6107 : 4081 : subroot->parse->setOperations == NULL)
6108 : : {
6109 : 3948 : Var *var = (Var *) texpr;
6110 : 3948 : RelOptInfo *subrel = find_base_rel(subroot, var->varno);
6111 : :
6112 : 3948 : item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
6113 : 3948 : }
6114 : 10931 : rel->attr_widths[te->resno - rel->min_attr] = item_width;
6115 [ - + + ]: 11106 : }
6116 : :
6117 : : /* Now estimate number of output rows, etc */
6118 : 3600 : set_baserel_size_estimates(root, rel);
6119 : 3600 : }
6120 : :
6121 : : /*
6122 : : * set_function_size_estimates
6123 : : * Set the size estimates for a base relation that is a function call.
6124 : : *
6125 : : * The rel's targetlist and restrictinfo list must have been constructed
6126 : : * already.
6127 : : *
6128 : : * We set the same fields as set_baserel_size_estimates.
6129 : : */
6130 : : void
6131 : 3642 : set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6132 : : {
6133 : 3642 : RangeTblEntry *rte;
6134 : 3642 : ListCell *lc;
6135 : :
6136 : : /* Should only be applied to base relations that are functions */
6137 [ + - ]: 3642 : Assert(rel->relid > 0);
6138 [ + - ]: 3642 : rte = planner_rt_fetch(rel->relid, root);
6139 [ + - ]: 3642 : Assert(rte->rtekind == RTE_FUNCTION);
6140 : :
6141 : : /*
6142 : : * Estimate number of rows the functions will return. The rowcount of the
6143 : : * node is that of the largest function result.
6144 : : */
6145 : 3642 : rel->tuples = 0;
6146 [ + - + + : 7332 : foreach(lc, rte->functions)
+ + ]
6147 : : {
6148 : 3690 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
6149 : 3690 : double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
6150 : :
6151 [ + + ]: 3690 : if (ntup > rel->tuples)
6152 : 3646 : rel->tuples = ntup;
6153 : 3690 : }
6154 : :
6155 : : /* Now estimate number of output rows, etc */
6156 : 3642 : set_baserel_size_estimates(root, rel);
6157 : 3642 : }
6158 : :
6159 : : /*
6160 : : * set_function_size_estimates
6161 : : * Set the size estimates for a base relation that is a function call.
6162 : : *
6163 : : * The rel's targetlist and restrictinfo list must have been constructed
6164 : : * already.
6165 : : *
6166 : : * We set the same fields as set_tablefunc_size_estimates.
6167 : : */
6168 : : void
6169 : 103 : set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6170 : : {
6171 : : /* Should only be applied to base relations that are functions */
6172 [ + - ]: 103 : Assert(rel->relid > 0);
6173 [ + - + - ]: 103 : Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
6174 : :
6175 : 103 : rel->tuples = 100;
6176 : :
6177 : : /* Now estimate number of output rows, etc */
6178 : 103 : set_baserel_size_estimates(root, rel);
6179 : 103 : }
6180 : :
6181 : : /*
6182 : : * set_values_size_estimates
6183 : : * Set the size estimates for a base relation that is a values list.
6184 : : *
6185 : : * The rel's targetlist and restrictinfo list must have been constructed
6186 : : * already.
6187 : : *
6188 : : * We set the same fields as set_baserel_size_estimates.
6189 : : */
6190 : : void
6191 : 1114 : set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6192 : : {
6193 : 1114 : RangeTblEntry *rte;
6194 : :
6195 : : /* Should only be applied to base relations that are values lists */
6196 [ + - ]: 1114 : Assert(rel->relid > 0);
6197 [ + - ]: 1114 : rte = planner_rt_fetch(rel->relid, root);
6198 [ + - ]: 1114 : Assert(rte->rtekind == RTE_VALUES);
6199 : :
6200 : : /*
6201 : : * Estimate number of rows the values list will return. We know this
6202 : : * precisely based on the list length (well, barring set-returning
6203 : : * functions in list items, but that's a refinement not catered for
6204 : : * anywhere else either).
6205 : : */
6206 : 1114 : rel->tuples = list_length(rte->values_lists);
6207 : :
6208 : : /* Now estimate number of output rows, etc */
6209 : 1114 : set_baserel_size_estimates(root, rel);
6210 : 1114 : }
6211 : :
6212 : : /*
6213 : : * set_cte_size_estimates
6214 : : * Set the size estimates for a base relation that is a CTE reference.
6215 : : *
6216 : : * The rel's targetlist and restrictinfo list must have been constructed
6217 : : * already, and we need an estimate of the number of rows returned by the CTE
6218 : : * (if a regular CTE) or the non-recursive term (if a self-reference).
6219 : : *
6220 : : * We set the same fields as set_baserel_size_estimates.
6221 : : */
6222 : : void
6223 : 286 : set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
6224 : : {
6225 : 286 : RangeTblEntry *rte;
6226 : :
6227 : : /* Should only be applied to base relations that are CTE references */
6228 [ + - ]: 286 : Assert(rel->relid > 0);
6229 [ + - ]: 286 : rte = planner_rt_fetch(rel->relid, root);
6230 [ + - ]: 286 : Assert(rte->rtekind == RTE_CTE);
6231 : :
6232 [ + + ]: 286 : if (rte->self_reference)
6233 : : {
6234 : : /*
6235 : : * In a self-reference, we assume the average worktable size is a
6236 : : * multiple of the nonrecursive term's size. The best multiplier will
6237 : : * vary depending on query "fan-out", so make its value adjustable.
6238 : : */
6239 : 74 : rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
6240 : 74 : }
6241 : : else
6242 : : {
6243 : : /* Otherwise just believe the CTE's rowcount estimate */
6244 : 212 : rel->tuples = cte_rows;
6245 : : }
6246 : :
6247 : : /* Now estimate number of output rows, etc */
6248 : 286 : set_baserel_size_estimates(root, rel);
6249 : 286 : }
6250 : :
6251 : : /*
6252 : : * set_namedtuplestore_size_estimates
6253 : : * Set the size estimates for a base relation that is a tuplestore reference.
6254 : : *
6255 : : * The rel's targetlist and restrictinfo list must have been constructed
6256 : : * already.
6257 : : *
6258 : : * We set the same fields as set_baserel_size_estimates.
6259 : : */
6260 : : void
6261 : 77 : set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6262 : : {
6263 : 77 : RangeTblEntry *rte;
6264 : :
6265 : : /* Should only be applied to base relations that are tuplestore references */
6266 [ + - ]: 77 : Assert(rel->relid > 0);
6267 [ + - ]: 77 : rte = planner_rt_fetch(rel->relid, root);
6268 [ + - ]: 77 : Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
6269 : :
6270 : : /*
6271 : : * Use the estimate provided by the code which is generating the named
6272 : : * tuplestore. In some cases, the actual number might be available; in
6273 : : * others the same plan will be re-used, so a "typical" value might be
6274 : : * estimated and used.
6275 : : */
6276 : 77 : rel->tuples = rte->enrtuples;
6277 [ + - ]: 77 : if (rel->tuples < 0)
6278 : 0 : rel->tuples = 1000;
6279 : :
6280 : : /* Now estimate number of output rows, etc */
6281 : 77 : set_baserel_size_estimates(root, rel);
6282 : 77 : }
6283 : :
6284 : : /*
6285 : : * set_result_size_estimates
6286 : : * Set the size estimates for an RTE_RESULT base relation
6287 : : *
6288 : : * The rel's targetlist and restrictinfo list must have been constructed
6289 : : * already.
6290 : : *
6291 : : * We set the same fields as set_baserel_size_estimates.
6292 : : */
6293 : : void
6294 : 676 : set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6295 : : {
6296 : : /* Should only be applied to RTE_RESULT base relations */
6297 [ + - ]: 676 : Assert(rel->relid > 0);
6298 [ + - + - ]: 676 : Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6299 : :
6300 : : /* RTE_RESULT always generates a single row, natively */
6301 : 676 : rel->tuples = 1;
6302 : :
6303 : : /* Now estimate number of output rows, etc */
6304 : 676 : set_baserel_size_estimates(root, rel);
6305 : 676 : }
6306 : :
6307 : : /*
6308 : : * set_foreign_size_estimates
6309 : : * Set the size estimates for a base relation that is a foreign table.
6310 : : *
6311 : : * There is not a whole lot that we can do here; the foreign-data wrapper
6312 : : * is responsible for producing useful estimates. We can do a decent job
6313 : : * of estimating baserestrictcost, so we set that, and we also set up width
6314 : : * using what will be purely datatype-driven estimates from the targetlist.
6315 : : * There is no way to do anything sane with the rows value, so we just put
6316 : : * a default estimate and hope that the wrapper can improve on it. The
6317 : : * wrapper's GetForeignRelSize function will be called momentarily.
6318 : : *
6319 : : * The rel's targetlist and restrictinfo list must have been constructed
6320 : : * already.
6321 : : */
6322 : : void
6323 : 0 : set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6324 : : {
6325 : : /* Should only be applied to base relations */
6326 [ # # ]: 0 : Assert(rel->relid > 0);
6327 : :
6328 : 0 : rel->rows = 1000; /* entirely bogus default estimate */
6329 : :
6330 : 0 : cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
6331 : :
6332 : 0 : set_rel_width(root, rel);
6333 : 0 : }
6334 : :
6335 : :
6336 : : /*
6337 : : * set_rel_width
6338 : : * Set the estimated output width of a base relation.
6339 : : *
6340 : : * The estimated output width is the sum of the per-attribute width estimates
6341 : : * for the actually-referenced columns, plus any PHVs or other expressions
6342 : : * that have to be calculated at this relation. This is the amount of data
6343 : : * we'd need to pass upwards in case of a sort, hash, etc.
6344 : : *
6345 : : * This function also sets reltarget->cost, so it's a bit misnamed now.
6346 : : *
6347 : : * NB: this works best on plain relations because it prefers to look at
6348 : : * real Vars. For subqueries, set_subquery_size_estimates will already have
6349 : : * copied up whatever per-column estimates were made within the subquery,
6350 : : * and for other types of rels there isn't much we can do anyway. We fall
6351 : : * back on (fairly stupid) datatype-based width estimates if we can't get
6352 : : * any better number.
6353 : : *
6354 : : * The per-attribute width estimates are cached for possible re-use while
6355 : : * building join relations or post-scan/join pathtargets.
6356 : : */
6357 : : static void
6358 : 52735 : set_rel_width(PlannerInfo *root, RelOptInfo *rel)
6359 : : {
6360 [ - + ]: 52735 : Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
6361 : 52735 : int64 tuple_width = 0;
6362 : 52735 : bool have_wholerow_var = false;
6363 : 52735 : ListCell *lc;
6364 : :
6365 : : /* Vars are assumed to have cost zero, but other exprs do not */
6366 : 52735 : rel->reltarget->cost.startup = 0;
6367 : 52735 : rel->reltarget->cost.per_tuple = 0;
6368 : :
6369 [ + + + + : 182314 : foreach(lc, rel->reltarget->exprs)
+ + ]
6370 : : {
6371 : 129579 : Node *node = (Node *) lfirst(lc);
6372 : :
6373 : : /*
6374 : : * Ordinarily, a Var in a rel's targetlist must belong to that rel;
6375 : : * but there are corner cases involving LATERAL references where that
6376 : : * isn't so. If the Var has the wrong varno, fall through to the
6377 : : * generic case (it doesn't seem worth the trouble to be any smarter).
6378 : : */
6379 [ + + + + ]: 129579 : if (IsA(node, Var) &&
6380 : 126152 : ((Var *) node)->varno == rel->relid)
6381 : : {
6382 : 126141 : Var *var = (Var *) node;
6383 : 126141 : int ndx;
6384 : 126141 : int32 item_width;
6385 : :
6386 [ + - ]: 126141 : Assert(var->varattno >= rel->min_attr);
6387 [ + - ]: 126141 : Assert(var->varattno <= rel->max_attr);
6388 : :
6389 : 126141 : ndx = var->varattno - rel->min_attr;
6390 : :
6391 : : /*
6392 : : * If it's a whole-row Var, we'll deal with it below after we have
6393 : : * already cached as many attr widths as possible.
6394 : : */
6395 [ + + ]: 126141 : if (var->varattno == 0)
6396 : : {
6397 : 269 : have_wholerow_var = true;
6398 : 269 : continue;
6399 : : }
6400 : :
6401 : : /*
6402 : : * The width may have been cached already (especially if it's a
6403 : : * subquery), so don't duplicate effort.
6404 : : */
6405 [ + + ]: 125872 : if (rel->attr_widths[ndx] > 0)
6406 : : {
6407 : 36175 : tuple_width += rel->attr_widths[ndx];
6408 : 36175 : continue;
6409 : : }
6410 : :
6411 : : /* Try to get column width from statistics */
6412 [ + + + + ]: 89697 : if (reloid != InvalidOid && var->varattno > 0)
6413 : : {
6414 : 71530 : item_width = get_attavgwidth(reloid, var->varattno);
6415 [ + + ]: 71530 : if (item_width > 0)
6416 : : {
6417 : 60357 : rel->attr_widths[ndx] = item_width;
6418 : 60357 : tuple_width += item_width;
6419 : 60357 : continue;
6420 : : }
6421 : 11173 : }
6422 : :
6423 : : /*
6424 : : * Not a plain relation, or can't find statistics for it. Estimate
6425 : : * using just the type info.
6426 : : */
6427 : 29340 : item_width = get_typavgwidth(var->vartype, var->vartypmod);
6428 [ - + ]: 29340 : Assert(item_width > 0);
6429 : 29340 : rel->attr_widths[ndx] = item_width;
6430 : 29340 : tuple_width += item_width;
6431 [ + + ]: 126141 : }
6432 [ + + ]: 3438 : else if (IsA(node, PlaceHolderVar))
6433 : : {
6434 : : /*
6435 : : * We will need to evaluate the PHV's contained expression while
6436 : : * scanning this rel, so be sure to include it in reltarget->cost.
6437 : : */
6438 : 325 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
6439 : 325 : PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
6440 : 325 : QualCost cost;
6441 : :
6442 : 325 : tuple_width += phinfo->ph_width;
6443 : 325 : cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
6444 : 325 : rel->reltarget->cost.startup += cost.startup;
6445 : 325 : rel->reltarget->cost.per_tuple += cost.per_tuple;
6446 : 325 : }
6447 : : else
6448 : : {
6449 : : /*
6450 : : * We could be looking at an expression pulled up from a subquery,
6451 : : * or a ROW() representing a whole-row child Var, etc. Do what we
6452 : : * can using the expression type information.
6453 : : */
6454 : 3113 : int32 item_width;
6455 : 3113 : QualCost cost;
6456 : :
6457 : 3113 : item_width = get_typavgwidth(exprType(node), exprTypmod(node));
6458 [ + - ]: 3113 : Assert(item_width > 0);
6459 : 3113 : tuple_width += item_width;
6460 : : /* Not entirely clear if we need to account for cost, but do so */
6461 : 3113 : cost_qual_eval_node(&cost, node, root);
6462 : 3113 : rel->reltarget->cost.startup += cost.startup;
6463 : 3113 : rel->reltarget->cost.per_tuple += cost.per_tuple;
6464 : 3113 : }
6465 [ - + + ]: 129579 : }
6466 : :
6467 : : /*
6468 : : * If we have a whole-row reference, estimate its width as the sum of
6469 : : * per-column widths plus heap tuple header overhead.
6470 : : */
6471 [ + + ]: 52735 : if (have_wholerow_var)
6472 : : {
6473 : 269 : int64 wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
6474 : :
6475 [ + + ]: 269 : if (reloid != InvalidOid)
6476 : : {
6477 : : /* Real relation, so estimate true tuple width */
6478 : 374 : wholerow_width += get_relation_data_width(reloid,
6479 : 187 : rel->attr_widths - rel->min_attr);
6480 : 187 : }
6481 : : else
6482 : : {
6483 : : /* Do what we can with info for a phony rel */
6484 : 82 : AttrNumber i;
6485 : :
6486 [ + + ]: 223 : for (i = 1; i <= rel->max_attr; i++)
6487 : 141 : wholerow_width += rel->attr_widths[i - rel->min_attr];
6488 : 82 : }
6489 : :
6490 : 269 : rel->attr_widths[0 - rel->min_attr] = clamp_width_est(wholerow_width);
6491 : :
6492 : : /*
6493 : : * Include the whole-row Var as part of the output tuple. Yes, that
6494 : : * really is what happens at runtime.
6495 : : */
6496 : 269 : tuple_width += wholerow_width;
6497 : 269 : }
6498 : :
6499 : 52735 : rel->reltarget->width = clamp_width_est(tuple_width);
6500 : 52735 : }
6501 : :
6502 : : /*
6503 : : * set_pathtarget_cost_width
6504 : : * Set the estimated eval cost and output width of a PathTarget tlist.
6505 : : *
6506 : : * As a notational convenience, returns the same PathTarget pointer passed in.
6507 : : *
6508 : : * Most, though not quite all, uses of this function occur after we've run
6509 : : * set_rel_width() for base relations; so we can usually obtain cached width
6510 : : * estimates for Vars. If we can't, fall back on datatype-based width
6511 : : * estimates. Present early-planning uses of PathTargets don't need accurate
6512 : : * widths badly enough to justify going to the catalogs for better data.
6513 : : */
6514 : : PathTarget *
6515 : 63879 : set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
6516 : : {
6517 : 63879 : int64 tuple_width = 0;
6518 : 63879 : ListCell *lc;
6519 : :
6520 : : /* Vars are assumed to have cost zero, but other exprs do not */
6521 : 63879 : target->cost.startup = 0;
6522 : 63879 : target->cost.per_tuple = 0;
6523 : :
6524 [ + + + + : 216028 : foreach(lc, target->exprs)
+ + ]
6525 : : {
6526 : 152149 : Node *node = (Node *) lfirst(lc);
6527 : :
6528 : 152149 : tuple_width += get_expr_width(root, node);
6529 : :
6530 : : /* For non-Vars, account for evaluation cost */
6531 [ + + ]: 152149 : if (!IsA(node, Var))
6532 : : {
6533 : 68157 : QualCost cost;
6534 : :
6535 : 68157 : cost_qual_eval_node(&cost, node, root);
6536 : 68157 : target->cost.startup += cost.startup;
6537 : 68157 : target->cost.per_tuple += cost.per_tuple;
6538 : 68157 : }
6539 : 152149 : }
6540 : :
6541 : 63879 : target->width = clamp_width_est(tuple_width);
6542 : :
6543 : 127758 : return target;
6544 : 63879 : }
6545 : :
6546 : : /*
6547 : : * get_expr_width
6548 : : * Estimate the width of the given expr attempting to use the width
6549 : : * cached in a Var's owning RelOptInfo, else fallback on the type's
6550 : : * average width when unable to or when the given Node is not a Var.
6551 : : */
6552 : : static int32
6553 : 171978 : get_expr_width(PlannerInfo *root, const Node *expr)
6554 : : {
6555 : 171978 : int32 width;
6556 : :
6557 [ + + ]: 171978 : if (IsA(expr, Var))
6558 : : {
6559 : 102367 : const Var *var = (const Var *) expr;
6560 : :
6561 : : /* We should not see any upper-level Vars here */
6562 [ + - ]: 102367 : Assert(var->varlevelsup == 0);
6563 : :
6564 : : /* Try to get data from RelOptInfo cache */
6565 [ + + - + ]: 102367 : if (!IS_SPECIAL_VARNO(var->varno) &&
6566 : 101627 : var->varno < root->simple_rel_array_size)
6567 : : {
6568 : 101627 : RelOptInfo *rel = root->simple_rel_array[var->varno];
6569 : :
6570 [ + + ]: 101627 : if (rel != NULL &&
6571 [ + - - + ]: 99375 : var->varattno >= rel->min_attr &&
6572 : 99375 : var->varattno <= rel->max_attr)
6573 : : {
6574 : 99375 : int ndx = var->varattno - rel->min_attr;
6575 : :
6576 [ + + ]: 99375 : if (rel->attr_widths[ndx] > 0)
6577 : 95540 : return rel->attr_widths[ndx];
6578 [ + + ]: 99375 : }
6579 [ + + ]: 101627 : }
6580 : :
6581 : : /*
6582 : : * No cached data available, so estimate using just the type info.
6583 : : */
6584 : 6827 : width = get_typavgwidth(var->vartype, var->vartypmod);
6585 [ + - ]: 6827 : Assert(width > 0);
6586 : :
6587 : 6827 : return width;
6588 : 102367 : }
6589 : :
6590 : 69611 : width = get_typavgwidth(exprType(expr), exprTypmod(expr));
6591 [ + - ]: 69611 : Assert(width > 0);
6592 : 69611 : return width;
6593 : 171978 : }
6594 : :
6595 : : /*
6596 : : * relation_byte_size
6597 : : * Estimate the storage space in bytes for a given number of tuples
6598 : : * of a given width (size in bytes).
6599 : : */
6600 : : static double
6601 : 482581 : relation_byte_size(double tuples, int width)
6602 : : {
6603 : 482581 : return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
6604 : : }
6605 : :
6606 : : /*
6607 : : * page_size
6608 : : * Returns an estimate of the number of pages covered by a given
6609 : : * number of tuples of a given width (size in bytes).
6610 : : */
6611 : : static double
6612 : 696 : page_size(double tuples, int width)
6613 : : {
6614 : 696 : return ceil(relation_byte_size(tuples, width) / BLCKSZ);
6615 : : }
6616 : :
6617 : : /*
6618 : : * Estimate the fraction of the work that each worker will do given the
6619 : : * number of workers budgeted for the path.
6620 : : */
6621 : : static double
6622 : 75484 : get_parallel_divisor(Path *path)
6623 : : {
6624 : 75484 : double parallel_divisor = path->parallel_workers;
6625 : :
6626 : : /*
6627 : : * Early experience with parallel query suggests that when there is only
6628 : : * one worker, the leader often makes a very substantial contribution to
6629 : : * executing the parallel portion of the plan, but as more workers are
6630 : : * added, it does less and less, because it's busy reading tuples from the
6631 : : * workers and doing whatever non-parallel post-processing is needed. By
6632 : : * the time we reach 4 workers, the leader no longer makes a meaningful
6633 : : * contribution. Thus, for now, estimate that the leader spends 30% of
6634 : : * its time servicing each worker, and the remainder executing the
6635 : : * parallel plan.
6636 : : */
6637 [ + + ]: 75484 : if (parallel_leader_participation)
6638 : : {
6639 : 75285 : double leader_contribution;
6640 : :
6641 : 75285 : leader_contribution = 1.0 - (0.3 * path->parallel_workers);
6642 [ + + ]: 75285 : if (leader_contribution > 0)
6643 : 74855 : parallel_divisor += leader_contribution;
6644 : 75285 : }
6645 : :
6646 : 150968 : return parallel_divisor;
6647 : 75484 : }
6648 : :
6649 : : /*
6650 : : * compute_bitmap_pages
6651 : : * Estimate number of pages fetched from heap in a bitmap heap scan.
6652 : : *
6653 : : * 'baserel' is the relation to be scanned
6654 : : * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
6655 : : * 'loop_count' is the number of repetitions of the indexscan to factor into
6656 : : * estimates of caching behavior
6657 : : *
6658 : : * If cost_p isn't NULL, the indexTotalCost estimate is returned in *cost_p.
6659 : : * If tuples_p isn't NULL, the tuples_fetched estimate is returned in *tuples_p.
6660 : : */
6661 : : double
6662 : 63469 : compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel,
6663 : : Path *bitmapqual, double loop_count,
6664 : : Cost *cost_p, double *tuples_p)
6665 : : {
6666 : 63469 : Cost indexTotalCost;
6667 : 63469 : Selectivity indexSelectivity;
6668 : 63469 : double T;
6669 : 63469 : double pages_fetched;
6670 : 63469 : double tuples_fetched;
6671 : 63469 : double heap_pages;
6672 : 63469 : double maxentries;
6673 : :
6674 : : /*
6675 : : * Fetch total cost of obtaining the bitmap, as well as its total
6676 : : * selectivity.
6677 : : */
6678 : 63469 : cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6679 : :
6680 : : /*
6681 : : * Estimate number of main-table pages fetched.
6682 : : */
6683 : 63469 : tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6684 : :
6685 [ + + ]: 63469 : T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6686 : :
6687 : : /*
6688 : : * For a single scan, the number of heap pages that need to be fetched is
6689 : : * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6690 : : * re-reads needed).
6691 : : */
6692 : 63469 : pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6693 : :
6694 : : /*
6695 : : * Calculate the number of pages fetched from the heap. Then based on
6696 : : * current work_mem estimate get the estimated maxentries in the bitmap.
6697 : : * (Note that we always do this calculation based on the number of pages
6698 : : * that would be fetched in a single iteration, even if loop_count > 1.
6699 : : * That's correct, because only that number of entries will be stored in
6700 : : * the bitmap at one time.)
6701 : : */
6702 [ + + ]: 63469 : heap_pages = Min(pages_fetched, baserel->pages);
6703 : 63469 : maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
6704 : :
6705 [ + + ]: 63469 : if (loop_count > 1)
6706 : : {
6707 : : /*
6708 : : * For repeated bitmap scans, scale up the number of tuples fetched in
6709 : : * the Mackert and Lohman formula by the number of scans, so that we
6710 : : * estimate the number of pages fetched by all the scans. Then
6711 : : * pro-rate for one scan.
6712 : : */
6713 : 28204 : pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6714 : 14102 : baserel->pages,
6715 : 14102 : get_indexpath_pages(bitmapqual),
6716 : 14102 : root);
6717 : 14102 : pages_fetched /= loop_count;
6718 : 14102 : }
6719 : :
6720 [ + + ]: 63469 : if (pages_fetched >= T)
6721 : 7397 : pages_fetched = T;
6722 : : else
6723 : 56072 : pages_fetched = ceil(pages_fetched);
6724 : :
6725 [ + + ]: 63469 : if (maxentries < heap_pages)
6726 : : {
6727 : 3 : double exact_pages;
6728 : 3 : double lossy_pages;
6729 : :
6730 : : /*
6731 : : * Crude approximation of the number of lossy pages. Because of the
6732 : : * way tbm_lossify() is coded, the number of lossy pages increases
6733 : : * very sharply as soon as we run short of memory; this formula has
6734 : : * that property and seems to perform adequately in testing, but it's
6735 : : * possible we could do better somehow.
6736 : : */
6737 [ - + ]: 3 : lossy_pages = Max(0, heap_pages - maxentries / 2);
6738 : 3 : exact_pages = heap_pages - lossy_pages;
6739 : :
6740 : : /*
6741 : : * If there are lossy pages then recompute the number of tuples
6742 : : * processed by the bitmap heap node. We assume here that the chance
6743 : : * of a given tuple coming from an exact page is the same as the
6744 : : * chance that a given page is exact. This might not be true, but
6745 : : * it's not clear how we can do any better.
6746 : : */
6747 [ - + ]: 3 : if (lossy_pages > 0)
6748 : 3 : tuples_fetched =
6749 : 9 : clamp_row_est(indexSelectivity *
6750 : 9 : (exact_pages / heap_pages) * baserel->tuples +
6751 : 3 : (lossy_pages / heap_pages) * baserel->tuples);
6752 : 3 : }
6753 : :
6754 [ + + ]: 63469 : if (cost_p)
6755 : 50395 : *cost_p = indexTotalCost;
6756 [ + + ]: 63469 : if (tuples_p)
6757 : 50395 : *tuples_p = tuples_fetched;
6758 : :
6759 : 126938 : return pages_fetched;
6760 : 63469 : }
6761 : :
6762 : : /*
6763 : : * compute_gather_rows
6764 : : * Estimate number of rows for gather (merge) nodes.
6765 : : *
6766 : : * In a parallel plan, each worker's row estimate is determined by dividing the
6767 : : * total number of rows by parallel_divisor, which accounts for the leader's
6768 : : * contribution in addition to the number of workers. Accordingly, when
6769 : : * estimating the number of rows for gather (merge) nodes, we multiply the rows
6770 : : * per worker by the same parallel_divisor to undo the division.
6771 : : */
6772 : : double
6773 : 6643 : compute_gather_rows(Path *path)
6774 : : {
6775 [ + - ]: 6643 : Assert(path->parallel_workers > 0);
6776 : :
6777 : 6643 : return clamp_row_est(path->rows * get_parallel_divisor(path));
6778 : : }
|