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