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