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/guc.h"
91 #include "utils/lsyscache.h"
92 #include "utils/selfuncs.h"
93 #include "utils/spccache.h"
94 #include "utils/tuplesort.h"
97 #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 = -1;
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 set_default_effective_cache_size(void)
463 * If the value of effective_cache_size is -1, use the preferred
466 if (effective_cache_size == -1)
470 snprintf(buf, sizeof(buf), "%d", NBuffers * DEFAULT_EFFECTIVE_CACHE_SIZE_MULTI);
471 SetConfigOption("effective_cache_size", buf, PGC_POSTMASTER, PGC_S_OVERRIDE);
473 Assert(effective_cache_size > 0);
477 * GUC check_hook for effective_cache_size
480 check_effective_cache_size(int *newval, void **extra, GucSource source)
483 * -1 indicates a request for auto-tune.
488 * If we haven't yet changed the boot_val default of -1, just let it
489 * be. We'll fix it in index_pages_fetched
491 if (effective_cache_size == -1)
494 /* Otherwise, substitute the auto-tune value */
495 *newval = NBuffers * DEFAULT_EFFECTIVE_CACHE_SIZE_MULTI;
506 * index_pages_fetched
507 * Estimate the number of pages actually fetched after accounting for
510 * We use an approximation proposed by Mackert and Lohman, "Index Scans
511 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
512 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
513 * The Mackert and Lohman approximation is that the number of pages
516 * min(2TNs/(2T+Ns), T) when T <= b
517 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
518 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
520 * T = # pages in table
521 * N = # tuples in table
522 * s = selectivity = fraction of table to be scanned
523 * b = # buffer pages available (we include kernel space here)
525 * We assume that effective_cache_size is the total number of buffer pages
526 * available for the whole query, and pro-rate that space across all the
527 * tables in the query and the index currently under consideration. (This
528 * ignores space needed for other indexes used by the query, but since we
529 * don't know which indexes will get used, we can't estimate that very well;
530 * and in any case counting all the tables may well be an overestimate, since
531 * depending on the join plan not all the tables may be scanned concurrently.)
533 * The product Ns is the number of tuples fetched; we pass in that
534 * product rather than calculating it here. "pages" is the number of pages
535 * in the object under consideration (either an index or a table).
536 * "index_pages" is the amount to add to the total table space, which was
537 * computed for us by query_planner.
539 * Caller is expected to have ensured that tuples_fetched is greater than zero
540 * and rounded to integer (see clamp_row_est). The result will likewise be
541 * greater than zero and integral.
544 index_pages_fetched(double tuples_fetched, BlockNumber pages,
545 double index_pages, PlannerInfo *root)
547 double pages_fetched;
552 /* T is # pages in table, but don't allow it to be zero */
553 T = (pages > 1) ? (double) pages : 1.0;
555 /* Compute number of pages assumed to be competing for cache space */
556 total_pages = root->total_table_pages + index_pages;
557 total_pages = Max(total_pages, 1.0);
558 Assert(T <= total_pages);
560 /* b is pro-rated share of effective_cache_size */
561 b = (double) effective_cache_size *T / total_pages;
563 /* force it positive and integral */
569 /* This part is the Mackert and Lohman formula */
573 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
574 if (pages_fetched >= T)
577 pages_fetched = ceil(pages_fetched);
583 lim = (2.0 * T * b) / (2.0 * T - b);
584 if (tuples_fetched <= lim)
587 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
592 b + (tuples_fetched - lim) * (T - b) / T;
594 pages_fetched = ceil(pages_fetched);
596 return pages_fetched;
600 * get_indexpath_pages
601 * Determine the total size of the indexes used in a bitmap index path.
603 * Note: if the same index is used more than once in a bitmap tree, we will
604 * count it multiple times, which perhaps is the wrong thing ... but it's
605 * not completely clear, and detecting duplicates is difficult, so ignore it
609 get_indexpath_pages(Path *bitmapqual)
614 if (IsA(bitmapqual, BitmapAndPath))
616 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
618 foreach(l, apath->bitmapquals)
620 result += get_indexpath_pages((Path *) lfirst(l));
623 else if (IsA(bitmapqual, BitmapOrPath))
625 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
627 foreach(l, opath->bitmapquals)
629 result += get_indexpath_pages((Path *) lfirst(l));
632 else if (IsA(bitmapqual, IndexPath))
634 IndexPath *ipath = (IndexPath *) bitmapqual;
636 result = (double) ipath->indexinfo->pages;
639 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
645 * cost_bitmap_heap_scan
646 * Determines and returns the cost of scanning a relation using a bitmap
647 * index-then-heap plan.
649 * 'baserel' is the relation to be scanned
650 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
651 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
652 * 'loop_count' is the number of repetitions of the indexscan to factor into
653 * estimates of caching behavior
655 * Note: the component IndexPaths in bitmapqual should have been costed
656 * using the same loop_count.
659 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
660 ParamPathInfo *param_info,
661 Path *bitmapqual, double loop_count)
663 Cost startup_cost = 0;
666 Selectivity indexSelectivity;
667 QualCost qpqual_cost;
670 double tuples_fetched;
671 double pages_fetched;
672 double spc_seq_page_cost,
673 spc_random_page_cost;
676 /* Should only be applied to base relations */
677 Assert(IsA(baserel, RelOptInfo));
678 Assert(baserel->relid > 0);
679 Assert(baserel->rtekind == RTE_RELATION);
681 /* Mark the path with the correct row estimate */
683 path->rows = param_info->ppi_rows;
685 path->rows = baserel->rows;
687 if (!enable_bitmapscan)
688 startup_cost += disable_cost;
691 * Fetch total cost of obtaining the bitmap, as well as its total
694 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
696 startup_cost += indexTotalCost;
698 /* Fetch estimated page costs for tablespace containing table. */
699 get_tablespace_page_costs(baserel->reltablespace,
700 &spc_random_page_cost,
704 * Estimate number of main-table pages fetched.
706 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
708 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
713 * For repeated bitmap scans, scale up the number of tuples fetched in
714 * the Mackert and Lohman formula by the number of scans, so that we
715 * estimate the number of pages fetched by all the scans. Then
716 * pro-rate for one scan.
718 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
720 get_indexpath_pages(bitmapqual),
722 pages_fetched /= loop_count;
727 * For a single scan, the number of heap pages that need to be fetched
728 * is the same as the Mackert and Lohman formula for the case T <= b
729 * (ie, no re-reads needed).
731 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
733 if (pages_fetched >= T)
736 pages_fetched = ceil(pages_fetched);
739 * For small numbers of pages we should charge spc_random_page_cost
740 * apiece, while if nearly all the table's pages are being read, it's more
741 * appropriate to charge spc_seq_page_cost apiece. The effect is
742 * nonlinear, too. For lack of a better idea, interpolate like this to
743 * determine the cost per page.
745 if (pages_fetched >= 2.0)
746 cost_per_page = spc_random_page_cost -
747 (spc_random_page_cost - spc_seq_page_cost)
748 * sqrt(pages_fetched / T);
750 cost_per_page = spc_random_page_cost;
752 run_cost += pages_fetched * cost_per_page;
755 * Estimate CPU costs per tuple.
757 * Often the indexquals don't need to be rechecked at each tuple ... but
758 * not always, especially not if there are enough tuples involved that the
759 * bitmaps become lossy. For the moment, just assume they will be
760 * rechecked always. This means we charge the full freight for all the
763 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
765 startup_cost += qpqual_cost.startup;
766 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
768 run_cost += cpu_per_tuple * tuples_fetched;
770 path->startup_cost = startup_cost;
771 path->total_cost = startup_cost + run_cost;
775 * cost_bitmap_tree_node
776 * Extract cost and selectivity from a bitmap tree node (index/and/or)
779 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
781 if (IsA(path, IndexPath))
783 *cost = ((IndexPath *) path)->indextotalcost;
784 *selec = ((IndexPath *) path)->indexselectivity;
787 * Charge a small amount per retrieved tuple to reflect the costs of
788 * manipulating the bitmap. This is mostly to make sure that a bitmap
789 * scan doesn't look to be the same cost as an indexscan to retrieve a
792 *cost += 0.1 * cpu_operator_cost * path->rows;
794 else if (IsA(path, BitmapAndPath))
796 *cost = path->total_cost;
797 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
799 else if (IsA(path, BitmapOrPath))
801 *cost = path->total_cost;
802 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
806 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
807 *cost = *selec = 0; /* keep compiler quiet */
812 * cost_bitmap_and_node
813 * Estimate the cost of a BitmapAnd node
815 * Note that this considers only the costs of index scanning and bitmap
816 * creation, not the eventual heap access. In that sense the object isn't
817 * truly a Path, but it has enough path-like properties (costs in particular)
818 * to warrant treating it as one. We don't bother to set the path rows field,
822 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
829 * We estimate AND selectivity on the assumption that the inputs are
830 * independent. This is probably often wrong, but we don't have the info
833 * The runtime cost of the BitmapAnd itself is estimated at 100x
834 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
835 * definitely too simplistic?
839 foreach(l, path->bitmapquals)
841 Path *subpath = (Path *) lfirst(l);
843 Selectivity subselec;
845 cost_bitmap_tree_node(subpath, &subCost, &subselec);
849 totalCost += subCost;
850 if (l != list_head(path->bitmapquals))
851 totalCost += 100.0 * cpu_operator_cost;
853 path->bitmapselectivity = selec;
854 path->path.rows = 0; /* per above, not used */
855 path->path.startup_cost = totalCost;
856 path->path.total_cost = totalCost;
860 * cost_bitmap_or_node
861 * Estimate the cost of a BitmapOr node
863 * See comments for cost_bitmap_and_node.
866 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
873 * We estimate OR selectivity on the assumption that the inputs are
874 * non-overlapping, since that's often the case in "x IN (list)" type
875 * situations. Of course, we clamp to 1.0 at the end.
877 * The runtime cost of the BitmapOr itself is estimated at 100x
878 * cpu_operator_cost for each tbm_union needed. Probably too small,
879 * definitely too simplistic? We are aware that the tbm_unions are
880 * optimized out when the inputs are BitmapIndexScans.
884 foreach(l, path->bitmapquals)
886 Path *subpath = (Path *) lfirst(l);
888 Selectivity subselec;
890 cost_bitmap_tree_node(subpath, &subCost, &subselec);
894 totalCost += subCost;
895 if (l != list_head(path->bitmapquals) &&
896 !IsA(subpath, IndexPath))
897 totalCost += 100.0 * cpu_operator_cost;
899 path->bitmapselectivity = Min(selec, 1.0);
900 path->path.rows = 0; /* per above, not used */
901 path->path.startup_cost = totalCost;
902 path->path.total_cost = totalCost;
907 * Determines and returns the cost of scanning a relation using TIDs.
909 * 'baserel' is the relation to be scanned
910 * 'tidquals' is the list of TID-checkable quals
911 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
914 cost_tidscan(Path *path, PlannerInfo *root,
915 RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
917 Cost startup_cost = 0;
919 bool isCurrentOf = false;
920 QualCost qpqual_cost;
922 QualCost tid_qual_cost;
925 double spc_random_page_cost;
927 /* Should only be applied to base relations */
928 Assert(baserel->relid > 0);
929 Assert(baserel->rtekind == RTE_RELATION);
931 /* Mark the path with the correct row estimate */
933 path->rows = param_info->ppi_rows;
935 path->rows = baserel->rows;
937 /* Count how many tuples we expect to retrieve */
941 if (IsA(lfirst(l), ScalarArrayOpExpr))
943 /* Each element of the array yields 1 tuple */
944 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
945 Node *arraynode = (Node *) lsecond(saop->args);
947 ntuples += estimate_array_length(arraynode);
949 else if (IsA(lfirst(l), CurrentOfExpr))
951 /* CURRENT OF yields 1 tuple */
957 /* It's just CTID = something, count 1 tuple */
963 * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
964 * understands how to do it correctly. Therefore, honor enable_tidscan
965 * only when CURRENT OF isn't present. Also note that cost_qual_eval
966 * counts a CurrentOfExpr as having startup cost disable_cost, which we
967 * subtract off here; that's to prevent other plan types such as seqscan
972 Assert(baserel->baserestrictcost.startup >= disable_cost);
973 startup_cost -= disable_cost;
975 else if (!enable_tidscan)
976 startup_cost += disable_cost;
979 * The TID qual expressions will be computed once, any other baserestrict
980 * quals once per retrived tuple.
982 cost_qual_eval(&tid_qual_cost, tidquals, root);
984 /* fetch estimated page cost for tablespace containing table */
985 get_tablespace_page_costs(baserel->reltablespace,
986 &spc_random_page_cost,
989 /* disk costs --- assume each tuple on a different page */
990 run_cost += spc_random_page_cost * ntuples;
992 /* Add scanning CPU costs */
993 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
995 /* XXX currently we assume TID quals are a subset of qpquals */
996 startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
997 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
998 tid_qual_cost.per_tuple;
999 run_cost += cpu_per_tuple * ntuples;
1001 path->startup_cost = startup_cost;
1002 path->total_cost = startup_cost + run_cost;
1007 * Determines and returns the cost of scanning a subquery RTE.
1009 * 'baserel' is the relation to be scanned
1010 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1013 cost_subqueryscan(Path *path, PlannerInfo *root,
1014 RelOptInfo *baserel, ParamPathInfo *param_info)
1018 QualCost qpqual_cost;
1021 /* Should only be applied to base relations that are subqueries */
1022 Assert(baserel->relid > 0);
1023 Assert(baserel->rtekind == RTE_SUBQUERY);
1025 /* Mark the path with the correct row estimate */
1027 path->rows = param_info->ppi_rows;
1029 path->rows = baserel->rows;
1032 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1033 * any restriction clauses that will be attached to the SubqueryScan node,
1034 * plus cpu_tuple_cost to account for selection and projection overhead.
1036 path->startup_cost = baserel->subplan->startup_cost;
1037 path->total_cost = baserel->subplan->total_cost;
1039 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1041 startup_cost = qpqual_cost.startup;
1042 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1043 run_cost = cpu_per_tuple * baserel->tuples;
1045 path->startup_cost += startup_cost;
1046 path->total_cost += startup_cost + run_cost;
1051 * Determines and returns the cost of scanning a function RTE.
1053 * 'baserel' is the relation to be scanned
1054 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1057 cost_functionscan(Path *path, PlannerInfo *root,
1058 RelOptInfo *baserel, ParamPathInfo *param_info)
1060 Cost startup_cost = 0;
1062 QualCost qpqual_cost;
1067 /* Should only be applied to base relations that are functions */
1068 Assert(baserel->relid > 0);
1069 rte = planner_rt_fetch(baserel->relid, root);
1070 Assert(rte->rtekind == RTE_FUNCTION);
1072 /* Mark the path with the correct row estimate */
1074 path->rows = param_info->ppi_rows;
1076 path->rows = baserel->rows;
1079 * Estimate costs of executing the function expression.
1081 * Currently, nodeFunctionscan.c always executes the function to
1082 * completion before returning any rows, and caches the results in a
1083 * tuplestore. So the function eval cost is all startup cost, and per-row
1084 * costs are minimal.
1086 * XXX in principle we ought to charge tuplestore spill costs if the
1087 * number of rows is large. However, given how phony our rowcount
1088 * estimates for functions tend to be, there's not a lot of point in that
1089 * refinement right now.
1091 cost_qual_eval_node(&exprcost, rte->funcexpr, root);
1093 startup_cost += exprcost.startup + exprcost.per_tuple;
1095 /* Add scanning CPU costs */
1096 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1098 startup_cost += qpqual_cost.startup;
1099 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1100 run_cost += cpu_per_tuple * baserel->tuples;
1102 path->startup_cost = startup_cost;
1103 path->total_cost = startup_cost + run_cost;
1108 * Determines and returns the cost of scanning a VALUES RTE.
1110 * 'baserel' is the relation to be scanned
1111 * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1114 cost_valuesscan(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 values lists */
1123 Assert(baserel->relid > 0);
1124 Assert(baserel->rtekind == RTE_VALUES);
1126 /* Mark the path with the correct row estimate */
1128 path->rows = param_info->ppi_rows;
1130 path->rows = baserel->rows;
1133 * For now, estimate list evaluation cost at one operator eval per list
1134 * (probably pretty bogus, but is it worth being smarter?)
1136 cpu_per_tuple = cpu_operator_cost;
1138 /* Add scanning CPU costs */
1139 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1141 startup_cost += qpqual_cost.startup;
1142 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1143 run_cost += cpu_per_tuple * baserel->tuples;
1145 path->startup_cost = startup_cost;
1146 path->total_cost = startup_cost + run_cost;
1151 * Determines and returns the cost of scanning a CTE RTE.
1153 * Note: this is used for both self-reference and regular CTEs; the
1154 * possible cost differences are below the threshold of what we could
1155 * estimate accurately anyway. Note that the costs of evaluating the
1156 * referenced CTE query are added into the final plan as initplan costs,
1157 * and should NOT be counted here.
1160 cost_ctescan(Path *path, PlannerInfo *root,
1161 RelOptInfo *baserel, ParamPathInfo *param_info)
1163 Cost startup_cost = 0;
1165 QualCost qpqual_cost;
1168 /* Should only be applied to base relations that are CTEs */
1169 Assert(baserel->relid > 0);
1170 Assert(baserel->rtekind == RTE_CTE);
1172 /* Mark the path with the correct row estimate */
1174 path->rows = param_info->ppi_rows;
1176 path->rows = baserel->rows;
1178 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1179 cpu_per_tuple = cpu_tuple_cost;
1181 /* Add scanning CPU costs */
1182 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1184 startup_cost += qpqual_cost.startup;
1185 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1186 run_cost += cpu_per_tuple * baserel->tuples;
1188 path->startup_cost = startup_cost;
1189 path->total_cost = startup_cost + run_cost;
1193 * cost_recursive_union
1194 * Determines and returns the cost of performing a recursive union,
1195 * and also the estimated output size.
1197 * We are given Plans for the nonrecursive and recursive terms.
1199 * Note that the arguments and output are Plans, not Paths as in most of
1200 * the rest of this module. That's because we don't bother setting up a
1201 * Path representation for recursive union --- we have only one way to do it.
1204 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1210 /* We probably have decent estimates for the non-recursive term */
1211 startup_cost = nrterm->startup_cost;
1212 total_cost = nrterm->total_cost;
1213 total_rows = nrterm->plan_rows;
1216 * We arbitrarily assume that about 10 recursive iterations will be
1217 * needed, and that we've managed to get a good fix on the cost and output
1218 * size of each one of them. These are mighty shaky assumptions but it's
1219 * hard to see how to do better.
1221 total_cost += 10 * rterm->total_cost;
1222 total_rows += 10 * rterm->plan_rows;
1225 * Also charge cpu_tuple_cost per row to account for the costs of
1226 * manipulating the tuplestores. (We don't worry about possible
1227 * spill-to-disk costs.)
1229 total_cost += cpu_tuple_cost * total_rows;
1231 runion->startup_cost = startup_cost;
1232 runion->total_cost = total_cost;
1233 runion->plan_rows = total_rows;
1234 runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1239 * Determines and returns the cost of sorting a relation, including
1240 * the cost of reading the input data.
1242 * If the total volume of data to sort is less than sort_mem, we will do
1243 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1244 * comparisons for t tuples.
1246 * If the total volume exceeds sort_mem, we switch to a tape-style merge
1247 * algorithm. There will still be about t*log2(t) tuple comparisons in
1248 * total, but we will also need to write and read each tuple once per
1249 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1250 * number of initial runs formed and M is the merge order used by tuplesort.c.
1251 * Since the average initial run should be about twice sort_mem, we have
1252 * disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
1253 * cpu = comparison_cost * t * log2(t)
1255 * If the sort is bounded (i.e., only the first k result tuples are needed)
1256 * and k tuples can fit into sort_mem, we use a heap method that keeps only
1257 * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1259 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1260 * accesses (XXX can't we refine that guess?)
1262 * By default, we charge two operator evals per tuple comparison, which should
1263 * be in the right ballpark in most cases. The caller can tweak this by
1264 * specifying nonzero comparison_cost; typically that's used for any extra
1265 * work that has to be done to prepare the inputs to the comparison operators.
1267 * 'pathkeys' is a list of sort keys
1268 * 'input_cost' is the total cost for reading the input data
1269 * 'tuples' is the number of tuples in the relation
1270 * 'width' is the average tuple width in bytes
1271 * 'comparison_cost' is the extra cost per comparison, if any
1272 * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1273 * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1275 * NOTE: some callers currently pass NIL for pathkeys because they
1276 * can't conveniently supply the sort keys. Since this routine doesn't
1277 * currently do anything with pathkeys anyway, that doesn't matter...
1278 * but if it ever does, it should react gracefully to lack of key data.
1279 * (Actually, the thing we'd most likely be interested in is just the number
1280 * of sort keys, which all callers *could* supply.)
1283 cost_sort(Path *path, PlannerInfo *root,
1284 List *pathkeys, Cost input_cost, double tuples, int width,
1285 Cost comparison_cost, int sort_mem,
1286 double limit_tuples)
1288 Cost startup_cost = input_cost;
1290 double input_bytes = relation_byte_size(tuples, width);
1291 double output_bytes;
1292 double output_tuples;
1293 long sort_mem_bytes = sort_mem * 1024L;
1296 startup_cost += disable_cost;
1298 path->rows = tuples;
1301 * We want to be sure the cost of a sort is never estimated as zero, even
1302 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1307 /* Include the default cost-per-comparison */
1308 comparison_cost += 2.0 * cpu_operator_cost;
1310 /* Do we have a useful LIMIT? */
1311 if (limit_tuples > 0 && limit_tuples < tuples)
1313 output_tuples = limit_tuples;
1314 output_bytes = relation_byte_size(output_tuples, width);
1318 output_tuples = tuples;
1319 output_bytes = input_bytes;
1322 if (output_bytes > sort_mem_bytes)
1325 * We'll have to use a disk-based sort of all the tuples
1327 double npages = ceil(input_bytes / BLCKSZ);
1328 double nruns = (input_bytes / sort_mem_bytes) * 0.5;
1329 double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1331 double npageaccesses;
1336 * Assume about N log2 N comparisons
1338 startup_cost += comparison_cost * tuples * LOG2(tuples);
1342 /* Compute logM(r) as log(r) / log(M) */
1343 if (nruns > mergeorder)
1344 log_runs = ceil(log(nruns) / log(mergeorder));
1347 npageaccesses = 2.0 * npages * log_runs;
1348 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1349 startup_cost += npageaccesses *
1350 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1352 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1355 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1356 * a total number of tuple comparisons of N log2 K; but the constant
1357 * factor is a bit higher than for quicksort. Tweak it so that the
1358 * cost curve is continuous at the crossover point.
1360 startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1364 /* We'll use plain quicksort on all the input tuples */
1365 startup_cost += comparison_cost * tuples * LOG2(tuples);
1369 * Also charge a small amount (arbitrarily set equal to operator cost) per
1370 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1371 * doesn't do qual-checking or projection, so it has less overhead than
1372 * most plan nodes. Note it's correct to use tuples not output_tuples
1373 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1374 * counting the LIMIT otherwise.
1376 run_cost += cpu_operator_cost * tuples;
1378 path->startup_cost = startup_cost;
1379 path->total_cost = startup_cost + run_cost;
1384 * Determines and returns the cost of a MergeAppend node.
1386 * MergeAppend merges several pre-sorted input streams, using a heap that
1387 * at any given instant holds the next tuple from each stream. If there
1388 * are N streams, we need about N*log2(N) tuple comparisons to construct
1389 * the heap at startup, and then for each output tuple, about log2(N)
1390 * comparisons to delete the top heap entry and another log2(N) comparisons
1391 * to insert its successor from the same stream.
1393 * (The effective value of N will drop once some of the input streams are
1394 * exhausted, but it seems unlikely to be worth trying to account for that.)
1396 * The heap is never spilled to disk, since we assume N is not very large.
1397 * So this is much simpler than cost_sort.
1399 * As in cost_sort, we charge two operator evals per tuple comparison.
1401 * 'pathkeys' is a list of sort keys
1402 * 'n_streams' is the number of input streams
1403 * 'input_startup_cost' is the sum of the input streams' startup costs
1404 * 'input_total_cost' is the sum of the input streams' total costs
1405 * 'tuples' is the number of tuples in all the streams
1408 cost_merge_append(Path *path, PlannerInfo *root,
1409 List *pathkeys, int n_streams,
1410 Cost input_startup_cost, Cost input_total_cost,
1413 Cost startup_cost = 0;
1415 Cost comparison_cost;
1422 N = (n_streams < 2) ? 2.0 : (double) n_streams;
1425 /* Assumed cost per tuple comparison */
1426 comparison_cost = 2.0 * cpu_operator_cost;
1428 /* Heap creation cost */
1429 startup_cost += comparison_cost * N * logN;
1431 /* Per-tuple heap maintenance cost */
1432 run_cost += tuples * comparison_cost * 2.0 * logN;
1435 * Also charge a small amount (arbitrarily set equal to operator cost) per
1436 * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1437 * node doesn't do qual-checking or projection, so it has less overhead
1438 * than most plan nodes.
1440 run_cost += cpu_operator_cost * tuples;
1442 path->startup_cost = startup_cost + input_startup_cost;
1443 path->total_cost = startup_cost + run_cost + input_total_cost;
1448 * Determines and returns the cost of materializing a relation, including
1449 * the cost of reading the input data.
1451 * If the total volume of data to materialize exceeds work_mem, we will need
1452 * to write it to disk, so the cost is much higher in that case.
1454 * Note that here we are estimating the costs for the first scan of the
1455 * relation, so the materialization is all overhead --- any savings will
1456 * occur only on rescan, which is estimated in cost_rescan.
1459 cost_material(Path *path,
1460 Cost input_startup_cost, Cost input_total_cost,
1461 double tuples, int width)
1463 Cost startup_cost = input_startup_cost;
1464 Cost run_cost = input_total_cost - input_startup_cost;
1465 double nbytes = relation_byte_size(tuples, width);
1466 long work_mem_bytes = work_mem * 1024L;
1468 path->rows = tuples;
1471 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1472 * reflect bookkeeping overhead. (This rate must be more than what
1473 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1474 * if it is exactly the same then there will be a cost tie between
1475 * nestloop with A outer, materialized B inner and nestloop with B outer,
1476 * materialized A inner. The extra cost ensures we'll prefer
1477 * materializing the smaller rel.) Note that this is normally a good deal
1478 * less than cpu_tuple_cost; which is OK because a Material plan node
1479 * doesn't do qual-checking or projection, so it's got less overhead than
1482 run_cost += 2 * cpu_operator_cost * tuples;
1485 * If we will spill to disk, charge at the rate of seq_page_cost per page.
1486 * This cost is assumed to be evenly spread through the plan run phase,
1487 * which isn't exactly accurate but our cost model doesn't allow for
1488 * nonuniform costs within the run phase.
1490 if (nbytes > work_mem_bytes)
1492 double npages = ceil(nbytes / BLCKSZ);
1494 run_cost += seq_page_cost * npages;
1497 path->startup_cost = startup_cost;
1498 path->total_cost = startup_cost + run_cost;
1503 * Determines and returns the cost of performing an Agg plan node,
1504 * including the cost of its input.
1506 * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
1507 * we are using a hashed Agg node just to do grouping).
1509 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1510 * are for appropriately-sorted input.
1513 cost_agg(Path *path, PlannerInfo *root,
1514 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
1515 int numGroupCols, double numGroups,
1516 Cost input_startup_cost, Cost input_total_cost,
1517 double input_tuples)
1519 double output_tuples;
1522 AggClauseCosts dummy_aggcosts;
1524 /* Use all-zero per-aggregate costs if NULL is passed */
1525 if (aggcosts == NULL)
1527 Assert(aggstrategy == AGG_HASHED);
1528 MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1529 aggcosts = &dummy_aggcosts;
1533 * The transCost.per_tuple component of aggcosts should be charged once
1534 * per input tuple, corresponding to the costs of evaluating the aggregate
1535 * transfns and their input expressions (with any startup cost of course
1536 * charged but once). The finalCost component is charged once per output
1537 * tuple, corresponding to the costs of evaluating the finalfns.
1539 * If we are grouping, we charge an additional cpu_operator_cost per
1540 * grouping column per input tuple for grouping comparisons.
1542 * We will produce a single output tuple if not grouping, and a tuple per
1543 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1545 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1546 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1547 * input path is already sorted appropriately, AGG_SORTED should be
1548 * preferred (since it has no risk of memory overflow). This will happen
1549 * as long as the computed total costs are indeed exactly equal --- but if
1550 * there's roundoff error we might do the wrong thing. So be sure that
1551 * the computations below form the same intermediate values in the same
1554 if (aggstrategy == AGG_PLAIN)
1556 startup_cost = input_total_cost;
1557 startup_cost += aggcosts->transCost.startup;
1558 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1559 startup_cost += aggcosts->finalCost;
1560 /* we aren't grouping */
1561 total_cost = startup_cost + cpu_tuple_cost;
1564 else if (aggstrategy == AGG_SORTED)
1566 /* Here we are able to deliver output on-the-fly */
1567 startup_cost = input_startup_cost;
1568 total_cost = input_total_cost;
1569 /* calcs phrased this way to match HASHED case, see note above */
1570 total_cost += aggcosts->transCost.startup;
1571 total_cost += aggcosts->transCost.per_tuple * input_tuples;
1572 total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1573 total_cost += aggcosts->finalCost * numGroups;
1574 total_cost += cpu_tuple_cost * numGroups;
1575 output_tuples = numGroups;
1579 /* must be AGG_HASHED */
1580 startup_cost = input_total_cost;
1581 startup_cost += aggcosts->transCost.startup;
1582 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1583 startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1584 total_cost = startup_cost;
1585 total_cost += aggcosts->finalCost * numGroups;
1586 total_cost += cpu_tuple_cost * numGroups;
1587 output_tuples = numGroups;
1590 path->rows = output_tuples;
1591 path->startup_cost = startup_cost;
1592 path->total_cost = total_cost;
1597 * Determines and returns the cost of performing a WindowAgg plan node,
1598 * including the cost of its input.
1600 * Input is assumed already properly sorted.
1603 cost_windowagg(Path *path, PlannerInfo *root,
1604 List *windowFuncs, int numPartCols, int numOrderCols,
1605 Cost input_startup_cost, Cost input_total_cost,
1606 double input_tuples)
1612 startup_cost = input_startup_cost;
1613 total_cost = input_total_cost;
1616 * Window functions are assumed to cost their stated execution cost, plus
1617 * the cost of evaluating their input expressions, per tuple. Since they
1618 * may in fact evaluate their inputs at multiple rows during each cycle,
1619 * this could be a drastic underestimate; but without a way to know how
1620 * many rows the window function will fetch, it's hard to do better. In
1621 * any case, it's a good estimate for all the built-in window functions,
1622 * so we'll just do this for now.
1624 foreach(lc, windowFuncs)
1626 WindowFunc *wfunc = (WindowFunc *) lfirst(lc);
1630 Assert(IsA(wfunc, WindowFunc));
1632 wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1634 /* also add the input expressions' cost to per-input-row costs */
1635 cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1636 startup_cost += argcosts.startup;
1637 wfunccost += argcosts.per_tuple;
1640 * Add the filter's cost to per-input-row costs. XXX We should reduce
1641 * input expression costs according to filter selectivity.
1643 cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
1644 startup_cost += argcosts.startup;
1645 wfunccost += argcosts.per_tuple;
1647 total_cost += wfunccost * input_tuples;
1651 * We also charge cpu_operator_cost per grouping column per tuple for
1652 * grouping comparisons, plus cpu_tuple_cost per tuple for general
1655 * XXX this neglects costs of spooling the data to disk when it overflows
1656 * work_mem. Sooner or later that should get accounted for.
1658 total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1659 total_cost += cpu_tuple_cost * input_tuples;
1661 path->rows = input_tuples;
1662 path->startup_cost = startup_cost;
1663 path->total_cost = total_cost;
1668 * Determines and returns the cost of performing a Group plan node,
1669 * including the cost of its input.
1671 * Note: caller must ensure that input costs are for appropriately-sorted
1675 cost_group(Path *path, PlannerInfo *root,
1676 int numGroupCols, double numGroups,
1677 Cost input_startup_cost, Cost input_total_cost,
1678 double input_tuples)
1683 startup_cost = input_startup_cost;
1684 total_cost = input_total_cost;
1687 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1688 * all columns get compared at most of the tuples.
1690 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1692 path->rows = numGroups;
1693 path->startup_cost = startup_cost;
1694 path->total_cost = total_cost;
1698 * initial_cost_nestloop
1699 * Preliminary estimate of the cost of a nestloop join path.
1701 * This must quickly produce lower-bound estimates of the path's startup and
1702 * total costs. If we are unable to eliminate the proposed path from
1703 * consideration using the lower bounds, final_cost_nestloop will be called
1704 * to obtain the final estimates.
1706 * The exact division of labor between this function and final_cost_nestloop
1707 * is private to them, and represents a tradeoff between speed of the initial
1708 * estimate and getting a tight lower bound. We choose to not examine the
1709 * join quals here, since that's by far the most expensive part of the
1710 * calculations. The end result is that CPU-cost considerations must be
1711 * left for the second phase.
1713 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
1714 * other data to be used by final_cost_nestloop
1715 * 'jointype' is the type of join to be performed
1716 * 'outer_path' is the outer input to the join
1717 * 'inner_path' is the inner input to the join
1718 * 'sjinfo' is extra info about the join for selectivity estimation
1719 * 'semifactors' contains valid data if jointype is SEMI or ANTI
1722 initial_cost_nestloop(PlannerInfo *root, JoinCostWorkspace *workspace,
1724 Path *outer_path, Path *inner_path,
1725 SpecialJoinInfo *sjinfo,
1726 SemiAntiJoinFactors *semifactors)
1728 Cost startup_cost = 0;
1730 double outer_path_rows = outer_path->rows;
1731 Cost inner_rescan_start_cost;
1732 Cost inner_rescan_total_cost;
1733 Cost inner_run_cost;
1734 Cost inner_rescan_run_cost;
1736 /* estimate costs to rescan the inner relation */
1737 cost_rescan(root, inner_path,
1738 &inner_rescan_start_cost,
1739 &inner_rescan_total_cost);
1741 /* cost of source data */
1744 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1745 * before we can start returning tuples, so the join's startup cost is
1746 * their sum. We'll also pay the inner path's rescan startup cost
1749 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1750 run_cost += outer_path->total_cost - outer_path->startup_cost;
1751 if (outer_path_rows > 1)
1752 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1754 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1755 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1757 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
1759 double outer_matched_rows;
1760 Selectivity inner_scan_frac;
1763 * SEMI or ANTI join: executor will stop after first match.
1765 * For an outer-rel row that has at least one match, we can expect the
1766 * inner scan to stop after a fraction 1/(match_count+1) of the inner
1767 * rows, if the matches are evenly distributed. Since they probably
1768 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1769 * that fraction. (If we used a larger fuzz factor, we'd have to
1770 * clamp inner_scan_frac to at most 1.0; but since match_count is at
1771 * least 1, no such clamp is needed now.)
1773 * A complicating factor is that rescans may be cheaper than first
1774 * scans. If we never scan all the way to the end of the inner rel,
1775 * it might be (depending on the plan type) that we'd never pay the
1776 * whole inner first-scan run cost. However it is difficult to
1777 * estimate whether that will happen, so be conservative and always
1778 * charge the whole first-scan cost once.
1780 run_cost += inner_run_cost;
1782 outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
1783 inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
1785 /* Add inner run cost for additional outer tuples having matches */
1786 if (outer_matched_rows > 1)
1787 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1790 * The cost of processing unmatched rows varies depending on the
1791 * details of the joinclauses, so we leave that part for later.
1794 /* Save private data for final_cost_nestloop */
1795 workspace->outer_matched_rows = outer_matched_rows;
1796 workspace->inner_scan_frac = inner_scan_frac;
1800 /* Normal case; we'll scan whole input rel for each outer row */
1801 run_cost += inner_run_cost;
1802 if (outer_path_rows > 1)
1803 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1806 /* CPU costs left for later */
1808 /* Public result fields */
1809 workspace->startup_cost = startup_cost;
1810 workspace->total_cost = startup_cost + run_cost;
1811 /* Save private data for final_cost_nestloop */
1812 workspace->run_cost = run_cost;
1813 workspace->inner_rescan_run_cost = inner_rescan_run_cost;
1817 * final_cost_nestloop
1818 * Final estimate of the cost and result size of a nestloop join path.
1820 * 'path' is already filled in except for the rows and cost fields
1821 * 'workspace' is the result from initial_cost_nestloop
1822 * 'sjinfo' is extra info about the join for selectivity estimation
1823 * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
1826 final_cost_nestloop(PlannerInfo *root, NestPath *path,
1827 JoinCostWorkspace *workspace,
1828 SpecialJoinInfo *sjinfo,
1829 SemiAntiJoinFactors *semifactors)
1831 Path *outer_path = path->outerjoinpath;
1832 Path *inner_path = path->innerjoinpath;
1833 double outer_path_rows = outer_path->rows;
1834 double inner_path_rows = inner_path->rows;
1835 Cost startup_cost = workspace->startup_cost;
1836 Cost run_cost = workspace->run_cost;
1837 Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
1839 QualCost restrict_qual_cost;
1842 /* Mark the path with the correct row estimate */
1843 if (path->path.param_info)
1844 path->path.rows = path->path.param_info->ppi_rows;
1846 path->path.rows = path->path.parent->rows;
1849 * We could include disable_cost in the preliminary estimate, but that
1850 * would amount to optimizing for the case where the join method is
1851 * disabled, which doesn't seem like the way to bet.
1853 if (!enable_nestloop)
1854 startup_cost += disable_cost;
1856 /* cost of source data */
1858 if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI)
1860 double outer_matched_rows = workspace->outer_matched_rows;
1861 Selectivity inner_scan_frac = workspace->inner_scan_frac;
1864 * SEMI or ANTI join: executor will stop after first match.
1867 /* Compute number of tuples processed (not number emitted!) */
1868 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1871 * For unmatched outer-rel rows, there are two cases. If the inner
1872 * path is an indexscan using all the joinquals as indexquals, then an
1873 * unmatched row results in an indexscan returning no rows, which is
1874 * probably quite cheap. We estimate this case as the same cost to
1875 * return the first tuple of a nonempty scan. Otherwise, the executor
1876 * will have to scan the whole inner rel; not so cheap.
1878 if (has_indexed_join_quals(path))
1880 run_cost += (outer_path_rows - outer_matched_rows) *
1881 inner_rescan_run_cost / inner_path_rows;
1884 * We won't be evaluating any quals at all for these rows, so
1885 * don't add them to ntuples.
1890 run_cost += (outer_path_rows - outer_matched_rows) *
1891 inner_rescan_run_cost;
1892 ntuples += (outer_path_rows - outer_matched_rows) *
1898 /* Normal-case source costs were included in preliminary estimate */
1900 /* Compute number of tuples processed (not number emitted!) */
1901 ntuples = outer_path_rows * inner_path_rows;
1905 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1906 startup_cost += restrict_qual_cost.startup;
1907 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1908 run_cost += cpu_per_tuple * ntuples;
1910 path->path.startup_cost = startup_cost;
1911 path->path.total_cost = startup_cost + run_cost;
1915 * initial_cost_mergejoin
1916 * Preliminary estimate of the cost of a mergejoin path.
1918 * This must quickly produce lower-bound estimates of the path's startup and
1919 * total costs. If we are unable to eliminate the proposed path from
1920 * consideration using the lower bounds, final_cost_mergejoin will be called
1921 * to obtain the final estimates.
1923 * The exact division of labor between this function and final_cost_mergejoin
1924 * is private to them, and represents a tradeoff between speed of the initial
1925 * estimate and getting a tight lower bound. We choose to not examine the
1926 * join quals here, except for obtaining the scan selectivity estimate which
1927 * is really essential (but fortunately, use of caching keeps the cost of
1928 * getting that down to something reasonable).
1929 * We also assume that cost_sort is cheap enough to use here.
1931 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
1932 * other data to be used by final_cost_mergejoin
1933 * 'jointype' is the type of join to be performed
1934 * 'mergeclauses' is the list of joinclauses to be used as merge clauses
1935 * 'outer_path' is the outer input to the join
1936 * 'inner_path' is the inner input to the join
1937 * 'outersortkeys' is the list of sort keys for the outer path
1938 * 'innersortkeys' is the list of sort keys for the inner path
1939 * 'sjinfo' is extra info about the join for selectivity estimation
1941 * Note: outersortkeys and innersortkeys should be NIL if no explicit
1942 * sort is needed because the respective source path is already ordered.
1945 initial_cost_mergejoin(PlannerInfo *root, JoinCostWorkspace *workspace,
1948 Path *outer_path, Path *inner_path,
1949 List *outersortkeys, List *innersortkeys,
1950 SpecialJoinInfo *sjinfo)
1952 Cost startup_cost = 0;
1954 double outer_path_rows = outer_path->rows;
1955 double inner_path_rows = inner_path->rows;
1956 Cost inner_run_cost;
1961 Selectivity outerstartsel,
1965 Path sort_path; /* dummy for result of cost_sort */
1967 /* Protect some assumptions below that rowcounts aren't zero or NaN */
1968 if (outer_path_rows <= 0 || isnan(outer_path_rows))
1969 outer_path_rows = 1;
1970 if (inner_path_rows <= 0 || isnan(inner_path_rows))
1971 inner_path_rows = 1;
1974 * A merge join will stop as soon as it exhausts either input stream
1975 * (unless it's an outer join, in which case the outer side has to be
1976 * scanned all the way anyway). Estimate fraction of the left and right
1977 * inputs that will actually need to be scanned. Likewise, we can
1978 * estimate the number of rows that will be skipped before the first join
1979 * pair is found, which should be factored into startup cost. We use only
1980 * the first (most significant) merge clause for this purpose. Since
1981 * mergejoinscansel() is a fairly expensive computation, we cache the
1982 * results in the merge clause RestrictInfo.
1984 if (mergeclauses && jointype != JOIN_FULL)
1986 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1991 MergeScanSelCache *cache;
1993 /* Get the input pathkeys to determine the sort-order details */
1994 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1995 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1998 opathkey = (PathKey *) linitial(opathkeys);
1999 ipathkey = (PathKey *) linitial(ipathkeys);
2000 /* debugging check */
2001 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2002 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2003 opathkey->pk_strategy != ipathkey->pk_strategy ||
2004 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2005 elog(ERROR, "left and right pathkeys do not match in mergejoin");
2007 /* Get the selectivity with caching */
2008 cache = cached_scansel(root, firstclause, opathkey);
2010 if (bms_is_subset(firstclause->left_relids,
2011 outer_path->parent->relids))
2013 /* left side of clause is outer */
2014 outerstartsel = cache->leftstartsel;
2015 outerendsel = cache->leftendsel;
2016 innerstartsel = cache->rightstartsel;
2017 innerendsel = cache->rightendsel;
2021 /* left side of clause is inner */
2022 outerstartsel = cache->rightstartsel;
2023 outerendsel = cache->rightendsel;
2024 innerstartsel = cache->leftstartsel;
2025 innerendsel = cache->leftendsel;
2027 if (jointype == JOIN_LEFT ||
2028 jointype == JOIN_ANTI)
2030 outerstartsel = 0.0;
2033 else if (jointype == JOIN_RIGHT)
2035 innerstartsel = 0.0;
2041 /* cope with clauseless or full mergejoin */
2042 outerstartsel = innerstartsel = 0.0;
2043 outerendsel = innerendsel = 1.0;
2047 * Convert selectivities to row counts. We force outer_rows and
2048 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
2050 outer_skip_rows = rint(outer_path_rows * outerstartsel);
2051 inner_skip_rows = rint(inner_path_rows * innerstartsel);
2052 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
2053 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
2055 Assert(outer_skip_rows <= outer_rows);
2056 Assert(inner_skip_rows <= inner_rows);
2059 * Readjust scan selectivities to account for above rounding. This is
2060 * normally an insignificant effect, but when there are only a few rows in
2061 * the inputs, failing to do this makes for a large percentage error.
2063 outerstartsel = outer_skip_rows / outer_path_rows;
2064 innerstartsel = inner_skip_rows / inner_path_rows;
2065 outerendsel = outer_rows / outer_path_rows;
2066 innerendsel = inner_rows / inner_path_rows;
2068 Assert(outerstartsel <= outerendsel);
2069 Assert(innerstartsel <= innerendsel);
2071 /* cost of source data */
2073 if (outersortkeys) /* do we need to sort outer? */
2075 cost_sort(&sort_path,
2078 outer_path->total_cost,
2080 outer_path->parent->width,
2084 startup_cost += sort_path.startup_cost;
2085 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2087 run_cost += (sort_path.total_cost - sort_path.startup_cost)
2088 * (outerendsel - outerstartsel);
2092 startup_cost += outer_path->startup_cost;
2093 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
2095 run_cost += (outer_path->total_cost - outer_path->startup_cost)
2096 * (outerendsel - outerstartsel);
2099 if (innersortkeys) /* do we need to sort inner? */
2101 cost_sort(&sort_path,
2104 inner_path->total_cost,
2106 inner_path->parent->width,
2110 startup_cost += sort_path.startup_cost;
2111 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2113 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
2114 * (innerendsel - innerstartsel);
2118 startup_cost += inner_path->startup_cost;
2119 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
2121 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
2122 * (innerendsel - innerstartsel);
2126 * We can't yet determine whether rescanning occurs, or whether
2127 * materialization of the inner input should be done. The minimum
2128 * possible inner input cost, regardless of rescan and materialization
2129 * considerations, is inner_run_cost. We include that in
2130 * workspace->total_cost, but not yet in run_cost.
2133 /* CPU costs left for later */
2135 /* Public result fields */
2136 workspace->startup_cost = startup_cost;
2137 workspace->total_cost = startup_cost + run_cost + inner_run_cost;
2138 /* Save private data for final_cost_mergejoin */
2139 workspace->run_cost = run_cost;
2140 workspace->inner_run_cost = inner_run_cost;
2141 workspace->outer_rows = outer_rows;
2142 workspace->inner_rows = inner_rows;
2143 workspace->outer_skip_rows = outer_skip_rows;
2144 workspace->inner_skip_rows = inner_skip_rows;
2148 * final_cost_mergejoin
2149 * Final estimate of the cost and result size of a mergejoin path.
2151 * Unlike other costsize functions, this routine makes one actual decision:
2152 * whether we should materialize the inner path. We do that either because
2153 * the inner path can't support mark/restore, or because it's cheaper to
2154 * use an interposed Material node to handle mark/restore. When the decision
2155 * is cost-based it would be logically cleaner to build and cost two separate
2156 * paths with and without that flag set; but that would require repeating most
2157 * of the cost calculations, which are not all that cheap. Since the choice
2158 * will not affect output pathkeys or startup cost, only total cost, there is
2159 * no possibility of wanting to keep both paths. So it seems best to make
2160 * the decision here and record it in the path's materialize_inner field.
2162 * 'path' is already filled in except for the rows and cost fields and
2164 * 'workspace' is the result from initial_cost_mergejoin
2165 * 'sjinfo' is extra info about the join for selectivity estimation
2168 final_cost_mergejoin(PlannerInfo *root, MergePath *path,
2169 JoinCostWorkspace *workspace,
2170 SpecialJoinInfo *sjinfo)
2172 Path *outer_path = path->jpath.outerjoinpath;
2173 Path *inner_path = path->jpath.innerjoinpath;
2174 double inner_path_rows = inner_path->rows;
2175 List *mergeclauses = path->path_mergeclauses;
2176 List *innersortkeys = path->innersortkeys;
2177 Cost startup_cost = workspace->startup_cost;
2178 Cost run_cost = workspace->run_cost;
2179 Cost inner_run_cost = workspace->inner_run_cost;
2180 double outer_rows = workspace->outer_rows;
2181 double inner_rows = workspace->inner_rows;
2182 double outer_skip_rows = workspace->outer_skip_rows;
2183 double inner_skip_rows = workspace->inner_skip_rows;
2187 QualCost merge_qual_cost;
2188 QualCost qp_qual_cost;
2189 double mergejointuples,
2193 /* Protect some assumptions below that rowcounts aren't zero or NaN */
2194 if (inner_path_rows <= 0 || isnan(inner_path_rows))
2195 inner_path_rows = 1;
2197 /* Mark the path with the correct row estimate */
2198 if (path->jpath.path.param_info)
2199 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2201 path->jpath.path.rows = path->jpath.path.parent->rows;
2204 * We could include disable_cost in the preliminary estimate, but that
2205 * would amount to optimizing for the case where the join method is
2206 * disabled, which doesn't seem like the way to bet.
2208 if (!enable_mergejoin)
2209 startup_cost += disable_cost;
2212 * Compute cost of the mergequals and qpquals (other restriction clauses)
2215 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2216 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2217 qp_qual_cost.startup -= merge_qual_cost.startup;
2218 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2221 * Get approx # tuples passing the mergequals. We use approx_tuple_count
2222 * here because we need an estimate done with JOIN_INNER semantics.
2224 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2227 * When there are equal merge keys in the outer relation, the mergejoin
2228 * must rescan any matching tuples in the inner relation. This means
2229 * re-fetching inner tuples; we have to estimate how often that happens.
2231 * For regular inner and outer joins, the number of re-fetches can be
2232 * estimated approximately as size of merge join output minus size of
2233 * inner relation. Assume that the distinct key values are 1, 2, ..., and
2234 * denote the number of values of each key in the outer relation as m1,
2235 * m2, ...; in the inner relation, n1, n2, ... Then we have
2237 * size of join = m1 * n1 + m2 * n2 + ...
2239 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2240 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2243 * This equation works correctly for outer tuples having no inner match
2244 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2245 * are effectively subtracting those from the number of rescanned tuples,
2246 * when we should not. Can we do better without expensive selectivity
2249 * The whole issue is moot if we are working from a unique-ified outer
2252 if (IsA(outer_path, UniquePath))
2253 rescannedtuples = 0;
2256 rescannedtuples = mergejointuples - inner_path_rows;
2257 /* Must clamp because of possible underestimate */
2258 if (rescannedtuples < 0)
2259 rescannedtuples = 0;
2261 /* We'll inflate various costs this much to account for rescanning */
2262 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
2265 * Decide whether we want to materialize the inner input to shield it from
2266 * mark/restore and performing re-fetches. Our cost model for regular
2267 * re-fetches is that a re-fetch costs the same as an original fetch,
2268 * which is probably an overestimate; but on the other hand we ignore the
2269 * bookkeeping costs of mark/restore. Not clear if it's worth developing
2270 * a more refined model. So we just need to inflate the inner run cost by
2273 bare_inner_cost = inner_run_cost * rescanratio;
2276 * When we interpose a Material node the re-fetch cost is assumed to be
2277 * just cpu_operator_cost per tuple, independently of the underlying
2278 * plan's cost; and we charge an extra cpu_operator_cost per original
2279 * fetch as well. Note that we're assuming the materialize node will
2280 * never spill to disk, since it only has to remember tuples back to the
2281 * last mark. (If there are a huge number of duplicates, our other cost
2282 * factors will make the path so expensive that it probably won't get
2283 * chosen anyway.) So we don't use cost_rescan here.
2285 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
2286 * of the generated Material node.
2288 mat_inner_cost = inner_run_cost +
2289 cpu_operator_cost * inner_path_rows * rescanratio;
2292 * Prefer materializing if it looks cheaper, unless the user has asked to
2293 * suppress materialization.
2295 if (enable_material && mat_inner_cost < bare_inner_cost)
2296 path->materialize_inner = true;
2299 * Even if materializing doesn't look cheaper, we *must* do it if the
2300 * inner path is to be used directly (without sorting) and it doesn't
2301 * support mark/restore.
2303 * Since the inner side must be ordered, and only Sorts and IndexScans can
2304 * create order to begin with, and they both support mark/restore, you
2305 * might think there's no problem --- but you'd be wrong. Nestloop and
2306 * merge joins can *preserve* the order of their inputs, so they can be
2307 * selected as the input of a mergejoin, and they don't support
2308 * mark/restore at present.
2310 * We don't test the value of enable_material here, because
2311 * materialization is required for correctness in this case, and turning
2312 * it off does not entitle us to deliver an invalid plan.
2314 else if (innersortkeys == NIL &&
2315 !ExecSupportsMarkRestore(inner_path->pathtype))
2316 path->materialize_inner = true;
2319 * Also, force materializing if the inner path is to be sorted and the
2320 * sort is expected to spill to disk. This is because the final merge
2321 * pass can be done on-the-fly if it doesn't have to support mark/restore.
2322 * We don't try to adjust the cost estimates for this consideration,
2325 * Since materialization is a performance optimization in this case,
2326 * rather than necessary for correctness, we skip it if enable_material is
2329 else if (enable_material && innersortkeys != NIL &&
2330 relation_byte_size(inner_path_rows, inner_path->parent->width) >
2332 path->materialize_inner = true;
2334 path->materialize_inner = false;
2336 /* Charge the right incremental cost for the chosen case */
2337 if (path->materialize_inner)
2338 run_cost += mat_inner_cost;
2340 run_cost += bare_inner_cost;
2345 * The number of tuple comparisons needed is approximately number of outer
2346 * rows plus number of inner rows plus number of rescanned tuples (can we
2347 * refine this?). At each one, we need to evaluate the mergejoin quals.
2349 startup_cost += merge_qual_cost.startup;
2350 startup_cost += merge_qual_cost.per_tuple *
2351 (outer_skip_rows + inner_skip_rows * rescanratio);
2352 run_cost += merge_qual_cost.per_tuple *
2353 ((outer_rows - outer_skip_rows) +
2354 (inner_rows - inner_skip_rows) * rescanratio);
2357 * For each tuple that gets through the mergejoin proper, we charge
2358 * cpu_tuple_cost plus the cost of evaluating additional restriction
2359 * clauses that are to be applied at the join. (This is pessimistic since
2360 * not all of the quals may get evaluated at each tuple.)
2362 * Note: we could adjust for SEMI/ANTI joins skipping some qual
2363 * evaluations here, but it's probably not worth the trouble.
2365 startup_cost += qp_qual_cost.startup;
2366 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2367 run_cost += cpu_per_tuple * mergejointuples;
2369 path->jpath.path.startup_cost = startup_cost;
2370 path->jpath.path.total_cost = startup_cost + run_cost;
2374 * run mergejoinscansel() with caching
2376 static MergeScanSelCache *
2377 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2379 MergeScanSelCache *cache;
2381 Selectivity leftstartsel,
2385 MemoryContext oldcontext;
2387 /* Do we have this result already? */
2388 foreach(lc, rinfo->scansel_cache)
2390 cache = (MergeScanSelCache *) lfirst(lc);
2391 if (cache->opfamily == pathkey->pk_opfamily &&
2392 cache->collation == pathkey->pk_eclass->ec_collation &&
2393 cache->strategy == pathkey->pk_strategy &&
2394 cache->nulls_first == pathkey->pk_nulls_first)
2398 /* Nope, do the computation */
2399 mergejoinscansel(root,
2400 (Node *) rinfo->clause,
2401 pathkey->pk_opfamily,
2402 pathkey->pk_strategy,
2403 pathkey->pk_nulls_first,
2409 /* Cache the result in suitably long-lived workspace */
2410 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2412 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2413 cache->opfamily = pathkey->pk_opfamily;
2414 cache->collation = pathkey->pk_eclass->ec_collation;
2415 cache->strategy = pathkey->pk_strategy;
2416 cache->nulls_first = pathkey->pk_nulls_first;
2417 cache->leftstartsel = leftstartsel;
2418 cache->leftendsel = leftendsel;
2419 cache->rightstartsel = rightstartsel;
2420 cache->rightendsel = rightendsel;
2422 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2424 MemoryContextSwitchTo(oldcontext);
2430 * initial_cost_hashjoin
2431 * Preliminary estimate of the cost of a hashjoin path.
2433 * This must quickly produce lower-bound estimates of the path's startup and
2434 * total costs. If we are unable to eliminate the proposed path from
2435 * consideration using the lower bounds, final_cost_hashjoin will be called
2436 * to obtain the final estimates.
2438 * The exact division of labor between this function and final_cost_hashjoin
2439 * is private to them, and represents a tradeoff between speed of the initial
2440 * estimate and getting a tight lower bound. We choose to not examine the
2441 * join quals here (other than by counting the number of hash clauses),
2442 * so we can't do much with CPU costs. We do assume that
2443 * ExecChooseHashTableSize is cheap enough to use here.
2445 * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
2446 * other data to be used by final_cost_hashjoin
2447 * 'jointype' is the type of join to be performed
2448 * 'hashclauses' is the list of joinclauses to be used as hash clauses
2449 * 'outer_path' is the outer input to the join
2450 * 'inner_path' is the inner input to the join
2451 * 'sjinfo' is extra info about the join for selectivity estimation
2452 * 'semifactors' contains valid data if jointype is SEMI or ANTI
2455 initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
2458 Path *outer_path, Path *inner_path,
2459 SpecialJoinInfo *sjinfo,
2460 SemiAntiJoinFactors *semifactors)
2462 Cost startup_cost = 0;
2464 double outer_path_rows = outer_path->rows;
2465 double inner_path_rows = inner_path->rows;
2466 int num_hashclauses = list_length(hashclauses);
2471 /* cost of source data */
2472 startup_cost += outer_path->startup_cost;
2473 run_cost += outer_path->total_cost - outer_path->startup_cost;
2474 startup_cost += inner_path->total_cost;
2477 * Cost of computing hash function: must do it once per input tuple. We
2478 * charge one cpu_operator_cost for each column's hash function. Also,
2479 * tack on one cpu_tuple_cost per inner row, to model the costs of
2480 * inserting the row into the hashtable.
2482 * XXX when a hashclause is more complex than a single operator, we really
2483 * should charge the extra eval costs of the left or right side, as
2484 * appropriate, here. This seems more work than it's worth at the moment.
2486 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2488 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2491 * Get hash table size that executor would use for inner relation.
2493 * XXX for the moment, always assume that skew optimization will be
2494 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2495 * trying to determine that for sure.
2497 * XXX at some point it might be interesting to try to account for skew
2498 * optimization in the cost estimate, but for now, we don't.
2500 ExecChooseHashTableSize(inner_path_rows,
2501 inner_path->parent->width,
2508 * If inner relation is too big then we will need to "batch" the join,
2509 * which implies writing and reading most of the tuples to disk an extra
2510 * time. Charge seq_page_cost per page, since the I/O should be nice and
2511 * sequential. Writing the inner rel counts as startup cost, all the rest
2516 double outerpages = page_size(outer_path_rows,
2517 outer_path->parent->width);
2518 double innerpages = page_size(inner_path_rows,
2519 inner_path->parent->width);
2521 startup_cost += seq_page_cost * innerpages;
2522 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2525 /* CPU costs left for later */
2527 /* Public result fields */
2528 workspace->startup_cost = startup_cost;
2529 workspace->total_cost = startup_cost + run_cost;
2530 /* Save private data for final_cost_hashjoin */
2531 workspace->run_cost = run_cost;
2532 workspace->numbuckets = numbuckets;
2533 workspace->numbatches = numbatches;
2537 * final_cost_hashjoin
2538 * Final estimate of the cost and result size of a hashjoin path.
2540 * Note: the numbatches estimate is also saved into 'path' for use later
2542 * 'path' is already filled in except for the rows and cost fields and
2544 * 'workspace' is the result from initial_cost_hashjoin
2545 * 'sjinfo' is extra info about the join for selectivity estimation
2546 * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
2549 final_cost_hashjoin(PlannerInfo *root, HashPath *path,
2550 JoinCostWorkspace *workspace,
2551 SpecialJoinInfo *sjinfo,
2552 SemiAntiJoinFactors *semifactors)
2554 Path *outer_path = path->jpath.outerjoinpath;
2555 Path *inner_path = path->jpath.innerjoinpath;
2556 double outer_path_rows = outer_path->rows;
2557 double inner_path_rows = inner_path->rows;
2558 List *hashclauses = path->path_hashclauses;
2559 Cost startup_cost = workspace->startup_cost;
2560 Cost run_cost = workspace->run_cost;
2561 int numbuckets = workspace->numbuckets;
2562 int numbatches = workspace->numbatches;
2564 QualCost hash_qual_cost;
2565 QualCost qp_qual_cost;
2566 double hashjointuples;
2567 double virtualbuckets;
2568 Selectivity innerbucketsize;
2571 /* Mark the path with the correct row estimate */
2572 if (path->jpath.path.param_info)
2573 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2575 path->jpath.path.rows = path->jpath.path.parent->rows;
2578 * We could include disable_cost in the preliminary estimate, but that
2579 * would amount to optimizing for the case where the join method is
2580 * disabled, which doesn't seem like the way to bet.
2582 if (!enable_hashjoin)
2583 startup_cost += disable_cost;
2585 /* mark the path with estimated # of batches */
2586 path->num_batches = numbatches;
2588 /* and compute the number of "virtual" buckets in the whole join */
2589 virtualbuckets = (double) numbuckets *(double) numbatches;
2592 * Determine bucketsize fraction for inner relation. We use the smallest
2593 * bucketsize estimated for any individual hashclause; this is undoubtedly
2596 * BUT: if inner relation has been unique-ified, we can assume it's good
2597 * for hashing. This is important both because it's the right answer, and
2598 * because we avoid contaminating the cache with a value that's wrong for
2599 * non-unique-ified paths.
2601 if (IsA(inner_path, UniquePath))
2602 innerbucketsize = 1.0 / virtualbuckets;
2605 innerbucketsize = 1.0;
2606 foreach(hcl, hashclauses)
2608 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2609 Selectivity thisbucketsize;
2611 Assert(IsA(restrictinfo, RestrictInfo));
2614 * First we have to figure out which side of the hashjoin clause
2615 * is the inner side.
2617 * Since we tend to visit the same clauses over and over when
2618 * planning a large query, we cache the bucketsize estimate in the
2619 * RestrictInfo node to avoid repeated lookups of statistics.
2621 if (bms_is_subset(restrictinfo->right_relids,
2622 inner_path->parent->relids))
2624 /* righthand side is inner */
2625 thisbucketsize = restrictinfo->right_bucketsize;
2626 if (thisbucketsize < 0)
2628 /* not cached yet */
2630 estimate_hash_bucketsize(root,
2631 get_rightop(restrictinfo->clause),
2633 restrictinfo->right_bucketsize = thisbucketsize;
2638 Assert(bms_is_subset(restrictinfo->left_relids,
2639 inner_path->parent->relids));
2640 /* lefthand side is inner */
2641 thisbucketsize = restrictinfo->left_bucketsize;
2642 if (thisbucketsize < 0)
2644 /* not cached yet */
2646 estimate_hash_bucketsize(root,
2647 get_leftop(restrictinfo->clause),
2649 restrictinfo->left_bucketsize = thisbucketsize;
2653 if (innerbucketsize > thisbucketsize)
2654 innerbucketsize = thisbucketsize;
2659 * Compute cost of the hashquals and qpquals (other restriction clauses)
2662 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2663 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2664 qp_qual_cost.startup -= hash_qual_cost.startup;
2665 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2669 if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI)
2671 double outer_matched_rows;
2672 Selectivity inner_scan_frac;
2675 * SEMI or ANTI join: executor will stop after first match.
2677 * For an outer-rel row that has at least one match, we can expect the
2678 * bucket scan to stop after a fraction 1/(match_count+1) of the
2679 * bucket's rows, if the matches are evenly distributed. Since they
2680 * probably aren't quite evenly distributed, we apply a fuzz factor of
2681 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2682 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2683 * at least 1, no such clamp is needed now.)
2685 outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2686 inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2688 startup_cost += hash_qual_cost.startup;
2689 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2690 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2693 * For unmatched outer-rel rows, the picture is quite a lot different.
2694 * In the first place, there is no reason to assume that these rows
2695 * preferentially hit heavily-populated buckets; instead assume they
2696 * are uncorrelated with the inner distribution and so they see an
2697 * average bucket size of inner_path_rows / virtualbuckets. In the
2698 * second place, it seems likely that they will have few if any exact
2699 * hash-code matches and so very few of the tuples in the bucket will
2700 * actually require eval of the hash quals. We don't have any good
2701 * way to estimate how many will, but for the moment assume that the
2702 * effective cost per bucket entry is one-tenth what it is for
2705 run_cost += hash_qual_cost.per_tuple *
2706 (outer_path_rows - outer_matched_rows) *
2707 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2709 /* Get # of tuples that will pass the basic join */
2710 if (path->jpath.jointype == JOIN_SEMI)
2711 hashjointuples = outer_matched_rows;
2713 hashjointuples = outer_path_rows - outer_matched_rows;
2718 * The number of tuple comparisons needed is the number of outer
2719 * tuples times the typical number of tuples in a hash bucket, which
2720 * is the inner relation size times its bucketsize fraction. At each
2721 * one, we need to evaluate the hashjoin quals. But actually,
2722 * charging the full qual eval cost at each tuple is pessimistic,
2723 * since we don't evaluate the quals unless the hash values match
2724 * exactly. For lack of a better idea, halve the cost estimate to
2727 startup_cost += hash_qual_cost.startup;
2728 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2729 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2732 * Get approx # tuples passing the hashquals. We use
2733 * approx_tuple_count here because we need an estimate done with
2734 * JOIN_INNER semantics.
2736 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2740 * For each tuple that gets through the hashjoin proper, we charge
2741 * cpu_tuple_cost plus the cost of evaluating additional restriction
2742 * clauses that are to be applied at the join. (This is pessimistic since
2743 * not all of the quals may get evaluated at each tuple.)
2745 startup_cost += qp_qual_cost.startup;
2746 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2747 run_cost += cpu_per_tuple * hashjointuples;
2749 path->jpath.path.startup_cost = startup_cost;
2750 path->jpath.path.total_cost = startup_cost + run_cost;
2756 * Figure the costs for a SubPlan (or initplan).
2758 * Note: we could dig the subplan's Plan out of the root list, but in practice
2759 * all callers have it handy already, so we make them pass it.
2762 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2766 /* Figure any cost for evaluating the testexpr */
2767 cost_qual_eval(&sp_cost,
2768 make_ands_implicit((Expr *) subplan->testexpr),
2771 if (subplan->useHashTable)
2774 * If we are using a hash table for the subquery outputs, then the
2775 * cost of evaluating the query is a one-time cost. We charge one
2776 * cpu_operator_cost per tuple for the work of loading the hashtable,
2779 sp_cost.startup += plan->total_cost +
2780 cpu_operator_cost * plan->plan_rows;
2783 * The per-tuple costs include the cost of evaluating the lefthand
2784 * expressions, plus the cost of probing the hashtable. We already
2785 * accounted for the lefthand expressions as part of the testexpr, and
2786 * will also have counted one cpu_operator_cost for each comparison
2787 * operator. That is probably too low for the probing cost, but it's
2788 * hard to make a better estimate, so live with it for now.
2794 * Otherwise we will be rescanning the subplan output on each
2795 * evaluation. We need to estimate how much of the output we will
2796 * actually need to scan. NOTE: this logic should agree with the
2797 * tuple_fraction estimates used by make_subplan() in
2800 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2802 if (subplan->subLinkType == EXISTS_SUBLINK)
2804 /* we only need to fetch 1 tuple */
2805 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2807 else if (subplan->subLinkType == ALL_SUBLINK ||
2808 subplan->subLinkType == ANY_SUBLINK)
2810 /* assume we need 50% of the tuples */
2811 sp_cost.per_tuple += 0.50 * plan_run_cost;
2812 /* also charge a cpu_operator_cost per row examined */
2813 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2817 /* assume we need all tuples */
2818 sp_cost.per_tuple += plan_run_cost;
2822 * Also account for subplan's startup cost. If the subplan is
2823 * uncorrelated or undirect correlated, AND its topmost node is one
2824 * that materializes its output, assume that we'll only need to pay
2825 * its startup cost once; otherwise assume we pay the startup cost
2828 if (subplan->parParam == NIL &&
2829 ExecMaterializesOutput(nodeTag(plan)))
2830 sp_cost.startup += plan->startup_cost;
2832 sp_cost.per_tuple += plan->startup_cost;
2835 subplan->startup_cost = sp_cost.startup;
2836 subplan->per_call_cost = sp_cost.per_tuple;
2842 * Given a finished Path, estimate the costs of rescanning it after
2843 * having done so the first time. For some Path types a rescan is
2844 * cheaper than an original scan (if no parameters change), and this
2845 * function embodies knowledge about that. The default is to return
2846 * the same costs stored in the Path. (Note that the cost estimates
2847 * actually stored in Paths are always for first scans.)
2849 * This function is not currently intended to model effects such as rescans
2850 * being cheaper due to disk block caching; what we are concerned with is
2851 * plan types wherein the executor caches results explicitly, or doesn't
2852 * redo startup calculations, etc.
2855 cost_rescan(PlannerInfo *root, Path *path,
2856 Cost *rescan_startup_cost, /* output parameters */
2857 Cost *rescan_total_cost)
2859 switch (path->pathtype)
2861 case T_FunctionScan:
2864 * Currently, nodeFunctionscan.c always executes the function to
2865 * completion before returning any rows, and caches the results in
2866 * a tuplestore. So the function eval cost is all startup cost
2867 * and isn't paid over again on rescans. However, all run costs
2868 * will be paid over again.
2870 *rescan_startup_cost = 0;
2871 *rescan_total_cost = path->total_cost - path->startup_cost;
2876 * Assume that all of the startup cost represents hash table
2877 * building, which we won't have to do over.
2879 *rescan_startup_cost = 0;
2880 *rescan_total_cost = path->total_cost - path->startup_cost;
2883 case T_WorkTableScan:
2886 * These plan types materialize their final result in a
2887 * tuplestore or tuplesort object. So the rescan cost is only
2888 * cpu_tuple_cost per tuple, unless the result is large enough
2891 Cost run_cost = cpu_tuple_cost * path->rows;
2892 double nbytes = relation_byte_size(path->rows,
2893 path->parent->width);
2894 long work_mem_bytes = work_mem * 1024L;
2896 if (nbytes > work_mem_bytes)
2898 /* It will spill, so account for re-read cost */
2899 double npages = ceil(nbytes / BLCKSZ);
2901 run_cost += seq_page_cost * npages;
2903 *rescan_startup_cost = 0;
2904 *rescan_total_cost = run_cost;
2911 * These plan types not only materialize their results, but do
2912 * not implement qual filtering or projection. So they are
2913 * even cheaper to rescan than the ones above. We charge only
2914 * cpu_operator_cost per tuple. (Note: keep that in sync with
2915 * the run_cost charge in cost_sort, and also see comments in
2916 * cost_material before you change it.)
2918 Cost run_cost = cpu_operator_cost * path->rows;
2919 double nbytes = relation_byte_size(path->rows,
2920 path->parent->width);
2921 long work_mem_bytes = work_mem * 1024L;
2923 if (nbytes > work_mem_bytes)
2925 /* It will spill, so account for re-read cost */
2926 double npages = ceil(nbytes / BLCKSZ);
2928 run_cost += seq_page_cost * npages;
2930 *rescan_startup_cost = 0;
2931 *rescan_total_cost = run_cost;
2935 *rescan_startup_cost = path->startup_cost;
2936 *rescan_total_cost = path->total_cost;
2944 * Estimate the CPU costs of evaluating a WHERE clause.
2945 * The input can be either an implicitly-ANDed list of boolean
2946 * expressions, or a list of RestrictInfo nodes. (The latter is
2947 * preferred since it allows caching of the results.)
2948 * The result includes both a one-time (startup) component,
2949 * and a per-evaluation component.
2952 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2954 cost_qual_eval_context context;
2957 context.root = root;
2958 context.total.startup = 0;
2959 context.total.per_tuple = 0;
2961 /* We don't charge any cost for the implicit ANDing at top level ... */
2965 Node *qual = (Node *) lfirst(l);
2967 cost_qual_eval_walker(qual, &context);
2970 *cost = context.total;
2974 * cost_qual_eval_node
2975 * As above, for a single RestrictInfo or expression.
2978 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2980 cost_qual_eval_context context;
2982 context.root = root;
2983 context.total.startup = 0;
2984 context.total.per_tuple = 0;
2986 cost_qual_eval_walker(qual, &context);
2988 *cost = context.total;
2992 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2998 * RestrictInfo nodes contain an eval_cost field reserved for this
2999 * routine's use, so that it's not necessary to evaluate the qual clause's
3000 * cost more than once. If the clause's cost hasn't been computed yet,
3001 * the field's startup value will contain -1.
3003 if (IsA(node, RestrictInfo))
3005 RestrictInfo *rinfo = (RestrictInfo *) node;
3007 if (rinfo->eval_cost.startup < 0)
3009 cost_qual_eval_context locContext;
3011 locContext.root = context->root;
3012 locContext.total.startup = 0;
3013 locContext.total.per_tuple = 0;
3016 * For an OR clause, recurse into the marked-up tree so that we
3017 * set the eval_cost for contained RestrictInfos too.
3019 if (rinfo->orclause)
3020 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
3022 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
3025 * If the RestrictInfo is marked pseudoconstant, it will be tested
3026 * only once, so treat its cost as all startup cost.
3028 if (rinfo->pseudoconstant)
3030 /* count one execution during startup */
3031 locContext.total.startup += locContext.total.per_tuple;
3032 locContext.total.per_tuple = 0;
3034 rinfo->eval_cost = locContext.total;
3036 context->total.startup += rinfo->eval_cost.startup;
3037 context->total.per_tuple += rinfo->eval_cost.per_tuple;
3038 /* do NOT recurse into children */
3043 * For each operator or function node in the given tree, we charge the
3044 * estimated execution cost given by pg_proc.procost (remember to multiply
3045 * this by cpu_operator_cost).
3047 * Vars and Consts are charged zero, and so are boolean operators (AND,
3048 * OR, NOT). Simplistic, but a lot better than no model at all.
3050 * Should we try to account for the possibility of short-circuit
3051 * evaluation of AND/OR? Probably *not*, because that would make the
3052 * results depend on the clause ordering, and we are not in any position
3053 * to expect that the current ordering of the clauses is the one that's
3054 * going to end up being used. The above per-RestrictInfo caching would
3055 * not mix well with trying to re-order clauses anyway.
3057 * Another issue that is entirely ignored here is that if a set-returning
3058 * function is below top level in the tree, the functions/operators above
3059 * it will need to be evaluated multiple times. In practical use, such
3060 * cases arise so seldom as to not be worth the added complexity needed;
3061 * moreover, since our rowcount estimates for functions tend to be pretty
3062 * phony, the results would also be pretty phony.
3064 if (IsA(node, FuncExpr))
3066 context->total.per_tuple +=
3067 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
3069 else if (IsA(node, OpExpr) ||
3070 IsA(node, DistinctExpr) ||
3071 IsA(node, NullIfExpr))
3073 /* rely on struct equivalence to treat these all alike */
3074 set_opfuncid((OpExpr *) node);
3075 context->total.per_tuple +=
3076 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
3078 else if (IsA(node, ScalarArrayOpExpr))
3081 * Estimate that the operator will be applied to about half of the
3082 * array elements before the answer is determined.
3084 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
3085 Node *arraynode = (Node *) lsecond(saop->args);
3087 set_sa_opfuncid(saop);
3088 context->total.per_tuple += get_func_cost(saop->opfuncid) *
3089 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
3091 else if (IsA(node, Aggref) ||
3092 IsA(node, WindowFunc))
3095 * Aggref and WindowFunc nodes are (and should be) treated like Vars,
3096 * ie, zero execution cost in the current model, because they behave
3097 * essentially like Vars in execQual.c. We disregard the costs of
3098 * their input expressions for the same reason. The actual execution
3099 * costs of the aggregate/window functions and their arguments have to
3100 * be factored into plan-node-specific costing of the Agg or WindowAgg
3103 return false; /* don't recurse into children */
3105 else if (IsA(node, CoerceViaIO))
3107 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3112 /* check the result type's input function */
3113 getTypeInputInfo(iocoerce->resulttype,
3114 &iofunc, &typioparam);
3115 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3116 /* check the input type's output function */
3117 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
3118 &iofunc, &typisvarlena);
3119 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3121 else if (IsA(node, ArrayCoerceExpr))
3123 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3124 Node *arraynode = (Node *) acoerce->arg;
3126 if (OidIsValid(acoerce->elemfuncid))
3127 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
3128 cpu_operator_cost * estimate_array_length(arraynode);
3130 else if (IsA(node, RowCompareExpr))
3132 /* Conservatively assume we will check all the columns */
3133 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3136 foreach(lc, rcexpr->opnos)
3138 Oid opid = lfirst_oid(lc);
3140 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
3144 else if (IsA(node, CurrentOfExpr))
3146 /* Report high cost to prevent selection of anything but TID scan */
3147 context->total.startup += disable_cost;
3149 else if (IsA(node, SubLink))
3151 /* This routine should not be applied to un-planned expressions */
3152 elog(ERROR, "cannot handle unplanned sub-select");
3154 else if (IsA(node, SubPlan))
3157 * A subplan node in an expression typically indicates that the
3158 * subplan will be executed on each evaluation, so charge accordingly.
3159 * (Sub-selects that can be executed as InitPlans have already been
3160 * removed from the expression.)
3162 SubPlan *subplan = (SubPlan *) node;
3164 context->total.startup += subplan->startup_cost;
3165 context->total.per_tuple += subplan->per_call_cost;
3168 * We don't want to recurse into the testexpr, because it was already
3169 * counted in the SubPlan node's costs. So we're done.
3173 else if (IsA(node, AlternativeSubPlan))
3176 * Arbitrarily use the first alternative plan for costing. (We should
3177 * certainly only include one alternative, and we don't yet have
3178 * enough information to know which one the executor is most likely to
3181 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
3183 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
3187 /* recurse into children */
3188 return expression_tree_walker(node, cost_qual_eval_walker,
3193 * get_restriction_qual_cost
3194 * Compute evaluation costs of a baserel's restriction quals, plus any
3195 * movable join quals that have been pushed down to the scan.
3196 * Results are returned into *qpqual_cost.
3198 * This is a convenience subroutine that works for seqscans and other cases
3199 * where all the given quals will be evaluated the hard way. It's not useful
3200 * for cost_index(), for example, where the index machinery takes care of
3201 * some of the quals. We assume baserestrictcost was previously set by
3202 * set_baserel_size_estimates().
3205 get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
3206 ParamPathInfo *param_info,
3207 QualCost *qpqual_cost)
3211 /* Include costs of pushed-down clauses */
3212 cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
3214 qpqual_cost->startup += baserel->baserestrictcost.startup;
3215 qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
3218 *qpqual_cost = baserel->baserestrictcost;
3223 * compute_semi_anti_join_factors
3224 * Estimate how much of the inner input a SEMI or ANTI join
3225 * can be expected to scan.
3227 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
3228 * inner rows as soon as it finds a match to the current outer row.
3229 * We should therefore adjust some of the cost components for this effect.
3230 * This function computes some estimates needed for these adjustments.
3231 * These estimates will be the same regardless of the particular paths used
3232 * for the outer and inner relation, so we compute these once and then pass
3233 * them to all the join cost estimation functions.
3236 * outerrel: outer relation under consideration
3237 * innerrel: inner relation under consideration
3238 * jointype: must be JOIN_SEMI or JOIN_ANTI
3239 * sjinfo: SpecialJoinInfo relevant to this join
3240 * restrictlist: join quals
3241 * Output parameters:
3242 * *semifactors is filled in (see relation.h for field definitions)
3245 compute_semi_anti_join_factors(PlannerInfo *root,
3246 RelOptInfo *outerrel,
3247 RelOptInfo *innerrel,
3249 SpecialJoinInfo *sjinfo,
3251 SemiAntiJoinFactors *semifactors)
3255 Selectivity avgmatch;
3256 SpecialJoinInfo norm_sjinfo;
3260 /* Should only be called in these cases */
3261 Assert(jointype == JOIN_SEMI || jointype == JOIN_ANTI);
3264 * In an ANTI join, we must ignore clauses that are "pushed down", since
3265 * those won't affect the match logic. In a SEMI join, we do not
3266 * distinguish joinquals from "pushed down" quals, so just use the whole
3267 * restrictinfo list.
3269 if (jointype == JOIN_ANTI)
3272 foreach(l, restrictlist)
3274 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3276 Assert(IsA(rinfo, RestrictInfo));
3277 if (!rinfo->is_pushed_down)
3278 joinquals = lappend(joinquals, rinfo);
3282 joinquals = restrictlist;
3285 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
3287 jselec = clauselist_selectivity(root,
3294 * Also get the normal inner-join selectivity of the join clauses.
3296 norm_sjinfo.type = T_SpecialJoinInfo;
3297 norm_sjinfo.min_lefthand = outerrel->relids;
3298 norm_sjinfo.min_righthand = innerrel->relids;
3299 norm_sjinfo.syn_lefthand = outerrel->relids;
3300 norm_sjinfo.syn_righthand = innerrel->relids;
3301 norm_sjinfo.jointype = JOIN_INNER;
3302 /* we don't bother trying to make the remaining fields valid */
3303 norm_sjinfo.lhs_strict = false;
3304 norm_sjinfo.delay_upper_joins = false;
3305 norm_sjinfo.join_quals = NIL;
3307 nselec = clauselist_selectivity(root,
3313 /* Avoid leaking a lot of ListCells */
3314 if (jointype == JOIN_ANTI)
3315 list_free(joinquals);
3318 * jselec can be interpreted as the fraction of outer-rel rows that have
3319 * any matches (this is true for both SEMI and ANTI cases). And nselec is
3320 * the fraction of the Cartesian product that matches. So, the average
3321 * number of matches for each outer-rel row that has at least one match is
3322 * nselec * inner_rows / jselec.
3324 * Note: it is correct to use the inner rel's "rows" count here, even
3325 * though we might later be considering a parameterized inner path with
3326 * fewer rows. This is because we have included all the join clauses in
3327 * the selectivity estimate.
3329 if (jselec > 0) /* protect against zero divide */
3331 avgmatch = nselec * innerrel->rows / jselec;
3332 /* Clamp to sane range */
3333 avgmatch = Max(1.0, avgmatch);
3338 semifactors->outer_match_frac = jselec;
3339 semifactors->match_count = avgmatch;
3343 * has_indexed_join_quals
3344 * Check whether all the joinquals of a nestloop join are used as
3345 * inner index quals.
3347 * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
3348 * indexscan) that uses all the joinquals as indexquals, we can assume that an
3349 * unmatched outer tuple is cheap to process, whereas otherwise it's probably
3353 has_indexed_join_quals(NestPath *joinpath)
3355 Relids joinrelids = joinpath->path.parent->relids;
3356 Path *innerpath = joinpath->innerjoinpath;
3361 /* If join still has quals to evaluate, it's not fast */
3362 if (joinpath->joinrestrictinfo != NIL)
3364 /* Nor if the inner path isn't parameterized at all */
3365 if (innerpath->param_info == NULL)
3368 /* Find the indexclauses list for the inner scan */
3369 switch (innerpath->pathtype)
3372 case T_IndexOnlyScan:
3373 indexclauses = ((IndexPath *) innerpath)->indexclauses;
3375 case T_BitmapHeapScan:
3377 /* Accept only a simple bitmap scan, not AND/OR cases */
3378 Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
3380 if (IsA(bmqual, IndexPath))
3381 indexclauses = ((IndexPath *) bmqual)->indexclauses;
3389 * If it's not a simple indexscan, it probably doesn't run quickly
3390 * for zero rows out, even if it's a parameterized path using all
3397 * Examine the inner path's param clauses. Any that are from the outer
3398 * path must be found in the indexclauses list, either exactly or in an
3399 * equivalent form generated by equivclass.c. Also, we must find at least
3400 * one such clause, else it's a clauseless join which isn't fast.
3403 foreach(lc, innerpath->param_info->ppi_clauses)
3405 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3407 if (join_clause_is_movable_into(rinfo,
3408 innerpath->parent->relids,
3411 if (!(list_member_ptr(indexclauses, rinfo) ||
3412 is_redundant_derived_clause(rinfo, indexclauses)))
3422 * approx_tuple_count
3423 * Quick-and-dirty estimation of the number of join rows passing
3424 * a set of qual conditions.
3426 * The quals can be either an implicitly-ANDed list of boolean expressions,
3427 * or a list of RestrictInfo nodes (typically the latter).
3429 * We intentionally compute the selectivity under JOIN_INNER rules, even
3430 * if it's some type of outer join. This is appropriate because we are
3431 * trying to figure out how many tuples pass the initial merge or hash
3434 * This is quick-and-dirty because we bypass clauselist_selectivity, and
3435 * simply multiply the independent clause selectivities together. Now
3436 * clauselist_selectivity often can't do any better than that anyhow, but
3437 * for some situations (such as range constraints) it is smarter. However,
3438 * we can't effectively cache the results of clauselist_selectivity, whereas
3439 * the individual clause selectivities can be and are cached.
3441 * Since we are only using the results to estimate how many potential
3442 * output tuples are generated and passed through qpqual checking, it
3443 * seems OK to live with the approximation.
3446 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
3449 double outer_tuples = path->outerjoinpath->rows;
3450 double inner_tuples = path->innerjoinpath->rows;
3451 SpecialJoinInfo sjinfo;
3452 Selectivity selec = 1.0;
3456 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
3458 sjinfo.type = T_SpecialJoinInfo;
3459 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
3460 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
3461 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
3462 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
3463 sjinfo.jointype = JOIN_INNER;
3464 /* we don't bother trying to make the remaining fields valid */
3465 sjinfo.lhs_strict = false;
3466 sjinfo.delay_upper_joins = false;
3467 sjinfo.join_quals = NIL;
3469 /* Get the approximate selectivity */
3472 Node *qual = (Node *) lfirst(l);
3474 /* Note that clause_selectivity will be able to cache its result */
3475 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
3478 /* Apply it to the input relation sizes */
3479 tuples = selec * outer_tuples * inner_tuples;
3481 return clamp_row_est(tuples);
3486 * set_baserel_size_estimates
3487 * Set the size estimates for the given base relation.
3489 * The rel's targetlist and restrictinfo list must have been constructed
3490 * already, and rel->tuples must be set.
3492 * We set the following fields of the rel node:
3493 * rows: the estimated number of output tuples (after applying
3494 * restriction clauses).
3495 * width: the estimated average output tuple width in bytes.
3496 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
3499 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3503 /* Should only be applied to base relations */
3504 Assert(rel->relid > 0);
3506 nrows = rel->tuples *
3507 clauselist_selectivity(root,
3508 rel->baserestrictinfo,
3513 rel->rows = clamp_row_est(nrows);
3515 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3517 set_rel_width(root, rel);
3521 * get_parameterized_baserel_size
3522 * Make a size estimate for a parameterized scan of a base relation.
3524 * 'param_clauses' lists the additional join clauses to be used.
3526 * set_baserel_size_estimates must have been applied already.
3529 get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel,
3530 List *param_clauses)
3536 * Estimate the number of rows returned by the parameterized scan, knowing
3537 * that it will apply all the extra join clauses as well as the rel's own
3538 * restriction clauses. Note that we force the clauses to be treated as
3539 * non-join clauses during selectivity estimation.
3541 allclauses = list_concat(list_copy(param_clauses),
3542 rel->baserestrictinfo);
3543 nrows = rel->tuples *
3544 clauselist_selectivity(root,
3546 rel->relid, /* do not use 0! */
3549 nrows = clamp_row_est(nrows);
3550 /* For safety, make sure result is not more than the base estimate */
3551 if (nrows > rel->rows)
3557 * set_joinrel_size_estimates
3558 * Set the size estimates for the given join relation.
3560 * The rel's targetlist must have been constructed already, and a
3561 * restriction clause list that matches the given component rels must
3564 * Since there is more than one way to make a joinrel for more than two
3565 * base relations, the results we get here could depend on which component
3566 * rel pair is provided. In theory we should get the same answers no matter
3567 * which pair is provided; in practice, since the selectivity estimation
3568 * routines don't handle all cases equally well, we might not. But there's
3569 * not much to be done about it. (Would it make sense to repeat the
3570 * calculations for each pair of input rels that's encountered, and somehow
3571 * average the results? Probably way more trouble than it's worth, and
3572 * anyway we must keep the rowcount estimate the same for all paths for the
3575 * We set only the rows field here. The width field was already set by
3576 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3579 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3580 RelOptInfo *outer_rel,
3581 RelOptInfo *inner_rel,
3582 SpecialJoinInfo *sjinfo,
3585 rel->rows = calc_joinrel_size_estimate(root,
3593 * get_parameterized_joinrel_size
3594 * Make a size estimate for a parameterized scan of a join relation.
3596 * 'rel' is the joinrel under consideration.
3597 * 'outer_rows', 'inner_rows' are the sizes of the (probably also
3598 * parameterized) join inputs under consideration.
3599 * 'sjinfo' is any SpecialJoinInfo relevant to this join.
3600 * 'restrict_clauses' lists the join clauses that need to be applied at the
3601 * join node (including any movable clauses that were moved down to this join,
3602 * and not including any movable clauses that were pushed down into the
3605 * set_joinrel_size_estimates must have been applied already.
3608 get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel,
3611 SpecialJoinInfo *sjinfo,
3612 List *restrict_clauses)
3617 * Estimate the number of rows returned by the parameterized join as the
3618 * sizes of the input paths times the selectivity of the clauses that have
3619 * ended up at this join node.
3621 * As with set_joinrel_size_estimates, the rowcount estimate could depend
3622 * on the pair of input paths provided, though ideally we'd get the same
3623 * estimate for any pair with the same parameterization.
3625 nrows = calc_joinrel_size_estimate(root,
3630 /* For safety, make sure result is not more than the base estimate */
3631 if (nrows > rel->rows)
3637 * calc_joinrel_size_estimate
3638 * Workhorse for set_joinrel_size_estimates and
3639 * get_parameterized_joinrel_size.
3642 calc_joinrel_size_estimate(PlannerInfo *root,
3645 SpecialJoinInfo *sjinfo,
3648 JoinType jointype = sjinfo->jointype;
3654 * Compute joinclause selectivity. Note that we are only considering
3655 * clauses that become restriction clauses at this join level; we are not
3656 * double-counting them because they were not considered in estimating the
3657 * sizes of the component rels.
3659 * For an outer join, we have to distinguish the selectivity of the join's
3660 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3661 * down". For inner joins we just count them all as joinclauses.
3663 if (IS_OUTER_JOIN(jointype))
3665 List *joinquals = NIL;
3666 List *pushedquals = NIL;
3669 /* Grovel through the clauses to separate into two lists */
3670 foreach(l, restrictlist)
3672 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3674 Assert(IsA(rinfo, RestrictInfo));
3675 if (rinfo->is_pushed_down)
3676 pushedquals = lappend(pushedquals, rinfo);
3678 joinquals = lappend(joinquals, rinfo);
3681 /* Get the separate selectivities */
3682 jselec = clauselist_selectivity(root,
3687 pselec = clauselist_selectivity(root,
3693 /* Avoid leaking a lot of ListCells */
3694 list_free(joinquals);
3695 list_free(pushedquals);
3699 jselec = clauselist_selectivity(root,
3704 pselec = 0.0; /* not used, keep compiler quiet */
3708 * Basically, we multiply size of Cartesian product by selectivity.
3710 * If we are doing an outer join, take that into account: the joinqual
3711 * selectivity has to be clamped using the knowledge that the output must
3712 * be at least as large as the non-nullable input. However, any
3713 * pushed-down quals are applied after the outer join, so their
3714 * selectivity applies fully.
3716 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3717 * of LHS rows that have matches, and we apply that straightforwardly.
3722 nrows = outer_rows * inner_rows * jselec;
3725 nrows = outer_rows * inner_rows * jselec;
3726 if (nrows < outer_rows)
3731 nrows = outer_rows * inner_rows * jselec;
3732 if (nrows < outer_rows)
3734 if (nrows < inner_rows)
3739 nrows = outer_rows * jselec;
3740 /* pselec not used */
3743 nrows = outer_rows * (1.0 - jselec);
3747 /* other values not expected here */
3748 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3749 nrows = 0; /* keep compiler quiet */
3753 return clamp_row_est(nrows);
3757 * set_subquery_size_estimates
3758 * Set the size estimates for a base relation that is a subquery.
3760 * The rel's targetlist and restrictinfo list must have been constructed
3761 * already, and the plan for the subquery must have been completed.
3762 * We look at the subquery's plan and PlannerInfo to extract data.
3764 * We set the same fields as set_baserel_size_estimates.
3767 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3769 PlannerInfo *subroot = rel->subroot;
3770 RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
3773 /* Should only be applied to base relations that are subqueries */
3774 Assert(rel->relid > 0);
3775 rte = planner_rt_fetch(rel->relid, root);
3776 Assert(rte->rtekind == RTE_SUBQUERY);
3778 /* Copy raw number of output rows from subplan */
3779 rel->tuples = rel->subplan->plan_rows;
3782 * Compute per-output-column width estimates by examining the subquery's
3783 * targetlist. For any output that is a plain Var, get the width estimate
3784 * that was made while planning the subquery. Otherwise, we leave it to
3785 * set_rel_width to fill in a datatype-based default estimate.
3787 foreach(lc, subroot->parse->targetList)
3789 TargetEntry *te = (TargetEntry *) lfirst(lc);
3790 Node *texpr = (Node *) te->expr;
3791 int32 item_width = 0;
3793 Assert(IsA(te, TargetEntry));
3794 /* junk columns aren't visible to upper query */
3799 * The subquery could be an expansion of a view that's had columns
3800 * added to it since the current query was parsed, so that there are
3801 * non-junk tlist columns in it that don't correspond to any column
3802 * visible at our query level. Ignore such columns.
3804 if (te->resno < rel->min_attr || te->resno > rel->max_attr)
3808 * XXX This currently doesn't work for subqueries containing set
3809 * operations, because the Vars in their tlists are bogus references
3810 * to the first leaf subquery, which wouldn't give the right answer
3811 * even if we could still get to its PlannerInfo.
3813 * Also, the subquery could be an appendrel for which all branches are
3814 * known empty due to constraint exclusion, in which case
3815 * set_append_rel_pathlist will have left the attr_widths set to zero.
3817 * In either case, we just leave the width estimate zero until
3818 * set_rel_width fixes it.
3820 if (IsA(texpr, Var) &&
3821 subroot->parse->setOperations == NULL)
3823 Var *var = (Var *) texpr;
3824 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3826 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3828 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3831 /* Now estimate number of output rows, etc */
3832 set_baserel_size_estimates(root, rel);
3836 * set_function_size_estimates
3837 * Set the size estimates for a base relation that is a function call.
3839 * The rel's targetlist and restrictinfo list must have been constructed
3842 * We set the same fields as set_baserel_size_estimates.
3845 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3849 /* Should only be applied to base relations that are functions */
3850 Assert(rel->relid > 0);
3851 rte = planner_rt_fetch(rel->relid, root);
3852 Assert(rte->rtekind == RTE_FUNCTION);
3854 /* Estimate number of rows the function itself will return */
3855 rel->tuples = expression_returns_set_rows(rte->funcexpr);
3857 /* Now estimate number of output rows, etc */
3858 set_baserel_size_estimates(root, rel);
3862 * set_values_size_estimates
3863 * Set the size estimates for a base relation that is a values list.
3865 * The rel's targetlist and restrictinfo list must have been constructed
3868 * We set the same fields as set_baserel_size_estimates.
3871 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3875 /* Should only be applied to base relations that are values lists */
3876 Assert(rel->relid > 0);
3877 rte = planner_rt_fetch(rel->relid, root);
3878 Assert(rte->rtekind == RTE_VALUES);
3881 * Estimate number of rows the values list will return. We know this
3882 * precisely based on the list length (well, barring set-returning
3883 * functions in list items, but that's a refinement not catered for
3884 * anywhere else either).
3886 rel->tuples = list_length(rte->values_lists);
3888 /* Now estimate number of output rows, etc */
3889 set_baserel_size_estimates(root, rel);
3893 * set_cte_size_estimates
3894 * Set the size estimates for a base relation that is a CTE reference.
3896 * The rel's targetlist and restrictinfo list must have been constructed
3897 * already, and we need the completed plan for the CTE (if a regular CTE)
3898 * or the non-recursive term (if a self-reference).
3900 * We set the same fields as set_baserel_size_estimates.
3903 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3907 /* Should only be applied to base relations that are CTE references */
3908 Assert(rel->relid > 0);
3909 rte = planner_rt_fetch(rel->relid, root);
3910 Assert(rte->rtekind == RTE_CTE);
3912 if (rte->self_reference)
3915 * In a self-reference, arbitrarily assume the average worktable size
3916 * is about 10 times the nonrecursive term's size.
3918 rel->tuples = 10 * cteplan->plan_rows;
3922 /* Otherwise just believe the CTE plan's output estimate */
3923 rel->tuples = cteplan->plan_rows;
3926 /* Now estimate number of output rows, etc */
3927 set_baserel_size_estimates(root, rel);
3931 * set_foreign_size_estimates
3932 * Set the size estimates for a base relation that is a foreign table.
3934 * There is not a whole lot that we can do here; the foreign-data wrapper
3935 * is responsible for producing useful estimates. We can do a decent job
3936 * of estimating baserestrictcost, so we set that, and we also set up width
3937 * using what will be purely datatype-driven estimates from the targetlist.
3938 * There is no way to do anything sane with the rows value, so we just put
3939 * a default estimate and hope that the wrapper can improve on it. The
3940 * wrapper's GetForeignRelSize function will be called momentarily.
3942 * The rel's targetlist and restrictinfo list must have been constructed
3946 set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3948 /* Should only be applied to base relations */
3949 Assert(rel->relid > 0);
3951 rel->rows = 1000; /* entirely bogus default estimate */
3953 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3955 set_rel_width(root, rel);
3961 * Set the estimated output width of a base relation.
3963 * The estimated output width is the sum of the per-attribute width estimates
3964 * for the actually-referenced columns, plus any PHVs or other expressions
3965 * that have to be calculated at this relation. This is the amount of data
3966 * we'd need to pass upwards in case of a sort, hash, etc.
3968 * NB: this works best on plain relations because it prefers to look at
3969 * real Vars. For subqueries, set_subquery_size_estimates will already have
3970 * copied up whatever per-column estimates were made within the subquery,
3971 * and for other types of rels there isn't much we can do anyway. We fall
3972 * back on (fairly stupid) datatype-based width estimates if we can't get
3973 * any better number.
3975 * The per-attribute width estimates are cached for possible re-use while
3976 * building join relations.
3979 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3981 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3982 int32 tuple_width = 0;
3983 bool have_wholerow_var = false;
3986 foreach(lc, rel->reltargetlist)
3988 Node *node = (Node *) lfirst(lc);
3991 * Ordinarily, a Var in a rel's reltargetlist must belong to that rel;
3992 * but there are corner cases involving LATERAL references where that
3993 * isn't so. If the Var has the wrong varno, fall through to the
3994 * generic case (it doesn't seem worth the trouble to be any smarter).
3996 if (IsA(node, Var) &&
3997 ((Var *) node)->varno == rel->relid)
3999 Var *var = (Var *) node;
4003 Assert(var->varattno >= rel->min_attr);
4004 Assert(var->varattno <= rel->max_attr);
4006 ndx = var->varattno - rel->min_attr;
4009 * If it's a whole-row Var, we'll deal with it below after we have
4010 * already cached as many attr widths as possible.
4012 if (var->varattno == 0)
4014 have_wholerow_var = true;
4019 * The width may have been cached already (especially if it's a
4020 * subquery), so don't duplicate effort.
4022 if (rel->attr_widths[ndx] > 0)
4024 tuple_width += rel->attr_widths[ndx];
4028 /* Try to get column width from statistics */
4029 if (reloid != InvalidOid && var->varattno > 0)
4031 item_width = get_attavgwidth(reloid, var->varattno);
4034 rel->attr_widths[ndx] = item_width;
4035 tuple_width += item_width;
4041 * Not a plain relation, or can't find statistics for it. Estimate
4042 * using just the type info.
4044 item_width = get_typavgwidth(var->vartype, var->vartypmod);
4045 Assert(item_width > 0);
4046 rel->attr_widths[ndx] = item_width;
4047 tuple_width += item_width;
4049 else if (IsA(node, PlaceHolderVar))
4051 PlaceHolderVar *phv = (PlaceHolderVar *) node;
4052 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv, false);
4054 tuple_width += phinfo->ph_width;
4059 * We could be looking at an expression pulled up from a subquery,
4060 * or a ROW() representing a whole-row child Var, etc. Do what we
4061 * can using the expression type information.
4065 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
4066 Assert(item_width > 0);
4067 tuple_width += item_width;
4072 * If we have a whole-row reference, estimate its width as the sum of
4073 * per-column widths plus sizeof(HeapTupleHeaderData).
4075 if (have_wholerow_var)
4077 int32 wholerow_width = sizeof(HeapTupleHeaderData);
4079 if (reloid != InvalidOid)
4081 /* Real relation, so estimate true tuple width */
4082 wholerow_width += get_relation_data_width(reloid,
4083 rel->attr_widths - rel->min_attr);
4087 /* Do what we can with info for a phony rel */
4090 for (i = 1; i <= rel->max_attr; i++)
4091 wholerow_width += rel->attr_widths[i - rel->min_attr];
4094 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
4097 * Include the whole-row Var as part of the output tuple. Yes, that
4098 * really is what happens at runtime.
4100 tuple_width += wholerow_width;
4103 Assert(tuple_width >= 0);
4104 rel->width = tuple_width;
4108 * relation_byte_size
4109 * Estimate the storage space in bytes for a given number of tuples
4110 * of a given width (size in bytes).
4113 relation_byte_size(double tuples, int width)
4115 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
4120 * Returns an estimate of the number of pages covered by a given
4121 * number of tuples of a given width (size in bytes).
4124 page_size(double tuples, int width)
4126 return ceil(relation_byte_size(tuples, width) / BLCKSZ);