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
8316 tgl@sss.pgh.pa.us 215 :CBC 7810621 : 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 : : */
2184 drowley@postgresql.o 223 [ + - - + ]: 7810621 : if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
2184 drowley@postgresql.o 224 :UBC 0 : nrows = MAXIMUM_ROWCOUNT;
2184 drowley@postgresql.o 225 [ + + ]:CBC 7810621 : else if (nrows <= 1.0)
8316 tgl@sss.pgh.pa.us 226 : 2537712 : nrows = 1.0;
227 : : else
7844 228 : 5272909 : nrows = rint(nrows);
229 : :
8316 230 : 7810621 : 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
1028 244 : 1500977 : 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 [ - + ]: 1500977 : if (tuple_width > MaxAllocSize)
1028 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 : : */
1028 tgl@sss.pgh.pa.us 257 [ - + ]:CBC 1500977 : Assert(tuple_width >= 0);
258 : :
259 : 1500977 : 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
7799 271 : 334440 : cost_seqscan(Path *path, PlannerInfo *root,
272 : : RelOptInfo *baserel, ParamPathInfo *param_info)
273 : : {
9736 274 : 334440 : 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;
257 rhaas@postgresql.org 280 : 334440 : uint64 enable_mask = PGS_SEQSCAN;
281 : :
282 : : /* Should only be applied to base relations */
8647 tgl@sss.pgh.pa.us 283 [ - + ]: 334440 : Assert(baserel->relid > 0);
8919 284 [ - + ]: 334440 : Assert(baserel->rtekind == RTE_RELATION);
285 : :
286 : : /* Mark the path with the correct row estimate */
5289 287 [ + + ]: 334440 : if (param_info)
288 : 1246 : path->rows = param_info->ppi_rows;
289 : : else
290 : 333194 : path->rows = baserel->rows;
291 : :
292 : : /* fetch estimated page cost for tablespace containing table */
6124 rhaas@postgresql.org 293 : 334440 : get_tablespace_page_costs(baserel->reltablespace,
294 : : NULL,
295 : : &spc_seq_page_cost);
296 : :
297 : : /*
298 : : * disk costs
299 : : */
3918 300 : 334440 : disk_run_cost = spc_seq_page_cost * baserel->pages;
301 : :
302 : : /* CPU costs */
5289 tgl@sss.pgh.pa.us 303 : 334440 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
304 : :
305 : 334440 : startup_cost += qpqual_cost.startup;
306 : 334440 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
3918 rhaas@postgresql.org 307 : 334440 : cpu_run_cost = cpu_per_tuple * baserel->tuples;
308 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 tgl@sss.pgh.pa.us 309 : 334440 : startup_cost += path->pathtarget->cost.startup;
310 : 334440 : cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
311 : :
312 : : /* Adjust costing for parallelism, if used. */
3777 rhaas@postgresql.org 313 [ + + ]: 334440 : if (path->parallel_workers > 0)
314 : : {
3559 315 : 23554 : double parallel_divisor = get_parallel_divisor(path);
316 : :
317 : : /* The CPU cost is divided among all the workers. */
3918 318 : 23554 : 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 : : */
3559 331 : 23554 : path->rows = clamp_row_est(path->rows / parallel_divisor);
332 : : }
333 : : else
257 334 : 310886 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
335 : :
336 : 334440 : path->disabled_nodes =
337 : 334440 : (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
4168 simon@2ndQuadrant.co 338 : 334440 : path->startup_cost = startup_cost;
3918 rhaas@postgresql.org 339 : 334440 : path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
4168 simon@2ndQuadrant.co 340 : 334440 : }
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
4097 tgl@sss.pgh.pa.us 350 : 262 : cost_samplescan(Path *path, PlannerInfo *root,
351 : : RelOptInfo *baserel, ParamPathInfo *param_info)
352 : : {
4168 simon@2ndQuadrant.co 353 : 262 : Cost startup_cost = 0;
354 : 262 : 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;
257 rhaas@postgresql.org 363 : 262 : uint64 enable_mask = 0;
364 : :
365 : : /* Should only be applied to base relations with tablesample clauses */
4168 simon@2ndQuadrant.co 366 [ - + ]: 262 : Assert(baserel->relid > 0);
4097 tgl@sss.pgh.pa.us 367 [ + - ]: 262 : rte = planner_rt_fetch(baserel->relid, root);
368 [ - + ]: 262 : Assert(rte->rtekind == RTE_RELATION);
369 : 262 : tsc = rte->tablesample;
370 [ - + ]: 262 : Assert(tsc != NULL);
371 : 262 : tsm = GetTsmRoutine(tsc->tsmhandler);
372 : :
373 : : /* Mark the path with the correct row estimate */
374 [ + + ]: 262 : if (param_info)
375 : 70 : path->rows = param_info->ppi_rows;
376 : : else
4168 simon@2ndQuadrant.co 377 : 192 : path->rows = baserel->rows;
378 : :
379 : : /* fetch estimated page cost for tablespace containing table */
380 : 262 : 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 */
4097 tgl@sss.pgh.pa.us 385 : 524 : spc_page_cost = (tsm->NextSampleBlock != NULL) ?
386 [ + + ]: 262 : 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 : 262 : 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 : 262 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
403 : :
4168 simon@2ndQuadrant.co 404 : 262 : startup_cost += qpqual_cost.startup;
405 : 262 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
4097 tgl@sss.pgh.pa.us 406 : 262 : run_cost += cpu_per_tuple * baserel->tuples;
407 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 408 : 262 : startup_cost += path->pathtarget->cost.startup;
409 : 262 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
410 : :
257 rhaas@postgresql.org 411 [ + - ]: 262 : if (path->parallel_workers == 0)
412 : 262 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
413 : :
414 : 262 : path->disabled_nodes =
415 : 262 : (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
9736 tgl@sss.pgh.pa.us 416 : 262 : path->startup_cost = startup_cost;
417 : 262 : path->total_cost = startup_cost + run_cost;
11052 scrappy@hub.org 418 : 262 : }
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
4030 rhaas@postgresql.org 431 : 21206 : cost_gather(GatherPath *path, PlannerInfo *root,
432 : : RelOptInfo *rel, ParamPathInfo *param_info,
433 : : double *rows)
434 : : {
435 : 21206 : Cost startup_cost = 0;
436 : 21206 : Cost run_cost = 0;
437 : :
438 : : /* Mark the path with the correct row estimate */
3857 439 [ + + ]: 21206 : if (rows)
440 : 5713 : path->path.rows = *rows;
441 [ - + ]: 15493 : else if (param_info)
4030 rhaas@postgresql.org 442 :UBC 0 : path->path.rows = param_info->ppi_rows;
443 : : else
4030 rhaas@postgresql.org 444 :CBC 15493 : path->path.rows = rel->rows;
445 : :
446 : 21206 : startup_cost = path->subpath->startup_cost;
447 : :
448 : 21206 : run_cost = path->subpath->total_cost - path->subpath->startup_cost;
449 : :
450 : : /* Parallel setup and communication cost. */
451 : 21206 : startup_cost += parallel_setup_cost;
3988 452 : 21206 : run_cost += parallel_tuple_cost * path->path.rows;
453 : :
257 454 : 21206 : path->path.disabled_nodes = path->subpath->disabled_nodes
455 : 21206 : + ((rel->pgs_mask & PGS_GATHER) != 0 ? 0 : 1);
4030 456 : 21206 : path->path.startup_cost = startup_cost;
457 : 21206 : path->path.total_cost = (startup_cost + run_cost);
458 : 21206 : }
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
3504 471 : 15163 : 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 : 15163 : Cost startup_cost = 0;
478 : 15163 : 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 [ + + ]: 15163 : if (rows)
485 : 9153 : path->path.rows = *rows;
486 [ - + ]: 6010 : else if (param_info)
3504 rhaas@postgresql.org 487 :UBC 0 : path->path.rows = param_info->ppi_rows;
488 : : else
3504 rhaas@postgresql.org 489 :CBC 6010 : 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 [ - + ]: 15163 : Assert(path->num_workers > 0);
497 : 15163 : N = (double) path->num_workers + 1;
498 : 15163 : logN = LOG2(N);
499 : :
500 : : /* Assumed cost per tuple comparison */
501 : 15163 : comparison_cost = 2.0 * cpu_operator_cost;
502 : :
503 : : /* Heap creation cost */
504 : 15163 : startup_cost += comparison_cost * N * logN;
505 : :
506 : : /* Per-tuple heap maintenance cost */
507 : 15163 : run_cost += path->path.rows * comparison_cost * logN;
508 : :
509 : : /* small cost for heap management, like cost_merge_append */
510 : 15163 : 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 : 15163 : startup_cost += parallel_setup_cost;
519 : 15163 : run_cost += parallel_tuple_cost * path->path.rows * 1.05;
520 : :
257 521 : 15163 : path->path.disabled_nodes = path->subpath->disabled_nodes
522 : 15163 : + ((rel->pgs_mask & PGS_GATHER_MERGE) != 0 ? 0 : 1);
3504 523 : 15163 : path->path.startup_cost = startup_cost + input_startup_cost;
524 : 15163 : path->path.total_cost = (startup_cost + run_cost + input_total_cost);
525 : 15163 : }
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
3526 546 : 656045 : cost_index(IndexPath *path, PlannerInfo *root, double loop_count,
547 : : bool partial_path)
548 : : {
5406 tgl@sss.pgh.pa.us 549 : 656045 : IndexOptInfo *index = path->indexinfo;
7869 550 : 656045 : RelOptInfo *baserel = index->rel;
5406 551 : 656045 : bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
552 : : amcostestimate_function amcostestimate;
553 : : List *qpquals;
9736 554 : 656045 : Cost startup_cost = 0;
555 : 656045 : Cost run_cost = 0;
3526 rhaas@postgresql.org 556 : 656045 : 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 */
8919 tgl@sss.pgh.pa.us 575 [ + - - + ]: 656045 : Assert(IsA(baserel, RelOptInfo) &&
576 : : IsA(index, IndexOptInfo));
8647 577 [ - + ]: 656045 : Assert(baserel->relid > 0);
8919 578 [ - + ]: 656045 : 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 : : */
5289 587 [ + + ]: 656045 : if (path->path.param_info)
588 : : {
589 : 135966 : path->path.rows = path->path.param_info->ppi_rows;
590 : : /* qpquals come from the rel's restriction clauses and ppi_clauses */
2802 591 : 135966 : qpquals = list_concat(extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
592 : : path->indexclauses),
3400 593 : 135966 : extract_nonindex_conditions(path->path.param_info->ppi_clauses,
594 : : path->indexclauses));
595 : : }
596 : : else
597 : : {
5289 598 : 520079 : path->path.rows = baserel->rows;
599 : : /* qpquals come from just the rel's restriction clauses */
3847 600 : 520079 : qpquals = extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
601 : : path->indexclauses);
602 : : }
603 : :
604 : : /* is this scan type disabled? */
257 rhaas@postgresql.org 605 [ + + ]: 656045 : enable_mask = (indexonly ? PGS_INDEXONLYSCAN : PGS_INDEXSCAN)
606 [ + + ]: 656045 : | (partial_path ? 0 : PGS_CONSIDER_NONPARTIAL);
607 : 656045 : path->path.disabled_nodes =
608 : 656045 : (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 : : */
3921 tgl@sss.pgh.pa.us 617 : 656045 : amcostestimate = (amcostestimate_function) index->amcostestimate;
618 : 656045 : 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 : : */
7844 628 : 656045 : path->indextotalcost = indexTotalCost;
629 : 656045 : path->indexselectivity = indexSelectivity;
630 : :
631 : : /* all costs for touching index itself included here */
9736 632 : 656045 : startup_cost += indexStartupCost;
633 : 656045 : run_cost += indexTotalCost - indexStartupCost;
634 : :
635 : : /* estimate number of main-table tuples fetched */
7433 636 : 656045 : tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
637 : :
638 : : /* fetch estimated page costs for tablespace containing table */
6124 rhaas@postgresql.org 639 : 656045 : 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 : : */
5372 tgl@sss.pgh.pa.us 670 [ + + ]: 656045 : 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 : 73013 : pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
681 : : baserel->pages,
7328 682 : 73013 : (double) index->pages,
683 : : root);
684 : :
5483 685 [ + + ]: 73013 : if (indexonly)
5477 686 : 10567 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
687 : :
3526 rhaas@postgresql.org 688 : 73013 : rand_heap_pages = pages_fetched;
689 : :
5372 tgl@sss.pgh.pa.us 690 : 73013 : 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 : : */
7241 702 : 73013 : pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
703 : :
5372 704 : 73013 : pages_fetched = index_pages_fetched(pages_fetched * loop_count,
705 : : baserel->pages,
7241 706 : 73013 : (double) index->pages,
707 : : root);
708 : :
5483 709 [ + + ]: 73013 : if (indexonly)
5477 710 : 10567 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
711 : :
5372 712 : 73013 : 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 : : */
7433 720 : 583032 : pages_fetched = index_pages_fetched(tuples_fetched,
721 : : baserel->pages,
7328 722 : 583032 : (double) index->pages,
723 : : root);
724 : :
5483 725 [ + + ]: 583032 : if (indexonly)
5477 726 : 57258 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
727 : :
3526 rhaas@postgresql.org 728 : 583032 : rand_heap_pages = pages_fetched;
729 : :
730 : : /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
6124 731 : 583032 : max_IO_cost = pages_fetched * spc_random_page_cost;
732 : :
733 : : /* min_IO_cost is for the perfectly correlated case (csquared=1) */
7433 tgl@sss.pgh.pa.us 734 : 583032 : pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
735 : :
5483 736 [ + + ]: 583032 : if (indexonly)
5477 737 : 57258 : pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
738 : :
5475 739 [ + + ]: 583032 : if (pages_fetched > 0)
740 : : {
741 : 504863 : min_IO_cost = spc_random_page_cost;
742 [ + + ]: 504863 : if (pages_fetched > 1)
743 : 145848 : min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
744 : : }
745 : : else
746 : 78169 : min_IO_cost = 0;
747 : : }
748 : :
3526 rhaas@postgresql.org 749 [ + + ]: 656045 : 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 : : */
3499 756 [ + + ]: 223940 : if (indexonly)
757 : 18961 : 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 : : */
3526 765 : 223940 : 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 [ + + ]: 223940 : if (path->path.parallel_workers <= 0)
776 : 216250 : return;
777 : :
778 : 7690 : 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 : : */
7241 tgl@sss.pgh.pa.us 785 : 439795 : csquared = indexCorrelation * indexCorrelation;
786 : :
787 : 439795 : 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 : : */
4241 795 : 439795 : cost_qual_eval(&qpqual_cost, qpquals, root);
796 : :
5297 797 : 439795 : startup_cost += qpqual_cost.startup;
798 : 439795 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
799 : :
3526 rhaas@postgresql.org 800 : 439795 : cpu_run_cost += cpu_per_tuple * tuples_fetched;
801 : :
802 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 tgl@sss.pgh.pa.us 803 : 439795 : startup_cost += path->path.pathtarget->cost.startup;
3526 rhaas@postgresql.org 804 : 439795 : cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
805 : :
806 : : /* Adjust costing for parallelism, if used. */
807 [ + + ]: 439795 : if (path->path.parallel_workers > 0)
808 : : {
809 : 7690 : double parallel_divisor = get_parallel_divisor(&path->path);
810 : :
811 : 7690 : path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
812 : :
813 : : /* The CPU cost is divided among all the workers. */
814 : 7690 : cpu_run_cost /= parallel_divisor;
815 : : }
816 : :
817 : 439795 : run_cost += cpu_run_cost;
818 : :
7844 tgl@sss.pgh.pa.us 819 : 439795 : path->path.startup_cost = startup_cost;
820 : 439795 : 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 *
2802 840 : 792011 : extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
841 : : {
4241 842 : 792011 : List *result = NIL;
843 : : ListCell *lc;
844 : :
845 [ + + + + : 1633970 : foreach(lc, qual_clauses)
+ + ]
846 : : {
3472 847 : 841959 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
848 : :
4241 849 [ + + ]: 841959 : if (rinfo->pseudoconstant)
850 : 3394 : continue; /* we may drop pseudoconstants here */
2802 851 [ + + ]: 838565 : if (is_redundant_with_indexclauses(rinfo, indexclauses))
852 : 468460 : continue; /* dup or derived from same EquivalenceClass */
853 : : /* ... skip the predicate proof attempt createplan.c will try ... */
4241 854 : 370105 : result = lappend(result, rinfo);
855 : : }
856 : 792011 : 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
7433 898 : 932363 : 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 [ + + ]: 932363 : T = (pages > 1) ? (double) pages : 1.0;
908 : :
909 : : /* Compute number of pages assumed to be competing for cache space */
7328 910 : 932363 : total_pages = root->total_table_pages + index_pages;
911 [ + + ]: 932363 : total_pages = Max(total_pages, 1.0);
912 [ - + ]: 932363 : Assert(T <= total_pages);
913 : :
914 : : /* b is pro-rated share of effective_cache_size */
3400 915 : 932363 : b = (double) effective_cache_size * T / total_pages;
916 : :
917 : : /* force it positive and integral */
7433 918 [ - + ]: 932363 : if (b <= 1.0)
7433 tgl@sss.pgh.pa.us 919 :UBC 0 : b = 1.0;
920 : : else
7433 tgl@sss.pgh.pa.us 921 :CBC 932363 : b = ceil(b);
922 : :
923 : : /* This part is the Mackert and Lohman formula */
924 [ + - ]: 932363 : if (T <= b)
925 : : {
926 : 932363 : pages_fetched =
927 : 932363 : (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
928 [ + + ]: 932363 : if (pages_fetched >= T)
929 : 553236 : pages_fetched = T;
930 : : else
931 : 379127 : pages_fetched = ceil(pages_fetched);
932 : : }
933 : : else
934 : : {
935 : : double lim;
936 : :
7433 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 : : }
7433 tgl@sss.pgh.pa.us 950 :CBC 932363 : 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
7328 963 : 168293 : get_indexpath_pages(Path *bitmapqual)
964 : : {
965 : 168293 : double result = 0;
966 : : ListCell *l;
967 : :
968 [ + + ]: 168293 : if (IsA(bitmapqual, BitmapAndPath))
969 : : {
970 : 20936 : BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
971 : :
972 [ + - + + : 62808 : foreach(l, apath->bitmapquals)
+ + ]
973 : : {
974 : 41872 : result += get_indexpath_pages((Path *) lfirst(l));
975 : : }
976 : : }
977 [ + + ]: 147357 : else if (IsA(bitmapqual, BitmapOrPath))
978 : : {
979 : 181 : BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
980 : :
981 [ + - + + : 553 : foreach(l, opath->bitmapquals)
+ + ]
982 : : {
983 : 372 : result += get_indexpath_pages((Path *) lfirst(l));
984 : : }
985 : : }
986 [ + - ]: 147176 : else if (IsA(bitmapqual, IndexPath))
987 : : {
988 : 147176 : IndexPath *ipath = (IndexPath *) bitmapqual;
989 : :
990 : 147176 : result = (double) ipath->indexinfo->pages;
991 : : }
992 : : else
7328 tgl@sss.pgh.pa.us 993 [ # # ]:UBC 0 : elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
994 : :
7328 tgl@sss.pgh.pa.us 995 :CBC 168293 : 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
7799 1013 : 456506 : cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
1014 : : ParamPathInfo *param_info,
1015 : : Path *bitmapqual, double loop_count)
1016 : : {
7846 1017 : 456506 : Cost startup_cost = 0;
1018 : 456506 : 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;
257 rhaas@postgresql.org 1029 : 456506 : uint64 enable_mask = PGS_BITMAPSCAN;
1030 : :
1031 : : /* Should only be applied to base relations */
7846 tgl@sss.pgh.pa.us 1032 [ - + ]: 456506 : Assert(IsA(baserel, RelOptInfo));
1033 [ - + ]: 456506 : Assert(baserel->relid > 0);
1034 [ - + ]: 456506 : Assert(baserel->rtekind == RTE_RELATION);
1035 : :
1036 : : /* Mark the path with the correct row estimate */
5289 1037 [ + + ]: 456506 : if (param_info)
1038 : 215914 : path->rows = param_info->ppi_rows;
1039 : : else
5372 1040 : 240592 : path->rows = baserel->rows;
1041 : :
3545 rhaas@postgresql.org 1042 : 456506 : pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
1043 : : loop_count, &indexTotalCost,
1044 : : &tuples_fetched);
1045 : :
7844 tgl@sss.pgh.pa.us 1046 : 456506 : startup_cost += indexTotalCost;
3545 rhaas@postgresql.org 1047 [ + + ]: 456506 : T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1048 : :
1049 : : /* Fetch estimated page costs for tablespace containing table. */
6124 1050 : 456506 : 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 : : */
7843 tgl@sss.pgh.pa.us 1061 [ + + ]: 456506 : if (pages_fetched >= 2.0)
6124 rhaas@postgresql.org 1062 : 83747 : cost_per_page = spc_random_page_cost -
1063 : 83747 : (spc_random_page_cost - spc_seq_page_cost)
1064 : 83747 : * sqrt(pages_fetched / T);
1065 : : else
1066 : 372759 : cost_per_page = spc_random_page_cost;
1067 : :
7844 tgl@sss.pgh.pa.us 1068 : 456506 : 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 : : */
5289 1079 : 456506 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1080 : :
1081 : 456506 : startup_cost += qpqual_cost.startup;
1082 : 456506 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
3505 rhaas@postgresql.org 1083 : 456506 : cpu_run_cost = cpu_per_tuple * tuples_fetched;
1084 : :
1085 : : /* Adjust costing for parallelism, if used. */
1086 [ + + ]: 456506 : if (path->parallel_workers > 0)
1087 : : {
1088 : 3137 : double parallel_divisor = get_parallel_divisor(path);
1089 : :
1090 : : /* The CPU cost is divided among all the workers. */
1091 : 3137 : cpu_run_cost /= parallel_divisor;
1092 : :
1093 : 3137 : path->rows = clamp_row_est(path->rows / parallel_divisor);
1094 : : }
1095 : : else
257 1096 : 453369 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1097 : :
1098 : :
3505 1099 : 456506 : run_cost += cpu_run_cost;
1100 : :
1101 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 tgl@sss.pgh.pa.us 1102 : 456506 : startup_cost += path->pathtarget->cost.startup;
1103 : 456506 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1104 : :
257 rhaas@postgresql.org 1105 : 456506 : path->disabled_nodes =
1106 : 456506 : (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
7846 tgl@sss.pgh.pa.us 1107 : 456506 : path->startup_cost = startup_cost;
1108 : 456506 : path->total_cost = startup_cost + run_cost;
1109 : 456506 : }
1110 : :
1111 : : /*
1112 : : * cost_bitmap_tree_node
1113 : : * Extract cost and selectivity from a bitmap tree node (index/and/or)
1114 : : */
1115 : : void
7844 1116 : 866944 : cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
1117 : : {
1118 [ + + ]: 866944 : if (IsA(path, IndexPath))
1119 : : {
1120 : 818155 : *cost = ((IndexPath *) path)->indextotalcost;
1121 : 818155 : *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 : : */
5372 1129 : 818155 : *cost += 0.1 * cpu_operator_cost * path->rows;
1130 : : }
7844 1131 [ + + ]: 48789 : else if (IsA(path, BitmapAndPath))
1132 : : {
1133 : 44472 : *cost = path->total_cost;
1134 : 44472 : *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1135 : : }
1136 [ + - ]: 4317 : else if (IsA(path, BitmapOrPath))
1137 : : {
1138 : 4317 : *cost = path->total_cost;
1139 : 4317 : *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1140 : : }
1141 : : else
1142 : : {
7844 tgl@sss.pgh.pa.us 1143 [ # # ]:UBC 0 : elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1144 : : *cost = *selec = 0; /* keep compiler quiet */
1145 : : }
7844 tgl@sss.pgh.pa.us 1146 :CBC 866944 : }
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
7799 1159 : 44335 : 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 : : */
7844 1174 : 44335 : totalCost = 0.0;
1175 : 44335 : selec = 1.0;
1176 [ + - + + : 133005 : foreach(l, path->bitmapquals)
+ + ]
1177 : : {
7667 bruce@momjian.us 1178 : 88670 : Path *subpath = (Path *) lfirst(l);
1179 : : Cost subCost;
1180 : : Selectivity subselec;
1181 : :
7844 tgl@sss.pgh.pa.us 1182 : 88670 : cost_bitmap_tree_node(subpath, &subCost, &subselec);
1183 : :
1184 : 88670 : selec *= subselec;
1185 : :
1186 : 88670 : totalCost += subCost;
1187 [ + + ]: 88670 : if (l != list_head(path->bitmapquals))
1188 : 44335 : totalCost += 100.0 * cpu_operator_cost;
1189 : : }
1190 : 44335 : path->bitmapselectivity = selec;
5372 1191 : 44335 : path->path.rows = 0; /* per above, not used */
782 rhaas@postgresql.org 1192 : 44335 : path->path.disabled_nodes = 0;
7844 tgl@sss.pgh.pa.us 1193 : 44335 : path->path.startup_cost = totalCost;
1194 : 44335 : path->path.total_cost = totalCost;
1195 : 44335 : }
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
7799 1204 : 1688 : 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 : : */
7844 1220 : 1688 : totalCost = 0.0;
1221 : 1688 : selec = 0.0;
1222 [ + - + + : 3973 : foreach(l, path->bitmapquals)
+ + ]
1223 : : {
7667 bruce@momjian.us 1224 : 2285 : Path *subpath = (Path *) lfirst(l);
1225 : : Cost subCost;
1226 : : Selectivity subselec;
1227 : :
7844 tgl@sss.pgh.pa.us 1228 : 2285 : cost_bitmap_tree_node(subpath, &subCost, &subselec);
1229 : :
1230 : 2285 : selec += subselec;
1231 : :
1232 : 2285 : totalCost += subCost;
1233 [ + + ]: 2285 : if (l != list_head(path->bitmapquals) &&
1234 [ - + ]: 597 : !IsA(subpath, IndexPath))
7844 tgl@sss.pgh.pa.us 1235 :UBC 0 : totalCost += 100.0 * cpu_operator_cost;
1236 : : }
7844 tgl@sss.pgh.pa.us 1237 [ + - ]:CBC 1688 : path->bitmapselectivity = Min(selec, 1.0);
5372 1238 : 1688 : path->path.rows = 0; /* per above, not used */
7844 1239 : 1688 : path->path.startup_cost = totalCost;
1240 : 1688 : path->path.total_cost = totalCost;
1241 : 1688 : }
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
7799 1252 : 643 : cost_tidscan(Path *path, PlannerInfo *root,
1253 : : RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
1254 : : {
9736 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;
257 rhaas@postgresql.org 1263 : 643 : uint64 enable_mask = 0;
1264 : :
1265 : : /* Should only be applied to base relations */
8647 tgl@sss.pgh.pa.us 1266 [ - + ]: 643 : Assert(baserel->relid > 0);
8919 1267 [ - + ]: 643 : Assert(baserel->rtekind == RTE_RELATION);
782 rhaas@postgresql.org 1268 [ - + ]: 643 : Assert(tidquals != NIL);
1269 : :
1270 : : /* Mark the path with the correct row estimate */
5160 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 */
7625 1277 : 643 : ntuples = 0;
1278 [ + - + + : 1307 : foreach(l, tidquals)
+ + ]
1279 : : {
2843 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 : : */
257 rhaas@postgresql.org 1288 [ - + - - ]: 664 : Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0 || IsA(qual, CurrentOfExpr));
782 1289 [ + + - + ]: 664 : Assert(list_length(tidquals) == 1 || !IsA(qual, CurrentOfExpr));
1290 : :
2843 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;
7313 bruce@momjian.us 1295 : 41 : Node *arraynode = (Node *) lsecond(saop->args);
1296 : :
1012 tgl@sss.pgh.pa.us 1297 : 41 : ntuples += estimate_array_length(root, arraynode);
1298 : : }
2843 1299 [ + + ]: 623 : else if (IsA(qual, CurrentOfExpr))
1300 : : {
1301 : : /* CURRENT OF yields 1 tuple */
6928 1302 : 344 : ntuples++;
1303 : : }
1304 : : else
1305 : : {
1306 : : /* It's just CTID = something, count 1 tuple */
7625 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 : : */
7063 1315 : 643 : cost_qual_eval(&tid_qual_cost, tidquals, root);
1316 : :
1317 : : /* fetch estimated page cost for tablespace containing table */
6124 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 */
5160 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 -
7063 1331 : 643 : tid_qual_cost.per_tuple;
9736 1332 : 643 : run_cost += cpu_per_tuple * ntuples;
1333 : :
1334 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 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 : : */
257 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;
9736 tgl@sss.pgh.pa.us 1348 : 643 : path->startup_cost = startup_cost;
1349 : 643 : path->total_cost = startup_cost + run_cost;
9820 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
2053 drowley@postgresql.o 1362 : 1683 : 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;
257 rhaas@postgresql.org 1378 : 1683 : uint64 enable_mask = PGS_TIDSCAN;
1379 : :
1380 : : /* Should only be applied to base relations */
2053 drowley@postgresql.o 1381 [ - + ]: 1683 : Assert(baserel->relid > 0);
1382 [ - + ]: 1683 : Assert(baserel->rtekind == RTE_RELATION);
1383 : :
1384 : : /* Mark the path with the correct row estimate */
1385 [ - + ]: 1683 : if (param_info)
2053 drowley@postgresql.o 1386 :UBC 0 : path->rows = param_info->ppi_rows;
1387 : : else
2053 drowley@postgresql.o 1388 :CBC 1683 : path->rows = baserel->rows;
1389 : :
1390 : : /* Count how many tuples and pages we expect to scan */
1391 : 1683 : selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1392 : : JOIN_INNER, NULL);
1393 : 1683 : pages = ceil(selectivity * baserel->pages);
1394 : :
1395 [ + + ]: 1683 : 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 : 1683 : ntuples = selectivity * baserel->tuples;
1407 : 1683 : 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 : 1683 : cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1414 : :
1415 : : /* fetch estimated page cost for tablespace containing table */
1416 : 1683 : 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 */
319 1421 : 1683 : disk_run_cost = spc_random_page_cost + spc_seq_page_cost * nseqpages;
1422 : :
1423 : : /* Add scanning CPU costs */
2053 1424 : 1683 : 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 : : */
319 1433 : 1683 : startup_cost = qpqual_cost.startup + tid_qual_cost.per_tuple;
2053 1434 : 1683 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1435 : 1683 : tid_qual_cost.per_tuple;
319 1436 : 1683 : cpu_run_cost = cpu_per_tuple * ntuples;
1437 : :
1438 : : /* tlist eval costs are paid per output row, not per tuple scanned */
2053 1439 : 1683 : startup_cost += path->pathtarget->cost.startup;
319 1440 : 1683 : cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
1441 : :
1442 : : /* Adjust costing for parallelism, if used. */
1443 [ + + ]: 1683 : 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 : : */
257 rhaas@postgresql.org 1461 [ - + ]: 1683 : Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0);
1462 [ + + ]: 1683 : if (path->parallel_workers == 0)
1463 : 1643 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1464 : 1683 : path->disabled_nodes =
1465 : 1683 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
2053 drowley@postgresql.o 1466 : 1683 : path->startup_cost = startup_cost;
319 1467 : 1683 : path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
2053 1468 : 1683 : }
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
3871 tgl@sss.pgh.pa.us 1479 : 48747 : 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;
257 rhaas@postgresql.org 1488 : 48747 : uint64 enable_mask = 0;
1489 : :
1490 : : /* Should only be applied to base relations that are subqueries */
8491 tgl@sss.pgh.pa.us 1491 [ - + ]: 48747 : Assert(baserel->relid > 0);
1492 [ - + ]: 48747 : 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 : : */
5289 1500 [ + + ]: 48747 : if (param_info)
1622 1501 : 1040 : qpquals = list_concat_copy(param_info->ppi_clauses,
1502 : 1040 : baserel->baserestrictinfo);
1503 : : else
1504 : 47707 : qpquals = baserel->baserestrictinfo;
1505 : :
1506 : 48747 : path->path.rows = clamp_row_est(path->subpath->rows *
1507 : 48747 : 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 : : */
257 rhaas@postgresql.org 1519 [ + + ]: 48747 : if (path->path.parallel_workers == 0)
1520 : 48692 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1521 : 48747 : path->path.disabled_nodes = path->subpath->disabled_nodes
1522 : 48747 : + (((baserel->pgs_mask & enable_mask) != enable_mask) ? 1 : 0);
3871 tgl@sss.pgh.pa.us 1523 : 48747 : path->path.startup_cost = path->subpath->startup_cost;
1524 : 48747 : 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 : : */
1546 1539 [ + + + + ]: 48747 : if (qpquals == NIL && trivial_pathtarget)
1540 : 22155 : return;
1541 : :
5289 1542 : 26592 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1543 : :
1544 : 26592 : startup_cost = qpqual_cost.startup;
1545 : 26592 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1622 1546 : 26592 : run_cost = cpu_per_tuple * path->subpath->rows;
1547 : :
1548 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3871 1549 : 26592 : startup_cost += path->path.pathtarget->cost.startup;
1550 : 26592 : run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1551 : :
1552 : 26592 : path->path.startup_cost += startup_cost;
1553 : 26592 : 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
5179 1564 : 35218 : cost_functionscan(Path *path, PlannerInfo *root,
1565 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1566 : : {
8919 1567 : 35218 : Cost startup_cost = 0;
1568 : 35218 : Cost run_cost = 0;
1569 : : QualCost qpqual_cost;
1570 : : Cost cpu_per_tuple;
1571 : : RangeTblEntry *rte;
1572 : : QualCost exprcost;
257 rhaas@postgresql.org 1573 : 35218 : uint64 enable_mask = 0;
1574 : :
1575 : : /* Should only be applied to base relations that are functions */
8647 tgl@sss.pgh.pa.us 1576 [ - + ]: 35218 : Assert(baserel->relid > 0);
7114 1577 [ + - ]: 35218 : rte = planner_rt_fetch(baserel->relid, root);
7203 1578 [ - + ]: 35218 : Assert(rte->rtekind == RTE_FUNCTION);
1579 : :
1580 : : /* Mark the path with the correct row estimate */
5179 1581 [ + + ]: 35218 : if (param_info)
1582 : 4323 : path->rows = param_info->ppi_rows;
1583 : : else
1584 : 30895 : 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 : : */
4708 1599 : 35218 : cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1600 : :
6239 1601 : 35218 : startup_cost += exprcost.startup + exprcost.per_tuple;
1602 : :
1603 : : /* Add scanning CPU costs */
5179 1604 : 35218 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1605 : :
1606 : 35218 : startup_cost += qpqual_cost.startup;
1607 : 35218 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
8919 1608 : 35218 : run_cost += cpu_per_tuple * baserel->tuples;
1609 : :
1610 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 1611 : 35218 : startup_cost += path->pathtarget->cost.startup;
1612 : 35218 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1613 : :
257 rhaas@postgresql.org 1614 [ + - ]: 35218 : if (path->parallel_workers == 0)
1615 : 35218 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1616 : 35218 : path->disabled_nodes =
1617 : 35218 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
8919 tgl@sss.pgh.pa.us 1618 : 35218 : path->startup_cost = startup_cost;
1619 : 35218 : path->total_cost = startup_cost + run_cost;
1620 : 35218 : }
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
3505 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;
257 rhaas@postgresql.org 1639 : 602 : uint64 enable_mask = 0;
1640 : :
1641 : : /* Should only be applied to base relations that are functions */
3505 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 : :
257 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;
3505 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
5174 tgl@sss.pgh.pa.us 1691 : 6779 : cost_valuesscan(Path *path, PlannerInfo *root,
1692 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1693 : : {
7376 mail@joeconway.com 1694 : 6779 : Cost startup_cost = 0;
1695 : 6779 : Cost run_cost = 0;
1696 : : QualCost qpqual_cost;
1697 : : Cost cpu_per_tuple;
257 rhaas@postgresql.org 1698 : 6779 : uint64 enable_mask = 0;
1699 : :
1700 : : /* Should only be applied to base relations that are values lists */
7376 mail@joeconway.com 1701 [ - + ]: 6779 : Assert(baserel->relid > 0);
1702 [ - + ]: 6779 : Assert(baserel->rtekind == RTE_VALUES);
1703 : :
1704 : : /* Mark the path with the correct row estimate */
5174 tgl@sss.pgh.pa.us 1705 [ + + ]: 6779 : if (param_info)
1706 : 55 : path->rows = param_info->ppi_rows;
1707 : : else
1708 : 6724 : 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 : : */
7376 mail@joeconway.com 1714 : 6779 : cpu_per_tuple = cpu_operator_cost;
1715 : :
1716 : : /* Add scanning CPU costs */
5174 tgl@sss.pgh.pa.us 1717 : 6779 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1718 : :
1719 : 6779 : startup_cost += qpqual_cost.startup;
1720 : 6779 : cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
7376 mail@joeconway.com 1721 : 6779 : run_cost += cpu_per_tuple * baserel->tuples;
1722 : :
1723 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 tgl@sss.pgh.pa.us 1724 : 6779 : startup_cost += path->pathtarget->cost.startup;
1725 : 6779 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1726 : :
257 rhaas@postgresql.org 1727 [ + - ]: 6779 : if (path->parallel_workers == 0)
1728 : 6779 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1729 : 6779 : path->disabled_nodes =
1730 : 6779 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
7376 mail@joeconway.com 1731 : 6779 : path->startup_cost = startup_cost;
1732 : 6779 : path->total_cost = startup_cost + run_cost;
1733 : 6779 : }
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
5160 tgl@sss.pgh.pa.us 1746 : 4009 : cost_ctescan(Path *path, PlannerInfo *root,
1747 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1748 : : {
6582 1749 : 4009 : Cost startup_cost = 0;
1750 : 4009 : Cost run_cost = 0;
1751 : : QualCost qpqual_cost;
1752 : : Cost cpu_per_tuple;
257 rhaas@postgresql.org 1753 : 4009 : uint64 enable_mask = 0;
1754 : :
1755 : : /* Should only be applied to base relations that are CTEs */
6582 tgl@sss.pgh.pa.us 1756 [ - + ]: 4009 : Assert(baserel->relid > 0);
1757 [ - + ]: 4009 : Assert(baserel->rtekind == RTE_CTE);
1758 : :
1759 : : /* Mark the path with the correct row estimate */
5160 1760 [ - + ]: 4009 : if (param_info)
5160 tgl@sss.pgh.pa.us 1761 :UBC 0 : path->rows = param_info->ppi_rows;
1762 : : else
5160 tgl@sss.pgh.pa.us 1763 :CBC 4009 : path->rows = baserel->rows;
1764 : :
1765 : : /* Charge one CPU tuple cost per row for tuplestore manipulation */
6582 1766 : 4009 : cpu_per_tuple = cpu_tuple_cost;
1767 : :
1768 : : /* Add scanning CPU costs */
5160 1769 : 4009 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1770 : :
1771 : 4009 : startup_cost += qpqual_cost.startup;
1772 : 4009 : cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
6582 1773 : 4009 : run_cost += cpu_per_tuple * baserel->tuples;
1774 : :
1775 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 1776 : 4009 : startup_cost += path->pathtarget->cost.startup;
1777 : 4009 : run_cost += path->pathtarget->cost.per_tuple * path->rows;
1778 : :
257 rhaas@postgresql.org 1779 [ + - ]: 4009 : if (path->parallel_workers == 0)
1780 : 4009 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1781 : 4009 : path->disabled_nodes =
1782 : 4009 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
6582 tgl@sss.pgh.pa.us 1783 : 4009 : path->startup_cost = startup_cost;
1784 : 4009 : path->total_cost = startup_cost + run_cost;
1785 : 4009 : }
1786 : :
1787 : : /*
1788 : : * cost_namedtuplestorescan
1789 : : * Determines and returns the cost of scanning a named tuplestore.
1790 : : */
1791 : : void
3482 kgrittn@postgresql.o 1792 : 407 : cost_namedtuplestorescan(Path *path, PlannerInfo *root,
1793 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1794 : : {
1795 : 407 : Cost startup_cost = 0;
1796 : 407 : Cost run_cost = 0;
1797 : : QualCost qpqual_cost;
1798 : : Cost cpu_per_tuple;
257 rhaas@postgresql.org 1799 : 407 : uint64 enable_mask = 0;
1800 : :
1801 : : /* Should only be applied to base relations that are Tuplestores */
3482 kgrittn@postgresql.o 1802 [ - + ]: 407 : Assert(baserel->relid > 0);
1803 [ - + ]: 407 : Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1804 : :
1805 : : /* Mark the path with the correct row estimate */
1806 [ - + ]: 407 : if (param_info)
3482 kgrittn@postgresql.o 1807 :UBC 0 : path->rows = param_info->ppi_rows;
1808 : : else
3482 kgrittn@postgresql.o 1809 :CBC 407 : path->rows = baserel->rows;
1810 : :
1811 : : /* Charge one CPU tuple cost per row for tuplestore manipulation */
1812 : 407 : cpu_per_tuple = cpu_tuple_cost;
1813 : :
1814 : : /* Add scanning CPU costs */
1815 : 407 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1816 : :
1817 : 407 : startup_cost += qpqual_cost.startup;
1818 : 407 : cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1819 : 407 : run_cost += cpu_per_tuple * baserel->tuples;
1820 : :
257 rhaas@postgresql.org 1821 [ + - ]: 407 : if (path->parallel_workers == 0)
1822 : 407 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1823 : 407 : path->disabled_nodes =
1824 : 407 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
3482 kgrittn@postgresql.o 1825 : 407 : path->startup_cost = startup_cost;
1826 : 407 : path->total_cost = startup_cost + run_cost;
1827 : 407 : }
1828 : :
1829 : : /*
1830 : : * cost_resultscan
1831 : : * Determines and returns the cost of scanning an RTE_RESULT relation.
1832 : : */
1833 : : void
2814 tgl@sss.pgh.pa.us 1834 : 3812 : cost_resultscan(Path *path, PlannerInfo *root,
1835 : : RelOptInfo *baserel, ParamPathInfo *param_info)
1836 : : {
1837 : 3812 : Cost startup_cost = 0;
1838 : 3812 : Cost run_cost = 0;
1839 : : QualCost qpqual_cost;
1840 : : Cost cpu_per_tuple;
257 rhaas@postgresql.org 1841 : 3812 : uint64 enable_mask = 0;
1842 : :
1843 : : /* Should only be applied to RTE_RESULT base relations */
2814 tgl@sss.pgh.pa.us 1844 [ - + ]: 3812 : Assert(baserel->relid > 0);
1845 [ - + ]: 3812 : Assert(baserel->rtekind == RTE_RESULT);
1846 : :
1847 : : /* Mark the path with the correct row estimate */
1848 [ + + ]: 3812 : if (param_info)
1849 : 225 : path->rows = param_info->ppi_rows;
1850 : : else
1851 : 3587 : path->rows = baserel->rows;
1852 : :
1853 : : /* We charge qual cost plus cpu_tuple_cost */
1854 : 3812 : get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1855 : :
1856 : 3812 : startup_cost += qpqual_cost.startup;
1857 : 3812 : cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1858 : 3812 : run_cost += cpu_per_tuple * baserel->tuples;
1859 : :
257 rhaas@postgresql.org 1860 [ + - ]: 3812 : if (path->parallel_workers == 0)
1861 : 3812 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1862 : 3812 : path->disabled_nodes =
1863 : 3812 : (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
2814 tgl@sss.pgh.pa.us 1864 : 3812 : path->startup_cost = startup_cost;
1865 : 3812 : path->total_cost = startup_cost + run_cost;
1866 : 3812 : }
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
3871 1876 : 692 : cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
1877 : : {
1878 : : Cost startup_cost;
1879 : : Cost total_cost;
1880 : : double total_rows;
257 rhaas@postgresql.org 1881 : 692 : uint64 enable_mask = 0;
1882 : :
1883 : : /* We probably have decent estimates for the non-recursive term */
6582 tgl@sss.pgh.pa.us 1884 : 692 : startup_cost = nrterm->startup_cost;
1885 : 692 : total_cost = nrterm->total_cost;
3871 1886 : 692 : 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 : : */
6582 1894 : 692 : total_cost += 10 * rterm->total_cost;
3871 1895 : 692 : 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 : : */
6582 1902 : 692 : total_cost += cpu_tuple_cost * total_rows;
1903 : :
257 rhaas@postgresql.org 1904 [ + - ]: 692 : if (runion->parallel_workers == 0)
1905 : 692 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
1906 : 692 : runion->disabled_nodes =
1907 : 692 : (runion->parent->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
6582 tgl@sss.pgh.pa.us 1908 : 692 : runion->startup_cost = startup_cost;
1909 : 692 : runion->total_cost = total_cost;
3871 1910 : 692 : runion->rows = total_rows;
1911 : 692 : runion->pathtarget->width = Max(nrterm->pathtarget->width,
1912 : : rterm->pathtarget->width);
6582 1913 : 692 : }
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
1470 1952 : 1464907 : 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 : : {
7101 1957 : 1464907 : double input_bytes = relation_byte_size(tuples, width);
1958 : : double output_bytes;
1959 : : double output_tuples;
619 1960 : 1464907 : 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 : : */
9773 1966 [ + + ]: 1464907 : if (tuples < 2.0)
1967 : 430342 : tuples = 2.0;
1968 : :
1969 : : /* Include the default cost-per-comparison */
1470 1970 : 1464907 : comparison_cost += 2.0 * cpu_operator_cost;
1971 : :
1972 : : /* Do we have a useful LIMIT? */
7101 1973 [ + + + + ]: 1464907 : if (limit_tuples > 0 && limit_tuples < tuples)
1974 : : {
1975 : 1347 : output_tuples = limit_tuples;
1976 : 1347 : output_bytes = relation_byte_size(output_tuples, width);
1977 : : }
1978 : : else
1979 : : {
1980 : 1463560 : output_tuples = tuples;
1981 : 1463560 : output_bytes = input_bytes;
1982 : : }
1983 : :
5849 1984 [ + + ]: 1464907 : if (output_bytes > sort_mem_bytes)
1985 : : {
1986 : : /*
1987 : : * We'll have to use a disk-based sort of all the tuples
1988 : : */
7101 1989 : 10534 : double npages = ceil(input_bytes / BLCKSZ);
3839 rhaas@postgresql.org 1990 : 10534 : double nruns = input_bytes / sort_mem_bytes;
5849 tgl@sss.pgh.pa.us 1991 : 10534 : 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 : : */
1470 2000 : 10534 : *startup_cost = comparison_cost * tuples * LOG2(tuples);
2001 : :
2002 : : /* Disk costs */
2003 : :
2004 : : /* Compute logM(r) as log(r) / log(M) */
7540 2005 [ + + ]: 10534 : if (nruns > mergeorder)
2006 : 3389 : log_runs = ceil(log(nruns) / log(mergeorder));
2007 : : else
9773 2008 : 7145 : log_runs = 1.0;
9736 2009 : 10534 : npageaccesses = 2.0 * npages * log_runs;
2010 : : /* Assume 3/4ths of accesses are sequential, 1/4th are not */
2380 tomas.vondra@postgre 2011 : 10534 : *startup_cost += npageaccesses *
7434 tgl@sss.pgh.pa.us 2012 : 10534 : (seq_page_cost * 0.75 + random_page_cost * 0.25);
2013 : : }
5849 2014 [ + + - + ]: 1454373 : 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 : : */
1470 2022 : 897 : *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
2023 : : }
2024 : : else
2025 : : {
2026 : : /* We'll use plain quicksort on all the input tuples */
2027 : 1453476 : *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 : : */
2380 tomas.vondra@postgre 2038 : 1464907 : *run_cost = cpu_operator_cost * tuples;
2039 : 1464907 : }
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 : 9149 : 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 : 9149 : 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 : 9149 : List *presortedExprs = NIL;
2074 : : ListCell *l;
2363 2075 : 9149 : bool unknown_varno = false;
2076 : :
1396 drowley@postgresql.o 2077 [ + - - + ]: 9149 : 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 : : */
2380 tomas.vondra@postgre 2083 [ + + ]: 9149 : if (input_tuples < 2.0)
2084 : 5022 : input_tuples = 2.0;
2085 : :
2086 : : /* Default estimate of number of groups, capped to one group per row. */
2363 2087 [ + + ]: 9149 : 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 : : */
2380 2111 [ + - + - : 9228 : foreach(l, pathkeys)
+ - ]
2112 : : {
2113 : 9228 : PathKey *key = (PathKey *) lfirst(l);
2114 : 9228 : EquivalenceMember *member = (EquivalenceMember *)
1242 tgl@sss.pgh.pa.us 2115 : 9228 : 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 : : */
2090 2121 [ + + ]: 9228 : if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2122 : : {
2363 tomas.vondra@postgre 2123 : 7 : unknown_varno = true;
2124 : 7 : break;
2125 : : }
2126 : :
2127 : : /* expression not containing any Vars with "varno 0" */
2380 2128 : 9221 : presortedExprs = lappend(presortedExprs, member->em_expr);
2129 : :
1396 drowley@postgresql.o 2130 [ + + ]: 9221 : if (foreach_current_index(l) + 1 >= presorted_keys)
2380 tomas.vondra@postgre 2131 : 9142 : break;
2132 : : }
2133 : :
2134 : : /* Estimate the number of groups with equal presorted keys. */
2363 2135 [ + + ]: 9149 : if (!unknown_varno)
2022 drowley@postgresql.o 2136 : 9142 : input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2137 : : NULL, NULL);
2138 : :
2380 tomas.vondra@postgre 2139 : 9149 : group_tuples = input_tuples / input_groups;
2140 : 9149 : 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 : : */
1470 tgl@sss.pgh.pa.us 2146 : 9149 : 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 : : */
1396 drowley@postgresql.o 2154 : 9149 : 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 : 9149 : run_cost = group_run_cost + (group_run_cost + group_startup_cost) *
2164 : 9149 : (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 : : */
2380 tomas.vondra@postgre 2171 : 9149 : 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 : 9149 : run_cost += 2.0 * cpu_tuple_cost * input_groups;
2178 : :
2179 : 9149 : 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 : : */
782 rhaas@postgresql.org 2186 [ - + ]: 9149 : Assert(enable_incremental_sort);
2187 : 9149 : path->disabled_nodes = input_disabled_nodes;
2188 : :
2380 tomas.vondra@postgre 2189 : 9149 : path->startup_cost = startup_cost;
2190 : 9149 : path->total_cost = startup_cost + run_cost;
2191 : :
2192 : : /* set output parameter values */
62 drowley@postgresql.o 2193 [ + + ]:GNC 9149 : if (num_groups)
2194 : 7961 : *num_groups = input_groups;
2380 tomas.vondra@postgre 2195 :CBC 9149 : }
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 : 1455758 : 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 : :
1470 tgl@sss.pgh.pa.us 2220 : 1455758 : cost_tuplesort(&startup_cost, &run_cost,
2221 : : tuples, width,
2222 : : comparison_cost, sort_mem,
2223 : : limit_tuples);
2224 : :
2380 tomas.vondra@postgre 2225 : 1455758 : 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 : 1455758 : path->rows = tuples;
782 rhaas@postgresql.org 2232 : 1455758 : path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
9736 tgl@sss.pgh.pa.us 2233 : 1455758 : path->startup_cost = startup_cost;
2234 : 1455758 : path->total_cost = startup_cost + run_cost;
11052 scrappy@hub.org 2235 : 1455758 : }
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
3233 rhaas@postgresql.org 2244 : 21207 : 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 [ + + ]: 21207 : if (numpaths == 0)
2255 : 17175 : return 0;
2256 : :
2257 : : /*
2258 : : * Array length is number of workers or number of relevant paths,
2259 : : * whichever is less.
2260 : : */
2261 : 4032 : arrlen = Min(parallel_workers, numpaths);
306 michael@paquier.xyz 2262 : 4032 : costarr = palloc_array(Cost, arrlen);
2263 : :
2264 : : /* The first few paths will each be claimed by a different worker. */
3233 rhaas@postgresql.org 2265 : 4032 : path_index = 0;
2266 [ + - + + : 11692 : foreach(cell, subpaths)
+ + ]
2267 : : {
2268 : 8661 : Path *subpath = (Path *) lfirst(cell);
2269 : :
2270 [ + + ]: 8661 : if (path_index == arrlen)
2271 : 1001 : break;
2272 : 7660 : 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 : 4032 : 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 : : */
2646 tgl@sss.pgh.pa.us 2285 [ + - + + : 6699 : for_each_cell(l, subpaths, cell)
+ + ]
2286 : : {
3233 rhaas@postgresql.org 2287 : 3127 : Path *subpath = (Path *) lfirst(l);
2288 : :
2289 : : /* Consider only the non-partial paths */
2290 [ + + ]: 3127 : if (path_index++ == numpaths)
2291 : 460 : break;
2292 : :
2293 : 2667 : costarr[min_index] += subpath->total_cost;
2294 : :
2295 : : /* Update the new min cost array index */
1510 drowley@postgresql.o 2296 : 2667 : min_index = 0;
2297 [ + + ]: 8031 : for (int i = 0; i < arrlen; i++)
2298 : : {
3233 rhaas@postgresql.org 2299 [ + + ]: 5364 : if (costarr[i] < costarr[min_index])
2300 : 897 : min_index = i;
2301 : : }
2302 : : }
2303 : :
2304 : : /* Return the highest cost from the array */
1510 drowley@postgresql.o 2305 : 4032 : max_index = 0;
2306 [ + + ]: 11692 : for (int i = 0; i < arrlen; i++)
2307 : : {
3233 rhaas@postgresql.org 2308 [ + + ]: 7660 : if (costarr[i] > costarr[max_index])
2309 : 356 : max_index = i;
2310 : : }
2311 : :
2312 : 4032 : return costarr[max_index];
2313 : : }
2314 : :
2315 : : /*
2316 : : * cost_append
2317 : : * Determines and returns the cost of an Append node.
2318 : : */
2319 : : void
461 rguo@postgresql.org 2320 : 58090 : cost_append(AppendPath *apath, PlannerInfo *root)
2321 : : {
257 rhaas@postgresql.org 2322 : 58090 : RelOptInfo *rel = apath->path.parent;
2323 : : ListCell *l;
2324 : 58090 : uint64 enable_mask = PGS_APPEND;
2325 : :
2326 [ + + ]: 58090 : if (apath->path.parallel_workers == 0)
2327 : 36843 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
2328 : :
2329 : 58090 : apath->path.disabled_nodes =
2330 : 58090 : (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
3233 2331 : 58090 : apath->path.startup_cost = 0;
2332 : 58090 : apath->path.total_cost = 0;
2747 tgl@sss.pgh.pa.us 2333 : 58090 : apath->path.rows = 0;
2334 : :
3233 rhaas@postgresql.org 2335 [ + + ]: 58090 : if (apath->subpaths == NIL)
2336 : 1825 : return;
2337 : :
2338 [ + + ]: 56265 : if (!apath->path.parallel_aware)
2339 : : {
2747 tgl@sss.pgh.pa.us 2340 : 35058 : List *pathkeys = apath->path.pathkeys;
2341 : :
2342 [ + + ]: 35058 : if (pathkeys == NIL)
2343 : : {
1468 drowley@postgresql.o 2344 : 33217 : 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 : 33217 : 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 : : */
2747 tgl@sss.pgh.pa.us 2356 [ + - + + : 129915 : foreach(l, apath->subpaths)
+ + ]
2357 : : {
2358 : 96698 : Path *subpath = (Path *) lfirst(l);
2359 : :
2360 : 96698 : apath->path.rows += subpath->rows;
782 rhaas@postgresql.org 2361 : 96698 : apath->path.disabled_nodes += subpath->disabled_nodes;
2747 tgl@sss.pgh.pa.us 2362 : 96698 : 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 [ + - + + : 7177 : foreach(l, apath->subpaths)
+ + ]
2386 : : {
2387 : 5336 : Path *subpath = (Path *) lfirst(l);
2388 : : int presorted_keys;
2389 : : Path sort_path; /* dummy for result of
2390 : : * cost_sort/cost_incremental_sort */
2391 : :
461 rguo@postgresql.org 2392 [ + + ]: 5336 : 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 [ + - + + ]: 46 : 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 : 36 : cost_sort(&sort_path,
2424 : : root,
2425 : : pathkeys,
2426 : : subpath->disabled_nodes,
2427 : : subpath->total_cost,
2428 : : subpath->rows,
2429 : 36 : subpath->pathtarget->width,
2430 : : 0.0,
2431 : : work_mem,
2432 : : apath->limit_tuples);
2433 : : }
2434 : :
2747 tgl@sss.pgh.pa.us 2435 : 46 : subpath = &sort_path;
2436 : : }
2437 : :
2438 : 5336 : apath->path.rows += subpath->rows;
782 rhaas@postgresql.org 2439 : 5336 : apath->path.disabled_nodes += subpath->disabled_nodes;
2747 tgl@sss.pgh.pa.us 2440 : 5336 : apath->path.startup_cost += subpath->startup_cost;
2441 : 5336 : apath->path.total_cost += subpath->total_cost;
2442 : : }
2443 : : }
2444 : : }
2445 : : else /* parallel-aware */
2446 : : {
3233 rhaas@postgresql.org 2447 : 21207 : int i = 0;
2448 : 21207 : double parallel_divisor = get_parallel_divisor(&apath->path);
2449 : :
2450 : : /* Parallel-aware Append never produces ordered output. */
2747 tgl@sss.pgh.pa.us 2451 [ - + ]: 21207 : Assert(apath->path.pathkeys == NIL);
2452 : :
2453 : : /* Calculate startup cost. */
3233 rhaas@postgresql.org 2454 [ + - + + : 84084 : foreach(l, apath->subpaths)
+ + ]
2455 : : {
2456 : 62877 : 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 [ + + ]: 62877 : if (i == 0)
2464 : 21207 : apath->path.startup_cost = subpath->startup_cost;
2465 [ + + ]: 41670 : else if (i < apath->path.parallel_workers)
2466 [ + + ]: 20743 : 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 [ + + ]: 62877 : if (i < apath->first_partial_path)
2477 : 10327 : apath->path.rows += subpath->rows / parallel_divisor;
2478 : : else
2479 : : {
2480 : : double subpath_parallel_divisor;
2481 : :
3203 2482 : 52550 : subpath_parallel_divisor = get_parallel_divisor(subpath);
2483 : 52550 : apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2484 : : parallel_divisor);
3233 2485 : 52550 : apath->path.total_cost += subpath->total_cost;
2486 : : }
2487 : :
782 2488 : 62877 : apath->path.disabled_nodes += subpath->disabled_nodes;
3203 2489 : 62877 : apath->path.rows = clamp_row_est(apath->path.rows);
2490 : :
3233 2491 : 62877 : i++;
2492 : : }
2493 : :
2494 : : /* Add cost for non-partial subpaths. */
2495 : 21207 : apath->path.total_cost +=
2496 : 21207 : 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 : : */
3155 2505 : 56265 : apath->path.total_cost +=
2506 : 56265 : 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
5842 tgl@sss.pgh.pa.us 2535 : 7570 : 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 : : {
257 rhaas@postgresql.org 2541 : 7570 : RelOptInfo *rel = path->parent;
5842 tgl@sss.pgh.pa.us 2542 : 7570 : Cost startup_cost = 0;
2543 : 7570 : Cost run_cost = 0;
2544 : : Cost comparison_cost;
2545 : : double N;
2546 : : double logN;
257 rhaas@postgresql.org 2547 : 7570 : uint64 enable_mask = PGS_MERGE_APPEND;
2548 : :
2549 [ + - ]: 7570 : if (path->parallel_workers == 0)
2550 : 7570 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
2551 : :
2552 : : /*
2553 : : * Avoid log(0)...
2554 : : */
5842 tgl@sss.pgh.pa.us 2555 [ + - ]: 7570 : N = (n_streams < 2) ? 2.0 : (double) n_streams;
2556 : 7570 : logN = LOG2(N);
2557 : :
2558 : : /* Assumed cost per tuple comparison */
2559 : 7570 : comparison_cost = 2.0 * cpu_operator_cost;
2560 : :
2561 : : /* Heap creation cost */
2562 : 7570 : startup_cost += comparison_cost * N * logN;
2563 : :
2564 : : /* Per-tuple heap maintenance cost */
3628 2565 : 7570 : 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 : : */
3155 rhaas@postgresql.org 2571 : 7570 : run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2572 : :
257 2573 : 7570 : path->disabled_nodes =
2574 : 7570 : (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
2575 : 7570 : path->disabled_nodes += input_disabled_nodes;
5842 tgl@sss.pgh.pa.us 2576 : 7570 : path->startup_cost = startup_cost + input_startup_cost;
2577 : 7570 : path->total_cost = startup_cost + run_cost + input_total_cost;
2578 : 7570 : }
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
8717 2593 : 472964 : 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 : : {
6239 2598 : 472964 : Cost startup_cost = input_startup_cost;
2599 : 472964 : Cost run_cost = input_total_cost - input_startup_cost;
8717 2600 : 472964 : double nbytes = relation_byte_size(tuples, width);
619 2601 : 472964 : double work_mem_bytes = work_mem * (Size) 1024;
2602 : :
5372 2603 : 472964 : 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 : : */
6079 2617 : 472964 : 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 : : */
8287 2625 [ + + ]: 472964 : if (nbytes > work_mem_bytes)
2626 : : {
8717 2627 : 3133 : double npages = ceil(nbytes / BLCKSZ);
2628 : :
7434 2629 : 3133 : run_cost += seq_page_cost * npages;
2630 : : }
2631 : :
257 rhaas@postgresql.org 2632 : 472964 : path->disabled_nodes = input_disabled_nodes + (enabled ? 0 : 1);
8717 tgl@sss.pgh.pa.us 2633 : 472964 : path->startup_cost = startup_cost;
2634 : 472964 : path->total_cost = startup_cost + run_cost;
2635 : 472964 : }
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
1916 drowley@postgresql.o 2651 : 189854 : cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath,
2652 : : Cost *rescan_startup_cost, Cost *rescan_total_cost)
2653 : : {
2654 : : EstimationInfo estinfo;
2655 : : ListCell *lc;
2656 : 189854 : Cost input_startup_cost = mpath->subpath->startup_cost;
2657 : 189854 : Cost input_total_cost = mpath->subpath->total_cost;
2658 : 189854 : double tuples = mpath->subpath->rows;
440 2659 : 189854 : Cardinality est_calls = mpath->est_calls;
1916 2660 : 189854 : 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 */
1905 tgl@sss.pgh.pa.us 2672 : 189854 : 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 : : */
2019 drowley@postgresql.o 2680 : 189854 : est_entry_bytes = relation_byte_size(tuples, width) +
2681 : 189854 : ExecEstimateCacheEntryOverheadBytes(tuples);
2682 : :
2683 : : /* include the estimated width for the cache keys */
1302 2684 [ + - + + : 403119 : foreach(lc, mpath->param_exprs)
+ + ]
2685 : 213265 : 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 */
2019 2688 : 189854 : est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2689 : :
2690 : : /* estimate on the distinct number of parameter values */
440 2691 : 189854 : 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 : : */
2019 2702 [ + + ]: 189854 : if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
440 2703 : 11142 : ndistinct = est_calls;
2704 : :
2705 : : /* Remember the ndistinct estimate for EXPLAIN */
2706 : 189854 : 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 : : */
1916 2717 [ + + + - : 189854 : 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 : : */
2019 2726 [ + + ]: 189854 : 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 : : */
440 2734 : 379708 : hit_ratio = ((est_calls - ndistinct) / est_calls) *
1300 2735 [ + + ]: 189854 : (est_cache_entries / Max(ndistinct, est_cache_entries));
2736 : :
2737 : : /* Remember the hit ratio estimate for EXPLAIN */
440 2738 : 189854 : mpath->est_hit_ratio = hit_ratio;
2739 : :
1300 2740 [ + - - + ]: 189854 : 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 : : */
2019 2747 : 189854 : 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 : 189854 : 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 : 189854 : 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 : 189854 : 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 : 189854 : 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 : 189854 : startup_cost += cpu_tuple_cost;
2781 : :
2782 : 189854 : *rescan_startup_cost = startup_cost;
2783 : 189854 : *rescan_total_cost = total_cost;
2784 : 189854 : }
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
7799 tgl@sss.pgh.pa.us 2798 : 75665 : 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;
571 peter@eisentraut.org 2809 : 75665 : const AggClauseCosts dummy_aggcosts = {0};
2810 : :
2811 : : /* Use all-zero per-aggregate costs if NULL is passed */
5650 tgl@sss.pgh.pa.us 2812 [ + + ]: 75665 : if (aggcosts == NULL)
2813 : : {
2814 [ - + ]: 15280 : Assert(aggstrategy == AGG_HASHED);
2815 : 15280 : 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 : : */
8726 2840 [ + + ]: 75665 : if (aggstrategy == AGG_PLAIN)
2841 : : {
2842 : 33245 : startup_cost = input_total_cost;
5650 2843 : 33245 : startup_cost += aggcosts->transCost.startup;
2844 : 33245 : startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2802 2845 : 33245 : startup_cost += aggcosts->finalCost.startup;
2846 : 33245 : startup_cost += aggcosts->finalCost.per_tuple;
2847 : : /* we aren't grouping */
7716 2848 : 33245 : total_cost = startup_cost + cpu_tuple_cost;
5372 2849 : 33245 : output_tuples = 1;
2850 : :
2851 : : /* AGG_PLAIN neither hashes nor sorts, so neither switch disables it */
2852 : : }
3486 rhodiumtoad@postgres 2853 [ + + + + ]: 42420 : else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2854 : : {
2855 : : /* Here we are able to deliver output on-the-fly */
8726 tgl@sss.pgh.pa.us 2856 : 16066 : startup_cost = input_startup_cost;
2857 : 16066 : total_cost = input_total_cost;
2858 : : /* calcs phrased this way to match HASHED case, see note above */
5650 2859 : 16066 : total_cost += aggcosts->transCost.startup;
2860 : 16066 : total_cost += aggcosts->transCost.per_tuple * input_tuples;
2861 : 16066 : total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2802 2862 : 16066 : total_cost += aggcosts->finalCost.startup;
2863 : 16066 : total_cost += aggcosts->finalCost.per_tuple * numGroups;
7716 2864 : 16066 : total_cost += cpu_tuple_cost * numGroups;
5372 2865 : 16066 : 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 : : */
95 rguo@postgresql.org 2879 [ + + ]:GNC 16066 : if (aggstrategy == AGG_MIXED)
2880 : : {
2881 [ + + ]: 966 : if (!enable_hashagg)
2882 : 460 : ++disabled_nodes;
2883 : : }
2884 [ + + + + ]: 15100 : else if (numGroupCols > 0 && !enable_groupagg) /* AGG_SORTED */
2885 : 90 : ++disabled_nodes;
2886 : : }
2887 : : else
2888 : : {
2889 : : /* must be AGG_HASHED */
8726 tgl@sss.pgh.pa.us 2890 :CBC 26354 : startup_cost = input_total_cost;
5650 2891 : 26354 : startup_cost += aggcosts->transCost.startup;
2892 : 26354 : startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2893 : : /* cost of computing hash value */
2894 : 26354 : startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2802 2895 : 26354 : startup_cost += aggcosts->finalCost.startup;
2896 : :
8726 2897 : 26354 : total_cost = startup_cost;
2802 2898 : 26354 : total_cost += aggcosts->finalCost.per_tuple * numGroups;
2899 : : /* cost of retrieving from hash table */
7716 2900 : 26354 : total_cost += cpu_tuple_cost * numGroups;
5372 2901 : 26354 : output_tuples = numGroups;
2902 : :
2903 : : /* AGG_HASHED is disabled when enable_hashagg is off */
95 rguo@postgresql.org 2904 [ + + ]:GNC 26354 : if (!enable_hashagg)
2905 : 1814 : ++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 : : */
2399 jdavis@postgresql.or 2921 [ + + + + ]:CBC 75665 : if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2922 : : {
2923 : : double pages;
2342 tgl@sss.pgh.pa.us 2924 : 27320 : double pages_written = 0.0;
2925 : 27320 : 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 : : */
2148 heikki.linnakangas@i 2939 : 27320 : hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2940 : : input_width,
2342 tgl@sss.pgh.pa.us 2941 : 27320 : aggcosts->transitionSpace);
2399 jdavis@postgresql.or 2942 : 27320 : hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2943 : : &ngroups_limit, &num_partitions);
2944 : :
2342 tgl@sss.pgh.pa.us 2945 [ - + ]: 27320 : nbatches = Max((numGroups * hashentrysize) / mem_limit,
2946 : : numGroups / ngroups_limit);
2947 : :
2389 jdavis@postgresql.or 2948 [ + + ]: 27320 : nbatches = Max(ceil(nbatches), 1.0);
2949 : 27320 : 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 : : */
2342 tgl@sss.pgh.pa.us 2956 : 27320 : 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 : : */
2389 jdavis@postgresql.or 2962 : 27320 : pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2963 : 27320 : 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 : : */
2226 2969 : 27320 : pages_read *= 2.0;
2970 : 27320 : pages_written *= 2.0;
2971 : :
2399 2972 : 27320 : startup_cost += pages_written * random_page_cost;
2973 : 27320 : total_cost += pages_written * random_page_cost;
2974 : 27320 : total_cost += pages_read * seq_page_cost;
2975 : :
2976 : : /* account for CPU cost of spilling a tuple and reading it back */
2226 2977 : 27320 : spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2978 : 27320 : startup_cost += spill_cost;
2979 : 27320 : total_cost += spill_cost;
2980 : : }
2981 : :
2982 : : /*
2983 : : * If there are quals (HAVING quals), account for their cost and
2984 : : * selectivity.
2985 : : */
3266 tgl@sss.pgh.pa.us 2986 [ + + ]: 75665 : if (quals)
2987 : : {
2988 : : QualCost qual_cost;
2989 : :
2990 : 4008 : cost_qual_eval(&qual_cost, quals, root);
2991 : 4008 : startup_cost += qual_cost.startup;
2992 : 4008 : total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2993 : :
2994 : 4008 : output_tuples = clamp_row_est(output_tuples *
2995 : 4008 : clauselist_selectivity(root,
2996 : : quals,
2997 : : 0,
2998 : : JOIN_INNER,
2999 : : NULL));
3000 : : }
3001 : :
5372 3002 : 75665 : path->rows = output_tuples;
782 rhaas@postgresql.org 3003 : 75665 : path->disabled_nodes = disabled_nodes;
8726 tgl@sss.pgh.pa.us 3004 : 75665 : path->startup_cost = startup_cost;
3005 : 75665 : path->total_cost = total_cost;
3006 : 75665 : }
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
1165 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 : : */
1165 drowley@postgresql.o 3104 :UBC 0 : Assert(false);
3105 : : return_tuples = 1.0;
3106 : : }
3107 : : }
1165 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 : : */
1165 drowley@postgresql.o 3135 :UBC 0 : end_offset_value = 1.0;
3136 : : }
3137 : : else
3138 : : {
1165 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 : : */
1165 drowley@postgresql.o 3167 :UBC 0 : end_offset_value =
3168 : 0 : partition_tuples / peer_tuples * DEFAULT_INEQ_SEL;
3169 : : }
3170 : :
1165 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 : : */
1165 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 : :
1165 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
6497 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 : :
1165 drowley@postgresql.o 3249 : 2654 : numPartCols = list_length(winclause->partitionClause);
3250 : 2654 : numOrderCols = list_length(winclause->orderClause);
3251 : :
6497 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 : : */
5650 3264 [ + - + + : 6041 : foreach(lc, windowFuncs)
+ + ]
3265 : : {
3472 3266 : 3387 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3267 : : Cost wfunccost;
3268 : : QualCost argcosts;
3269 : :
2802 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 */
5650 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 : : */
4836 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 : :
5650 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;
6497 3301 : 2654 : total_cost += cpu_tuple_cost * input_tuples;
3302 : :
5372 3303 : 2654 : path->rows = input_tuples;
782 rhaas@postgresql.org 3304 : 2654 : path->disabled_nodes = input_disabled_nodes;
6497 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 : : */
1165 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);
6497 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
7799 3333 : 1058 : 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 : :
3266 3344 : 1058 : output_tuples = numGroups;
8726 3345 : 1058 : startup_cost = input_startup_cost;
3346 : 1058 : 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 : 1058 : 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 : : */
3266 3358 [ - + ]: 1058 : if (quals)
3359 : : {
3360 : : QualCost qual_cost;
3361 : :
3266 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 : :
3266 tgl@sss.pgh.pa.us 3374 :CBC 1058 : path->rows = output_tuples;
95 rguo@postgresql.org 3375 :GNC 1058 : path->disabled_nodes = input_disabled_nodes + (enable_groupagg ? 0 : 1);
8726 tgl@sss.pgh.pa.us 3376 :CBC 1058 : path->startup_cost = startup_cost;
3377 : 1058 : path->total_cost = total_cost;
3378 : 1058 : }
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
5372 3405 : 2458908 : 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;
9736 3411 : 2458908 : Cost startup_cost = 0;
3412 : 2458908 : Cost run_cost = 0;
5372 3413 : 2458908 : 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. */
257 rhaas@postgresql.org 3420 : 2458908 : disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
782 3421 : 2458908 : disabled_nodes += inner_path->disabled_nodes;
3422 : 2458908 : disabled_nodes += outer_path->disabled_nodes;
3423 : :
3424 : : /* estimate costs to rescan the inner relation */
6239 tgl@sss.pgh.pa.us 3425 : 2458908 : 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 : : */
9736 3437 : 2458908 : startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3438 : 2458908 : run_cost += outer_path->total_cost - outer_path->startup_cost;
6239 3439 [ + + ]: 2458908 : if (outer_path_rows > 1)
3440 : 1694291 : run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3441 : :
6365 3442 : 2458908 : inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
6239 3443 : 2458908 : inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3444 : :
3475 3445 [ + + + + ]: 2458908 : if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3446 [ + + ]: 2343438 : 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 */
4149 3457 : 1055437 : workspace->inner_run_cost = inner_run_cost;
3458 : 1055437 : 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 */
5372 3463 : 1403471 : run_cost += inner_run_cost;
3464 [ + + ]: 1403471 : if (outer_path_rows > 1)
3465 : 1051089 : run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3466 : : }
3467 : :
3468 : : /* CPU costs left for later */
3469 : :
3470 : : /* Public result fields */
782 rhaas@postgresql.org 3471 : 2458908 : workspace->disabled_nodes = disabled_nodes;
5372 tgl@sss.pgh.pa.us 3472 : 2458908 : workspace->startup_cost = startup_cost;
3473 : 2458908 : workspace->total_cost = startup_cost + run_cost;
3474 : : /* Save private data for final_cost_nestloop */
3475 : 2458908 : workspace->run_cost = run_cost;
3476 : 2458908 : }
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 : 1147133 : final_cost_nestloop(PlannerInfo *root, NestPath *path,
3488 : : JoinCostWorkspace *workspace,
3489 : : JoinPathExtraData *extra)
3490 : : {
1891 peter@eisentraut.org 3491 : 1147133 : Path *outer_path = path->jpath.outerjoinpath;
3492 : 1147133 : Path *inner_path = path->jpath.innerjoinpath;
5372 tgl@sss.pgh.pa.us 3493 : 1147133 : double outer_path_rows = outer_path->rows;
3494 : 1147133 : double inner_path_rows = inner_path->rows;
3495 : 1147133 : Cost startup_cost = workspace->startup_cost;
3496 : 1147133 : 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. */
782 rhaas@postgresql.org 3502 : 1147133 : path->jpath.path.disabled_nodes = workspace->disabled_nodes;
3503 : :
3504 : : /* Protect some assumptions below that rowcounts aren't zero */
2184 drowley@postgresql.o 3505 [ - + ]: 1147133 : if (outer_path_rows <= 0)
3852 tgl@sss.pgh.pa.us 3506 :UBC 0 : outer_path_rows = 1;
2184 drowley@postgresql.o 3507 [ + + ]:CBC 1147133 : if (inner_path_rows <= 0)
3852 tgl@sss.pgh.pa.us 3508 : 637 : inner_path_rows = 1;
3509 : : /* Mark the path with the correct row estimate */
1891 peter@eisentraut.org 3510 [ + + ]: 1147133 : if (path->jpath.path.param_info)
3511 : 26480 : path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3512 : : else
3513 : 1120653 : path->jpath.path.rows = path->jpath.path.parent->rows;
3514 : :
3515 : : /* For partial paths, scale row estimate. */
3516 [ + + ]: 1147133 : if (path->jpath.path.parallel_workers > 0)
3517 : : {
3518 : 38559 : double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3519 : :
3520 : 38559 : path->jpath.path.rows =
3521 : 38559 : 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 [ + + + + ]: 1147133 : if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3475 tgl@sss.pgh.pa.us 3527 [ + + ]: 1062957 : extra->inner_unique)
5372 3528 : 719623 : {
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 : : */
4149 3533 : 719623 : Cost inner_run_cost = workspace->inner_run_cost;
3534 : 719623 : 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 : : */
3475 3548 : 719623 : outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3418 3549 : 719623 : outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3475 3550 : 719623 : 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 : : */
6365 3556 : 719623 : 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 : : */
5289 3567 [ + + ]: 719623 : 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 : : */
4149 3583 : 113210 : run_cost += inner_run_cost * inner_scan_frac;
3584 [ + + ]: 113210 : if (outer_matched_rows > 1)
3585 : 12461 : 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 : : */
3418 3593 : 113210 : run_cost += outer_unmatched_rows *
6239 3594 : 113210 : 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 */
3418 3617 : 606413 : ntuples += outer_unmatched_rows * inner_path_rows;
3618 : :
3619 : : /* Now add the forced full scan, and decrement appropriate count */
4149 3620 : 606413 : run_cost += inner_run_cost;
3418 3621 [ + + ]: 606413 : if (outer_unmatched_rows >= 1)
3622 : 578972 : outer_unmatched_rows -= 1;
3623 : : else
3624 : 27441 : outer_matched_rows -= 1;
3625 : :
3626 : : /* Add inner run cost for additional outer tuples having matches */
3627 [ + + ]: 606413 : if (outer_matched_rows > 0)
3628 : 202444 : run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3629 : :
3630 : : /* Add inner run cost for additional unmatched outer tuples */
3631 [ + + ]: 606413 : if (outer_unmatched_rows > 0)
3632 : 345917 : 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!) */
6365 3640 : 427510 : ntuples = outer_path_rows * inner_path_rows;
3641 : : }
3642 : :
3643 : : /* CPU costs */
1891 peter@eisentraut.org 3644 : 1147133 : cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
8674 tgl@sss.pgh.pa.us 3645 : 1147133 : startup_cost += restrict_qual_cost.startup;
3646 : 1147133 : cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
9736 3647 : 1147133 : run_cost += cpu_per_tuple * ntuples;
3648 : :
3649 : : /* tlist eval costs are paid per output row, not per tuple scanned */
1891 peter@eisentraut.org 3650 : 1147133 : startup_cost += path->jpath.path.pathtarget->cost.startup;
3651 : 1147133 : run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3652 : :
3653 : 1147133 : path->jpath.path.startup_cost = startup_cost;
3654 : 1147133 : path->jpath.path.total_cost = startup_cost + run_cost;
11052 scrappy@hub.org 3655 : 1147133 : }
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
5372 tgl@sss.pgh.pa.us 3690 : 1039924 : 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;
9736 3699 : 1039924 : Cost startup_cost = 0;
3700 : 1039924 : Cost run_cost = 0;
5372 3701 : 1039924 : double outer_path_rows = outer_path->rows;
3702 : 1039924 : 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 */
2184 drowley@postgresql.o 3716 [ + + ]: 1039924 : if (outer_path_rows <= 0)
6776 tgl@sss.pgh.pa.us 3717 : 72 : outer_path_rows = 1;
2184 drowley@postgresql.o 3718 [ + + ]: 1039924 : if (inner_path_rows <= 0)
6776 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 : : */
5372 3732 [ + + + + ]: 1039924 : if (mergeclauses && jointype != JOIN_FULL)
8991 3733 : 1034835 : {
7205 3734 : 1034835 : 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 [ + + ]: 1034835 : opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3743 [ + + ]: 1034835 : ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3744 [ - + ]: 1034835 : Assert(opathkeys);
3745 [ - + ]: 1034835 : Assert(ipathkeys);
3746 : 1034835 : opathkey = (PathKey *) linitial(opathkeys);
3747 : 1034835 : ipathkey = (PathKey *) linitial(ipathkeys);
3748 : : /* debugging check */
3749 [ + - ]: 1034835 : if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
5686 3750 [ + - ]: 1034835 : opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
556 peter@eisentraut.org 3751 [ + - ]: 1034835 : opathkey->pk_cmptype != ipathkey->pk_cmptype ||
7205 tgl@sss.pgh.pa.us 3752 [ - + ]: 1034835 : opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
7205 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 */
7203 tgl@sss.pgh.pa.us 3756 :CBC 1034835 : cache = cached_scansel(root, firstclause, opathkey);
3757 : :
7205 3758 [ + + ]: 1034835 : if (bms_is_subset(firstclause->left_relids,
3759 : 1034835 : outer_path->parent->relids))
3760 : : {
3761 : : /* left side of clause is outer */
6883 3762 : 535010 : outerstartsel = cache->leftstartsel;
3763 : 535010 : outerendsel = cache->leftendsel;
3764 : 535010 : innerstartsel = cache->rightstartsel;
3765 : 535010 : innerendsel = cache->rightendsel;
3766 : : }
3767 : : else
3768 : : {
3769 : : /* left side of clause is inner */
3770 : 499825 : outerstartsel = cache->rightstartsel;
3771 : 499825 : outerendsel = cache->rightendsel;
3772 : 499825 : innerstartsel = cache->leftstartsel;
3773 : 499825 : innerendsel = cache->leftendsel;
3774 : : }
5372 3775 [ + + + + ]: 1034835 : if (jointype == JOIN_LEFT ||
3776 : : jointype == JOIN_ANTI)
3777 : : {
6883 3778 : 133541 : outerstartsel = 0.0;
3779 : 133541 : outerendsel = 1.0;
3780 : : }
1286 3781 [ + + + + ]: 901294 : else if (jointype == JOIN_RIGHT ||
3782 : : jointype == JOIN_RIGHT_ANTI)
3783 : : {
6883 3784 : 134589 : innerstartsel = 0.0;
3785 : 134589 : innerendsel = 1.0;
3786 : : }
3787 : : }
3788 : : else
3789 : : {
3790 : : /* cope with clauseless or full mergejoin */
3791 : 5089 : outerstartsel = innerstartsel = 0.0;
3792 : 5089 : 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 : 1039924 : outer_skip_rows = rint(outer_path_rows * outerstartsel);
3800 : 1039924 : inner_skip_rows = rint(inner_path_rows * innerstartsel);
3801 : 1039924 : outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3802 : 1039924 : inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3803 : :
3804 [ - + ]: 1039924 : Assert(outer_skip_rows <= outer_rows);
3805 [ - + ]: 1039924 : 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 : 1039924 : outerstartsel = outer_skip_rows / outer_path_rows;
3813 : 1039924 : innerstartsel = inner_skip_rows / inner_path_rows;
3814 : 1039924 : outerendsel = outer_rows / outer_path_rows;
3815 : 1039924 : innerendsel = inner_rows / inner_path_rows;
3816 : :
5400 3817 [ - + ]: 1039924 : Assert(outerstartsel <= outerendsel);
3818 [ - + ]: 1039924 : 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 : : */
257 rhaas@postgresql.org 3832 : 1039924 : disabled_nodes = 0;
3833 : :
3834 : : /* cost of source data */
3835 : :
9736 tgl@sss.pgh.pa.us 3836 [ + + ]: 1039924 : 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 : : */
522 rguo@postgresql.org 3843 [ - + ]: 523202 : 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 [ + + + + ]: 523202 : if (enable_incremental_sort && outer_presorted_keys > 0)
3850 : : {
3851 : 1163 : 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 : 1163 : outer_path->pathtarget->width,
3860 : : 0.0,
3861 : : work_mem,
3862 : : -1.0,
3863 : : NULL);
3864 : : }
3865 : : else
3866 : : {
733 3867 : 522039 : cost_sort(&sort_path,
3868 : : root,
3869 : : outersortkeys,
3870 : : outer_path->disabled_nodes,
3871 : : outer_path->total_cost,
3872 : : outer_path_rows,
3873 : 522039 : outer_path->pathtarget->width,
3874 : : 0.0,
3875 : : work_mem,
3876 : : -1.0);
3877 : : }
3878 : :
782 rhaas@postgresql.org 3879 : 523202 : disabled_nodes += sort_path.disabled_nodes;
9736 tgl@sss.pgh.pa.us 3880 : 523202 : startup_cost += sort_path.startup_cost;
6883 3881 : 523202 : startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3882 : 523202 : * outerstartsel;
8991 3883 : 523202 : run_cost += (sort_path.total_cost - sort_path.startup_cost)
6883 3884 : 523202 : * (outerendsel - outerstartsel);
3885 : : }
3886 : : else
3887 : : {
782 rhaas@postgresql.org 3888 : 516722 : disabled_nodes += outer_path->disabled_nodes;
9736 tgl@sss.pgh.pa.us 3889 : 516722 : startup_cost += outer_path->startup_cost;
6883 3890 : 516722 : startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3891 : 516722 : * outerstartsel;
8991 3892 : 516722 : run_cost += (outer_path->total_cost - outer_path->startup_cost)
6883 3893 : 516722 : * (outerendsel - outerstartsel);
3894 : : }
3895 : :
9736 3896 [ + + ]: 1039924 : 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 : : */
522 rguo@postgresql.org 3903 [ - + ]: 830796 : 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 : :
9736 tgl@sss.pgh.pa.us 3910 : 830796 : cost_sort(&sort_path,
3911 : : root,
3912 : : innersortkeys,
3913 : : inner_path->disabled_nodes,
3914 : : inner_path->total_cost,
3915 : : inner_path_rows,
3889 3916 : 830796 : inner_path->pathtarget->width,
3917 : : 0.0,
3918 : : work_mem,
3919 : : -1.0);
782 rhaas@postgresql.org 3920 : 830796 : disabled_nodes += sort_path.disabled_nodes;
9736 tgl@sss.pgh.pa.us 3921 : 830796 : startup_cost += sort_path.startup_cost;
6883 3922 : 830796 : startup_cost += (sort_path.total_cost - sort_path.startup_cost)
6175 3923 : 830796 : * innerstartsel;
3924 : 830796 : inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3925 : 830796 : * (innerendsel - innerstartsel);
3926 : : }
3927 : : else
3928 : : {
782 rhaas@postgresql.org 3929 : 209128 : disabled_nodes += inner_path->disabled_nodes;
9736 tgl@sss.pgh.pa.us 3930 : 209128 : startup_cost += inner_path->startup_cost;
6883 3931 : 209128 : startup_cost += (inner_path->total_cost - inner_path->startup_cost)
6175 3932 : 209128 : * innerstartsel;
3933 : 209128 : inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3934 : 209128 : * (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 */
782 rhaas@postgresql.org 3948 : 1039924 : workspace->disabled_nodes = disabled_nodes;
5372 tgl@sss.pgh.pa.us 3949 : 1039924 : workspace->startup_cost = startup_cost;
3950 : 1039924 : workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3951 : : /* Save private data for final_cost_mergejoin */
3952 : 1039924 : workspace->run_cost = run_cost;
3953 : 1039924 : workspace->inner_run_cost = inner_run_cost;
3954 : 1039924 : workspace->outer_rows = outer_rows;
3955 : 1039924 : workspace->inner_rows = inner_rows;
3956 : 1039924 : workspace->outer_skip_rows = outer_skip_rows;
3957 : 1039924 : workspace->inner_skip_rows = inner_skip_rows;
3958 : 1039924 : }
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 : 336915 : final_cost_mergejoin(PlannerInfo *root, MergePath *path,
3989 : : JoinCostWorkspace *workspace,
3990 : : JoinPathExtraData *extra)
3991 : : {
3992 : 336915 : Path *outer_path = path->jpath.outerjoinpath;
3993 : 336915 : Path *inner_path = path->jpath.innerjoinpath;
3994 : 336915 : double inner_path_rows = inner_path->rows;
3995 : 336915 : List *mergeclauses = path->path_mergeclauses;
3996 : 336915 : List *innersortkeys = path->innersortkeys;
3997 : 336915 : Cost startup_cost = workspace->startup_cost;
3998 : 336915 : Cost run_cost = workspace->run_cost;
3999 : 336915 : Cost inner_run_cost = workspace->inner_run_cost;
4000 : 336915 : double outer_rows = workspace->outer_rows;
4001 : 336915 : double inner_rows = workspace->inner_rows;
4002 : 336915 : double outer_skip_rows = workspace->outer_skip_rows;
4003 : 336915 : 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;
257 rhaas@postgresql.org 4012 : 336915 : uint64 enable_mask = 0;
4013 : :
4014 : : /* Protect some assumptions below that rowcounts aren't zero */
2184 drowley@postgresql.o 4015 [ + + ]: 336915 : if (inner_path_rows <= 0)
5372 tgl@sss.pgh.pa.us 4016 : 64 : inner_path_rows = 1;
4017 : :
4018 : : /* Mark the path with the correct row estimate */
5289 4019 [ + + ]: 336915 : if (path->jpath.path.param_info)
4020 : 1586 : path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4021 : : else
4022 : 335329 : path->jpath.path.rows = path->jpath.path.parent->rows;
4023 : :
4024 : : /* For partial paths, scale row estimate. */
3559 rhaas@postgresql.org 4025 [ + + ]: 336915 : if (path->jpath.path.parallel_workers > 0)
4026 : : {
3435 bruce@momjian.us 4027 : 46937 : double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4028 : :
3498 rhaas@postgresql.org 4029 : 46937 : path->jpath.path.rows =
4030 : 46937 : 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 : : */
5372 tgl@sss.pgh.pa.us 4037 : 336915 : cost_qual_eval(&merge_qual_cost, mergeclauses, root);
4038 : 336915 : cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4039 : 336915 : qp_qual_cost.startup -= merge_qual_cost.startup;
4040 : 336915 : 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 : : */
3475 4048 [ + + ]: 336915 : if ((path->jpath.jointype == JOIN_SEMI ||
4049 [ + + ]: 332049 : path->jpath.jointype == JOIN_ANTI ||
4050 [ + + + + ]: 439591 : extra->inner_unique) &&
4051 : 124152 : (list_length(path->jpath.joinrestrictinfo) ==
4052 : 124152 : list_length(path->path_mergeclauses)))
4053 : 105789 : path->skip_mark_restore = true;
4054 : : else
4055 : 231126 : 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 : : */
5372 4061 : 336915 : 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 : : */
419 rguo@postgresql.org 4089 [ + + ]: 336915 : if (path->skip_mark_restore ||
4090 [ + + + + : 231126 : RELATION_WAS_MADE_UNIQUE(outer_path->parent, extra->sjinfo,
+ + ]
4091 : : path->jpath.jointype))
5372 tgl@sss.pgh.pa.us 4092 : 108723 : rescannedtuples = 0;
4093 : : else
4094 : : {
4095 : 228192 : rescannedtuples = mergejointuples - inner_path_rows;
4096 : : /* Must clamp because of possible underestimate */
4097 [ + + ]: 228192 : if (rescannedtuples < 0)
4098 : 52031 : 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 : : */
2855 4106 : 336915 : 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 : : */
6175 4117 : 336915 : 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 : 336915 : mat_inner_cost = inner_run_cost +
2855 4133 : 336915 : cpu_operator_cost * inner_rows * rescanratio;
4134 : :
4135 : : /*
4136 : : * If we don't need mark/restore at all, we don't need materialization.
4137 : : */
3475 4138 [ + + ]: 336915 : if (path->skip_mark_restore)
4139 : 105789 : 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 : : */
257 rhaas@postgresql.org 4146 [ + + + + ]: 231126 : else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
4147 : 227387 : (mat_inner_cost < bare_inner_cost ||
4148 [ + + ]: 227387 : (extra->pgs_mask & PGS_MERGEJOIN_PLAIN) == 0))
6175 tgl@sss.pgh.pa.us 4149 : 2410 : 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 [ + + ]: 228716 : else if (innersortkeys == NIL &&
4357 rhaas@postgresql.org 4165 [ + + ]: 5917 : !ExecSupportsMarkRestore(inner_path))
6175 tgl@sss.pgh.pa.us 4166 : 1376 : 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 : : */
257 rhaas@postgresql.org 4179 [ + + + + ]: 227340 : else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
4180 : 221491 : innersortkeys != NIL &&
3889 tgl@sss.pgh.pa.us 4181 : 221491 : relation_byte_size(inner_path_rows,
4182 : 221491 : inner_path->pathtarget->width) >
619 4183 [ + + ]: 221491 : work_mem * (Size) 1024)
6175 4184 : 190 : path->materialize_inner = true;
4185 : : else
4186 : 227150 : path->materialize_inner = false;
4187 : :
4188 : : /* Get the number of disabled nodes, not yet including this one. */
257 rhaas@postgresql.org 4189 : 336915 : 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 : : */
6175 tgl@sss.pgh.pa.us 4195 [ + + ]: 336915 : if (path->materialize_inner)
4196 : : {
4197 : 3976 : run_cost += mat_inner_cost;
257 rhaas@postgresql.org 4198 : 3976 : enable_mask |= PGS_MERGEJOIN_MATERIALIZE;
4199 : : }
4200 : : else
4201 : : {
6175 tgl@sss.pgh.pa.us 4202 : 332939 : run_cost += bare_inner_cost;
257 rhaas@postgresql.org 4203 : 332939 : enable_mask |= PGS_MERGEJOIN_PLAIN;
4204 : : }
4205 : :
4206 : : /* Incremental count of disabled nodes if this node is disabled. */
4207 [ + + ]: 336915 : if (path->jpath.path.parallel_workers == 0)
4208 : 289978 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
4209 [ + + ]: 336915 : if ((extra->pgs_mask & enable_mask) != enable_mask)
4210 : 574 : ++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 : : */
8659 tgl@sss.pgh.pa.us 4219 : 336915 : startup_cost += merge_qual_cost.startup;
6883 4220 : 336915 : startup_cost += merge_qual_cost.per_tuple *
4221 : 336915 : (outer_skip_rows + inner_skip_rows * rescanratio);
8659 4222 : 336915 : run_cost += merge_qual_cost.per_tuple *
6883 4223 : 336915 : ((outer_rows - outer_skip_rows) +
4224 : 336915 : (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 : : */
8659 4235 : 336915 : startup_cost += qp_qual_cost.startup;
4236 : 336915 : cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
6631 4237 : 336915 : run_cost += cpu_per_tuple * mergejointuples;
4238 : :
4239 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 4240 : 336915 : startup_cost += path->jpath.path.pathtarget->cost.startup;
4241 : 336915 : run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4242 : :
8659 4243 : 336915 : path->jpath.path.startup_cost = startup_cost;
4244 : 336915 : path->jpath.path.total_cost = startup_cost + run_cost;
11052 scrappy@hub.org 4245 : 336915 : }
4246 : :
4247 : : /*
4248 : : * run mergejoinscansel() with caching
4249 : : */
4250 : : static MergeScanSelCache *
6906 bruce@momjian.us 4251 : 1034835 : 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? */
7203 tgl@sss.pgh.pa.us 4262 [ + + + + : 1034839 : foreach(lc, rinfo->scansel_cache)
+ + ]
4263 : : {
4264 : 934942 : cache = (MergeScanSelCache *) lfirst(lc);
4265 [ + - ]: 934942 : if (cache->opfamily == pathkey->pk_opfamily &&
5686 4266 [ + - ]: 934942 : cache->collation == pathkey->pk_eclass->ec_collation &&
556 peter@eisentraut.org 4267 [ + + ]: 934942 : cache->cmptype == pathkey->pk_cmptype &&
7203 tgl@sss.pgh.pa.us 4268 [ + - ]: 934938 : cache->nulls_first == pathkey->pk_nulls_first)
4269 : 934938 : return cache;
4270 : : }
4271 : :
4272 : : /* Nope, do the computation */
4273 : 99897 : mergejoinscansel(root,
4274 : 99897 : (Node *) rinfo->clause,
4275 : : pathkey->pk_opfamily,
4276 : : pathkey->pk_cmptype,
4277 : 99897 : pathkey->pk_nulls_first,
4278 : : &leftstartsel,
4279 : : &leftendsel,
4280 : : &rightstartsel,
4281 : : &rightendsel);
4282 : :
4283 : : /* Cache the result in suitably long-lived workspace */
4284 : 99897 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4285 : :
306 michael@paquier.xyz 4286 : 99897 : cache = palloc_object(MergeScanSelCache);
7203 tgl@sss.pgh.pa.us 4287 : 99897 : cache->opfamily = pathkey->pk_opfamily;
5686 4288 : 99897 : cache->collation = pathkey->pk_eclass->ec_collation;
556 peter@eisentraut.org 4289 : 99897 : cache->cmptype = pathkey->pk_cmptype;
7203 tgl@sss.pgh.pa.us 4290 : 99897 : cache->nulls_first = pathkey->pk_nulls_first;
6883 4291 : 99897 : cache->leftstartsel = leftstartsel;
4292 : 99897 : cache->leftendsel = leftendsel;
4293 : 99897 : cache->rightstartsel = rightstartsel;
4294 : 99897 : cache->rightendsel = rightendsel;
4295 : :
7203 4296 : 99897 : rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4297 : :
4298 : 99897 : MemoryContextSwitchTo(oldcontext);
4299 : :
4300 : 99897 : 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
5372 4330 : 616801 : 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;
9736 4338 : 616801 : Cost startup_cost = 0;
4339 : 616801 : Cost run_cost = 0;
5372 4340 : 616801 : double outer_path_rows = outer_path->rows;
4341 : 616801 : double inner_path_rows = inner_path->rows;
3218 andres@anarazel.de 4342 : 616801 : double inner_path_rows_total = inner_path_rows;
8170 neilc@samurai.com 4343 : 616801 : int num_hashclauses = list_length(hashclauses);
4344 : : int numbuckets;
4345 : : int numbatches;
4346 : : int num_skew_mcvs;
4347 : : size_t space_allowed; /* unused */
257 rhaas@postgresql.org 4348 : 616801 : uint64 enable_mask = PGS_HASHJOIN;
4349 : :
4350 [ + + ]: 616801 : if (outer_path->parallel_workers == 0)
4351 : 503359 : enable_mask |= PGS_CONSIDER_NONPARTIAL;
4352 : :
4353 : : /* Count up disabled nodes. */
4354 : 616801 : disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
782 4355 : 616801 : disabled_nodes += inner_path->disabled_nodes;
4356 : 616801 : disabled_nodes += outer_path->disabled_nodes;
4357 : :
4358 : : /* cost of source data */
9736 tgl@sss.pgh.pa.us 4359 : 616801 : startup_cost += outer_path->startup_cost;
4360 : 616801 : run_cost += outer_path->total_cost - outer_path->startup_cost;
4361 : 616801 : 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 : : */
7217 4373 : 616801 : startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
4374 : 616801 : * inner_path_rows;
8659 4375 : 616801 : 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 : : */
3218 andres@anarazel.de 4383 [ + + ]: 616801 : if (parallel_hash)
4384 : 57755 : 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 : 616801 : ExecChooseHashTableSize(inner_path_rows_total,
3889 tgl@sss.pgh.pa.us 4397 : 616801 : 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 : : */
5372 4413 [ + + ]: 616801 : if (numbatches > 1)
4414 : : {
4415 : 3068 : double outerpages = page_size(outer_path_rows,
3889 4416 : 3068 : outer_path->pathtarget->width);
5372 4417 : 3068 : double innerpages = page_size(inner_path_rows,
3889 4418 : 3068 : inner_path->pathtarget->width);
4419 : :
5372 4420 : 3068 : startup_cost += seq_page_cost * innerpages;
4421 : 3068 : run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4422 : : }
4423 : :
4424 : : /* CPU costs left for later */
4425 : :
4426 : : /* Public result fields */
782 rhaas@postgresql.org 4427 : 616801 : workspace->disabled_nodes = disabled_nodes;
5372 tgl@sss.pgh.pa.us 4428 : 616801 : workspace->startup_cost = startup_cost;
4429 : 616801 : workspace->total_cost = startup_cost + run_cost;
4430 : : /* Save private data for final_cost_hashjoin */
4431 : 616801 : workspace->run_cost = run_cost;
4432 : 616801 : workspace->numbuckets = numbuckets;
4433 : 616801 : workspace->numbatches = numbatches;
3218 andres@anarazel.de 4434 : 616801 : workspace->inner_rows_total = inner_path_rows_total;
5372 tgl@sss.pgh.pa.us 4435 : 616801 : }
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 : 338570 : final_cost_hashjoin(PlannerInfo *root, HashPath *path,
4450 : : JoinCostWorkspace *workspace,
4451 : : JoinPathExtraData *extra)
4452 : : {
4453 : 338570 : Path *outer_path = path->jpath.outerjoinpath;
4454 : 338570 : Path *inner_path = path->jpath.innerjoinpath;
4455 : 338570 : double outer_path_rows = outer_path->rows;
4456 : 338570 : double inner_path_rows = inner_path->rows;
3218 andres@anarazel.de 4457 : 338570 : double inner_path_rows_total = workspace->inner_rows_total;
5372 tgl@sss.pgh.pa.us 4458 : 338570 : List *hashclauses = path->path_hashclauses;
4459 : 338570 : Cost startup_cost = workspace->startup_cost;
4460 : 338570 : Cost run_cost = workspace->run_cost;
4461 : 338570 : int numbuckets = workspace->numbuckets;
4462 : 338570 : int numbatches = workspace->numbatches;
4463 : : Cost cpu_per_tuple;
4464 : : QualCost hash_qual_cost;
4465 : : QualCost qp_qual_cost;
48 rguo@postgresql.org 4466 :GNC 338570 : 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. */
782 rhaas@postgresql.org 4474 :CBC 338570 : path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4475 : :
4476 : : /* Mark the path with the correct row estimate */
5289 tgl@sss.pgh.pa.us 4477 [ + + ]: 338570 : if (path->jpath.path.param_info)
4478 : 3267 : path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4479 : : else
4480 : 335303 : path->jpath.path.rows = path->jpath.path.parent->rows;
4481 : :
4482 : : /* For partial paths, scale row estimate. */
3559 rhaas@postgresql.org 4483 [ + + ]: 338570 : if (path->jpath.path.parallel_workers > 0)
4484 : : {
3435 bruce@momjian.us 4485 : 81651 : double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4486 : :
3498 rhaas@postgresql.org 4487 : 81651 : path->jpath.path.rows =
4488 : 81651 : clamp_row_est(path->jpath.path.rows / parallel_divisor);
4489 : : }
4490 : :
4491 : : /* mark the path with estimated # of batches */
6409 tgl@sss.pgh.pa.us 4492 : 338570 : path->num_batches = numbatches;
4493 : :
4494 : : /* store the total number of tuples (sum of partial row estimates) */
3218 andres@anarazel.de 4495 : 338570 : path->inner_rows_total = inner_path_rows_total;
4496 : :
4497 : : /* and compute the number of "virtual" buckets in the whole join */
3400 tgl@sss.pgh.pa.us 4498 : 338570 : 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 : : */
419 rguo@postgresql.org 4510 [ + + + + : 338570 : if (RELATION_WAS_MADE_UNIQUE(inner_path->parent, extra->sjinfo,
+ + ]
4511 : : path->jpath.jointype))
4512 : : {
8658 tgl@sss.pgh.pa.us 4513 : 3128 : innerbucketsize = 1.0 / virtualbuckets;
287 4514 : 3128 : innermcvfreq = 1.0 / inner_path_rows_total;
4515 : : }
4516 : : else
4517 : : {
4518 : : List *otherclauses;
4519 : :
8658 4520 : 335442 : innerbucketsize = 1.0;
3345 4521 : 335442 : innermcvfreq = 1.0;
4522 : :
4523 : : /* At first, try to estimate bucket size using extended statistics. */
581 akorotkov@postgresql 4524 : 335442 : otherclauses = estimate_multivariate_bucketsize(root,
4525 : : inner_path->parent,
4526 : : hashclauses,
4527 : : &innerbucketsize);
4528 : :
4529 : : /* Pass through the remaining clauses */
4530 [ + + + + : 698931 : foreach(hcl, otherclauses)
+ + ]
4531 : : {
3472 tgl@sss.pgh.pa.us 4532 : 363489 : 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 : : */
8647 4544 [ + + ]: 363489 : if (bms_is_subset(restrictinfo->right_relids,
4545 : 363489 : inner_path->parent->relids))
4546 : : {
4547 : : /* righthand side is inner */
8658 4548 : 190155 : thisbucketsize = restrictinfo->right_bucketsize;
4549 [ + + ]: 190155 : if (thisbucketsize < 0)
4550 : : {
4551 : : /* not cached yet */
3345 4552 : 82473 : estimate_hash_bucket_stats(root,
4553 : 82473 : get_rightop(restrictinfo->clause),
4554 : : virtualbuckets,
4555 : : &restrictinfo->right_mcvfreq,
4556 : : &restrictinfo->right_bucketsize);
4557 : 82473 : thisbucketsize = restrictinfo->right_bucketsize;
4558 : : }
4559 : 190155 : thismcvfreq = restrictinfo->right_mcvfreq;
4560 : : }
4561 : : else
4562 : : {
8647 4563 [ - + ]: 173334 : Assert(bms_is_subset(restrictinfo->left_relids,
4564 : : inner_path->parent->relids));
4565 : : /* lefthand side is inner */
8658 4566 : 173334 : thisbucketsize = restrictinfo->left_bucketsize;
4567 [ + + ]: 173334 : if (thisbucketsize < 0)
4568 : : {
4569 : : /* not cached yet */
3345 4570 : 70429 : estimate_hash_bucket_stats(root,
4571 : 70429 : get_leftop(restrictinfo->clause),
4572 : : virtualbuckets,
4573 : : &restrictinfo->left_mcvfreq,
4574 : : &restrictinfo->left_bucketsize);
4575 : 70429 : thisbucketsize = restrictinfo->left_bucketsize;
4576 : : }
4577 : 173334 : thismcvfreq = restrictinfo->left_mcvfreq;
4578 : : }
4579 : :
8658 4580 [ + + ]: 363489 : if (innerbucketsize > thisbucketsize)
4581 : 273236 : innerbucketsize = thisbucketsize;
4582 : : /* Disregard zero for MCV freq, it means we have no data */
287 4583 [ + + + + ]: 363489 : if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq)
3345 4584 : 274791 : 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 : 338570 : if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
1905 4597 [ + + ]: 677140 : inner_path->pathtarget->width) > get_hash_memory_limit())
3345 4598 : 84 : startup_cost += disable_cost;
4599 : :
4600 : : /*
4601 : : * Compute cost of the hashquals and qpquals (other restriction clauses)
4602 : : * separately.
4603 : : */
5372 4604 : 338570 : cost_qual_eval(&hash_qual_cost, hashclauses, root);
4605 : 338570 : cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4606 : 338570 : qp_qual_cost.startup -= hash_qual_cost.startup;
4607 : 338570 : qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4608 : :
4609 : : /* CPU costs */
4610 : :
3475 4611 [ + + ]: 338570 : if (path->jpath.jointype == JOIN_SEMI ||
4612 [ + + ]: 334107 : path->jpath.jointype == JOIN_ANTI ||
4613 [ + + ]: 325631 : extra->inner_unique)
6365 4614 : 95074 : {
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 : : */
48 rguo@postgresql.org 4638 [ + + ]:GNC 95074 : if (path->jpath.jointype == JOIN_RIGHT_SEMI ||
4639 [ + + ]: 95025 : path->jpath.jointype == JOIN_RIGHT_ANTI)
4640 : : {
4641 [ + + ]: 2864 : outer_matched_rows = Min(approx_tuple_count(root, &path->jpath,
4642 : : hashclauses),
4643 : : outer_path_rows);
4644 : 2864 : inner_scan_frac = 1.0;
4645 : : }
4646 : : else
4647 : : {
4648 : 92210 : outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4649 : 92210 : inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4650 : : }
4651 : :
6365 tgl@sss.pgh.pa.us 4652 :CBC 95074 : startup_cost += hash_qual_cost.startup;
4653 : 190148 : run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4654 : 95074 : 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 : 190148 : run_cost += hash_qual_cost.per_tuple *
4670 : 190148 : (outer_path_rows - outer_matched_rows) *
4671 : 95074 : 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 : 243496 : startup_cost += hash_qual_cost.startup;
4686 : 486992 : run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4687 : 243496 : 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 : : */
48 rguo@postgresql.org 4704 [ + + ]:GNC 338570 : if (path->jpath.jointype == JOIN_RIGHT_SEMI)
4705 : 3593 : hashjointuples = clamp_row_est(inner_path_rows *
4706 : 3593 : extra->semifactors.outer_match_frac);
4707 [ + + ]: 334977 : else if (path->jpath.jointype == JOIN_RIGHT_ANTI)
4708 : 8220 : hashjointuples = clamp_row_est(inner_path_rows *
4709 : 8220 : (1.0 - extra->semifactors.outer_match_frac));
4710 [ + + ]: 326757 : else if (path->jpath.jointype == JOIN_ANTI)
4711 : 8476 : hashjointuples = outer_path_rows - outer_matched_rows;
4712 [ + + + + ]: 318281 : else if (path->jpath.jointype == JOIN_SEMI || extra->inner_unique)
4713 : 83734 : hashjointuples = outer_matched_rows;
4714 : : else
6365 tgl@sss.pgh.pa.us 4715 :CBC 234547 : 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 : : */
8659 4738 : 338570 : startup_cost += qp_qual_cost.startup;
48 rguo@postgresql.org 4739 [ + + ]:GNC 338570 : if (path->jpath.jointype == JOIN_RIGHT_ANTI &&
4740 [ + + ]: 8220 : 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 : 338551 : cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4755 : 338551 : run_cost += cpu_per_tuple * hashjointuples;
4756 : : }
4757 : :
4758 : : /* tlist eval costs are paid per output row, not per tuple scanned */
3889 tgl@sss.pgh.pa.us 4759 :CBC 338570 : startup_cost += path->jpath.path.pathtarget->cost.startup;
4760 : 338570 : run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4761 : :
8659 4762 : 338570 : path->jpath.path.startup_cost = startup_cost;
4763 : 338570 : path->jpath.path.total_cost = startup_cost + run_cost;
9736 4764 : 338570 : }
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
6625 4775 : 32394 : 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 : 32394 : cost_qual_eval(&sp_cost,
4795 : 32394 : make_ands_implicit((Expr *) subplan->testexpr),
4796 : : NULL);
4797 : :
4798 [ + + ]: 32394 : 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 : 1675 : sp_cost.startup += plan->total_cost +
4807 : 1675 : 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 : 30719 : Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4828 : :
4829 [ + + ]: 30719 : if (subplan->subLinkType == EXISTS_SUBLINK)
4830 : : {
4831 : : /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3852 4832 : 1816 : sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4833 : : }
6625 4834 [ + + ]: 28903 : else if (subplan->subLinkType == ALL_SUBLINK ||
4835 [ + + ]: 28888 : subplan->subLinkType == ANY_SUBLINK)
4836 : : {
4837 : : /* assume we need 50% of the tuples */
4838 : 138 : sp_cost.per_tuple += 0.50 * plan_run_cost;
4839 : : /* also charge a cpu_operator_cost per row examined */
4840 : 138 : sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4841 : : }
4842 : : else
4843 : : {
4844 : : /* assume we need all tuples */
4845 : 28765 : 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 [ + + + + ]: 40193 : if (subplan->parParam == NIL &&
6239 4856 : 9474 : ExecMaterializesOutput(nodeTag(plan)))
6625 4857 : 638 : sp_cost.startup += plan->startup_cost;
4858 : : else
4859 : 30081 : sp_cost.per_tuple += plan->startup_cost;
4860 : : }
4861 : :
206 rhaas@postgresql.org 4862 : 32394 : subplan->disabled_nodes = plan->disabled_nodes;
6625 tgl@sss.pgh.pa.us 4863 : 32394 : subplan->startup_cost = sp_cost.startup;
4864 : 32394 : subplan->per_call_cost = sp_cost.per_tuple;
4865 : 32394 : }
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
6239 4883 : 2458908 : cost_rescan(PlannerInfo *root, Path *path,
4884 : : Cost *rescan_startup_cost, /* output parameters */
4885 : : Cost *rescan_total_cost)
4886 : : {
4887 [ + + + + : 2458908 : switch (path->pathtype)
+ + ]
4888 : : {
4889 : 30753 : 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 : 30753 : *rescan_startup_cost = 0;
4899 : 30753 : *rescan_total_cost = path->total_cost - path->startup_cost;
4900 : 30753 : break;
4901 : 85843 : 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 : : */
3729 4907 [ + - ]: 85843 : if (((HashPath *) path)->num_batches == 1)
4908 : : {
4909 : : /* Startup cost is exactly the cost of hash table building */
4910 : 85843 : *rescan_startup_cost = 0;
4911 : 85843 : *rescan_total_cost = path->total_cost - path->startup_cost;
4912 : : }
4913 : : else
4914 : : {
4915 : : /* Otherwise, no special treatment */
3729 tgl@sss.pgh.pa.us 4916 :UBC 0 : *rescan_startup_cost = path->startup_cost;
4917 : 0 : *rescan_total_cost = path->total_cost;
4918 : : }
6239 tgl@sss.pgh.pa.us 4919 :CBC 85843 : break;
4920 : 5373 : 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 : : */
5372 4929 : 5373 : Cost run_cost = cpu_tuple_cost * path->rows;
4930 : 5373 : double nbytes = relation_byte_size(path->rows,
3400 4931 : 5373 : path->pathtarget->width);
619 4932 : 5373 : double work_mem_bytes = work_mem * (Size) 1024;
4933 : :
6239 4934 [ + + ]: 5373 : if (nbytes > work_mem_bytes)
4935 : : {
4936 : : /* It will spill, so account for re-read cost */
4937 : 224 : double npages = ceil(nbytes / BLCKSZ);
4938 : :
4939 : 224 : run_cost += seq_page_cost * npages;
4940 : : }
4941 : 5373 : *rescan_startup_cost = 0;
4942 : 5373 : *rescan_total_cost = run_cost;
4943 : : }
4944 : 5373 : break;
6079 4945 : 839866 : 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 : : */
5372 4956 : 839866 : Cost run_cost = cpu_operator_cost * path->rows;
4957 : 839866 : double nbytes = relation_byte_size(path->rows,
3400 4958 : 839866 : path->pathtarget->width);
619 4959 : 839866 : double work_mem_bytes = work_mem * (Size) 1024;
4960 : :
6079 4961 [ + + ]: 839866 : if (nbytes > work_mem_bytes)
4962 : : {
4963 : : /* It will spill, so account for re-read cost */
4964 : 5911 : double npages = ceil(nbytes / BLCKSZ);
4965 : :
4966 : 5911 : run_cost += seq_page_cost * npages;
4967 : : }
4968 : 839866 : *rescan_startup_cost = 0;
4969 : 839866 : *rescan_total_cost = run_cost;
4970 : : }
4971 : 839866 : break;
1916 drowley@postgresql.o 4972 : 189854 : case T_Memoize:
4973 : : /* All the hard work is done by cost_memoize_rescan */
4974 : 189854 : cost_memoize_rescan(root, (MemoizePath *) path,
4975 : : rescan_startup_cost, rescan_total_cost);
2019 4976 : 189854 : break;
6239 tgl@sss.pgh.pa.us 4977 : 1307219 : default:
4978 : 1307219 : *rescan_startup_cost = path->startup_cost;
4979 : 1307219 : *rescan_total_cost = path->total_cost;
4980 : 1307219 : break;
4981 : : }
4982 : 2458908 : }
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
7172 4998 : 3597302 : cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
4999 : : {
5000 : : cost_qual_eval_context context;
5001 : : ListCell *l;
5002 : :
5003 : 3597302 : context.root = root;
5004 : 3597302 : context.total.startup = 0;
5005 : 3597302 : context.total.per_tuple = 0;
5006 : :
5007 : : /* We don't charge any cost for the implicit ANDing at top level ... */
5008 : :
9435 5009 [ + + + + : 6899358 : foreach(l, quals)
+ + ]
5010 : : {
9335 bruce@momjian.us 5011 : 3302056 : Node *qual = (Node *) lfirst(l);
5012 : :
7172 tgl@sss.pgh.pa.us 5013 : 3302056 : cost_qual_eval_walker(qual, &context);
5014 : : }
5015 : :
5016 : 3597302 : *cost = context.total;
9736 5017 : 3597302 : }
5018 : :
5019 : : /*
5020 : : * cost_qual_eval_node
5021 : : * As above, for a single RestrictInfo or expression.
5022 : : */
5023 : : void
7172 5024 : 1423004 : cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
5025 : : {
5026 : : cost_qual_eval_context context;
5027 : :
5028 : 1423004 : context.root = root;
5029 : 1423004 : context.total.startup = 0;
5030 : 1423004 : context.total.per_tuple = 0;
5031 : :
5032 : 1423004 : cost_qual_eval_walker(qual, &context);
5033 : :
5034 : 1423004 : *cost = context.total;
7203 5035 : 1423004 : }
5036 : :
5037 : : static bool
6906 bruce@momjian.us 5038 : 7437795 : cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
5039 : : {
9736 tgl@sss.pgh.pa.us 5040 [ + + ]: 7437795 : if (node == NULL)
5041 : 78286 : 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 : : */
7203 5049 [ + + ]: 7359509 : if (IsA(node, RestrictInfo))
5050 : : {
5051 : 3455449 : RestrictInfo *rinfo = (RestrictInfo *) node;
5052 : :
5053 [ + + ]: 3455449 : if (rinfo->eval_cost.startup < 0)
5054 : : {
5055 : : cost_qual_eval_context locContext;
5056 : :
7172 5057 : 457676 : locContext.root = context->root;
5058 : 457676 : locContext.total.startup = 0;
5059 : 457676 : 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 : : */
7203 5065 [ + + ]: 457676 : if (rinfo->orclause)
7172 5066 : 8149 : cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
5067 : : else
5068 : 449527 : 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 : : */
7203 5074 [ + + ]: 457676 : if (rinfo->pseudoconstant)
5075 : : {
5076 : : /* count one execution during startup */
7172 5077 : 8501 : locContext.total.startup += locContext.total.per_tuple;
5078 : 8501 : locContext.total.per_tuple = 0;
5079 : : }
5080 : 457676 : rinfo->eval_cost = locContext.total;
5081 : : }
5082 : 3455449 : context->total.startup += rinfo->eval_cost.startup;
5083 : 3455449 : context->total.per_tuple += rinfo->eval_cost.per_tuple;
5084 : : /* do NOT recurse into children */
7203 5085 : 3455449 : 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 [ + + ]: 3904060 : if (IsA(node, FuncExpr))
5111 : : {
2802 5112 : 251681 : add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
5113 : : &context->total);
5114 : : }
7203 5115 [ + + ]: 3652379 : else if (IsA(node, OpExpr) ||
5116 [ + + ]: 3141313 : IsA(node, DistinctExpr) ||
5117 [ + + ]: 3140672 : IsA(node, NullIfExpr))
5118 : : {
5119 : : /* rely on struct equivalence to treat these all alike */
5120 : 511961 : set_opfuncid((OpExpr *) node);
2802 5121 : 511961 : add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
5122 : : &context->total);
5123 : : }
8506 5124 [ + + ]: 3140418 : else if (IsA(node, ScalarArrayOpExpr))
5125 : : {
7625 5126 : 34070 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
7313 bruce@momjian.us 5127 : 34070 : Node *arraynode = (Node *) lsecond(saop->args);
5128 : : QualCost sacosts;
5129 : : QualCost hcosts;
1012 tgl@sss.pgh.pa.us 5130 : 34070 : double estarraylen = estimate_array_length(context->root, arraynode);
5131 : :
7203 5132 : 34070 : set_sa_opfuncid(saop);
2802 5133 : 34070 : sacosts.startup = sacosts.per_tuple = 0;
5134 : 34070 : add_function_cost(context->root, saop->opfuncid, NULL,
5135 : : &sacosts);
5136 : :
2013 drowley@postgresql.o 5137 [ + + ]: 34070 : if (OidIsValid(saop->hashfuncid))
5138 : : {
5139 : : /* Handle costs for hashed ScalarArrayOpExpr */
5140 : 318 : hcosts.startup = hcosts.per_tuple = 0;
5141 : :
5142 : 318 : add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
5143 : 318 : context->total.startup += sacosts.startup + hcosts.startup;
5144 : :
5145 : : /* Estimate the cost of building the hashtable. */
5146 : 318 : 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 : 318 : 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 : 33752 : context->total.startup += sacosts.startup;
5167 : 67504 : context->total.per_tuple += sacosts.per_tuple *
1012 tgl@sss.pgh.pa.us 5168 : 33752 : estimate_array_length(context->root, arraynode) * 0.5;
5169 : : }
5170 : : }
5650 5171 [ + + ]: 3106348 : else if (IsA(node, Aggref) ||
5172 [ + + ]: 3050261 : 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 : 59565 : return false; /* don't recurse into children */
5184 : : }
1666 5185 [ + + ]: 3046783 : 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 : : }
7069 5191 [ + + ]: 3046425 : else if (IsA(node, CoerceViaIO))
5192 : : {
5193 : 20008 : CoerceViaIO *iocoerce = (CoerceViaIO *) node;
5194 : : Oid iofunc;
5195 : : Oid typioparam;
5196 : : bool typisvarlena;
5197 : :
5198 : : /* check the result type's input function */
5199 : 20008 : getTypeInputInfo(iocoerce->resulttype,
5200 : : &iofunc, &typioparam);
2802 5201 : 20008 : add_function_cost(context->root, iofunc, NULL,
5202 : : &context->total);
5203 : : /* check the input type's output function */
7069 5204 : 20008 : getTypeOutputInfo(exprType((Node *) iocoerce->arg),
5205 : : &iofunc, &typisvarlena);
2802 5206 : 20008 : add_function_cost(context->root, iofunc, NULL,
5207 : : &context->total);
5208 : : }
7139 5209 [ + + ]: 3026417 : else if (IsA(node, ArrayCoerceExpr))
5210 : : {
5211 : 3879 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
5212 : : QualCost perelemcost;
5213 : :
3299 5214 : 3879 : cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
5215 : : context->root);
5216 : 3879 : context->total.startup += perelemcost.startup;
5217 [ + + ]: 3879 : if (perelemcost.per_tuple > 0)
5218 : 62 : context->total.per_tuple += perelemcost.per_tuple *
1012 5219 : 62 : estimate_array_length(context->root, (Node *) acoerce->arg);
5220 : : }
7593 5221 [ + + ]: 3022538 : 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 : :
7203 5227 [ + - + + : 870 : foreach(lc, rcexpr->opnos)
+ + ]
5228 : : {
6906 bruce@momjian.us 5229 : 595 : Oid opid = lfirst_oid(lc);
5230 : :
2802 tgl@sss.pgh.pa.us 5231 : 595 : add_function_cost(context->root, get_opcode(opid), NULL,
5232 : : &context->total);
5233 : : }
5234 : : }
3377 5235 [ + + ]: 3022263 : else if (IsA(node, MinMaxExpr) ||
1244 michael@paquier.xyz 5236 [ + + ]: 3022040 : IsA(node, SQLValueFunction) ||
3377 tgl@sss.pgh.pa.us 5237 [ + + ]: 3018337 : IsA(node, XmlExpr) ||
5238 [ + + ]: 3018177 : IsA(node, CoerceToDomain) ||
935 amitlan@postgresql.o 5239 [ + + ]: 3011641 : IsA(node, NextValueExpr) ||
5240 [ + + ]: 3011327 : IsA(node, JsonExpr))
5241 : : {
5242 : : /* Treat all these as having cost 1 */
3377 tgl@sss.pgh.pa.us 5243 : 13515 : context->total.per_tuple += cpu_operator_cost;
5244 : : }
8674 5245 [ - + ]: 3008748 : else if (IsA(node, SubLink))
5246 : : {
5247 : : /* This routine should not be applied to un-planned expressions */
8480 tgl@sss.pgh.pa.us 5248 [ # # ]:UBC 0 : elog(ERROR, "cannot handle unplanned sub-select");
5249 : : }
8703 tgl@sss.pgh.pa.us 5250 [ + + ]:CBC 3008748 : 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 : : */
8470 bruce@momjian.us 5258 : 33061 : SubPlan *subplan = (SubPlan *) node;
5259 : :
6625 tgl@sss.pgh.pa.us 5260 : 33061 : context->total.startup += subplan->startup_cost;
5261 : 33061 : 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 : 33061 : return false;
5268 : : }
5269 [ + + ]: 2975687 : 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 : : }
3889 5282 [ + + ]: 2974289 : 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 : 5585 : return false;
5295 : : }
5296 : :
5297 : : /* recurse into children */
683 peter@eisentraut.org 5298 : 3804093 : 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
5289 tgl@sss.pgh.pa.us 5314 : 870953 : get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
5315 : : ParamPathInfo *param_info,
5316 : : QualCost *qpqual_cost)
5317 : : {
5318 [ + + ]: 870953 : if (param_info)
5319 : : {
5320 : : /* Include costs of pushed-down clauses */
5321 : 222802 : cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
5322 : :
5323 : 222802 : qpqual_cost->startup += baserel->baserestrictcost.startup;
5324 : 222802 : qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
5325 : : }
5326 : : else
5327 : 648151 : *qpqual_cost = baserel->baserestrictcost;
5328 : 870953 : }
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
5372 5362 : 196653 : 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 : : */
3475 5385 [ + + ]: 196653 : if (IS_OUTER_JOIN(jointype))
5386 : : {
6365 5387 : 70058 : joinquals = NIL;
5372 5388 [ + + + + : 165590 : foreach(l, restrictlist)
+ + ]
5389 : : {
3472 5390 : 95532 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5391 : :
3097 5392 [ + + + - ]: 95532 : if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
6365 5393 : 87663 : joinquals = lappend(joinquals, rinfo);
5394 : : }
5395 : : }
5396 : : else
5372 5397 : 126595 : joinquals = restrictlist;
5398 : :
5399 : : /*
5400 : : * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5401 : : */
6365 5402 [ + + ]: 381043 : jselec = clauselist_selectivity(root,
5403 : : joinquals,
5404 : : 0,
48 rguo@postgresql.org 5405 [ + + ]:GNC 184390 : (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 [ + + + + ]: 196653 : if (jointype == JOIN_RIGHT_SEMI || jointype == JOIN_RIGHT_ANTI)
5417 : 18459 : avgmatch = 1.0;
5418 : : else
5419 : : {
5420 : 178194 : init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
5421 : :
5422 : 178194 : 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 [ + + ]: 178194 : if (jselec > 0) /* protect against zero divide */
5441 : : {
5442 : 178144 : avgmatch = nselec * innerrel->rows / jselec;
5443 : : /* Clamp to sane range */
5444 [ + + ]: 178144 : avgmatch = Max(1.0, avgmatch);
5445 : : }
5446 : : else
5447 : 50 : avgmatch = 1.0;
5448 : : }
5449 : :
5450 : : /* Avoid leaking a lot of ListCells */
3475 tgl@sss.pgh.pa.us 5451 [ + + ]:CBC 196653 : if (IS_OUTER_JOIN(jointype))
6365 5452 : 70058 : list_free(joinquals);
5453 : :
5372 5454 : 196653 : semifactors->outer_match_frac = jselec;
5455 : 196653 : semifactors->match_count = avgmatch;
5456 : 196653 : }
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
1891 peter@eisentraut.org 5469 : 719623 : has_indexed_join_quals(NestPath *path)
5470 : : {
5471 : 719623 : JoinPath *joinpath = &path->jpath;
5289 tgl@sss.pgh.pa.us 5472 : 719623 : Relids joinrelids = joinpath->path.parent->relids;
5473 : 719623 : 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 [ + + ]: 719623 : if (joinpath->joinrestrictinfo != NIL)
5480 : 533166 : return false;
5481 : : /* Nor if the inner path isn't parameterized at all */
5482 [ + + ]: 186457 : if (innerpath->param_info == NULL)
5483 : 2544 : return false;
5484 : :
5485 : : /* Find the indexclauses list for the inner scan */
5486 [ + + + ]: 183913 : switch (innerpath->pathtype)
5487 : : {
5488 : 118686 : case T_IndexScan:
5489 : : case T_IndexOnlyScan:
5490 : 118686 : indexclauses = ((IndexPath *) innerpath)->indexclauses;
5491 : 118686 : break;
5492 : 307 : case T_BitmapHeapScan:
5493 : : {
5494 : : /* Accept only a simple bitmap scan, not AND/OR cases */
5237 bruce@momjian.us 5495 : 307 : Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
5496 : :
5497 [ + + ]: 307 : if (IsA(bmqual, IndexPath))
5498 : 267 : indexclauses = ((IndexPath *) bmqual)->indexclauses;
5499 : : else
5500 : 40 : return false;
5501 : 267 : break;
5502 : : }
5289 tgl@sss.pgh.pa.us 5503 : 64920 : 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 : : */
5372 5510 : 64920 : 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 : : */
5289 5519 : 118953 : found_one = false;
5520 [ + - + + : 237411 : foreach(lc, innerpath->param_info->ppi_clauses)
+ + ]
5521 : : {
5522 : 123761 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
5523 : :
5524 [ + + ]: 123761 : if (join_clause_is_movable_into(rinfo,
5525 : 123761 : innerpath->parent->relids,
5526 : : joinrelids))
5527 : : {
2802 5528 [ + + ]: 123321 : if (!is_redundant_with_indexclauses(rinfo, indexclauses))
5289 5529 : 5303 : return false;
5530 : 118018 : found_one = true;
5531 : : }
5532 : : }
5533 : 113650 : 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
6457 5562 : 574955 : approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
5563 : : {
5564 : : double tuples;
5372 5565 : 574955 : double outer_tuples = path->outerjoinpath->rows;
5566 : 574955 : double inner_tuples = path->innerjoinpath->rows;
5567 : : SpecialJoinInfo sjinfo;
6631 5568 : 574955 : Selectivity selec = 1.0;
5569 : : ListCell *l;
5570 : :
5571 : : /*
5572 : : * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5573 : : */
931 amitlan@postgresql.o 5574 : 574955 : init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
5575 : 574955 : path->innerjoinpath->parent->relids);
5576 : :
5577 : : /* Get the approximate selectivity */
9260 tgl@sss.pgh.pa.us 5578 [ + + + + : 1216319 : foreach(l, quals)
+ + ]
5579 : : {
5580 : 641364 : Node *qual = (Node *) lfirst(l);
5581 : :
5582 : : /* Note that clause_selectivity will be able to cache its result */
3476 simon@2ndQuadrant.co 5583 : 641364 : selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5584 : : }
5585 : :
5586 : : /* Apply it to the input relation sizes */
6457 tgl@sss.pgh.pa.us 5587 : 574955 : tuples = selec * outer_tuples * inner_tuples;
5588 : :
6631 5589 : 574955 : 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
7799 5607 : 392170 : set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
5608 : : {
5609 : : double nrows;
5610 : :
5611 : : /* Should only be applied to base relations */
8647 5612 [ - + ]: 392170 : Assert(rel->relid > 0);
5613 : :
8316 5614 : 784320 : nrows = rel->tuples *
8317 5615 : 392170 : clauselist_selectivity(root,
5616 : : rel->baserestrictinfo,
5617 : : 0,
5618 : : JOIN_INNER,
5619 : : NULL);
5620 : :
8316 5621 : 392150 : rel->rows = clamp_row_est(nrows);
5622 : :
7172 5623 : 392150 : cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
5624 : :
9773 5625 : 392150 : set_rel_width(root, rel);
11052 scrappy@hub.org 5626 : 392150 : }
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
5289 tgl@sss.pgh.pa.us 5637 : 133462 : 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 : : */
2618 5649 : 133462 : allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5289 5650 : 266924 : nrows = rel->tuples *
5651 : 133462 : clauselist_selectivity(root,
5652 : : allclauses,
3400 5653 : 133462 : rel->relid, /* do not use 0! */
5654 : : JOIN_INNER,
5655 : : NULL);
5289 5656 : 133462 : nrows = clamp_row_est(nrows);
5657 : : /* For safety, make sure result is not more than the base estimate */
5658 [ - + ]: 133462 : if (nrows > rel->rows)
5289 tgl@sss.pgh.pa.us 5659 :UBC 0 : nrows = rel->rows;
5289 tgl@sss.pgh.pa.us 5660 :CBC 133462 : 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
7799 5686 : 202936 : set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
5687 : : RelOptInfo *outer_rel,
5688 : : RelOptInfo *inner_rel,
5689 : : SpecialJoinInfo *sjinfo,
5690 : : List *restrictlist)
5691 : : {
5372 5692 : 202936 : 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 : 202936 : }
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
5289 5718 : 8722 : 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 : 8722 : 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 [ + + ]: 8722 : if (nrows > rel->rows)
5745 : 386 : nrows = rel->rows;
5746 : 8722 : 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
5372 5759 : 211658 : 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 : : {
6633 5768 : 211658 : 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 : : */
3768 5789 : 211658 : 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 : : */
7276 5800 [ + + ]: 211658 : if (IS_OUTER_JOIN(jointype))
5801 : : {
5802 : 62380 : List *joinquals = NIL;
5803 : 62380 : List *pushedquals = NIL;
5804 : : ListCell *l;
5805 : :
5806 : : /* Grovel through the clauses to separate into two lists */
5807 [ + + + + : 145714 : foreach(l, restrictlist)
+ + ]
5808 : : {
3472 5809 : 83334 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5810 : :
3097 5811 [ + + + + ]: 83334 : if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
7276 5812 : 5476 : pushedquals = lappend(pushedquals, rinfo);
5813 : : else
5814 : 77858 : joinquals = lappend(joinquals, rinfo);
5815 : : }
5816 : :
5817 : : /* Get the separate selectivities */
3779 5818 : 62380 : jselec = clauselist_selectivity(root,
5819 : : joinquals,
5820 : : 0,
5821 : : jointype,
5822 : : sjinfo);
7276 5823 : 62380 : pselec = clauselist_selectivity(root,
5824 : : pushedquals,
5825 : : 0,
5826 : : jointype,
5827 : : sjinfo);
5828 : :
5829 : : /* Avoid leaking a lot of ListCells */
5830 : 62380 : list_free(joinquals);
5831 : 62380 : list_free(pushedquals);
5832 : : }
5833 : : else
5834 : : {
3779 5835 : 149278 : jselec = clauselist_selectivity(root,
5836 : : restrictlist,
5837 : : 0,
5838 : : jointype,
5839 : : sjinfo);
7276 5840 : 149278 : 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 : : */
9369 5855 [ + + + + : 211658 : switch (jointype)
+ - ]
5856 : : {
5857 : 142668 : case JOIN_INNER:
3768 5858 : 142668 : nrows = outer_rows * inner_rows * fkselec * jselec;
5859 : : /* pselec not used */
9369 5860 : 142668 : break;
5861 : 48779 : case JOIN_LEFT:
3768 5862 : 48779 : nrows = outer_rows * inner_rows * fkselec * jselec;
5372 5863 [ + + ]: 48779 : if (nrows < outer_rows)
5864 : 20637 : nrows = outer_rows;
7276 5865 : 48779 : nrows *= pselec;
9369 5866 : 48779 : break;
5867 : 1447 : case JOIN_FULL:
3768 5868 : 1447 : nrows = outer_rows * inner_rows * fkselec * jselec;
5372 5869 [ + + ]: 1447 : if (nrows < outer_rows)
5870 : 1004 : nrows = outer_rows;
5871 [ + + ]: 1447 : if (nrows < inner_rows)
5872 : 100 : nrows = inner_rows;
7276 5873 : 1447 : nrows *= pselec;
9369 5874 : 1447 : break;
6633 5875 : 6610 : case JOIN_SEMI:
3768 5876 : 6610 : nrows = outer_rows * fkselec * jselec;
5877 : : /* pselec not used */
8666 5878 : 6610 : break;
6633 5879 : 12154 : case JOIN_ANTI:
3768 5880 : 12154 : nrows = outer_rows * (1.0 - fkselec * jselec);
6633 5881 : 12154 : nrows *= pselec;
8666 5882 : 12154 : break;
9369 tgl@sss.pgh.pa.us 5883 :UBC 0 : default:
5884 : : /* other values not expected here */
8480 5885 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d", (int) jointype);
5886 : : nrows = 0; /* keep compiler quiet */
5887 : : break;
5888 : : }
5889 : :
5372 tgl@sss.pgh.pa.us 5890 :CBC 211658 : 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
3768 5909 : 211658 : get_foreign_key_join_selectivity(PlannerInfo *root,
5910 : : Relids outer_relids,
5911 : : Relids inner_relids,
5912 : : SpecialJoinInfo *sjinfo,
5913 : : List **restrictlist)
5914 : : {
5915 : 211658 : Selectivity fkselec = 1.0;
5916 : 211658 : JoinType jointype = sjinfo->jointype;
5917 : 211658 : List *worklist = *restrictlist;
5918 : : ListCell *lc;
5919 : :
5920 : : /* Consider each FK constraint that is known to match the query */
5921 [ + + + + : 213491 : foreach(lc, root->fkey_list)
+ + ]
5922 : : {
5923 : 1833 : 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 [ + + + + ]: 3326 : if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5933 : 1493 : bms_is_member(fkinfo->ref_relid, inner_relids))
5934 : 1252 : ref_is_outer = false;
5935 [ + + + + ]: 921 : else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5936 : 340 : bms_is_member(fkinfo->con_relid, inner_relids))
5937 : 101 : ref_is_outer = true;
5938 : : else
5939 : 480 : 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 : : */
3402 5953 [ + - + + : 1353 : if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
+ + ]
5954 [ - + ]: 831 : (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 : : */
3768 5963 [ + + ]: 1343 : if (worklist == *restrictlist)
5964 : 1155 : worklist = list_copy(worklist);
5965 : :
5966 : 1343 : removedlist = NIL;
2646 5967 [ + + + + : 2806 : foreach(cell, worklist)
+ + ]
5968 : : {
3768 5969 : 1463 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5970 : 1463 : bool remove_it = false;
5971 : : int i;
5972 : :
5973 : : /* Drop this clause if it matches any column of the FK */
5974 [ + + ]: 1826 : for (i = 0; i < fkinfo->nkeys; i++)
5975 : : {
5976 [ + + ]: 1801 : 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 [ + + ]: 357 : if (fkinfo->eclass[i] == rinfo->parent_ec)
5992 : : {
5993 : 352 : remove_it = true;
5994 : 352 : break;
5995 : : }
5996 : : }
5997 : : else
5998 : : {
5999 : : /*
6000 : : * Otherwise, see if rinfo was previously matched to FK as
6001 : : * a "loose" clause.
6002 : : */
6003 [ + + ]: 1444 : if (list_member_ptr(fkinfo->rinfos[i], rinfo))
6004 : : {
6005 : 1086 : remove_it = true;
6006 : 1086 : break;
6007 : : }
6008 : : }
6009 : : }
6010 [ + + ]: 1463 : if (remove_it)
6011 : : {
2646 6012 : 1438 : worklist = foreach_delete_current(worklist, cell);
3768 6013 : 1438 : 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 : : */
2175 6043 [ + + ]: 1343 : if (removedlist == NIL ||
6044 : 1120 : list_length(removedlist) !=
6045 [ - + ]: 1120 : (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
6046 : : {
3768 6047 : 223 : worklist = list_concat(worklist, removedlist);
6048 : 223 : 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 : : */
3402 6074 [ + - + + ]: 1120 : if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
3768 6075 : 643 : {
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 : : */
3402 6087 : 643 : RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
6088 [ + + ]: 643 : double ref_tuples = Max(ref_rel->tuples, 1.0);
6089 : :
6090 : 643 : 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 : : */
3768 6099 : 477 : RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
6100 [ + - ]: 477 : double ref_tuples = Max(ref_rel->tuples, 1.0);
6101 : :
6102 : 477 : 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 : : */
2175 6115 [ + + ]: 1120 : 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];
556 amitlan@postgresql.o 6124 : 5 : RestrictInfo *rinfo = find_derived_clause_for_ec_member(root,
6125 : : ec,
6126 : : em);
6127 : :
2175 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 : :
3768 6145 : 211658 : *restrictlist = worklist;
2175 6146 [ - + - + ]: 211658 : CLAMP_PROBABILITY(fkselec);
3768 6147 : 211658 : 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
5518 6161 : 29796 : set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6162 : : {
6163 : 29796 : PlannerInfo *subroot = rel->subroot;
6164 : : RelOptInfo *sub_final_rel;
6165 : : ListCell *lc;
6166 : :
6167 : : /* Should only be applied to base relations that are subqueries */
5806 6168 [ - + ]: 29796 : Assert(rel->relid > 0);
3308 andrew@dunslane.net 6169 [ + - - + ]: 29796 : 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 : : */
3871 tgl@sss.pgh.pa.us 6175 : 29796 : sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
6176 : 29796 : 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 : : */
5806 6184 [ + + + + : 144881 : foreach(lc, subroot->parse->targetList)
+ + ]
6185 : : {
3472 6186 : 115085 : TargetEntry *te = lfirst_node(TargetEntry, lc);
5806 6187 : 115085 : Node *texpr = (Node *) te->expr;
5529 6188 : 115085 : int32 item_width = 0;
6189 : :
6190 : : /* junk columns aren't visible to upper query */
5806 6191 [ + + ]: 115085 : if (te->resjunk)
6192 : 3818 : 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 : : */
4943 6200 [ + - - + ]: 111267 : if (te->resno < rel->min_attr || te->resno > rel->max_attr)
4943 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 : : */
5806 tgl@sss.pgh.pa.us 6216 [ + + ]:CBC 111267 : if (IsA(texpr, Var) &&
6217 [ + + ]: 47151 : subroot->parse->setOperations == NULL)
6218 : : {
5664 bruce@momjian.us 6219 : 44237 : Var *var = (Var *) texpr;
5806 tgl@sss.pgh.pa.us 6220 : 44237 : RelOptInfo *subrel = find_base_rel(subroot, var->varno);
6221 : :
6222 : 44237 : item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
6223 : : }
6224 : 111267 : rel->attr_widths[te->resno - rel->min_attr] = item_width;
6225 : : }
6226 : :
6227 : : /* Now estimate number of output rows, etc */
6228 : 29796 : set_baserel_size_estimates(root, rel);
6229 : 29796 : }
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
7799 6241 : 35218 : 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 */
8647 6247 [ - + ]: 35218 : Assert(rel->relid > 0);
7114 6248 [ + - ]: 35218 : rte = planner_rt_fetch(rel->relid, root);
7677 6249 [ - + ]: 35218 : 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 : : */
4708 6255 : 35218 : rel->tuples = 0;
6256 [ + - + + : 70708 : foreach(lc, rte->functions)
+ + ]
6257 : : {
6258 : 35490 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2802 6259 : 35490 : double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
6260 : :
4708 6261 [ + + ]: 35490 : if (ntup > rel->tuples)
6262 : 35239 : rel->tuples = ntup;
6263 : : }
6264 : :
6265 : : /* Now estimate number of output rows, etc */
8316 6266 : 35218 : set_baserel_size_estimates(root, rel);
8919 6267 : 35218 : }
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
3505 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);
3308 andrew@dunslane.net 6283 [ + - - + ]: 602 : Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
6284 : :
3505 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
7376 mail@joeconway.com 6301 : 6779 : 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 [ - + ]: 6779 : Assert(rel->relid > 0);
7114 tgl@sss.pgh.pa.us 6307 [ + - ]: 6779 : rte = planner_rt_fetch(rel->relid, root);
7376 mail@joeconway.com 6308 [ - + ]: 6779 : 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 : 6779 : rel->tuples = list_length(rte->values_lists);
6317 : :
6318 : : /* Now estimate number of output rows, etc */
6319 : 6779 : set_baserel_size_estimates(root, rel);
6320 : 6779 : }
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
3871 tgl@sss.pgh.pa.us 6333 : 4009 : 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 */
6582 6338 [ - + ]: 4009 : Assert(rel->relid > 0);
6339 [ + - ]: 4009 : rte = planner_rt_fetch(rel->relid, root);
6340 [ - + ]: 4009 : Assert(rte->rtekind == RTE_CTE);
6341 : :
6342 [ + + ]: 4009 : 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 : : */
1663 6349 : 696 : rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
6350 : : }
6351 : : else
6352 : : {
6353 : : /* Otherwise just believe the CTE's rowcount estimate */
3871 6354 : 3313 : rel->tuples = cte_rows;
6355 : : }
6356 : :
6357 : : /* Now estimate number of output rows, etc */
6582 6358 : 4009 : set_baserel_size_estimates(root, rel);
6359 : 4009 : }
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
3482 kgrittn@postgresql.o 6371 : 407 : 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 [ - + ]: 407 : Assert(rel->relid > 0);
6377 [ + - ]: 407 : rte = planner_rt_fetch(rel->relid, root);
6378 [ - + ]: 407 : 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 : 407 : rel->tuples = rte->enrtuples;
6387 [ - + ]: 407 : if (rel->tuples < 0)
3482 kgrittn@postgresql.o 6388 :UBC 0 : rel->tuples = 1000;
6389 : :
6390 : : /* Now estimate number of output rows, etc */
3482 kgrittn@postgresql.o 6391 :CBC 407 : set_baserel_size_estimates(root, rel);
6392 : 407 : }
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
2814 tgl@sss.pgh.pa.us 6404 : 3747 : set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6405 : : {
6406 : : /* Should only be applied to RTE_RESULT base relations */
6407 [ - + ]: 3747 : Assert(rel->relid > 0);
6408 [ + - - + ]: 3747 : Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6409 : :
6410 : : /* RTE_RESULT always generates a single row, natively */
6411 : 3747 : rel->tuples = 1;
6412 : :
6413 : : /* Now estimate number of output rows, etc */
6414 : 3747 : set_baserel_size_estimates(root, rel);
6415 : 3747 : }
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
5713 6433 : 1331 : set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
6434 : : {
6435 : : /* Should only be applied to base relations */
6436 [ - + ]: 1331 : Assert(rel->relid > 0);
6437 : :
6438 : 1331 : rel->rows = 1000; /* entirely bogus default estimate */
6439 : :
6440 : 1331 : cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
6441 : :
6442 : 1331 : set_rel_width(root, rel);
6443 : 1331 : }
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
7799 6468 : 393481 : set_rel_width(PlannerInfo *root, RelOptInfo *rel)
6469 : : {
6569 6470 [ + - ]: 393481 : Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
1028 6471 : 393481 : int64 tuple_width = 0;
5806 6472 : 393481 : bool have_wholerow_var = false;
6473 : : ListCell *lc;
6474 : :
6475 : : /* Vars are assumed to have cost zero, but other exprs do not */
3864 6476 : 393481 : rel->reltarget->cost.startup = 0;
6477 : 393481 : rel->reltarget->cost.per_tuple = 0;
6478 : :
6479 [ + + + + : 1381928 : foreach(lc, rel->reltarget->exprs)
+ + ]
6480 : : {
6565 6481 : 988447 : 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 : : */
5160 6489 [ + + ]: 988447 : if (IsA(node, Var) &&
6490 [ + + ]: 968753 : ((Var *) node)->varno == rel->relid)
8164 6491 : 247535 : {
6565 6492 : 968658 : Var *var = (Var *) node;
6493 : : int ndx;
6494 : : int32 item_width;
6495 : :
6496 [ - + ]: 968658 : Assert(var->varattno >= rel->min_attr);
6497 [ - + ]: 968658 : Assert(var->varattno <= rel->max_attr);
6498 : :
6499 : 968658 : 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 : : */
5806 6505 [ + + ]: 968658 : if (var->varattno == 0)
6506 : : {
6507 : 2163 : have_wholerow_var = true;
6508 : 2163 : 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 : : */
6565 6515 [ + + ]: 966495 : if (rel->attr_widths[ndx] > 0)
6516 : : {
6517 : 201304 : tuple_width += rel->attr_widths[ndx];
8506 6518 : 201304 : continue;
6519 : : }
6520 : :
6521 : : /* Try to get column width from statistics */
5806 6522 [ + + + + ]: 765191 : if (reloid != InvalidOid && var->varattno > 0)
6523 : : {
6565 6524 : 606687 : item_width = get_attavgwidth(reloid, var->varattno);
6525 [ + + ]: 606687 : if (item_width > 0)
6526 : : {
6527 : 517656 : rel->attr_widths[ndx] = item_width;
6528 : 517656 : tuple_width += item_width;
6529 : 517656 : 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 : 247535 : item_width = get_typavgwidth(var->vartype, var->vartypmod);
6538 [ - + ]: 247535 : Assert(item_width > 0);
6539 : 247535 : rel->attr_widths[ndx] = item_width;
6540 : 247535 : tuple_width += item_width;
6541 : : }
6542 [ + + ]: 19789 : 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 : 2068 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
1517 6549 : 2068 : PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
6550 : : QualCost cost;
6551 : :
6565 6552 : 2068 : tuple_width += phinfo->ph_width;
3889 6553 : 2068 : cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
3864 6554 : 2068 : rel->reltarget->cost.startup += cost.startup;
6555 : 2068 : 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 : :
6302 6567 : 17721 : item_width = get_typavgwidth(exprType(node), exprTypmod(node));
6568 [ - + ]: 17721 : Assert(item_width > 0);
6569 : 17721 : tuple_width += item_width;
6570 : : /* Not entirely clear if we need to account for cost, but do so */
3889 6571 : 17721 : cost_qual_eval_node(&cost, node, root);
3864 6572 : 17721 : rel->reltarget->cost.startup += cost.startup;
6573 : 17721 : 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 : : */
5806 6581 [ + + ]: 393481 : if (have_wholerow_var)
6582 : : {
1028 6583 : 2163 : int64 wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
6584 : :
5806 6585 [ + + ]: 2163 : if (reloid != InvalidOid)
6586 : : {
6587 : : /* Real relation, so estimate true tuple width */
6588 : 1643 : wholerow_width += get_relation_data_width(reloid,
3400 6589 : 1643 : 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 : :
5806 6596 [ + + ]: 1410 : for (i = 1; i <= rel->max_attr; i++)
6597 : 890 : wholerow_width += rel->attr_widths[i - rel->min_attr];
6598 : : }
6599 : :
1028 6600 : 2163 : 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 : : */
5806 6606 : 2163 : tuple_width += wholerow_width;
6607 : : }
6608 : :
1028 6609 : 393481 : rel->reltarget->width = clamp_width_est(tuple_width);
11052 scrappy@hub.org 6610 : 393481 : }
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 *
3871 tgl@sss.pgh.pa.us 6625 : 463213 : set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
6626 : : {
1028 6627 : 463213 : int64 tuple_width = 0;
6628 : : ListCell *lc;
6629 : :
6630 : : /* Vars are assumed to have cost zero, but other exprs do not */
3871 6631 : 463213 : target->cost.startup = 0;
6632 : 463213 : target->cost.per_tuple = 0;
6633 : :
6634 [ + + + + : 1598493 : foreach(lc, target->exprs)
+ + ]
6635 : : {
6636 : 1135280 : Node *node = (Node *) lfirst(lc);
6637 : :
1302 drowley@postgresql.o 6638 : 1135280 : tuple_width += get_expr_width(root, node);
6639 : :
6640 : : /* For non-Vars, account for evaluation cost */
6641 [ + + ]: 1135280 : if (!IsA(node, Var))
6642 : : {
6643 : : QualCost cost;
6644 : :
3871 tgl@sss.pgh.pa.us 6645 : 498332 : cost_qual_eval_node(&cost, node, root);
6646 : 498332 : target->cost.startup += cost.startup;
6647 : 498332 : target->cost.per_tuple += cost.per_tuple;
6648 : : }
6649 : : }
6650 : :
1028 6651 : 463213 : target->width = clamp_width_est(tuple_width);
6652 : :
3871 6653 : 463213 : 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
1302 drowley@postgresql.o 6663 : 1348545 : get_expr_width(PlannerInfo *root, const Node *expr)
6664 : : {
6665 : : int32 width;
6666 : :
6667 [ + + ]: 1348545 : if (IsA(expr, Var))
6668 : : {
6669 : 841924 : const Var *var = (const Var *) expr;
6670 : :
6671 : : /* We should not see any upper-level Vars here */
6672 [ - + ]: 841924 : Assert(var->varlevelsup == 0);
6673 : :
6674 : : /* Try to get data from RelOptInfo cache */
6675 [ + + ]: 841924 : if (!IS_SPECIAL_VARNO(var->varno) &&
6676 [ + - ]: 837431 : var->varno < root->simple_rel_array_size)
6677 : : {
6678 : 837431 : RelOptInfo *rel = root->simple_rel_array[var->varno];
6679 : :
6680 [ + + ]: 837431 : if (rel != NULL &&
6681 [ + - ]: 822668 : var->varattno >= rel->min_attr &&
6682 [ + - ]: 822668 : var->varattno <= rel->max_attr)
6683 : : {
6684 : 822668 : int ndx = var->varattno - rel->min_attr;
6685 : :
6686 [ + + ]: 822668 : if (rel->attr_widths[ndx] > 0)
6687 : 796164 : return rel->attr_widths[ndx];
6688 : : }
6689 : : }
6690 : :
6691 : : /*
6692 : : * No cached data available, so estimate using just the type info.
6693 : : */
6694 : 45760 : width = get_typavgwidth(var->vartype, var->vartypmod);
6695 [ - + ]: 45760 : Assert(width > 0);
6696 : :
6697 : 45760 : return width;
6698 : : }
6699 : :
6700 : 506621 : width = get_typavgwidth(exprType(expr), exprTypmod(expr));
6701 [ - + ]: 506621 : Assert(width > 0);
6702 : 506621 : 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
9773 tgl@sss.pgh.pa.us 6711 : 3567828 : relation_byte_size(double tuples, int width)
6712 : : {
4251 6713 : 3567828 : 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
9773 6722 : 6136 : page_size(double tuples, int width)
6723 : : {
6724 : 6136 : 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
3559 rhaas@postgresql.org 6732 : 369444 : get_parallel_divisor(Path *path)
6733 : : {
6734 : 369444 : 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 : : */
3253 6747 [ + + ]: 369444 : if (parallel_leader_participation)
6748 : : {
6749 : : double leader_contribution;
6750 : :
6751 : 368439 : leader_contribution = 1.0 - (0.3 * path->parallel_workers);
6752 [ + + ]: 368439 : if (leader_contribution > 0)
6753 : 366288 : parallel_divisor += leader_contribution;
6754 : : }
6755 : :
3559 6756 : 369444 : 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
1029 tgl@sss.pgh.pa.us 6772 : 567841 : 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 : : */
3545 rhaas@postgresql.org 6788 : 567841 : cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6789 : :
6790 : : /*
6791 : : * Estimate number of main-table pages fetched.
6792 : : */
6793 : 567841 : tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6794 : :
6795 [ + + ]: 567841 : 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 : : */
3258 6802 : 567841 : 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 [ + + ]: 567841 : heap_pages = Min(pages_fetched, baserel->pages);
619 tgl@sss.pgh.pa.us 6813 : 567841 : maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
6814 : :
3545 rhaas@postgresql.org 6815 [ + + ]: 567841 : 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 : 126049 : pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6824 : : baserel->pages,
6825 : : get_indexpath_pages(bitmapqual),
6826 : : root);
6827 : 126049 : pages_fetched /= loop_count;
6828 : : }
6829 : :
6830 [ + + ]: 567841 : if (pages_fetched >= T)
6831 : 53954 : pages_fetched = T;
6832 : : else
6833 : 513887 : pages_fetched = ceil(pages_fetched);
6834 : :
3258 6835 [ + + ]: 567841 : 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 : :
1029 tgl@sss.pgh.pa.us 6864 [ + + ]: 567841 : if (cost_p)
6865 : 456506 : *cost_p = indexTotalCost;
6866 [ + + ]: 567841 : if (tuples_p)
6867 : 456506 : *tuples_p = tuples_fetched;
6868 : :
3545 rhaas@postgresql.org 6869 : 567841 : 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
811 rguo@postgresql.org 6883 : 36364 : compute_gather_rows(Path *path)
6884 : : {
6885 [ - + ]: 36364 : Assert(path->parallel_workers > 0);
6886 : :
6887 : 36364 : return clamp_row_est(path->rows * get_parallel_divisor(path));
6888 : : }
|