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