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