]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/costsize.c
Improve relation width estimation for subqueries.
[postgresql] / src / backend / optimizer / path / costsize.c
1 /*-------------------------------------------------------------------------
2  *
3  * costsize.c
4  *        Routines to compute (and set) relation sizes and path costs
5  *
6  * Path costs are measured in arbitrary units established by these basic
7  * parameters:
8  *
9  *      seq_page_cost           Cost of a sequential page fetch
10  *      random_page_cost        Cost of a non-sequential page fetch
11  *      cpu_tuple_cost          Cost of typical CPU time to process a tuple
12  *      cpu_index_tuple_cost  Cost of typical CPU time to process an index tuple
13  *      cpu_operator_cost       Cost of CPU time to execute an operator or function
14  *
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.)
19  *
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.)
24  *
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.
29  *
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.
34  *
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.
49  *
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.
56  *
57  *
58  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
59  * Portions Copyright (c) 1994, Regents of the University of California
60  *
61  * IDENTIFICATION
62  *        src/backend/optimizer/path/costsize.c
63  *
64  *-------------------------------------------------------------------------
65  */
66
67 #include "postgres.h"
68
69 #include <math.h>
70
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"
87
88
89 #define LOG2(x)  (log(x) / 0.693147180559945)
90
91 /*
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:
94  */
95 #define PATH_ROWS(path) \
96         (IsA(path, UniquePath) ? \
97          ((UniquePath *) (path))->rows : \
98          (path)->parent->rows)
99
100
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;
106
107 int                     effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
108
109 Cost            disable_cost = 1.0e10;
110
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;
121
122 typedef struct
123 {
124         PlannerInfo *root;
125         QualCost        total;
126 } cost_qual_eval_context;
127
128 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
129                            RestrictInfo *rinfo,
130                            PathKey *pathkey);
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,
140                                    List *quals);
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);
144
145
146 /*
147  * clamp_row_est
148  *              Force a row-count estimate to a sane value.
149  */
150 double
151 clamp_row_est(double nrows)
152 {
153         /*
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.
157          */
158         if (nrows <= 1.0)
159                 nrows = 1.0;
160         else
161                 nrows = rint(nrows);
162
163         return nrows;
164 }
165
166
167 /*
168  * cost_seqscan
169  *        Determines and returns the cost of scanning a relation sequentially.
170  */
171 void
172 cost_seqscan(Path *path, PlannerInfo *root,
173                          RelOptInfo *baserel)
174 {
175         double          spc_seq_page_cost;
176         Cost            startup_cost = 0;
177         Cost            run_cost = 0;
178         Cost            cpu_per_tuple;
179
180         /* Should only be applied to base relations */
181         Assert(baserel->relid > 0);
182         Assert(baserel->rtekind == RTE_RELATION);
183
184         if (!enable_seqscan)
185                 startup_cost += disable_cost;
186
187         /* fetch estimated page cost for tablespace containing table */
188         get_tablespace_page_costs(baserel->reltablespace,
189                                                           NULL,
190                                                           &spc_seq_page_cost);
191
192         /*
193          * disk costs
194          */
195         run_cost += spc_seq_page_cost * baserel->pages;
196
197         /* CPU costs */
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;
201
202         path->startup_cost = startup_cost;
203         path->total_cost = startup_cost + run_cost;
204 }
205
206 /*
207  * cost_index
208  *        Determines and returns the cost of scanning a relation using an index.
209  *
210  * 'index' is the index to be used
211  * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
212  * 'outer_rel' is the outer relation when we are considering using the index
213  *              scan as the inside of a nestloop join (hence, some of the indexQuals
214  *              are join clauses, and we should expect repeated scans of the index);
215  *              NULL for a plain index scan
216  *
217  * cost_index() takes an IndexPath not just a Path, because it sets a few
218  * additional fields of the IndexPath besides startup_cost and total_cost.
219  * These fields are needed if the IndexPath is used in a BitmapIndexScan.
220  *
221  * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
222  * Any additional quals evaluated as qpquals may reduce the number of returned
223  * tuples, but they won't reduce the number of tuples we have to fetch from
224  * the table, so they don't reduce the scan cost.
225  *
226  * NOTE: as of 8.0, indexQuals is a list of RestrictInfo nodes, where formerly
227  * it was a list of bare clause expressions.
228  */
229 void
230 cost_index(IndexPath *path, PlannerInfo *root,
231                    IndexOptInfo *index,
232                    List *indexQuals,
233                    RelOptInfo *outer_rel)
234 {
235         RelOptInfo *baserel = index->rel;
236         Cost            startup_cost = 0;
237         Cost            run_cost = 0;
238         Cost            indexStartupCost;
239         Cost            indexTotalCost;
240         Selectivity indexSelectivity;
241         double          indexCorrelation,
242                                 csquared;
243         double          spc_seq_page_cost,
244                                 spc_random_page_cost;
245         Cost            min_IO_cost,
246                                 max_IO_cost;
247         Cost            cpu_per_tuple;
248         double          tuples_fetched;
249         double          pages_fetched;
250
251         /* Should only be applied to base relations */
252         Assert(IsA(baserel, RelOptInfo) &&
253                    IsA(index, IndexOptInfo));
254         Assert(baserel->relid > 0);
255         Assert(baserel->rtekind == RTE_RELATION);
256
257         if (!enable_indexscan)
258                 startup_cost += disable_cost;
259
260         /*
261          * Call index-access-method-specific code to estimate the processing cost
262          * for scanning the index, as well as the selectivity of the index (ie,
263          * the fraction of main-table tuples we will have to retrieve) and its
264          * correlation to the main-table tuple order.
265          */
266         OidFunctionCall8(index->amcostestimate,
267                                          PointerGetDatum(root),
268                                          PointerGetDatum(index),
269                                          PointerGetDatum(indexQuals),
270                                          PointerGetDatum(outer_rel),
271                                          PointerGetDatum(&indexStartupCost),
272                                          PointerGetDatum(&indexTotalCost),
273                                          PointerGetDatum(&indexSelectivity),
274                                          PointerGetDatum(&indexCorrelation));
275
276         /*
277          * Save amcostestimate's results for possible use in bitmap scan planning.
278          * We don't bother to save indexStartupCost or indexCorrelation, because a
279          * bitmap scan doesn't care about either.
280          */
281         path->indextotalcost = indexTotalCost;
282         path->indexselectivity = indexSelectivity;
283
284         /* all costs for touching index itself included here */
285         startup_cost += indexStartupCost;
286         run_cost += indexTotalCost - indexStartupCost;
287
288         /* estimate number of main-table tuples fetched */
289         tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
290
291         /* fetch estimated page costs for tablespace containing table */
292         get_tablespace_page_costs(baserel->reltablespace,
293                                                           &spc_random_page_cost,
294                                                           &spc_seq_page_cost);
295
296         /*----------
297          * Estimate number of main-table pages fetched, and compute I/O cost.
298          *
299          * When the index ordering is uncorrelated with the table ordering,
300          * we use an approximation proposed by Mackert and Lohman (see
301          * index_pages_fetched() for details) to compute the number of pages
302          * fetched, and then charge spc_random_page_cost per page fetched.
303          *
304          * When the index ordering is exactly correlated with the table ordering
305          * (just after a CLUSTER, for example), the number of pages fetched should
306          * be exactly selectivity * table_size.  What's more, all but the first
307          * will be sequential fetches, not the random fetches that occur in the
308          * uncorrelated case.  So if the number of pages is more than 1, we
309          * ought to charge
310          *              spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
311          * For partially-correlated indexes, we ought to charge somewhere between
312          * these two estimates.  We currently interpolate linearly between the
313          * estimates based on the correlation squared (XXX is that appropriate?).
314          *----------
315          */
316         if (outer_rel != NULL && outer_rel->rows > 1)
317         {
318                 /*
319                  * For repeated indexscans, the appropriate estimate for the
320                  * uncorrelated case is to scale up the number of tuples fetched in
321                  * the Mackert and Lohman formula by the number of scans, so that we
322                  * estimate the number of pages fetched by all the scans; then
323                  * pro-rate the costs for one scan.  In this case we assume all the
324                  * fetches are random accesses.
325                  */
326                 double          num_scans = outer_rel->rows;
327
328                 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
329                                                                                         baserel->pages,
330                                                                                         (double) index->pages,
331                                                                                         root);
332
333                 max_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
334
335                 /*
336                  * In the perfectly correlated case, the number of pages touched by
337                  * each scan is selectivity * table_size, and we can use the Mackert
338                  * and Lohman formula at the page level to estimate how much work is
339                  * saved by caching across scans.  We still assume all the fetches are
340                  * random, though, which is an overestimate that's hard to correct for
341                  * without double-counting the cache effects.  (But in most cases
342                  * where such a plan is actually interesting, only one page would get
343                  * fetched per scan anyway, so it shouldn't matter much.)
344                  */
345                 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
346
347                 pages_fetched = index_pages_fetched(pages_fetched * num_scans,
348                                                                                         baserel->pages,
349                                                                                         (double) index->pages,
350                                                                                         root);
351
352                 min_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
353         }
354         else
355         {
356                 /*
357                  * Normal case: apply the Mackert and Lohman formula, and then
358                  * interpolate between that and the correlation-derived result.
359                  */
360                 pages_fetched = index_pages_fetched(tuples_fetched,
361                                                                                         baserel->pages,
362                                                                                         (double) index->pages,
363                                                                                         root);
364
365                 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
366                 max_IO_cost = pages_fetched * spc_random_page_cost;
367
368                 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
369                 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
370                 min_IO_cost = spc_random_page_cost;
371                 if (pages_fetched > 1)
372                         min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
373         }
374
375         /*
376          * Now interpolate based on estimated index order correlation to get total
377          * disk I/O cost for main table accesses.
378          */
379         csquared = indexCorrelation * indexCorrelation;
380
381         run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
382
383         /*
384          * Estimate CPU costs per tuple.
385          *
386          * Normally the indexquals will be removed from the list of restriction
387          * clauses that we have to evaluate as qpquals, so we should subtract
388          * their costs from baserestrictcost.  But if we are doing a join then
389          * some of the indexquals are join clauses and shouldn't be subtracted.
390          * Rather than work out exactly how much to subtract, we don't subtract
391          * anything.
392          */
393         startup_cost += baserel->baserestrictcost.startup;
394         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
395
396         if (outer_rel == NULL)
397         {
398                 QualCost        index_qual_cost;
399
400                 cost_qual_eval(&index_qual_cost, indexQuals, root);
401                 /* any startup cost still has to be paid ... */
402                 cpu_per_tuple -= index_qual_cost.per_tuple;
403         }
404
405         run_cost += cpu_per_tuple * tuples_fetched;
406
407         path->path.startup_cost = startup_cost;
408         path->path.total_cost = startup_cost + run_cost;
409 }
410
411 /*
412  * index_pages_fetched
413  *        Estimate the number of pages actually fetched after accounting for
414  *        cache effects.
415  *
416  * We use an approximation proposed by Mackert and Lohman, "Index Scans
417  * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
418  * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
419  * The Mackert and Lohman approximation is that the number of pages
420  * fetched is
421  *      PF =
422  *              min(2TNs/(2T+Ns), T)                    when T <= b
423  *              2TNs/(2T+Ns)                                    when T > b and Ns <= 2Tb/(2T-b)
424  *              b + (Ns - 2Tb/(2T-b))*(T-b)/T   when T > b and Ns > 2Tb/(2T-b)
425  * where
426  *              T = # pages in table
427  *              N = # tuples in table
428  *              s = selectivity = fraction of table to be scanned
429  *              b = # buffer pages available (we include kernel space here)
430  *
431  * We assume that effective_cache_size is the total number of buffer pages
432  * available for the whole query, and pro-rate that space across all the
433  * tables in the query and the index currently under consideration.  (This
434  * ignores space needed for other indexes used by the query, but since we
435  * don't know which indexes will get used, we can't estimate that very well;
436  * and in any case counting all the tables may well be an overestimate, since
437  * depending on the join plan not all the tables may be scanned concurrently.)
438  *
439  * The product Ns is the number of tuples fetched; we pass in that
440  * product rather than calculating it here.  "pages" is the number of pages
441  * in the object under consideration (either an index or a table).
442  * "index_pages" is the amount to add to the total table space, which was
443  * computed for us by query_planner.
444  *
445  * Caller is expected to have ensured that tuples_fetched is greater than zero
446  * and rounded to integer (see clamp_row_est).  The result will likewise be
447  * greater than zero and integral.
448  */
449 double
450 index_pages_fetched(double tuples_fetched, BlockNumber pages,
451                                         double index_pages, PlannerInfo *root)
452 {
453         double          pages_fetched;
454         double          total_pages;
455         double          T,
456                                 b;
457
458         /* T is # pages in table, but don't allow it to be zero */
459         T = (pages > 1) ? (double) pages : 1.0;
460
461         /* Compute number of pages assumed to be competing for cache space */
462         total_pages = root->total_table_pages + index_pages;
463         total_pages = Max(total_pages, 1.0);
464         Assert(T <= total_pages);
465
466         /* b is pro-rated share of effective_cache_size */
467         b = (double) effective_cache_size *T / total_pages;
468
469         /* force it positive and integral */
470         if (b <= 1.0)
471                 b = 1.0;
472         else
473                 b = ceil(b);
474
475         /* This part is the Mackert and Lohman formula */
476         if (T <= b)
477         {
478                 pages_fetched =
479                         (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
480                 if (pages_fetched >= T)
481                         pages_fetched = T;
482                 else
483                         pages_fetched = ceil(pages_fetched);
484         }
485         else
486         {
487                 double          lim;
488
489                 lim = (2.0 * T * b) / (2.0 * T - b);
490                 if (tuples_fetched <= lim)
491                 {
492                         pages_fetched =
493                                 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
494                 }
495                 else
496                 {
497                         pages_fetched =
498                                 b + (tuples_fetched - lim) * (T - b) / T;
499                 }
500                 pages_fetched = ceil(pages_fetched);
501         }
502         return pages_fetched;
503 }
504
505 /*
506  * get_indexpath_pages
507  *              Determine the total size of the indexes used in a bitmap index path.
508  *
509  * Note: if the same index is used more than once in a bitmap tree, we will
510  * count it multiple times, which perhaps is the wrong thing ... but it's
511  * not completely clear, and detecting duplicates is difficult, so ignore it
512  * for now.
513  */
514 static double
515 get_indexpath_pages(Path *bitmapqual)
516 {
517         double          result = 0;
518         ListCell   *l;
519
520         if (IsA(bitmapqual, BitmapAndPath))
521         {
522                 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
523
524                 foreach(l, apath->bitmapquals)
525                 {
526                         result += get_indexpath_pages((Path *) lfirst(l));
527                 }
528         }
529         else if (IsA(bitmapqual, BitmapOrPath))
530         {
531                 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
532
533                 foreach(l, opath->bitmapquals)
534                 {
535                         result += get_indexpath_pages((Path *) lfirst(l));
536                 }
537         }
538         else if (IsA(bitmapqual, IndexPath))
539         {
540                 IndexPath  *ipath = (IndexPath *) bitmapqual;
541
542                 result = (double) ipath->indexinfo->pages;
543         }
544         else
545                 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
546
547         return result;
548 }
549
550 /*
551  * cost_bitmap_heap_scan
552  *        Determines and returns the cost of scanning a relation using a bitmap
553  *        index-then-heap plan.
554  *
555  * 'baserel' is the relation to be scanned
556  * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
557  * 'outer_rel' is the outer relation when we are considering using the bitmap
558  *              scan as the inside of a nestloop join (hence, some of the indexQuals
559  *              are join clauses, and we should expect repeated scans of the table);
560  *              NULL for a plain bitmap scan
561  *
562  * Note: if this is a join inner path, the component IndexPaths in bitmapqual
563  * should have been costed accordingly.
564  */
565 void
566 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
567                                           Path *bitmapqual, RelOptInfo *outer_rel)
568 {
569         Cost            startup_cost = 0;
570         Cost            run_cost = 0;
571         Cost            indexTotalCost;
572         Selectivity indexSelectivity;
573         Cost            cpu_per_tuple;
574         Cost            cost_per_page;
575         double          tuples_fetched;
576         double          pages_fetched;
577         double          spc_seq_page_cost,
578                                 spc_random_page_cost;
579         double          T;
580
581         /* Should only be applied to base relations */
582         Assert(IsA(baserel, RelOptInfo));
583         Assert(baserel->relid > 0);
584         Assert(baserel->rtekind == RTE_RELATION);
585
586         if (!enable_bitmapscan)
587                 startup_cost += disable_cost;
588
589         /*
590          * Fetch total cost of obtaining the bitmap, as well as its total
591          * selectivity.
592          */
593         cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
594
595         startup_cost += indexTotalCost;
596
597         /* Fetch estimated page costs for tablespace containing table. */
598         get_tablespace_page_costs(baserel->reltablespace,
599                                                           &spc_random_page_cost,
600                                                           &spc_seq_page_cost);
601
602         /*
603          * Estimate number of main-table pages fetched.
604          */
605         tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
606
607         T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
608
609         if (outer_rel != NULL && outer_rel->rows > 1)
610         {
611                 /*
612                  * For repeated bitmap scans, scale up the number of tuples fetched in
613                  * the Mackert and Lohman formula by the number of scans, so that we
614                  * estimate the number of pages fetched by all the scans. Then
615                  * pro-rate for one scan.
616                  */
617                 double          num_scans = outer_rel->rows;
618
619                 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
620                                                                                         baserel->pages,
621                                                                                         get_indexpath_pages(bitmapqual),
622                                                                                         root);
623                 pages_fetched /= num_scans;
624         }
625         else
626         {
627                 /*
628                  * For a single scan, the number of heap pages that need to be fetched
629                  * is the same as the Mackert and Lohman formula for the case T <= b
630                  * (ie, no re-reads needed).
631                  */
632                 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
633         }
634         if (pages_fetched >= T)
635                 pages_fetched = T;
636         else
637                 pages_fetched = ceil(pages_fetched);
638
639         /*
640          * For small numbers of pages we should charge spc_random_page_cost
641          * apiece, while if nearly all the table's pages are being read, it's more
642          * appropriate to charge spc_seq_page_cost apiece.      The effect is
643          * nonlinear, too. For lack of a better idea, interpolate like this to
644          * determine the cost per page.
645          */
646         if (pages_fetched >= 2.0)
647                 cost_per_page = spc_random_page_cost -
648                         (spc_random_page_cost - spc_seq_page_cost)
649                         * sqrt(pages_fetched / T);
650         else
651                 cost_per_page = spc_random_page_cost;
652
653         run_cost += pages_fetched * cost_per_page;
654
655         /*
656          * Estimate CPU costs per tuple.
657          *
658          * Often the indexquals don't need to be rechecked at each tuple ... but
659          * not always, especially not if there are enough tuples involved that the
660          * bitmaps become lossy.  For the moment, just assume they will be
661          * rechecked always.
662          */
663         startup_cost += baserel->baserestrictcost.startup;
664         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
665
666         run_cost += cpu_per_tuple * tuples_fetched;
667
668         path->startup_cost = startup_cost;
669         path->total_cost = startup_cost + run_cost;
670 }
671
672 /*
673  * cost_bitmap_tree_node
674  *              Extract cost and selectivity from a bitmap tree node (index/and/or)
675  */
676 void
677 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
678 {
679         if (IsA(path, IndexPath))
680         {
681                 *cost = ((IndexPath *) path)->indextotalcost;
682                 *selec = ((IndexPath *) path)->indexselectivity;
683
684                 /*
685                  * Charge a small amount per retrieved tuple to reflect the costs of
686                  * manipulating the bitmap.  This is mostly to make sure that a bitmap
687                  * scan doesn't look to be the same cost as an indexscan to retrieve a
688                  * single tuple.
689                  */
690                 *cost += 0.1 * cpu_operator_cost * ((IndexPath *) path)->rows;
691         }
692         else if (IsA(path, BitmapAndPath))
693         {
694                 *cost = path->total_cost;
695                 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
696         }
697         else if (IsA(path, BitmapOrPath))
698         {
699                 *cost = path->total_cost;
700                 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
701         }
702         else
703         {
704                 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
705                 *cost = *selec = 0;             /* keep compiler quiet */
706         }
707 }
708
709 /*
710  * cost_bitmap_and_node
711  *              Estimate the cost of a BitmapAnd node
712  *
713  * Note that this considers only the costs of index scanning and bitmap
714  * creation, not the eventual heap access.      In that sense the object isn't
715  * truly a Path, but it has enough path-like properties (costs in particular)
716  * to warrant treating it as one.
717  */
718 void
719 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
720 {
721         Cost            totalCost;
722         Selectivity selec;
723         ListCell   *l;
724
725         /*
726          * We estimate AND selectivity on the assumption that the inputs are
727          * independent.  This is probably often wrong, but we don't have the info
728          * to do better.
729          *
730          * The runtime cost of the BitmapAnd itself is estimated at 100x
731          * cpu_operator_cost for each tbm_intersect needed.  Probably too small,
732          * definitely too simplistic?
733          */
734         totalCost = 0.0;
735         selec = 1.0;
736         foreach(l, path->bitmapquals)
737         {
738                 Path       *subpath = (Path *) lfirst(l);
739                 Cost            subCost;
740                 Selectivity subselec;
741
742                 cost_bitmap_tree_node(subpath, &subCost, &subselec);
743
744                 selec *= subselec;
745
746                 totalCost += subCost;
747                 if (l != list_head(path->bitmapquals))
748                         totalCost += 100.0 * cpu_operator_cost;
749         }
750         path->bitmapselectivity = selec;
751         path->path.startup_cost = totalCost;
752         path->path.total_cost = totalCost;
753 }
754
755 /*
756  * cost_bitmap_or_node
757  *              Estimate the cost of a BitmapOr node
758  *
759  * See comments for cost_bitmap_and_node.
760  */
761 void
762 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
763 {
764         Cost            totalCost;
765         Selectivity selec;
766         ListCell   *l;
767
768         /*
769          * We estimate OR selectivity on the assumption that the inputs are
770          * non-overlapping, since that's often the case in "x IN (list)" type
771          * situations.  Of course, we clamp to 1.0 at the end.
772          *
773          * The runtime cost of the BitmapOr itself is estimated at 100x
774          * cpu_operator_cost for each tbm_union needed.  Probably too small,
775          * definitely too simplistic?  We are aware that the tbm_unions are
776          * optimized out when the inputs are BitmapIndexScans.
777          */
778         totalCost = 0.0;
779         selec = 0.0;
780         foreach(l, path->bitmapquals)
781         {
782                 Path       *subpath = (Path *) lfirst(l);
783                 Cost            subCost;
784                 Selectivity subselec;
785
786                 cost_bitmap_tree_node(subpath, &subCost, &subselec);
787
788                 selec += subselec;
789
790                 totalCost += subCost;
791                 if (l != list_head(path->bitmapquals) &&
792                         !IsA(subpath, IndexPath))
793                         totalCost += 100.0 * cpu_operator_cost;
794         }
795         path->bitmapselectivity = Min(selec, 1.0);
796         path->path.startup_cost = totalCost;
797         path->path.total_cost = totalCost;
798 }
799
800 /*
801  * cost_tidscan
802  *        Determines and returns the cost of scanning a relation using TIDs.
803  */
804 void
805 cost_tidscan(Path *path, PlannerInfo *root,
806                          RelOptInfo *baserel, List *tidquals)
807 {
808         Cost            startup_cost = 0;
809         Cost            run_cost = 0;
810         bool            isCurrentOf = false;
811         Cost            cpu_per_tuple;
812         QualCost        tid_qual_cost;
813         int                     ntuples;
814         ListCell   *l;
815         double          spc_random_page_cost;
816
817         /* Should only be applied to base relations */
818         Assert(baserel->relid > 0);
819         Assert(baserel->rtekind == RTE_RELATION);
820
821         /* Count how many tuples we expect to retrieve */
822         ntuples = 0;
823         foreach(l, tidquals)
824         {
825                 if (IsA(lfirst(l), ScalarArrayOpExpr))
826                 {
827                         /* Each element of the array yields 1 tuple */
828                         ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
829                         Node       *arraynode = (Node *) lsecond(saop->args);
830
831                         ntuples += estimate_array_length(arraynode);
832                 }
833                 else if (IsA(lfirst(l), CurrentOfExpr))
834                 {
835                         /* CURRENT OF yields 1 tuple */
836                         isCurrentOf = true;
837                         ntuples++;
838                 }
839                 else
840                 {
841                         /* It's just CTID = something, count 1 tuple */
842                         ntuples++;
843                 }
844         }
845
846         /*
847          * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
848          * understands how to do it correctly.  Therefore, honor enable_tidscan
849          * only when CURRENT OF isn't present.  Also note that cost_qual_eval
850          * counts a CurrentOfExpr as having startup cost disable_cost, which we
851          * subtract off here; that's to prevent other plan types such as seqscan
852          * from winning.
853          */
854         if (isCurrentOf)
855         {
856                 Assert(baserel->baserestrictcost.startup >= disable_cost);
857                 startup_cost -= disable_cost;
858         }
859         else if (!enable_tidscan)
860                 startup_cost += disable_cost;
861
862         /*
863          * The TID qual expressions will be computed once, any other baserestrict
864          * quals once per retrived tuple.
865          */
866         cost_qual_eval(&tid_qual_cost, tidquals, root);
867
868         /* fetch estimated page cost for tablespace containing table */
869         get_tablespace_page_costs(baserel->reltablespace,
870                                                           &spc_random_page_cost,
871                                                           NULL);
872
873         /* disk costs --- assume each tuple on a different page */
874         run_cost += spc_random_page_cost * ntuples;
875
876         /* CPU costs */
877         startup_cost += baserel->baserestrictcost.startup +
878                 tid_qual_cost.per_tuple;
879         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple -
880                 tid_qual_cost.per_tuple;
881         run_cost += cpu_per_tuple * ntuples;
882
883         path->startup_cost = startup_cost;
884         path->total_cost = startup_cost + run_cost;
885 }
886
887 /*
888  * cost_subqueryscan
889  *        Determines and returns the cost of scanning a subquery RTE.
890  */
891 void
892 cost_subqueryscan(Path *path, RelOptInfo *baserel)
893 {
894         Cost            startup_cost;
895         Cost            run_cost;
896         Cost            cpu_per_tuple;
897
898         /* Should only be applied to base relations that are subqueries */
899         Assert(baserel->relid > 0);
900         Assert(baserel->rtekind == RTE_SUBQUERY);
901
902         /*
903          * Cost of path is cost of evaluating the subplan, plus cost of evaluating
904          * any restriction clauses that will be attached to the SubqueryScan node,
905          * plus cpu_tuple_cost to account for selection and projection overhead.
906          */
907         path->startup_cost = baserel->subplan->startup_cost;
908         path->total_cost = baserel->subplan->total_cost;
909
910         startup_cost = baserel->baserestrictcost.startup;
911         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
912         run_cost = cpu_per_tuple * baserel->tuples;
913
914         path->startup_cost += startup_cost;
915         path->total_cost += startup_cost + run_cost;
916 }
917
918 /*
919  * cost_functionscan
920  *        Determines and returns the cost of scanning a function RTE.
921  */
922 void
923 cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
924 {
925         Cost            startup_cost = 0;
926         Cost            run_cost = 0;
927         Cost            cpu_per_tuple;
928         RangeTblEntry *rte;
929         QualCost        exprcost;
930
931         /* Should only be applied to base relations that are functions */
932         Assert(baserel->relid > 0);
933         rte = planner_rt_fetch(baserel->relid, root);
934         Assert(rte->rtekind == RTE_FUNCTION);
935
936         /*
937          * Estimate costs of executing the function expression.
938          *
939          * Currently, nodeFunctionscan.c always executes the function to
940          * completion before returning any rows, and caches the results in a
941          * tuplestore.  So the function eval cost is all startup cost, and per-row
942          * costs are minimal.
943          *
944          * XXX in principle we ought to charge tuplestore spill costs if the
945          * number of rows is large.  However, given how phony our rowcount
946          * estimates for functions tend to be, there's not a lot of point in that
947          * refinement right now.
948          */
949         cost_qual_eval_node(&exprcost, rte->funcexpr, root);
950
951         startup_cost += exprcost.startup + exprcost.per_tuple;
952
953         /* Add scanning CPU costs */
954         startup_cost += baserel->baserestrictcost.startup;
955         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
956         run_cost += cpu_per_tuple * baserel->tuples;
957
958         path->startup_cost = startup_cost;
959         path->total_cost = startup_cost + run_cost;
960 }
961
962 /*
963  * cost_valuesscan
964  *        Determines and returns the cost of scanning a VALUES RTE.
965  */
966 void
967 cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
968 {
969         Cost            startup_cost = 0;
970         Cost            run_cost = 0;
971         Cost            cpu_per_tuple;
972
973         /* Should only be applied to base relations that are values lists */
974         Assert(baserel->relid > 0);
975         Assert(baserel->rtekind == RTE_VALUES);
976
977         /*
978          * For now, estimate list evaluation cost at one operator eval per list
979          * (probably pretty bogus, but is it worth being smarter?)
980          */
981         cpu_per_tuple = cpu_operator_cost;
982
983         /* Add scanning CPU costs */
984         startup_cost += baserel->baserestrictcost.startup;
985         cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
986         run_cost += cpu_per_tuple * baserel->tuples;
987
988         path->startup_cost = startup_cost;
989         path->total_cost = startup_cost + run_cost;
990 }
991
992 /*
993  * cost_ctescan
994  *        Determines and returns the cost of scanning a CTE RTE.
995  *
996  * Note: this is used for both self-reference and regular CTEs; the
997  * possible cost differences are below the threshold of what we could
998  * estimate accurately anyway.  Note that the costs of evaluating the
999  * referenced CTE query are added into the final plan as initplan costs,
1000  * and should NOT be counted here.
1001  */
1002 void
1003 cost_ctescan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
1004 {
1005         Cost            startup_cost = 0;
1006         Cost            run_cost = 0;
1007         Cost            cpu_per_tuple;
1008
1009         /* Should only be applied to base relations that are CTEs */
1010         Assert(baserel->relid > 0);
1011         Assert(baserel->rtekind == RTE_CTE);
1012
1013         /* Charge one CPU tuple cost per row for tuplestore manipulation */
1014         cpu_per_tuple = cpu_tuple_cost;
1015
1016         /* Add scanning CPU costs */
1017         startup_cost += baserel->baserestrictcost.startup;
1018         cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
1019         run_cost += cpu_per_tuple * baserel->tuples;
1020
1021         path->startup_cost = startup_cost;
1022         path->total_cost = startup_cost + run_cost;
1023 }
1024
1025 /*
1026  * cost_recursive_union
1027  *        Determines and returns the cost of performing a recursive union,
1028  *        and also the estimated output size.
1029  *
1030  * We are given Plans for the nonrecursive and recursive terms.
1031  *
1032  * Note that the arguments and output are Plans, not Paths as in most of
1033  * the rest of this module.  That's because we don't bother setting up a
1034  * Path representation for recursive union --- we have only one way to do it.
1035  */
1036 void
1037 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1038 {
1039         Cost            startup_cost;
1040         Cost            total_cost;
1041         double          total_rows;
1042
1043         /* We probably have decent estimates for the non-recursive term */
1044         startup_cost = nrterm->startup_cost;
1045         total_cost = nrterm->total_cost;
1046         total_rows = nrterm->plan_rows;
1047
1048         /*
1049          * We arbitrarily assume that about 10 recursive iterations will be
1050          * needed, and that we've managed to get a good fix on the cost and output
1051          * size of each one of them.  These are mighty shaky assumptions but it's
1052          * hard to see how to do better.
1053          */
1054         total_cost += 10 * rterm->total_cost;
1055         total_rows += 10 * rterm->plan_rows;
1056
1057         /*
1058          * Also charge cpu_tuple_cost per row to account for the costs of
1059          * manipulating the tuplestores.  (We don't worry about possible
1060          * spill-to-disk costs.)
1061          */
1062         total_cost += cpu_tuple_cost * total_rows;
1063
1064         runion->startup_cost = startup_cost;
1065         runion->total_cost = total_cost;
1066         runion->plan_rows = total_rows;
1067         runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1068 }
1069
1070 /*
1071  * cost_sort
1072  *        Determines and returns the cost of sorting a relation, including
1073  *        the cost of reading the input data.
1074  *
1075  * If the total volume of data to sort is less than sort_mem, we will do
1076  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1077  * comparisons for t tuples.
1078  *
1079  * If the total volume exceeds sort_mem, we switch to a tape-style merge
1080  * algorithm.  There will still be about t*log2(t) tuple comparisons in
1081  * total, but we will also need to write and read each tuple once per
1082  * merge pass.  We expect about ceil(logM(r)) merge passes where r is the
1083  * number of initial runs formed and M is the merge order used by tuplesort.c.
1084  * Since the average initial run should be about twice sort_mem, we have
1085  *              disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
1086  *              cpu = comparison_cost * t * log2(t)
1087  *
1088  * If the sort is bounded (i.e., only the first k result tuples are needed)
1089  * and k tuples can fit into sort_mem, we use a heap method that keeps only
1090  * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1091  *
1092  * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1093  * accesses (XXX can't we refine that guess?)
1094  *
1095  * By default, we charge two operator evals per tuple comparison, which should
1096  * be in the right ballpark in most cases.  The caller can tweak this by
1097  * specifying nonzero comparison_cost; typically that's used for any extra
1098  * work that has to be done to prepare the inputs to the comparison operators.
1099  *
1100  * 'pathkeys' is a list of sort keys
1101  * 'input_cost' is the total cost for reading the input data
1102  * 'tuples' is the number of tuples in the relation
1103  * 'width' is the average tuple width in bytes
1104  * 'comparison_cost' is the extra cost per comparison, if any
1105  * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1106  * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1107  *
1108  * NOTE: some callers currently pass NIL for pathkeys because they
1109  * can't conveniently supply the sort keys.  Since this routine doesn't
1110  * currently do anything with pathkeys anyway, that doesn't matter...
1111  * but if it ever does, it should react gracefully to lack of key data.
1112  * (Actually, the thing we'd most likely be interested in is just the number
1113  * of sort keys, which all callers *could* supply.)
1114  */
1115 void
1116 cost_sort(Path *path, PlannerInfo *root,
1117                   List *pathkeys, Cost input_cost, double tuples, int width,
1118                   Cost comparison_cost, int sort_mem,
1119                   double limit_tuples)
1120 {
1121         Cost            startup_cost = input_cost;
1122         Cost            run_cost = 0;
1123         double          input_bytes = relation_byte_size(tuples, width);
1124         double          output_bytes;
1125         double          output_tuples;
1126         long            sort_mem_bytes = sort_mem * 1024L;
1127
1128         if (!enable_sort)
1129                 startup_cost += disable_cost;
1130
1131         /*
1132          * We want to be sure the cost of a sort is never estimated as zero, even
1133          * if passed-in tuple count is zero.  Besides, mustn't do log(0)...
1134          */
1135         if (tuples < 2.0)
1136                 tuples = 2.0;
1137
1138         /* Include the default cost-per-comparison */
1139         comparison_cost += 2.0 * cpu_operator_cost;
1140
1141         /* Do we have a useful LIMIT? */
1142         if (limit_tuples > 0 && limit_tuples < tuples)
1143         {
1144                 output_tuples = limit_tuples;
1145                 output_bytes = relation_byte_size(output_tuples, width);
1146         }
1147         else
1148         {
1149                 output_tuples = tuples;
1150                 output_bytes = input_bytes;
1151         }
1152
1153         if (output_bytes > sort_mem_bytes)
1154         {
1155                 /*
1156                  * We'll have to use a disk-based sort of all the tuples
1157                  */
1158                 double          npages = ceil(input_bytes / BLCKSZ);
1159                 double          nruns = (input_bytes / sort_mem_bytes) * 0.5;
1160                 double          mergeorder = tuplesort_merge_order(sort_mem_bytes);
1161                 double          log_runs;
1162                 double          npageaccesses;
1163
1164                 /*
1165                  * CPU costs
1166                  *
1167                  * Assume about N log2 N comparisons
1168                  */
1169                 startup_cost += comparison_cost * tuples * LOG2(tuples);
1170
1171                 /* Disk costs */
1172
1173                 /* Compute logM(r) as log(r) / log(M) */
1174                 if (nruns > mergeorder)
1175                         log_runs = ceil(log(nruns) / log(mergeorder));
1176                 else
1177                         log_runs = 1.0;
1178                 npageaccesses = 2.0 * npages * log_runs;
1179                 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1180                 startup_cost += npageaccesses *
1181                         (seq_page_cost * 0.75 + random_page_cost * 0.25);
1182         }
1183         else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1184         {
1185                 /*
1186                  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1187                  * a total number of tuple comparisons of N log2 K; but the constant
1188                  * factor is a bit higher than for quicksort.  Tweak it so that the
1189                  * cost curve is continuous at the crossover point.
1190                  */
1191                 startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1192         }
1193         else
1194         {
1195                 /* We'll use plain quicksort on all the input tuples */
1196                 startup_cost += comparison_cost * tuples * LOG2(tuples);
1197         }
1198
1199         /*
1200          * Also charge a small amount (arbitrarily set equal to operator cost) per
1201          * extracted tuple.  We don't charge cpu_tuple_cost because a Sort node
1202          * doesn't do qual-checking or projection, so it has less overhead than
1203          * most plan nodes.  Note it's correct to use tuples not output_tuples
1204          * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1205          * counting the LIMIT otherwise.
1206          */
1207         run_cost += cpu_operator_cost * tuples;
1208
1209         path->startup_cost = startup_cost;
1210         path->total_cost = startup_cost + run_cost;
1211 }
1212
1213 /*
1214  * cost_merge_append
1215  *        Determines and returns the cost of a MergeAppend node.
1216  *
1217  * MergeAppend merges several pre-sorted input streams, using a heap that
1218  * at any given instant holds the next tuple from each stream.  If there
1219  * are N streams, we need about N*log2(N) tuple comparisons to construct
1220  * the heap at startup, and then for each output tuple, about log2(N)
1221  * comparisons to delete the top heap entry and another log2(N) comparisons
1222  * to insert its successor from the same stream.
1223  *
1224  * (The effective value of N will drop once some of the input streams are
1225  * exhausted, but it seems unlikely to be worth trying to account for that.)
1226  *
1227  * The heap is never spilled to disk, since we assume N is not very large.
1228  * So this is much simpler than cost_sort.
1229  *
1230  * As in cost_sort, we charge two operator evals per tuple comparison.
1231  *
1232  * 'pathkeys' is a list of sort keys
1233  * 'n_streams' is the number of input streams
1234  * 'input_startup_cost' is the sum of the input streams' startup costs
1235  * 'input_total_cost' is the sum of the input streams' total costs
1236  * 'tuples' is the number of tuples in all the streams
1237  */
1238 void
1239 cost_merge_append(Path *path, PlannerInfo *root,
1240                                   List *pathkeys, int n_streams,
1241                                   Cost input_startup_cost, Cost input_total_cost,
1242                                   double tuples)
1243 {
1244         Cost            startup_cost = 0;
1245         Cost            run_cost = 0;
1246         Cost            comparison_cost;
1247         double          N;
1248         double          logN;
1249
1250         /*
1251          * Avoid log(0)...
1252          */
1253         N = (n_streams < 2) ? 2.0 : (double) n_streams;
1254         logN = LOG2(N);
1255
1256         /* Assumed cost per tuple comparison */
1257         comparison_cost = 2.0 * cpu_operator_cost;
1258
1259         /* Heap creation cost */
1260         startup_cost += comparison_cost * N * logN;
1261
1262         /* Per-tuple heap maintenance cost */
1263         run_cost += tuples * comparison_cost * 2.0 * logN;
1264
1265         /*
1266          * Also charge a small amount (arbitrarily set equal to operator cost) per
1267          * extracted tuple.  We don't charge cpu_tuple_cost because a MergeAppend
1268          * node doesn't do qual-checking or projection, so it has less overhead
1269          * than most plan nodes.
1270          */
1271         run_cost += cpu_operator_cost * tuples;
1272
1273         path->startup_cost = startup_cost + input_startup_cost;
1274         path->total_cost = startup_cost + run_cost + input_total_cost;
1275 }
1276
1277 /*
1278  * cost_material
1279  *        Determines and returns the cost of materializing a relation, including
1280  *        the cost of reading the input data.
1281  *
1282  * If the total volume of data to materialize exceeds work_mem, we will need
1283  * to write it to disk, so the cost is much higher in that case.
1284  *
1285  * Note that here we are estimating the costs for the first scan of the
1286  * relation, so the materialization is all overhead --- any savings will
1287  * occur only on rescan, which is estimated in cost_rescan.
1288  */
1289 void
1290 cost_material(Path *path,
1291                           Cost input_startup_cost, Cost input_total_cost,
1292                           double tuples, int width)
1293 {
1294         Cost            startup_cost = input_startup_cost;
1295         Cost            run_cost = input_total_cost - input_startup_cost;
1296         double          nbytes = relation_byte_size(tuples, width);
1297         long            work_mem_bytes = work_mem * 1024L;
1298
1299         /*
1300          * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1301          * reflect bookkeeping overhead.  (This rate must be more than what
1302          * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1303          * if it is exactly the same then there will be a cost tie between
1304          * nestloop with A outer, materialized B inner and nestloop with B outer,
1305          * materialized A inner.  The extra cost ensures we'll prefer
1306          * materializing the smaller rel.)      Note that this is normally a good deal
1307          * less than cpu_tuple_cost; which is OK because a Material plan node
1308          * doesn't do qual-checking or projection, so it's got less overhead than
1309          * most plan nodes.
1310          */
1311         run_cost += 2 * cpu_operator_cost * tuples;
1312
1313         /*
1314          * If we will spill to disk, charge at the rate of seq_page_cost per page.
1315          * This cost is assumed to be evenly spread through the plan run phase,
1316          * which isn't exactly accurate but our cost model doesn't allow for
1317          * nonuniform costs within the run phase.
1318          */
1319         if (nbytes > work_mem_bytes)
1320         {
1321                 double          npages = ceil(nbytes / BLCKSZ);
1322
1323                 run_cost += seq_page_cost * npages;
1324         }
1325
1326         path->startup_cost = startup_cost;
1327         path->total_cost = startup_cost + run_cost;
1328 }
1329
1330 /*
1331  * cost_agg
1332  *              Determines and returns the cost of performing an Agg plan node,
1333  *              including the cost of its input.
1334  *
1335  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1336  * are for appropriately-sorted input.
1337  */
1338 void
1339 cost_agg(Path *path, PlannerInfo *root,
1340                  AggStrategy aggstrategy, int numAggs,
1341                  int numGroupCols, double numGroups,
1342                  Cost input_startup_cost, Cost input_total_cost,
1343                  double input_tuples)
1344 {
1345         Cost            startup_cost;
1346         Cost            total_cost;
1347
1348         /*
1349          * We charge one cpu_operator_cost per aggregate function per input tuple,
1350          * and another one per output tuple (corresponding to transfn and finalfn
1351          * calls respectively).  If we are grouping, we charge an additional
1352          * cpu_operator_cost per grouping column per input tuple for grouping
1353          * comparisons.
1354          *
1355          * We will produce a single output tuple if not grouping, and a tuple per
1356          * group otherwise.  We charge cpu_tuple_cost for each output tuple.
1357          *
1358          * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1359          * same total CPU cost, but AGG_SORTED has lower startup cost.  If the
1360          * input path is already sorted appropriately, AGG_SORTED should be
1361          * preferred (since it has no risk of memory overflow).  This will happen
1362          * as long as the computed total costs are indeed exactly equal --- but if
1363          * there's roundoff error we might do the wrong thing.  So be sure that
1364          * the computations below form the same intermediate values in the same
1365          * order.
1366          *
1367          * Note: ideally we should use the pg_proc.procost costs of each
1368          * aggregate's component functions, but for now that seems like an
1369          * excessive amount of work.
1370          */
1371         if (aggstrategy == AGG_PLAIN)
1372         {
1373                 startup_cost = input_total_cost;
1374                 startup_cost += cpu_operator_cost * (input_tuples + 1) * numAggs;
1375                 /* we aren't grouping */
1376                 total_cost = startup_cost + cpu_tuple_cost;
1377         }
1378         else if (aggstrategy == AGG_SORTED)
1379         {
1380                 /* Here we are able to deliver output on-the-fly */
1381                 startup_cost = input_startup_cost;
1382                 total_cost = input_total_cost;
1383                 /* calcs phrased this way to match HASHED case, see note above */
1384                 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1385                 total_cost += cpu_operator_cost * input_tuples * numAggs;
1386                 total_cost += cpu_operator_cost * numGroups * numAggs;
1387                 total_cost += cpu_tuple_cost * numGroups;
1388         }
1389         else
1390         {
1391                 /* must be AGG_HASHED */
1392                 startup_cost = input_total_cost;
1393                 startup_cost += cpu_operator_cost * input_tuples * numGroupCols;
1394                 startup_cost += cpu_operator_cost * input_tuples * numAggs;
1395                 total_cost = startup_cost;
1396                 total_cost += cpu_operator_cost * numGroups * numAggs;
1397                 total_cost += cpu_tuple_cost * numGroups;
1398         }
1399
1400         path->startup_cost = startup_cost;
1401         path->total_cost = total_cost;
1402 }
1403
1404 /*
1405  * cost_windowagg
1406  *              Determines and returns the cost of performing a WindowAgg plan node,
1407  *              including the cost of its input.
1408  *
1409  * Input is assumed already properly sorted.
1410  */
1411 void
1412 cost_windowagg(Path *path, PlannerInfo *root,
1413                            int numWindowFuncs, int numPartCols, int numOrderCols,
1414                            Cost input_startup_cost, Cost input_total_cost,
1415                            double input_tuples)
1416 {
1417         Cost            startup_cost;
1418         Cost            total_cost;
1419
1420         startup_cost = input_startup_cost;
1421         total_cost = input_total_cost;
1422
1423         /*
1424          * We charge one cpu_operator_cost per window function per tuple (often a
1425          * drastic underestimate, but without a way to gauge how many tuples the
1426          * window function will fetch, it's hard to do better).  We also charge
1427          * cpu_operator_cost per grouping column per tuple for grouping
1428          * comparisons, plus cpu_tuple_cost per tuple for general overhead.
1429          */
1430         total_cost += cpu_operator_cost * input_tuples * numWindowFuncs;
1431         total_cost += cpu_operator_cost * input_tuples * (numPartCols + numOrderCols);
1432         total_cost += cpu_tuple_cost * input_tuples;
1433
1434         path->startup_cost = startup_cost;
1435         path->total_cost = total_cost;
1436 }
1437
1438 /*
1439  * cost_group
1440  *              Determines and returns the cost of performing a Group plan node,
1441  *              including the cost of its input.
1442  *
1443  * Note: caller must ensure that input costs are for appropriately-sorted
1444  * input.
1445  */
1446 void
1447 cost_group(Path *path, PlannerInfo *root,
1448                    int numGroupCols, double numGroups,
1449                    Cost input_startup_cost, Cost input_total_cost,
1450                    double input_tuples)
1451 {
1452         Cost            startup_cost;
1453         Cost            total_cost;
1454
1455         startup_cost = input_startup_cost;
1456         total_cost = input_total_cost;
1457
1458         /*
1459          * Charge one cpu_operator_cost per comparison per input tuple. We assume
1460          * all columns get compared at most of the tuples.
1461          */
1462         total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1463
1464         path->startup_cost = startup_cost;
1465         path->total_cost = total_cost;
1466 }
1467
1468 /*
1469  * If a nestloop's inner path is an indexscan, be sure to use its estimated
1470  * output row count, which may be lower than the restriction-clause-only row
1471  * count of its parent.  (We don't include this case in the PATH_ROWS macro
1472  * because it applies *only* to a nestloop's inner relation.)  We have to
1473  * be prepared to recurse through Append or MergeAppend nodes in case of an
1474  * appendrel.  (It's not clear MergeAppend can be seen here, but we may as
1475  * well handle it if so.)
1476  */
1477 static double
1478 nestloop_inner_path_rows(Path *path)
1479 {
1480         double          result;
1481
1482         if (IsA(path, IndexPath))
1483                 result = ((IndexPath *) path)->rows;
1484         else if (IsA(path, BitmapHeapPath))
1485                 result = ((BitmapHeapPath *) path)->rows;
1486         else if (IsA(path, AppendPath))
1487         {
1488                 ListCell   *l;
1489
1490                 result = 0;
1491                 foreach(l, ((AppendPath *) path)->subpaths)
1492                 {
1493                         result += nestloop_inner_path_rows((Path *) lfirst(l));
1494                 }
1495         }
1496         else if (IsA(path, MergeAppendPath))
1497         {
1498                 ListCell   *l;
1499
1500                 result = 0;
1501                 foreach(l, ((MergeAppendPath *) path)->subpaths)
1502                 {
1503                         result += nestloop_inner_path_rows((Path *) lfirst(l));
1504                 }
1505         }
1506         else
1507                 result = PATH_ROWS(path);
1508
1509         return result;
1510 }
1511
1512 /*
1513  * cost_nestloop
1514  *        Determines and returns the cost of joining two relations using the
1515  *        nested loop algorithm.
1516  *
1517  * 'path' is already filled in except for the cost fields
1518  * 'sjinfo' is extra info about the join for selectivity estimation
1519  */
1520 void
1521 cost_nestloop(NestPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1522 {
1523         Path       *outer_path = path->outerjoinpath;
1524         Path       *inner_path = path->innerjoinpath;
1525         Cost            startup_cost = 0;
1526         Cost            run_cost = 0;
1527         Cost            inner_rescan_start_cost;
1528         Cost            inner_rescan_total_cost;
1529         Cost            inner_run_cost;
1530         Cost            inner_rescan_run_cost;
1531         Cost            cpu_per_tuple;
1532         QualCost        restrict_qual_cost;
1533         double          outer_path_rows = PATH_ROWS(outer_path);
1534         double          inner_path_rows = nestloop_inner_path_rows(inner_path);
1535         double          ntuples;
1536         Selectivity outer_match_frac;
1537         Selectivity match_count;
1538         bool            indexed_join_quals;
1539
1540         if (!enable_nestloop)
1541                 startup_cost += disable_cost;
1542
1543         /* estimate costs to rescan the inner relation */
1544         cost_rescan(root, inner_path,
1545                                 &inner_rescan_start_cost,
1546                                 &inner_rescan_total_cost);
1547
1548         /* cost of source data */
1549
1550         /*
1551          * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1552          * before we can start returning tuples, so the join's startup cost is
1553          * their sum.  We'll also pay the inner path's rescan startup cost
1554          * multiple times.
1555          */
1556         startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1557         run_cost += outer_path->total_cost - outer_path->startup_cost;
1558         if (outer_path_rows > 1)
1559                 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1560
1561         inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1562         inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1563
1564         if (adjust_semi_join(root, path, sjinfo,
1565                                                  &outer_match_frac,
1566                                                  &match_count,
1567                                                  &indexed_join_quals))
1568         {
1569                 double          outer_matched_rows;
1570                 Selectivity inner_scan_frac;
1571
1572                 /*
1573                  * SEMI or ANTI join: executor will stop after first match.
1574                  *
1575                  * For an outer-rel row that has at least one match, we can expect the
1576                  * inner scan to stop after a fraction 1/(match_count+1) of the inner
1577                  * rows, if the matches are evenly distributed.  Since they probably
1578                  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1579                  * that fraction.  (If we used a larger fuzz factor, we'd have to
1580                  * clamp inner_scan_frac to at most 1.0; but since match_count is at
1581                  * least 1, no such clamp is needed now.)
1582                  *
1583                  * A complicating factor is that rescans may be cheaper than first
1584                  * scans.  If we never scan all the way to the end of the inner rel,
1585                  * it might be (depending on the plan type) that we'd never pay the
1586                  * whole inner first-scan run cost.  However it is difficult to
1587                  * estimate whether that will happen, so be conservative and always
1588                  * charge the whole first-scan cost once.
1589                  */
1590                 run_cost += inner_run_cost;
1591
1592                 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
1593                 inner_scan_frac = 2.0 / (match_count + 1.0);
1594
1595                 /* Add inner run cost for additional outer tuples having matches */
1596                 if (outer_matched_rows > 1)
1597                         run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1598
1599                 /* Compute number of tuples processed (not number emitted!) */
1600                 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1601
1602                 /*
1603                  * For unmatched outer-rel rows, there are two cases.  If the inner
1604                  * path is an indexscan using all the joinquals as indexquals, then an
1605                  * unmatched row results in an indexscan returning no rows, which is
1606                  * probably quite cheap.  We estimate this case as the same cost to
1607                  * return the first tuple of a nonempty scan.  Otherwise, the executor
1608                  * will have to scan the whole inner rel; not so cheap.
1609                  */
1610                 if (indexed_join_quals)
1611                 {
1612                         run_cost += (outer_path_rows - outer_matched_rows) *
1613                                 inner_rescan_run_cost / inner_path_rows;
1614
1615                         /*
1616                          * We won't be evaluating any quals at all for these rows, so
1617                          * don't add them to ntuples.
1618                          */
1619                 }
1620                 else
1621                 {
1622                         run_cost += (outer_path_rows - outer_matched_rows) *
1623                                 inner_rescan_run_cost;
1624                         ntuples += (outer_path_rows - outer_matched_rows) *
1625                                 inner_path_rows;
1626                 }
1627         }
1628         else
1629         {
1630                 /* Normal case; we'll scan whole input rel for each outer row */
1631                 run_cost += inner_run_cost;
1632                 if (outer_path_rows > 1)
1633                         run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1634
1635                 /* Compute number of tuples processed (not number emitted!) */
1636                 ntuples = outer_path_rows * inner_path_rows;
1637         }
1638
1639         /* CPU costs */
1640         cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1641         startup_cost += restrict_qual_cost.startup;
1642         cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1643         run_cost += cpu_per_tuple * ntuples;
1644
1645         path->path.startup_cost = startup_cost;
1646         path->path.total_cost = startup_cost + run_cost;
1647 }
1648
1649 /*
1650  * cost_mergejoin
1651  *        Determines and returns the cost of joining two relations using the
1652  *        merge join algorithm.
1653  *
1654  * Unlike other costsize functions, this routine makes one actual decision:
1655  * whether we should materialize the inner path.  We do that either because
1656  * the inner path can't support mark/restore, or because it's cheaper to
1657  * use an interposed Material node to handle mark/restore.      When the decision
1658  * is cost-based it would be logically cleaner to build and cost two separate
1659  * paths with and without that flag set; but that would require repeating most
1660  * of the calculations here, which are not all that cheap.      Since the choice
1661  * will not affect output pathkeys or startup cost, only total cost, there is
1662  * no possibility of wanting to keep both paths.  So it seems best to make
1663  * the decision here and record it in the path's materialize_inner field.
1664  *
1665  * 'path' is already filled in except for the cost fields and materialize_inner
1666  * 'sjinfo' is extra info about the join for selectivity estimation
1667  *
1668  * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
1669  * outersortkeys and innersortkeys are lists of the keys to be used
1670  * to sort the outer and inner relations, or NIL if no explicit
1671  * sort is needed because the source path is already ordered.
1672  */
1673 void
1674 cost_mergejoin(MergePath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1675 {
1676         Path       *outer_path = path->jpath.outerjoinpath;
1677         Path       *inner_path = path->jpath.innerjoinpath;
1678         List       *mergeclauses = path->path_mergeclauses;
1679         List       *outersortkeys = path->outersortkeys;
1680         List       *innersortkeys = path->innersortkeys;
1681         Cost            startup_cost = 0;
1682         Cost            run_cost = 0;
1683         Cost            cpu_per_tuple,
1684                                 inner_run_cost,
1685                                 bare_inner_cost,
1686                                 mat_inner_cost;
1687         QualCost        merge_qual_cost;
1688         QualCost        qp_qual_cost;
1689         double          outer_path_rows = PATH_ROWS(outer_path);
1690         double          inner_path_rows = PATH_ROWS(inner_path);
1691         double          outer_rows,
1692                                 inner_rows,
1693                                 outer_skip_rows,
1694                                 inner_skip_rows;
1695         double          mergejointuples,
1696                                 rescannedtuples;
1697         double          rescanratio;
1698         Selectivity outerstartsel,
1699                                 outerendsel,
1700                                 innerstartsel,
1701                                 innerendsel;
1702         Path            sort_path;              /* dummy for result of cost_sort */
1703
1704         /* Protect some assumptions below that rowcounts aren't zero */
1705         if (outer_path_rows <= 0)
1706                 outer_path_rows = 1;
1707         if (inner_path_rows <= 0)
1708                 inner_path_rows = 1;
1709
1710         if (!enable_mergejoin)
1711                 startup_cost += disable_cost;
1712
1713         /*
1714          * Compute cost of the mergequals and qpquals (other restriction clauses)
1715          * separately.
1716          */
1717         cost_qual_eval(&merge_qual_cost, mergeclauses, root);
1718         cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
1719         qp_qual_cost.startup -= merge_qual_cost.startup;
1720         qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
1721
1722         /*
1723          * Get approx # tuples passing the mergequals.  We use approx_tuple_count
1724          * here because we need an estimate done with JOIN_INNER semantics.
1725          */
1726         mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
1727
1728         /*
1729          * When there are equal merge keys in the outer relation, the mergejoin
1730          * must rescan any matching tuples in the inner relation. This means
1731          * re-fetching inner tuples; we have to estimate how often that happens.
1732          *
1733          * For regular inner and outer joins, the number of re-fetches can be
1734          * estimated approximately as size of merge join output minus size of
1735          * inner relation. Assume that the distinct key values are 1, 2, ..., and
1736          * denote the number of values of each key in the outer relation as m1,
1737          * m2, ...; in the inner relation, n1, n2, ...  Then we have
1738          *
1739          * size of join = m1 * n1 + m2 * n2 + ...
1740          *
1741          * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
1742          * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
1743          * relation
1744          *
1745          * This equation works correctly for outer tuples having no inner match
1746          * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
1747          * are effectively subtracting those from the number of rescanned tuples,
1748          * when we should not.  Can we do better without expensive selectivity
1749          * computations?
1750          *
1751          * The whole issue is moot if we are working from a unique-ified outer
1752          * input.
1753          */
1754         if (IsA(outer_path, UniquePath))
1755                 rescannedtuples = 0;
1756         else
1757         {
1758                 rescannedtuples = mergejointuples - inner_path_rows;
1759                 /* Must clamp because of possible underestimate */
1760                 if (rescannedtuples < 0)
1761                         rescannedtuples = 0;
1762         }
1763         /* We'll inflate various costs this much to account for rescanning */
1764         rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
1765
1766         /*
1767          * A merge join will stop as soon as it exhausts either input stream
1768          * (unless it's an outer join, in which case the outer side has to be
1769          * scanned all the way anyway).  Estimate fraction of the left and right
1770          * inputs that will actually need to be scanned.  Likewise, we can
1771          * estimate the number of rows that will be skipped before the first join
1772          * pair is found, which should be factored into startup cost. We use only
1773          * the first (most significant) merge clause for this purpose. Since
1774          * mergejoinscansel() is a fairly expensive computation, we cache the
1775          * results in the merge clause RestrictInfo.
1776          */
1777         if (mergeclauses && path->jpath.jointype != JOIN_FULL)
1778         {
1779                 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1780                 List       *opathkeys;
1781                 List       *ipathkeys;
1782                 PathKey    *opathkey;
1783                 PathKey    *ipathkey;
1784                 MergeScanSelCache *cache;
1785
1786                 /* Get the input pathkeys to determine the sort-order details */
1787                 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1788                 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1789                 Assert(opathkeys);
1790                 Assert(ipathkeys);
1791                 opathkey = (PathKey *) linitial(opathkeys);
1792                 ipathkey = (PathKey *) linitial(ipathkeys);
1793                 /* debugging check */
1794                 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1795                         opathkey->pk_strategy != ipathkey->pk_strategy ||
1796                         opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1797                         elog(ERROR, "left and right pathkeys do not match in mergejoin");
1798
1799                 /* Get the selectivity with caching */
1800                 cache = cached_scansel(root, firstclause, opathkey);
1801
1802                 if (bms_is_subset(firstclause->left_relids,
1803                                                   outer_path->parent->relids))
1804                 {
1805                         /* left side of clause is outer */
1806                         outerstartsel = cache->leftstartsel;
1807                         outerendsel = cache->leftendsel;
1808                         innerstartsel = cache->rightstartsel;
1809                         innerendsel = cache->rightendsel;
1810                 }
1811                 else
1812                 {
1813                         /* left side of clause is inner */
1814                         outerstartsel = cache->rightstartsel;
1815                         outerendsel = cache->rightendsel;
1816                         innerstartsel = cache->leftstartsel;
1817                         innerendsel = cache->leftendsel;
1818                 }
1819                 if (path->jpath.jointype == JOIN_LEFT ||
1820                         path->jpath.jointype == JOIN_ANTI)
1821                 {
1822                         outerstartsel = 0.0;
1823                         outerendsel = 1.0;
1824                 }
1825                 else if (path->jpath.jointype == JOIN_RIGHT)
1826                 {
1827                         innerstartsel = 0.0;
1828                         innerendsel = 1.0;
1829                 }
1830         }
1831         else
1832         {
1833                 /* cope with clauseless or full mergejoin */
1834                 outerstartsel = innerstartsel = 0.0;
1835                 outerendsel = innerendsel = 1.0;
1836         }
1837
1838         /*
1839          * Convert selectivities to row counts.  We force outer_rows and
1840          * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1841          */
1842         outer_skip_rows = rint(outer_path_rows * outerstartsel);
1843         inner_skip_rows = rint(inner_path_rows * innerstartsel);
1844         outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1845         inner_rows = clamp_row_est(inner_path_rows * innerendsel);
1846
1847         Assert(outer_skip_rows <= outer_rows);
1848         Assert(inner_skip_rows <= inner_rows);
1849
1850         /*
1851          * Readjust scan selectivities to account for above rounding.  This is
1852          * normally an insignificant effect, but when there are only a few rows in
1853          * the inputs, failing to do this makes for a large percentage error.
1854          */
1855         outerstartsel = outer_skip_rows / outer_path_rows;
1856         innerstartsel = inner_skip_rows / inner_path_rows;
1857         outerendsel = outer_rows / outer_path_rows;
1858         innerendsel = inner_rows / inner_path_rows;
1859
1860         Assert(outerstartsel <= outerendsel);
1861         Assert(innerstartsel <= innerendsel);
1862
1863         /* cost of source data */
1864
1865         if (outersortkeys)                      /* do we need to sort outer? */
1866         {
1867                 cost_sort(&sort_path,
1868                                   root,
1869                                   outersortkeys,
1870                                   outer_path->total_cost,
1871                                   outer_path_rows,
1872                                   outer_path->parent->width,
1873                                   0.0,
1874                                   work_mem,
1875                                   -1.0);
1876                 startup_cost += sort_path.startup_cost;
1877                 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1878                         * outerstartsel;
1879                 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1880                         * (outerendsel - outerstartsel);
1881         }
1882         else
1883         {
1884                 startup_cost += outer_path->startup_cost;
1885                 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
1886                         * outerstartsel;
1887                 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1888                         * (outerendsel - outerstartsel);
1889         }
1890
1891         if (innersortkeys)                      /* do we need to sort inner? */
1892         {
1893                 cost_sort(&sort_path,
1894                                   root,
1895                                   innersortkeys,
1896                                   inner_path->total_cost,
1897                                   inner_path_rows,
1898                                   inner_path->parent->width,
1899                                   0.0,
1900                                   work_mem,
1901                                   -1.0);
1902                 startup_cost += sort_path.startup_cost;
1903                 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1904                         * innerstartsel;
1905                 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
1906                         * (innerendsel - innerstartsel);
1907         }
1908         else
1909         {
1910                 startup_cost += inner_path->startup_cost;
1911                 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
1912                         * innerstartsel;
1913                 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
1914                         * (innerendsel - innerstartsel);
1915         }
1916
1917         /*
1918          * Decide whether we want to materialize the inner input to shield it from
1919          * mark/restore and performing re-fetches.      Our cost model for regular
1920          * re-fetches is that a re-fetch costs the same as an original fetch,
1921          * which is probably an overestimate; but on the other hand we ignore the
1922          * bookkeeping costs of mark/restore.  Not clear if it's worth developing
1923          * a more refined model.  So we just need to inflate the inner run cost by
1924          * rescanratio.
1925          */
1926         bare_inner_cost = inner_run_cost * rescanratio;
1927
1928         /*
1929          * When we interpose a Material node the re-fetch cost is assumed to be
1930          * just cpu_operator_cost per tuple, independently of the underlying
1931          * plan's cost; and we charge an extra cpu_operator_cost per original
1932          * fetch as well.  Note that we're assuming the materialize node will
1933          * never spill to disk, since it only has to remember tuples back to the
1934          * last mark.  (If there are a huge number of duplicates, our other cost
1935          * factors will make the path so expensive that it probably won't get
1936          * chosen anyway.)      So we don't use cost_rescan here.
1937          *
1938          * Note: keep this estimate in sync with create_mergejoin_plan's labeling
1939          * of the generated Material node.
1940          */
1941         mat_inner_cost = inner_run_cost +
1942                 cpu_operator_cost * inner_path_rows * rescanratio;
1943
1944         /*
1945          * Prefer materializing if it looks cheaper, unless the user has asked to
1946          * suppress materialization.
1947          */
1948         if (enable_material && mat_inner_cost < bare_inner_cost)
1949                 path->materialize_inner = true;
1950
1951         /*
1952          * Even if materializing doesn't look cheaper, we *must* do it if the
1953          * inner path is to be used directly (without sorting) and it doesn't
1954          * support mark/restore.
1955          *
1956          * Since the inner side must be ordered, and only Sorts and IndexScans can
1957          * create order to begin with, and they both support mark/restore, you
1958          * might think there's no problem --- but you'd be wrong.  Nestloop and
1959          * merge joins can *preserve* the order of their inputs, so they can be
1960          * selected as the input of a mergejoin, and they don't support
1961          * mark/restore at present.
1962          *
1963          * We don't test the value of enable_material here, because
1964          * materialization is required for correctness in this case, and turning
1965          * it off does not entitle us to deliver an invalid plan.
1966          */
1967         else if (innersortkeys == NIL &&
1968                          !ExecSupportsMarkRestore(inner_path->pathtype))
1969                 path->materialize_inner = true;
1970
1971         /*
1972          * Also, force materializing if the inner path is to be sorted and the
1973          * sort is expected to spill to disk.  This is because the final merge
1974          * pass can be done on-the-fly if it doesn't have to support mark/restore.
1975          * We don't try to adjust the cost estimates for this consideration,
1976          * though.
1977          *
1978          * Since materialization is a performance optimization in this case,
1979          * rather than necessary for correctness, we skip it if enable_material is
1980          * off.
1981          */
1982         else if (enable_material && innersortkeys != NIL &&
1983                          relation_byte_size(inner_path_rows, inner_path->parent->width) >
1984                          (work_mem * 1024L))
1985                 path->materialize_inner = true;
1986         else
1987                 path->materialize_inner = false;
1988
1989         /* Charge the right incremental cost for the chosen case */
1990         if (path->materialize_inner)
1991                 run_cost += mat_inner_cost;
1992         else
1993                 run_cost += bare_inner_cost;
1994
1995         /* CPU costs */
1996
1997         /*
1998          * The number of tuple comparisons needed is approximately number of outer
1999          * rows plus number of inner rows plus number of rescanned tuples (can we
2000          * refine this?).  At each one, we need to evaluate the mergejoin quals.
2001          */
2002         startup_cost += merge_qual_cost.startup;
2003         startup_cost += merge_qual_cost.per_tuple *
2004                 (outer_skip_rows + inner_skip_rows * rescanratio);
2005         run_cost += merge_qual_cost.per_tuple *
2006                 ((outer_rows - outer_skip_rows) +
2007                  (inner_rows - inner_skip_rows) * rescanratio);
2008
2009         /*
2010          * For each tuple that gets through the mergejoin proper, we charge
2011          * cpu_tuple_cost plus the cost of evaluating additional restriction
2012          * clauses that are to be applied at the join.  (This is pessimistic since
2013          * not all of the quals may get evaluated at each tuple.)
2014          *
2015          * Note: we could adjust for SEMI/ANTI joins skipping some qual
2016          * evaluations here, but it's probably not worth the trouble.
2017          */
2018         startup_cost += qp_qual_cost.startup;
2019         cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2020         run_cost += cpu_per_tuple * mergejointuples;
2021
2022         path->jpath.path.startup_cost = startup_cost;
2023         path->jpath.path.total_cost = startup_cost + run_cost;
2024 }
2025
2026 /*
2027  * run mergejoinscansel() with caching
2028  */
2029 static MergeScanSelCache *
2030 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2031 {
2032         MergeScanSelCache *cache;
2033         ListCell   *lc;
2034         Selectivity leftstartsel,
2035                                 leftendsel,
2036                                 rightstartsel,
2037                                 rightendsel;
2038         MemoryContext oldcontext;
2039
2040         /* Do we have this result already? */
2041         foreach(lc, rinfo->scansel_cache)
2042         {
2043                 cache = (MergeScanSelCache *) lfirst(lc);
2044                 if (cache->opfamily == pathkey->pk_opfamily &&
2045                         cache->strategy == pathkey->pk_strategy &&
2046                         cache->nulls_first == pathkey->pk_nulls_first)
2047                         return cache;
2048         }
2049
2050         /* Nope, do the computation */
2051         mergejoinscansel(root,
2052                                          (Node *) rinfo->clause,
2053                                          pathkey->pk_opfamily,
2054                                          pathkey->pk_strategy,
2055                                          pathkey->pk_nulls_first,
2056                                          &leftstartsel,
2057                                          &leftendsel,
2058                                          &rightstartsel,
2059                                          &rightendsel);
2060
2061         /* Cache the result in suitably long-lived workspace */
2062         oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2063
2064         cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2065         cache->opfamily = pathkey->pk_opfamily;
2066         cache->strategy = pathkey->pk_strategy;
2067         cache->nulls_first = pathkey->pk_nulls_first;
2068         cache->leftstartsel = leftstartsel;
2069         cache->leftendsel = leftendsel;
2070         cache->rightstartsel = rightstartsel;
2071         cache->rightendsel = rightendsel;
2072
2073         rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2074
2075         MemoryContextSwitchTo(oldcontext);
2076
2077         return cache;
2078 }
2079
2080 /*
2081  * cost_hashjoin
2082  *        Determines and returns the cost of joining two relations using the
2083  *        hash join algorithm.
2084  *
2085  * 'path' is already filled in except for the cost fields
2086  * 'sjinfo' is extra info about the join for selectivity estimation
2087  *
2088  * Note: path's hashclauses should be a subset of the joinrestrictinfo list
2089  */
2090 void
2091 cost_hashjoin(HashPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
2092 {
2093         Path       *outer_path = path->jpath.outerjoinpath;
2094         Path       *inner_path = path->jpath.innerjoinpath;
2095         List       *hashclauses = path->path_hashclauses;
2096         Cost            startup_cost = 0;
2097         Cost            run_cost = 0;
2098         Cost            cpu_per_tuple;
2099         QualCost        hash_qual_cost;
2100         QualCost        qp_qual_cost;
2101         double          hashjointuples;
2102         double          outer_path_rows = PATH_ROWS(outer_path);
2103         double          inner_path_rows = PATH_ROWS(inner_path);
2104         int                     num_hashclauses = list_length(hashclauses);
2105         int                     numbuckets;
2106         int                     numbatches;
2107         int                     num_skew_mcvs;
2108         double          virtualbuckets;
2109         Selectivity innerbucketsize;
2110         Selectivity outer_match_frac;
2111         Selectivity match_count;
2112         ListCell   *hcl;
2113
2114         if (!enable_hashjoin)
2115                 startup_cost += disable_cost;
2116
2117         /*
2118          * Compute cost of the hashquals and qpquals (other restriction clauses)
2119          * separately.
2120          */
2121         cost_qual_eval(&hash_qual_cost, hashclauses, root);
2122         cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2123         qp_qual_cost.startup -= hash_qual_cost.startup;
2124         qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2125
2126         /* cost of source data */
2127         startup_cost += outer_path->startup_cost;
2128         run_cost += outer_path->total_cost - outer_path->startup_cost;
2129         startup_cost += inner_path->total_cost;
2130
2131         /*
2132          * Cost of computing hash function: must do it once per input tuple. We
2133          * charge one cpu_operator_cost for each column's hash function.  Also,
2134          * tack on one cpu_tuple_cost per inner row, to model the costs of
2135          * inserting the row into the hashtable.
2136          *
2137          * XXX when a hashclause is more complex than a single operator, we really
2138          * should charge the extra eval costs of the left or right side, as
2139          * appropriate, here.  This seems more work than it's worth at the moment.
2140          */
2141         startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2142                 * inner_path_rows;
2143         run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2144
2145         /*
2146          * Get hash table size that executor would use for inner relation.
2147          *
2148          * XXX for the moment, always assume that skew optimization will be
2149          * performed.  As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2150          * trying to determine that for sure.
2151          *
2152          * XXX at some point it might be interesting to try to account for skew
2153          * optimization in the cost estimate, but for now, we don't.
2154          */
2155         ExecChooseHashTableSize(inner_path_rows,
2156                                                         inner_path->parent->width,
2157                                                         true,           /* useskew */
2158                                                         &numbuckets,
2159                                                         &numbatches,
2160                                                         &num_skew_mcvs);
2161         virtualbuckets = (double) numbuckets *(double) numbatches;
2162
2163         /* mark the path with estimated # of batches */
2164         path->num_batches = numbatches;
2165
2166         /*
2167          * Determine bucketsize fraction for inner relation.  We use the smallest
2168          * bucketsize estimated for any individual hashclause; this is undoubtedly
2169          * conservative.
2170          *
2171          * BUT: if inner relation has been unique-ified, we can assume it's good
2172          * for hashing.  This is important both because it's the right answer, and
2173          * because we avoid contaminating the cache with a value that's wrong for
2174          * non-unique-ified paths.
2175          */
2176         if (IsA(inner_path, UniquePath))
2177                 innerbucketsize = 1.0 / virtualbuckets;
2178         else
2179         {
2180                 innerbucketsize = 1.0;
2181                 foreach(hcl, hashclauses)
2182                 {
2183                         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2184                         Selectivity thisbucketsize;
2185
2186                         Assert(IsA(restrictinfo, RestrictInfo));
2187
2188                         /*
2189                          * First we have to figure out which side of the hashjoin clause
2190                          * is the inner side.
2191                          *
2192                          * Since we tend to visit the same clauses over and over when
2193                          * planning a large query, we cache the bucketsize estimate in the
2194                          * RestrictInfo node to avoid repeated lookups of statistics.
2195                          */
2196                         if (bms_is_subset(restrictinfo->right_relids,
2197                                                           inner_path->parent->relids))
2198                         {
2199                                 /* righthand side is inner */
2200                                 thisbucketsize = restrictinfo->right_bucketsize;
2201                                 if (thisbucketsize < 0)
2202                                 {
2203                                         /* not cached yet */
2204                                         thisbucketsize =
2205                                                 estimate_hash_bucketsize(root,
2206                                                                                    get_rightop(restrictinfo->clause),
2207                                                                                                  virtualbuckets);
2208                                         restrictinfo->right_bucketsize = thisbucketsize;
2209                                 }
2210                         }
2211                         else
2212                         {
2213                                 Assert(bms_is_subset(restrictinfo->left_relids,
2214                                                                          inner_path->parent->relids));
2215                                 /* lefthand side is inner */
2216                                 thisbucketsize = restrictinfo->left_bucketsize;
2217                                 if (thisbucketsize < 0)
2218                                 {
2219                                         /* not cached yet */
2220                                         thisbucketsize =
2221                                                 estimate_hash_bucketsize(root,
2222                                                                                         get_leftop(restrictinfo->clause),
2223                                                                                                  virtualbuckets);
2224                                         restrictinfo->left_bucketsize = thisbucketsize;
2225                                 }
2226                         }
2227
2228                         if (innerbucketsize > thisbucketsize)
2229                                 innerbucketsize = thisbucketsize;
2230                 }
2231         }
2232
2233         /*
2234          * If inner relation is too big then we will need to "batch" the join,
2235          * which implies writing and reading most of the tuples to disk an extra
2236          * time.  Charge seq_page_cost per page, since the I/O should be nice and
2237          * sequential.  Writing the inner rel counts as startup cost, all the rest
2238          * as run cost.
2239          */
2240         if (numbatches > 1)
2241         {
2242                 double          outerpages = page_size(outer_path_rows,
2243                                                                                    outer_path->parent->width);
2244                 double          innerpages = page_size(inner_path_rows,
2245                                                                                    inner_path->parent->width);
2246
2247                 startup_cost += seq_page_cost * innerpages;
2248                 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2249         }
2250
2251         /* CPU costs */
2252
2253         if (adjust_semi_join(root, &path->jpath, sjinfo,
2254                                                  &outer_match_frac,
2255                                                  &match_count,
2256                                                  NULL))
2257         {
2258                 double          outer_matched_rows;
2259                 Selectivity inner_scan_frac;
2260
2261                 /*
2262                  * SEMI or ANTI join: executor will stop after first match.
2263                  *
2264                  * For an outer-rel row that has at least one match, we can expect the
2265                  * bucket scan to stop after a fraction 1/(match_count+1) of the
2266                  * bucket's rows, if the matches are evenly distributed.  Since they
2267                  * probably aren't quite evenly distributed, we apply a fuzz factor of
2268                  * 2.0 to that fraction.  (If we used a larger fuzz factor, we'd have
2269                  * to clamp inner_scan_frac to at most 1.0; but since match_count is
2270                  * at least 1, no such clamp is needed now.)
2271                  */
2272                 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
2273                 inner_scan_frac = 2.0 / (match_count + 1.0);
2274
2275                 startup_cost += hash_qual_cost.startup;
2276                 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2277                         clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2278
2279                 /*
2280                  * For unmatched outer-rel rows, the picture is quite a lot different.
2281                  * In the first place, there is no reason to assume that these rows
2282                  * preferentially hit heavily-populated buckets; instead assume they
2283                  * are uncorrelated with the inner distribution and so they see an
2284                  * average bucket size of inner_path_rows / virtualbuckets.  In the
2285                  * second place, it seems likely that they will have few if any exact
2286                  * hash-code matches and so very few of the tuples in the bucket will
2287                  * actually require eval of the hash quals.  We don't have any good
2288                  * way to estimate how many will, but for the moment assume that the
2289                  * effective cost per bucket entry is one-tenth what it is for
2290                  * matchable tuples.
2291                  */
2292                 run_cost += hash_qual_cost.per_tuple *
2293                         (outer_path_rows - outer_matched_rows) *
2294                         clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2295
2296                 /* Get # of tuples that will pass the basic join */
2297                 if (path->jpath.jointype == JOIN_SEMI)
2298                         hashjointuples = outer_matched_rows;
2299                 else
2300                         hashjointuples = outer_path_rows - outer_matched_rows;
2301         }
2302         else
2303         {
2304                 /*
2305                  * The number of tuple comparisons needed is the number of outer
2306                  * tuples times the typical number of tuples in a hash bucket, which
2307                  * is the inner relation size times its bucketsize fraction.  At each
2308                  * one, we need to evaluate the hashjoin quals.  But actually,
2309                  * charging the full qual eval cost at each tuple is pessimistic,
2310                  * since we don't evaluate the quals unless the hash values match
2311                  * exactly.  For lack of a better idea, halve the cost estimate to
2312                  * allow for that.
2313                  */
2314                 startup_cost += hash_qual_cost.startup;
2315                 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2316                         clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2317
2318                 /*
2319                  * Get approx # tuples passing the hashquals.  We use
2320                  * approx_tuple_count here because we need an estimate done with
2321                  * JOIN_INNER semantics.
2322                  */
2323                 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2324         }
2325
2326         /*
2327          * For each tuple that gets through the hashjoin proper, we charge
2328          * cpu_tuple_cost plus the cost of evaluating additional restriction
2329          * clauses that are to be applied at the join.  (This is pessimistic since
2330          * not all of the quals may get evaluated at each tuple.)
2331          */
2332         startup_cost += qp_qual_cost.startup;
2333         cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2334         run_cost += cpu_per_tuple * hashjointuples;
2335
2336         path->jpath.path.startup_cost = startup_cost;
2337         path->jpath.path.total_cost = startup_cost + run_cost;
2338 }
2339
2340
2341 /*
2342  * cost_subplan
2343  *              Figure the costs for a SubPlan (or initplan).
2344  *
2345  * Note: we could dig the subplan's Plan out of the root list, but in practice
2346  * all callers have it handy already, so we make them pass it.
2347  */
2348 void
2349 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2350 {
2351         QualCost        sp_cost;
2352
2353         /* Figure any cost for evaluating the testexpr */
2354         cost_qual_eval(&sp_cost,
2355                                    make_ands_implicit((Expr *) subplan->testexpr),
2356                                    root);
2357
2358         if (subplan->useHashTable)
2359         {
2360                 /*
2361                  * If we are using a hash table for the subquery outputs, then the
2362                  * cost of evaluating the query is a one-time cost.  We charge one
2363                  * cpu_operator_cost per tuple for the work of loading the hashtable,
2364                  * too.
2365                  */
2366                 sp_cost.startup += plan->total_cost +
2367                         cpu_operator_cost * plan->plan_rows;
2368
2369                 /*
2370                  * The per-tuple costs include the cost of evaluating the lefthand
2371                  * expressions, plus the cost of probing the hashtable.  We already
2372                  * accounted for the lefthand expressions as part of the testexpr, and
2373                  * will also have counted one cpu_operator_cost for each comparison
2374                  * operator.  That is probably too low for the probing cost, but it's
2375                  * hard to make a better estimate, so live with it for now.
2376                  */
2377         }
2378         else
2379         {
2380                 /*
2381                  * Otherwise we will be rescanning the subplan output on each
2382                  * evaluation.  We need to estimate how much of the output we will
2383                  * actually need to scan.  NOTE: this logic should agree with the
2384                  * tuple_fraction estimates used by make_subplan() in
2385                  * plan/subselect.c.
2386                  */
2387                 Cost            plan_run_cost = plan->total_cost - plan->startup_cost;
2388
2389                 if (subplan->subLinkType == EXISTS_SUBLINK)
2390                 {
2391                         /* we only need to fetch 1 tuple */
2392                         sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2393                 }
2394                 else if (subplan->subLinkType == ALL_SUBLINK ||
2395                                  subplan->subLinkType == ANY_SUBLINK)
2396                 {
2397                         /* assume we need 50% of the tuples */
2398                         sp_cost.per_tuple += 0.50 * plan_run_cost;
2399                         /* also charge a cpu_operator_cost per row examined */
2400                         sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2401                 }
2402                 else
2403                 {
2404                         /* assume we need all tuples */
2405                         sp_cost.per_tuple += plan_run_cost;
2406                 }
2407
2408                 /*
2409                  * Also account for subplan's startup cost. If the subplan is
2410                  * uncorrelated or undirect correlated, AND its topmost node is one
2411                  * that materializes its output, assume that we'll only need to pay
2412                  * its startup cost once; otherwise assume we pay the startup cost
2413                  * every time.
2414                  */
2415                 if (subplan->parParam == NIL &&
2416                         ExecMaterializesOutput(nodeTag(plan)))
2417                         sp_cost.startup += plan->startup_cost;
2418                 else
2419                         sp_cost.per_tuple += plan->startup_cost;
2420         }
2421
2422         subplan->startup_cost = sp_cost.startup;
2423         subplan->per_call_cost = sp_cost.per_tuple;
2424 }
2425
2426
2427 /*
2428  * cost_rescan
2429  *              Given a finished Path, estimate the costs of rescanning it after
2430  *              having done so the first time.  For some Path types a rescan is
2431  *              cheaper than an original scan (if no parameters change), and this
2432  *              function embodies knowledge about that.  The default is to return
2433  *              the same costs stored in the Path.      (Note that the cost estimates
2434  *              actually stored in Paths are always for first scans.)
2435  *
2436  * This function is not currently intended to model effects such as rescans
2437  * being cheaper due to disk block caching; what we are concerned with is
2438  * plan types wherein the executor caches results explicitly, or doesn't
2439  * redo startup calculations, etc.
2440  */
2441 static void
2442 cost_rescan(PlannerInfo *root, Path *path,
2443                         Cost *rescan_startup_cost,      /* output parameters */
2444                         Cost *rescan_total_cost)
2445 {
2446         switch (path->pathtype)
2447         {
2448                 case T_FunctionScan:
2449
2450                         /*
2451                          * Currently, nodeFunctionscan.c always executes the function to
2452                          * completion before returning any rows, and caches the results in
2453                          * a tuplestore.  So the function eval cost is all startup cost
2454                          * and isn't paid over again on rescans. However, all run costs
2455                          * will be paid over again.
2456                          */
2457                         *rescan_startup_cost = 0;
2458                         *rescan_total_cost = path->total_cost - path->startup_cost;
2459                         break;
2460                 case T_HashJoin:
2461
2462                         /*
2463                          * Assume that all of the startup cost represents hash table
2464                          * building, which we won't have to do over.
2465                          */
2466                         *rescan_startup_cost = 0;
2467                         *rescan_total_cost = path->total_cost - path->startup_cost;
2468                         break;
2469                 case T_CteScan:
2470                 case T_WorkTableScan:
2471                         {
2472                                 /*
2473                                  * These plan types materialize their final result in a
2474                                  * tuplestore or tuplesort object.      So the rescan cost is only
2475                                  * cpu_tuple_cost per tuple, unless the result is large enough
2476                                  * to spill to disk.
2477                                  */
2478                                 Cost            run_cost = cpu_tuple_cost * path->parent->rows;
2479                                 double          nbytes = relation_byte_size(path->parent->rows,
2480                                                                                                                 path->parent->width);
2481                                 long            work_mem_bytes = work_mem * 1024L;
2482
2483                                 if (nbytes > work_mem_bytes)
2484                                 {
2485                                         /* It will spill, so account for re-read cost */
2486                                         double          npages = ceil(nbytes / BLCKSZ);
2487
2488                                         run_cost += seq_page_cost * npages;
2489                                 }
2490                                 *rescan_startup_cost = 0;
2491                                 *rescan_total_cost = run_cost;
2492                         }
2493                         break;
2494                 case T_Material:
2495                 case T_Sort:
2496                         {
2497                                 /*
2498                                  * These plan types not only materialize their results, but do
2499                                  * not implement qual filtering or projection.  So they are
2500                                  * even cheaper to rescan than the ones above.  We charge only
2501                                  * cpu_operator_cost per tuple.  (Note: keep that in sync with
2502                                  * the run_cost charge in cost_sort, and also see comments in
2503                                  * cost_material before you change it.)
2504                                  */
2505                                 Cost            run_cost = cpu_operator_cost * path->parent->rows;
2506                                 double          nbytes = relation_byte_size(path->parent->rows,
2507                                                                                                                 path->parent->width);
2508                                 long            work_mem_bytes = work_mem * 1024L;
2509
2510                                 if (nbytes > work_mem_bytes)
2511                                 {
2512                                         /* It will spill, so account for re-read cost */
2513                                         double          npages = ceil(nbytes / BLCKSZ);
2514
2515                                         run_cost += seq_page_cost * npages;
2516                                 }
2517                                 *rescan_startup_cost = 0;
2518                                 *rescan_total_cost = run_cost;
2519                         }
2520                         break;
2521                 default:
2522                         *rescan_startup_cost = path->startup_cost;
2523                         *rescan_total_cost = path->total_cost;
2524                         break;
2525         }
2526 }
2527
2528
2529 /*
2530  * cost_qual_eval
2531  *              Estimate the CPU costs of evaluating a WHERE clause.
2532  *              The input can be either an implicitly-ANDed list of boolean
2533  *              expressions, or a list of RestrictInfo nodes.  (The latter is
2534  *              preferred since it allows caching of the results.)
2535  *              The result includes both a one-time (startup) component,
2536  *              and a per-evaluation component.
2537  */
2538 void
2539 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2540 {
2541         cost_qual_eval_context context;
2542         ListCell   *l;
2543
2544         context.root = root;
2545         context.total.startup = 0;
2546         context.total.per_tuple = 0;
2547
2548         /* We don't charge any cost for the implicit ANDing at top level ... */
2549
2550         foreach(l, quals)
2551         {
2552                 Node       *qual = (Node *) lfirst(l);
2553
2554                 cost_qual_eval_walker(qual, &context);
2555         }
2556
2557         *cost = context.total;
2558 }
2559
2560 /*
2561  * cost_qual_eval_node
2562  *              As above, for a single RestrictInfo or expression.
2563  */
2564 void
2565 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2566 {
2567         cost_qual_eval_context context;
2568
2569         context.root = root;
2570         context.total.startup = 0;
2571         context.total.per_tuple = 0;
2572
2573         cost_qual_eval_walker(qual, &context);
2574
2575         *cost = context.total;
2576 }
2577
2578 static bool
2579 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2580 {
2581         if (node == NULL)
2582                 return false;
2583
2584         /*
2585          * RestrictInfo nodes contain an eval_cost field reserved for this
2586          * routine's use, so that it's not necessary to evaluate the qual clause's
2587          * cost more than once.  If the clause's cost hasn't been computed yet,
2588          * the field's startup value will contain -1.
2589          */
2590         if (IsA(node, RestrictInfo))
2591         {
2592                 RestrictInfo *rinfo = (RestrictInfo *) node;
2593
2594                 if (rinfo->eval_cost.startup < 0)
2595                 {
2596                         cost_qual_eval_context locContext;
2597
2598                         locContext.root = context->root;
2599                         locContext.total.startup = 0;
2600                         locContext.total.per_tuple = 0;
2601
2602                         /*
2603                          * For an OR clause, recurse into the marked-up tree so that we
2604                          * set the eval_cost for contained RestrictInfos too.
2605                          */
2606                         if (rinfo->orclause)
2607                                 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2608                         else
2609                                 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2610
2611                         /*
2612                          * If the RestrictInfo is marked pseudoconstant, it will be tested
2613                          * only once, so treat its cost as all startup cost.
2614                          */
2615                         if (rinfo->pseudoconstant)
2616                         {
2617                                 /* count one execution during startup */
2618                                 locContext.total.startup += locContext.total.per_tuple;
2619                                 locContext.total.per_tuple = 0;
2620                         }
2621                         rinfo->eval_cost = locContext.total;
2622                 }
2623                 context->total.startup += rinfo->eval_cost.startup;
2624                 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2625                 /* do NOT recurse into children */
2626                 return false;
2627         }
2628
2629         /*
2630          * For each operator or function node in the given tree, we charge the
2631          * estimated execution cost given by pg_proc.procost (remember to multiply
2632          * this by cpu_operator_cost).
2633          *
2634          * Vars and Consts are charged zero, and so are boolean operators (AND,
2635          * OR, NOT). Simplistic, but a lot better than no model at all.
2636          *
2637          * Note that Aggref and WindowFunc nodes are (and should be) treated like
2638          * Vars --- whatever execution cost they have is absorbed into
2639          * plan-node-specific costing.  As far as expression evaluation is
2640          * concerned they're just like Vars.
2641          *
2642          * Should we try to account for the possibility of short-circuit
2643          * evaluation of AND/OR?  Probably *not*, because that would make the
2644          * results depend on the clause ordering, and we are not in any position
2645          * to expect that the current ordering of the clauses is the one that's
2646          * going to end up being used.  (Is it worth applying order_qual_clauses
2647          * much earlier in the planning process to fix this?)
2648          */
2649         if (IsA(node, FuncExpr))
2650         {
2651                 context->total.per_tuple +=
2652                         get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
2653         }
2654         else if (IsA(node, OpExpr) ||
2655                          IsA(node, DistinctExpr) ||
2656                          IsA(node, NullIfExpr))
2657         {
2658                 /* rely on struct equivalence to treat these all alike */
2659                 set_opfuncid((OpExpr *) node);
2660                 context->total.per_tuple +=
2661                         get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
2662         }
2663         else if (IsA(node, ScalarArrayOpExpr))
2664         {
2665                 /*
2666                  * Estimate that the operator will be applied to about half of the
2667                  * array elements before the answer is determined.
2668                  */
2669                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2670                 Node       *arraynode = (Node *) lsecond(saop->args);
2671
2672                 set_sa_opfuncid(saop);
2673                 context->total.per_tuple += get_func_cost(saop->opfuncid) *
2674                         cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
2675         }
2676         else if (IsA(node, CoerceViaIO))
2677         {
2678                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2679                 Oid                     iofunc;
2680                 Oid                     typioparam;
2681                 bool            typisvarlena;
2682
2683                 /* check the result type's input function */
2684                 getTypeInputInfo(iocoerce->resulttype,
2685                                                  &iofunc, &typioparam);
2686                 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2687                 /* check the input type's output function */
2688                 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
2689                                                   &iofunc, &typisvarlena);
2690                 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2691         }
2692         else if (IsA(node, ArrayCoerceExpr))
2693         {
2694                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2695                 Node       *arraynode = (Node *) acoerce->arg;
2696
2697                 if (OidIsValid(acoerce->elemfuncid))
2698                         context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
2699                                 cpu_operator_cost * estimate_array_length(arraynode);
2700         }
2701         else if (IsA(node, RowCompareExpr))
2702         {
2703                 /* Conservatively assume we will check all the columns */
2704                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2705                 ListCell   *lc;
2706
2707                 foreach(lc, rcexpr->opnos)
2708                 {
2709                         Oid                     opid = lfirst_oid(lc);
2710
2711                         context->total.per_tuple += get_func_cost(get_opcode(opid)) *
2712                                 cpu_operator_cost;
2713                 }
2714         }
2715         else if (IsA(node, CurrentOfExpr))
2716         {
2717                 /* Report high cost to prevent selection of anything but TID scan */
2718                 context->total.startup += disable_cost;
2719         }
2720         else if (IsA(node, SubLink))
2721         {
2722                 /* This routine should not be applied to un-planned expressions */
2723                 elog(ERROR, "cannot handle unplanned sub-select");
2724         }
2725         else if (IsA(node, SubPlan))
2726         {
2727                 /*
2728                  * A subplan node in an expression typically indicates that the
2729                  * subplan will be executed on each evaluation, so charge accordingly.
2730                  * (Sub-selects that can be executed as InitPlans have already been
2731                  * removed from the expression.)
2732                  */
2733                 SubPlan    *subplan = (SubPlan *) node;
2734
2735                 context->total.startup += subplan->startup_cost;
2736                 context->total.per_tuple += subplan->per_call_cost;
2737
2738                 /*
2739                  * We don't want to recurse into the testexpr, because it was already
2740                  * counted in the SubPlan node's costs.  So we're done.
2741                  */
2742                 return false;
2743         }
2744         else if (IsA(node, AlternativeSubPlan))
2745         {
2746                 /*
2747                  * Arbitrarily use the first alternative plan for costing.      (We should
2748                  * certainly only include one alternative, and we don't yet have
2749                  * enough information to know which one the executor is most likely to
2750                  * use.)
2751                  */
2752                 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2753
2754                 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
2755                                                                          context);
2756         }
2757
2758         /* recurse into children */
2759         return expression_tree_walker(node, cost_qual_eval_walker,
2760                                                                   (void *) context);
2761 }
2762
2763
2764 /*
2765  * adjust_semi_join
2766  *        Estimate how much of the inner input a SEMI or ANTI join
2767  *        can be expected to scan.
2768  *
2769  * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
2770  * inner rows as soon as it finds a match to the current outer row.
2771  * We should therefore adjust some of the cost components for this effect.
2772  * This function computes some estimates needed for these adjustments.
2773  *
2774  * 'path' is already filled in except for the cost fields
2775  * 'sjinfo' is extra info about the join for selectivity estimation
2776  *
2777  * Returns TRUE if this is a SEMI or ANTI join, FALSE if not.
2778  *
2779  * Output parameters (set only in TRUE-result case):
2780  * *outer_match_frac is set to the fraction of the outer tuples that are
2781  *              expected to have at least one match.
2782  * *match_count is set to the average number of matches expected for
2783  *              outer tuples that have at least one match.
2784  * *indexed_join_quals is set to TRUE if all the joinquals are used as
2785  *              inner index quals, FALSE if not.
2786  *
2787  * indexed_join_quals can be passed as NULL if that information is not
2788  * relevant (it is only useful for the nestloop case).
2789  */
2790 static bool
2791 adjust_semi_join(PlannerInfo *root, JoinPath *path, SpecialJoinInfo *sjinfo,
2792                                  Selectivity *outer_match_frac,
2793                                  Selectivity *match_count,
2794                                  bool *indexed_join_quals)
2795 {
2796         JoinType        jointype = path->jointype;
2797         Selectivity jselec;
2798         Selectivity nselec;
2799         Selectivity avgmatch;
2800         SpecialJoinInfo norm_sjinfo;
2801         List       *joinquals;
2802         ListCell   *l;
2803
2804         /* Fall out if it's not JOIN_SEMI or JOIN_ANTI */
2805         if (jointype != JOIN_SEMI && jointype != JOIN_ANTI)
2806                 return false;
2807
2808         /*
2809          * Note: it's annoying to repeat this selectivity estimation on each call,
2810          * when the joinclause list will be the same for all path pairs
2811          * implementing a given join.  clausesel.c will save us from the worst
2812          * effects of this by caching at the RestrictInfo level; but perhaps it'd
2813          * be worth finding a way to cache the results at a higher level.
2814          */
2815
2816         /*
2817          * In an ANTI join, we must ignore clauses that are "pushed down", since
2818          * those won't affect the match logic.  In a SEMI join, we do not
2819          * distinguish joinquals from "pushed down" quals, so just use the whole
2820          * restrictinfo list.
2821          */
2822         if (jointype == JOIN_ANTI)
2823         {
2824                 joinquals = NIL;
2825                 foreach(l, path->joinrestrictinfo)
2826                 {
2827                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2828
2829                         Assert(IsA(rinfo, RestrictInfo));
2830                         if (!rinfo->is_pushed_down)
2831                                 joinquals = lappend(joinquals, rinfo);
2832                 }
2833         }
2834         else
2835                 joinquals = path->joinrestrictinfo;
2836
2837         /*
2838          * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
2839          */
2840         jselec = clauselist_selectivity(root,
2841                                                                         joinquals,
2842                                                                         0,
2843                                                                         jointype,
2844                                                                         sjinfo);
2845
2846         /*
2847          * Also get the normal inner-join selectivity of the join clauses.
2848          */
2849         norm_sjinfo.type = T_SpecialJoinInfo;
2850         norm_sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2851         norm_sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2852         norm_sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2853         norm_sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2854         norm_sjinfo.jointype = JOIN_INNER;
2855         /* we don't bother trying to make the remaining fields valid */
2856         norm_sjinfo.lhs_strict = false;
2857         norm_sjinfo.delay_upper_joins = false;
2858         norm_sjinfo.join_quals = NIL;
2859
2860         nselec = clauselist_selectivity(root,
2861                                                                         joinquals,
2862                                                                         0,
2863                                                                         JOIN_INNER,
2864                                                                         &norm_sjinfo);
2865
2866         /* Avoid leaking a lot of ListCells */
2867         if (jointype == JOIN_ANTI)
2868                 list_free(joinquals);
2869
2870         /*
2871          * jselec can be interpreted as the fraction of outer-rel rows that have
2872          * any matches (this is true for both SEMI and ANTI cases).  And nselec is
2873          * the fraction of the Cartesian product that matches.  So, the average
2874          * number of matches for each outer-rel row that has at least one match is
2875          * nselec * inner_rows / jselec.
2876          *
2877          * Note: it is correct to use the inner rel's "rows" count here, not
2878          * PATH_ROWS(), even if the inner path under consideration is an inner
2879          * indexscan.  This is because we have included all the join clauses in
2880          * the selectivity estimate, even ones used in an inner indexscan.
2881          */
2882         if (jselec > 0)                         /* protect against zero divide */
2883         {
2884                 avgmatch = nselec * path->innerjoinpath->parent->rows / jselec;
2885                 /* Clamp to sane range */
2886                 avgmatch = Max(1.0, avgmatch);
2887         }
2888         else
2889                 avgmatch = 1.0;
2890
2891         *outer_match_frac = jselec;
2892         *match_count = avgmatch;
2893
2894         /*
2895          * If requested, check whether the inner path uses all the joinquals as
2896          * indexquals.  (If that's true, we can assume that an unmatched outer
2897          * tuple is cheap to process, whereas otherwise it's probably expensive.)
2898          */
2899         if (indexed_join_quals)
2900         {
2901                 if (path->joinrestrictinfo != NIL)
2902                 {
2903                         List       *nrclauses;
2904
2905                         nrclauses = select_nonredundant_join_clauses(root,
2906                                                                                                                  path->joinrestrictinfo,
2907                                                                                                                  path->innerjoinpath);
2908                         *indexed_join_quals = (nrclauses == NIL);
2909                 }
2910                 else
2911                 {
2912                         /* a clauseless join does NOT qualify */
2913                         *indexed_join_quals = false;
2914                 }
2915         }
2916
2917         return true;
2918 }
2919
2920
2921 /*
2922  * approx_tuple_count
2923  *              Quick-and-dirty estimation of the number of join rows passing
2924  *              a set of qual conditions.
2925  *
2926  * The quals can be either an implicitly-ANDed list of boolean expressions,
2927  * or a list of RestrictInfo nodes (typically the latter).
2928  *
2929  * We intentionally compute the selectivity under JOIN_INNER rules, even
2930  * if it's some type of outer join.  This is appropriate because we are
2931  * trying to figure out how many tuples pass the initial merge or hash
2932  * join step.
2933  *
2934  * This is quick-and-dirty because we bypass clauselist_selectivity, and
2935  * simply multiply the independent clause selectivities together.  Now
2936  * clauselist_selectivity often can't do any better than that anyhow, but
2937  * for some situations (such as range constraints) it is smarter.  However,
2938  * we can't effectively cache the results of clauselist_selectivity, whereas
2939  * the individual clause selectivities can be and are cached.
2940  *
2941  * Since we are only using the results to estimate how many potential
2942  * output tuples are generated and passed through qpqual checking, it
2943  * seems OK to live with the approximation.
2944  */
2945 static double
2946 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
2947 {
2948         double          tuples;
2949         double          outer_tuples = path->outerjoinpath->parent->rows;
2950         double          inner_tuples = path->innerjoinpath->parent->rows;
2951         SpecialJoinInfo sjinfo;
2952         Selectivity selec = 1.0;
2953         ListCell   *l;
2954
2955         /*
2956          * Make up a SpecialJoinInfo for JOIN_INNER semantics.
2957          */
2958         sjinfo.type = T_SpecialJoinInfo;
2959         sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2960         sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2961         sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2962         sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2963         sjinfo.jointype = JOIN_INNER;
2964         /* we don't bother trying to make the remaining fields valid */
2965         sjinfo.lhs_strict = false;
2966         sjinfo.delay_upper_joins = false;
2967         sjinfo.join_quals = NIL;
2968
2969         /* Get the approximate selectivity */
2970         foreach(l, quals)
2971         {
2972                 Node       *qual = (Node *) lfirst(l);
2973
2974                 /* Note that clause_selectivity will be able to cache its result */
2975                 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
2976         }
2977
2978         /* Apply it to the input relation sizes */
2979         tuples = selec * outer_tuples * inner_tuples;
2980
2981         return clamp_row_est(tuples);
2982 }
2983
2984
2985 /*
2986  * set_baserel_size_estimates
2987  *              Set the size estimates for the given base relation.
2988  *
2989  * The rel's targetlist and restrictinfo list must have been constructed
2990  * already, and rel->tuples must be set.
2991  *
2992  * We set the following fields of the rel node:
2993  *      rows: the estimated number of output tuples (after applying
2994  *                restriction clauses).
2995  *      width: the estimated average output tuple width in bytes.
2996  *      baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
2997  */
2998 void
2999 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3000 {
3001         double          nrows;
3002
3003         /* Should only be applied to base relations */
3004         Assert(rel->relid > 0);
3005
3006         nrows = rel->tuples *
3007                 clauselist_selectivity(root,
3008                                                            rel->baserestrictinfo,
3009                                                            0,
3010                                                            JOIN_INNER,
3011                                                            NULL);
3012
3013         rel->rows = clamp_row_est(nrows);
3014
3015         cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3016
3017         set_rel_width(root, rel);
3018 }
3019
3020 /*
3021  * set_joinrel_size_estimates
3022  *              Set the size estimates for the given join relation.
3023  *
3024  * The rel's targetlist must have been constructed already, and a
3025  * restriction clause list that matches the given component rels must
3026  * be provided.
3027  *
3028  * Since there is more than one way to make a joinrel for more than two
3029  * base relations, the results we get here could depend on which component
3030  * rel pair is provided.  In theory we should get the same answers no matter
3031  * which pair is provided; in practice, since the selectivity estimation
3032  * routines don't handle all cases equally well, we might not.  But there's
3033  * not much to be done about it.  (Would it make sense to repeat the
3034  * calculations for each pair of input rels that's encountered, and somehow
3035  * average the results?  Probably way more trouble than it's worth.)
3036  *
3037  * We set only the rows field here.  The width field was already set by
3038  * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3039  */
3040 void
3041 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3042                                                    RelOptInfo *outer_rel,
3043                                                    RelOptInfo *inner_rel,
3044                                                    SpecialJoinInfo *sjinfo,
3045                                                    List *restrictlist)
3046 {
3047         JoinType        jointype = sjinfo->jointype;
3048         Selectivity jselec;
3049         Selectivity pselec;
3050         double          nrows;
3051
3052         /*
3053          * Compute joinclause selectivity.      Note that we are only considering
3054          * clauses that become restriction clauses at this join level; we are not
3055          * double-counting them because they were not considered in estimating the
3056          * sizes of the component rels.
3057          *
3058          * For an outer join, we have to distinguish the selectivity of the join's
3059          * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3060          * down".  For inner joins we just count them all as joinclauses.
3061          */
3062         if (IS_OUTER_JOIN(jointype))
3063         {
3064                 List       *joinquals = NIL;
3065                 List       *pushedquals = NIL;
3066                 ListCell   *l;
3067
3068                 /* Grovel through the clauses to separate into two lists */
3069                 foreach(l, restrictlist)
3070                 {
3071                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3072
3073                         Assert(IsA(rinfo, RestrictInfo));
3074                         if (rinfo->is_pushed_down)
3075                                 pushedquals = lappend(pushedquals, rinfo);
3076                         else
3077                                 joinquals = lappend(joinquals, rinfo);
3078                 }
3079
3080                 /* Get the separate selectivities */
3081                 jselec = clauselist_selectivity(root,
3082                                                                                 joinquals,
3083                                                                                 0,
3084                                                                                 jointype,
3085                                                                                 sjinfo);
3086                 pselec = clauselist_selectivity(root,
3087                                                                                 pushedquals,
3088                                                                                 0,
3089                                                                                 jointype,
3090                                                                                 sjinfo);
3091
3092                 /* Avoid leaking a lot of ListCells */
3093                 list_free(joinquals);
3094                 list_free(pushedquals);
3095         }
3096         else
3097         {
3098                 jselec = clauselist_selectivity(root,
3099                                                                                 restrictlist,
3100                                                                                 0,
3101                                                                                 jointype,
3102                                                                                 sjinfo);
3103                 pselec = 0.0;                   /* not used, keep compiler quiet */
3104         }
3105
3106         /*
3107          * Basically, we multiply size of Cartesian product by selectivity.
3108          *
3109          * If we are doing an outer join, take that into account: the joinqual
3110          * selectivity has to be clamped using the knowledge that the output must
3111          * be at least as large as the non-nullable input.      However, any
3112          * pushed-down quals are applied after the outer join, so their
3113          * selectivity applies fully.
3114          *
3115          * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3116          * of LHS rows that have matches, and we apply that straightforwardly.
3117          */
3118         switch (jointype)
3119         {
3120                 case JOIN_INNER:
3121                         nrows = outer_rel->rows * inner_rel->rows * jselec;
3122                         break;
3123                 case JOIN_LEFT:
3124                         nrows = outer_rel->rows * inner_rel->rows * jselec;
3125                         if (nrows < outer_rel->rows)
3126                                 nrows = outer_rel->rows;
3127                         nrows *= pselec;
3128                         break;
3129                 case JOIN_FULL:
3130                         nrows = outer_rel->rows * inner_rel->rows * jselec;
3131                         if (nrows < outer_rel->rows)
3132                                 nrows = outer_rel->rows;
3133                         if (nrows < inner_rel->rows)
3134                                 nrows = inner_rel->rows;
3135                         nrows *= pselec;
3136                         break;
3137                 case JOIN_SEMI:
3138                         nrows = outer_rel->rows * jselec;
3139                         /* pselec not used */
3140                         break;
3141                 case JOIN_ANTI:
3142                         nrows = outer_rel->rows * (1.0 - jselec);
3143                         nrows *= pselec;
3144                         break;
3145                 default:
3146                         /* other values not expected here */
3147                         elog(ERROR, "unrecognized join type: %d", (int) jointype);
3148                         nrows = 0;                      /* keep compiler quiet */
3149                         break;
3150         }
3151
3152         rel->rows = clamp_row_est(nrows);
3153 }
3154
3155 /*
3156  * set_subquery_size_estimates
3157  *              Set the size estimates for a base relation that is a subquery.
3158  *
3159  * The rel's targetlist and restrictinfo list must have been constructed
3160  * already, and the plan for the subquery must have been completed.
3161  * We look at the subquery's plan and PlannerInfo to extract data.
3162  *
3163  * We set the same fields as set_baserel_size_estimates.
3164  */
3165 void
3166 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3167                                                         PlannerInfo *subroot)
3168 {
3169         RangeTblEntry *rte;
3170         ListCell   *lc;
3171
3172         /* Should only be applied to base relations that are subqueries */
3173         Assert(rel->relid > 0);
3174         rte = planner_rt_fetch(rel->relid, root);
3175         Assert(rte->rtekind == RTE_SUBQUERY);
3176
3177         /* Copy raw number of output rows from subplan */
3178         rel->tuples = rel->subplan->plan_rows;
3179
3180         /*
3181          * Compute per-output-column width estimates by examining the subquery's
3182          * targetlist.  For any output that is a plain Var, get the width estimate
3183          * that was made while planning the subquery.  Otherwise, fall back on a
3184          * datatype-based estimate.
3185          */
3186         foreach(lc, subroot->parse->targetList)
3187         {
3188                 TargetEntry *te = (TargetEntry *) lfirst(lc);
3189                 Node       *texpr = (Node *) te->expr;
3190                 int32           item_width;
3191
3192                 Assert(IsA(te, TargetEntry));
3193                 /* junk columns aren't visible to upper query */
3194                 if (te->resjunk)
3195                         continue;
3196
3197                 /*
3198                  * XXX This currently doesn't work for subqueries containing set
3199                  * operations, because the Vars in their tlists are bogus references
3200                  * to the first leaf subquery, which wouldn't give the right answer
3201                  * even if we could still get to its PlannerInfo.  So fall back on
3202                  * datatype in that case.
3203                  */
3204                 if (IsA(texpr, Var) &&
3205                         subroot->parse->setOperations == NULL)
3206                 {
3207                         Var        *var = (Var *) texpr;
3208                         RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3209
3210                         item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3211                 }
3212                 else
3213                 {
3214                         item_width = get_typavgwidth(exprType(texpr), exprTypmod(texpr));
3215                 }
3216                 Assert(item_width > 0);
3217                 Assert(te->resno >= rel->min_attr && te->resno <= rel->max_attr);
3218                 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3219         }
3220
3221         /* Now estimate number of output rows, etc */
3222         set_baserel_size_estimates(root, rel);
3223 }
3224
3225 /*
3226  * set_function_size_estimates
3227  *              Set the size estimates for a base relation that is a function call.
3228  *
3229  * The rel's targetlist and restrictinfo list must have been constructed
3230  * already.
3231  *
3232  * We set the same fields as set_baserel_size_estimates.
3233  */
3234 void
3235 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3236 {
3237         RangeTblEntry *rte;
3238
3239         /* Should only be applied to base relations that are functions */
3240         Assert(rel->relid > 0);
3241         rte = planner_rt_fetch(rel->relid, root);
3242         Assert(rte->rtekind == RTE_FUNCTION);
3243
3244         /* Estimate number of rows the function itself will return */
3245         rel->tuples = clamp_row_est(expression_returns_set_rows(rte->funcexpr));
3246
3247         /* Now estimate number of output rows, etc */
3248         set_baserel_size_estimates(root, rel);
3249 }
3250
3251 /*
3252  * set_values_size_estimates
3253  *              Set the size estimates for a base relation that is a values list.
3254  *
3255  * The rel's targetlist and restrictinfo list must have been constructed
3256  * already.
3257  *
3258  * We set the same fields as set_baserel_size_estimates.
3259  */
3260 void
3261 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3262 {
3263         RangeTblEntry *rte;
3264
3265         /* Should only be applied to base relations that are values lists */
3266         Assert(rel->relid > 0);
3267         rte = planner_rt_fetch(rel->relid, root);
3268         Assert(rte->rtekind == RTE_VALUES);
3269
3270         /*
3271          * Estimate number of rows the values list will return. We know this
3272          * precisely based on the list length (well, barring set-returning
3273          * functions in list items, but that's a refinement not catered for
3274          * anywhere else either).
3275          */
3276         rel->tuples = list_length(rte->values_lists);
3277
3278         /* Now estimate number of output rows, etc */
3279         set_baserel_size_estimates(root, rel);
3280 }
3281
3282 /*
3283  * set_cte_size_estimates
3284  *              Set the size estimates for a base relation that is a CTE reference.
3285  *
3286  * The rel's targetlist and restrictinfo list must have been constructed
3287  * already, and we need the completed plan for the CTE (if a regular CTE)
3288  * or the non-recursive term (if a self-reference).
3289  *
3290  * We set the same fields as set_baserel_size_estimates.
3291  */
3292 void
3293 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3294 {
3295         RangeTblEntry *rte;
3296
3297         /* Should only be applied to base relations that are CTE references */
3298         Assert(rel->relid > 0);
3299         rte = planner_rt_fetch(rel->relid, root);
3300         Assert(rte->rtekind == RTE_CTE);
3301
3302         if (rte->self_reference)
3303         {
3304                 /*
3305                  * In a self-reference, arbitrarily assume the average worktable size
3306                  * is about 10 times the nonrecursive term's size.
3307                  */
3308                 rel->tuples = 10 * cteplan->plan_rows;
3309         }
3310         else
3311         {
3312                 /* Otherwise just believe the CTE plan's output estimate */
3313                 rel->tuples = cteplan->plan_rows;
3314         }
3315
3316         /* Now estimate number of output rows, etc */
3317         set_baserel_size_estimates(root, rel);
3318 }
3319
3320
3321 /*
3322  * set_rel_width
3323  *              Set the estimated output width of a base relation.
3324  *
3325  * The estimated output width is the sum of the per-attribute width estimates
3326  * for the actually-referenced columns, plus any PHVs or other expressions
3327  * that have to be calculated at this relation.  This is the amount of data
3328  * we'd need to pass upwards in case of a sort, hash, etc.
3329  *
3330  * NB: this works best on plain relations because it prefers to look at
3331  * real Vars.  For subqueries, set_subquery_size_estimates will already have
3332  * copied up whatever per-column estimates were made within the subquery,
3333  * and for other types of rels there isn't much we can do anyway.  We fall
3334  * back on (fairly stupid) datatype-based width estimates if we can't get
3335  * any better number.
3336  *
3337  * The per-attribute width estimates are cached for possible re-use while
3338  * building join relations.
3339  */
3340 static void
3341 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3342 {
3343         Oid                     reloid = planner_rt_fetch(rel->relid, root)->relid;
3344         int32           tuple_width = 0;
3345         bool            have_wholerow_var = false;
3346         ListCell   *lc;
3347
3348         foreach(lc, rel->reltargetlist)
3349         {
3350                 Node       *node = (Node *) lfirst(lc);
3351
3352                 if (IsA(node, Var))
3353                 {
3354                         Var                *var = (Var *) node;
3355                         int                     ndx;
3356                         int32           item_width;
3357
3358                         Assert(var->varno == rel->relid);
3359                         Assert(var->varattno >= rel->min_attr);
3360                         Assert(var->varattno <= rel->max_attr);
3361
3362                         ndx = var->varattno - rel->min_attr;
3363
3364                         /*
3365                          * If it's a whole-row Var, we'll deal with it below after we
3366                          * have already cached as many attr widths as possible.
3367                          */
3368                         if (var->varattno == 0)
3369                         {
3370                                 have_wholerow_var = true;
3371                                 continue;
3372                         }
3373
3374                         /*
3375                          * The width may have been cached already (especially if it's
3376                          * a subquery), so don't duplicate effort.
3377                          */
3378                         if (rel->attr_widths[ndx] > 0)
3379                         {
3380                                 tuple_width += rel->attr_widths[ndx];
3381                                 continue;
3382                         }
3383
3384                         /* Try to get column width from statistics */
3385                         if (reloid != InvalidOid && var->varattno > 0)
3386                         {
3387                                 item_width = get_attavgwidth(reloid, var->varattno);
3388                                 if (item_width > 0)
3389                                 {
3390                                         rel->attr_widths[ndx] = item_width;
3391                                         tuple_width += item_width;
3392                                         continue;
3393                                 }
3394                         }
3395
3396                         /*
3397                          * Not a plain relation, or can't find statistics for it. Estimate
3398                          * using just the type info.
3399                          */
3400                         item_width = get_typavgwidth(var->vartype, var->vartypmod);
3401                         Assert(item_width > 0);
3402                         rel->attr_widths[ndx] = item_width;
3403                         tuple_width += item_width;
3404                 }
3405                 else if (IsA(node, PlaceHolderVar))
3406                 {
3407                         PlaceHolderVar *phv = (PlaceHolderVar *) node;
3408                         PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
3409
3410                         tuple_width += phinfo->ph_width;
3411                 }
3412                 else
3413                 {
3414                         /*
3415                          * We could be looking at an expression pulled up from a subquery,
3416                          * or a ROW() representing a whole-row child Var, etc.  Do what we
3417                          * can using the expression type information.
3418                          */
3419                         int32           item_width;
3420
3421                         item_width = get_typavgwidth(exprType(node), exprTypmod(node));
3422                         Assert(item_width > 0);
3423                         tuple_width += item_width;
3424                 }
3425         }
3426
3427         /*
3428          * If we have a whole-row reference, estimate its width as the sum of
3429          * per-column widths plus sizeof(HeapTupleHeaderData).
3430          */
3431         if (have_wholerow_var)
3432         {
3433                 int32   wholerow_width = sizeof(HeapTupleHeaderData);
3434
3435                 if (reloid != InvalidOid)
3436                 {
3437                         /* Real relation, so estimate true tuple width */
3438                         wholerow_width += get_relation_data_width(reloid,
3439                                                                                                           rel->attr_widths - rel->min_attr);
3440                 }
3441                 else
3442                 {
3443                         /* Do what we can with info for a phony rel */
3444                         AttrNumber      i;
3445
3446                         for (i = 1; i <= rel->max_attr; i++)
3447                                 wholerow_width += rel->attr_widths[i - rel->min_attr];
3448                 }
3449
3450                 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
3451
3452                 /*
3453                  * Include the whole-row Var as part of the output tuple.  Yes,
3454                  * that really is what happens at runtime.
3455                  */
3456                 tuple_width += wholerow_width;
3457         }
3458
3459         Assert(tuple_width >= 0);
3460         rel->width = tuple_width;
3461 }
3462
3463 /*
3464  * relation_byte_size
3465  *        Estimate the storage space in bytes for a given number of tuples
3466  *        of a given width (size in bytes).
3467  */
3468 static double
3469 relation_byte_size(double tuples, int width)
3470 {
3471         return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
3472 }
3473
3474 /*
3475  * page_size
3476  *        Returns an estimate of the number of pages covered by a given
3477  *        number of tuples of a given width (size in bytes).
3478  */
3479 static double
3480 page_size(double tuples, int width)
3481 {
3482         return ceil(relation_byte_size(tuples, width) / BLCKSZ);
3483 }