1 /*-------------------------------------------------------------------------
4 * Routines to compute (and set) relation sizes and path costs
6 * Path costs are measured in arbitrary units established by these basic
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
15 * We expect that the kernel will typically do some amount of read-ahead
16 * optimization; this in conjunction with seek costs means that seq_page_cost
17 * is normally considerably less than random_page_cost. (However, if the
18 * database is fully cached in RAM, it is reasonable to set them equal.)
20 * We also use a rough estimate "effective_cache_size" of the number of
21 * disk pages in Postgres + OS-level disk cache. (We can't simply use
22 * NBuffers for this purpose because that would ignore the effects of
23 * the kernel's disk cache.)
25 * Obviously, taking constants for these values is an oversimplification,
26 * but it's tough enough to get any useful estimates even at this level of
27 * detail. Note that all of these parameters are user-settable, in case
28 * the default values are drastically off for a particular platform.
30 * seq_page_cost and random_page_cost can also be overridden for an individual
31 * tablespace, in case some data is on a fast disk and other data is on a slow
32 * disk. Per-tablespace overrides never apply to temporary work files such as
33 * an external sort or a materialize node that overflows work_mem.
35 * We compute two separate costs for each path:
36 * total_cost: total estimated cost to fetch all tuples
37 * startup_cost: cost that is expended before first tuple is fetched
38 * In some scenarios, such as when there is a LIMIT or we are implementing
39 * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
40 * path's result. A caller can estimate the cost of fetching a partial
41 * result by interpolating between startup_cost and total_cost. In detail:
42 * actual_cost = startup_cost +
43 * (total_cost - startup_cost) * tuples_to_fetch / path->rows;
44 * Note that a base relation's rows count (and, by extension, plan_rows for
45 * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
46 * that this equation works properly. (Also, these routines guarantee not to
47 * set the rows count to zero, so there will be no zero divide.) The LIMIT is
48 * applied as a top-level plan node.
50 * For largely historical reasons, most of the routines in this module use
51 * the passed result Path only to store their results (rows, startup_cost and
52 * total_cost) into. All the input data they need is passed as separate
53 * parameters, even though much of it could be extracted from the Path.
54 * An exception is made for the cost_XXXjoin() routines, which expect all
55 * the other fields of the passed XXXPath to be filled in, and similarly
56 * cost_index() assumes the passed IndexPath is valid except for its output
60 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
61 * Portions Copyright (c) 1994, Regents of the University of California
64 * src/backend/optimizer/path/costsize.c
66 *-------------------------------------------------------------------------
72 #include <float.h> /* for _isnan */
76 #include "access/htup_details.h"
77 #include "executor/executor.h"
78 #include "executor/nodeHash.h"
79 #include "miscadmin.h"
80 #include "nodes/nodeFuncs.h"
81 #include "optimizer/clauses.h"
82 #include "optimizer/cost.h"
83 #include "optimizer/pathnode.h"
84 #include "optimizer/paths.h"
85 #include "optimizer/placeholder.h"
86 #include "optimizer/plancat.h"
87 #include "optimizer/planmain.h"
88 #include "optimizer/restrictinfo.h"
89 #include "parser/parsetree.h"
90 #include "utils/lsyscache.h"
91 #include "utils/selfuncs.h"
92 #include "utils/spccache.h"
93 #include "utils/tuplesort.h"
96 #define LOG2(x) (log(x) / 0.693147180559945)
99 double seq_page_cost = DEFAULT_SEQ_PAGE_COST;
100 double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
101 double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
102 double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
103 double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
105 int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
107 Cost disable_cost = 1.0e10;
109 bool enable_seqscan = true;
110 bool enable_indexscan = true;
111 bool enable_indexonlyscan = true;
112 bool enable_bitmapscan = true;
113 bool enable_tidscan = true;
114 bool enable_sort = true;
115 bool enable_hashagg = true;
116 bool enable_nestloop = true;
117 bool enable_material = true;
118 bool enable_mergejoin = true;
119 bool enable_hashjoin = true;
125 } cost_qual_eval_context;
127 static List *extract_nonindex_conditions(List *qual_clauses, List *indexquals);
128 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
131 static void cost_rescan(PlannerInfo *root, Path *path,
132 Cost *rescan_startup_cost, Cost *rescan_total_cost);
133 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
134 static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
135 ParamPathInfo *param_info,
136 QualCost *qpqual_cost);
137 static bool has_indexed_join_quals(NestPath *joinpath);
138 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
140 static double calc_joinrel_size_estimate(PlannerInfo *root,
143 SpecialJoinInfo *sjinfo,
145 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
146 static double relation_byte_size(double tuples, int width);
147 static double page_size(double tuples, int width);
152 * Force a row-count estimate to a sane value.
155 clamp_row_est(double nrows)
158 * Force estimate to be at least one row, to make explain output look
159 * better and to avoid possible divide-by-zero when interpolating costs.
160 * Make it an integer, too.
173 * Determines and returns the cost of scanning a relation sequentially.
175 * 'baserel' is the relation to be scanned
176 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
179 cost_seqscan(Path *path, PlannerInfo *root,
180 RelOptInfo *baserel, ParamPathInfo *param_info)
182 Cost startup_cost = 0;
184 double spc_seq_page_cost;
185 QualCost qpqual_cost;
188 /* Should only be applied to base relations */
189 Assert(baserel->relid > 0);
190 Assert(baserel->rtekind == RTE_RELATION);
192 /* Mark the path with the correct row estimate */
194 path->rows = param_info->ppi_rows;
196 path->rows = baserel->rows;
199 startup_cost += disable_cost;
201 /* fetch estimated page cost for tablespace containing table */
202 get_tablespace_page_costs(baserel->reltablespace,
209 run_cost += spc_seq_page_cost * baserel->pages;
212 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
214 startup_cost += qpqual_cost.startup;
215 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
216 run_cost += cpu_per_tuple * baserel->tuples;
218 path->startup_cost = startup_cost;
219 path->total_cost = startup_cost + run_cost;
224 * Determines and returns the cost of scanning a relation using an index.
226 * 'path' describes the indexscan under consideration, and is complete
227 * except for the fields to be set by this routine
228 * 'loop_count' is the number of repetitions of the indexscan to factor into
229 * estimates of caching behavior
231 * In addition to rows, startup_cost and total_cost, cost_index() sets the
232 * path's indextotalcost and indexselectivity fields. These values will be
233 * needed if the IndexPath is used in a BitmapIndexScan.
235 * NOTE: path->indexquals must contain only clauses usable as index
236 * restrictions. Any additional quals evaluated as qpquals may reduce the
237 * number of returned tuples, but they won't reduce the number of tuples
238 * we have to fetch from the table, so they don't reduce the scan cost.
241 cost_index(IndexPath *path, PlannerInfo *root, double loop_count)
243 IndexOptInfo *index = path->indexinfo;
244 RelOptInfo *baserel = index->rel;
245 bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
247 Cost startup_cost = 0;
249 Cost indexStartupCost;
251 Selectivity indexSelectivity;
252 double indexCorrelation,
254 double spc_seq_page_cost,
255 spc_random_page_cost;
258 QualCost qpqual_cost;
260 double tuples_fetched;
261 double pages_fetched;
263 /* Should only be applied to base relations */
264 Assert(IsA(baserel, RelOptInfo) &&
265 IsA(index, IndexOptInfo));
266 Assert(baserel->relid > 0);
267 Assert(baserel->rtekind == RTE_RELATION);
270 * Mark the path with the correct row estimate, and identify which quals
271 * will need to be enforced as qpquals.
273 if (path->path.param_info)
275 path->path.rows = path->path.param_info->ppi_rows;
276 /* qpquals come from the rel's restriction clauses and ppi_clauses */
277 qpquals = list_concat(
278 extract_nonindex_conditions(baserel->baserestrictinfo,
280 extract_nonindex_conditions(path->path.param_info->ppi_clauses,
285 path->path.rows = baserel->rows;
286 /* qpquals come from just the rel's restriction clauses */
287 qpquals = extract_nonindex_conditions(baserel->baserestrictinfo,
291 if (!enable_indexscan)
292 startup_cost += disable_cost;
293 /* we don't need to check enable_indexonlyscan; indxpath.c does that */
296 * Call index-access-method-specific code to estimate the processing cost
297 * for scanning the index, as well as the selectivity of the index (ie,
298 * the fraction of main-table tuples we will have to retrieve) and its
299 * correlation to the main-table tuple order.
301 OidFunctionCall7(index->amcostestimate,
302 PointerGetDatum(root),
303 PointerGetDatum(path),
304 Float8GetDatum(loop_count),
305 PointerGetDatum(&indexStartupCost),
306 PointerGetDatum(&indexTotalCost),
307 PointerGetDatum(&indexSelectivity),
308 PointerGetDatum(&indexCorrelation));
311 * Save amcostestimate's results for possible use in bitmap scan planning.
312 * We don't bother to save indexStartupCost or indexCorrelation, because a
313 * bitmap scan doesn't care about either.
315 path->indextotalcost = indexTotalCost;
316 path->indexselectivity = indexSelectivity;
318 /* all costs for touching index itself included here */
319 startup_cost += indexStartupCost;
320 run_cost += indexTotalCost - indexStartupCost;
322 /* estimate number of main-table tuples fetched */
323 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
325 /* fetch estimated page costs for tablespace containing table */
326 get_tablespace_page_costs(baserel->reltablespace,
327 &spc_random_page_cost,
331 * Estimate number of main-table pages fetched, and compute I/O cost.
333 * When the index ordering is uncorrelated with the table ordering,
334 * we use an approximation proposed by Mackert and Lohman (see
335 * index_pages_fetched() for details) to compute the number of pages
336 * fetched, and then charge spc_random_page_cost per page fetched.
338 * When the index ordering is exactly correlated with the table ordering
339 * (just after a CLUSTER, for example), the number of pages fetched should
340 * be exactly selectivity * table_size. What's more, all but the first
341 * will be sequential fetches, not the random fetches that occur in the
342 * uncorrelated case. So if the number of pages is more than 1, we
344 * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
345 * For partially-correlated indexes, we ought to charge somewhere between
346 * these two estimates. We currently interpolate linearly between the
347 * estimates based on the correlation squared (XXX is that appropriate?).
349 * If it's an index-only scan, then we will not need to fetch any heap
350 * pages for which the visibility map shows all tuples are visible.
351 * Hence, reduce the estimated number of heap fetches accordingly.
352 * We use the measured fraction of the entire heap that is all-visible,
353 * which might not be particularly relevant to the subset of the heap
354 * that this query will fetch; but it's not clear how to do better.
360 * For repeated indexscans, the appropriate estimate for the
361 * uncorrelated case is to scale up the number of tuples fetched in
362 * the Mackert and Lohman formula by the number of scans, so that we
363 * estimate the number of pages fetched by all the scans; then
364 * pro-rate the costs for one scan. In this case we assume all the
365 * fetches are random accesses.
367 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
369 (double) index->pages,
373 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
375 max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
378 * In the perfectly correlated case, the number of pages touched by
379 * each scan is selectivity * table_size, and we can use the Mackert
380 * and Lohman formula at the page level to estimate how much work is
381 * saved by caching across scans. We still assume all the fetches are
382 * random, though, which is an overestimate that's hard to correct for
383 * without double-counting the cache effects. (But in most cases
384 * where such a plan is actually interesting, only one page would get
385 * fetched per scan anyway, so it shouldn't matter much.)
387 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
389 pages_fetched = index_pages_fetched(pages_fetched * loop_count,
391 (double) index->pages,
395 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
397 min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
402 * Normal case: apply the Mackert and Lohman formula, and then
403 * interpolate between that and the correlation-derived result.
405 pages_fetched = index_pages_fetched(tuples_fetched,
407 (double) index->pages,
411 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
413 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
414 max_IO_cost = pages_fetched * spc_random_page_cost;
416 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
417 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
420 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
422 if (pages_fetched > 0)
424 min_IO_cost = spc_random_page_cost;
425 if (pages_fetched > 1)
426 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
433 * Now interpolate based on estimated index order correlation to get total
434 * disk I/O cost for main table accesses.
436 csquared = indexCorrelation * indexCorrelation;
438 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
441 * Estimate CPU costs per tuple.
443 * What we want here is cpu_tuple_cost plus the evaluation costs of any
444 * qual clauses that we have to evaluate as qpquals.
446 cost_qual_eval(&qpqual_cost, qpquals, root);
448 startup_cost += qpqual_cost.startup;
449 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
451 run_cost += cpu_per_tuple * tuples_fetched;
453 path->path.startup_cost = startup_cost;
454 path->path.total_cost = startup_cost + run_cost;
458 * extract_nonindex_conditions
460 * Given a list of quals to be enforced in an indexscan, extract the ones that
461 * will have to be applied as qpquals (ie, the index machinery won't handle
462 * them). The actual rules for this appear in create_indexscan_plan() in
463 * createplan.c, but the full rules are fairly expensive and we don't want to
464 * go to that much effort for index paths that don't get selected for the
465 * final plan. So we approximate it as quals that don't appear directly in
466 * indexquals and also are not redundant children of the same EquivalenceClass
467 * as some indexqual. This method neglects some infrequently-relevant
468 * considerations such as clauses that needn't be checked because they are
469 * implied by a partial index's predicate. It does not seem worth the cycles
470 * to try to factor those things in at this stage, even though createplan.c
471 * will take pains to remove such unnecessary clauses from the qpquals list if
472 * this path is selected for use.
475 extract_nonindex_conditions(List *qual_clauses, List *indexquals)
480 foreach(lc, qual_clauses)
482 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
484 Assert(IsA(rinfo, RestrictInfo));
485 if (rinfo->pseudoconstant)
486 continue; /* we may drop pseudoconstants here */
487 if (list_member_ptr(indexquals, rinfo))
488 continue; /* simple duplicate */
489 if (is_redundant_derived_clause(rinfo, indexquals))
490 continue; /* derived from same EquivalenceClass */
491 /* ... skip the predicate proof attempts createplan.c will try ... */
492 result = lappend(result, rinfo);
498 * index_pages_fetched
499 * Estimate the number of pages actually fetched after accounting for
502 * We use an approximation proposed by Mackert and Lohman, "Index Scans
503 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
504 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
505 * The Mackert and Lohman approximation is that the number of pages
508 * min(2TNs/(2T+Ns), T) when T <= b
509 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
510 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
512 * T = # pages in table
513 * N = # tuples in table
514 * s = selectivity = fraction of table to be scanned
515 * b = # buffer pages available (we include kernel space here)
517 * We assume that effective_cache_size is the total number of buffer pages
518 * available for the whole query, and pro-rate that space across all the
519 * tables in the query and the index currently under consideration. (This
520 * ignores space needed for other indexes used by the query, but since we
521 * don't know which indexes will get used, we can't estimate that very well;
522 * and in any case counting all the tables may well be an overestimate, since
523 * depending on the join plan not all the tables may be scanned concurrently.)
525 * The product Ns is the number of tuples fetched; we pass in that
526 * product rather than calculating it here. "pages" is the number of pages
527 * in the object under consideration (either an index or a table).
528 * "index_pages" is the amount to add to the total table space, which was
529 * computed for us by query_planner.
531 * Caller is expected to have ensured that tuples_fetched is greater than zero
532 * and rounded to integer (see clamp_row_est). The result will likewise be
533 * greater than zero and integral.
536 index_pages_fetched(double tuples_fetched, BlockNumber pages,
537 double index_pages, PlannerInfo *root)
539 double pages_fetched;
544 /* T is # pages in table, but don't allow it to be zero */
545 T = (pages > 1) ? (double) pages : 1.0;
547 /* Compute number of pages assumed to be competing for cache space */
548 total_pages = root->total_table_pages + index_pages;
549 total_pages = Max(total_pages, 1.0);
550 Assert(T <= total_pages);
552 /* b is pro-rated share of effective_cache_size */
553 b = (double) effective_cache_size *T / total_pages;
555 /* force it positive and integral */
561 /* This part is the Mackert and Lohman formula */
565 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
566 if (pages_fetched >= T)
569 pages_fetched = ceil(pages_fetched);
575 lim = (2.0 * T * b) / (2.0 * T - b);
576 if (tuples_fetched <= lim)
579 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
584 b + (tuples_fetched - lim) * (T - b) / T;
586 pages_fetched = ceil(pages_fetched);
588 return pages_fetched;
592 * get_indexpath_pages
593 * Determine the total size of the indexes used in a bitmap index path.
595 * Note: if the same index is used more than once in a bitmap tree, we will
596 * count it multiple times, which perhaps is the wrong thing ... but it's
597 * not completely clear, and detecting duplicates is difficult, so ignore it
601 get_indexpath_pages(Path *bitmapqual)
606 if (IsA(bitmapqual, BitmapAndPath))
608 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
610 foreach(l, apath->bitmapquals)
612 result += get_indexpath_pages((Path *) lfirst(l));
615 else if (IsA(bitmapqual, BitmapOrPath))
617 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
619 foreach(l, opath->bitmapquals)
621 result += get_indexpath_pages((Path *) lfirst(l));
624 else if (IsA(bitmapqual, IndexPath))
626 IndexPath *ipath = (IndexPath *) bitmapqual;
628 result = (double) ipath->indexinfo->pages;
631 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
637 * cost_bitmap_heap_scan
638 * Determines and returns the cost of scanning a relation using a bitmap
639 * index-then-heap plan.
641 * 'baserel' is the relation to be scanned
642 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
643 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
644 * 'loop_count' is the number of repetitions of the indexscan to factor into
645 * estimates of caching behavior
647 * Note: the component IndexPaths in bitmapqual should have been costed
648 * using the same loop_count.
651 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
652 ParamPathInfo *param_info,
653 Path *bitmapqual, double loop_count)
655 Cost startup_cost = 0;
658 Selectivity indexSelectivity;
659 QualCost qpqual_cost;
662 double tuples_fetched;
663 double pages_fetched;
664 double spc_seq_page_cost,
665 spc_random_page_cost;
668 /* Should only be applied to base relations */
669 Assert(IsA(baserel, RelOptInfo));
670 Assert(baserel->relid > 0);
671 Assert(baserel->rtekind == RTE_RELATION);
673 /* Mark the path with the correct row estimate */
675 path->rows = param_info->ppi_rows;
677 path->rows = baserel->rows;
679 if (!enable_bitmapscan)
680 startup_cost += disable_cost;
683 * Fetch total cost of obtaining the bitmap, as well as its total
686 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
688 startup_cost += indexTotalCost;
690 /* Fetch estimated page costs for tablespace containing table. */
691 get_tablespace_page_costs(baserel->reltablespace,
692 &spc_random_page_cost,
696 * Estimate number of main-table pages fetched.
698 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
700 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
705 * For repeated bitmap scans, scale up the number of tuples fetched in
706 * the Mackert and Lohman formula by the number of scans, so that we
707 * estimate the number of pages fetched by all the scans. Then
708 * pro-rate for one scan.
710 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
712 get_indexpath_pages(bitmapqual),
714 pages_fetched /= loop_count;
719 * For a single scan, the number of heap pages that need to be fetched
720 * is the same as the Mackert and Lohman formula for the case T <= b
721 * (ie, no re-reads needed).
723 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
725 if (pages_fetched >= T)
728 pages_fetched = ceil(pages_fetched);
731 * For small numbers of pages we should charge spc_random_page_cost
732 * apiece, while if nearly all the table's pages are being read, it's more
733 * appropriate to charge spc_seq_page_cost apiece. The effect is
734 * nonlinear, too. For lack of a better idea, interpolate like this to
735 * determine the cost per page.
737 if (pages_fetched >= 2.0)
738 cost_per_page = spc_random_page_cost -
739 (spc_random_page_cost - spc_seq_page_cost)
740 * sqrt(pages_fetched / T);
742 cost_per_page = spc_random_page_cost;
744 run_cost += pages_fetched * cost_per_page;
747 * Estimate CPU costs per tuple.
749 * Often the indexquals don't need to be rechecked at each tuple ... but
750 * not always, especially not if there are enough tuples involved that the
751 * bitmaps become lossy. For the moment, just assume they will be
752 * rechecked always. This means we charge the full freight for all the
755 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
757 startup_cost += qpqual_cost.startup;
758 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
760 run_cost += cpu_per_tuple * tuples_fetched;
762 path->startup_cost = startup_cost;
763 path->total_cost = startup_cost + run_cost;
767 * cost_bitmap_tree_node
768 * Extract cost and selectivity from a bitmap tree node (index/and/or)
771 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
773 if (IsA(path, IndexPath))
775 *cost = ((IndexPath *) path)->indextotalcost;
776 *selec = ((IndexPath *) path)->indexselectivity;
779 * Charge a small amount per retrieved tuple to reflect the costs of
780 * manipulating the bitmap. This is mostly to make sure that a bitmap
781 * scan doesn't look to be the same cost as an indexscan to retrieve a
784 *cost += 0.1 * cpu_operator_cost * path->rows;
786 else if (IsA(path, BitmapAndPath))
788 *cost = path->total_cost;
789 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
791 else if (IsA(path, BitmapOrPath))
793 *cost = path->total_cost;
794 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
798 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
799 *cost = *selec = 0; /* keep compiler quiet */
804 * cost_bitmap_and_node
805 * Estimate the cost of a BitmapAnd node
807 * Note that this considers only the costs of index scanning and bitmap
808 * creation, not the eventual heap access. In that sense the object isn't
809 * truly a Path, but it has enough path-like properties (costs in particular)
810 * to warrant treating it as one. We don't bother to set the path rows field,
814 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
821 * We estimate AND selectivity on the assumption that the inputs are
822 * independent. This is probably often wrong, but we don't have the info
825 * The runtime cost of the BitmapAnd itself is estimated at 100x
826 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
827 * definitely too simplistic?
831 foreach(l, path->bitmapquals)
833 Path *subpath = (Path *) lfirst(l);
835 Selectivity subselec;
837 cost_bitmap_tree_node(subpath, &subCost, &subselec);
841 totalCost += subCost;
842 if (l != list_head(path->bitmapquals))
843 totalCost += 100.0 * cpu_operator_cost;
845 path->bitmapselectivity = selec;
846 path->path.rows = 0; /* per above, not used */
847 path->path.startup_cost = totalCost;
848 path->path.total_cost = totalCost;
852 * cost_bitmap_or_node
853 * Estimate the cost of a BitmapOr node
855 * See comments for cost_bitmap_and_node.
858 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
865 * We estimate OR selectivity on the assumption that the inputs are
866 * non-overlapping, since that's often the case in "x IN (list)" type
867 * situations. Of course, we clamp to 1.0 at the end.
869 * The runtime cost of the BitmapOr itself is estimated at 100x
870 * cpu_operator_cost for each tbm_union needed. Probably too small,
871 * definitely too simplistic? We are aware that the tbm_unions are
872 * optimized out when the inputs are BitmapIndexScans.
876 foreach(l, path->bitmapquals)
878 Path *subpath = (Path *) lfirst(l);
880 Selectivity subselec;
882 cost_bitmap_tree_node(subpath, &subCost, &subselec);
886 totalCost += subCost;
887 if (l != list_head(path->bitmapquals) &&
888 !IsA(subpath, IndexPath))
889 totalCost += 100.0 * cpu_operator_cost;
891 path->bitmapselectivity = Min(selec, 1.0);
892 path->path.rows = 0; /* per above, not used */
893 path->path.startup_cost = totalCost;
894 path->path.total_cost = totalCost;
899 * Determines and returns the cost of scanning a relation using TIDs.
901 * 'baserel' is the relation to be scanned
902 * 'tidquals' is the list of TID-checkable quals
903 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
906 cost_tidscan(Path *path, PlannerInfo *root,
907 RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
909 Cost startup_cost = 0;
911 bool isCurrentOf = false;
912 QualCost qpqual_cost;
914 QualCost tid_qual_cost;
917 double spc_random_page_cost;
919 /* Should only be applied to base relations */
920 Assert(baserel->relid > 0);
921 Assert(baserel->rtekind == RTE_RELATION);
923 /* Mark the path with the correct row estimate */
925 path->rows = param_info->ppi_rows;
927 path->rows = baserel->rows;
929 /* Count how many tuples we expect to retrieve */
933 if (IsA(lfirst(l), ScalarArrayOpExpr))
935 /* Each element of the array yields 1 tuple */
936 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
937 Node *arraynode = (Node *) lsecond(saop->args);
939 ntuples += estimate_array_length(arraynode);
941 else if (IsA(lfirst(l), CurrentOfExpr))
943 /* CURRENT OF yields 1 tuple */
949 /* It's just CTID = something, count 1 tuple */
955 * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
956 * understands how to do it correctly. Therefore, honor enable_tidscan
957 * only when CURRENT OF isn't present. Also note that cost_qual_eval
958 * counts a CurrentOfExpr as having startup cost disable_cost, which we
959 * subtract off here; that's to prevent other plan types such as seqscan
964 Assert(baserel->baserestrictcost.startup >= disable_cost);
965 startup_cost -= disable_cost;
967 else if (!enable_tidscan)
968 startup_cost += disable_cost;
971 * The TID qual expressions will be computed once, any other baserestrict
972 * quals once per retrived tuple.
974 cost_qual_eval(&tid_qual_cost, tidquals, root);
976 /* fetch estimated page cost for tablespace containing table */
977 get_tablespace_page_costs(baserel->reltablespace,
978 &spc_random_page_cost,
981 /* disk costs --- assume each tuple on a different page */
982 run_cost += spc_random_page_cost * ntuples;
984 /* Add scanning CPU costs */
985 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
987 /* XXX currently we assume TID quals are a subset of qpquals */
988 startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
989 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
990 tid_qual_cost.per_tuple;
991 run_cost += cpu_per_tuple * ntuples;
993 path->startup_cost = startup_cost;
994 path->total_cost = startup_cost + run_cost;
999 * Determines and returns the cost of scanning a subquery RTE.
1001 * 'baserel' is the relation to be scanned
1002 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1005 cost_subqueryscan(Path *path, PlannerInfo *root,
1006 RelOptInfo *baserel, ParamPathInfo *param_info)
1010 QualCost qpqual_cost;
1013 /* Should only be applied to base relations that are subqueries */
1014 Assert(baserel->relid > 0);
1015 Assert(baserel->rtekind == RTE_SUBQUERY);
1017 /* Mark the path with the correct row estimate */
1019 path->rows = param_info->ppi_rows;
1021 path->rows = baserel->rows;
1024 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1025 * any restriction clauses that will be attached to the SubqueryScan node,
1026 * plus cpu_tuple_cost to account for selection and projection overhead.
1028 path->startup_cost = baserel->subplan->startup_cost;
1029 path->total_cost = baserel->subplan->total_cost;
1031 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1033 startup_cost = qpqual_cost.startup;
1034 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1035 run_cost = cpu_per_tuple * baserel->tuples;
1037 path->startup_cost += startup_cost;
1038 path->total_cost += startup_cost + run_cost;
1043 * Determines and returns the cost of scanning a function RTE.
1045 * 'baserel' is the relation to be scanned
1046 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1049 cost_functionscan(Path *path, PlannerInfo *root,
1050 RelOptInfo *baserel, ParamPathInfo *param_info)
1052 Cost startup_cost = 0;
1054 QualCost qpqual_cost;
1059 /* Should only be applied to base relations that are functions */
1060 Assert(baserel->relid > 0);
1061 rte = planner_rt_fetch(baserel->relid, root);
1062 Assert(rte->rtekind == RTE_FUNCTION);
1064 /* Mark the path with the correct row estimate */
1066 path->rows = param_info->ppi_rows;
1068 path->rows = baserel->rows;
1071 * Estimate costs of executing the function expression(s).
1073 * Currently, nodeFunctionscan.c always executes the functions to
1074 * completion before returning any rows, and caches the results in a
1075 * tuplestore. So the function eval cost is all startup cost, and per-row
1076 * costs are minimal.
1078 * XXX in principle we ought to charge tuplestore spill costs if the
1079 * number of rows is large. However, given how phony our rowcount
1080 * estimates for functions tend to be, there's not a lot of point in that
1081 * refinement right now.
1083 cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1085 startup_cost += exprcost.startup + exprcost.per_tuple;
1087 /* Add scanning CPU costs */
1088 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1090 startup_cost += qpqual_cost.startup;
1091 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1092 run_cost += cpu_per_tuple * baserel->tuples;
1094 path->startup_cost = startup_cost;
1095 path->total_cost = startup_cost + run_cost;
1100 * Determines and returns the cost of scanning a VALUES RTE.
1102 * 'baserel' is the relation to be scanned
1103 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1106 cost_valuesscan(Path *path, PlannerInfo *root,
1107 RelOptInfo *baserel, ParamPathInfo *param_info)
1109 Cost startup_cost = 0;
1111 QualCost qpqual_cost;
1114 /* Should only be applied to base relations that are values lists */
1115 Assert(baserel->relid > 0);
1116 Assert(baserel->rtekind == RTE_VALUES);
1118 /* Mark the path with the correct row estimate */
1120 path->rows = param_info->ppi_rows;
1122 path->rows = baserel->rows;
1125 * For now, estimate list evaluation cost at one operator eval per list
1126 * (probably pretty bogus, but is it worth being smarter?)
1128 cpu_per_tuple = cpu_operator_cost;
1130 /* Add scanning CPU costs */
1131 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1133 startup_cost += qpqual_cost.startup;
1134 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1135 run_cost += cpu_per_tuple * baserel->tuples;
1137 path->startup_cost = startup_cost;
1138 path->total_cost = startup_cost + run_cost;
1143 * Determines and returns the cost of scanning a CTE RTE.
1145 * Note: this is used for both self-reference and regular CTEs; the
1146 * possible cost differences are below the threshold of what we could
1147 * estimate accurately anyway. Note that the costs of evaluating the
1148 * referenced CTE query are added into the final plan as initplan costs,
1149 * and should NOT be counted here.
1152 cost_ctescan(Path *path, PlannerInfo *root,
1153 RelOptInfo *baserel, ParamPathInfo *param_info)
1155 Cost startup_cost = 0;
1157 QualCost qpqual_cost;
1160 /* Should only be applied to base relations that are CTEs */
1161 Assert(baserel->relid > 0);
1162 Assert(baserel->rtekind == RTE_CTE);
1164 /* Mark the path with the correct row estimate */
1166 path->rows = param_info->ppi_rows;
1168 path->rows = baserel->rows;
1170 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1171 cpu_per_tuple = cpu_tuple_cost;
1173 /* Add scanning CPU costs */
1174 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1176 startup_cost += qpqual_cost.startup;
1177 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1178 run_cost += cpu_per_tuple * baserel->tuples;
1180 path->startup_cost = startup_cost;
1181 path->total_cost = startup_cost + run_cost;
1185 * cost_recursive_union
1186 * Determines and returns the cost of performing a recursive union,
1187 * and also the estimated output size.
1189 * We are given Plans for the nonrecursive and recursive terms.
1191 * Note that the arguments and output are Plans, not Paths as in most of
1192 * the rest of this module. That's because we don't bother setting up a
1193 * Path representation for recursive union --- we have only one way to do it.
1196 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1202 /* We probably have decent estimates for the non-recursive term */
1203 startup_cost = nrterm->startup_cost;
1204 total_cost = nrterm->total_cost;
1205 total_rows = nrterm->plan_rows;
1208 * We arbitrarily assume that about 10 recursive iterations will be
1209 * needed, and that we've managed to get a good fix on the cost and output
1210 * size of each one of them. These are mighty shaky assumptions but it's
1211 * hard to see how to do better.
1213 total_cost += 10 * rterm->total_cost;
1214 total_rows += 10 * rterm->plan_rows;
1217 * Also charge cpu_tuple_cost per row to account for the costs of
1218 * manipulating the tuplestores. (We don't worry about possible
1219 * spill-to-disk costs.)
1221 total_cost += cpu_tuple_cost * total_rows;
1223 runion->startup_cost = startup_cost;
1224 runion->total_cost = total_cost;
1225 runion->plan_rows = total_rows;
1226 runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1231 * Determines and returns the cost of sorting a relation, including
1232 * the cost of reading the input data.
1234 * If the total volume of data to sort is less than sort_mem, we will do
1235 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1236 * comparisons for t tuples.
1238 * If the total volume exceeds sort_mem, we switch to a tape-style merge
1239 * algorithm. There will still be about t*log2(t) tuple comparisons in
1240 * total, but we will also need to write and read each tuple once per
1241 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1242 * number of initial runs formed and M is the merge order used by tuplesort.c.
1243 * Since the average initial run should be about twice sort_mem, we have
1244 * disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
1245 * cpu = comparison_cost * t * log2(t)
1247 * If the sort is bounded (i.e., only the first k result tuples are needed)
1248 * and k tuples can fit into sort_mem, we use a heap method that keeps only
1249 * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1251 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1252 * accesses (XXX can't we refine that guess?)
1254 * By default, we charge two operator evals per tuple comparison, which should
1255 * be in the right ballpark in most cases. The caller can tweak this by
1256 * specifying nonzero comparison_cost; typically that's used for any extra
1257 * work that has to be done to prepare the inputs to the comparison operators.
1259 * 'pathkeys' is a list of sort keys
1260 * 'input_cost' is the total cost for reading the input data
1261 * 'tuples' is the number of tuples in the relation
1262 * 'width' is the average tuple width in bytes
1263 * 'comparison_cost' is the extra cost per comparison, if any
1264 * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1265 * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1267 * NOTE: some callers currently pass NIL for pathkeys because they
1268 * can't conveniently supply the sort keys. Since this routine doesn't
1269 * currently do anything with pathkeys anyway, that doesn't matter...
1270 * but if it ever does, it should react gracefully to lack of key data.
1271 * (Actually, the thing we'd most likely be interested in is just the number
1272 * of sort keys, which all callers *could* supply.)
1275 cost_sort(Path *path, PlannerInfo *root,
1276 List *pathkeys, Cost input_cost, double tuples, int width,
1277 Cost comparison_cost, int sort_mem,
1278 double limit_tuples)
1280 Cost startup_cost = input_cost;
1282 double input_bytes = relation_byte_size(tuples, width);
1283 double output_bytes;
1284 double output_tuples;
1285 long sort_mem_bytes = sort_mem * 1024L;
1288 startup_cost += disable_cost;
1290 path->rows = tuples;
1293 * We want to be sure the cost of a sort is never estimated as zero, even
1294 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1299 /* Include the default cost-per-comparison */
1300 comparison_cost += 2.0 * cpu_operator_cost;
1302 /* Do we have a useful LIMIT? */
1303 if (limit_tuples > 0 && limit_tuples < tuples)
1305 output_tuples = limit_tuples;
1306 output_bytes = relation_byte_size(output_tuples, width);
1310 output_tuples = tuples;
1311 output_bytes = input_bytes;
1314 if (output_bytes > sort_mem_bytes)
1317 * We'll have to use a disk-based sort of all the tuples
1319 double npages = ceil(input_bytes / BLCKSZ);
1320 double nruns = (input_bytes / sort_mem_bytes) * 0.5;
1321 double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1323 double npageaccesses;
1328 * Assume about N log2 N comparisons
1330 startup_cost += comparison_cost * tuples * LOG2(tuples);
1334 /* Compute logM(r) as log(r) / log(M) */
1335 if (nruns > mergeorder)
1336 log_runs = ceil(log(nruns) / log(mergeorder));
1339 npageaccesses = 2.0 * npages * log_runs;
1340 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1341 startup_cost += npageaccesses *
1342 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1344 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1347 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1348 * a total number of tuple comparisons of N log2 K; but the constant
1349 * factor is a bit higher than for quicksort. Tweak it so that the
1350 * cost curve is continuous at the crossover point.
1352 startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1356 /* We'll use plain quicksort on all the input tuples */
1357 startup_cost += comparison_cost * tuples * LOG2(tuples);
1361 * Also charge a small amount (arbitrarily set equal to operator cost) per
1362 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1363 * doesn't do qual-checking or projection, so it has less overhead than
1364 * most plan nodes. Note it's correct to use tuples not output_tuples
1365 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1366 * counting the LIMIT otherwise.
1368 run_cost += cpu_operator_cost * tuples;
1370 path->startup_cost = startup_cost;
1371 path->total_cost = startup_cost + run_cost;
1376 * Determines and returns the cost of a MergeAppend node.
1378 * MergeAppend merges several pre-sorted input streams, using a heap that
1379 * at any given instant holds the next tuple from each stream. If there
1380 * are N streams, we need about N*log2(N) tuple comparisons to construct
1381 * the heap at startup, and then for each output tuple, about log2(N)
1382 * comparisons to delete the top heap entry and another log2(N) comparisons
1383 * to insert its successor from the same stream.
1385 * (The effective value of N will drop once some of the input streams are
1386 * exhausted, but it seems unlikely to be worth trying to account for that.)
1388 * The heap is never spilled to disk, since we assume N is not very large.
1389 * So this is much simpler than cost_sort.
1391 * As in cost_sort, we charge two operator evals per tuple comparison.
1393 * 'pathkeys' is a list of sort keys
1394 * 'n_streams' is the number of input streams
1395 * 'input_startup_cost' is the sum of the input streams' startup costs
1396 * 'input_total_cost' is the sum of the input streams' total costs
1397 * 'tuples' is the number of tuples in all the streams
1400 cost_merge_append(Path *path, PlannerInfo *root,
1401 List *pathkeys, int n_streams,
1402 Cost input_startup_cost, Cost input_total_cost,
1405 Cost startup_cost = 0;
1407 Cost comparison_cost;
1414 N = (n_streams < 2) ? 2.0 : (double) n_streams;
1417 /* Assumed cost per tuple comparison */
1418 comparison_cost = 2.0 * cpu_operator_cost;
1420 /* Heap creation cost */
1421 startup_cost += comparison_cost * N * logN;
1423 /* Per-tuple heap maintenance cost */
1424 run_cost += tuples * comparison_cost * 2.0 * logN;
1427 * Also charge a small amount (arbitrarily set equal to operator cost) per
1428 * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1429 * node doesn't do qual-checking or projection, so it has less overhead
1430 * than most plan nodes.
1432 run_cost += cpu_operator_cost * tuples;
1434 path->startup_cost = startup_cost + input_startup_cost;
1435 path->total_cost = startup_cost + run_cost + input_total_cost;
1440 * Determines and returns the cost of materializing a relation, including
1441 * the cost of reading the input data.
1443 * If the total volume of data to materialize exceeds work_mem, we will need
1444 * to write it to disk, so the cost is much higher in that case.
1446 * Note that here we are estimating the costs for the first scan of the
1447 * relation, so the materialization is all overhead --- any savings will
1448 * occur only on rescan, which is estimated in cost_rescan.
1451 cost_material(Path *path,
1452 Cost input_startup_cost, Cost input_total_cost,
1453 double tuples, int width)
1455 Cost startup_cost = input_startup_cost;
1456 Cost run_cost = input_total_cost - input_startup_cost;
1457 double nbytes = relation_byte_size(tuples, width);
1458 long work_mem_bytes = work_mem * 1024L;
1460 path->rows = tuples;
1463 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1464 * reflect bookkeeping overhead. (This rate must be more than what
1465 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1466 * if it is exactly the same then there will be a cost tie between
1467 * nestloop with A outer, materialized B inner and nestloop with B outer,
1468 * materialized A inner. The extra cost ensures we'll prefer
1469 * materializing the smaller rel.) Note that this is normally a good deal
1470 * less than cpu_tuple_cost; which is OK because a Material plan node
1471 * doesn't do qual-checking or projection, so it's got less overhead than
1474 run_cost += 2 * cpu_operator_cost * tuples;
1477 * If we will spill to disk, charge at the rate of seq_page_cost per page.
1478 * This cost is assumed to be evenly spread through the plan run phase,
1479 * which isn't exactly accurate but our cost model doesn't allow for
1480 * nonuniform costs within the run phase.
1482 if (nbytes > work_mem_bytes)
1484 double npages = ceil(nbytes / BLCKSZ);
1486 run_cost += seq_page_cost * npages;
1489 path->startup_cost = startup_cost;
1490 path->total_cost = startup_cost + run_cost;
1495 * Determines and returns the cost of performing an Agg plan node,
1496 * including the cost of its input.
1498 * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
1499 * we are using a hashed Agg node just to do grouping).
1501 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1502 * are for appropriately-sorted input.
1505 cost_agg(Path *path, PlannerInfo *root,
1506 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
1507 int numGroupCols, double numGroups,
1508 Cost input_startup_cost, Cost input_total_cost,
1509 double input_tuples)
1511 double output_tuples;
1514 AggClauseCosts dummy_aggcosts;
1516 /* Use all-zero per-aggregate costs if NULL is passed */
1517 if (aggcosts == NULL)
1519 Assert(aggstrategy == AGG_HASHED);
1520 MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1521 aggcosts = &dummy_aggcosts;
1525 * The transCost.per_tuple component of aggcosts should be charged once
1526 * per input tuple, corresponding to the costs of evaluating the aggregate
1527 * transfns and their input expressions (with any startup cost of course
1528 * charged but once). The finalCost component is charged once per output
1529 * tuple, corresponding to the costs of evaluating the finalfns.
1531 * If we are grouping, we charge an additional cpu_operator_cost per
1532 * grouping column per input tuple for grouping comparisons.
1534 * We will produce a single output tuple if not grouping, and a tuple per
1535 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1537 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1538 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1539 * input path is already sorted appropriately, AGG_SORTED should be
1540 * preferred (since it has no risk of memory overflow). This will happen
1541 * as long as the computed total costs are indeed exactly equal --- but if
1542 * there's roundoff error we might do the wrong thing. So be sure that
1543 * the computations below form the same intermediate values in the same
1546 if (aggstrategy == AGG_PLAIN)
1548 startup_cost = input_total_cost;
1549 startup_cost += aggcosts->transCost.startup;
1550 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1551 startup_cost += aggcosts->finalCost;
1552 /* we aren't grouping */
1553 total_cost = startup_cost + cpu_tuple_cost;
1556 else if (aggstrategy == AGG_SORTED)
1558 /* Here we are able to deliver output on-the-fly */
1559 startup_cost = input_startup_cost;
1560 total_cost = input_total_cost;
1561 /* calcs phrased this way to match HASHED case, see note above */
1562 total_cost += aggcosts->transCost.startup;
1563 total_cost += aggcosts->transCost.per_tuple * input_tuples;
1564 total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1565 total_cost += aggcosts->finalCost * numGroups;
1566 total_cost += cpu_tuple_cost * numGroups;
1567 output_tuples = numGroups;
1571 /* must be AGG_HASHED */
1572 startup_cost = input_total_cost;
1573 startup_cost += aggcosts->transCost.startup;
1574 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1575 startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1576 total_cost = startup_cost;
1577 total_cost += aggcosts->finalCost * numGroups;
1578 total_cost += cpu_tuple_cost * numGroups;
1579 output_tuples = numGroups;
1582 path->rows = output_tuples;
1583 path->startup_cost = startup_cost;
1584 path->total_cost = total_cost;
1589 * Determines and returns the cost of performing a WindowAgg plan node,
1590 * including the cost of its input.
1592 * Input is assumed already properly sorted.
1595 cost_windowagg(Path *path, PlannerInfo *root,
1596 List *windowFuncs, int numPartCols, int numOrderCols,
1597 Cost input_startup_cost, Cost input_total_cost,
1598 double input_tuples)
1604 startup_cost = input_startup_cost;
1605 total_cost = input_total_cost;
1608 * Window functions are assumed to cost their stated execution cost, plus
1609 * the cost of evaluating their input expressions, per tuple. Since they
1610 * may in fact evaluate their inputs at multiple rows during each cycle,
1611 * this could be a drastic underestimate; but without a way to know how
1612 * many rows the window function will fetch, it's hard to do better. In
1613 * any case, it's a good estimate for all the built-in window functions,
1614 * so we'll just do this for now.
1616 foreach(lc, windowFuncs)
1618 WindowFunc *wfunc = (WindowFunc *) lfirst(lc);
1622 Assert(IsA(wfunc, WindowFunc));
1624 wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1626 /* also add the input expressions' cost to per-input-row costs */
1627 cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1628 startup_cost += argcosts.startup;
1629 wfunccost += argcosts.per_tuple;
1632 * Add the filter's cost to per-input-row costs. XXX We should reduce
1633 * input expression costs according to filter selectivity.
1635 cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
1636 startup_cost += argcosts.startup;
1637 wfunccost += argcosts.per_tuple;
1639 total_cost += wfunccost * input_tuples;
1643 * We also charge cpu_operator_cost per grouping column per tuple for
1644 * grouping comparisons, plus cpu_tuple_cost per tuple for general
1647 * XXX this neglects costs of spooling the data to disk when it overflows
1648 * work_mem. Sooner or later that should get accounted for.
1650 total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1651 total_cost += cpu_tuple_cost * input_tuples;
1653 path->rows = input_tuples;
1654 path->startup_cost = startup_cost;
1655 path->total_cost = total_cost;
1660 * Determines and returns the cost of performing a Group plan node,
1661 * including the cost of its input.
1663 * Note: caller must ensure that input costs are for appropriately-sorted
1667 cost_group(Path *path, PlannerInfo *root,
1668 int numGroupCols, double numGroups,
1669 Cost input_startup_cost, Cost input_total_cost,
1670 double input_tuples)
1675 startup_cost = input_startup_cost;
1676 total_cost = input_total_cost;
1679 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1680 * all columns get compared at most of the tuples.
1682 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1684 path->rows = numGroups;
1685 path->startup_cost = startup_cost;
1686 path->total_cost = total_cost;
1690 * initial_cost_nestloop
1691 * Preliminary estimate of the cost of a nestloop join path.
1693 * This must quickly produce lower-bound estimates of the path's startup and
1694 * total costs. If we are unable to eliminate the proposed path from
1695 * consideration using the lower bounds, final_cost_nestloop will be called
1696 * to obtain the final estimates.
1698 * The exact division of labor between this function and final_cost_nestloop
1699 * is private to them, and represents a tradeoff between speed of the initial
1700 * estimate and getting a tight lower bound. We choose to not examine the
1701 * join quals here, since that's by far the most expensive part of the
1702 * calculations. The end result is that CPU-cost considerations must be
1703 * left for the second phase.
1705 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
1706 * other data to be used by final_cost_nestloop
1707 * 'jointype' is the type of join to be performed
1708 * 'outer_path' is the outer input to the join
1709 * 'inner_path' is the inner input to the join
1710 * 'sjinfo' is extra info about the join for selectivity estimation
1711 * 'semifactors' contains valid data if jointype is SEMI or ANTI
1714 initial_cost_nestloop(PlannerInfo *root, JoinCostWorkspace *workspace,
1716 Path *outer_path, Path *inner_path,
1717 SpecialJoinInfo *sjinfo,
1718 SemiAntiJoinFactors *semifactors)
1720 Cost startup_cost = 0;
1722 double outer_path_rows = outer_path->rows;
1723 Cost inner_rescan_start_cost;
1724 Cost inner_rescan_total_cost;
1725 Cost inner_run_cost;
1726 Cost inner_rescan_run_cost;
1728 /* estimate costs to rescan the inner relation */
1729 cost_rescan(root, inner_path,
1730 &inner_rescan_start_cost,
1731 &inner_rescan_total_cost);
1733 /* cost of source data */
1736 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1737 * before we can start returning tuples, so the join's startup cost is
1738 * their sum. We'll also pay the inner path's rescan startup cost
1741 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1742 run_cost += outer_path->total_cost - outer_path->startup_cost;
1743 if (outer_path_rows > 1)
1744 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1746 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1747 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1749 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
1751 double outer_matched_rows;
1752 Selectivity inner_scan_frac;
1755 * SEMI or ANTI join: executor will stop after first match.
1757 * For an outer-rel row that has at least one match, we can expect the
1758 * inner scan to stop after a fraction 1/(match_count+1) of the inner
1759 * rows, if the matches are evenly distributed. Since they probably
1760 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1761 * that fraction. (If we used a larger fuzz factor, we'd have to
1762 * clamp inner_scan_frac to at most 1.0; but since match_count is at
1763 * least 1, no such clamp is needed now.)
1765 * A complicating factor is that rescans may be cheaper than first
1766 * scans. If we never scan all the way to the end of the inner rel,
1767 * it might be (depending on the plan type) that we'd never pay the
1768 * whole inner first-scan run cost. However it is difficult to
1769 * estimate whether that will happen, so be conservative and always
1770 * charge the whole first-scan cost once.
1772 run_cost += inner_run_cost;
1774 outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
1775 inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
1777 /* Add inner run cost for additional outer tuples having matches */
1778 if (outer_matched_rows > 1)
1779 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1782 * The cost of processing unmatched rows varies depending on the
1783 * details of the joinclauses, so we leave that part for later.
1786 /* Save private data for final_cost_nestloop */
1787 workspace->outer_matched_rows = outer_matched_rows;
1788 workspace->inner_scan_frac = inner_scan_frac;
1792 /* Normal case; we'll scan whole input rel for each outer row */
1793 run_cost += inner_run_cost;
1794 if (outer_path_rows > 1)
1795 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1798 /* CPU costs left for later */
1800 /* Public result fields */
1801 workspace->startup_cost = startup_cost;
1802 workspace->total_cost = startup_cost + run_cost;
1803 /* Save private data for final_cost_nestloop */
1804 workspace->run_cost = run_cost;
1805 workspace->inner_rescan_run_cost = inner_rescan_run_cost;
1809 * final_cost_nestloop
1810 * Final estimate of the cost and result size of a nestloop join path.
1812 * 'path' is already filled in except for the rows and cost fields
1813 * 'workspace' is the result from initial_cost_nestloop
1814 * 'sjinfo' is extra info about the join for selectivity estimation
1815 * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
1818 final_cost_nestloop(PlannerInfo *root, NestPath *path,
1819 JoinCostWorkspace *workspace,
1820 SpecialJoinInfo *sjinfo,
1821 SemiAntiJoinFactors *semifactors)
1823 Path *outer_path = path->outerjoinpath;
1824 Path *inner_path = path->innerjoinpath;
1825 double outer_path_rows = outer_path->rows;
1826 double inner_path_rows = inner_path->rows;
1827 Cost startup_cost = workspace->startup_cost;
1828 Cost run_cost = workspace->run_cost;
1829 Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
1831 QualCost restrict_qual_cost;
1834 /* Mark the path with the correct row estimate */
1835 if (path->path.param_info)
1836 path->path.rows = path->path.param_info->ppi_rows;
1838 path->path.rows = path->path.parent->rows;
1841 * We could include disable_cost in the preliminary estimate, but that
1842 * would amount to optimizing for the case where the join method is
1843 * disabled, which doesn't seem like the way to bet.
1845 if (!enable_nestloop)
1846 startup_cost += disable_cost;
1848 /* cost of source data */
1850 if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI)
1852 double outer_matched_rows = workspace->outer_matched_rows;
1853 Selectivity inner_scan_frac = workspace->inner_scan_frac;
1856 * SEMI or ANTI join: executor will stop after first match.
1859 /* Compute number of tuples processed (not number emitted!) */
1860 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1863 * For unmatched outer-rel rows, there are two cases. If the inner
1864 * path is an indexscan using all the joinquals as indexquals, then an
1865 * unmatched row results in an indexscan returning no rows, which is
1866 * probably quite cheap. We estimate this case as the same cost to
1867 * return the first tuple of a nonempty scan. Otherwise, the executor
1868 * will have to scan the whole inner rel; not so cheap.
1870 if (has_indexed_join_quals(path))
1872 run_cost += (outer_path_rows - outer_matched_rows) *
1873 inner_rescan_run_cost / inner_path_rows;
1876 * We won't be evaluating any quals at all for these rows, so
1877 * don't add them to ntuples.
1882 run_cost += (outer_path_rows - outer_matched_rows) *
1883 inner_rescan_run_cost;
1884 ntuples += (outer_path_rows - outer_matched_rows) *
1890 /* Normal-case source costs were included in preliminary estimate */
1892 /* Compute number of tuples processed (not number emitted!) */
1893 ntuples = outer_path_rows * inner_path_rows;
1897 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1898 startup_cost += restrict_qual_cost.startup;
1899 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1900 run_cost += cpu_per_tuple * ntuples;
1902 path->path.startup_cost = startup_cost;
1903 path->path.total_cost = startup_cost + run_cost;
1907 * initial_cost_mergejoin
1908 * Preliminary estimate of the cost of a mergejoin path.
1910 * This must quickly produce lower-bound estimates of the path's startup and
1911 * total costs. If we are unable to eliminate the proposed path from
1912 * consideration using the lower bounds, final_cost_mergejoin will be called
1913 * to obtain the final estimates.
1915 * The exact division of labor between this function and final_cost_mergejoin
1916 * is private to them, and represents a tradeoff between speed of the initial
1917 * estimate and getting a tight lower bound. We choose to not examine the
1918 * join quals here, except for obtaining the scan selectivity estimate which
1919 * is really essential (but fortunately, use of caching keeps the cost of
1920 * getting that down to something reasonable).
1921 * We also assume that cost_sort is cheap enough to use here.
1923 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
1924 * other data to be used by final_cost_mergejoin
1925 * 'jointype' is the type of join to be performed
1926 * 'mergeclauses' is the list of joinclauses to be used as merge clauses
1927 * 'outer_path' is the outer input to the join
1928 * 'inner_path' is the inner input to the join
1929 * 'outersortkeys' is the list of sort keys for the outer path
1930 * 'innersortkeys' is the list of sort keys for the inner path
1931 * 'sjinfo' is extra info about the join for selectivity estimation
1933 * Note: outersortkeys and innersortkeys should be NIL if no explicit
1934 * sort is needed because the respective source path is already ordered.
1937 initial_cost_mergejoin(PlannerInfo *root, JoinCostWorkspace *workspace,
1940 Path *outer_path, Path *inner_path,
1941 List *outersortkeys, List *innersortkeys,
1942 SpecialJoinInfo *sjinfo)
1944 Cost startup_cost = 0;
1946 double outer_path_rows = outer_path->rows;
1947 double inner_path_rows = inner_path->rows;
1948 Cost inner_run_cost;
1953 Selectivity outerstartsel,
1957 Path sort_path; /* dummy for result of cost_sort */
1959 /* Protect some assumptions below that rowcounts aren't zero or NaN */
1960 if (outer_path_rows <= 0 || isnan(outer_path_rows))
1961 outer_path_rows = 1;
1962 if (inner_path_rows <= 0 || isnan(inner_path_rows))
1963 inner_path_rows = 1;
1966 * A merge join will stop as soon as it exhausts either input stream
1967 * (unless it's an outer join, in which case the outer side has to be
1968 * scanned all the way anyway). Estimate fraction of the left and right
1969 * inputs that will actually need to be scanned. Likewise, we can
1970 * estimate the number of rows that will be skipped before the first join
1971 * pair is found, which should be factored into startup cost. We use only
1972 * the first (most significant) merge clause for this purpose. Since
1973 * mergejoinscansel() is a fairly expensive computation, we cache the
1974 * results in the merge clause RestrictInfo.
1976 if (mergeclauses && jointype != JOIN_FULL)
1978 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1983 MergeScanSelCache *cache;
1985 /* Get the input pathkeys to determine the sort-order details */
1986 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1987 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1990 opathkey = (PathKey *) linitial(opathkeys);
1991 ipathkey = (PathKey *) linitial(ipathkeys);
1992 /* debugging check */
1993 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1994 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
1995 opathkey->pk_strategy != ipathkey->pk_strategy ||
1996 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1997 elog(ERROR, "left and right pathkeys do not match in mergejoin");
1999 /* Get the selectivity with caching */
2000 cache = cached_scansel(root, firstclause, opathkey);
2002 if (bms_is_subset(firstclause->left_relids,
2003 outer_path->parent->relids))
2005 /* left side of clause is outer */
2006 outerstartsel = cache->leftstartsel;
2007 outerendsel = cache->leftendsel;
2008 innerstartsel = cache->rightstartsel;
2009 innerendsel = cache->rightendsel;
2013 /* left side of clause is inner */
2014 outerstartsel = cache->rightstartsel;
2015 outerendsel = cache->rightendsel;
2016 innerstartsel = cache->leftstartsel;
2017 innerendsel = cache->leftendsel;
2019 if (jointype == JOIN_LEFT ||
2020 jointype == JOIN_ANTI)
2022 outerstartsel = 0.0;
2025 else if (jointype == JOIN_RIGHT)
2027 innerstartsel = 0.0;
2033 /* cope with clauseless or full mergejoin */
2034 outerstartsel = innerstartsel = 0.0;
2035 outerendsel = innerendsel = 1.0;
2039 * Convert selectivities to row counts. We force outer_rows and
2040 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
2042 outer_skip_rows = rint(outer_path_rows * outerstartsel);
2043 inner_skip_rows = rint(inner_path_rows * innerstartsel);
2044 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
2045 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
2047 Assert(outer_skip_rows <= outer_rows);
2048 Assert(inner_skip_rows <= inner_rows);
2051 * Readjust scan selectivities to account for above rounding. This is
2052 * normally an insignificant effect, but when there are only a few rows in
2053 * the inputs, failing to do this makes for a large percentage error.
2055 outerstartsel = outer_skip_rows / outer_path_rows;
2056 innerstartsel = inner_skip_rows / inner_path_rows;
2057 outerendsel = outer_rows / outer_path_rows;
2058 innerendsel = inner_rows / inner_path_rows;
2060 Assert(outerstartsel <= outerendsel);
2061 Assert(innerstartsel <= innerendsel);
2063 /* cost of source data */
2065 if (outersortkeys) /* do we need to sort outer? */
2067 cost_sort(&sort_path,
2070 outer_path->total_cost,
2072 outer_path->parent->width,
2076 startup_cost += sort_path.startup_cost;
2077 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2079 run_cost += (sort_path.total_cost - sort_path.startup_cost)
2080 * (outerendsel - outerstartsel);
2084 startup_cost += outer_path->startup_cost;
2085 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
2087 run_cost += (outer_path->total_cost - outer_path->startup_cost)
2088 * (outerendsel - outerstartsel);
2091 if (innersortkeys) /* do we need to sort inner? */
2093 cost_sort(&sort_path,
2096 inner_path->total_cost,
2098 inner_path->parent->width,
2102 startup_cost += sort_path.startup_cost;
2103 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2105 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
2106 * (innerendsel - innerstartsel);
2110 startup_cost += inner_path->startup_cost;
2111 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
2113 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
2114 * (innerendsel - innerstartsel);
2118 * We can't yet determine whether rescanning occurs, or whether
2119 * materialization of the inner input should be done. The minimum
2120 * possible inner input cost, regardless of rescan and materialization
2121 * considerations, is inner_run_cost. We include that in
2122 * workspace->total_cost, but not yet in run_cost.
2125 /* CPU costs left for later */
2127 /* Public result fields */
2128 workspace->startup_cost = startup_cost;
2129 workspace->total_cost = startup_cost + run_cost + inner_run_cost;
2130 /* Save private data for final_cost_mergejoin */
2131 workspace->run_cost = run_cost;
2132 workspace->inner_run_cost = inner_run_cost;
2133 workspace->outer_rows = outer_rows;
2134 workspace->inner_rows = inner_rows;
2135 workspace->outer_skip_rows = outer_skip_rows;
2136 workspace->inner_skip_rows = inner_skip_rows;
2140 * final_cost_mergejoin
2141 * Final estimate of the cost and result size of a mergejoin path.
2143 * Unlike other costsize functions, this routine makes one actual decision:
2144 * whether we should materialize the inner path. We do that either because
2145 * the inner path can't support mark/restore, or because it's cheaper to
2146 * use an interposed Material node to handle mark/restore. When the decision
2147 * is cost-based it would be logically cleaner to build and cost two separate
2148 * paths with and without that flag set; but that would require repeating most
2149 * of the cost calculations, which are not all that cheap. Since the choice
2150 * will not affect output pathkeys or startup cost, only total cost, there is
2151 * no possibility of wanting to keep both paths. So it seems best to make
2152 * the decision here and record it in the path's materialize_inner field.
2154 * 'path' is already filled in except for the rows and cost fields and
2156 * 'workspace' is the result from initial_cost_mergejoin
2157 * 'sjinfo' is extra info about the join for selectivity estimation
2160 final_cost_mergejoin(PlannerInfo *root, MergePath *path,
2161 JoinCostWorkspace *workspace,
2162 SpecialJoinInfo *sjinfo)
2164 Path *outer_path = path->jpath.outerjoinpath;
2165 Path *inner_path = path->jpath.innerjoinpath;
2166 double inner_path_rows = inner_path->rows;
2167 List *mergeclauses = path->path_mergeclauses;
2168 List *innersortkeys = path->innersortkeys;
2169 Cost startup_cost = workspace->startup_cost;
2170 Cost run_cost = workspace->run_cost;
2171 Cost inner_run_cost = workspace->inner_run_cost;
2172 double outer_rows = workspace->outer_rows;
2173 double inner_rows = workspace->inner_rows;
2174 double outer_skip_rows = workspace->outer_skip_rows;
2175 double inner_skip_rows = workspace->inner_skip_rows;
2179 QualCost merge_qual_cost;
2180 QualCost qp_qual_cost;
2181 double mergejointuples,
2185 /* Protect some assumptions below that rowcounts aren't zero or NaN */
2186 if (inner_path_rows <= 0 || isnan(inner_path_rows))
2187 inner_path_rows = 1;
2189 /* Mark the path with the correct row estimate */
2190 if (path->jpath.path.param_info)
2191 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2193 path->jpath.path.rows = path->jpath.path.parent->rows;
2196 * We could include disable_cost in the preliminary estimate, but that
2197 * would amount to optimizing for the case where the join method is
2198 * disabled, which doesn't seem like the way to bet.
2200 if (!enable_mergejoin)
2201 startup_cost += disable_cost;
2204 * Compute cost of the mergequals and qpquals (other restriction clauses)
2207 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2208 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2209 qp_qual_cost.startup -= merge_qual_cost.startup;
2210 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2213 * Get approx # tuples passing the mergequals. We use approx_tuple_count
2214 * here because we need an estimate done with JOIN_INNER semantics.
2216 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2219 * When there are equal merge keys in the outer relation, the mergejoin
2220 * must rescan any matching tuples in the inner relation. This means
2221 * re-fetching inner tuples; we have to estimate how often that happens.
2223 * For regular inner and outer joins, the number of re-fetches can be
2224 * estimated approximately as size of merge join output minus size of
2225 * inner relation. Assume that the distinct key values are 1, 2, ..., and
2226 * denote the number of values of each key in the outer relation as m1,
2227 * m2, ...; in the inner relation, n1, n2, ... Then we have
2229 * size of join = m1 * n1 + m2 * n2 + ...
2231 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2232 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2235 * This equation works correctly for outer tuples having no inner match
2236 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2237 * are effectively subtracting those from the number of rescanned tuples,
2238 * when we should not. Can we do better without expensive selectivity
2241 * The whole issue is moot if we are working from a unique-ified outer
2244 if (IsA(outer_path, UniquePath))
2245 rescannedtuples = 0;
2248 rescannedtuples = mergejointuples - inner_path_rows;
2249 /* Must clamp because of possible underestimate */
2250 if (rescannedtuples < 0)
2251 rescannedtuples = 0;
2253 /* We'll inflate various costs this much to account for rescanning */
2254 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
2257 * Decide whether we want to materialize the inner input to shield it from
2258 * mark/restore and performing re-fetches. Our cost model for regular
2259 * re-fetches is that a re-fetch costs the same as an original fetch,
2260 * which is probably an overestimate; but on the other hand we ignore the
2261 * bookkeeping costs of mark/restore. Not clear if it's worth developing
2262 * a more refined model. So we just need to inflate the inner run cost by
2265 bare_inner_cost = inner_run_cost * rescanratio;
2268 * When we interpose a Material node the re-fetch cost is assumed to be
2269 * just cpu_operator_cost per tuple, independently of the underlying
2270 * plan's cost; and we charge an extra cpu_operator_cost per original
2271 * fetch as well. Note that we're assuming the materialize node will
2272 * never spill to disk, since it only has to remember tuples back to the
2273 * last mark. (If there are a huge number of duplicates, our other cost
2274 * factors will make the path so expensive that it probably won't get
2275 * chosen anyway.) So we don't use cost_rescan here.
2277 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
2278 * of the generated Material node.
2280 mat_inner_cost = inner_run_cost +
2281 cpu_operator_cost * inner_path_rows * rescanratio;
2284 * Prefer materializing if it looks cheaper, unless the user has asked to
2285 * suppress materialization.
2287 if (enable_material && mat_inner_cost < bare_inner_cost)
2288 path->materialize_inner = true;
2291 * Even if materializing doesn't look cheaper, we *must* do it if the
2292 * inner path is to be used directly (without sorting) and it doesn't
2293 * support mark/restore.
2295 * Since the inner side must be ordered, and only Sorts and IndexScans can
2296 * create order to begin with, and they both support mark/restore, you
2297 * might think there's no problem --- but you'd be wrong. Nestloop and
2298 * merge joins can *preserve* the order of their inputs, so they can be
2299 * selected as the input of a mergejoin, and they don't support
2300 * mark/restore at present.
2302 * We don't test the value of enable_material here, because
2303 * materialization is required for correctness in this case, and turning
2304 * it off does not entitle us to deliver an invalid plan.
2306 else if (innersortkeys == NIL &&
2307 !ExecSupportsMarkRestore(inner_path))
2308 path->materialize_inner = true;
2311 * Also, force materializing if the inner path is to be sorted and the
2312 * sort is expected to spill to disk. This is because the final merge
2313 * pass can be done on-the-fly if it doesn't have to support mark/restore.
2314 * We don't try to adjust the cost estimates for this consideration,
2317 * Since materialization is a performance optimization in this case,
2318 * rather than necessary for correctness, we skip it if enable_material is
2321 else if (enable_material && innersortkeys != NIL &&
2322 relation_byte_size(inner_path_rows, inner_path->parent->width) >
2324 path->materialize_inner = true;
2326 path->materialize_inner = false;
2328 /* Charge the right incremental cost for the chosen case */
2329 if (path->materialize_inner)
2330 run_cost += mat_inner_cost;
2332 run_cost += bare_inner_cost;
2337 * The number of tuple comparisons needed is approximately number of outer
2338 * rows plus number of inner rows plus number of rescanned tuples (can we
2339 * refine this?). At each one, we need to evaluate the mergejoin quals.
2341 startup_cost += merge_qual_cost.startup;
2342 startup_cost += merge_qual_cost.per_tuple *
2343 (outer_skip_rows + inner_skip_rows * rescanratio);
2344 run_cost += merge_qual_cost.per_tuple *
2345 ((outer_rows - outer_skip_rows) +
2346 (inner_rows - inner_skip_rows) * rescanratio);
2349 * For each tuple that gets through the mergejoin proper, we charge
2350 * cpu_tuple_cost plus the cost of evaluating additional restriction
2351 * clauses that are to be applied at the join. (This is pessimistic since
2352 * not all of the quals may get evaluated at each tuple.)
2354 * Note: we could adjust for SEMI/ANTI joins skipping some qual
2355 * evaluations here, but it's probably not worth the trouble.
2357 startup_cost += qp_qual_cost.startup;
2358 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2359 run_cost += cpu_per_tuple * mergejointuples;
2361 path->jpath.path.startup_cost = startup_cost;
2362 path->jpath.path.total_cost = startup_cost + run_cost;
2366 * run mergejoinscansel() with caching
2368 static MergeScanSelCache *
2369 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2371 MergeScanSelCache *cache;
2373 Selectivity leftstartsel,
2377 MemoryContext oldcontext;
2379 /* Do we have this result already? */
2380 foreach(lc, rinfo->scansel_cache)
2382 cache = (MergeScanSelCache *) lfirst(lc);
2383 if (cache->opfamily == pathkey->pk_opfamily &&
2384 cache->collation == pathkey->pk_eclass->ec_collation &&
2385 cache->strategy == pathkey->pk_strategy &&
2386 cache->nulls_first == pathkey->pk_nulls_first)
2390 /* Nope, do the computation */
2391 mergejoinscansel(root,
2392 (Node *) rinfo->clause,
2393 pathkey->pk_opfamily,
2394 pathkey->pk_strategy,
2395 pathkey->pk_nulls_first,
2401 /* Cache the result in suitably long-lived workspace */
2402 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2404 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2405 cache->opfamily = pathkey->pk_opfamily;
2406 cache->collation = pathkey->pk_eclass->ec_collation;
2407 cache->strategy = pathkey->pk_strategy;
2408 cache->nulls_first = pathkey->pk_nulls_first;
2409 cache->leftstartsel = leftstartsel;
2410 cache->leftendsel = leftendsel;
2411 cache->rightstartsel = rightstartsel;
2412 cache->rightendsel = rightendsel;
2414 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2416 MemoryContextSwitchTo(oldcontext);
2422 * initial_cost_hashjoin
2423 * Preliminary estimate of the cost of a hashjoin path.
2425 * This must quickly produce lower-bound estimates of the path's startup and
2426 * total costs. If we are unable to eliminate the proposed path from
2427 * consideration using the lower bounds, final_cost_hashjoin will be called
2428 * to obtain the final estimates.
2430 * The exact division of labor between this function and final_cost_hashjoin
2431 * is private to them, and represents a tradeoff between speed of the initial
2432 * estimate and getting a tight lower bound. We choose to not examine the
2433 * join quals here (other than by counting the number of hash clauses),
2434 * so we can't do much with CPU costs. We do assume that
2435 * ExecChooseHashTableSize is cheap enough to use here.
2437 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
2438 * other data to be used by final_cost_hashjoin
2439 * 'jointype' is the type of join to be performed
2440 * 'hashclauses' is the list of joinclauses to be used as hash clauses
2441 * 'outer_path' is the outer input to the join
2442 * 'inner_path' is the inner input to the join
2443 * 'sjinfo' is extra info about the join for selectivity estimation
2444 * 'semifactors' contains valid data if jointype is SEMI or ANTI
2447 initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
2450 Path *outer_path, Path *inner_path,
2451 SpecialJoinInfo *sjinfo,
2452 SemiAntiJoinFactors *semifactors)
2454 Cost startup_cost = 0;
2456 double outer_path_rows = outer_path->rows;
2457 double inner_path_rows = inner_path->rows;
2458 int num_hashclauses = list_length(hashclauses);
2463 /* cost of source data */
2464 startup_cost += outer_path->startup_cost;
2465 run_cost += outer_path->total_cost - outer_path->startup_cost;
2466 startup_cost += inner_path->total_cost;
2469 * Cost of computing hash function: must do it once per input tuple. We
2470 * charge one cpu_operator_cost for each column's hash function. Also,
2471 * tack on one cpu_tuple_cost per inner row, to model the costs of
2472 * inserting the row into the hashtable.
2474 * XXX when a hashclause is more complex than a single operator, we really
2475 * should charge the extra eval costs of the left or right side, as
2476 * appropriate, here. This seems more work than it's worth at the moment.
2478 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2480 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2483 * Get hash table size that executor would use for inner relation.
2485 * XXX for the moment, always assume that skew optimization will be
2486 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2487 * trying to determine that for sure.
2489 * XXX at some point it might be interesting to try to account for skew
2490 * optimization in the cost estimate, but for now, we don't.
2492 ExecChooseHashTableSize(inner_path_rows,
2493 inner_path->parent->width,
2500 * If inner relation is too big then we will need to "batch" the join,
2501 * which implies writing and reading most of the tuples to disk an extra
2502 * time. Charge seq_page_cost per page, since the I/O should be nice and
2503 * sequential. Writing the inner rel counts as startup cost, all the rest
2508 double outerpages = page_size(outer_path_rows,
2509 outer_path->parent->width);
2510 double innerpages = page_size(inner_path_rows,
2511 inner_path->parent->width);
2513 startup_cost += seq_page_cost * innerpages;
2514 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2517 /* CPU costs left for later */
2519 /* Public result fields */
2520 workspace->startup_cost = startup_cost;
2521 workspace->total_cost = startup_cost + run_cost;
2522 /* Save private data for final_cost_hashjoin */
2523 workspace->run_cost = run_cost;
2524 workspace->numbuckets = numbuckets;
2525 workspace->numbatches = numbatches;
2529 * final_cost_hashjoin
2530 * Final estimate of the cost and result size of a hashjoin path.
2532 * Note: the numbatches estimate is also saved into 'path' for use later
2534 * 'path' is already filled in except for the rows and cost fields and
2536 * 'workspace' is the result from initial_cost_hashjoin
2537 * 'sjinfo' is extra info about the join for selectivity estimation
2538 * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
2541 final_cost_hashjoin(PlannerInfo *root, HashPath *path,
2542 JoinCostWorkspace *workspace,
2543 SpecialJoinInfo *sjinfo,
2544 SemiAntiJoinFactors *semifactors)
2546 Path *outer_path = path->jpath.outerjoinpath;
2547 Path *inner_path = path->jpath.innerjoinpath;
2548 double outer_path_rows = outer_path->rows;
2549 double inner_path_rows = inner_path->rows;
2550 List *hashclauses = path->path_hashclauses;
2551 Cost startup_cost = workspace->startup_cost;
2552 Cost run_cost = workspace->run_cost;
2553 int numbuckets = workspace->numbuckets;
2554 int numbatches = workspace->numbatches;
2556 QualCost hash_qual_cost;
2557 QualCost qp_qual_cost;
2558 double hashjointuples;
2559 double virtualbuckets;
2560 Selectivity innerbucketsize;
2563 /* Mark the path with the correct row estimate */
2564 if (path->jpath.path.param_info)
2565 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2567 path->jpath.path.rows = path->jpath.path.parent->rows;
2570 * We could include disable_cost in the preliminary estimate, but that
2571 * would amount to optimizing for the case where the join method is
2572 * disabled, which doesn't seem like the way to bet.
2574 if (!enable_hashjoin)
2575 startup_cost += disable_cost;
2577 /* mark the path with estimated # of batches */
2578 path->num_batches = numbatches;
2580 /* and compute the number of "virtual" buckets in the whole join */
2581 virtualbuckets = (double) numbuckets *(double) numbatches;
2584 * Determine bucketsize fraction for inner relation. We use the smallest
2585 * bucketsize estimated for any individual hashclause; this is undoubtedly
2588 * BUT: if inner relation has been unique-ified, we can assume it's good
2589 * for hashing. This is important both because it's the right answer, and
2590 * because we avoid contaminating the cache with a value that's wrong for
2591 * non-unique-ified paths.
2593 if (IsA(inner_path, UniquePath))
2594 innerbucketsize = 1.0 / virtualbuckets;
2597 innerbucketsize = 1.0;
2598 foreach(hcl, hashclauses)
2600 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2601 Selectivity thisbucketsize;
2603 Assert(IsA(restrictinfo, RestrictInfo));
2606 * First we have to figure out which side of the hashjoin clause
2607 * is the inner side.
2609 * Since we tend to visit the same clauses over and over when
2610 * planning a large query, we cache the bucketsize estimate in the
2611 * RestrictInfo node to avoid repeated lookups of statistics.
2613 if (bms_is_subset(restrictinfo->right_relids,
2614 inner_path->parent->relids))
2616 /* righthand side is inner */
2617 thisbucketsize = restrictinfo->right_bucketsize;
2618 if (thisbucketsize < 0)
2620 /* not cached yet */
2622 estimate_hash_bucketsize(root,
2623 get_rightop(restrictinfo->clause),
2625 restrictinfo->right_bucketsize = thisbucketsize;
2630 Assert(bms_is_subset(restrictinfo->left_relids,
2631 inner_path->parent->relids));
2632 /* lefthand side is inner */
2633 thisbucketsize = restrictinfo->left_bucketsize;
2634 if (thisbucketsize < 0)
2636 /* not cached yet */
2638 estimate_hash_bucketsize(root,
2639 get_leftop(restrictinfo->clause),
2641 restrictinfo->left_bucketsize = thisbucketsize;
2645 if (innerbucketsize > thisbucketsize)
2646 innerbucketsize = thisbucketsize;
2651 * Compute cost of the hashquals and qpquals (other restriction clauses)
2654 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2655 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2656 qp_qual_cost.startup -= hash_qual_cost.startup;
2657 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2661 if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI)
2663 double outer_matched_rows;
2664 Selectivity inner_scan_frac;
2667 * SEMI or ANTI join: executor will stop after first match.
2669 * For an outer-rel row that has at least one match, we can expect the
2670 * bucket scan to stop after a fraction 1/(match_count+1) of the
2671 * bucket's rows, if the matches are evenly distributed. Since they
2672 * probably aren't quite evenly distributed, we apply a fuzz factor of
2673 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2674 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2675 * at least 1, no such clamp is needed now.)
2677 outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2678 inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2680 startup_cost += hash_qual_cost.startup;
2681 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2682 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2685 * For unmatched outer-rel rows, the picture is quite a lot different.
2686 * In the first place, there is no reason to assume that these rows
2687 * preferentially hit heavily-populated buckets; instead assume they
2688 * are uncorrelated with the inner distribution and so they see an
2689 * average bucket size of inner_path_rows / virtualbuckets. In the
2690 * second place, it seems likely that they will have few if any exact
2691 * hash-code matches and so very few of the tuples in the bucket will
2692 * actually require eval of the hash quals. We don't have any good
2693 * way to estimate how many will, but for the moment assume that the
2694 * effective cost per bucket entry is one-tenth what it is for
2697 run_cost += hash_qual_cost.per_tuple *
2698 (outer_path_rows - outer_matched_rows) *
2699 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2701 /* Get # of tuples that will pass the basic join */
2702 if (path->jpath.jointype == JOIN_SEMI)
2703 hashjointuples = outer_matched_rows;
2705 hashjointuples = outer_path_rows - outer_matched_rows;
2710 * The number of tuple comparisons needed is the number of outer
2711 * tuples times the typical number of tuples in a hash bucket, which
2712 * is the inner relation size times its bucketsize fraction. At each
2713 * one, we need to evaluate the hashjoin quals. But actually,
2714 * charging the full qual eval cost at each tuple is pessimistic,
2715 * since we don't evaluate the quals unless the hash values match
2716 * exactly. For lack of a better idea, halve the cost estimate to
2719 startup_cost += hash_qual_cost.startup;
2720 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2721 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2724 * Get approx # tuples passing the hashquals. We use
2725 * approx_tuple_count here because we need an estimate done with
2726 * JOIN_INNER semantics.
2728 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2732 * For each tuple that gets through the hashjoin proper, we charge
2733 * cpu_tuple_cost plus the cost of evaluating additional restriction
2734 * clauses that are to be applied at the join. (This is pessimistic since
2735 * not all of the quals may get evaluated at each tuple.)
2737 startup_cost += qp_qual_cost.startup;
2738 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2739 run_cost += cpu_per_tuple * hashjointuples;
2741 path->jpath.path.startup_cost = startup_cost;
2742 path->jpath.path.total_cost = startup_cost + run_cost;
2748 * Figure the costs for a SubPlan (or initplan).
2750 * Note: we could dig the subplan's Plan out of the root list, but in practice
2751 * all callers have it handy already, so we make them pass it.
2754 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2758 /* Figure any cost for evaluating the testexpr */
2759 cost_qual_eval(&sp_cost,
2760 make_ands_implicit((Expr *) subplan->testexpr),
2763 if (subplan->useHashTable)
2766 * If we are using a hash table for the subquery outputs, then the
2767 * cost of evaluating the query is a one-time cost. We charge one
2768 * cpu_operator_cost per tuple for the work of loading the hashtable,
2771 sp_cost.startup += plan->total_cost +
2772 cpu_operator_cost * plan->plan_rows;
2775 * The per-tuple costs include the cost of evaluating the lefthand
2776 * expressions, plus the cost of probing the hashtable. We already
2777 * accounted for the lefthand expressions as part of the testexpr, and
2778 * will also have counted one cpu_operator_cost for each comparison
2779 * operator. That is probably too low for the probing cost, but it's
2780 * hard to make a better estimate, so live with it for now.
2786 * Otherwise we will be rescanning the subplan output on each
2787 * evaluation. We need to estimate how much of the output we will
2788 * actually need to scan. NOTE: this logic should agree with the
2789 * tuple_fraction estimates used by make_subplan() in
2792 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2794 if (subplan->subLinkType == EXISTS_SUBLINK)
2796 /* we only need to fetch 1 tuple */
2797 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2799 else if (subplan->subLinkType == ALL_SUBLINK ||
2800 subplan->subLinkType == ANY_SUBLINK)
2802 /* assume we need 50% of the tuples */
2803 sp_cost.per_tuple += 0.50 * plan_run_cost;
2804 /* also charge a cpu_operator_cost per row examined */
2805 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2809 /* assume we need all tuples */
2810 sp_cost.per_tuple += plan_run_cost;
2814 * Also account for subplan's startup cost. If the subplan is
2815 * uncorrelated or undirect correlated, AND its topmost node is one
2816 * that materializes its output, assume that we'll only need to pay
2817 * its startup cost once; otherwise assume we pay the startup cost
2820 if (subplan->parParam == NIL &&
2821 ExecMaterializesOutput(nodeTag(plan)))
2822 sp_cost.startup += plan->startup_cost;
2824 sp_cost.per_tuple += plan->startup_cost;
2827 subplan->startup_cost = sp_cost.startup;
2828 subplan->per_call_cost = sp_cost.per_tuple;
2834 * Given a finished Path, estimate the costs of rescanning it after
2835 * having done so the first time. For some Path types a rescan is
2836 * cheaper than an original scan (if no parameters change), and this
2837 * function embodies knowledge about that. The default is to return
2838 * the same costs stored in the Path. (Note that the cost estimates
2839 * actually stored in Paths are always for first scans.)
2841 * This function is not currently intended to model effects such as rescans
2842 * being cheaper due to disk block caching; what we are concerned with is
2843 * plan types wherein the executor caches results explicitly, or doesn't
2844 * redo startup calculations, etc.
2847 cost_rescan(PlannerInfo *root, Path *path,
2848 Cost *rescan_startup_cost, /* output parameters */
2849 Cost *rescan_total_cost)
2851 switch (path->pathtype)
2853 case T_FunctionScan:
2856 * Currently, nodeFunctionscan.c always executes the function to
2857 * completion before returning any rows, and caches the results in
2858 * a tuplestore. So the function eval cost is all startup cost
2859 * and isn't paid over again on rescans. However, all run costs
2860 * will be paid over again.
2862 *rescan_startup_cost = 0;
2863 *rescan_total_cost = path->total_cost - path->startup_cost;
2868 * Assume that all of the startup cost represents hash table
2869 * building, which we won't have to do over.
2871 *rescan_startup_cost = 0;
2872 *rescan_total_cost = path->total_cost - path->startup_cost;
2875 case T_WorkTableScan:
2878 * These plan types materialize their final result in a
2879 * tuplestore or tuplesort object. So the rescan cost is only
2880 * cpu_tuple_cost per tuple, unless the result is large enough
2883 Cost run_cost = cpu_tuple_cost * path->rows;
2884 double nbytes = relation_byte_size(path->rows,
2885 path->parent->width);
2886 long work_mem_bytes = work_mem * 1024L;
2888 if (nbytes > work_mem_bytes)
2890 /* It will spill, so account for re-read cost */
2891 double npages = ceil(nbytes / BLCKSZ);
2893 run_cost += seq_page_cost * npages;
2895 *rescan_startup_cost = 0;
2896 *rescan_total_cost = run_cost;
2903 * These plan types not only materialize their results, but do
2904 * not implement qual filtering or projection. So they are
2905 * even cheaper to rescan than the ones above. We charge only
2906 * cpu_operator_cost per tuple. (Note: keep that in sync with
2907 * the run_cost charge in cost_sort, and also see comments in
2908 * cost_material before you change it.)
2910 Cost run_cost = cpu_operator_cost * path->rows;
2911 double nbytes = relation_byte_size(path->rows,
2912 path->parent->width);
2913 long work_mem_bytes = work_mem * 1024L;
2915 if (nbytes > work_mem_bytes)
2917 /* It will spill, so account for re-read cost */
2918 double npages = ceil(nbytes / BLCKSZ);
2920 run_cost += seq_page_cost * npages;
2922 *rescan_startup_cost = 0;
2923 *rescan_total_cost = run_cost;
2927 *rescan_startup_cost = path->startup_cost;
2928 *rescan_total_cost = path->total_cost;
2936 * Estimate the CPU costs of evaluating a WHERE clause.
2937 * The input can be either an implicitly-ANDed list of boolean
2938 * expressions, or a list of RestrictInfo nodes. (The latter is
2939 * preferred since it allows caching of the results.)
2940 * The result includes both a one-time (startup) component,
2941 * and a per-evaluation component.
2944 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2946 cost_qual_eval_context context;
2949 context.root = root;
2950 context.total.startup = 0;
2951 context.total.per_tuple = 0;
2953 /* We don't charge any cost for the implicit ANDing at top level ... */
2957 Node *qual = (Node *) lfirst(l);
2959 cost_qual_eval_walker(qual, &context);
2962 *cost = context.total;
2966 * cost_qual_eval_node
2967 * As above, for a single RestrictInfo or expression.
2970 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2972 cost_qual_eval_context context;
2974 context.root = root;
2975 context.total.startup = 0;
2976 context.total.per_tuple = 0;
2978 cost_qual_eval_walker(qual, &context);
2980 *cost = context.total;
2984 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2990 * RestrictInfo nodes contain an eval_cost field reserved for this
2991 * routine's use, so that it's not necessary to evaluate the qual clause's
2992 * cost more than once. If the clause's cost hasn't been computed yet,
2993 * the field's startup value will contain -1.
2995 if (IsA(node, RestrictInfo))
2997 RestrictInfo *rinfo = (RestrictInfo *) node;
2999 if (rinfo->eval_cost.startup < 0)
3001 cost_qual_eval_context locContext;
3003 locContext.root = context->root;
3004 locContext.total.startup = 0;
3005 locContext.total.per_tuple = 0;
3008 * For an OR clause, recurse into the marked-up tree so that we
3009 * set the eval_cost for contained RestrictInfos too.
3011 if (rinfo->orclause)
3012 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
3014 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
3017 * If the RestrictInfo is marked pseudoconstant, it will be tested
3018 * only once, so treat its cost as all startup cost.
3020 if (rinfo->pseudoconstant)
3022 /* count one execution during startup */
3023 locContext.total.startup += locContext.total.per_tuple;
3024 locContext.total.per_tuple = 0;
3026 rinfo->eval_cost = locContext.total;
3028 context->total.startup += rinfo->eval_cost.startup;
3029 context->total.per_tuple += rinfo->eval_cost.per_tuple;
3030 /* do NOT recurse into children */
3035 * For each operator or function node in the given tree, we charge the
3036 * estimated execution cost given by pg_proc.procost (remember to multiply
3037 * this by cpu_operator_cost).
3039 * Vars and Consts are charged zero, and so are boolean operators (AND,
3040 * OR, NOT). Simplistic, but a lot better than no model at all.
3042 * Should we try to account for the possibility of short-circuit
3043 * evaluation of AND/OR? Probably *not*, because that would make the
3044 * results depend on the clause ordering, and we are not in any position
3045 * to expect that the current ordering of the clauses is the one that's
3046 * going to end up being used. The above per-RestrictInfo caching would
3047 * not mix well with trying to re-order clauses anyway.
3049 * Another issue that is entirely ignored here is that if a set-returning
3050 * function is below top level in the tree, the functions/operators above
3051 * it will need to be evaluated multiple times. In practical use, such
3052 * cases arise so seldom as to not be worth the added complexity needed;
3053 * moreover, since our rowcount estimates for functions tend to be pretty
3054 * phony, the results would also be pretty phony.
3056 if (IsA(node, FuncExpr))
3058 context->total.per_tuple +=
3059 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
3061 else if (IsA(node, OpExpr) ||
3062 IsA(node, DistinctExpr) ||
3063 IsA(node, NullIfExpr))
3065 /* rely on struct equivalence to treat these all alike */
3066 set_opfuncid((OpExpr *) node);
3067 context->total.per_tuple +=
3068 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
3070 else if (IsA(node, ScalarArrayOpExpr))
3073 * Estimate that the operator will be applied to about half of the
3074 * array elements before the answer is determined.
3076 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
3077 Node *arraynode = (Node *) lsecond(saop->args);
3079 set_sa_opfuncid(saop);
3080 context->total.per_tuple += get_func_cost(saop->opfuncid) *
3081 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
3083 else if (IsA(node, Aggref) ||
3084 IsA(node, WindowFunc))
3087 * Aggref and WindowFunc nodes are (and should be) treated like Vars,
3088 * ie, zero execution cost in the current model, because they behave
3089 * essentially like Vars in execQual.c. We disregard the costs of
3090 * their input expressions for the same reason. The actual execution
3091 * costs of the aggregate/window functions and their arguments have to
3092 * be factored into plan-node-specific costing of the Agg or WindowAgg
3095 return false; /* don't recurse into children */
3097 else if (IsA(node, CoerceViaIO))
3099 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3104 /* check the result type's input function */
3105 getTypeInputInfo(iocoerce->resulttype,
3106 &iofunc, &typioparam);
3107 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3108 /* check the input type's output function */
3109 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
3110 &iofunc, &typisvarlena);
3111 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3113 else if (IsA(node, ArrayCoerceExpr))
3115 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3116 Node *arraynode = (Node *) acoerce->arg;
3118 if (OidIsValid(acoerce->elemfuncid))
3119 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
3120 cpu_operator_cost * estimate_array_length(arraynode);
3122 else if (IsA(node, RowCompareExpr))
3124 /* Conservatively assume we will check all the columns */
3125 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3128 foreach(lc, rcexpr->opnos)
3130 Oid opid = lfirst_oid(lc);
3132 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
3136 else if (IsA(node, CurrentOfExpr))
3138 /* Report high cost to prevent selection of anything but TID scan */
3139 context->total.startup += disable_cost;
3141 else if (IsA(node, SubLink))
3143 /* This routine should not be applied to un-planned expressions */
3144 elog(ERROR, "cannot handle unplanned sub-select");
3146 else if (IsA(node, SubPlan))
3149 * A subplan node in an expression typically indicates that the
3150 * subplan will be executed on each evaluation, so charge accordingly.
3151 * (Sub-selects that can be executed as InitPlans have already been
3152 * removed from the expression.)
3154 SubPlan *subplan = (SubPlan *) node;
3156 context->total.startup += subplan->startup_cost;
3157 context->total.per_tuple += subplan->per_call_cost;
3160 * We don't want to recurse into the testexpr, because it was already
3161 * counted in the SubPlan node's costs. So we're done.
3165 else if (IsA(node, AlternativeSubPlan))
3168 * Arbitrarily use the first alternative plan for costing. (We should
3169 * certainly only include one alternative, and we don't yet have
3170 * enough information to know which one the executor is most likely to
3173 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
3175 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
3179 /* recurse into children */
3180 return expression_tree_walker(node, cost_qual_eval_walker,
3185 * get_restriction_qual_cost
3186 * Compute evaluation costs of a baserel's restriction quals, plus any
3187 * movable join quals that have been pushed down to the scan.
3188 * Results are returned into *qpqual_cost.
3190 * This is a convenience subroutine that works for seqscans and other cases
3191 * where all the given quals will be evaluated the hard way. It's not useful
3192 * for cost_index(), for example, where the index machinery takes care of
3193 * some of the quals. We assume baserestrictcost was previously set by
3194 * set_baserel_size_estimates().
3197 get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
3198 ParamPathInfo *param_info,
3199 QualCost *qpqual_cost)
3203 /* Include costs of pushed-down clauses */
3204 cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
3206 qpqual_cost->startup += baserel->baserestrictcost.startup;
3207 qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
3210 *qpqual_cost = baserel->baserestrictcost;
3215 * compute_semi_anti_join_factors
3216 * Estimate how much of the inner input a SEMI or ANTI join
3217 * can be expected to scan.
3219 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
3220 * inner rows as soon as it finds a match to the current outer row.
3221 * We should therefore adjust some of the cost components for this effect.
3222 * This function computes some estimates needed for these adjustments.
3223 * These estimates will be the same regardless of the particular paths used
3224 * for the outer and inner relation, so we compute these once and then pass
3225 * them to all the join cost estimation functions.
3228 * outerrel: outer relation under consideration
3229 * innerrel: inner relation under consideration
3230 * jointype: must be JOIN_SEMI or JOIN_ANTI
3231 * sjinfo: SpecialJoinInfo relevant to this join
3232 * restrictlist: join quals
3233 * Output parameters:
3234 * *semifactors is filled in (see relation.h for field definitions)
3237 compute_semi_anti_join_factors(PlannerInfo *root,
3238 RelOptInfo *outerrel,
3239 RelOptInfo *innerrel,
3241 SpecialJoinInfo *sjinfo,
3243 SemiAntiJoinFactors *semifactors)
3247 Selectivity avgmatch;
3248 SpecialJoinInfo norm_sjinfo;
3252 /* Should only be called in these cases */
3253 Assert(jointype == JOIN_SEMI || jointype == JOIN_ANTI);
3256 * In an ANTI join, we must ignore clauses that are "pushed down", since
3257 * those won't affect the match logic. In a SEMI join, we do not
3258 * distinguish joinquals from "pushed down" quals, so just use the whole
3259 * restrictinfo list.
3261 if (jointype == JOIN_ANTI)
3264 foreach(l, restrictlist)
3266 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3268 Assert(IsA(rinfo, RestrictInfo));
3269 if (!rinfo->is_pushed_down)
3270 joinquals = lappend(joinquals, rinfo);
3274 joinquals = restrictlist;
3277 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
3279 jselec = clauselist_selectivity(root,
3286 * Also get the normal inner-join selectivity of the join clauses.
3288 norm_sjinfo.type = T_SpecialJoinInfo;
3289 norm_sjinfo.min_lefthand = outerrel->relids;
3290 norm_sjinfo.min_righthand = innerrel->relids;
3291 norm_sjinfo.syn_lefthand = outerrel->relids;
3292 norm_sjinfo.syn_righthand = innerrel->relids;
3293 norm_sjinfo.jointype = JOIN_INNER;
3294 /* we don't bother trying to make the remaining fields valid */
3295 norm_sjinfo.lhs_strict = false;
3296 norm_sjinfo.delay_upper_joins = false;
3297 norm_sjinfo.semi_can_btree = false;
3298 norm_sjinfo.semi_can_hash = false;
3299 norm_sjinfo.semi_operators = NIL;
3300 norm_sjinfo.semi_rhs_exprs = NIL;
3302 nselec = clauselist_selectivity(root,
3308 /* Avoid leaking a lot of ListCells */
3309 if (jointype == JOIN_ANTI)
3310 list_free(joinquals);
3313 * jselec can be interpreted as the fraction of outer-rel rows that have
3314 * any matches (this is true for both SEMI and ANTI cases). And nselec is
3315 * the fraction of the Cartesian product that matches. So, the average
3316 * number of matches for each outer-rel row that has at least one match is
3317 * nselec * inner_rows / jselec.
3319 * Note: it is correct to use the inner rel's "rows" count here, even
3320 * though we might later be considering a parameterized inner path with
3321 * fewer rows. This is because we have included all the join clauses in
3322 * the selectivity estimate.
3324 if (jselec > 0) /* protect against zero divide */
3326 avgmatch = nselec * innerrel->rows / jselec;
3327 /* Clamp to sane range */
3328 avgmatch = Max(1.0, avgmatch);
3333 semifactors->outer_match_frac = jselec;
3334 semifactors->match_count = avgmatch;
3338 * has_indexed_join_quals
3339 * Check whether all the joinquals of a nestloop join are used as
3340 * inner index quals.
3342 * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
3343 * indexscan) that uses all the joinquals as indexquals, we can assume that an
3344 * unmatched outer tuple is cheap to process, whereas otherwise it's probably
3348 has_indexed_join_quals(NestPath *joinpath)
3350 Relids joinrelids = joinpath->path.parent->relids;
3351 Path *innerpath = joinpath->innerjoinpath;
3356 /* If join still has quals to evaluate, it's not fast */
3357 if (joinpath->joinrestrictinfo != NIL)
3359 /* Nor if the inner path isn't parameterized at all */
3360 if (innerpath->param_info == NULL)
3363 /* Find the indexclauses list for the inner scan */
3364 switch (innerpath->pathtype)
3367 case T_IndexOnlyScan:
3368 indexclauses = ((IndexPath *) innerpath)->indexclauses;
3370 case T_BitmapHeapScan:
3372 /* Accept only a simple bitmap scan, not AND/OR cases */
3373 Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
3375 if (IsA(bmqual, IndexPath))
3376 indexclauses = ((IndexPath *) bmqual)->indexclauses;
3384 * If it's not a simple indexscan, it probably doesn't run quickly
3385 * for zero rows out, even if it's a parameterized path using all
3392 * Examine the inner path's param clauses. Any that are from the outer
3393 * path must be found in the indexclauses list, either exactly or in an
3394 * equivalent form generated by equivclass.c. Also, we must find at least
3395 * one such clause, else it's a clauseless join which isn't fast.
3398 foreach(lc, innerpath->param_info->ppi_clauses)
3400 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3402 if (join_clause_is_movable_into(rinfo,
3403 innerpath->parent->relids,
3406 if (!(list_member_ptr(indexclauses, rinfo) ||
3407 is_redundant_derived_clause(rinfo, indexclauses)))
3417 * approx_tuple_count
3418 * Quick-and-dirty estimation of the number of join rows passing
3419 * a set of qual conditions.
3421 * The quals can be either an implicitly-ANDed list of boolean expressions,
3422 * or a list of RestrictInfo nodes (typically the latter).
3424 * We intentionally compute the selectivity under JOIN_INNER rules, even
3425 * if it's some type of outer join. This is appropriate because we are
3426 * trying to figure out how many tuples pass the initial merge or hash
3429 * This is quick-and-dirty because we bypass clauselist_selectivity, and
3430 * simply multiply the independent clause selectivities together. Now
3431 * clauselist_selectivity often can't do any better than that anyhow, but
3432 * for some situations (such as range constraints) it is smarter. However,
3433 * we can't effectively cache the results of clauselist_selectivity, whereas
3434 * the individual clause selectivities can be and are cached.
3436 * Since we are only using the results to estimate how many potential
3437 * output tuples are generated and passed through qpqual checking, it
3438 * seems OK to live with the approximation.
3441 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
3444 double outer_tuples = path->outerjoinpath->rows;
3445 double inner_tuples = path->innerjoinpath->rows;
3446 SpecialJoinInfo sjinfo;
3447 Selectivity selec = 1.0;
3451 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
3453 sjinfo.type = T_SpecialJoinInfo;
3454 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
3455 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
3456 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
3457 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
3458 sjinfo.jointype = JOIN_INNER;
3459 /* we don't bother trying to make the remaining fields valid */
3460 sjinfo.lhs_strict = false;
3461 sjinfo.delay_upper_joins = false;
3462 sjinfo.semi_can_btree = false;
3463 sjinfo.semi_can_hash = false;
3464 sjinfo.semi_operators = NIL;
3465 sjinfo.semi_rhs_exprs = NIL;
3467 /* Get the approximate selectivity */
3470 Node *qual = (Node *) lfirst(l);
3472 /* Note that clause_selectivity will be able to cache its result */
3473 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
3476 /* Apply it to the input relation sizes */
3477 tuples = selec * outer_tuples * inner_tuples;
3479 return clamp_row_est(tuples);
3484 * set_baserel_size_estimates
3485 * Set the size estimates for the given base relation.
3487 * The rel's targetlist and restrictinfo list must have been constructed
3488 * already, and rel->tuples must be set.
3490 * We set the following fields of the rel node:
3491 * rows: the estimated number of output tuples (after applying
3492 * restriction clauses).
3493 * width: the estimated average output tuple width in bytes.
3494 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
3497 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3501 /* Should only be applied to base relations */
3502 Assert(rel->relid > 0);
3504 nrows = rel->tuples *
3505 clauselist_selectivity(root,
3506 rel->baserestrictinfo,
3511 rel->rows = clamp_row_est(nrows);
3513 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3515 set_rel_width(root, rel);
3519 * get_parameterized_baserel_size
3520 * Make a size estimate for a parameterized scan of a base relation.
3522 * 'param_clauses' lists the additional join clauses to be used.
3524 * set_baserel_size_estimates must have been applied already.
3527 get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel,
3528 List *param_clauses)
3534 * Estimate the number of rows returned by the parameterized scan, knowing
3535 * that it will apply all the extra join clauses as well as the rel's own
3536 * restriction clauses. Note that we force the clauses to be treated as
3537 * non-join clauses during selectivity estimation.
3539 allclauses = list_concat(list_copy(param_clauses),
3540 rel->baserestrictinfo);
3541 nrows = rel->tuples *
3542 clauselist_selectivity(root,
3544 rel->relid, /* do not use 0! */
3547 nrows = clamp_row_est(nrows);
3548 /* For safety, make sure result is not more than the base estimate */
3549 if (nrows > rel->rows)
3555 * set_joinrel_size_estimates
3556 * Set the size estimates for the given join relation.
3558 * The rel's targetlist must have been constructed already, and a
3559 * restriction clause list that matches the given component rels must
3562 * Since there is more than one way to make a joinrel for more than two
3563 * base relations, the results we get here could depend on which component
3564 * rel pair is provided. In theory we should get the same answers no matter
3565 * which pair is provided; in practice, since the selectivity estimation
3566 * routines don't handle all cases equally well, we might not. But there's
3567 * not much to be done about it. (Would it make sense to repeat the
3568 * calculations for each pair of input rels that's encountered, and somehow
3569 * average the results? Probably way more trouble than it's worth, and
3570 * anyway we must keep the rowcount estimate the same for all paths for the
3573 * We set only the rows field here. The width field was already set by
3574 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3577 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3578 RelOptInfo *outer_rel,
3579 RelOptInfo *inner_rel,
3580 SpecialJoinInfo *sjinfo,
3583 rel->rows = calc_joinrel_size_estimate(root,
3591 * get_parameterized_joinrel_size
3592 * Make a size estimate for a parameterized scan of a join relation.
3594 * 'rel' is the joinrel under consideration.
3595 * 'outer_rows', 'inner_rows' are the sizes of the (probably also
3596 * parameterized) join inputs under consideration.
3597 * 'sjinfo' is any SpecialJoinInfo relevant to this join.
3598 * 'restrict_clauses' lists the join clauses that need to be applied at the
3599 * join node (including any movable clauses that were moved down to this join,
3600 * and not including any movable clauses that were pushed down into the
3603 * set_joinrel_size_estimates must have been applied already.
3606 get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel,
3609 SpecialJoinInfo *sjinfo,
3610 List *restrict_clauses)
3615 * Estimate the number of rows returned by the parameterized join as the
3616 * sizes of the input paths times the selectivity of the clauses that have
3617 * ended up at this join node.
3619 * As with set_joinrel_size_estimates, the rowcount estimate could depend
3620 * on the pair of input paths provided, though ideally we'd get the same
3621 * estimate for any pair with the same parameterization.
3623 nrows = calc_joinrel_size_estimate(root,
3628 /* For safety, make sure result is not more than the base estimate */
3629 if (nrows > rel->rows)
3635 * calc_joinrel_size_estimate
3636 * Workhorse for set_joinrel_size_estimates and
3637 * get_parameterized_joinrel_size.
3640 calc_joinrel_size_estimate(PlannerInfo *root,
3643 SpecialJoinInfo *sjinfo,
3646 JoinType jointype = sjinfo->jointype;
3652 * Compute joinclause selectivity. Note that we are only considering
3653 * clauses that become restriction clauses at this join level; we are not
3654 * double-counting them because they were not considered in estimating the
3655 * sizes of the component rels.
3657 * For an outer join, we have to distinguish the selectivity of the join's
3658 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3659 * down". For inner joins we just count them all as joinclauses.
3661 if (IS_OUTER_JOIN(jointype))
3663 List *joinquals = NIL;
3664 List *pushedquals = NIL;
3667 /* Grovel through the clauses to separate into two lists */
3668 foreach(l, restrictlist)
3670 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3672 Assert(IsA(rinfo, RestrictInfo));
3673 if (rinfo->is_pushed_down)
3674 pushedquals = lappend(pushedquals, rinfo);
3676 joinquals = lappend(joinquals, rinfo);
3679 /* Get the separate selectivities */
3680 jselec = clauselist_selectivity(root,
3685 pselec = clauselist_selectivity(root,
3691 /* Avoid leaking a lot of ListCells */
3692 list_free(joinquals);
3693 list_free(pushedquals);
3697 jselec = clauselist_selectivity(root,
3702 pselec = 0.0; /* not used, keep compiler quiet */
3706 * Basically, we multiply size of Cartesian product by selectivity.
3708 * If we are doing an outer join, take that into account: the joinqual
3709 * selectivity has to be clamped using the knowledge that the output must
3710 * be at least as large as the non-nullable input. However, any
3711 * pushed-down quals are applied after the outer join, so their
3712 * selectivity applies fully.
3714 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3715 * of LHS rows that have matches, and we apply that straightforwardly.
3720 nrows = outer_rows * inner_rows * jselec;
3723 nrows = outer_rows * inner_rows * jselec;
3724 if (nrows < outer_rows)
3729 nrows = outer_rows * inner_rows * jselec;
3730 if (nrows < outer_rows)
3732 if (nrows < inner_rows)
3737 nrows = outer_rows * jselec;
3738 /* pselec not used */
3741 nrows = outer_rows * (1.0 - jselec);
3745 /* other values not expected here */
3746 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3747 nrows = 0; /* keep compiler quiet */
3751 return clamp_row_est(nrows);
3755 * set_subquery_size_estimates
3756 * Set the size estimates for a base relation that is a subquery.
3758 * The rel's targetlist and restrictinfo list must have been constructed
3759 * already, and the plan for the subquery must have been completed.
3760 * We look at the subquery's plan and PlannerInfo to extract data.
3762 * We set the same fields as set_baserel_size_estimates.
3765 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3767 PlannerInfo *subroot = rel->subroot;
3768 RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
3771 /* Should only be applied to base relations that are subqueries */
3772 Assert(rel->relid > 0);
3773 rte = planner_rt_fetch(rel->relid, root);
3774 Assert(rte->rtekind == RTE_SUBQUERY);
3776 /* Copy raw number of output rows from subplan */
3777 rel->tuples = rel->subplan->plan_rows;
3780 * Compute per-output-column width estimates by examining the subquery's
3781 * targetlist. For any output that is a plain Var, get the width estimate
3782 * that was made while planning the subquery. Otherwise, we leave it to
3783 * set_rel_width to fill in a datatype-based default estimate.
3785 foreach(lc, subroot->parse->targetList)
3787 TargetEntry *te = (TargetEntry *) lfirst(lc);
3788 Node *texpr = (Node *) te->expr;
3789 int32 item_width = 0;
3791 Assert(IsA(te, TargetEntry));
3792 /* junk columns aren't visible to upper query */
3797 * The subquery could be an expansion of a view that's had columns
3798 * added to it since the current query was parsed, so that there are
3799 * non-junk tlist columns in it that don't correspond to any column
3800 * visible at our query level. Ignore such columns.
3802 if (te->resno < rel->min_attr || te->resno > rel->max_attr)
3806 * XXX This currently doesn't work for subqueries containing set
3807 * operations, because the Vars in their tlists are bogus references
3808 * to the first leaf subquery, which wouldn't give the right answer
3809 * even if we could still get to its PlannerInfo.
3811 * Also, the subquery could be an appendrel for which all branches are
3812 * known empty due to constraint exclusion, in which case
3813 * set_append_rel_pathlist will have left the attr_widths set to zero.
3815 * In either case, we just leave the width estimate zero until
3816 * set_rel_width fixes it.
3818 if (IsA(texpr, Var) &&
3819 subroot->parse->setOperations == NULL)
3821 Var *var = (Var *) texpr;
3822 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3824 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3826 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3829 /* Now estimate number of output rows, etc */
3830 set_baserel_size_estimates(root, rel);
3834 * set_function_size_estimates
3835 * Set the size estimates for a base relation that is a function call.
3837 * The rel's targetlist and restrictinfo list must have been constructed
3840 * We set the same fields as set_baserel_size_estimates.
3843 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3848 /* Should only be applied to base relations that are functions */
3849 Assert(rel->relid > 0);
3850 rte = planner_rt_fetch(rel->relid, root);
3851 Assert(rte->rtekind == RTE_FUNCTION);
3854 * Estimate number of rows the functions will return. The rowcount of the
3855 * node is that of the largest function result.
3858 foreach(lc, rte->functions)
3860 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
3861 double ntup = expression_returns_set_rows(rtfunc->funcexpr);
3863 if (ntup > rel->tuples)
3867 /* Now estimate number of output rows, etc */
3868 set_baserel_size_estimates(root, rel);
3872 * set_values_size_estimates
3873 * Set the size estimates for a base relation that is a values list.
3875 * The rel's targetlist and restrictinfo list must have been constructed
3878 * We set the same fields as set_baserel_size_estimates.
3881 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3885 /* Should only be applied to base relations that are values lists */
3886 Assert(rel->relid > 0);
3887 rte = planner_rt_fetch(rel->relid, root);
3888 Assert(rte->rtekind == RTE_VALUES);
3891 * Estimate number of rows the values list will return. We know this
3892 * precisely based on the list length (well, barring set-returning
3893 * functions in list items, but that's a refinement not catered for
3894 * anywhere else either).
3896 rel->tuples = list_length(rte->values_lists);
3898 /* Now estimate number of output rows, etc */
3899 set_baserel_size_estimates(root, rel);
3903 * set_cte_size_estimates
3904 * Set the size estimates for a base relation that is a CTE reference.
3906 * The rel's targetlist and restrictinfo list must have been constructed
3907 * already, and we need the completed plan for the CTE (if a regular CTE)
3908 * or the non-recursive term (if a self-reference).
3910 * We set the same fields as set_baserel_size_estimates.
3913 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3917 /* Should only be applied to base relations that are CTE references */
3918 Assert(rel->relid > 0);
3919 rte = planner_rt_fetch(rel->relid, root);
3920 Assert(rte->rtekind == RTE_CTE);
3922 if (rte->self_reference)
3925 * In a self-reference, arbitrarily assume the average worktable size
3926 * is about 10 times the nonrecursive term's size.
3928 rel->tuples = 10 * cteplan->plan_rows;
3932 /* Otherwise just believe the CTE plan's output estimate */
3933 rel->tuples = cteplan->plan_rows;
3936 /* Now estimate number of output rows, etc */
3937 set_baserel_size_estimates(root, rel);
3941 * set_foreign_size_estimates
3942 * Set the size estimates for a base relation that is a foreign table.
3944 * There is not a whole lot that we can do here; the foreign-data wrapper
3945 * is responsible for producing useful estimates. We can do a decent job
3946 * of estimating baserestrictcost, so we set that, and we also set up width
3947 * using what will be purely datatype-driven estimates from the targetlist.
3948 * There is no way to do anything sane with the rows value, so we just put
3949 * a default estimate and hope that the wrapper can improve on it. The
3950 * wrapper's GetForeignRelSize function will be called momentarily.
3952 * The rel's targetlist and restrictinfo list must have been constructed
3956 set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3958 /* Should only be applied to base relations */
3959 Assert(rel->relid > 0);
3961 rel->rows = 1000; /* entirely bogus default estimate */
3963 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3965 set_rel_width(root, rel);
3971 * Set the estimated output width of a base relation.
3973 * The estimated output width is the sum of the per-attribute width estimates
3974 * for the actually-referenced columns, plus any PHVs or other expressions
3975 * that have to be calculated at this relation. This is the amount of data
3976 * we'd need to pass upwards in case of a sort, hash, etc.
3978 * NB: this works best on plain relations because it prefers to look at
3979 * real Vars. For subqueries, set_subquery_size_estimates will already have
3980 * copied up whatever per-column estimates were made within the subquery,
3981 * and for other types of rels there isn't much we can do anyway. We fall
3982 * back on (fairly stupid) datatype-based width estimates if we can't get
3983 * any better number.
3985 * The per-attribute width estimates are cached for possible re-use while
3986 * building join relations.
3989 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3991 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3992 int32 tuple_width = 0;
3993 bool have_wholerow_var = false;
3996 foreach(lc, rel->reltargetlist)
3998 Node *node = (Node *) lfirst(lc);
4001 * Ordinarily, a Var in a rel's reltargetlist must belong to that rel;
4002 * but there are corner cases involving LATERAL references where that
4003 * isn't so. If the Var has the wrong varno, fall through to the
4004 * generic case (it doesn't seem worth the trouble to be any smarter).
4006 if (IsA(node, Var) &&
4007 ((Var *) node)->varno == rel->relid)
4009 Var *var = (Var *) node;
4013 Assert(var->varattno >= rel->min_attr);
4014 Assert(var->varattno <= rel->max_attr);
4016 ndx = var->varattno - rel->min_attr;
4019 * If it's a whole-row Var, we'll deal with it below after we have
4020 * already cached as many attr widths as possible.
4022 if (var->varattno == 0)
4024 have_wholerow_var = true;
4029 * The width may have been cached already (especially if it's a
4030 * subquery), so don't duplicate effort.
4032 if (rel->attr_widths[ndx] > 0)
4034 tuple_width += rel->attr_widths[ndx];
4038 /* Try to get column width from statistics */
4039 if (reloid != InvalidOid && var->varattno > 0)
4041 item_width = get_attavgwidth(reloid, var->varattno);
4044 rel->attr_widths[ndx] = item_width;
4045 tuple_width += item_width;
4051 * Not a plain relation, or can't find statistics for it. Estimate
4052 * using just the type info.
4054 item_width = get_typavgwidth(var->vartype, var->vartypmod);
4055 Assert(item_width > 0);
4056 rel->attr_widths[ndx] = item_width;
4057 tuple_width += item_width;
4059 else if (IsA(node, PlaceHolderVar))
4061 PlaceHolderVar *phv = (PlaceHolderVar *) node;
4062 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv, false);
4064 tuple_width += phinfo->ph_width;
4069 * We could be looking at an expression pulled up from a subquery,
4070 * or a ROW() representing a whole-row child Var, etc. Do what we
4071 * can using the expression type information.
4075 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
4076 Assert(item_width > 0);
4077 tuple_width += item_width;
4082 * If we have a whole-row reference, estimate its width as the sum of
4083 * per-column widths plus heap tuple header overhead.
4085 if (have_wholerow_var)
4087 int32 wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
4089 if (reloid != InvalidOid)
4091 /* Real relation, so estimate true tuple width */
4092 wholerow_width += get_relation_data_width(reloid,
4093 rel->attr_widths - rel->min_attr);
4097 /* Do what we can with info for a phony rel */
4100 for (i = 1; i <= rel->max_attr; i++)
4101 wholerow_width += rel->attr_widths[i - rel->min_attr];
4104 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
4107 * Include the whole-row Var as part of the output tuple. Yes, that
4108 * really is what happens at runtime.
4110 tuple_width += wholerow_width;
4113 Assert(tuple_width >= 0);
4114 rel->width = tuple_width;
4118 * relation_byte_size
4119 * Estimate the storage space in bytes for a given number of tuples
4120 * of a given width (size in bytes).
4123 relation_byte_size(double tuples, int width)
4125 return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
4130 * Returns an estimate of the number of pages covered by a given
4131 * number of tuples of a given width (size in bytes).
4134 page_size(double tuples, int width)
4136 return ceil(relation_byte_size(tuples, width) / BLCKSZ);