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-2013, 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 MergeScanSelCache *cached_scansel(PlannerInfo *root,
130 static void cost_rescan(PlannerInfo *root, Path *path,
131 Cost *rescan_startup_cost, Cost *rescan_total_cost);
132 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
133 static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
134 ParamPathInfo *param_info,
135 QualCost *qpqual_cost);
136 static bool has_indexed_join_quals(NestPath *joinpath);
137 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
139 static double calc_joinrel_size_estimate(PlannerInfo *root,
142 SpecialJoinInfo *sjinfo,
144 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
145 static double relation_byte_size(double tuples, int width);
146 static double page_size(double tuples, int width);
151 * Force a row-count estimate to a sane value.
154 clamp_row_est(double nrows)
157 * Force estimate to be at least one row, to make explain output look
158 * better and to avoid possible divide-by-zero when interpolating costs.
159 * Make it an integer, too.
172 * Determines and returns the cost of scanning a relation sequentially.
174 * 'baserel' is the relation to be scanned
175 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
178 cost_seqscan(Path *path, PlannerInfo *root,
179 RelOptInfo *baserel, ParamPathInfo *param_info)
181 Cost startup_cost = 0;
183 double spc_seq_page_cost;
184 QualCost qpqual_cost;
187 /* Should only be applied to base relations */
188 Assert(baserel->relid > 0);
189 Assert(baserel->rtekind == RTE_RELATION);
191 /* Mark the path with the correct row estimate */
193 path->rows = param_info->ppi_rows;
195 path->rows = baserel->rows;
198 startup_cost += disable_cost;
200 /* fetch estimated page cost for tablespace containing table */
201 get_tablespace_page_costs(baserel->reltablespace,
208 run_cost += spc_seq_page_cost * baserel->pages;
211 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
213 startup_cost += qpqual_cost.startup;
214 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
215 run_cost += cpu_per_tuple * baserel->tuples;
217 path->startup_cost = startup_cost;
218 path->total_cost = startup_cost + run_cost;
223 * Determines and returns the cost of scanning a relation using an index.
225 * 'path' describes the indexscan under consideration, and is complete
226 * except for the fields to be set by this routine
227 * 'loop_count' is the number of repetitions of the indexscan to factor into
228 * estimates of caching behavior
230 * In addition to rows, startup_cost and total_cost, cost_index() sets the
231 * path's indextotalcost and indexselectivity fields. These values will be
232 * needed if the IndexPath is used in a BitmapIndexScan.
234 * NOTE: path->indexquals must contain only clauses usable as index
235 * restrictions. Any additional quals evaluated as qpquals may reduce the
236 * number of returned tuples, but they won't reduce the number of tuples
237 * we have to fetch from the table, so they don't reduce the scan cost.
240 cost_index(IndexPath *path, PlannerInfo *root, double loop_count)
242 IndexOptInfo *index = path->indexinfo;
243 RelOptInfo *baserel = index->rel;
244 bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
246 Cost startup_cost = 0;
248 Cost indexStartupCost;
250 Selectivity indexSelectivity;
251 double indexCorrelation,
253 double spc_seq_page_cost,
254 spc_random_page_cost;
257 QualCost qpqual_cost;
259 double tuples_fetched;
260 double pages_fetched;
262 /* Should only be applied to base relations */
263 Assert(IsA(baserel, RelOptInfo) &&
264 IsA(index, IndexOptInfo));
265 Assert(baserel->relid > 0);
266 Assert(baserel->rtekind == RTE_RELATION);
268 /* Mark the path with the correct row estimate */
269 if (path->path.param_info)
271 path->path.rows = path->path.param_info->ppi_rows;
272 /* also get the set of clauses that should be enforced by the scan */
273 allclauses = list_concat(list_copy(path->path.param_info->ppi_clauses),
274 baserel->baserestrictinfo);
278 path->path.rows = baserel->rows;
279 /* allclauses should just be the rel's restriction clauses */
280 allclauses = baserel->baserestrictinfo;
283 if (!enable_indexscan)
284 startup_cost += disable_cost;
285 /* we don't need to check enable_indexonlyscan; indxpath.c does that */
288 * Call index-access-method-specific code to estimate the processing cost
289 * for scanning the index, as well as the selectivity of the index (ie,
290 * the fraction of main-table tuples we will have to retrieve) and its
291 * correlation to the main-table tuple order.
293 OidFunctionCall7(index->amcostestimate,
294 PointerGetDatum(root),
295 PointerGetDatum(path),
296 Float8GetDatum(loop_count),
297 PointerGetDatum(&indexStartupCost),
298 PointerGetDatum(&indexTotalCost),
299 PointerGetDatum(&indexSelectivity),
300 PointerGetDatum(&indexCorrelation));
303 * Save amcostestimate's results for possible use in bitmap scan planning.
304 * We don't bother to save indexStartupCost or indexCorrelation, because a
305 * bitmap scan doesn't care about either.
307 path->indextotalcost = indexTotalCost;
308 path->indexselectivity = indexSelectivity;
310 /* all costs for touching index itself included here */
311 startup_cost += indexStartupCost;
312 run_cost += indexTotalCost - indexStartupCost;
314 /* estimate number of main-table tuples fetched */
315 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
317 /* fetch estimated page costs for tablespace containing table */
318 get_tablespace_page_costs(baserel->reltablespace,
319 &spc_random_page_cost,
323 * Estimate number of main-table pages fetched, and compute I/O cost.
325 * When the index ordering is uncorrelated with the table ordering,
326 * we use an approximation proposed by Mackert and Lohman (see
327 * index_pages_fetched() for details) to compute the number of pages
328 * fetched, and then charge spc_random_page_cost per page fetched.
330 * When the index ordering is exactly correlated with the table ordering
331 * (just after a CLUSTER, for example), the number of pages fetched should
332 * be exactly selectivity * table_size. What's more, all but the first
333 * will be sequential fetches, not the random fetches that occur in the
334 * uncorrelated case. So if the number of pages is more than 1, we
336 * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
337 * For partially-correlated indexes, we ought to charge somewhere between
338 * these two estimates. We currently interpolate linearly between the
339 * estimates based on the correlation squared (XXX is that appropriate?).
341 * If it's an index-only scan, then we will not need to fetch any heap
342 * pages for which the visibility map shows all tuples are visible.
343 * Hence, reduce the estimated number of heap fetches accordingly.
344 * We use the measured fraction of the entire heap that is all-visible,
345 * which might not be particularly relevant to the subset of the heap
346 * that this query will fetch; but it's not clear how to do better.
352 * For repeated indexscans, the appropriate estimate for the
353 * uncorrelated case is to scale up the number of tuples fetched in
354 * the Mackert and Lohman formula by the number of scans, so that we
355 * estimate the number of pages fetched by all the scans; then
356 * pro-rate the costs for one scan. In this case we assume all the
357 * fetches are random accesses.
359 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
361 (double) index->pages,
365 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
367 max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
370 * In the perfectly correlated case, the number of pages touched by
371 * each scan is selectivity * table_size, and we can use the Mackert
372 * and Lohman formula at the page level to estimate how much work is
373 * saved by caching across scans. We still assume all the fetches are
374 * random, though, which is an overestimate that's hard to correct for
375 * without double-counting the cache effects. (But in most cases
376 * where such a plan is actually interesting, only one page would get
377 * fetched per scan anyway, so it shouldn't matter much.)
379 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
381 pages_fetched = index_pages_fetched(pages_fetched * loop_count,
383 (double) index->pages,
387 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
389 min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
394 * Normal case: apply the Mackert and Lohman formula, and then
395 * interpolate between that and the correlation-derived result.
397 pages_fetched = index_pages_fetched(tuples_fetched,
399 (double) index->pages,
403 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
405 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
406 max_IO_cost = pages_fetched * spc_random_page_cost;
408 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
409 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
412 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
414 if (pages_fetched > 0)
416 min_IO_cost = spc_random_page_cost;
417 if (pages_fetched > 1)
418 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
425 * Now interpolate based on estimated index order correlation to get total
426 * disk I/O cost for main table accesses.
428 csquared = indexCorrelation * indexCorrelation;
430 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
433 * Estimate CPU costs per tuple.
435 * What we want here is cpu_tuple_cost plus the evaluation costs of any
436 * qual clauses that we have to evaluate as qpquals. We approximate that
437 * list as allclauses minus any clauses appearing in indexquals. (We
438 * assume that pointer equality is enough to recognize duplicate
439 * RestrictInfos.) This method neglects some considerations such as
440 * clauses that needn't be checked because they are implied by a partial
441 * index's predicate. It does not seem worth the cycles to try to factor
442 * those things in at this stage, even though createplan.c will take pains
443 * to remove such unnecessary clauses from the qpquals list if this path
444 * is selected for use.
446 cost_qual_eval(&qpqual_cost,
447 list_difference_ptr(allclauses, path->indexquals),
450 startup_cost += qpqual_cost.startup;
451 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
453 run_cost += cpu_per_tuple * tuples_fetched;
455 path->path.startup_cost = startup_cost;
456 path->path.total_cost = startup_cost + run_cost;
460 * index_pages_fetched
461 * Estimate the number of pages actually fetched after accounting for
464 * We use an approximation proposed by Mackert and Lohman, "Index Scans
465 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
466 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
467 * The Mackert and Lohman approximation is that the number of pages
470 * min(2TNs/(2T+Ns), T) when T <= b
471 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
472 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
474 * T = # pages in table
475 * N = # tuples in table
476 * s = selectivity = fraction of table to be scanned
477 * b = # buffer pages available (we include kernel space here)
479 * We assume that effective_cache_size is the total number of buffer pages
480 * available for the whole query, and pro-rate that space across all the
481 * tables in the query and the index currently under consideration. (This
482 * ignores space needed for other indexes used by the query, but since we
483 * don't know which indexes will get used, we can't estimate that very well;
484 * and in any case counting all the tables may well be an overestimate, since
485 * depending on the join plan not all the tables may be scanned concurrently.)
487 * The product Ns is the number of tuples fetched; we pass in that
488 * product rather than calculating it here. "pages" is the number of pages
489 * in the object under consideration (either an index or a table).
490 * "index_pages" is the amount to add to the total table space, which was
491 * computed for us by query_planner.
493 * Caller is expected to have ensured that tuples_fetched is greater than zero
494 * and rounded to integer (see clamp_row_est). The result will likewise be
495 * greater than zero and integral.
498 index_pages_fetched(double tuples_fetched, BlockNumber pages,
499 double index_pages, PlannerInfo *root)
501 double pages_fetched;
506 /* T is # pages in table, but don't allow it to be zero */
507 T = (pages > 1) ? (double) pages : 1.0;
509 /* Compute number of pages assumed to be competing for cache space */
510 total_pages = root->total_table_pages + index_pages;
511 total_pages = Max(total_pages, 1.0);
512 Assert(T <= total_pages);
514 /* b is pro-rated share of effective_cache_size */
515 b = (double) effective_cache_size *T / total_pages;
517 /* force it positive and integral */
523 /* This part is the Mackert and Lohman formula */
527 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
528 if (pages_fetched >= T)
531 pages_fetched = ceil(pages_fetched);
537 lim = (2.0 * T * b) / (2.0 * T - b);
538 if (tuples_fetched <= lim)
541 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
546 b + (tuples_fetched - lim) * (T - b) / T;
548 pages_fetched = ceil(pages_fetched);
550 return pages_fetched;
554 * get_indexpath_pages
555 * Determine the total size of the indexes used in a bitmap index path.
557 * Note: if the same index is used more than once in a bitmap tree, we will
558 * count it multiple times, which perhaps is the wrong thing ... but it's
559 * not completely clear, and detecting duplicates is difficult, so ignore it
563 get_indexpath_pages(Path *bitmapqual)
568 if (IsA(bitmapqual, BitmapAndPath))
570 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
572 foreach(l, apath->bitmapquals)
574 result += get_indexpath_pages((Path *) lfirst(l));
577 else if (IsA(bitmapqual, BitmapOrPath))
579 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
581 foreach(l, opath->bitmapquals)
583 result += get_indexpath_pages((Path *) lfirst(l));
586 else if (IsA(bitmapqual, IndexPath))
588 IndexPath *ipath = (IndexPath *) bitmapqual;
590 result = (double) ipath->indexinfo->pages;
593 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
599 * cost_bitmap_heap_scan
600 * Determines and returns the cost of scanning a relation using a bitmap
601 * index-then-heap plan.
603 * 'baserel' is the relation to be scanned
604 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
605 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
606 * 'loop_count' is the number of repetitions of the indexscan to factor into
607 * estimates of caching behavior
609 * Note: the component IndexPaths in bitmapqual should have been costed
610 * using the same loop_count.
613 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
614 ParamPathInfo *param_info,
615 Path *bitmapqual, double loop_count)
617 Cost startup_cost = 0;
620 Selectivity indexSelectivity;
621 QualCost qpqual_cost;
624 double tuples_fetched;
625 double pages_fetched;
626 double spc_seq_page_cost,
627 spc_random_page_cost;
630 /* Should only be applied to base relations */
631 Assert(IsA(baserel, RelOptInfo));
632 Assert(baserel->relid > 0);
633 Assert(baserel->rtekind == RTE_RELATION);
635 /* Mark the path with the correct row estimate */
637 path->rows = param_info->ppi_rows;
639 path->rows = baserel->rows;
641 if (!enable_bitmapscan)
642 startup_cost += disable_cost;
645 * Fetch total cost of obtaining the bitmap, as well as its total
648 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
650 startup_cost += indexTotalCost;
652 /* Fetch estimated page costs for tablespace containing table. */
653 get_tablespace_page_costs(baserel->reltablespace,
654 &spc_random_page_cost,
658 * Estimate number of main-table pages fetched.
660 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
662 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
667 * For repeated bitmap scans, scale up the number of tuples fetched in
668 * the Mackert and Lohman formula by the number of scans, so that we
669 * estimate the number of pages fetched by all the scans. Then
670 * pro-rate for one scan.
672 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
674 get_indexpath_pages(bitmapqual),
676 pages_fetched /= loop_count;
681 * For a single scan, the number of heap pages that need to be fetched
682 * is the same as the Mackert and Lohman formula for the case T <= b
683 * (ie, no re-reads needed).
685 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
687 if (pages_fetched >= T)
690 pages_fetched = ceil(pages_fetched);
693 * For small numbers of pages we should charge spc_random_page_cost
694 * apiece, while if nearly all the table's pages are being read, it's more
695 * appropriate to charge spc_seq_page_cost apiece. The effect is
696 * nonlinear, too. For lack of a better idea, interpolate like this to
697 * determine the cost per page.
699 if (pages_fetched >= 2.0)
700 cost_per_page = spc_random_page_cost -
701 (spc_random_page_cost - spc_seq_page_cost)
702 * sqrt(pages_fetched / T);
704 cost_per_page = spc_random_page_cost;
706 run_cost += pages_fetched * cost_per_page;
709 * Estimate CPU costs per tuple.
711 * Often the indexquals don't need to be rechecked at each tuple ... but
712 * not always, especially not if there are enough tuples involved that the
713 * bitmaps become lossy. For the moment, just assume they will be
714 * rechecked always. This means we charge the full freight for all the
717 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
719 startup_cost += qpqual_cost.startup;
720 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
722 run_cost += cpu_per_tuple * tuples_fetched;
724 path->startup_cost = startup_cost;
725 path->total_cost = startup_cost + run_cost;
729 * cost_bitmap_tree_node
730 * Extract cost and selectivity from a bitmap tree node (index/and/or)
733 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
735 if (IsA(path, IndexPath))
737 *cost = ((IndexPath *) path)->indextotalcost;
738 *selec = ((IndexPath *) path)->indexselectivity;
741 * Charge a small amount per retrieved tuple to reflect the costs of
742 * manipulating the bitmap. This is mostly to make sure that a bitmap
743 * scan doesn't look to be the same cost as an indexscan to retrieve a
746 *cost += 0.1 * cpu_operator_cost * path->rows;
748 else if (IsA(path, BitmapAndPath))
750 *cost = path->total_cost;
751 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
753 else if (IsA(path, BitmapOrPath))
755 *cost = path->total_cost;
756 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
760 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
761 *cost = *selec = 0; /* keep compiler quiet */
766 * cost_bitmap_and_node
767 * Estimate the cost of a BitmapAnd node
769 * Note that this considers only the costs of index scanning and bitmap
770 * creation, not the eventual heap access. In that sense the object isn't
771 * truly a Path, but it has enough path-like properties (costs in particular)
772 * to warrant treating it as one. We don't bother to set the path rows field,
776 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
783 * We estimate AND selectivity on the assumption that the inputs are
784 * independent. This is probably often wrong, but we don't have the info
787 * The runtime cost of the BitmapAnd itself is estimated at 100x
788 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
789 * definitely too simplistic?
793 foreach(l, path->bitmapquals)
795 Path *subpath = (Path *) lfirst(l);
797 Selectivity subselec;
799 cost_bitmap_tree_node(subpath, &subCost, &subselec);
803 totalCost += subCost;
804 if (l != list_head(path->bitmapquals))
805 totalCost += 100.0 * cpu_operator_cost;
807 path->bitmapselectivity = selec;
808 path->path.rows = 0; /* per above, not used */
809 path->path.startup_cost = totalCost;
810 path->path.total_cost = totalCost;
814 * cost_bitmap_or_node
815 * Estimate the cost of a BitmapOr node
817 * See comments for cost_bitmap_and_node.
820 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
827 * We estimate OR selectivity on the assumption that the inputs are
828 * non-overlapping, since that's often the case in "x IN (list)" type
829 * situations. Of course, we clamp to 1.0 at the end.
831 * The runtime cost of the BitmapOr itself is estimated at 100x
832 * cpu_operator_cost for each tbm_union needed. Probably too small,
833 * definitely too simplistic? We are aware that the tbm_unions are
834 * optimized out when the inputs are BitmapIndexScans.
838 foreach(l, path->bitmapquals)
840 Path *subpath = (Path *) lfirst(l);
842 Selectivity subselec;
844 cost_bitmap_tree_node(subpath, &subCost, &subselec);
848 totalCost += subCost;
849 if (l != list_head(path->bitmapquals) &&
850 !IsA(subpath, IndexPath))
851 totalCost += 100.0 * cpu_operator_cost;
853 path->bitmapselectivity = Min(selec, 1.0);
854 path->path.rows = 0; /* per above, not used */
855 path->path.startup_cost = totalCost;
856 path->path.total_cost = totalCost;
861 * Determines and returns the cost of scanning a relation using TIDs.
863 * 'baserel' is the relation to be scanned
864 * 'tidquals' is the list of TID-checkable quals
865 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
868 cost_tidscan(Path *path, PlannerInfo *root,
869 RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
871 Cost startup_cost = 0;
873 bool isCurrentOf = false;
874 QualCost qpqual_cost;
876 QualCost tid_qual_cost;
879 double spc_random_page_cost;
881 /* Should only be applied to base relations */
882 Assert(baserel->relid > 0);
883 Assert(baserel->rtekind == RTE_RELATION);
885 /* Mark the path with the correct row estimate */
887 path->rows = param_info->ppi_rows;
889 path->rows = baserel->rows;
891 /* Count how many tuples we expect to retrieve */
895 if (IsA(lfirst(l), ScalarArrayOpExpr))
897 /* Each element of the array yields 1 tuple */
898 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
899 Node *arraynode = (Node *) lsecond(saop->args);
901 ntuples += estimate_array_length(arraynode);
903 else if (IsA(lfirst(l), CurrentOfExpr))
905 /* CURRENT OF yields 1 tuple */
911 /* It's just CTID = something, count 1 tuple */
917 * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
918 * understands how to do it correctly. Therefore, honor enable_tidscan
919 * only when CURRENT OF isn't present. Also note that cost_qual_eval
920 * counts a CurrentOfExpr as having startup cost disable_cost, which we
921 * subtract off here; that's to prevent other plan types such as seqscan
926 Assert(baserel->baserestrictcost.startup >= disable_cost);
927 startup_cost -= disable_cost;
929 else if (!enable_tidscan)
930 startup_cost += disable_cost;
933 * The TID qual expressions will be computed once, any other baserestrict
934 * quals once per retrived tuple.
936 cost_qual_eval(&tid_qual_cost, tidquals, root);
938 /* fetch estimated page cost for tablespace containing table */
939 get_tablespace_page_costs(baserel->reltablespace,
940 &spc_random_page_cost,
943 /* disk costs --- assume each tuple on a different page */
944 run_cost += spc_random_page_cost * ntuples;
946 /* Add scanning CPU costs */
947 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
949 /* XXX currently we assume TID quals are a subset of qpquals */
950 startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
951 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
952 tid_qual_cost.per_tuple;
953 run_cost += cpu_per_tuple * ntuples;
955 path->startup_cost = startup_cost;
956 path->total_cost = startup_cost + run_cost;
961 * Determines and returns the cost of scanning a subquery RTE.
963 * 'baserel' is the relation to be scanned
964 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
967 cost_subqueryscan(Path *path, PlannerInfo *root,
968 RelOptInfo *baserel, ParamPathInfo *param_info)
972 QualCost qpqual_cost;
975 /* Should only be applied to base relations that are subqueries */
976 Assert(baserel->relid > 0);
977 Assert(baserel->rtekind == RTE_SUBQUERY);
979 /* Mark the path with the correct row estimate */
981 path->rows = param_info->ppi_rows;
983 path->rows = baserel->rows;
986 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
987 * any restriction clauses that will be attached to the SubqueryScan node,
988 * plus cpu_tuple_cost to account for selection and projection overhead.
990 path->startup_cost = baserel->subplan->startup_cost;
991 path->total_cost = baserel->subplan->total_cost;
993 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
995 startup_cost = qpqual_cost.startup;
996 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
997 run_cost = cpu_per_tuple * baserel->tuples;
999 path->startup_cost += startup_cost;
1000 path->total_cost += startup_cost + run_cost;
1005 * Determines and returns the cost of scanning a function RTE.
1007 * 'baserel' is the relation to be scanned
1008 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1011 cost_functionscan(Path *path, PlannerInfo *root,
1012 RelOptInfo *baserel, ParamPathInfo *param_info)
1014 Cost startup_cost = 0;
1016 QualCost qpqual_cost;
1021 /* Should only be applied to base relations that are functions */
1022 Assert(baserel->relid > 0);
1023 rte = planner_rt_fetch(baserel->relid, root);
1024 Assert(rte->rtekind == RTE_FUNCTION);
1026 /* Mark the path with the correct row estimate */
1028 path->rows = param_info->ppi_rows;
1030 path->rows = baserel->rows;
1033 * Estimate costs of executing the function expression.
1035 * Currently, nodeFunctionscan.c always executes the function to
1036 * completion before returning any rows, and caches the results in a
1037 * tuplestore. So the function eval cost is all startup cost, and per-row
1038 * costs are minimal.
1040 * XXX in principle we ought to charge tuplestore spill costs if the
1041 * number of rows is large. However, given how phony our rowcount
1042 * estimates for functions tend to be, there's not a lot of point in that
1043 * refinement right now.
1045 cost_qual_eval_node(&exprcost, rte->funcexpr, root);
1047 startup_cost += exprcost.startup + exprcost.per_tuple;
1049 /* Add scanning CPU costs */
1050 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1052 startup_cost += qpqual_cost.startup;
1053 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1054 run_cost += cpu_per_tuple * baserel->tuples;
1056 path->startup_cost = startup_cost;
1057 path->total_cost = startup_cost + run_cost;
1062 * Determines and returns the cost of scanning a VALUES RTE.
1064 * 'baserel' is the relation to be scanned
1065 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1068 cost_valuesscan(Path *path, PlannerInfo *root,
1069 RelOptInfo *baserel, ParamPathInfo *param_info)
1071 Cost startup_cost = 0;
1073 QualCost qpqual_cost;
1076 /* Should only be applied to base relations that are values lists */
1077 Assert(baserel->relid > 0);
1078 Assert(baserel->rtekind == RTE_VALUES);
1080 /* Mark the path with the correct row estimate */
1082 path->rows = param_info->ppi_rows;
1084 path->rows = baserel->rows;
1087 * For now, estimate list evaluation cost at one operator eval per list
1088 * (probably pretty bogus, but is it worth being smarter?)
1090 cpu_per_tuple = cpu_operator_cost;
1092 /* Add scanning CPU costs */
1093 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1095 startup_cost += qpqual_cost.startup;
1096 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1097 run_cost += cpu_per_tuple * baserel->tuples;
1099 path->startup_cost = startup_cost;
1100 path->total_cost = startup_cost + run_cost;
1105 * Determines and returns the cost of scanning a CTE RTE.
1107 * Note: this is used for both self-reference and regular CTEs; the
1108 * possible cost differences are below the threshold of what we could
1109 * estimate accurately anyway. Note that the costs of evaluating the
1110 * referenced CTE query are added into the final plan as initplan costs,
1111 * and should NOT be counted here.
1114 cost_ctescan(Path *path, PlannerInfo *root,
1115 RelOptInfo *baserel, ParamPathInfo *param_info)
1117 Cost startup_cost = 0;
1119 QualCost qpqual_cost;
1122 /* Should only be applied to base relations that are CTEs */
1123 Assert(baserel->relid > 0);
1124 Assert(baserel->rtekind == RTE_CTE);
1126 /* Mark the path with the correct row estimate */
1128 path->rows = param_info->ppi_rows;
1130 path->rows = baserel->rows;
1132 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1133 cpu_per_tuple = cpu_tuple_cost;
1135 /* Add scanning CPU costs */
1136 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1138 startup_cost += qpqual_cost.startup;
1139 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1140 run_cost += cpu_per_tuple * baserel->tuples;
1142 path->startup_cost = startup_cost;
1143 path->total_cost = startup_cost + run_cost;
1147 * cost_recursive_union
1148 * Determines and returns the cost of performing a recursive union,
1149 * and also the estimated output size.
1151 * We are given Plans for the nonrecursive and recursive terms.
1153 * Note that the arguments and output are Plans, not Paths as in most of
1154 * the rest of this module. That's because we don't bother setting up a
1155 * Path representation for recursive union --- we have only one way to do it.
1158 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1164 /* We probably have decent estimates for the non-recursive term */
1165 startup_cost = nrterm->startup_cost;
1166 total_cost = nrterm->total_cost;
1167 total_rows = nrterm->plan_rows;
1170 * We arbitrarily assume that about 10 recursive iterations will be
1171 * needed, and that we've managed to get a good fix on the cost and output
1172 * size of each one of them. These are mighty shaky assumptions but it's
1173 * hard to see how to do better.
1175 total_cost += 10 * rterm->total_cost;
1176 total_rows += 10 * rterm->plan_rows;
1179 * Also charge cpu_tuple_cost per row to account for the costs of
1180 * manipulating the tuplestores. (We don't worry about possible
1181 * spill-to-disk costs.)
1183 total_cost += cpu_tuple_cost * total_rows;
1185 runion->startup_cost = startup_cost;
1186 runion->total_cost = total_cost;
1187 runion->plan_rows = total_rows;
1188 runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1193 * Determines and returns the cost of sorting a relation, including
1194 * the cost of reading the input data.
1196 * If the total volume of data to sort is less than sort_mem, we will do
1197 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1198 * comparisons for t tuples.
1200 * If the total volume exceeds sort_mem, we switch to a tape-style merge
1201 * algorithm. There will still be about t*log2(t) tuple comparisons in
1202 * total, but we will also need to write and read each tuple once per
1203 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1204 * number of initial runs formed and M is the merge order used by tuplesort.c.
1205 * Since the average initial run should be about twice sort_mem, we have
1206 * disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
1207 * cpu = comparison_cost * t * log2(t)
1209 * If the sort is bounded (i.e., only the first k result tuples are needed)
1210 * and k tuples can fit into sort_mem, we use a heap method that keeps only
1211 * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1213 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1214 * accesses (XXX can't we refine that guess?)
1216 * By default, we charge two operator evals per tuple comparison, which should
1217 * be in the right ballpark in most cases. The caller can tweak this by
1218 * specifying nonzero comparison_cost; typically that's used for any extra
1219 * work that has to be done to prepare the inputs to the comparison operators.
1221 * 'pathkeys' is a list of sort keys
1222 * 'input_cost' is the total cost for reading the input data
1223 * 'tuples' is the number of tuples in the relation
1224 * 'width' is the average tuple width in bytes
1225 * 'comparison_cost' is the extra cost per comparison, if any
1226 * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1227 * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1229 * NOTE: some callers currently pass NIL for pathkeys because they
1230 * can't conveniently supply the sort keys. Since this routine doesn't
1231 * currently do anything with pathkeys anyway, that doesn't matter...
1232 * but if it ever does, it should react gracefully to lack of key data.
1233 * (Actually, the thing we'd most likely be interested in is just the number
1234 * of sort keys, which all callers *could* supply.)
1237 cost_sort(Path *path, PlannerInfo *root,
1238 List *pathkeys, Cost input_cost, double tuples, int width,
1239 Cost comparison_cost, int sort_mem,
1240 double limit_tuples)
1242 Cost startup_cost = input_cost;
1244 double input_bytes = relation_byte_size(tuples, width);
1245 double output_bytes;
1246 double output_tuples;
1247 long sort_mem_bytes = sort_mem * 1024L;
1250 startup_cost += disable_cost;
1252 path->rows = tuples;
1255 * We want to be sure the cost of a sort is never estimated as zero, even
1256 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1261 /* Include the default cost-per-comparison */
1262 comparison_cost += 2.0 * cpu_operator_cost;
1264 /* Do we have a useful LIMIT? */
1265 if (limit_tuples > 0 && limit_tuples < tuples)
1267 output_tuples = limit_tuples;
1268 output_bytes = relation_byte_size(output_tuples, width);
1272 output_tuples = tuples;
1273 output_bytes = input_bytes;
1276 if (output_bytes > sort_mem_bytes)
1279 * We'll have to use a disk-based sort of all the tuples
1281 double npages = ceil(input_bytes / BLCKSZ);
1282 double nruns = (input_bytes / sort_mem_bytes) * 0.5;
1283 double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1285 double npageaccesses;
1290 * Assume about N log2 N comparisons
1292 startup_cost += comparison_cost * tuples * LOG2(tuples);
1296 /* Compute logM(r) as log(r) / log(M) */
1297 if (nruns > mergeorder)
1298 log_runs = ceil(log(nruns) / log(mergeorder));
1301 npageaccesses = 2.0 * npages * log_runs;
1302 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1303 startup_cost += npageaccesses *
1304 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1306 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1309 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1310 * a total number of tuple comparisons of N log2 K; but the constant
1311 * factor is a bit higher than for quicksort. Tweak it so that the
1312 * cost curve is continuous at the crossover point.
1314 startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1318 /* We'll use plain quicksort on all the input tuples */
1319 startup_cost += comparison_cost * tuples * LOG2(tuples);
1323 * Also charge a small amount (arbitrarily set equal to operator cost) per
1324 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1325 * doesn't do qual-checking or projection, so it has less overhead than
1326 * most plan nodes. Note it's correct to use tuples not output_tuples
1327 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1328 * counting the LIMIT otherwise.
1330 run_cost += cpu_operator_cost * tuples;
1332 path->startup_cost = startup_cost;
1333 path->total_cost = startup_cost + run_cost;
1338 * Determines and returns the cost of a MergeAppend node.
1340 * MergeAppend merges several pre-sorted input streams, using a heap that
1341 * at any given instant holds the next tuple from each stream. If there
1342 * are N streams, we need about N*log2(N) tuple comparisons to construct
1343 * the heap at startup, and then for each output tuple, about log2(N)
1344 * comparisons to delete the top heap entry and another log2(N) comparisons
1345 * to insert its successor from the same stream.
1347 * (The effective value of N will drop once some of the input streams are
1348 * exhausted, but it seems unlikely to be worth trying to account for that.)
1350 * The heap is never spilled to disk, since we assume N is not very large.
1351 * So this is much simpler than cost_sort.
1353 * As in cost_sort, we charge two operator evals per tuple comparison.
1355 * 'pathkeys' is a list of sort keys
1356 * 'n_streams' is the number of input streams
1357 * 'input_startup_cost' is the sum of the input streams' startup costs
1358 * 'input_total_cost' is the sum of the input streams' total costs
1359 * 'tuples' is the number of tuples in all the streams
1362 cost_merge_append(Path *path, PlannerInfo *root,
1363 List *pathkeys, int n_streams,
1364 Cost input_startup_cost, Cost input_total_cost,
1367 Cost startup_cost = 0;
1369 Cost comparison_cost;
1376 N = (n_streams < 2) ? 2.0 : (double) n_streams;
1379 /* Assumed cost per tuple comparison */
1380 comparison_cost = 2.0 * cpu_operator_cost;
1382 /* Heap creation cost */
1383 startup_cost += comparison_cost * N * logN;
1385 /* Per-tuple heap maintenance cost */
1386 run_cost += tuples * comparison_cost * 2.0 * logN;
1389 * Also charge a small amount (arbitrarily set equal to operator cost) per
1390 * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1391 * node doesn't do qual-checking or projection, so it has less overhead
1392 * than most plan nodes.
1394 run_cost += cpu_operator_cost * tuples;
1396 path->startup_cost = startup_cost + input_startup_cost;
1397 path->total_cost = startup_cost + run_cost + input_total_cost;
1402 * Determines and returns the cost of materializing a relation, including
1403 * the cost of reading the input data.
1405 * If the total volume of data to materialize exceeds work_mem, we will need
1406 * to write it to disk, so the cost is much higher in that case.
1408 * Note that here we are estimating the costs for the first scan of the
1409 * relation, so the materialization is all overhead --- any savings will
1410 * occur only on rescan, which is estimated in cost_rescan.
1413 cost_material(Path *path,
1414 Cost input_startup_cost, Cost input_total_cost,
1415 double tuples, int width)
1417 Cost startup_cost = input_startup_cost;
1418 Cost run_cost = input_total_cost - input_startup_cost;
1419 double nbytes = relation_byte_size(tuples, width);
1420 long work_mem_bytes = work_mem * 1024L;
1422 path->rows = tuples;
1425 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1426 * reflect bookkeeping overhead. (This rate must be more than what
1427 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1428 * if it is exactly the same then there will be a cost tie between
1429 * nestloop with A outer, materialized B inner and nestloop with B outer,
1430 * materialized A inner. The extra cost ensures we'll prefer
1431 * materializing the smaller rel.) Note that this is normally a good deal
1432 * less than cpu_tuple_cost; which is OK because a Material plan node
1433 * doesn't do qual-checking or projection, so it's got less overhead than
1436 run_cost += 2 * cpu_operator_cost * tuples;
1439 * If we will spill to disk, charge at the rate of seq_page_cost per page.
1440 * This cost is assumed to be evenly spread through the plan run phase,
1441 * which isn't exactly accurate but our cost model doesn't allow for
1442 * nonuniform costs within the run phase.
1444 if (nbytes > work_mem_bytes)
1446 double npages = ceil(nbytes / BLCKSZ);
1448 run_cost += seq_page_cost * npages;
1451 path->startup_cost = startup_cost;
1452 path->total_cost = startup_cost + run_cost;
1457 * Determines and returns the cost of performing an Agg plan node,
1458 * including the cost of its input.
1460 * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
1461 * we are using a hashed Agg node just to do grouping).
1463 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1464 * are for appropriately-sorted input.
1467 cost_agg(Path *path, PlannerInfo *root,
1468 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
1469 int numGroupCols, double numGroups,
1470 Cost input_startup_cost, Cost input_total_cost,
1471 double input_tuples)
1473 double output_tuples;
1476 AggClauseCosts dummy_aggcosts;
1478 /* Use all-zero per-aggregate costs if NULL is passed */
1479 if (aggcosts == NULL)
1481 Assert(aggstrategy == AGG_HASHED);
1482 MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1483 aggcosts = &dummy_aggcosts;
1487 * The transCost.per_tuple component of aggcosts should be charged once
1488 * per input tuple, corresponding to the costs of evaluating the aggregate
1489 * transfns and their input expressions (with any startup cost of course
1490 * charged but once). The finalCost component is charged once per output
1491 * tuple, corresponding to the costs of evaluating the finalfns.
1493 * If we are grouping, we charge an additional cpu_operator_cost per
1494 * grouping column per input tuple for grouping comparisons.
1496 * We will produce a single output tuple if not grouping, and a tuple per
1497 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1499 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1500 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1501 * input path is already sorted appropriately, AGG_SORTED should be
1502 * preferred (since it has no risk of memory overflow). This will happen
1503 * as long as the computed total costs are indeed exactly equal --- but if
1504 * there's roundoff error we might do the wrong thing. So be sure that
1505 * the computations below form the same intermediate values in the same
1508 if (aggstrategy == AGG_PLAIN)
1510 startup_cost = input_total_cost;
1511 startup_cost += aggcosts->transCost.startup;
1512 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1513 startup_cost += aggcosts->finalCost;
1514 /* we aren't grouping */
1515 total_cost = startup_cost + cpu_tuple_cost;
1518 else if (aggstrategy == AGG_SORTED)
1520 /* Here we are able to deliver output on-the-fly */
1521 startup_cost = input_startup_cost;
1522 total_cost = input_total_cost;
1523 /* calcs phrased this way to match HASHED case, see note above */
1524 total_cost += aggcosts->transCost.startup;
1525 total_cost += aggcosts->transCost.per_tuple * input_tuples;
1526 total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1527 total_cost += aggcosts->finalCost * numGroups;
1528 total_cost += cpu_tuple_cost * numGroups;
1529 output_tuples = numGroups;
1533 /* must be AGG_HASHED */
1534 startup_cost = input_total_cost;
1535 startup_cost += aggcosts->transCost.startup;
1536 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1537 startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1538 total_cost = startup_cost;
1539 total_cost += aggcosts->finalCost * numGroups;
1540 total_cost += cpu_tuple_cost * numGroups;
1541 output_tuples = numGroups;
1544 path->rows = output_tuples;
1545 path->startup_cost = startup_cost;
1546 path->total_cost = total_cost;
1551 * Determines and returns the cost of performing a WindowAgg plan node,
1552 * including the cost of its input.
1554 * Input is assumed already properly sorted.
1557 cost_windowagg(Path *path, PlannerInfo *root,
1558 List *windowFuncs, int numPartCols, int numOrderCols,
1559 Cost input_startup_cost, Cost input_total_cost,
1560 double input_tuples)
1566 startup_cost = input_startup_cost;
1567 total_cost = input_total_cost;
1570 * Window functions are assumed to cost their stated execution cost, plus
1571 * the cost of evaluating their input expressions, per tuple. Since they
1572 * may in fact evaluate their inputs at multiple rows during each cycle,
1573 * this could be a drastic underestimate; but without a way to know how
1574 * many rows the window function will fetch, it's hard to do better. In
1575 * any case, it's a good estimate for all the built-in window functions,
1576 * so we'll just do this for now.
1578 foreach(lc, windowFuncs)
1580 WindowFunc *wfunc = (WindowFunc *) lfirst(lc);
1584 Assert(IsA(wfunc, WindowFunc));
1586 wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1588 /* also add the input expressions' cost to per-input-row costs */
1589 cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1590 startup_cost += argcosts.startup;
1591 wfunccost += argcosts.per_tuple;
1593 total_cost += wfunccost * input_tuples;
1597 * We also charge cpu_operator_cost per grouping column per tuple for
1598 * grouping comparisons, plus cpu_tuple_cost per tuple for general
1601 * XXX this neglects costs of spooling the data to disk when it overflows
1602 * work_mem. Sooner or later that should get accounted for.
1604 total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1605 total_cost += cpu_tuple_cost * input_tuples;
1607 path->rows = input_tuples;
1608 path->startup_cost = startup_cost;
1609 path->total_cost = total_cost;
1614 * Determines and returns the cost of performing a Group plan node,
1615 * including the cost of its input.
1617 * Note: caller must ensure that input costs are for appropriately-sorted
1621 cost_group(Path *path, PlannerInfo *root,
1622 int numGroupCols, double numGroups,
1623 Cost input_startup_cost, Cost input_total_cost,
1624 double input_tuples)
1629 startup_cost = input_startup_cost;
1630 total_cost = input_total_cost;
1633 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1634 * all columns get compared at most of the tuples.
1636 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1638 path->rows = numGroups;
1639 path->startup_cost = startup_cost;
1640 path->total_cost = total_cost;
1644 * initial_cost_nestloop
1645 * Preliminary estimate of the cost of a nestloop join path.
1647 * This must quickly produce lower-bound estimates of the path's startup and
1648 * total costs. If we are unable to eliminate the proposed path from
1649 * consideration using the lower bounds, final_cost_nestloop will be called
1650 * to obtain the final estimates.
1652 * The exact division of labor between this function and final_cost_nestloop
1653 * is private to them, and represents a tradeoff between speed of the initial
1654 * estimate and getting a tight lower bound. We choose to not examine the
1655 * join quals here, since that's by far the most expensive part of the
1656 * calculations. The end result is that CPU-cost considerations must be
1657 * left for the second phase.
1659 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
1660 * other data to be used by final_cost_nestloop
1661 * 'jointype' is the type of join to be performed
1662 * 'outer_path' is the outer input to the join
1663 * 'inner_path' is the inner input to the join
1664 * 'sjinfo' is extra info about the join for selectivity estimation
1665 * 'semifactors' contains valid data if jointype is SEMI or ANTI
1668 initial_cost_nestloop(PlannerInfo *root, JoinCostWorkspace *workspace,
1670 Path *outer_path, Path *inner_path,
1671 SpecialJoinInfo *sjinfo,
1672 SemiAntiJoinFactors *semifactors)
1674 Cost startup_cost = 0;
1676 double outer_path_rows = outer_path->rows;
1677 Cost inner_rescan_start_cost;
1678 Cost inner_rescan_total_cost;
1679 Cost inner_run_cost;
1680 Cost inner_rescan_run_cost;
1682 /* estimate costs to rescan the inner relation */
1683 cost_rescan(root, inner_path,
1684 &inner_rescan_start_cost,
1685 &inner_rescan_total_cost);
1687 /* cost of source data */
1690 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1691 * before we can start returning tuples, so the join's startup cost is
1692 * their sum. We'll also pay the inner path's rescan startup cost
1695 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1696 run_cost += outer_path->total_cost - outer_path->startup_cost;
1697 if (outer_path_rows > 1)
1698 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1700 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1701 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1703 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
1705 double outer_matched_rows;
1706 Selectivity inner_scan_frac;
1709 * SEMI or ANTI join: executor will stop after first match.
1711 * For an outer-rel row that has at least one match, we can expect the
1712 * inner scan to stop after a fraction 1/(match_count+1) of the inner
1713 * rows, if the matches are evenly distributed. Since they probably
1714 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1715 * that fraction. (If we used a larger fuzz factor, we'd have to
1716 * clamp inner_scan_frac to at most 1.0; but since match_count is at
1717 * least 1, no such clamp is needed now.)
1719 * A complicating factor is that rescans may be cheaper than first
1720 * scans. If we never scan all the way to the end of the inner rel,
1721 * it might be (depending on the plan type) that we'd never pay the
1722 * whole inner first-scan run cost. However it is difficult to
1723 * estimate whether that will happen, so be conservative and always
1724 * charge the whole first-scan cost once.
1726 run_cost += inner_run_cost;
1728 outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
1729 inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
1731 /* Add inner run cost for additional outer tuples having matches */
1732 if (outer_matched_rows > 1)
1733 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1736 * The cost of processing unmatched rows varies depending on the
1737 * details of the joinclauses, so we leave that part for later.
1740 /* Save private data for final_cost_nestloop */
1741 workspace->outer_matched_rows = outer_matched_rows;
1742 workspace->inner_scan_frac = inner_scan_frac;
1746 /* Normal case; we'll scan whole input rel for each outer row */
1747 run_cost += inner_run_cost;
1748 if (outer_path_rows > 1)
1749 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1752 /* CPU costs left for later */
1754 /* Public result fields */
1755 workspace->startup_cost = startup_cost;
1756 workspace->total_cost = startup_cost + run_cost;
1757 /* Save private data for final_cost_nestloop */
1758 workspace->run_cost = run_cost;
1759 workspace->inner_rescan_run_cost = inner_rescan_run_cost;
1763 * final_cost_nestloop
1764 * Final estimate of the cost and result size of a nestloop join path.
1766 * 'path' is already filled in except for the rows and cost fields
1767 * 'workspace' is the result from initial_cost_nestloop
1768 * 'sjinfo' is extra info about the join for selectivity estimation
1769 * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
1772 final_cost_nestloop(PlannerInfo *root, NestPath *path,
1773 JoinCostWorkspace *workspace,
1774 SpecialJoinInfo *sjinfo,
1775 SemiAntiJoinFactors *semifactors)
1777 Path *outer_path = path->outerjoinpath;
1778 Path *inner_path = path->innerjoinpath;
1779 double outer_path_rows = outer_path->rows;
1780 double inner_path_rows = inner_path->rows;
1781 Cost startup_cost = workspace->startup_cost;
1782 Cost run_cost = workspace->run_cost;
1783 Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
1785 QualCost restrict_qual_cost;
1788 /* Mark the path with the correct row estimate */
1789 if (path->path.param_info)
1790 path->path.rows = path->path.param_info->ppi_rows;
1792 path->path.rows = path->path.parent->rows;
1795 * We could include disable_cost in the preliminary estimate, but that
1796 * would amount to optimizing for the case where the join method is
1797 * disabled, which doesn't seem like the way to bet.
1799 if (!enable_nestloop)
1800 startup_cost += disable_cost;
1802 /* cost of source data */
1804 if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI)
1806 double outer_matched_rows = workspace->outer_matched_rows;
1807 Selectivity inner_scan_frac = workspace->inner_scan_frac;
1810 * SEMI or ANTI join: executor will stop after first match.
1813 /* Compute number of tuples processed (not number emitted!) */
1814 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1817 * For unmatched outer-rel rows, there are two cases. If the inner
1818 * path is an indexscan using all the joinquals as indexquals, then an
1819 * unmatched row results in an indexscan returning no rows, which is
1820 * probably quite cheap. We estimate this case as the same cost to
1821 * return the first tuple of a nonempty scan. Otherwise, the executor
1822 * will have to scan the whole inner rel; not so cheap.
1824 if (has_indexed_join_quals(path))
1826 run_cost += (outer_path_rows - outer_matched_rows) *
1827 inner_rescan_run_cost / inner_path_rows;
1830 * We won't be evaluating any quals at all for these rows, so
1831 * don't add them to ntuples.
1836 run_cost += (outer_path_rows - outer_matched_rows) *
1837 inner_rescan_run_cost;
1838 ntuples += (outer_path_rows - outer_matched_rows) *
1844 /* Normal-case source costs were included in preliminary estimate */
1846 /* Compute number of tuples processed (not number emitted!) */
1847 ntuples = outer_path_rows * inner_path_rows;
1851 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1852 startup_cost += restrict_qual_cost.startup;
1853 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1854 run_cost += cpu_per_tuple * ntuples;
1856 path->path.startup_cost = startup_cost;
1857 path->path.total_cost = startup_cost + run_cost;
1861 * initial_cost_mergejoin
1862 * Preliminary estimate of the cost of a mergejoin path.
1864 * This must quickly produce lower-bound estimates of the path's startup and
1865 * total costs. If we are unable to eliminate the proposed path from
1866 * consideration using the lower bounds, final_cost_mergejoin will be called
1867 * to obtain the final estimates.
1869 * The exact division of labor between this function and final_cost_mergejoin
1870 * is private to them, and represents a tradeoff between speed of the initial
1871 * estimate and getting a tight lower bound. We choose to not examine the
1872 * join quals here, except for obtaining the scan selectivity estimate which
1873 * is really essential (but fortunately, use of caching keeps the cost of
1874 * getting that down to something reasonable).
1875 * We also assume that cost_sort is cheap enough to use here.
1877 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
1878 * other data to be used by final_cost_mergejoin
1879 * 'jointype' is the type of join to be performed
1880 * 'mergeclauses' is the list of joinclauses to be used as merge clauses
1881 * 'outer_path' is the outer input to the join
1882 * 'inner_path' is the inner input to the join
1883 * 'outersortkeys' is the list of sort keys for the outer path
1884 * 'innersortkeys' is the list of sort keys for the inner path
1885 * 'sjinfo' is extra info about the join for selectivity estimation
1887 * Note: outersortkeys and innersortkeys should be NIL if no explicit
1888 * sort is needed because the respective source path is already ordered.
1891 initial_cost_mergejoin(PlannerInfo *root, JoinCostWorkspace *workspace,
1894 Path *outer_path, Path *inner_path,
1895 List *outersortkeys, List *innersortkeys,
1896 SpecialJoinInfo *sjinfo)
1898 Cost startup_cost = 0;
1900 double outer_path_rows = outer_path->rows;
1901 double inner_path_rows = inner_path->rows;
1902 Cost inner_run_cost;
1907 Selectivity outerstartsel,
1911 Path sort_path; /* dummy for result of cost_sort */
1913 /* Protect some assumptions below that rowcounts aren't zero or NaN */
1914 if (outer_path_rows <= 0 || isnan(outer_path_rows))
1915 outer_path_rows = 1;
1916 if (inner_path_rows <= 0 || isnan(inner_path_rows))
1917 inner_path_rows = 1;
1920 * A merge join will stop as soon as it exhausts either input stream
1921 * (unless it's an outer join, in which case the outer side has to be
1922 * scanned all the way anyway). Estimate fraction of the left and right
1923 * inputs that will actually need to be scanned. Likewise, we can
1924 * estimate the number of rows that will be skipped before the first join
1925 * pair is found, which should be factored into startup cost. We use only
1926 * the first (most significant) merge clause for this purpose. Since
1927 * mergejoinscansel() is a fairly expensive computation, we cache the
1928 * results in the merge clause RestrictInfo.
1930 if (mergeclauses && jointype != JOIN_FULL)
1932 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1937 MergeScanSelCache *cache;
1939 /* Get the input pathkeys to determine the sort-order details */
1940 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1941 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1944 opathkey = (PathKey *) linitial(opathkeys);
1945 ipathkey = (PathKey *) linitial(ipathkeys);
1946 /* debugging check */
1947 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1948 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
1949 opathkey->pk_strategy != ipathkey->pk_strategy ||
1950 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1951 elog(ERROR, "left and right pathkeys do not match in mergejoin");
1953 /* Get the selectivity with caching */
1954 cache = cached_scansel(root, firstclause, opathkey);
1956 if (bms_is_subset(firstclause->left_relids,
1957 outer_path->parent->relids))
1959 /* left side of clause is outer */
1960 outerstartsel = cache->leftstartsel;
1961 outerendsel = cache->leftendsel;
1962 innerstartsel = cache->rightstartsel;
1963 innerendsel = cache->rightendsel;
1967 /* left side of clause is inner */
1968 outerstartsel = cache->rightstartsel;
1969 outerendsel = cache->rightendsel;
1970 innerstartsel = cache->leftstartsel;
1971 innerendsel = cache->leftendsel;
1973 if (jointype == JOIN_LEFT ||
1974 jointype == JOIN_ANTI)
1976 outerstartsel = 0.0;
1979 else if (jointype == JOIN_RIGHT)
1981 innerstartsel = 0.0;
1987 /* cope with clauseless or full mergejoin */
1988 outerstartsel = innerstartsel = 0.0;
1989 outerendsel = innerendsel = 1.0;
1993 * Convert selectivities to row counts. We force outer_rows and
1994 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1996 outer_skip_rows = rint(outer_path_rows * outerstartsel);
1997 inner_skip_rows = rint(inner_path_rows * innerstartsel);
1998 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1999 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
2001 Assert(outer_skip_rows <= outer_rows);
2002 Assert(inner_skip_rows <= inner_rows);
2005 * Readjust scan selectivities to account for above rounding. This is
2006 * normally an insignificant effect, but when there are only a few rows in
2007 * the inputs, failing to do this makes for a large percentage error.
2009 outerstartsel = outer_skip_rows / outer_path_rows;
2010 innerstartsel = inner_skip_rows / inner_path_rows;
2011 outerendsel = outer_rows / outer_path_rows;
2012 innerendsel = inner_rows / inner_path_rows;
2014 Assert(outerstartsel <= outerendsel);
2015 Assert(innerstartsel <= innerendsel);
2017 /* cost of source data */
2019 if (outersortkeys) /* do we need to sort outer? */
2021 cost_sort(&sort_path,
2024 outer_path->total_cost,
2026 outer_path->parent->width,
2030 startup_cost += sort_path.startup_cost;
2031 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2033 run_cost += (sort_path.total_cost - sort_path.startup_cost)
2034 * (outerendsel - outerstartsel);
2038 startup_cost += outer_path->startup_cost;
2039 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
2041 run_cost += (outer_path->total_cost - outer_path->startup_cost)
2042 * (outerendsel - outerstartsel);
2045 if (innersortkeys) /* do we need to sort inner? */
2047 cost_sort(&sort_path,
2050 inner_path->total_cost,
2052 inner_path->parent->width,
2056 startup_cost += sort_path.startup_cost;
2057 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2059 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
2060 * (innerendsel - innerstartsel);
2064 startup_cost += inner_path->startup_cost;
2065 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
2067 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
2068 * (innerendsel - innerstartsel);
2072 * We can't yet determine whether rescanning occurs, or whether
2073 * materialization of the inner input should be done. The minimum
2074 * possible inner input cost, regardless of rescan and materialization
2075 * considerations, is inner_run_cost. We include that in
2076 * workspace->total_cost, but not yet in run_cost.
2079 /* CPU costs left for later */
2081 /* Public result fields */
2082 workspace->startup_cost = startup_cost;
2083 workspace->total_cost = startup_cost + run_cost + inner_run_cost;
2084 /* Save private data for final_cost_mergejoin */
2085 workspace->run_cost = run_cost;
2086 workspace->inner_run_cost = inner_run_cost;
2087 workspace->outer_rows = outer_rows;
2088 workspace->inner_rows = inner_rows;
2089 workspace->outer_skip_rows = outer_skip_rows;
2090 workspace->inner_skip_rows = inner_skip_rows;
2094 * final_cost_mergejoin
2095 * Final estimate of the cost and result size of a mergejoin path.
2097 * Unlike other costsize functions, this routine makes one actual decision:
2098 * whether we should materialize the inner path. We do that either because
2099 * the inner path can't support mark/restore, or because it's cheaper to
2100 * use an interposed Material node to handle mark/restore. When the decision
2101 * is cost-based it would be logically cleaner to build and cost two separate
2102 * paths with and without that flag set; but that would require repeating most
2103 * of the cost calculations, which are not all that cheap. Since the choice
2104 * will not affect output pathkeys or startup cost, only total cost, there is
2105 * no possibility of wanting to keep both paths. So it seems best to make
2106 * the decision here and record it in the path's materialize_inner field.
2108 * 'path' is already filled in except for the rows and cost fields and
2110 * 'workspace' is the result from initial_cost_mergejoin
2111 * 'sjinfo' is extra info about the join for selectivity estimation
2114 final_cost_mergejoin(PlannerInfo *root, MergePath *path,
2115 JoinCostWorkspace *workspace,
2116 SpecialJoinInfo *sjinfo)
2118 Path *outer_path = path->jpath.outerjoinpath;
2119 Path *inner_path = path->jpath.innerjoinpath;
2120 double inner_path_rows = inner_path->rows;
2121 List *mergeclauses = path->path_mergeclauses;
2122 List *innersortkeys = path->innersortkeys;
2123 Cost startup_cost = workspace->startup_cost;
2124 Cost run_cost = workspace->run_cost;
2125 Cost inner_run_cost = workspace->inner_run_cost;
2126 double outer_rows = workspace->outer_rows;
2127 double inner_rows = workspace->inner_rows;
2128 double outer_skip_rows = workspace->outer_skip_rows;
2129 double inner_skip_rows = workspace->inner_skip_rows;
2133 QualCost merge_qual_cost;
2134 QualCost qp_qual_cost;
2135 double mergejointuples,
2139 /* Protect some assumptions below that rowcounts aren't zero or NaN */
2140 if (inner_path_rows <= 0 || isnan(inner_path_rows))
2141 inner_path_rows = 1;
2143 /* Mark the path with the correct row estimate */
2144 if (path->jpath.path.param_info)
2145 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2147 path->jpath.path.rows = path->jpath.path.parent->rows;
2150 * We could include disable_cost in the preliminary estimate, but that
2151 * would amount to optimizing for the case where the join method is
2152 * disabled, which doesn't seem like the way to bet.
2154 if (!enable_mergejoin)
2155 startup_cost += disable_cost;
2158 * Compute cost of the mergequals and qpquals (other restriction clauses)
2161 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2162 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2163 qp_qual_cost.startup -= merge_qual_cost.startup;
2164 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2167 * Get approx # tuples passing the mergequals. We use approx_tuple_count
2168 * here because we need an estimate done with JOIN_INNER semantics.
2170 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2173 * When there are equal merge keys in the outer relation, the mergejoin
2174 * must rescan any matching tuples in the inner relation. This means
2175 * re-fetching inner tuples; we have to estimate how often that happens.
2177 * For regular inner and outer joins, the number of re-fetches can be
2178 * estimated approximately as size of merge join output minus size of
2179 * inner relation. Assume that the distinct key values are 1, 2, ..., and
2180 * denote the number of values of each key in the outer relation as m1,
2181 * m2, ...; in the inner relation, n1, n2, ... Then we have
2183 * size of join = m1 * n1 + m2 * n2 + ...
2185 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2186 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2189 * This equation works correctly for outer tuples having no inner match
2190 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2191 * are effectively subtracting those from the number of rescanned tuples,
2192 * when we should not. Can we do better without expensive selectivity
2195 * The whole issue is moot if we are working from a unique-ified outer
2198 if (IsA(outer_path, UniquePath))
2199 rescannedtuples = 0;
2202 rescannedtuples = mergejointuples - inner_path_rows;
2203 /* Must clamp because of possible underestimate */
2204 if (rescannedtuples < 0)
2205 rescannedtuples = 0;
2207 /* We'll inflate various costs this much to account for rescanning */
2208 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
2211 * Decide whether we want to materialize the inner input to shield it from
2212 * mark/restore and performing re-fetches. Our cost model for regular
2213 * re-fetches is that a re-fetch costs the same as an original fetch,
2214 * which is probably an overestimate; but on the other hand we ignore the
2215 * bookkeeping costs of mark/restore. Not clear if it's worth developing
2216 * a more refined model. So we just need to inflate the inner run cost by
2219 bare_inner_cost = inner_run_cost * rescanratio;
2222 * When we interpose a Material node the re-fetch cost is assumed to be
2223 * just cpu_operator_cost per tuple, independently of the underlying
2224 * plan's cost; and we charge an extra cpu_operator_cost per original
2225 * fetch as well. Note that we're assuming the materialize node will
2226 * never spill to disk, since it only has to remember tuples back to the
2227 * last mark. (If there are a huge number of duplicates, our other cost
2228 * factors will make the path so expensive that it probably won't get
2229 * chosen anyway.) So we don't use cost_rescan here.
2231 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
2232 * of the generated Material node.
2234 mat_inner_cost = inner_run_cost +
2235 cpu_operator_cost * inner_path_rows * rescanratio;
2238 * Prefer materializing if it looks cheaper, unless the user has asked to
2239 * suppress materialization.
2241 if (enable_material && mat_inner_cost < bare_inner_cost)
2242 path->materialize_inner = true;
2245 * Even if materializing doesn't look cheaper, we *must* do it if the
2246 * inner path is to be used directly (without sorting) and it doesn't
2247 * support mark/restore.
2249 * Since the inner side must be ordered, and only Sorts and IndexScans can
2250 * create order to begin with, and they both support mark/restore, you
2251 * might think there's no problem --- but you'd be wrong. Nestloop and
2252 * merge joins can *preserve* the order of their inputs, so they can be
2253 * selected as the input of a mergejoin, and they don't support
2254 * mark/restore at present.
2256 * We don't test the value of enable_material here, because
2257 * materialization is required for correctness in this case, and turning
2258 * it off does not entitle us to deliver an invalid plan.
2260 else if (innersortkeys == NIL &&
2261 !ExecSupportsMarkRestore(inner_path->pathtype))
2262 path->materialize_inner = true;
2265 * Also, force materializing if the inner path is to be sorted and the
2266 * sort is expected to spill to disk. This is because the final merge
2267 * pass can be done on-the-fly if it doesn't have to support mark/restore.
2268 * We don't try to adjust the cost estimates for this consideration,
2271 * Since materialization is a performance optimization in this case,
2272 * rather than necessary for correctness, we skip it if enable_material is
2275 else if (enable_material && innersortkeys != NIL &&
2276 relation_byte_size(inner_path_rows, inner_path->parent->width) >
2278 path->materialize_inner = true;
2280 path->materialize_inner = false;
2282 /* Charge the right incremental cost for the chosen case */
2283 if (path->materialize_inner)
2284 run_cost += mat_inner_cost;
2286 run_cost += bare_inner_cost;
2291 * The number of tuple comparisons needed is approximately number of outer
2292 * rows plus number of inner rows plus number of rescanned tuples (can we
2293 * refine this?). At each one, we need to evaluate the mergejoin quals.
2295 startup_cost += merge_qual_cost.startup;
2296 startup_cost += merge_qual_cost.per_tuple *
2297 (outer_skip_rows + inner_skip_rows * rescanratio);
2298 run_cost += merge_qual_cost.per_tuple *
2299 ((outer_rows - outer_skip_rows) +
2300 (inner_rows - inner_skip_rows) * rescanratio);
2303 * For each tuple that gets through the mergejoin proper, we charge
2304 * cpu_tuple_cost plus the cost of evaluating additional restriction
2305 * clauses that are to be applied at the join. (This is pessimistic since
2306 * not all of the quals may get evaluated at each tuple.)
2308 * Note: we could adjust for SEMI/ANTI joins skipping some qual
2309 * evaluations here, but it's probably not worth the trouble.
2311 startup_cost += qp_qual_cost.startup;
2312 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2313 run_cost += cpu_per_tuple * mergejointuples;
2315 path->jpath.path.startup_cost = startup_cost;
2316 path->jpath.path.total_cost = startup_cost + run_cost;
2320 * run mergejoinscansel() with caching
2322 static MergeScanSelCache *
2323 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2325 MergeScanSelCache *cache;
2327 Selectivity leftstartsel,
2331 MemoryContext oldcontext;
2333 /* Do we have this result already? */
2334 foreach(lc, rinfo->scansel_cache)
2336 cache = (MergeScanSelCache *) lfirst(lc);
2337 if (cache->opfamily == pathkey->pk_opfamily &&
2338 cache->collation == pathkey->pk_eclass->ec_collation &&
2339 cache->strategy == pathkey->pk_strategy &&
2340 cache->nulls_first == pathkey->pk_nulls_first)
2344 /* Nope, do the computation */
2345 mergejoinscansel(root,
2346 (Node *) rinfo->clause,
2347 pathkey->pk_opfamily,
2348 pathkey->pk_strategy,
2349 pathkey->pk_nulls_first,
2355 /* Cache the result in suitably long-lived workspace */
2356 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2358 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2359 cache->opfamily = pathkey->pk_opfamily;
2360 cache->collation = pathkey->pk_eclass->ec_collation;
2361 cache->strategy = pathkey->pk_strategy;
2362 cache->nulls_first = pathkey->pk_nulls_first;
2363 cache->leftstartsel = leftstartsel;
2364 cache->leftendsel = leftendsel;
2365 cache->rightstartsel = rightstartsel;
2366 cache->rightendsel = rightendsel;
2368 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2370 MemoryContextSwitchTo(oldcontext);
2376 * initial_cost_hashjoin
2377 * Preliminary estimate of the cost of a hashjoin path.
2379 * This must quickly produce lower-bound estimates of the path's startup and
2380 * total costs. If we are unable to eliminate the proposed path from
2381 * consideration using the lower bounds, final_cost_hashjoin will be called
2382 * to obtain the final estimates.
2384 * The exact division of labor between this function and final_cost_hashjoin
2385 * is private to them, and represents a tradeoff between speed of the initial
2386 * estimate and getting a tight lower bound. We choose to not examine the
2387 * join quals here (other than by counting the number of hash clauses),
2388 * so we can't do much with CPU costs. We do assume that
2389 * ExecChooseHashTableSize is cheap enough to use here.
2391 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
2392 * other data to be used by final_cost_hashjoin
2393 * 'jointype' is the type of join to be performed
2394 * 'hashclauses' is the list of joinclauses to be used as hash clauses
2395 * 'outer_path' is the outer input to the join
2396 * 'inner_path' is the inner input to the join
2397 * 'sjinfo' is extra info about the join for selectivity estimation
2398 * 'semifactors' contains valid data if jointype is SEMI or ANTI
2401 initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
2404 Path *outer_path, Path *inner_path,
2405 SpecialJoinInfo *sjinfo,
2406 SemiAntiJoinFactors *semifactors)
2408 Cost startup_cost = 0;
2410 double outer_path_rows = outer_path->rows;
2411 double inner_path_rows = inner_path->rows;
2412 int num_hashclauses = list_length(hashclauses);
2417 /* cost of source data */
2418 startup_cost += outer_path->startup_cost;
2419 run_cost += outer_path->total_cost - outer_path->startup_cost;
2420 startup_cost += inner_path->total_cost;
2423 * Cost of computing hash function: must do it once per input tuple. We
2424 * charge one cpu_operator_cost for each column's hash function. Also,
2425 * tack on one cpu_tuple_cost per inner row, to model the costs of
2426 * inserting the row into the hashtable.
2428 * XXX when a hashclause is more complex than a single operator, we really
2429 * should charge the extra eval costs of the left or right side, as
2430 * appropriate, here. This seems more work than it's worth at the moment.
2432 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2434 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2437 * Get hash table size that executor would use for inner relation.
2439 * XXX for the moment, always assume that skew optimization will be
2440 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2441 * trying to determine that for sure.
2443 * XXX at some point it might be interesting to try to account for skew
2444 * optimization in the cost estimate, but for now, we don't.
2446 ExecChooseHashTableSize(inner_path_rows,
2447 inner_path->parent->width,
2454 * If inner relation is too big then we will need to "batch" the join,
2455 * which implies writing and reading most of the tuples to disk an extra
2456 * time. Charge seq_page_cost per page, since the I/O should be nice and
2457 * sequential. Writing the inner rel counts as startup cost, all the rest
2462 double outerpages = page_size(outer_path_rows,
2463 outer_path->parent->width);
2464 double innerpages = page_size(inner_path_rows,
2465 inner_path->parent->width);
2467 startup_cost += seq_page_cost * innerpages;
2468 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2471 /* CPU costs left for later */
2473 /* Public result fields */
2474 workspace->startup_cost = startup_cost;
2475 workspace->total_cost = startup_cost + run_cost;
2476 /* Save private data for final_cost_hashjoin */
2477 workspace->run_cost = run_cost;
2478 workspace->numbuckets = numbuckets;
2479 workspace->numbatches = numbatches;
2483 * final_cost_hashjoin
2484 * Final estimate of the cost and result size of a hashjoin path.
2486 * Note: the numbatches estimate is also saved into 'path' for use later
2488 * 'path' is already filled in except for the rows and cost fields and
2490 * 'workspace' is the result from initial_cost_hashjoin
2491 * 'sjinfo' is extra info about the join for selectivity estimation
2492 * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
2495 final_cost_hashjoin(PlannerInfo *root, HashPath *path,
2496 JoinCostWorkspace *workspace,
2497 SpecialJoinInfo *sjinfo,
2498 SemiAntiJoinFactors *semifactors)
2500 Path *outer_path = path->jpath.outerjoinpath;
2501 Path *inner_path = path->jpath.innerjoinpath;
2502 double outer_path_rows = outer_path->rows;
2503 double inner_path_rows = inner_path->rows;
2504 List *hashclauses = path->path_hashclauses;
2505 Cost startup_cost = workspace->startup_cost;
2506 Cost run_cost = workspace->run_cost;
2507 int numbuckets = workspace->numbuckets;
2508 int numbatches = workspace->numbatches;
2510 QualCost hash_qual_cost;
2511 QualCost qp_qual_cost;
2512 double hashjointuples;
2513 double virtualbuckets;
2514 Selectivity innerbucketsize;
2517 /* Mark the path with the correct row estimate */
2518 if (path->jpath.path.param_info)
2519 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2521 path->jpath.path.rows = path->jpath.path.parent->rows;
2524 * We could include disable_cost in the preliminary estimate, but that
2525 * would amount to optimizing for the case where the join method is
2526 * disabled, which doesn't seem like the way to bet.
2528 if (!enable_hashjoin)
2529 startup_cost += disable_cost;
2531 /* mark the path with estimated # of batches */
2532 path->num_batches = numbatches;
2534 /* and compute the number of "virtual" buckets in the whole join */
2535 virtualbuckets = (double) numbuckets *(double) numbatches;
2538 * Determine bucketsize fraction for inner relation. We use the smallest
2539 * bucketsize estimated for any individual hashclause; this is undoubtedly
2542 * BUT: if inner relation has been unique-ified, we can assume it's good
2543 * for hashing. This is important both because it's the right answer, and
2544 * because we avoid contaminating the cache with a value that's wrong for
2545 * non-unique-ified paths.
2547 if (IsA(inner_path, UniquePath))
2548 innerbucketsize = 1.0 / virtualbuckets;
2551 innerbucketsize = 1.0;
2552 foreach(hcl, hashclauses)
2554 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2555 Selectivity thisbucketsize;
2557 Assert(IsA(restrictinfo, RestrictInfo));
2560 * First we have to figure out which side of the hashjoin clause
2561 * is the inner side.
2563 * Since we tend to visit the same clauses over and over when
2564 * planning a large query, we cache the bucketsize estimate in the
2565 * RestrictInfo node to avoid repeated lookups of statistics.
2567 if (bms_is_subset(restrictinfo->right_relids,
2568 inner_path->parent->relids))
2570 /* righthand side is inner */
2571 thisbucketsize = restrictinfo->right_bucketsize;
2572 if (thisbucketsize < 0)
2574 /* not cached yet */
2576 estimate_hash_bucketsize(root,
2577 get_rightop(restrictinfo->clause),
2579 restrictinfo->right_bucketsize = thisbucketsize;
2584 Assert(bms_is_subset(restrictinfo->left_relids,
2585 inner_path->parent->relids));
2586 /* lefthand side is inner */
2587 thisbucketsize = restrictinfo->left_bucketsize;
2588 if (thisbucketsize < 0)
2590 /* not cached yet */
2592 estimate_hash_bucketsize(root,
2593 get_leftop(restrictinfo->clause),
2595 restrictinfo->left_bucketsize = thisbucketsize;
2599 if (innerbucketsize > thisbucketsize)
2600 innerbucketsize = thisbucketsize;
2605 * Compute cost of the hashquals and qpquals (other restriction clauses)
2608 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2609 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2610 qp_qual_cost.startup -= hash_qual_cost.startup;
2611 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2615 if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI)
2617 double outer_matched_rows;
2618 Selectivity inner_scan_frac;
2621 * SEMI or ANTI join: executor will stop after first match.
2623 * For an outer-rel row that has at least one match, we can expect the
2624 * bucket scan to stop after a fraction 1/(match_count+1) of the
2625 * bucket's rows, if the matches are evenly distributed. Since they
2626 * probably aren't quite evenly distributed, we apply a fuzz factor of
2627 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2628 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2629 * at least 1, no such clamp is needed now.)
2631 outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2632 inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2634 startup_cost += hash_qual_cost.startup;
2635 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2636 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2639 * For unmatched outer-rel rows, the picture is quite a lot different.
2640 * In the first place, there is no reason to assume that these rows
2641 * preferentially hit heavily-populated buckets; instead assume they
2642 * are uncorrelated with the inner distribution and so they see an
2643 * average bucket size of inner_path_rows / virtualbuckets. In the
2644 * second place, it seems likely that they will have few if any exact
2645 * hash-code matches and so very few of the tuples in the bucket will
2646 * actually require eval of the hash quals. We don't have any good
2647 * way to estimate how many will, but for the moment assume that the
2648 * effective cost per bucket entry is one-tenth what it is for
2651 run_cost += hash_qual_cost.per_tuple *
2652 (outer_path_rows - outer_matched_rows) *
2653 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2655 /* Get # of tuples that will pass the basic join */
2656 if (path->jpath.jointype == JOIN_SEMI)
2657 hashjointuples = outer_matched_rows;
2659 hashjointuples = outer_path_rows - outer_matched_rows;
2664 * The number of tuple comparisons needed is the number of outer
2665 * tuples times the typical number of tuples in a hash bucket, which
2666 * is the inner relation size times its bucketsize fraction. At each
2667 * one, we need to evaluate the hashjoin quals. But actually,
2668 * charging the full qual eval cost at each tuple is pessimistic,
2669 * since we don't evaluate the quals unless the hash values match
2670 * exactly. For lack of a better idea, halve the cost estimate to
2673 startup_cost += hash_qual_cost.startup;
2674 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2675 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2678 * Get approx # tuples passing the hashquals. We use
2679 * approx_tuple_count here because we need an estimate done with
2680 * JOIN_INNER semantics.
2682 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2686 * For each tuple that gets through the hashjoin proper, we charge
2687 * cpu_tuple_cost plus the cost of evaluating additional restriction
2688 * clauses that are to be applied at the join. (This is pessimistic since
2689 * not all of the quals may get evaluated at each tuple.)
2691 startup_cost += qp_qual_cost.startup;
2692 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2693 run_cost += cpu_per_tuple * hashjointuples;
2695 path->jpath.path.startup_cost = startup_cost;
2696 path->jpath.path.total_cost = startup_cost + run_cost;
2702 * Figure the costs for a SubPlan (or initplan).
2704 * Note: we could dig the subplan's Plan out of the root list, but in practice
2705 * all callers have it handy already, so we make them pass it.
2708 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2712 /* Figure any cost for evaluating the testexpr */
2713 cost_qual_eval(&sp_cost,
2714 make_ands_implicit((Expr *) subplan->testexpr),
2717 if (subplan->useHashTable)
2720 * If we are using a hash table for the subquery outputs, then the
2721 * cost of evaluating the query is a one-time cost. We charge one
2722 * cpu_operator_cost per tuple for the work of loading the hashtable,
2725 sp_cost.startup += plan->total_cost +
2726 cpu_operator_cost * plan->plan_rows;
2729 * The per-tuple costs include the cost of evaluating the lefthand
2730 * expressions, plus the cost of probing the hashtable. We already
2731 * accounted for the lefthand expressions as part of the testexpr, and
2732 * will also have counted one cpu_operator_cost for each comparison
2733 * operator. That is probably too low for the probing cost, but it's
2734 * hard to make a better estimate, so live with it for now.
2740 * Otherwise we will be rescanning the subplan output on each
2741 * evaluation. We need to estimate how much of the output we will
2742 * actually need to scan. NOTE: this logic should agree with the
2743 * tuple_fraction estimates used by make_subplan() in
2746 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2748 if (subplan->subLinkType == EXISTS_SUBLINK)
2750 /* we only need to fetch 1 tuple */
2751 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2753 else if (subplan->subLinkType == ALL_SUBLINK ||
2754 subplan->subLinkType == ANY_SUBLINK)
2756 /* assume we need 50% of the tuples */
2757 sp_cost.per_tuple += 0.50 * plan_run_cost;
2758 /* also charge a cpu_operator_cost per row examined */
2759 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2763 /* assume we need all tuples */
2764 sp_cost.per_tuple += plan_run_cost;
2768 * Also account for subplan's startup cost. If the subplan is
2769 * uncorrelated or undirect correlated, AND its topmost node is one
2770 * that materializes its output, assume that we'll only need to pay
2771 * its startup cost once; otherwise assume we pay the startup cost
2774 if (subplan->parParam == NIL &&
2775 ExecMaterializesOutput(nodeTag(plan)))
2776 sp_cost.startup += plan->startup_cost;
2778 sp_cost.per_tuple += plan->startup_cost;
2781 subplan->startup_cost = sp_cost.startup;
2782 subplan->per_call_cost = sp_cost.per_tuple;
2788 * Given a finished Path, estimate the costs of rescanning it after
2789 * having done so the first time. For some Path types a rescan is
2790 * cheaper than an original scan (if no parameters change), and this
2791 * function embodies knowledge about that. The default is to return
2792 * the same costs stored in the Path. (Note that the cost estimates
2793 * actually stored in Paths are always for first scans.)
2795 * This function is not currently intended to model effects such as rescans
2796 * being cheaper due to disk block caching; what we are concerned with is
2797 * plan types wherein the executor caches results explicitly, or doesn't
2798 * redo startup calculations, etc.
2801 cost_rescan(PlannerInfo *root, Path *path,
2802 Cost *rescan_startup_cost, /* output parameters */
2803 Cost *rescan_total_cost)
2805 switch (path->pathtype)
2807 case T_FunctionScan:
2810 * Currently, nodeFunctionscan.c always executes the function to
2811 * completion before returning any rows, and caches the results in
2812 * a tuplestore. So the function eval cost is all startup cost
2813 * and isn't paid over again on rescans. However, all run costs
2814 * will be paid over again.
2816 *rescan_startup_cost = 0;
2817 *rescan_total_cost = path->total_cost - path->startup_cost;
2822 * Assume that all of the startup cost represents hash table
2823 * building, which we won't have to do over.
2825 *rescan_startup_cost = 0;
2826 *rescan_total_cost = path->total_cost - path->startup_cost;
2829 case T_WorkTableScan:
2832 * These plan types materialize their final result in a
2833 * tuplestore or tuplesort object. So the rescan cost is only
2834 * cpu_tuple_cost per tuple, unless the result is large enough
2837 Cost run_cost = cpu_tuple_cost * path->rows;
2838 double nbytes = relation_byte_size(path->rows,
2839 path->parent->width);
2840 long work_mem_bytes = work_mem * 1024L;
2842 if (nbytes > work_mem_bytes)
2844 /* It will spill, so account for re-read cost */
2845 double npages = ceil(nbytes / BLCKSZ);
2847 run_cost += seq_page_cost * npages;
2849 *rescan_startup_cost = 0;
2850 *rescan_total_cost = run_cost;
2857 * These plan types not only materialize their results, but do
2858 * not implement qual filtering or projection. So they are
2859 * even cheaper to rescan than the ones above. We charge only
2860 * cpu_operator_cost per tuple. (Note: keep that in sync with
2861 * the run_cost charge in cost_sort, and also see comments in
2862 * cost_material before you change it.)
2864 Cost run_cost = cpu_operator_cost * path->rows;
2865 double nbytes = relation_byte_size(path->rows,
2866 path->parent->width);
2867 long work_mem_bytes = work_mem * 1024L;
2869 if (nbytes > work_mem_bytes)
2871 /* It will spill, so account for re-read cost */
2872 double npages = ceil(nbytes / BLCKSZ);
2874 run_cost += seq_page_cost * npages;
2876 *rescan_startup_cost = 0;
2877 *rescan_total_cost = run_cost;
2881 *rescan_startup_cost = path->startup_cost;
2882 *rescan_total_cost = path->total_cost;
2890 * Estimate the CPU costs of evaluating a WHERE clause.
2891 * The input can be either an implicitly-ANDed list of boolean
2892 * expressions, or a list of RestrictInfo nodes. (The latter is
2893 * preferred since it allows caching of the results.)
2894 * The result includes both a one-time (startup) component,
2895 * and a per-evaluation component.
2898 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2900 cost_qual_eval_context context;
2903 context.root = root;
2904 context.total.startup = 0;
2905 context.total.per_tuple = 0;
2907 /* We don't charge any cost for the implicit ANDing at top level ... */
2911 Node *qual = (Node *) lfirst(l);
2913 cost_qual_eval_walker(qual, &context);
2916 *cost = context.total;
2920 * cost_qual_eval_node
2921 * As above, for a single RestrictInfo or expression.
2924 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2926 cost_qual_eval_context context;
2928 context.root = root;
2929 context.total.startup = 0;
2930 context.total.per_tuple = 0;
2932 cost_qual_eval_walker(qual, &context);
2934 *cost = context.total;
2938 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2944 * RestrictInfo nodes contain an eval_cost field reserved for this
2945 * routine's use, so that it's not necessary to evaluate the qual clause's
2946 * cost more than once. If the clause's cost hasn't been computed yet,
2947 * the field's startup value will contain -1.
2949 if (IsA(node, RestrictInfo))
2951 RestrictInfo *rinfo = (RestrictInfo *) node;
2953 if (rinfo->eval_cost.startup < 0)
2955 cost_qual_eval_context locContext;
2957 locContext.root = context->root;
2958 locContext.total.startup = 0;
2959 locContext.total.per_tuple = 0;
2962 * For an OR clause, recurse into the marked-up tree so that we
2963 * set the eval_cost for contained RestrictInfos too.
2965 if (rinfo->orclause)
2966 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2968 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2971 * If the RestrictInfo is marked pseudoconstant, it will be tested
2972 * only once, so treat its cost as all startup cost.
2974 if (rinfo->pseudoconstant)
2976 /* count one execution during startup */
2977 locContext.total.startup += locContext.total.per_tuple;
2978 locContext.total.per_tuple = 0;
2980 rinfo->eval_cost = locContext.total;
2982 context->total.startup += rinfo->eval_cost.startup;
2983 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2984 /* do NOT recurse into children */
2989 * For each operator or function node in the given tree, we charge the
2990 * estimated execution cost given by pg_proc.procost (remember to multiply
2991 * this by cpu_operator_cost).
2993 * Vars and Consts are charged zero, and so are boolean operators (AND,
2994 * OR, NOT). Simplistic, but a lot better than no model at all.
2996 * Should we try to account for the possibility of short-circuit
2997 * evaluation of AND/OR? Probably *not*, because that would make the
2998 * results depend on the clause ordering, and we are not in any position
2999 * to expect that the current ordering of the clauses is the one that's
3000 * going to end up being used. The above per-RestrictInfo caching would
3001 * not mix well with trying to re-order clauses anyway.
3003 * Another issue that is entirely ignored here is that if a set-returning
3004 * function is below top level in the tree, the functions/operators above
3005 * it will need to be evaluated multiple times. In practical use, such
3006 * cases arise so seldom as to not be worth the added complexity needed;
3007 * moreover, since our rowcount estimates for functions tend to be pretty
3008 * phony, the results would also be pretty phony.
3010 if (IsA(node, FuncExpr))
3012 context->total.per_tuple +=
3013 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
3015 else if (IsA(node, OpExpr) ||
3016 IsA(node, DistinctExpr) ||
3017 IsA(node, NullIfExpr))
3019 /* rely on struct equivalence to treat these all alike */
3020 set_opfuncid((OpExpr *) node);
3021 context->total.per_tuple +=
3022 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
3024 else if (IsA(node, ScalarArrayOpExpr))
3027 * Estimate that the operator will be applied to about half of the
3028 * array elements before the answer is determined.
3030 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
3031 Node *arraynode = (Node *) lsecond(saop->args);
3033 set_sa_opfuncid(saop);
3034 context->total.per_tuple += get_func_cost(saop->opfuncid) *
3035 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
3037 else if (IsA(node, Aggref) ||
3038 IsA(node, WindowFunc))
3041 * Aggref and WindowFunc nodes are (and should be) treated like Vars,
3042 * ie, zero execution cost in the current model, because they behave
3043 * essentially like Vars in execQual.c. We disregard the costs of
3044 * their input expressions for the same reason. The actual execution
3045 * costs of the aggregate/window functions and their arguments have to
3046 * be factored into plan-node-specific costing of the Agg or WindowAgg
3049 return false; /* don't recurse into children */
3051 else if (IsA(node, CoerceViaIO))
3053 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3058 /* check the result type's input function */
3059 getTypeInputInfo(iocoerce->resulttype,
3060 &iofunc, &typioparam);
3061 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3062 /* check the input type's output function */
3063 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
3064 &iofunc, &typisvarlena);
3065 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3067 else if (IsA(node, ArrayCoerceExpr))
3069 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3070 Node *arraynode = (Node *) acoerce->arg;
3072 if (OidIsValid(acoerce->elemfuncid))
3073 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
3074 cpu_operator_cost * estimate_array_length(arraynode);
3076 else if (IsA(node, RowCompareExpr))
3078 /* Conservatively assume we will check all the columns */
3079 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3082 foreach(lc, rcexpr->opnos)
3084 Oid opid = lfirst_oid(lc);
3086 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
3090 else if (IsA(node, CurrentOfExpr))
3092 /* Report high cost to prevent selection of anything but TID scan */
3093 context->total.startup += disable_cost;
3095 else if (IsA(node, SubLink))
3097 /* This routine should not be applied to un-planned expressions */
3098 elog(ERROR, "cannot handle unplanned sub-select");
3100 else if (IsA(node, SubPlan))
3103 * A subplan node in an expression typically indicates that the
3104 * subplan will be executed on each evaluation, so charge accordingly.
3105 * (Sub-selects that can be executed as InitPlans have already been
3106 * removed from the expression.)
3108 SubPlan *subplan = (SubPlan *) node;
3110 context->total.startup += subplan->startup_cost;
3111 context->total.per_tuple += subplan->per_call_cost;
3114 * We don't want to recurse into the testexpr, because it was already
3115 * counted in the SubPlan node's costs. So we're done.
3119 else if (IsA(node, AlternativeSubPlan))
3122 * Arbitrarily use the first alternative plan for costing. (We should
3123 * certainly only include one alternative, and we don't yet have
3124 * enough information to know which one the executor is most likely to
3127 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
3129 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
3133 /* recurse into children */
3134 return expression_tree_walker(node, cost_qual_eval_walker,
3139 * get_restriction_qual_cost
3140 * Compute evaluation costs of a baserel's restriction quals, plus any
3141 * movable join quals that have been pushed down to the scan.
3142 * Results are returned into *qpqual_cost.
3144 * This is a convenience subroutine that works for seqscans and other cases
3145 * where all the given quals will be evaluated the hard way. It's not useful
3146 * for cost_index(), for example, where the index machinery takes care of
3147 * some of the quals. We assume baserestrictcost was previously set by
3148 * set_baserel_size_estimates().
3151 get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
3152 ParamPathInfo *param_info,
3153 QualCost *qpqual_cost)
3157 /* Include costs of pushed-down clauses */
3158 cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
3160 qpqual_cost->startup += baserel->baserestrictcost.startup;
3161 qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
3164 *qpqual_cost = baserel->baserestrictcost;
3169 * compute_semi_anti_join_factors
3170 * Estimate how much of the inner input a SEMI or ANTI join
3171 * can be expected to scan.
3173 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
3174 * inner rows as soon as it finds a match to the current outer row.
3175 * We should therefore adjust some of the cost components for this effect.
3176 * This function computes some estimates needed for these adjustments.
3177 * These estimates will be the same regardless of the particular paths used
3178 * for the outer and inner relation, so we compute these once and then pass
3179 * them to all the join cost estimation functions.
3182 * outerrel: outer relation under consideration
3183 * innerrel: inner relation under consideration
3184 * jointype: must be JOIN_SEMI or JOIN_ANTI
3185 * sjinfo: SpecialJoinInfo relevant to this join
3186 * restrictlist: join quals
3187 * Output parameters:
3188 * *semifactors is filled in (see relation.h for field definitions)
3191 compute_semi_anti_join_factors(PlannerInfo *root,
3192 RelOptInfo *outerrel,
3193 RelOptInfo *innerrel,
3195 SpecialJoinInfo *sjinfo,
3197 SemiAntiJoinFactors *semifactors)
3201 Selectivity avgmatch;
3202 SpecialJoinInfo norm_sjinfo;
3206 /* Should only be called in these cases */
3207 Assert(jointype == JOIN_SEMI || jointype == JOIN_ANTI);
3210 * In an ANTI join, we must ignore clauses that are "pushed down", since
3211 * those won't affect the match logic. In a SEMI join, we do not
3212 * distinguish joinquals from "pushed down" quals, so just use the whole
3213 * restrictinfo list.
3215 if (jointype == JOIN_ANTI)
3218 foreach(l, restrictlist)
3220 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3222 Assert(IsA(rinfo, RestrictInfo));
3223 if (!rinfo->is_pushed_down)
3224 joinquals = lappend(joinquals, rinfo);
3228 joinquals = restrictlist;
3231 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
3233 jselec = clauselist_selectivity(root,
3240 * Also get the normal inner-join selectivity of the join clauses.
3242 norm_sjinfo.type = T_SpecialJoinInfo;
3243 norm_sjinfo.min_lefthand = outerrel->relids;
3244 norm_sjinfo.min_righthand = innerrel->relids;
3245 norm_sjinfo.syn_lefthand = outerrel->relids;
3246 norm_sjinfo.syn_righthand = innerrel->relids;
3247 norm_sjinfo.jointype = JOIN_INNER;
3248 /* we don't bother trying to make the remaining fields valid */
3249 norm_sjinfo.lhs_strict = false;
3250 norm_sjinfo.delay_upper_joins = false;
3251 norm_sjinfo.join_quals = NIL;
3253 nselec = clauselist_selectivity(root,
3259 /* Avoid leaking a lot of ListCells */
3260 if (jointype == JOIN_ANTI)
3261 list_free(joinquals);
3264 * jselec can be interpreted as the fraction of outer-rel rows that have
3265 * any matches (this is true for both SEMI and ANTI cases). And nselec is
3266 * the fraction of the Cartesian product that matches. So, the average
3267 * number of matches for each outer-rel row that has at least one match is
3268 * nselec * inner_rows / jselec.
3270 * Note: it is correct to use the inner rel's "rows" count here, even
3271 * though we might later be considering a parameterized inner path with
3272 * fewer rows. This is because we have included all the join clauses in
3273 * the selectivity estimate.
3275 if (jselec > 0) /* protect against zero divide */
3277 avgmatch = nselec * innerrel->rows / jselec;
3278 /* Clamp to sane range */
3279 avgmatch = Max(1.0, avgmatch);
3284 semifactors->outer_match_frac = jselec;
3285 semifactors->match_count = avgmatch;
3289 * has_indexed_join_quals
3290 * Check whether all the joinquals of a nestloop join are used as
3291 * inner index quals.
3293 * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
3294 * indexscan) that uses all the joinquals as indexquals, we can assume that an
3295 * unmatched outer tuple is cheap to process, whereas otherwise it's probably
3299 has_indexed_join_quals(NestPath *joinpath)
3301 Relids joinrelids = joinpath->path.parent->relids;
3302 Path *innerpath = joinpath->innerjoinpath;
3307 /* If join still has quals to evaluate, it's not fast */
3308 if (joinpath->joinrestrictinfo != NIL)
3310 /* Nor if the inner path isn't parameterized at all */
3311 if (innerpath->param_info == NULL)
3314 /* Find the indexclauses list for the inner scan */
3315 switch (innerpath->pathtype)
3318 case T_IndexOnlyScan:
3319 indexclauses = ((IndexPath *) innerpath)->indexclauses;
3321 case T_BitmapHeapScan:
3323 /* Accept only a simple bitmap scan, not AND/OR cases */
3324 Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
3326 if (IsA(bmqual, IndexPath))
3327 indexclauses = ((IndexPath *) bmqual)->indexclauses;
3335 * If it's not a simple indexscan, it probably doesn't run quickly
3336 * for zero rows out, even if it's a parameterized path using all
3343 * Examine the inner path's param clauses. Any that are from the outer
3344 * path must be found in the indexclauses list, either exactly or in an
3345 * equivalent form generated by equivclass.c. Also, we must find at least
3346 * one such clause, else it's a clauseless join which isn't fast.
3349 foreach(lc, innerpath->param_info->ppi_clauses)
3351 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3353 if (join_clause_is_movable_into(rinfo,
3354 innerpath->parent->relids,
3357 if (!(list_member_ptr(indexclauses, rinfo) ||
3358 is_redundant_derived_clause(rinfo, indexclauses)))
3368 * approx_tuple_count
3369 * Quick-and-dirty estimation of the number of join rows passing
3370 * a set of qual conditions.
3372 * The quals can be either an implicitly-ANDed list of boolean expressions,
3373 * or a list of RestrictInfo nodes (typically the latter).
3375 * We intentionally compute the selectivity under JOIN_INNER rules, even
3376 * if it's some type of outer join. This is appropriate because we are
3377 * trying to figure out how many tuples pass the initial merge or hash
3380 * This is quick-and-dirty because we bypass clauselist_selectivity, and
3381 * simply multiply the independent clause selectivities together. Now
3382 * clauselist_selectivity often can't do any better than that anyhow, but
3383 * for some situations (such as range constraints) it is smarter. However,
3384 * we can't effectively cache the results of clauselist_selectivity, whereas
3385 * the individual clause selectivities can be and are cached.
3387 * Since we are only using the results to estimate how many potential
3388 * output tuples are generated and passed through qpqual checking, it
3389 * seems OK to live with the approximation.
3392 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
3395 double outer_tuples = path->outerjoinpath->rows;
3396 double inner_tuples = path->innerjoinpath->rows;
3397 SpecialJoinInfo sjinfo;
3398 Selectivity selec = 1.0;
3402 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
3404 sjinfo.type = T_SpecialJoinInfo;
3405 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
3406 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
3407 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
3408 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
3409 sjinfo.jointype = JOIN_INNER;
3410 /* we don't bother trying to make the remaining fields valid */
3411 sjinfo.lhs_strict = false;
3412 sjinfo.delay_upper_joins = false;
3413 sjinfo.join_quals = NIL;
3415 /* Get the approximate selectivity */
3418 Node *qual = (Node *) lfirst(l);
3420 /* Note that clause_selectivity will be able to cache its result */
3421 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
3424 /* Apply it to the input relation sizes */
3425 tuples = selec * outer_tuples * inner_tuples;
3427 return clamp_row_est(tuples);
3432 * set_baserel_size_estimates
3433 * Set the size estimates for the given base relation.
3435 * The rel's targetlist and restrictinfo list must have been constructed
3436 * already, and rel->tuples must be set.
3438 * We set the following fields of the rel node:
3439 * rows: the estimated number of output tuples (after applying
3440 * restriction clauses).
3441 * width: the estimated average output tuple width in bytes.
3442 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
3445 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3449 /* Should only be applied to base relations */
3450 Assert(rel->relid > 0);
3452 nrows = rel->tuples *
3453 clauselist_selectivity(root,
3454 rel->baserestrictinfo,
3459 rel->rows = clamp_row_est(nrows);
3461 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3463 set_rel_width(root, rel);
3467 * get_parameterized_baserel_size
3468 * Make a size estimate for a parameterized scan of a base relation.
3470 * 'param_clauses' lists the additional join clauses to be used.
3472 * set_baserel_size_estimates must have been applied already.
3475 get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel,
3476 List *param_clauses)
3482 * Estimate the number of rows returned by the parameterized scan, knowing
3483 * that it will apply all the extra join clauses as well as the rel's own
3484 * restriction clauses. Note that we force the clauses to be treated as
3485 * non-join clauses during selectivity estimation.
3487 allclauses = list_concat(list_copy(param_clauses),
3488 rel->baserestrictinfo);
3489 nrows = rel->tuples *
3490 clauselist_selectivity(root,
3492 rel->relid, /* do not use 0! */
3495 nrows = clamp_row_est(nrows);
3496 /* For safety, make sure result is not more than the base estimate */
3497 if (nrows > rel->rows)
3503 * set_joinrel_size_estimates
3504 * Set the size estimates for the given join relation.
3506 * The rel's targetlist must have been constructed already, and a
3507 * restriction clause list that matches the given component rels must
3510 * Since there is more than one way to make a joinrel for more than two
3511 * base relations, the results we get here could depend on which component
3512 * rel pair is provided. In theory we should get the same answers no matter
3513 * which pair is provided; in practice, since the selectivity estimation
3514 * routines don't handle all cases equally well, we might not. But there's
3515 * not much to be done about it. (Would it make sense to repeat the
3516 * calculations for each pair of input rels that's encountered, and somehow
3517 * average the results? Probably way more trouble than it's worth, and
3518 * anyway we must keep the rowcount estimate the same for all paths for the
3521 * We set only the rows field here. The width field was already set by
3522 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3525 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3526 RelOptInfo *outer_rel,
3527 RelOptInfo *inner_rel,
3528 SpecialJoinInfo *sjinfo,
3531 rel->rows = calc_joinrel_size_estimate(root,
3539 * get_parameterized_joinrel_size
3540 * Make a size estimate for a parameterized scan of a join relation.
3542 * 'rel' is the joinrel under consideration.
3543 * 'outer_rows', 'inner_rows' are the sizes of the (probably also
3544 * parameterized) join inputs under consideration.
3545 * 'sjinfo' is any SpecialJoinInfo relevant to this join.
3546 * 'restrict_clauses' lists the join clauses that need to be applied at the
3547 * join node (including any movable clauses that were moved down to this join,
3548 * and not including any movable clauses that were pushed down into the
3551 * set_joinrel_size_estimates must have been applied already.
3554 get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel,
3557 SpecialJoinInfo *sjinfo,
3558 List *restrict_clauses)
3563 * Estimate the number of rows returned by the parameterized join as the
3564 * sizes of the input paths times the selectivity of the clauses that have
3565 * ended up at this join node.
3567 * As with set_joinrel_size_estimates, the rowcount estimate could depend
3568 * on the pair of input paths provided, though ideally we'd get the same
3569 * estimate for any pair with the same parameterization.
3571 nrows = calc_joinrel_size_estimate(root,
3576 /* For safety, make sure result is not more than the base estimate */
3577 if (nrows > rel->rows)
3583 * calc_joinrel_size_estimate
3584 * Workhorse for set_joinrel_size_estimates and
3585 * get_parameterized_joinrel_size.
3588 calc_joinrel_size_estimate(PlannerInfo *root,
3591 SpecialJoinInfo *sjinfo,
3594 JoinType jointype = sjinfo->jointype;
3600 * Compute joinclause selectivity. Note that we are only considering
3601 * clauses that become restriction clauses at this join level; we are not
3602 * double-counting them because they were not considered in estimating the
3603 * sizes of the component rels.
3605 * For an outer join, we have to distinguish the selectivity of the join's
3606 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3607 * down". For inner joins we just count them all as joinclauses.
3609 if (IS_OUTER_JOIN(jointype))
3611 List *joinquals = NIL;
3612 List *pushedquals = NIL;
3615 /* Grovel through the clauses to separate into two lists */
3616 foreach(l, restrictlist)
3618 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3620 Assert(IsA(rinfo, RestrictInfo));
3621 if (rinfo->is_pushed_down)
3622 pushedquals = lappend(pushedquals, rinfo);
3624 joinquals = lappend(joinquals, rinfo);
3627 /* Get the separate selectivities */
3628 jselec = clauselist_selectivity(root,
3633 pselec = clauselist_selectivity(root,
3639 /* Avoid leaking a lot of ListCells */
3640 list_free(joinquals);
3641 list_free(pushedquals);
3645 jselec = clauselist_selectivity(root,
3650 pselec = 0.0; /* not used, keep compiler quiet */
3654 * Basically, we multiply size of Cartesian product by selectivity.
3656 * If we are doing an outer join, take that into account: the joinqual
3657 * selectivity has to be clamped using the knowledge that the output must
3658 * be at least as large as the non-nullable input. However, any
3659 * pushed-down quals are applied after the outer join, so their
3660 * selectivity applies fully.
3662 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3663 * of LHS rows that have matches, and we apply that straightforwardly.
3668 nrows = outer_rows * inner_rows * jselec;
3671 nrows = outer_rows * inner_rows * jselec;
3672 if (nrows < outer_rows)
3677 nrows = outer_rows * inner_rows * jselec;
3678 if (nrows < outer_rows)
3680 if (nrows < inner_rows)
3685 nrows = outer_rows * jselec;
3686 /* pselec not used */
3689 nrows = outer_rows * (1.0 - jselec);
3693 /* other values not expected here */
3694 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3695 nrows = 0; /* keep compiler quiet */
3699 return clamp_row_est(nrows);
3703 * set_subquery_size_estimates
3704 * Set the size estimates for a base relation that is a subquery.
3706 * The rel's targetlist and restrictinfo list must have been constructed
3707 * already, and the plan for the subquery must have been completed.
3708 * We look at the subquery's plan and PlannerInfo to extract data.
3710 * We set the same fields as set_baserel_size_estimates.
3713 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3715 PlannerInfo *subroot = rel->subroot;
3716 RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
3719 /* Should only be applied to base relations that are subqueries */
3720 Assert(rel->relid > 0);
3721 rte = planner_rt_fetch(rel->relid, root);
3722 Assert(rte->rtekind == RTE_SUBQUERY);
3724 /* Copy raw number of output rows from subplan */
3725 rel->tuples = rel->subplan->plan_rows;
3728 * Compute per-output-column width estimates by examining the subquery's
3729 * targetlist. For any output that is a plain Var, get the width estimate
3730 * that was made while planning the subquery. Otherwise, we leave it to
3731 * set_rel_width to fill in a datatype-based default estimate.
3733 foreach(lc, subroot->parse->targetList)
3735 TargetEntry *te = (TargetEntry *) lfirst(lc);
3736 Node *texpr = (Node *) te->expr;
3737 int32 item_width = 0;
3739 Assert(IsA(te, TargetEntry));
3740 /* junk columns aren't visible to upper query */
3745 * The subquery could be an expansion of a view that's had columns
3746 * added to it since the current query was parsed, so that there are
3747 * non-junk tlist columns in it that don't correspond to any column
3748 * visible at our query level. Ignore such columns.
3750 if (te->resno < rel->min_attr || te->resno > rel->max_attr)
3754 * XXX This currently doesn't work for subqueries containing set
3755 * operations, because the Vars in their tlists are bogus references
3756 * to the first leaf subquery, which wouldn't give the right answer
3757 * even if we could still get to its PlannerInfo.
3759 * Also, the subquery could be an appendrel for which all branches are
3760 * known empty due to constraint exclusion, in which case
3761 * set_append_rel_pathlist will have left the attr_widths set to zero.
3763 * In either case, we just leave the width estimate zero until
3764 * set_rel_width fixes it.
3766 if (IsA(texpr, Var) &&
3767 subroot->parse->setOperations == NULL)
3769 Var *var = (Var *) texpr;
3770 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3772 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3774 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3777 /* Now estimate number of output rows, etc */
3778 set_baserel_size_estimates(root, rel);
3782 * set_function_size_estimates
3783 * Set the size estimates for a base relation that is a function call.
3785 * The rel's targetlist and restrictinfo list must have been constructed
3788 * We set the same fields as set_baserel_size_estimates.
3791 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3795 /* Should only be applied to base relations that are functions */
3796 Assert(rel->relid > 0);
3797 rte = planner_rt_fetch(rel->relid, root);
3798 Assert(rte->rtekind == RTE_FUNCTION);
3800 /* Estimate number of rows the function itself will return */
3801 rel->tuples = expression_returns_set_rows(rte->funcexpr);
3803 /* Now estimate number of output rows, etc */
3804 set_baserel_size_estimates(root, rel);
3808 * set_values_size_estimates
3809 * Set the size estimates for a base relation that is a values list.
3811 * The rel's targetlist and restrictinfo list must have been constructed
3814 * We set the same fields as set_baserel_size_estimates.
3817 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3821 /* Should only be applied to base relations that are values lists */
3822 Assert(rel->relid > 0);
3823 rte = planner_rt_fetch(rel->relid, root);
3824 Assert(rte->rtekind == RTE_VALUES);
3827 * Estimate number of rows the values list will return. We know this
3828 * precisely based on the list length (well, barring set-returning
3829 * functions in list items, but that's a refinement not catered for
3830 * anywhere else either).
3832 rel->tuples = list_length(rte->values_lists);
3834 /* Now estimate number of output rows, etc */
3835 set_baserel_size_estimates(root, rel);
3839 * set_cte_size_estimates
3840 * Set the size estimates for a base relation that is a CTE reference.
3842 * The rel's targetlist and restrictinfo list must have been constructed
3843 * already, and we need the completed plan for the CTE (if a regular CTE)
3844 * or the non-recursive term (if a self-reference).
3846 * We set the same fields as set_baserel_size_estimates.
3849 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3853 /* Should only be applied to base relations that are CTE references */
3854 Assert(rel->relid > 0);
3855 rte = planner_rt_fetch(rel->relid, root);
3856 Assert(rte->rtekind == RTE_CTE);
3858 if (rte->self_reference)
3861 * In a self-reference, arbitrarily assume the average worktable size
3862 * is about 10 times the nonrecursive term's size.
3864 rel->tuples = 10 * cteplan->plan_rows;
3868 /* Otherwise just believe the CTE plan's output estimate */
3869 rel->tuples = cteplan->plan_rows;
3872 /* Now estimate number of output rows, etc */
3873 set_baserel_size_estimates(root, rel);
3877 * set_foreign_size_estimates
3878 * Set the size estimates for a base relation that is a foreign table.
3880 * There is not a whole lot that we can do here; the foreign-data wrapper
3881 * is responsible for producing useful estimates. We can do a decent job
3882 * of estimating baserestrictcost, so we set that, and we also set up width
3883 * using what will be purely datatype-driven estimates from the targetlist.
3884 * There is no way to do anything sane with the rows value, so we just put
3885 * a default estimate and hope that the wrapper can improve on it. The
3886 * wrapper's GetForeignRelSize function will be called momentarily.
3888 * The rel's targetlist and restrictinfo list must have been constructed
3892 set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3894 /* Should only be applied to base relations */
3895 Assert(rel->relid > 0);
3897 rel->rows = 1000; /* entirely bogus default estimate */
3899 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3901 set_rel_width(root, rel);
3907 * Set the estimated output width of a base relation.
3909 * The estimated output width is the sum of the per-attribute width estimates
3910 * for the actually-referenced columns, plus any PHVs or other expressions
3911 * that have to be calculated at this relation. This is the amount of data
3912 * we'd need to pass upwards in case of a sort, hash, etc.
3914 * NB: this works best on plain relations because it prefers to look at
3915 * real Vars. For subqueries, set_subquery_size_estimates will already have
3916 * copied up whatever per-column estimates were made within the subquery,
3917 * and for other types of rels there isn't much we can do anyway. We fall
3918 * back on (fairly stupid) datatype-based width estimates if we can't get
3919 * any better number.
3921 * The per-attribute width estimates are cached for possible re-use while
3922 * building join relations.
3925 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3927 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3928 int32 tuple_width = 0;
3929 bool have_wholerow_var = false;
3932 foreach(lc, rel->reltargetlist)
3934 Node *node = (Node *) lfirst(lc);
3937 * Ordinarily, a Var in a rel's reltargetlist must belong to that rel;
3938 * but there are corner cases involving LATERAL references in
3939 * appendrel members where that isn't so (see set_append_rel_size()).
3940 * If the Var has the wrong varno, fall through to the generic case
3941 * (it doesn't seem worth the trouble to be any smarter).
3943 if (IsA(node, Var) &&
3944 ((Var *) node)->varno == rel->relid)
3946 Var *var = (Var *) node;
3950 Assert(var->varattno >= rel->min_attr);
3951 Assert(var->varattno <= rel->max_attr);
3953 ndx = var->varattno - rel->min_attr;
3956 * If it's a whole-row Var, we'll deal with it below after we have
3957 * already cached as many attr widths as possible.
3959 if (var->varattno == 0)
3961 have_wholerow_var = true;
3966 * The width may have been cached already (especially if it's a
3967 * subquery), so don't duplicate effort.
3969 if (rel->attr_widths[ndx] > 0)
3971 tuple_width += rel->attr_widths[ndx];
3975 /* Try to get column width from statistics */
3976 if (reloid != InvalidOid && var->varattno > 0)
3978 item_width = get_attavgwidth(reloid, var->varattno);
3981 rel->attr_widths[ndx] = item_width;
3982 tuple_width += item_width;
3988 * Not a plain relation, or can't find statistics for it. Estimate
3989 * using just the type info.
3991 item_width = get_typavgwidth(var->vartype, var->vartypmod);
3992 Assert(item_width > 0);
3993 rel->attr_widths[ndx] = item_width;
3994 tuple_width += item_width;
3996 else if (IsA(node, PlaceHolderVar))
3998 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3999 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv, false);
4001 tuple_width += phinfo->ph_width;
4006 * We could be looking at an expression pulled up from a subquery,
4007 * or a ROW() representing a whole-row child Var, etc. Do what we
4008 * can using the expression type information.
4012 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
4013 Assert(item_width > 0);
4014 tuple_width += item_width;
4019 * If we have a whole-row reference, estimate its width as the sum of
4020 * per-column widths plus sizeof(HeapTupleHeaderData).
4022 if (have_wholerow_var)
4024 int32 wholerow_width = sizeof(HeapTupleHeaderData);
4026 if (reloid != InvalidOid)
4028 /* Real relation, so estimate true tuple width */
4029 wholerow_width += get_relation_data_width(reloid,
4030 rel->attr_widths - rel->min_attr);
4034 /* Do what we can with info for a phony rel */
4037 for (i = 1; i <= rel->max_attr; i++)
4038 wholerow_width += rel->attr_widths[i - rel->min_attr];
4041 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
4044 * Include the whole-row Var as part of the output tuple. Yes, that
4045 * really is what happens at runtime.
4047 tuple_width += wholerow_width;
4050 Assert(tuple_width >= 0);
4051 rel->width = tuple_width;
4055 * relation_byte_size
4056 * Estimate the storage space in bytes for a given number of tuples
4057 * of a given width (size in bytes).
4060 relation_byte_size(double tuples, int width)
4062 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
4067 * Returns an estimate of the number of pages covered by a given
4068 * number of tuples of a given width (size in bytes).
4071 page_size(double tuples, int width)
4073 return ceil(relation_byte_size(tuples, width) / BLCKSZ);