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