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->parent->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 startup_cost and total_cost
52 * results 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 non-cost fields of the passed XXXPath to be filled in.
58 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
59 * Portions Copyright (c) 1994, Regents of the University of California
62 * src/backend/optimizer/path/costsize.c
64 *-------------------------------------------------------------------------
71 #include "executor/executor.h"
72 #include "executor/nodeHash.h"
73 #include "miscadmin.h"
74 #include "nodes/nodeFuncs.h"
75 #include "optimizer/clauses.h"
76 #include "optimizer/cost.h"
77 #include "optimizer/pathnode.h"
78 #include "optimizer/placeholder.h"
79 #include "optimizer/plancat.h"
80 #include "optimizer/planmain.h"
81 #include "optimizer/restrictinfo.h"
82 #include "parser/parsetree.h"
83 #include "utils/lsyscache.h"
84 #include "utils/selfuncs.h"
85 #include "utils/spccache.h"
86 #include "utils/tuplesort.h"
89 #define LOG2(x) (log(x) / 0.693147180559945)
92 * Some Paths return less than the nominal number of rows of their parent
93 * relations; join nodes need to do this to get the correct input count:
95 #define PATH_ROWS(path) \
96 (IsA(path, UniquePath) ? \
97 ((UniquePath *) (path))->rows : \
101 double seq_page_cost = DEFAULT_SEQ_PAGE_COST;
102 double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
103 double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
104 double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
105 double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
107 int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
109 Cost disable_cost = 1.0e10;
111 bool enable_seqscan = true;
112 bool enable_indexscan = true;
113 bool enable_bitmapscan = true;
114 bool enable_tidscan = true;
115 bool enable_sort = true;
116 bool enable_hashagg = true;
117 bool enable_nestloop = true;
118 bool enable_material = true;
119 bool enable_mergejoin = true;
120 bool enable_hashjoin = true;
126 } cost_qual_eval_context;
128 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
131 static void cost_rescan(PlannerInfo *root, Path *path,
132 Cost *rescan_startup_cost, Cost *rescan_total_cost);
133 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
134 static bool adjust_semi_join(PlannerInfo *root, JoinPath *path,
135 SpecialJoinInfo *sjinfo,
136 Selectivity *outer_match_frac,
137 Selectivity *match_count,
138 bool *indexed_join_quals);
139 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
141 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
142 static double relation_byte_size(double tuples, int width);
143 static double page_size(double tuples, int width);
148 * Force a row-count estimate to a sane value.
151 clamp_row_est(double nrows)
154 * Force estimate to be at least one row, to make explain output look
155 * better and to avoid possible divide-by-zero when interpolating costs.
156 * Make it an integer, too.
169 * Determines and returns the cost of scanning a relation sequentially.
172 cost_seqscan(Path *path, PlannerInfo *root,
175 double spc_seq_page_cost;
176 Cost startup_cost = 0;
180 /* Should only be applied to base relations */
181 Assert(baserel->relid > 0);
182 Assert(baserel->rtekind == RTE_RELATION);
185 startup_cost += disable_cost;
187 /* fetch estimated page cost for tablespace containing table */
188 get_tablespace_page_costs(baserel->reltablespace,
195 run_cost += spc_seq_page_cost * baserel->pages;
198 startup_cost += baserel->baserestrictcost.startup;
199 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
200 run_cost += cpu_per_tuple * baserel->tuples;
202 path->startup_cost = startup_cost;
203 path->total_cost = startup_cost + run_cost;
208 * Determines and returns the cost of scanning a relation using an index.
210 * 'index' is the index to be used
211 * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
212 * 'indexOrderBys' is the list of ORDER BY operators for amcanorderbyop indexes
213 * 'outer_rel' is the outer relation when we are considering using the index
214 * scan as the inside of a nestloop join (hence, some of the indexQuals
215 * are join clauses, and we should expect repeated scans of the index);
216 * NULL for a plain index scan
218 * cost_index() takes an IndexPath not just a Path, because it sets a few
219 * additional fields of the IndexPath besides startup_cost and total_cost.
220 * These fields are needed if the IndexPath is used in a BitmapIndexScan.
222 * indexQuals is a list of RestrictInfo nodes, but indexOrderBys is a list of
225 * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
226 * Any additional quals evaluated as qpquals may reduce the number of returned
227 * tuples, but they won't reduce the number of tuples we have to fetch from
228 * the table, so they don't reduce the scan cost.
231 cost_index(IndexPath *path, PlannerInfo *root,
235 RelOptInfo *outer_rel)
237 RelOptInfo *baserel = index->rel;
238 Cost startup_cost = 0;
240 Cost indexStartupCost;
242 Selectivity indexSelectivity;
243 double indexCorrelation,
245 double spc_seq_page_cost,
246 spc_random_page_cost;
250 double tuples_fetched;
251 double pages_fetched;
253 /* Should only be applied to base relations */
254 Assert(IsA(baserel, RelOptInfo) &&
255 IsA(index, IndexOptInfo));
256 Assert(baserel->relid > 0);
257 Assert(baserel->rtekind == RTE_RELATION);
259 if (!enable_indexscan)
260 startup_cost += disable_cost;
263 * Call index-access-method-specific code to estimate the processing cost
264 * for scanning the index, as well as the selectivity of the index (ie,
265 * the fraction of main-table tuples we will have to retrieve) and its
266 * correlation to the main-table tuple order.
268 OidFunctionCall9(index->amcostestimate,
269 PointerGetDatum(root),
270 PointerGetDatum(index),
271 PointerGetDatum(indexQuals),
272 PointerGetDatum(indexOrderBys),
273 PointerGetDatum(outer_rel),
274 PointerGetDatum(&indexStartupCost),
275 PointerGetDatum(&indexTotalCost),
276 PointerGetDatum(&indexSelectivity),
277 PointerGetDatum(&indexCorrelation));
280 * Save amcostestimate's results for possible use in bitmap scan planning.
281 * We don't bother to save indexStartupCost or indexCorrelation, because a
282 * bitmap scan doesn't care about either.
284 path->indextotalcost = indexTotalCost;
285 path->indexselectivity = indexSelectivity;
287 /* all costs for touching index itself included here */
288 startup_cost += indexStartupCost;
289 run_cost += indexTotalCost - indexStartupCost;
291 /* estimate number of main-table tuples fetched */
292 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
294 /* fetch estimated page costs for tablespace containing table */
295 get_tablespace_page_costs(baserel->reltablespace,
296 &spc_random_page_cost,
300 * Estimate number of main-table pages fetched, and compute I/O cost.
302 * When the index ordering is uncorrelated with the table ordering,
303 * we use an approximation proposed by Mackert and Lohman (see
304 * index_pages_fetched() for details) to compute the number of pages
305 * fetched, and then charge spc_random_page_cost per page fetched.
307 * When the index ordering is exactly correlated with the table ordering
308 * (just after a CLUSTER, for example), the number of pages fetched should
309 * be exactly selectivity * table_size. What's more, all but the first
310 * will be sequential fetches, not the random fetches that occur in the
311 * uncorrelated case. So if the number of pages is more than 1, we
313 * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
314 * For partially-correlated indexes, we ought to charge somewhere between
315 * these two estimates. We currently interpolate linearly between the
316 * estimates based on the correlation squared (XXX is that appropriate?).
319 if (outer_rel != NULL && outer_rel->rows > 1)
322 * For repeated indexscans, the appropriate estimate for the
323 * uncorrelated case is to scale up the number of tuples fetched in
324 * the Mackert and Lohman formula by the number of scans, so that we
325 * estimate the number of pages fetched by all the scans; then
326 * pro-rate the costs for one scan. In this case we assume all the
327 * fetches are random accesses.
329 double num_scans = outer_rel->rows;
331 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
333 (double) index->pages,
336 max_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
339 * In the perfectly correlated case, the number of pages touched by
340 * each scan is selectivity * table_size, and we can use the Mackert
341 * and Lohman formula at the page level to estimate how much work is
342 * saved by caching across scans. We still assume all the fetches are
343 * random, though, which is an overestimate that's hard to correct for
344 * without double-counting the cache effects. (But in most cases
345 * where such a plan is actually interesting, only one page would get
346 * fetched per scan anyway, so it shouldn't matter much.)
348 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
350 pages_fetched = index_pages_fetched(pages_fetched * num_scans,
352 (double) index->pages,
355 min_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
360 * Normal case: apply the Mackert and Lohman formula, and then
361 * interpolate between that and the correlation-derived result.
363 pages_fetched = index_pages_fetched(tuples_fetched,
365 (double) index->pages,
368 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
369 max_IO_cost = pages_fetched * spc_random_page_cost;
371 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
372 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
373 min_IO_cost = spc_random_page_cost;
374 if (pages_fetched > 1)
375 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
379 * Now interpolate based on estimated index order correlation to get total
380 * disk I/O cost for main table accesses.
382 csquared = indexCorrelation * indexCorrelation;
384 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
387 * Estimate CPU costs per tuple.
389 * Normally the indexquals will be removed from the list of restriction
390 * clauses that we have to evaluate as qpquals, so we should subtract
391 * their costs from baserestrictcost. But if we are doing a join then
392 * some of the indexquals are join clauses and shouldn't be subtracted.
393 * Rather than work out exactly how much to subtract, we don't subtract
396 startup_cost += baserel->baserestrictcost.startup;
397 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
399 if (outer_rel == NULL)
401 QualCost index_qual_cost;
403 cost_qual_eval(&index_qual_cost, indexQuals, root);
404 /* any startup cost still has to be paid ... */
405 cpu_per_tuple -= index_qual_cost.per_tuple;
408 run_cost += cpu_per_tuple * tuples_fetched;
410 path->path.startup_cost = startup_cost;
411 path->path.total_cost = startup_cost + run_cost;
415 * index_pages_fetched
416 * Estimate the number of pages actually fetched after accounting for
419 * We use an approximation proposed by Mackert and Lohman, "Index Scans
420 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
421 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
422 * The Mackert and Lohman approximation is that the number of pages
425 * min(2TNs/(2T+Ns), T) when T <= b
426 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
427 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
429 * T = # pages in table
430 * N = # tuples in table
431 * s = selectivity = fraction of table to be scanned
432 * b = # buffer pages available (we include kernel space here)
434 * We assume that effective_cache_size is the total number of buffer pages
435 * available for the whole query, and pro-rate that space across all the
436 * tables in the query and the index currently under consideration. (This
437 * ignores space needed for other indexes used by the query, but since we
438 * don't know which indexes will get used, we can't estimate that very well;
439 * and in any case counting all the tables may well be an overestimate, since
440 * depending on the join plan not all the tables may be scanned concurrently.)
442 * The product Ns is the number of tuples fetched; we pass in that
443 * product rather than calculating it here. "pages" is the number of pages
444 * in the object under consideration (either an index or a table).
445 * "index_pages" is the amount to add to the total table space, which was
446 * computed for us by query_planner.
448 * Caller is expected to have ensured that tuples_fetched is greater than zero
449 * and rounded to integer (see clamp_row_est). The result will likewise be
450 * greater than zero and integral.
453 index_pages_fetched(double tuples_fetched, BlockNumber pages,
454 double index_pages, PlannerInfo *root)
456 double pages_fetched;
461 /* T is # pages in table, but don't allow it to be zero */
462 T = (pages > 1) ? (double) pages : 1.0;
464 /* Compute number of pages assumed to be competing for cache space */
465 total_pages = root->total_table_pages + index_pages;
466 total_pages = Max(total_pages, 1.0);
467 Assert(T <= total_pages);
469 /* b is pro-rated share of effective_cache_size */
470 b = (double) effective_cache_size *T / total_pages;
472 /* force it positive and integral */
478 /* This part is the Mackert and Lohman formula */
482 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
483 if (pages_fetched >= T)
486 pages_fetched = ceil(pages_fetched);
492 lim = (2.0 * T * b) / (2.0 * T - b);
493 if (tuples_fetched <= lim)
496 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
501 b + (tuples_fetched - lim) * (T - b) / T;
503 pages_fetched = ceil(pages_fetched);
505 return pages_fetched;
509 * get_indexpath_pages
510 * Determine the total size of the indexes used in a bitmap index path.
512 * Note: if the same index is used more than once in a bitmap tree, we will
513 * count it multiple times, which perhaps is the wrong thing ... but it's
514 * not completely clear, and detecting duplicates is difficult, so ignore it
518 get_indexpath_pages(Path *bitmapqual)
523 if (IsA(bitmapqual, BitmapAndPath))
525 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
527 foreach(l, apath->bitmapquals)
529 result += get_indexpath_pages((Path *) lfirst(l));
532 else if (IsA(bitmapqual, BitmapOrPath))
534 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
536 foreach(l, opath->bitmapquals)
538 result += get_indexpath_pages((Path *) lfirst(l));
541 else if (IsA(bitmapqual, IndexPath))
543 IndexPath *ipath = (IndexPath *) bitmapqual;
545 result = (double) ipath->indexinfo->pages;
548 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
554 * cost_bitmap_heap_scan
555 * Determines and returns the cost of scanning a relation using a bitmap
556 * index-then-heap plan.
558 * 'baserel' is the relation to be scanned
559 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
560 * 'outer_rel' is the outer relation when we are considering using the bitmap
561 * scan as the inside of a nestloop join (hence, some of the indexQuals
562 * are join clauses, and we should expect repeated scans of the table);
563 * NULL for a plain bitmap scan
565 * Note: if this is a join inner path, the component IndexPaths in bitmapqual
566 * should have been costed accordingly.
569 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
570 Path *bitmapqual, RelOptInfo *outer_rel)
572 Cost startup_cost = 0;
575 Selectivity indexSelectivity;
578 double tuples_fetched;
579 double pages_fetched;
580 double spc_seq_page_cost,
581 spc_random_page_cost;
584 /* Should only be applied to base relations */
585 Assert(IsA(baserel, RelOptInfo));
586 Assert(baserel->relid > 0);
587 Assert(baserel->rtekind == RTE_RELATION);
589 if (!enable_bitmapscan)
590 startup_cost += disable_cost;
593 * Fetch total cost of obtaining the bitmap, as well as its total
596 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
598 startup_cost += indexTotalCost;
600 /* Fetch estimated page costs for tablespace containing table. */
601 get_tablespace_page_costs(baserel->reltablespace,
602 &spc_random_page_cost,
606 * Estimate number of main-table pages fetched.
608 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
610 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
612 if (outer_rel != NULL && outer_rel->rows > 1)
615 * For repeated bitmap scans, scale up the number of tuples fetched in
616 * the Mackert and Lohman formula by the number of scans, so that we
617 * estimate the number of pages fetched by all the scans. Then
618 * pro-rate for one scan.
620 double num_scans = outer_rel->rows;
622 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
624 get_indexpath_pages(bitmapqual),
626 pages_fetched /= num_scans;
631 * For a single scan, the number of heap pages that need to be fetched
632 * is the same as the Mackert and Lohman formula for the case T <= b
633 * (ie, no re-reads needed).
635 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
637 if (pages_fetched >= T)
640 pages_fetched = ceil(pages_fetched);
643 * For small numbers of pages we should charge spc_random_page_cost
644 * apiece, while if nearly all the table's pages are being read, it's more
645 * appropriate to charge spc_seq_page_cost apiece. The effect is
646 * nonlinear, too. For lack of a better idea, interpolate like this to
647 * determine the cost per page.
649 if (pages_fetched >= 2.0)
650 cost_per_page = spc_random_page_cost -
651 (spc_random_page_cost - spc_seq_page_cost)
652 * sqrt(pages_fetched / T);
654 cost_per_page = spc_random_page_cost;
656 run_cost += pages_fetched * cost_per_page;
659 * Estimate CPU costs per tuple.
661 * Often the indexquals don't need to be rechecked at each tuple ... but
662 * not always, especially not if there are enough tuples involved that the
663 * bitmaps become lossy. For the moment, just assume they will be
666 startup_cost += baserel->baserestrictcost.startup;
667 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
669 run_cost += cpu_per_tuple * tuples_fetched;
671 path->startup_cost = startup_cost;
672 path->total_cost = startup_cost + run_cost;
676 * cost_bitmap_tree_node
677 * Extract cost and selectivity from a bitmap tree node (index/and/or)
680 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
682 if (IsA(path, IndexPath))
684 *cost = ((IndexPath *) path)->indextotalcost;
685 *selec = ((IndexPath *) path)->indexselectivity;
688 * Charge a small amount per retrieved tuple to reflect the costs of
689 * manipulating the bitmap. This is mostly to make sure that a bitmap
690 * scan doesn't look to be the same cost as an indexscan to retrieve a
693 *cost += 0.1 * cpu_operator_cost * ((IndexPath *) path)->rows;
695 else if (IsA(path, BitmapAndPath))
697 *cost = path->total_cost;
698 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
700 else if (IsA(path, BitmapOrPath))
702 *cost = path->total_cost;
703 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
707 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
708 *cost = *selec = 0; /* keep compiler quiet */
713 * cost_bitmap_and_node
714 * Estimate the cost of a BitmapAnd node
716 * Note that this considers only the costs of index scanning and bitmap
717 * creation, not the eventual heap access. In that sense the object isn't
718 * truly a Path, but it has enough path-like properties (costs in particular)
719 * to warrant treating it as one.
722 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
729 * We estimate AND selectivity on the assumption that the inputs are
730 * independent. This is probably often wrong, but we don't have the info
733 * The runtime cost of the BitmapAnd itself is estimated at 100x
734 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
735 * definitely too simplistic?
739 foreach(l, path->bitmapquals)
741 Path *subpath = (Path *) lfirst(l);
743 Selectivity subselec;
745 cost_bitmap_tree_node(subpath, &subCost, &subselec);
749 totalCost += subCost;
750 if (l != list_head(path->bitmapquals))
751 totalCost += 100.0 * cpu_operator_cost;
753 path->bitmapselectivity = selec;
754 path->path.startup_cost = totalCost;
755 path->path.total_cost = totalCost;
759 * cost_bitmap_or_node
760 * Estimate the cost of a BitmapOr node
762 * See comments for cost_bitmap_and_node.
765 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
772 * We estimate OR selectivity on the assumption that the inputs are
773 * non-overlapping, since that's often the case in "x IN (list)" type
774 * situations. Of course, we clamp to 1.0 at the end.
776 * The runtime cost of the BitmapOr itself is estimated at 100x
777 * cpu_operator_cost for each tbm_union needed. Probably too small,
778 * definitely too simplistic? We are aware that the tbm_unions are
779 * optimized out when the inputs are BitmapIndexScans.
783 foreach(l, path->bitmapquals)
785 Path *subpath = (Path *) lfirst(l);
787 Selectivity subselec;
789 cost_bitmap_tree_node(subpath, &subCost, &subselec);
793 totalCost += subCost;
794 if (l != list_head(path->bitmapquals) &&
795 !IsA(subpath, IndexPath))
796 totalCost += 100.0 * cpu_operator_cost;
798 path->bitmapselectivity = Min(selec, 1.0);
799 path->path.startup_cost = totalCost;
800 path->path.total_cost = totalCost;
805 * Determines and returns the cost of scanning a relation using TIDs.
808 cost_tidscan(Path *path, PlannerInfo *root,
809 RelOptInfo *baserel, List *tidquals)
811 Cost startup_cost = 0;
813 bool isCurrentOf = false;
815 QualCost tid_qual_cost;
818 double spc_random_page_cost;
820 /* Should only be applied to base relations */
821 Assert(baserel->relid > 0);
822 Assert(baserel->rtekind == RTE_RELATION);
824 /* Count how many tuples we expect to retrieve */
828 if (IsA(lfirst(l), ScalarArrayOpExpr))
830 /* Each element of the array yields 1 tuple */
831 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
832 Node *arraynode = (Node *) lsecond(saop->args);
834 ntuples += estimate_array_length(arraynode);
836 else if (IsA(lfirst(l), CurrentOfExpr))
838 /* CURRENT OF yields 1 tuple */
844 /* It's just CTID = something, count 1 tuple */
850 * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
851 * understands how to do it correctly. Therefore, honor enable_tidscan
852 * only when CURRENT OF isn't present. Also note that cost_qual_eval
853 * counts a CurrentOfExpr as having startup cost disable_cost, which we
854 * subtract off here; that's to prevent other plan types such as seqscan
859 Assert(baserel->baserestrictcost.startup >= disable_cost);
860 startup_cost -= disable_cost;
862 else if (!enable_tidscan)
863 startup_cost += disable_cost;
866 * The TID qual expressions will be computed once, any other baserestrict
867 * quals once per retrived tuple.
869 cost_qual_eval(&tid_qual_cost, tidquals, root);
871 /* fetch estimated page cost for tablespace containing table */
872 get_tablespace_page_costs(baserel->reltablespace,
873 &spc_random_page_cost,
876 /* disk costs --- assume each tuple on a different page */
877 run_cost += spc_random_page_cost * ntuples;
880 startup_cost += baserel->baserestrictcost.startup +
881 tid_qual_cost.per_tuple;
882 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple -
883 tid_qual_cost.per_tuple;
884 run_cost += cpu_per_tuple * ntuples;
886 path->startup_cost = startup_cost;
887 path->total_cost = startup_cost + run_cost;
892 * Determines and returns the cost of scanning a subquery RTE.
895 cost_subqueryscan(Path *path, RelOptInfo *baserel)
901 /* Should only be applied to base relations that are subqueries */
902 Assert(baserel->relid > 0);
903 Assert(baserel->rtekind == RTE_SUBQUERY);
906 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
907 * any restriction clauses that will be attached to the SubqueryScan node,
908 * plus cpu_tuple_cost to account for selection and projection overhead.
910 path->startup_cost = baserel->subplan->startup_cost;
911 path->total_cost = baserel->subplan->total_cost;
913 startup_cost = baserel->baserestrictcost.startup;
914 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
915 run_cost = cpu_per_tuple * baserel->tuples;
917 path->startup_cost += startup_cost;
918 path->total_cost += startup_cost + run_cost;
923 * Determines and returns the cost of scanning a function RTE.
926 cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
928 Cost startup_cost = 0;
934 /* Should only be applied to base relations that are functions */
935 Assert(baserel->relid > 0);
936 rte = planner_rt_fetch(baserel->relid, root);
937 Assert(rte->rtekind == RTE_FUNCTION);
940 * Estimate costs of executing the function expression.
942 * Currently, nodeFunctionscan.c always executes the function to
943 * completion before returning any rows, and caches the results in a
944 * tuplestore. So the function eval cost is all startup cost, and per-row
947 * XXX in principle we ought to charge tuplestore spill costs if the
948 * number of rows is large. However, given how phony our rowcount
949 * estimates for functions tend to be, there's not a lot of point in that
950 * refinement right now.
952 cost_qual_eval_node(&exprcost, rte->funcexpr, root);
954 startup_cost += exprcost.startup + exprcost.per_tuple;
956 /* Add scanning CPU costs */
957 startup_cost += baserel->baserestrictcost.startup;
958 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
959 run_cost += cpu_per_tuple * baserel->tuples;
961 path->startup_cost = startup_cost;
962 path->total_cost = startup_cost + run_cost;
967 * Determines and returns the cost of scanning a VALUES RTE.
970 cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
972 Cost startup_cost = 0;
976 /* Should only be applied to base relations that are values lists */
977 Assert(baserel->relid > 0);
978 Assert(baserel->rtekind == RTE_VALUES);
981 * For now, estimate list evaluation cost at one operator eval per list
982 * (probably pretty bogus, but is it worth being smarter?)
984 cpu_per_tuple = cpu_operator_cost;
986 /* Add scanning CPU costs */
987 startup_cost += baserel->baserestrictcost.startup;
988 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
989 run_cost += cpu_per_tuple * baserel->tuples;
991 path->startup_cost = startup_cost;
992 path->total_cost = startup_cost + run_cost;
997 * Determines and returns the cost of scanning a CTE RTE.
999 * Note: this is used for both self-reference and regular CTEs; the
1000 * possible cost differences are below the threshold of what we could
1001 * estimate accurately anyway. Note that the costs of evaluating the
1002 * referenced CTE query are added into the final plan as initplan costs,
1003 * and should NOT be counted here.
1006 cost_ctescan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
1008 Cost startup_cost = 0;
1012 /* Should only be applied to base relations that are CTEs */
1013 Assert(baserel->relid > 0);
1014 Assert(baserel->rtekind == RTE_CTE);
1016 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1017 cpu_per_tuple = cpu_tuple_cost;
1019 /* Add scanning CPU costs */
1020 startup_cost += baserel->baserestrictcost.startup;
1021 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
1022 run_cost += cpu_per_tuple * baserel->tuples;
1024 path->startup_cost = startup_cost;
1025 path->total_cost = startup_cost + run_cost;
1029 * cost_recursive_union
1030 * Determines and returns the cost of performing a recursive union,
1031 * and also the estimated output size.
1033 * We are given Plans for the nonrecursive and recursive terms.
1035 * Note that the arguments and output are Plans, not Paths as in most of
1036 * the rest of this module. That's because we don't bother setting up a
1037 * Path representation for recursive union --- we have only one way to do it.
1040 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1046 /* We probably have decent estimates for the non-recursive term */
1047 startup_cost = nrterm->startup_cost;
1048 total_cost = nrterm->total_cost;
1049 total_rows = nrterm->plan_rows;
1052 * We arbitrarily assume that about 10 recursive iterations will be
1053 * needed, and that we've managed to get a good fix on the cost and output
1054 * size of each one of them. These are mighty shaky assumptions but it's
1055 * hard to see how to do better.
1057 total_cost += 10 * rterm->total_cost;
1058 total_rows += 10 * rterm->plan_rows;
1061 * Also charge cpu_tuple_cost per row to account for the costs of
1062 * manipulating the tuplestores. (We don't worry about possible
1063 * spill-to-disk costs.)
1065 total_cost += cpu_tuple_cost * total_rows;
1067 runion->startup_cost = startup_cost;
1068 runion->total_cost = total_cost;
1069 runion->plan_rows = total_rows;
1070 runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1075 * Determines and returns the cost of sorting a relation, including
1076 * the cost of reading the input data.
1078 * If the total volume of data to sort is less than sort_mem, we will do
1079 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1080 * comparisons for t tuples.
1082 * If the total volume exceeds sort_mem, we switch to a tape-style merge
1083 * algorithm. There will still be about t*log2(t) tuple comparisons in
1084 * total, but we will also need to write and read each tuple once per
1085 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1086 * number of initial runs formed and M is the merge order used by tuplesort.c.
1087 * Since the average initial run should be about twice sort_mem, we have
1088 * disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
1089 * cpu = comparison_cost * t * log2(t)
1091 * If the sort is bounded (i.e., only the first k result tuples are needed)
1092 * and k tuples can fit into sort_mem, we use a heap method that keeps only
1093 * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1095 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1096 * accesses (XXX can't we refine that guess?)
1098 * By default, we charge two operator evals per tuple comparison, which should
1099 * be in the right ballpark in most cases. The caller can tweak this by
1100 * specifying nonzero comparison_cost; typically that's used for any extra
1101 * work that has to be done to prepare the inputs to the comparison operators.
1103 * 'pathkeys' is a list of sort keys
1104 * 'input_cost' is the total cost for reading the input data
1105 * 'tuples' is the number of tuples in the relation
1106 * 'width' is the average tuple width in bytes
1107 * 'comparison_cost' is the extra cost per comparison, if any
1108 * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1109 * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1111 * NOTE: some callers currently pass NIL for pathkeys because they
1112 * can't conveniently supply the sort keys. Since this routine doesn't
1113 * currently do anything with pathkeys anyway, that doesn't matter...
1114 * but if it ever does, it should react gracefully to lack of key data.
1115 * (Actually, the thing we'd most likely be interested in is just the number
1116 * of sort keys, which all callers *could* supply.)
1119 cost_sort(Path *path, PlannerInfo *root,
1120 List *pathkeys, Cost input_cost, double tuples, int width,
1121 Cost comparison_cost, int sort_mem,
1122 double limit_tuples)
1124 Cost startup_cost = input_cost;
1126 double input_bytes = relation_byte_size(tuples, width);
1127 double output_bytes;
1128 double output_tuples;
1129 long sort_mem_bytes = sort_mem * 1024L;
1132 startup_cost += disable_cost;
1135 * We want to be sure the cost of a sort is never estimated as zero, even
1136 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1141 /* Include the default cost-per-comparison */
1142 comparison_cost += 2.0 * cpu_operator_cost;
1144 /* Do we have a useful LIMIT? */
1145 if (limit_tuples > 0 && limit_tuples < tuples)
1147 output_tuples = limit_tuples;
1148 output_bytes = relation_byte_size(output_tuples, width);
1152 output_tuples = tuples;
1153 output_bytes = input_bytes;
1156 if (output_bytes > sort_mem_bytes)
1159 * We'll have to use a disk-based sort of all the tuples
1161 double npages = ceil(input_bytes / BLCKSZ);
1162 double nruns = (input_bytes / sort_mem_bytes) * 0.5;
1163 double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1165 double npageaccesses;
1170 * Assume about N log2 N comparisons
1172 startup_cost += comparison_cost * tuples * LOG2(tuples);
1176 /* Compute logM(r) as log(r) / log(M) */
1177 if (nruns > mergeorder)
1178 log_runs = ceil(log(nruns) / log(mergeorder));
1181 npageaccesses = 2.0 * npages * log_runs;
1182 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1183 startup_cost += npageaccesses *
1184 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1186 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1189 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1190 * a total number of tuple comparisons of N log2 K; but the constant
1191 * factor is a bit higher than for quicksort. Tweak it so that the
1192 * cost curve is continuous at the crossover point.
1194 startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1198 /* We'll use plain quicksort on all the input tuples */
1199 startup_cost += comparison_cost * tuples * LOG2(tuples);
1203 * Also charge a small amount (arbitrarily set equal to operator cost) per
1204 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1205 * doesn't do qual-checking or projection, so it has less overhead than
1206 * most plan nodes. Note it's correct to use tuples not output_tuples
1207 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1208 * counting the LIMIT otherwise.
1210 run_cost += cpu_operator_cost * tuples;
1212 path->startup_cost = startup_cost;
1213 path->total_cost = startup_cost + run_cost;
1218 * Determines and returns the cost of a MergeAppend node.
1220 * MergeAppend merges several pre-sorted input streams, using a heap that
1221 * at any given instant holds the next tuple from each stream. If there
1222 * are N streams, we need about N*log2(N) tuple comparisons to construct
1223 * the heap at startup, and then for each output tuple, about log2(N)
1224 * comparisons to delete the top heap entry and another log2(N) comparisons
1225 * to insert its successor from the same stream.
1227 * (The effective value of N will drop once some of the input streams are
1228 * exhausted, but it seems unlikely to be worth trying to account for that.)
1230 * The heap is never spilled to disk, since we assume N is not very large.
1231 * So this is much simpler than cost_sort.
1233 * As in cost_sort, we charge two operator evals per tuple comparison.
1235 * 'pathkeys' is a list of sort keys
1236 * 'n_streams' is the number of input streams
1237 * 'input_startup_cost' is the sum of the input streams' startup costs
1238 * 'input_total_cost' is the sum of the input streams' total costs
1239 * 'tuples' is the number of tuples in all the streams
1242 cost_merge_append(Path *path, PlannerInfo *root,
1243 List *pathkeys, int n_streams,
1244 Cost input_startup_cost, Cost input_total_cost,
1247 Cost startup_cost = 0;
1249 Cost comparison_cost;
1256 N = (n_streams < 2) ? 2.0 : (double) n_streams;
1259 /* Assumed cost per tuple comparison */
1260 comparison_cost = 2.0 * cpu_operator_cost;
1262 /* Heap creation cost */
1263 startup_cost += comparison_cost * N * logN;
1265 /* Per-tuple heap maintenance cost */
1266 run_cost += tuples * comparison_cost * 2.0 * logN;
1269 * Also charge a small amount (arbitrarily set equal to operator cost) per
1270 * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1271 * node doesn't do qual-checking or projection, so it has less overhead
1272 * than most plan nodes.
1274 run_cost += cpu_operator_cost * tuples;
1276 path->startup_cost = startup_cost + input_startup_cost;
1277 path->total_cost = startup_cost + run_cost + input_total_cost;
1282 * Determines and returns the cost of materializing a relation, including
1283 * the cost of reading the input data.
1285 * If the total volume of data to materialize exceeds work_mem, we will need
1286 * to write it to disk, so the cost is much higher in that case.
1288 * Note that here we are estimating the costs for the first scan of the
1289 * relation, so the materialization is all overhead --- any savings will
1290 * occur only on rescan, which is estimated in cost_rescan.
1293 cost_material(Path *path,
1294 Cost input_startup_cost, Cost input_total_cost,
1295 double tuples, int width)
1297 Cost startup_cost = input_startup_cost;
1298 Cost run_cost = input_total_cost - input_startup_cost;
1299 double nbytes = relation_byte_size(tuples, width);
1300 long work_mem_bytes = work_mem * 1024L;
1303 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1304 * reflect bookkeeping overhead. (This rate must be more than what
1305 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1306 * if it is exactly the same then there will be a cost tie between
1307 * nestloop with A outer, materialized B inner and nestloop with B outer,
1308 * materialized A inner. The extra cost ensures we'll prefer
1309 * materializing the smaller rel.) Note that this is normally a good deal
1310 * less than cpu_tuple_cost; which is OK because a Material plan node
1311 * doesn't do qual-checking or projection, so it's got less overhead than
1314 run_cost += 2 * cpu_operator_cost * tuples;
1317 * If we will spill to disk, charge at the rate of seq_page_cost per page.
1318 * This cost is assumed to be evenly spread through the plan run phase,
1319 * which isn't exactly accurate but our cost model doesn't allow for
1320 * nonuniform costs within the run phase.
1322 if (nbytes > work_mem_bytes)
1324 double npages = ceil(nbytes / BLCKSZ);
1326 run_cost += seq_page_cost * npages;
1329 path->startup_cost = startup_cost;
1330 path->total_cost = startup_cost + run_cost;
1335 * Determines and returns the cost of performing an Agg plan node,
1336 * including the cost of its input.
1338 * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
1339 * we are using a hashed Agg node just to do grouping).
1341 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1342 * are for appropriately-sorted input.
1345 cost_agg(Path *path, PlannerInfo *root,
1346 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
1347 int numGroupCols, double numGroups,
1348 Cost input_startup_cost, Cost input_total_cost,
1349 double input_tuples)
1353 AggClauseCosts dummy_aggcosts;
1355 /* Use all-zero per-aggregate costs if NULL is passed */
1356 if (aggcosts == NULL)
1358 Assert(aggstrategy == AGG_HASHED);
1359 MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1360 aggcosts = &dummy_aggcosts;
1364 * The transCost.per_tuple component of aggcosts should be charged once
1365 * per input tuple, corresponding to the costs of evaluating the aggregate
1366 * transfns and their input expressions (with any startup cost of course
1367 * charged but once). The finalCost component is charged once per output
1368 * tuple, corresponding to the costs of evaluating the finalfns.
1370 * If we are grouping, we charge an additional cpu_operator_cost per
1371 * grouping column per input tuple for grouping comparisons.
1373 * We will produce a single output tuple if not grouping, and a tuple per
1374 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1376 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1377 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1378 * input path is already sorted appropriately, AGG_SORTED should be
1379 * preferred (since it has no risk of memory overflow). This will happen
1380 * as long as the computed total costs are indeed exactly equal --- but if
1381 * there's roundoff error we might do the wrong thing. So be sure that
1382 * the computations below form the same intermediate values in the same
1385 if (aggstrategy == AGG_PLAIN)
1387 startup_cost = input_total_cost;
1388 startup_cost += aggcosts->transCost.startup;
1389 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1390 startup_cost += aggcosts->finalCost;
1391 /* we aren't grouping */
1392 total_cost = startup_cost + cpu_tuple_cost;
1394 else if (aggstrategy == AGG_SORTED)
1396 /* Here we are able to deliver output on-the-fly */
1397 startup_cost = input_startup_cost;
1398 total_cost = input_total_cost;
1399 /* calcs phrased this way to match HASHED case, see note above */
1400 total_cost += aggcosts->transCost.startup;
1401 total_cost += aggcosts->transCost.per_tuple * input_tuples;
1402 total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1403 total_cost += aggcosts->finalCost * numGroups;
1404 total_cost += cpu_tuple_cost * numGroups;
1408 /* must be AGG_HASHED */
1409 startup_cost = input_total_cost;
1410 startup_cost += aggcosts->transCost.startup;
1411 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1412 startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1413 total_cost = startup_cost;
1414 total_cost += aggcosts->finalCost * numGroups;
1415 total_cost += cpu_tuple_cost * numGroups;
1418 path->startup_cost = startup_cost;
1419 path->total_cost = total_cost;
1424 * Determines and returns the cost of performing a WindowAgg plan node,
1425 * including the cost of its input.
1427 * Input is assumed already properly sorted.
1430 cost_windowagg(Path *path, PlannerInfo *root,
1431 List *windowFuncs, int numPartCols, int numOrderCols,
1432 Cost input_startup_cost, Cost input_total_cost,
1433 double input_tuples)
1439 startup_cost = input_startup_cost;
1440 total_cost = input_total_cost;
1443 * Window functions are assumed to cost their stated execution cost, plus
1444 * the cost of evaluating their input expressions, per tuple. Since they
1445 * may in fact evaluate their inputs at multiple rows during each cycle,
1446 * this could be a drastic underestimate; but without a way to know how
1447 * many rows the window function will fetch, it's hard to do better. In
1448 * any case, it's a good estimate for all the built-in window functions,
1449 * so we'll just do this for now.
1451 foreach(lc, windowFuncs)
1453 WindowFunc *wfunc = (WindowFunc *) lfirst(lc);
1457 Assert(IsA(wfunc, WindowFunc));
1459 wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1461 /* also add the input expressions' cost to per-input-row costs */
1462 cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1463 startup_cost += argcosts.startup;
1464 wfunccost += argcosts.per_tuple;
1466 total_cost += wfunccost * input_tuples;
1470 * We also charge cpu_operator_cost per grouping column per tuple for
1471 * grouping comparisons, plus cpu_tuple_cost per tuple for general
1474 * XXX this neglects costs of spooling the data to disk when it overflows
1475 * work_mem. Sooner or later that should get accounted for.
1477 total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1478 total_cost += cpu_tuple_cost * input_tuples;
1480 path->startup_cost = startup_cost;
1481 path->total_cost = total_cost;
1486 * Determines and returns the cost of performing a Group plan node,
1487 * including the cost of its input.
1489 * Note: caller must ensure that input costs are for appropriately-sorted
1493 cost_group(Path *path, PlannerInfo *root,
1494 int numGroupCols, double numGroups,
1495 Cost input_startup_cost, Cost input_total_cost,
1496 double input_tuples)
1501 startup_cost = input_startup_cost;
1502 total_cost = input_total_cost;
1505 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1506 * all columns get compared at most of the tuples.
1508 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1510 path->startup_cost = startup_cost;
1511 path->total_cost = total_cost;
1515 * If a nestloop's inner path is an indexscan, be sure to use its estimated
1516 * output row count, which may be lower than the restriction-clause-only row
1517 * count of its parent. (We don't include this case in the PATH_ROWS macro
1518 * because it applies *only* to a nestloop's inner relation.) We have to
1519 * be prepared to recurse through Append or MergeAppend nodes in case of an
1520 * appendrel. (It's not clear MergeAppend can be seen here, but we may as
1521 * well handle it if so.)
1524 nestloop_inner_path_rows(Path *path)
1528 if (IsA(path, IndexPath))
1529 result = ((IndexPath *) path)->rows;
1530 else if (IsA(path, BitmapHeapPath))
1531 result = ((BitmapHeapPath *) path)->rows;
1532 else if (IsA(path, AppendPath))
1537 foreach(l, ((AppendPath *) path)->subpaths)
1539 result += nestloop_inner_path_rows((Path *) lfirst(l));
1542 else if (IsA(path, MergeAppendPath))
1547 foreach(l, ((MergeAppendPath *) path)->subpaths)
1549 result += nestloop_inner_path_rows((Path *) lfirst(l));
1553 result = PATH_ROWS(path);
1560 * Determines and returns the cost of joining two relations using the
1561 * nested loop algorithm.
1563 * 'path' is already filled in except for the cost fields
1564 * 'sjinfo' is extra info about the join for selectivity estimation
1567 cost_nestloop(NestPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1569 Path *outer_path = path->outerjoinpath;
1570 Path *inner_path = path->innerjoinpath;
1571 Cost startup_cost = 0;
1573 Cost inner_rescan_start_cost;
1574 Cost inner_rescan_total_cost;
1575 Cost inner_run_cost;
1576 Cost inner_rescan_run_cost;
1578 QualCost restrict_qual_cost;
1579 double outer_path_rows = PATH_ROWS(outer_path);
1580 double inner_path_rows = nestloop_inner_path_rows(inner_path);
1582 Selectivity outer_match_frac;
1583 Selectivity match_count;
1584 bool indexed_join_quals;
1586 if (!enable_nestloop)
1587 startup_cost += disable_cost;
1589 /* estimate costs to rescan the inner relation */
1590 cost_rescan(root, inner_path,
1591 &inner_rescan_start_cost,
1592 &inner_rescan_total_cost);
1594 /* cost of source data */
1597 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1598 * before we can start returning tuples, so the join's startup cost is
1599 * their sum. We'll also pay the inner path's rescan startup cost
1602 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1603 run_cost += outer_path->total_cost - outer_path->startup_cost;
1604 if (outer_path_rows > 1)
1605 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1607 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1608 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1610 if (adjust_semi_join(root, path, sjinfo,
1613 &indexed_join_quals))
1615 double outer_matched_rows;
1616 Selectivity inner_scan_frac;
1619 * SEMI or ANTI join: executor will stop after first match.
1621 * For an outer-rel row that has at least one match, we can expect the
1622 * inner scan to stop after a fraction 1/(match_count+1) of the inner
1623 * rows, if the matches are evenly distributed. Since they probably
1624 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1625 * that fraction. (If we used a larger fuzz factor, we'd have to
1626 * clamp inner_scan_frac to at most 1.0; but since match_count is at
1627 * least 1, no such clamp is needed now.)
1629 * A complicating factor is that rescans may be cheaper than first
1630 * scans. If we never scan all the way to the end of the inner rel,
1631 * it might be (depending on the plan type) that we'd never pay the
1632 * whole inner first-scan run cost. However it is difficult to
1633 * estimate whether that will happen, so be conservative and always
1634 * charge the whole first-scan cost once.
1636 run_cost += inner_run_cost;
1638 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
1639 inner_scan_frac = 2.0 / (match_count + 1.0);
1641 /* Add inner run cost for additional outer tuples having matches */
1642 if (outer_matched_rows > 1)
1643 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1645 /* Compute number of tuples processed (not number emitted!) */
1646 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1649 * For unmatched outer-rel rows, there are two cases. If the inner
1650 * path is an indexscan using all the joinquals as indexquals, then an
1651 * unmatched row results in an indexscan returning no rows, which is
1652 * probably quite cheap. We estimate this case as the same cost to
1653 * return the first tuple of a nonempty scan. Otherwise, the executor
1654 * will have to scan the whole inner rel; not so cheap.
1656 if (indexed_join_quals)
1658 run_cost += (outer_path_rows - outer_matched_rows) *
1659 inner_rescan_run_cost / inner_path_rows;
1662 * We won't be evaluating any quals at all for these rows, so
1663 * don't add them to ntuples.
1668 run_cost += (outer_path_rows - outer_matched_rows) *
1669 inner_rescan_run_cost;
1670 ntuples += (outer_path_rows - outer_matched_rows) *
1676 /* Normal case; we'll scan whole input rel for each outer row */
1677 run_cost += inner_run_cost;
1678 if (outer_path_rows > 1)
1679 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1681 /* Compute number of tuples processed (not number emitted!) */
1682 ntuples = outer_path_rows * inner_path_rows;
1686 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1687 startup_cost += restrict_qual_cost.startup;
1688 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1689 run_cost += cpu_per_tuple * ntuples;
1691 path->path.startup_cost = startup_cost;
1692 path->path.total_cost = startup_cost + run_cost;
1697 * Determines and returns the cost of joining two relations using the
1698 * merge join algorithm.
1700 * Unlike other costsize functions, this routine makes one actual decision:
1701 * whether we should materialize the inner path. We do that either because
1702 * the inner path can't support mark/restore, or because it's cheaper to
1703 * use an interposed Material node to handle mark/restore. When the decision
1704 * is cost-based it would be logically cleaner to build and cost two separate
1705 * paths with and without that flag set; but that would require repeating most
1706 * of the calculations here, which are not all that cheap. Since the choice
1707 * will not affect output pathkeys or startup cost, only total cost, there is
1708 * no possibility of wanting to keep both paths. So it seems best to make
1709 * the decision here and record it in the path's materialize_inner field.
1711 * 'path' is already filled in except for the cost fields and materialize_inner
1712 * 'sjinfo' is extra info about the join for selectivity estimation
1714 * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
1715 * outersortkeys and innersortkeys are lists of the keys to be used
1716 * to sort the outer and inner relations, or NIL if no explicit
1717 * sort is needed because the source path is already ordered.
1720 cost_mergejoin(MergePath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1722 Path *outer_path = path->jpath.outerjoinpath;
1723 Path *inner_path = path->jpath.innerjoinpath;
1724 List *mergeclauses = path->path_mergeclauses;
1725 List *outersortkeys = path->outersortkeys;
1726 List *innersortkeys = path->innersortkeys;
1727 Cost startup_cost = 0;
1733 QualCost merge_qual_cost;
1734 QualCost qp_qual_cost;
1735 double outer_path_rows = PATH_ROWS(outer_path);
1736 double inner_path_rows = PATH_ROWS(inner_path);
1741 double mergejointuples,
1744 Selectivity outerstartsel,
1748 Path sort_path; /* dummy for result of cost_sort */
1750 /* Protect some assumptions below that rowcounts aren't zero or NaN */
1751 if (outer_path_rows <= 0 || isnan(outer_path_rows))
1752 outer_path_rows = 1;
1753 if (inner_path_rows <= 0 || isnan(inner_path_rows))
1754 inner_path_rows = 1;
1756 if (!enable_mergejoin)
1757 startup_cost += disable_cost;
1760 * Compute cost of the mergequals and qpquals (other restriction clauses)
1763 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
1764 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
1765 qp_qual_cost.startup -= merge_qual_cost.startup;
1766 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
1769 * Get approx # tuples passing the mergequals. We use approx_tuple_count
1770 * here because we need an estimate done with JOIN_INNER semantics.
1772 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
1775 * When there are equal merge keys in the outer relation, the mergejoin
1776 * must rescan any matching tuples in the inner relation. This means
1777 * re-fetching inner tuples; we have to estimate how often that happens.
1779 * For regular inner and outer joins, the number of re-fetches can be
1780 * estimated approximately as size of merge join output minus size of
1781 * inner relation. Assume that the distinct key values are 1, 2, ..., and
1782 * denote the number of values of each key in the outer relation as m1,
1783 * m2, ...; in the inner relation, n1, n2, ... Then we have
1785 * size of join = m1 * n1 + m2 * n2 + ...
1787 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
1788 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
1791 * This equation works correctly for outer tuples having no inner match
1792 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
1793 * are effectively subtracting those from the number of rescanned tuples,
1794 * when we should not. Can we do better without expensive selectivity
1797 * The whole issue is moot if we are working from a unique-ified outer
1800 if (IsA(outer_path, UniquePath))
1801 rescannedtuples = 0;
1804 rescannedtuples = mergejointuples - inner_path_rows;
1805 /* Must clamp because of possible underestimate */
1806 if (rescannedtuples < 0)
1807 rescannedtuples = 0;
1809 /* We'll inflate various costs this much to account for rescanning */
1810 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
1813 * A merge join will stop as soon as it exhausts either input stream
1814 * (unless it's an outer join, in which case the outer side has to be
1815 * scanned all the way anyway). Estimate fraction of the left and right
1816 * inputs that will actually need to be scanned. Likewise, we can
1817 * estimate the number of rows that will be skipped before the first join
1818 * pair is found, which should be factored into startup cost. We use only
1819 * the first (most significant) merge clause for this purpose. Since
1820 * mergejoinscansel() is a fairly expensive computation, we cache the
1821 * results in the merge clause RestrictInfo.
1823 if (mergeclauses && path->jpath.jointype != JOIN_FULL)
1825 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1830 MergeScanSelCache *cache;
1832 /* Get the input pathkeys to determine the sort-order details */
1833 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1834 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1837 opathkey = (PathKey *) linitial(opathkeys);
1838 ipathkey = (PathKey *) linitial(ipathkeys);
1839 /* debugging check */
1840 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1841 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
1842 opathkey->pk_strategy != ipathkey->pk_strategy ||
1843 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1844 elog(ERROR, "left and right pathkeys do not match in mergejoin");
1846 /* Get the selectivity with caching */
1847 cache = cached_scansel(root, firstclause, opathkey);
1849 if (bms_is_subset(firstclause->left_relids,
1850 outer_path->parent->relids))
1852 /* left side of clause is outer */
1853 outerstartsel = cache->leftstartsel;
1854 outerendsel = cache->leftendsel;
1855 innerstartsel = cache->rightstartsel;
1856 innerendsel = cache->rightendsel;
1860 /* left side of clause is inner */
1861 outerstartsel = cache->rightstartsel;
1862 outerendsel = cache->rightendsel;
1863 innerstartsel = cache->leftstartsel;
1864 innerendsel = cache->leftendsel;
1866 if (path->jpath.jointype == JOIN_LEFT ||
1867 path->jpath.jointype == JOIN_ANTI)
1869 outerstartsel = 0.0;
1872 else if (path->jpath.jointype == JOIN_RIGHT)
1874 innerstartsel = 0.0;
1880 /* cope with clauseless or full mergejoin */
1881 outerstartsel = innerstartsel = 0.0;
1882 outerendsel = innerendsel = 1.0;
1886 * Convert selectivities to row counts. We force outer_rows and
1887 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1889 outer_skip_rows = rint(outer_path_rows * outerstartsel);
1890 inner_skip_rows = rint(inner_path_rows * innerstartsel);
1891 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1892 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
1894 Assert(outer_skip_rows <= outer_rows);
1895 Assert(inner_skip_rows <= inner_rows);
1898 * Readjust scan selectivities to account for above rounding. This is
1899 * normally an insignificant effect, but when there are only a few rows in
1900 * the inputs, failing to do this makes for a large percentage error.
1902 outerstartsel = outer_skip_rows / outer_path_rows;
1903 innerstartsel = inner_skip_rows / inner_path_rows;
1904 outerendsel = outer_rows / outer_path_rows;
1905 innerendsel = inner_rows / inner_path_rows;
1907 Assert(outerstartsel <= outerendsel);
1908 Assert(innerstartsel <= innerendsel);
1910 /* cost of source data */
1912 if (outersortkeys) /* do we need to sort outer? */
1914 cost_sort(&sort_path,
1917 outer_path->total_cost,
1919 outer_path->parent->width,
1923 startup_cost += sort_path.startup_cost;
1924 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1926 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1927 * (outerendsel - outerstartsel);
1931 startup_cost += outer_path->startup_cost;
1932 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
1934 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1935 * (outerendsel - outerstartsel);
1938 if (innersortkeys) /* do we need to sort inner? */
1940 cost_sort(&sort_path,
1943 inner_path->total_cost,
1945 inner_path->parent->width,
1949 startup_cost += sort_path.startup_cost;
1950 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1952 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
1953 * (innerendsel - innerstartsel);
1957 startup_cost += inner_path->startup_cost;
1958 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
1960 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
1961 * (innerendsel - innerstartsel);
1965 * Decide whether we want to materialize the inner input to shield it from
1966 * mark/restore and performing re-fetches. Our cost model for regular
1967 * re-fetches is that a re-fetch costs the same as an original fetch,
1968 * which is probably an overestimate; but on the other hand we ignore the
1969 * bookkeeping costs of mark/restore. Not clear if it's worth developing
1970 * a more refined model. So we just need to inflate the inner run cost by
1973 bare_inner_cost = inner_run_cost * rescanratio;
1976 * When we interpose a Material node the re-fetch cost is assumed to be
1977 * just cpu_operator_cost per tuple, independently of the underlying
1978 * plan's cost; and we charge an extra cpu_operator_cost per original
1979 * fetch as well. Note that we're assuming the materialize node will
1980 * never spill to disk, since it only has to remember tuples back to the
1981 * last mark. (If there are a huge number of duplicates, our other cost
1982 * factors will make the path so expensive that it probably won't get
1983 * chosen anyway.) So we don't use cost_rescan here.
1985 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
1986 * of the generated Material node.
1988 mat_inner_cost = inner_run_cost +
1989 cpu_operator_cost * inner_path_rows * rescanratio;
1992 * Prefer materializing if it looks cheaper, unless the user has asked to
1993 * suppress materialization.
1995 if (enable_material && mat_inner_cost < bare_inner_cost)
1996 path->materialize_inner = true;
1999 * Even if materializing doesn't look cheaper, we *must* do it if the
2000 * inner path is to be used directly (without sorting) and it doesn't
2001 * support mark/restore.
2003 * Since the inner side must be ordered, and only Sorts and IndexScans can
2004 * create order to begin with, and they both support mark/restore, you
2005 * might think there's no problem --- but you'd be wrong. Nestloop and
2006 * merge joins can *preserve* the order of their inputs, so they can be
2007 * selected as the input of a mergejoin, and they don't support
2008 * mark/restore at present.
2010 * We don't test the value of enable_material here, because
2011 * materialization is required for correctness in this case, and turning
2012 * it off does not entitle us to deliver an invalid plan.
2014 else if (innersortkeys == NIL &&
2015 !ExecSupportsMarkRestore(inner_path->pathtype))
2016 path->materialize_inner = true;
2019 * Also, force materializing if the inner path is to be sorted and the
2020 * sort is expected to spill to disk. This is because the final merge
2021 * pass can be done on-the-fly if it doesn't have to support mark/restore.
2022 * We don't try to adjust the cost estimates for this consideration,
2025 * Since materialization is a performance optimization in this case,
2026 * rather than necessary for correctness, we skip it if enable_material is
2029 else if (enable_material && innersortkeys != NIL &&
2030 relation_byte_size(inner_path_rows, inner_path->parent->width) >
2032 path->materialize_inner = true;
2034 path->materialize_inner = false;
2036 /* Charge the right incremental cost for the chosen case */
2037 if (path->materialize_inner)
2038 run_cost += mat_inner_cost;
2040 run_cost += bare_inner_cost;
2045 * The number of tuple comparisons needed is approximately number of outer
2046 * rows plus number of inner rows plus number of rescanned tuples (can we
2047 * refine this?). At each one, we need to evaluate the mergejoin quals.
2049 startup_cost += merge_qual_cost.startup;
2050 startup_cost += merge_qual_cost.per_tuple *
2051 (outer_skip_rows + inner_skip_rows * rescanratio);
2052 run_cost += merge_qual_cost.per_tuple *
2053 ((outer_rows - outer_skip_rows) +
2054 (inner_rows - inner_skip_rows) * rescanratio);
2057 * For each tuple that gets through the mergejoin proper, we charge
2058 * cpu_tuple_cost plus the cost of evaluating additional restriction
2059 * clauses that are to be applied at the join. (This is pessimistic since
2060 * not all of the quals may get evaluated at each tuple.)
2062 * Note: we could adjust for SEMI/ANTI joins skipping some qual
2063 * evaluations here, but it's probably not worth the trouble.
2065 startup_cost += qp_qual_cost.startup;
2066 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2067 run_cost += cpu_per_tuple * mergejointuples;
2069 path->jpath.path.startup_cost = startup_cost;
2070 path->jpath.path.total_cost = startup_cost + run_cost;
2074 * run mergejoinscansel() with caching
2076 static MergeScanSelCache *
2077 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2079 MergeScanSelCache *cache;
2081 Selectivity leftstartsel,
2085 MemoryContext oldcontext;
2087 /* Do we have this result already? */
2088 foreach(lc, rinfo->scansel_cache)
2090 cache = (MergeScanSelCache *) lfirst(lc);
2091 if (cache->opfamily == pathkey->pk_opfamily &&
2092 cache->collation == pathkey->pk_eclass->ec_collation &&
2093 cache->strategy == pathkey->pk_strategy &&
2094 cache->nulls_first == pathkey->pk_nulls_first)
2098 /* Nope, do the computation */
2099 mergejoinscansel(root,
2100 (Node *) rinfo->clause,
2101 pathkey->pk_opfamily,
2102 pathkey->pk_strategy,
2103 pathkey->pk_nulls_first,
2109 /* Cache the result in suitably long-lived workspace */
2110 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2112 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2113 cache->opfamily = pathkey->pk_opfamily;
2114 cache->collation = pathkey->pk_eclass->ec_collation;
2115 cache->strategy = pathkey->pk_strategy;
2116 cache->nulls_first = pathkey->pk_nulls_first;
2117 cache->leftstartsel = leftstartsel;
2118 cache->leftendsel = leftendsel;
2119 cache->rightstartsel = rightstartsel;
2120 cache->rightendsel = rightendsel;
2122 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2124 MemoryContextSwitchTo(oldcontext);
2131 * Determines and returns the cost of joining two relations using the
2132 * hash join algorithm.
2134 * 'path' is already filled in except for the cost fields
2135 * 'sjinfo' is extra info about the join for selectivity estimation
2137 * Note: path's hashclauses should be a subset of the joinrestrictinfo list
2140 cost_hashjoin(HashPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
2142 Path *outer_path = path->jpath.outerjoinpath;
2143 Path *inner_path = path->jpath.innerjoinpath;
2144 List *hashclauses = path->path_hashclauses;
2145 Cost startup_cost = 0;
2148 QualCost hash_qual_cost;
2149 QualCost qp_qual_cost;
2150 double hashjointuples;
2151 double outer_path_rows = PATH_ROWS(outer_path);
2152 double inner_path_rows = PATH_ROWS(inner_path);
2153 int num_hashclauses = list_length(hashclauses);
2157 double virtualbuckets;
2158 Selectivity innerbucketsize;
2159 Selectivity outer_match_frac;
2160 Selectivity match_count;
2163 if (!enable_hashjoin)
2164 startup_cost += disable_cost;
2167 * Compute cost of the hashquals and qpquals (other restriction clauses)
2170 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2171 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2172 qp_qual_cost.startup -= hash_qual_cost.startup;
2173 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2175 /* cost of source data */
2176 startup_cost += outer_path->startup_cost;
2177 run_cost += outer_path->total_cost - outer_path->startup_cost;
2178 startup_cost += inner_path->total_cost;
2181 * Cost of computing hash function: must do it once per input tuple. We
2182 * charge one cpu_operator_cost for each column's hash function. Also,
2183 * tack on one cpu_tuple_cost per inner row, to model the costs of
2184 * inserting the row into the hashtable.
2186 * XXX when a hashclause is more complex than a single operator, we really
2187 * should charge the extra eval costs of the left or right side, as
2188 * appropriate, here. This seems more work than it's worth at the moment.
2190 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2192 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2195 * Get hash table size that executor would use for inner relation.
2197 * XXX for the moment, always assume that skew optimization will be
2198 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2199 * trying to determine that for sure.
2201 * XXX at some point it might be interesting to try to account for skew
2202 * optimization in the cost estimate, but for now, we don't.
2204 ExecChooseHashTableSize(inner_path_rows,
2205 inner_path->parent->width,
2210 virtualbuckets = (double) numbuckets *(double) numbatches;
2212 /* mark the path with estimated # of batches */
2213 path->num_batches = numbatches;
2216 * Determine bucketsize fraction for inner relation. We use the smallest
2217 * bucketsize estimated for any individual hashclause; this is undoubtedly
2220 * BUT: if inner relation has been unique-ified, we can assume it's good
2221 * for hashing. This is important both because it's the right answer, and
2222 * because we avoid contaminating the cache with a value that's wrong for
2223 * non-unique-ified paths.
2225 if (IsA(inner_path, UniquePath))
2226 innerbucketsize = 1.0 / virtualbuckets;
2229 innerbucketsize = 1.0;
2230 foreach(hcl, hashclauses)
2232 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2233 Selectivity thisbucketsize;
2235 Assert(IsA(restrictinfo, RestrictInfo));
2238 * First we have to figure out which side of the hashjoin clause
2239 * is the inner side.
2241 * Since we tend to visit the same clauses over and over when
2242 * planning a large query, we cache the bucketsize estimate in the
2243 * RestrictInfo node to avoid repeated lookups of statistics.
2245 if (bms_is_subset(restrictinfo->right_relids,
2246 inner_path->parent->relids))
2248 /* righthand side is inner */
2249 thisbucketsize = restrictinfo->right_bucketsize;
2250 if (thisbucketsize < 0)
2252 /* not cached yet */
2254 estimate_hash_bucketsize(root,
2255 get_rightop(restrictinfo->clause),
2257 restrictinfo->right_bucketsize = thisbucketsize;
2262 Assert(bms_is_subset(restrictinfo->left_relids,
2263 inner_path->parent->relids));
2264 /* lefthand side is inner */
2265 thisbucketsize = restrictinfo->left_bucketsize;
2266 if (thisbucketsize < 0)
2268 /* not cached yet */
2270 estimate_hash_bucketsize(root,
2271 get_leftop(restrictinfo->clause),
2273 restrictinfo->left_bucketsize = thisbucketsize;
2277 if (innerbucketsize > thisbucketsize)
2278 innerbucketsize = thisbucketsize;
2283 * If inner relation is too big then we will need to "batch" the join,
2284 * which implies writing and reading most of the tuples to disk an extra
2285 * time. Charge seq_page_cost per page, since the I/O should be nice and
2286 * sequential. Writing the inner rel counts as startup cost, all the rest
2291 double outerpages = page_size(outer_path_rows,
2292 outer_path->parent->width);
2293 double innerpages = page_size(inner_path_rows,
2294 inner_path->parent->width);
2296 startup_cost += seq_page_cost * innerpages;
2297 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2302 if (adjust_semi_join(root, &path->jpath, sjinfo,
2307 double outer_matched_rows;
2308 Selectivity inner_scan_frac;
2311 * SEMI or ANTI join: executor will stop after first match.
2313 * For an outer-rel row that has at least one match, we can expect the
2314 * bucket scan to stop after a fraction 1/(match_count+1) of the
2315 * bucket's rows, if the matches are evenly distributed. Since they
2316 * probably aren't quite evenly distributed, we apply a fuzz factor of
2317 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2318 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2319 * at least 1, no such clamp is needed now.)
2321 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
2322 inner_scan_frac = 2.0 / (match_count + 1.0);
2324 startup_cost += hash_qual_cost.startup;
2325 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2326 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2329 * For unmatched outer-rel rows, the picture is quite a lot different.
2330 * In the first place, there is no reason to assume that these rows
2331 * preferentially hit heavily-populated buckets; instead assume they
2332 * are uncorrelated with the inner distribution and so they see an
2333 * average bucket size of inner_path_rows / virtualbuckets. In the
2334 * second place, it seems likely that they will have few if any exact
2335 * hash-code matches and so very few of the tuples in the bucket will
2336 * actually require eval of the hash quals. We don't have any good
2337 * way to estimate how many will, but for the moment assume that the
2338 * effective cost per bucket entry is one-tenth what it is for
2341 run_cost += hash_qual_cost.per_tuple *
2342 (outer_path_rows - outer_matched_rows) *
2343 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2345 /* Get # of tuples that will pass the basic join */
2346 if (path->jpath.jointype == JOIN_SEMI)
2347 hashjointuples = outer_matched_rows;
2349 hashjointuples = outer_path_rows - outer_matched_rows;
2354 * The number of tuple comparisons needed is the number of outer
2355 * tuples times the typical number of tuples in a hash bucket, which
2356 * is the inner relation size times its bucketsize fraction. At each
2357 * one, we need to evaluate the hashjoin quals. But actually,
2358 * charging the full qual eval cost at each tuple is pessimistic,
2359 * since we don't evaluate the quals unless the hash values match
2360 * exactly. For lack of a better idea, halve the cost estimate to
2363 startup_cost += hash_qual_cost.startup;
2364 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2365 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2368 * Get approx # tuples passing the hashquals. We use
2369 * approx_tuple_count here because we need an estimate done with
2370 * JOIN_INNER semantics.
2372 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2376 * For each tuple that gets through the hashjoin proper, we charge
2377 * cpu_tuple_cost plus the cost of evaluating additional restriction
2378 * clauses that are to be applied at the join. (This is pessimistic since
2379 * not all of the quals may get evaluated at each tuple.)
2381 startup_cost += qp_qual_cost.startup;
2382 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2383 run_cost += cpu_per_tuple * hashjointuples;
2385 path->jpath.path.startup_cost = startup_cost;
2386 path->jpath.path.total_cost = startup_cost + run_cost;
2392 * Figure the costs for a SubPlan (or initplan).
2394 * Note: we could dig the subplan's Plan out of the root list, but in practice
2395 * all callers have it handy already, so we make them pass it.
2398 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2402 /* Figure any cost for evaluating the testexpr */
2403 cost_qual_eval(&sp_cost,
2404 make_ands_implicit((Expr *) subplan->testexpr),
2407 if (subplan->useHashTable)
2410 * If we are using a hash table for the subquery outputs, then the
2411 * cost of evaluating the query is a one-time cost. We charge one
2412 * cpu_operator_cost per tuple for the work of loading the hashtable,
2415 sp_cost.startup += plan->total_cost +
2416 cpu_operator_cost * plan->plan_rows;
2419 * The per-tuple costs include the cost of evaluating the lefthand
2420 * expressions, plus the cost of probing the hashtable. We already
2421 * accounted for the lefthand expressions as part of the testexpr, and
2422 * will also have counted one cpu_operator_cost for each comparison
2423 * operator. That is probably too low for the probing cost, but it's
2424 * hard to make a better estimate, so live with it for now.
2430 * Otherwise we will be rescanning the subplan output on each
2431 * evaluation. We need to estimate how much of the output we will
2432 * actually need to scan. NOTE: this logic should agree with the
2433 * tuple_fraction estimates used by make_subplan() in
2436 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2438 if (subplan->subLinkType == EXISTS_SUBLINK)
2440 /* we only need to fetch 1 tuple */
2441 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2443 else if (subplan->subLinkType == ALL_SUBLINK ||
2444 subplan->subLinkType == ANY_SUBLINK)
2446 /* assume we need 50% of the tuples */
2447 sp_cost.per_tuple += 0.50 * plan_run_cost;
2448 /* also charge a cpu_operator_cost per row examined */
2449 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2453 /* assume we need all tuples */
2454 sp_cost.per_tuple += plan_run_cost;
2458 * Also account for subplan's startup cost. If the subplan is
2459 * uncorrelated or undirect correlated, AND its topmost node is one
2460 * that materializes its output, assume that we'll only need to pay
2461 * its startup cost once; otherwise assume we pay the startup cost
2464 if (subplan->parParam == NIL &&
2465 ExecMaterializesOutput(nodeTag(plan)))
2466 sp_cost.startup += plan->startup_cost;
2468 sp_cost.per_tuple += plan->startup_cost;
2471 subplan->startup_cost = sp_cost.startup;
2472 subplan->per_call_cost = sp_cost.per_tuple;
2478 * Given a finished Path, estimate the costs of rescanning it after
2479 * having done so the first time. For some Path types a rescan is
2480 * cheaper than an original scan (if no parameters change), and this
2481 * function embodies knowledge about that. The default is to return
2482 * the same costs stored in the Path. (Note that the cost estimates
2483 * actually stored in Paths are always for first scans.)
2485 * This function is not currently intended to model effects such as rescans
2486 * being cheaper due to disk block caching; what we are concerned with is
2487 * plan types wherein the executor caches results explicitly, or doesn't
2488 * redo startup calculations, etc.
2491 cost_rescan(PlannerInfo *root, Path *path,
2492 Cost *rescan_startup_cost, /* output parameters */
2493 Cost *rescan_total_cost)
2495 switch (path->pathtype)
2497 case T_FunctionScan:
2500 * Currently, nodeFunctionscan.c always executes the function to
2501 * completion before returning any rows, and caches the results in
2502 * a tuplestore. So the function eval cost is all startup cost
2503 * and isn't paid over again on rescans. However, all run costs
2504 * will be paid over again.
2506 *rescan_startup_cost = 0;
2507 *rescan_total_cost = path->total_cost - path->startup_cost;
2512 * Assume that all of the startup cost represents hash table
2513 * building, which we won't have to do over.
2515 *rescan_startup_cost = 0;
2516 *rescan_total_cost = path->total_cost - path->startup_cost;
2519 case T_WorkTableScan:
2522 * These plan types materialize their final result in a
2523 * tuplestore or tuplesort object. So the rescan cost is only
2524 * cpu_tuple_cost per tuple, unless the result is large enough
2527 Cost run_cost = cpu_tuple_cost * path->parent->rows;
2528 double nbytes = relation_byte_size(path->parent->rows,
2529 path->parent->width);
2530 long work_mem_bytes = work_mem * 1024L;
2532 if (nbytes > work_mem_bytes)
2534 /* It will spill, so account for re-read cost */
2535 double npages = ceil(nbytes / BLCKSZ);
2537 run_cost += seq_page_cost * npages;
2539 *rescan_startup_cost = 0;
2540 *rescan_total_cost = run_cost;
2547 * These plan types not only materialize their results, but do
2548 * not implement qual filtering or projection. So they are
2549 * even cheaper to rescan than the ones above. We charge only
2550 * cpu_operator_cost per tuple. (Note: keep that in sync with
2551 * the run_cost charge in cost_sort, and also see comments in
2552 * cost_material before you change it.)
2554 Cost run_cost = cpu_operator_cost * path->parent->rows;
2555 double nbytes = relation_byte_size(path->parent->rows,
2556 path->parent->width);
2557 long work_mem_bytes = work_mem * 1024L;
2559 if (nbytes > work_mem_bytes)
2561 /* It will spill, so account for re-read cost */
2562 double npages = ceil(nbytes / BLCKSZ);
2564 run_cost += seq_page_cost * npages;
2566 *rescan_startup_cost = 0;
2567 *rescan_total_cost = run_cost;
2571 *rescan_startup_cost = path->startup_cost;
2572 *rescan_total_cost = path->total_cost;
2580 * Estimate the CPU costs of evaluating a WHERE clause.
2581 * The input can be either an implicitly-ANDed list of boolean
2582 * expressions, or a list of RestrictInfo nodes. (The latter is
2583 * preferred since it allows caching of the results.)
2584 * The result includes both a one-time (startup) component,
2585 * and a per-evaluation component.
2588 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2590 cost_qual_eval_context context;
2593 context.root = root;
2594 context.total.startup = 0;
2595 context.total.per_tuple = 0;
2597 /* We don't charge any cost for the implicit ANDing at top level ... */
2601 Node *qual = (Node *) lfirst(l);
2603 cost_qual_eval_walker(qual, &context);
2606 *cost = context.total;
2610 * cost_qual_eval_node
2611 * As above, for a single RestrictInfo or expression.
2614 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2616 cost_qual_eval_context context;
2618 context.root = root;
2619 context.total.startup = 0;
2620 context.total.per_tuple = 0;
2622 cost_qual_eval_walker(qual, &context);
2624 *cost = context.total;
2628 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2634 * RestrictInfo nodes contain an eval_cost field reserved for this
2635 * routine's use, so that it's not necessary to evaluate the qual clause's
2636 * cost more than once. If the clause's cost hasn't been computed yet,
2637 * the field's startup value will contain -1.
2639 if (IsA(node, RestrictInfo))
2641 RestrictInfo *rinfo = (RestrictInfo *) node;
2643 if (rinfo->eval_cost.startup < 0)
2645 cost_qual_eval_context locContext;
2647 locContext.root = context->root;
2648 locContext.total.startup = 0;
2649 locContext.total.per_tuple = 0;
2652 * For an OR clause, recurse into the marked-up tree so that we
2653 * set the eval_cost for contained RestrictInfos too.
2655 if (rinfo->orclause)
2656 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2658 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2661 * If the RestrictInfo is marked pseudoconstant, it will be tested
2662 * only once, so treat its cost as all startup cost.
2664 if (rinfo->pseudoconstant)
2666 /* count one execution during startup */
2667 locContext.total.startup += locContext.total.per_tuple;
2668 locContext.total.per_tuple = 0;
2670 rinfo->eval_cost = locContext.total;
2672 context->total.startup += rinfo->eval_cost.startup;
2673 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2674 /* do NOT recurse into children */
2679 * For each operator or function node in the given tree, we charge the
2680 * estimated execution cost given by pg_proc.procost (remember to multiply
2681 * this by cpu_operator_cost).
2683 * Vars and Consts are charged zero, and so are boolean operators (AND,
2684 * OR, NOT). Simplistic, but a lot better than no model at all.
2686 * Should we try to account for the possibility of short-circuit
2687 * evaluation of AND/OR? Probably *not*, because that would make the
2688 * results depend on the clause ordering, and we are not in any position
2689 * to expect that the current ordering of the clauses is the one that's
2690 * going to end up being used. The above per-RestrictInfo caching would
2691 * not mix well with trying to re-order clauses anyway.
2693 if (IsA(node, FuncExpr))
2695 context->total.per_tuple +=
2696 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
2698 else if (IsA(node, OpExpr) ||
2699 IsA(node, DistinctExpr) ||
2700 IsA(node, NullIfExpr))
2702 /* rely on struct equivalence to treat these all alike */
2703 set_opfuncid((OpExpr *) node);
2704 context->total.per_tuple +=
2705 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
2707 else if (IsA(node, ScalarArrayOpExpr))
2710 * Estimate that the operator will be applied to about half of the
2711 * array elements before the answer is determined.
2713 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2714 Node *arraynode = (Node *) lsecond(saop->args);
2716 set_sa_opfuncid(saop);
2717 context->total.per_tuple += get_func_cost(saop->opfuncid) *
2718 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
2720 else if (IsA(node, Aggref) ||
2721 IsA(node, WindowFunc))
2724 * Aggref and WindowFunc nodes are (and should be) treated like Vars,
2725 * ie, zero execution cost in the current model, because they behave
2726 * essentially like Vars in execQual.c. We disregard the costs of
2727 * their input expressions for the same reason. The actual execution
2728 * costs of the aggregate/window functions and their arguments have to
2729 * be factored into plan-node-specific costing of the Agg or WindowAgg
2732 return false; /* don't recurse into children */
2734 else if (IsA(node, CoerceViaIO))
2736 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2741 /* check the result type's input function */
2742 getTypeInputInfo(iocoerce->resulttype,
2743 &iofunc, &typioparam);
2744 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2745 /* check the input type's output function */
2746 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
2747 &iofunc, &typisvarlena);
2748 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2750 else if (IsA(node, ArrayCoerceExpr))
2752 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2753 Node *arraynode = (Node *) acoerce->arg;
2755 if (OidIsValid(acoerce->elemfuncid))
2756 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
2757 cpu_operator_cost * estimate_array_length(arraynode);
2759 else if (IsA(node, RowCompareExpr))
2761 /* Conservatively assume we will check all the columns */
2762 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2765 foreach(lc, rcexpr->opnos)
2767 Oid opid = lfirst_oid(lc);
2769 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
2773 else if (IsA(node, CurrentOfExpr))
2775 /* Report high cost to prevent selection of anything but TID scan */
2776 context->total.startup += disable_cost;
2778 else if (IsA(node, SubLink))
2780 /* This routine should not be applied to un-planned expressions */
2781 elog(ERROR, "cannot handle unplanned sub-select");
2783 else if (IsA(node, SubPlan))
2786 * A subplan node in an expression typically indicates that the
2787 * subplan will be executed on each evaluation, so charge accordingly.
2788 * (Sub-selects that can be executed as InitPlans have already been
2789 * removed from the expression.)
2791 SubPlan *subplan = (SubPlan *) node;
2793 context->total.startup += subplan->startup_cost;
2794 context->total.per_tuple += subplan->per_call_cost;
2797 * We don't want to recurse into the testexpr, because it was already
2798 * counted in the SubPlan node's costs. So we're done.
2802 else if (IsA(node, AlternativeSubPlan))
2805 * Arbitrarily use the first alternative plan for costing. (We should
2806 * certainly only include one alternative, and we don't yet have
2807 * enough information to know which one the executor is most likely to
2810 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2812 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
2816 /* recurse into children */
2817 return expression_tree_walker(node, cost_qual_eval_walker,
2824 * Estimate how much of the inner input a SEMI or ANTI join
2825 * can be expected to scan.
2827 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
2828 * inner rows as soon as it finds a match to the current outer row.
2829 * We should therefore adjust some of the cost components for this effect.
2830 * This function computes some estimates needed for these adjustments.
2832 * 'path' is already filled in except for the cost fields
2833 * 'sjinfo' is extra info about the join for selectivity estimation
2835 * Returns TRUE if this is a SEMI or ANTI join, FALSE if not.
2837 * Output parameters (set only in TRUE-result case):
2838 * *outer_match_frac is set to the fraction of the outer tuples that are
2839 * expected to have at least one match.
2840 * *match_count is set to the average number of matches expected for
2841 * outer tuples that have at least one match.
2842 * *indexed_join_quals is set to TRUE if all the joinquals are used as
2843 * inner index quals, FALSE if not.
2845 * indexed_join_quals can be passed as NULL if that information is not
2846 * relevant (it is only useful for the nestloop case).
2849 adjust_semi_join(PlannerInfo *root, JoinPath *path, SpecialJoinInfo *sjinfo,
2850 Selectivity *outer_match_frac,
2851 Selectivity *match_count,
2852 bool *indexed_join_quals)
2854 JoinType jointype = path->jointype;
2857 Selectivity avgmatch;
2858 SpecialJoinInfo norm_sjinfo;
2862 /* Fall out if it's not JOIN_SEMI or JOIN_ANTI */
2863 if (jointype != JOIN_SEMI && jointype != JOIN_ANTI)
2867 * Note: it's annoying to repeat this selectivity estimation on each call,
2868 * when the joinclause list will be the same for all path pairs
2869 * implementing a given join. clausesel.c will save us from the worst
2870 * effects of this by caching at the RestrictInfo level; but perhaps it'd
2871 * be worth finding a way to cache the results at a higher level.
2875 * In an ANTI join, we must ignore clauses that are "pushed down", since
2876 * those won't affect the match logic. In a SEMI join, we do not
2877 * distinguish joinquals from "pushed down" quals, so just use the whole
2878 * restrictinfo list.
2880 if (jointype == JOIN_ANTI)
2883 foreach(l, path->joinrestrictinfo)
2885 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2887 Assert(IsA(rinfo, RestrictInfo));
2888 if (!rinfo->is_pushed_down)
2889 joinquals = lappend(joinquals, rinfo);
2893 joinquals = path->joinrestrictinfo;
2896 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
2898 jselec = clauselist_selectivity(root,
2905 * Also get the normal inner-join selectivity of the join clauses.
2907 norm_sjinfo.type = T_SpecialJoinInfo;
2908 norm_sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2909 norm_sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2910 norm_sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2911 norm_sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2912 norm_sjinfo.jointype = JOIN_INNER;
2913 /* we don't bother trying to make the remaining fields valid */
2914 norm_sjinfo.lhs_strict = false;
2915 norm_sjinfo.delay_upper_joins = false;
2916 norm_sjinfo.join_quals = NIL;
2918 nselec = clauselist_selectivity(root,
2924 /* Avoid leaking a lot of ListCells */
2925 if (jointype == JOIN_ANTI)
2926 list_free(joinquals);
2929 * jselec can be interpreted as the fraction of outer-rel rows that have
2930 * any matches (this is true for both SEMI and ANTI cases). And nselec is
2931 * the fraction of the Cartesian product that matches. So, the average
2932 * number of matches for each outer-rel row that has at least one match is
2933 * nselec * inner_rows / jselec.
2935 * Note: it is correct to use the inner rel's "rows" count here, not
2936 * PATH_ROWS(), even if the inner path under consideration is an inner
2937 * indexscan. This is because we have included all the join clauses in
2938 * the selectivity estimate, even ones used in an inner indexscan.
2940 if (jselec > 0) /* protect against zero divide */
2942 avgmatch = nselec * path->innerjoinpath->parent->rows / jselec;
2943 /* Clamp to sane range */
2944 avgmatch = Max(1.0, avgmatch);
2949 *outer_match_frac = jselec;
2950 *match_count = avgmatch;
2953 * If requested, check whether the inner path uses all the joinquals as
2954 * indexquals. (If that's true, we can assume that an unmatched outer
2955 * tuple is cheap to process, whereas otherwise it's probably expensive.)
2957 if (indexed_join_quals)
2959 if (path->joinrestrictinfo != NIL)
2963 nrclauses = select_nonredundant_join_clauses(root,
2964 path->joinrestrictinfo,
2965 path->innerjoinpath);
2966 *indexed_join_quals = (nrclauses == NIL);
2970 /* a clauseless join does NOT qualify */
2971 *indexed_join_quals = false;
2980 * approx_tuple_count
2981 * Quick-and-dirty estimation of the number of join rows passing
2982 * a set of qual conditions.
2984 * The quals can be either an implicitly-ANDed list of boolean expressions,
2985 * or a list of RestrictInfo nodes (typically the latter).
2987 * We intentionally compute the selectivity under JOIN_INNER rules, even
2988 * if it's some type of outer join. This is appropriate because we are
2989 * trying to figure out how many tuples pass the initial merge or hash
2992 * This is quick-and-dirty because we bypass clauselist_selectivity, and
2993 * simply multiply the independent clause selectivities together. Now
2994 * clauselist_selectivity often can't do any better than that anyhow, but
2995 * for some situations (such as range constraints) it is smarter. However,
2996 * we can't effectively cache the results of clauselist_selectivity, whereas
2997 * the individual clause selectivities can be and are cached.
2999 * Since we are only using the results to estimate how many potential
3000 * output tuples are generated and passed through qpqual checking, it
3001 * seems OK to live with the approximation.
3004 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
3007 double outer_tuples = path->outerjoinpath->parent->rows;
3008 double inner_tuples = path->innerjoinpath->parent->rows;
3009 SpecialJoinInfo sjinfo;
3010 Selectivity selec = 1.0;
3014 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
3016 sjinfo.type = T_SpecialJoinInfo;
3017 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
3018 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
3019 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
3020 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
3021 sjinfo.jointype = JOIN_INNER;
3022 /* we don't bother trying to make the remaining fields valid */
3023 sjinfo.lhs_strict = false;
3024 sjinfo.delay_upper_joins = false;
3025 sjinfo.join_quals = NIL;
3027 /* Get the approximate selectivity */
3030 Node *qual = (Node *) lfirst(l);
3032 /* Note that clause_selectivity will be able to cache its result */
3033 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
3036 /* Apply it to the input relation sizes */
3037 tuples = selec * outer_tuples * inner_tuples;
3039 return clamp_row_est(tuples);
3044 * set_baserel_size_estimates
3045 * Set the size estimates for the given base relation.
3047 * The rel's targetlist and restrictinfo list must have been constructed
3048 * already, and rel->tuples must be set.
3050 * We set the following fields of the rel node:
3051 * rows: the estimated number of output tuples (after applying
3052 * restriction clauses).
3053 * width: the estimated average output tuple width in bytes.
3054 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
3057 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3061 /* Should only be applied to base relations */
3062 Assert(rel->relid > 0);
3064 nrows = rel->tuples *
3065 clauselist_selectivity(root,
3066 rel->baserestrictinfo,
3071 rel->rows = clamp_row_est(nrows);
3073 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3075 set_rel_width(root, rel);
3079 * set_joinrel_size_estimates
3080 * Set the size estimates for the given join relation.
3082 * The rel's targetlist must have been constructed already, and a
3083 * restriction clause list that matches the given component rels must
3086 * Since there is more than one way to make a joinrel for more than two
3087 * base relations, the results we get here could depend on which component
3088 * rel pair is provided. In theory we should get the same answers no matter
3089 * which pair is provided; in practice, since the selectivity estimation
3090 * routines don't handle all cases equally well, we might not. But there's
3091 * not much to be done about it. (Would it make sense to repeat the
3092 * calculations for each pair of input rels that's encountered, and somehow
3093 * average the results? Probably way more trouble than it's worth.)
3095 * We set only the rows field here. The width field was already set by
3096 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3099 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3100 RelOptInfo *outer_rel,
3101 RelOptInfo *inner_rel,
3102 SpecialJoinInfo *sjinfo,
3105 JoinType jointype = sjinfo->jointype;
3111 * Compute joinclause selectivity. Note that we are only considering
3112 * clauses that become restriction clauses at this join level; we are not
3113 * double-counting them because they were not considered in estimating the
3114 * sizes of the component rels.
3116 * For an outer join, we have to distinguish the selectivity of the join's
3117 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3118 * down". For inner joins we just count them all as joinclauses.
3120 if (IS_OUTER_JOIN(jointype))
3122 List *joinquals = NIL;
3123 List *pushedquals = NIL;
3126 /* Grovel through the clauses to separate into two lists */
3127 foreach(l, restrictlist)
3129 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3131 Assert(IsA(rinfo, RestrictInfo));
3132 if (rinfo->is_pushed_down)
3133 pushedquals = lappend(pushedquals, rinfo);
3135 joinquals = lappend(joinquals, rinfo);
3138 /* Get the separate selectivities */
3139 jselec = clauselist_selectivity(root,
3144 pselec = clauselist_selectivity(root,
3150 /* Avoid leaking a lot of ListCells */
3151 list_free(joinquals);
3152 list_free(pushedquals);
3156 jselec = clauselist_selectivity(root,
3161 pselec = 0.0; /* not used, keep compiler quiet */
3165 * Basically, we multiply size of Cartesian product by selectivity.
3167 * If we are doing an outer join, take that into account: the joinqual
3168 * selectivity has to be clamped using the knowledge that the output must
3169 * be at least as large as the non-nullable input. However, any
3170 * pushed-down quals are applied after the outer join, so their
3171 * selectivity applies fully.
3173 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3174 * of LHS rows that have matches, and we apply that straightforwardly.
3179 nrows = outer_rel->rows * inner_rel->rows * jselec;
3182 nrows = outer_rel->rows * inner_rel->rows * jselec;
3183 if (nrows < outer_rel->rows)
3184 nrows = outer_rel->rows;
3188 nrows = outer_rel->rows * inner_rel->rows * jselec;
3189 if (nrows < outer_rel->rows)
3190 nrows = outer_rel->rows;
3191 if (nrows < inner_rel->rows)
3192 nrows = inner_rel->rows;
3196 nrows = outer_rel->rows * jselec;
3197 /* pselec not used */
3200 nrows = outer_rel->rows * (1.0 - jselec);
3204 /* other values not expected here */
3205 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3206 nrows = 0; /* keep compiler quiet */
3210 rel->rows = clamp_row_est(nrows);
3214 * set_subquery_size_estimates
3215 * Set the size estimates for a base relation that is a subquery.
3217 * The rel's targetlist and restrictinfo list must have been constructed
3218 * already, and the plan for the subquery must have been completed.
3219 * We look at the subquery's plan and PlannerInfo to extract data.
3221 * We set the same fields as set_baserel_size_estimates.
3224 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3225 PlannerInfo *subroot)
3230 /* Should only be applied to base relations that are subqueries */
3231 Assert(rel->relid > 0);
3232 rte = planner_rt_fetch(rel->relid, root);
3233 Assert(rte->rtekind == RTE_SUBQUERY);
3235 /* Copy raw number of output rows from subplan */
3236 rel->tuples = rel->subplan->plan_rows;
3239 * Compute per-output-column width estimates by examining the subquery's
3240 * targetlist. For any output that is a plain Var, get the width estimate
3241 * that was made while planning the subquery. Otherwise, fall back on a
3242 * datatype-based estimate.
3244 foreach(lc, subroot->parse->targetList)
3246 TargetEntry *te = (TargetEntry *) lfirst(lc);
3247 Node *texpr = (Node *) te->expr;
3250 Assert(IsA(te, TargetEntry));
3251 /* junk columns aren't visible to upper query */
3256 * XXX This currently doesn't work for subqueries containing set
3257 * operations, because the Vars in their tlists are bogus references
3258 * to the first leaf subquery, which wouldn't give the right answer
3259 * even if we could still get to its PlannerInfo. So fall back on
3260 * datatype in that case.
3262 if (IsA(texpr, Var) &&
3263 subroot->parse->setOperations == NULL)
3265 Var *var = (Var *) texpr;
3266 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3268 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3272 item_width = get_typavgwidth(exprType(texpr), exprTypmod(texpr));
3274 Assert(item_width > 0);
3275 Assert(te->resno >= rel->min_attr && te->resno <= rel->max_attr);
3276 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3279 /* Now estimate number of output rows, etc */
3280 set_baserel_size_estimates(root, rel);
3284 * set_function_size_estimates
3285 * Set the size estimates for a base relation that is a function call.
3287 * The rel's targetlist and restrictinfo list must have been constructed
3290 * We set the same fields as set_baserel_size_estimates.
3293 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3297 /* Should only be applied to base relations that are functions */
3298 Assert(rel->relid > 0);
3299 rte = planner_rt_fetch(rel->relid, root);
3300 Assert(rte->rtekind == RTE_FUNCTION);
3302 /* Estimate number of rows the function itself will return */
3303 rel->tuples = clamp_row_est(expression_returns_set_rows(rte->funcexpr));
3305 /* Now estimate number of output rows, etc */
3306 set_baserel_size_estimates(root, rel);
3310 * set_values_size_estimates
3311 * Set the size estimates for a base relation that is a values list.
3313 * The rel's targetlist and restrictinfo list must have been constructed
3316 * We set the same fields as set_baserel_size_estimates.
3319 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3323 /* Should only be applied to base relations that are values lists */
3324 Assert(rel->relid > 0);
3325 rte = planner_rt_fetch(rel->relid, root);
3326 Assert(rte->rtekind == RTE_VALUES);
3329 * Estimate number of rows the values list will return. We know this
3330 * precisely based on the list length (well, barring set-returning
3331 * functions in list items, but that's a refinement not catered for
3332 * anywhere else either).
3334 rel->tuples = list_length(rte->values_lists);
3336 /* Now estimate number of output rows, etc */
3337 set_baserel_size_estimates(root, rel);
3341 * set_cte_size_estimates
3342 * Set the size estimates for a base relation that is a CTE reference.
3344 * The rel's targetlist and restrictinfo list must have been constructed
3345 * already, and we need the completed plan for the CTE (if a regular CTE)
3346 * or the non-recursive term (if a self-reference).
3348 * We set the same fields as set_baserel_size_estimates.
3351 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3355 /* Should only be applied to base relations that are CTE references */
3356 Assert(rel->relid > 0);
3357 rte = planner_rt_fetch(rel->relid, root);
3358 Assert(rte->rtekind == RTE_CTE);
3360 if (rte->self_reference)
3363 * In a self-reference, arbitrarily assume the average worktable size
3364 * is about 10 times the nonrecursive term's size.
3366 rel->tuples = 10 * cteplan->plan_rows;
3370 /* Otherwise just believe the CTE plan's output estimate */
3371 rel->tuples = cteplan->plan_rows;
3374 /* Now estimate number of output rows, etc */
3375 set_baserel_size_estimates(root, rel);
3379 * set_foreign_size_estimates
3380 * Set the size estimates for a base relation that is a foreign table.
3382 * There is not a whole lot that we can do here; the foreign-data wrapper
3383 * is responsible for producing useful estimates. We can do a decent job
3384 * of estimating baserestrictcost, so we set that, and we also set up width
3385 * using what will be purely datatype-driven estimates from the targetlist.
3386 * There is no way to do anything sane with the rows value, so we just put
3387 * a default estimate and hope that the wrapper can improve on it. The
3388 * wrapper's PlanForeignScan function will be called momentarily.
3390 * The rel's targetlist and restrictinfo list must have been constructed
3394 set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3396 /* Should only be applied to base relations */
3397 Assert(rel->relid > 0);
3399 rel->rows = 1000; /* entirely bogus default estimate */
3401 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3403 set_rel_width(root, rel);
3409 * Set the estimated output width of a base relation.
3411 * The estimated output width is the sum of the per-attribute width estimates
3412 * for the actually-referenced columns, plus any PHVs or other expressions
3413 * that have to be calculated at this relation. This is the amount of data
3414 * we'd need to pass upwards in case of a sort, hash, etc.
3416 * NB: this works best on plain relations because it prefers to look at
3417 * real Vars. For subqueries, set_subquery_size_estimates will already have
3418 * copied up whatever per-column estimates were made within the subquery,
3419 * and for other types of rels there isn't much we can do anyway. We fall
3420 * back on (fairly stupid) datatype-based width estimates if we can't get
3421 * any better number.
3423 * The per-attribute width estimates are cached for possible re-use while
3424 * building join relations.
3427 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3429 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3430 int32 tuple_width = 0;
3431 bool have_wholerow_var = false;
3434 foreach(lc, rel->reltargetlist)
3436 Node *node = (Node *) lfirst(lc);
3440 Var *var = (Var *) node;
3444 Assert(var->varno == rel->relid);
3445 Assert(var->varattno >= rel->min_attr);
3446 Assert(var->varattno <= rel->max_attr);
3448 ndx = var->varattno - rel->min_attr;
3451 * If it's a whole-row Var, we'll deal with it below after we have
3452 * already cached as many attr widths as possible.
3454 if (var->varattno == 0)
3456 have_wholerow_var = true;
3461 * The width may have been cached already (especially if it's a
3462 * subquery), so don't duplicate effort.
3464 if (rel->attr_widths[ndx] > 0)
3466 tuple_width += rel->attr_widths[ndx];
3470 /* Try to get column width from statistics */
3471 if (reloid != InvalidOid && var->varattno > 0)
3473 item_width = get_attavgwidth(reloid, var->varattno);
3476 rel->attr_widths[ndx] = item_width;
3477 tuple_width += item_width;
3483 * Not a plain relation, or can't find statistics for it. Estimate
3484 * using just the type info.
3486 item_width = get_typavgwidth(var->vartype, var->vartypmod);
3487 Assert(item_width > 0);
3488 rel->attr_widths[ndx] = item_width;
3489 tuple_width += item_width;
3491 else if (IsA(node, PlaceHolderVar))
3493 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3494 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
3496 tuple_width += phinfo->ph_width;
3501 * We could be looking at an expression pulled up from a subquery,
3502 * or a ROW() representing a whole-row child Var, etc. Do what we
3503 * can using the expression type information.
3507 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
3508 Assert(item_width > 0);
3509 tuple_width += item_width;
3514 * If we have a whole-row reference, estimate its width as the sum of
3515 * per-column widths plus sizeof(HeapTupleHeaderData).
3517 if (have_wholerow_var)
3519 int32 wholerow_width = sizeof(HeapTupleHeaderData);
3521 if (reloid != InvalidOid)
3523 /* Real relation, so estimate true tuple width */
3524 wholerow_width += get_relation_data_width(reloid,
3525 rel->attr_widths - rel->min_attr);
3529 /* Do what we can with info for a phony rel */
3532 for (i = 1; i <= rel->max_attr; i++)
3533 wholerow_width += rel->attr_widths[i - rel->min_attr];
3536 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
3539 * Include the whole-row Var as part of the output tuple. Yes, that
3540 * really is what happens at runtime.
3542 tuple_width += wholerow_width;
3545 Assert(tuple_width >= 0);
3546 rel->width = tuple_width;
3550 * relation_byte_size
3551 * Estimate the storage space in bytes for a given number of tuples
3552 * of a given width (size in bytes).
3555 relation_byte_size(double tuples, int width)
3557 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
3562 * Returns an estimate of the number of pages covered by a given
3563 * number of tuples of a given width (size in bytes).
3566 page_size(double tuples, int width)
3568 return ceil(relation_byte_size(tuples, width) / BLCKSZ);