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