]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/costsize.c
Pgindent run before 9.1 beta2.
[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-2011, 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  * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
1339  * we are using a hashed Agg node just to do grouping).
1340  *
1341  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1342  * are for appropriately-sorted input.
1343  */
1344 void
1345 cost_agg(Path *path, PlannerInfo *root,
1346                  AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
1347                  int numGroupCols, double numGroups,
1348                  Cost input_startup_cost, Cost input_total_cost,
1349                  double input_tuples)
1350 {
1351         Cost            startup_cost;
1352         Cost            total_cost;
1353         AggClauseCosts dummy_aggcosts;
1354
1355         /* Use all-zero per-aggregate costs if NULL is passed */
1356         if (aggcosts == NULL)
1357         {
1358                 Assert(aggstrategy == AGG_HASHED);
1359                 MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1360                 aggcosts = &dummy_aggcosts;
1361         }
1362
1363         /*
1364          * The transCost.per_tuple component of aggcosts should be charged once
1365          * per input tuple, corresponding to the costs of evaluating the aggregate
1366          * transfns and their input expressions (with any startup cost of course
1367          * charged but once).  The finalCost component is charged once per output
1368          * tuple, corresponding to the costs of evaluating the finalfns.
1369          *
1370          * If we are grouping, we charge an additional cpu_operator_cost per
1371          * grouping column per input tuple for grouping comparisons.
1372          *
1373          * We will produce a single output tuple if not grouping, and a tuple per
1374          * group otherwise.  We charge cpu_tuple_cost for each output tuple.
1375          *
1376          * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1377          * same total CPU cost, but AGG_SORTED has lower startup cost.  If the
1378          * input path is already sorted appropriately, AGG_SORTED should be
1379          * preferred (since it has no risk of memory overflow).  This will happen
1380          * as long as the computed total costs are indeed exactly equal --- but if
1381          * there's roundoff error we might do the wrong thing.  So be sure that
1382          * the computations below form the same intermediate values in the same
1383          * order.
1384          */
1385         if (aggstrategy == AGG_PLAIN)
1386         {
1387                 startup_cost = input_total_cost;
1388                 startup_cost += aggcosts->transCost.startup;
1389                 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1390                 startup_cost += aggcosts->finalCost;
1391                 /* we aren't grouping */
1392                 total_cost = startup_cost + cpu_tuple_cost;
1393         }
1394         else if (aggstrategy == AGG_SORTED)
1395         {
1396                 /* Here we are able to deliver output on-the-fly */
1397                 startup_cost = input_startup_cost;
1398                 total_cost = input_total_cost;
1399                 /* calcs phrased this way to match HASHED case, see note above */
1400                 total_cost += aggcosts->transCost.startup;
1401                 total_cost += aggcosts->transCost.per_tuple * input_tuples;
1402                 total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1403                 total_cost += aggcosts->finalCost * numGroups;
1404                 total_cost += cpu_tuple_cost * numGroups;
1405         }
1406         else
1407         {
1408                 /* must be AGG_HASHED */
1409                 startup_cost = input_total_cost;
1410                 startup_cost += aggcosts->transCost.startup;
1411                 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1412                 startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1413                 total_cost = startup_cost;
1414                 total_cost += aggcosts->finalCost * numGroups;
1415                 total_cost += cpu_tuple_cost * numGroups;
1416         }
1417
1418         path->startup_cost = startup_cost;
1419         path->total_cost = total_cost;
1420 }
1421
1422 /*
1423  * cost_windowagg
1424  *              Determines and returns the cost of performing a WindowAgg plan node,
1425  *              including the cost of its input.
1426  *
1427  * Input is assumed already properly sorted.
1428  */
1429 void
1430 cost_windowagg(Path *path, PlannerInfo *root,
1431                            List *windowFuncs, int numPartCols, int numOrderCols,
1432                            Cost input_startup_cost, Cost input_total_cost,
1433                            double input_tuples)
1434 {
1435         Cost            startup_cost;
1436         Cost            total_cost;
1437         ListCell   *lc;
1438
1439         startup_cost = input_startup_cost;
1440         total_cost = input_total_cost;
1441
1442         /*
1443          * Window functions are assumed to cost their stated execution cost, plus
1444          * the cost of evaluating their input expressions, per tuple.  Since they
1445          * may in fact evaluate their inputs at multiple rows during each cycle,
1446          * this could be a drastic underestimate; but without a way to know how
1447          * many rows the window function will fetch, it's hard to do better.  In
1448          * any case, it's a good estimate for all the built-in window functions,
1449          * so we'll just do this for now.
1450          */
1451         foreach(lc, windowFuncs)
1452         {
1453                 WindowFunc *wfunc = (WindowFunc *) lfirst(lc);
1454                 Cost            wfunccost;
1455                 QualCost        argcosts;
1456
1457                 Assert(IsA(wfunc, WindowFunc));
1458
1459                 wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1460
1461                 /* also add the input expressions' cost to per-input-row costs */
1462                 cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1463                 startup_cost += argcosts.startup;
1464                 wfunccost += argcosts.per_tuple;
1465
1466                 total_cost += wfunccost * input_tuples;
1467         }
1468
1469         /*
1470          * We also charge cpu_operator_cost per grouping column per tuple for
1471          * grouping comparisons, plus cpu_tuple_cost per tuple for general
1472          * overhead.
1473          *
1474          * XXX this neglects costs of spooling the data to disk when it overflows
1475          * work_mem.  Sooner or later that should get accounted for.
1476          */
1477         total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1478         total_cost += cpu_tuple_cost * input_tuples;
1479
1480         path->startup_cost = startup_cost;
1481         path->total_cost = total_cost;
1482 }
1483
1484 /*
1485  * cost_group
1486  *              Determines and returns the cost of performing a Group plan node,
1487  *              including the cost of its input.
1488  *
1489  * Note: caller must ensure that input costs are for appropriately-sorted
1490  * input.
1491  */
1492 void
1493 cost_group(Path *path, PlannerInfo *root,
1494                    int numGroupCols, double numGroups,
1495                    Cost input_startup_cost, Cost input_total_cost,
1496                    double input_tuples)
1497 {
1498         Cost            startup_cost;
1499         Cost            total_cost;
1500
1501         startup_cost = input_startup_cost;
1502         total_cost = input_total_cost;
1503
1504         /*
1505          * Charge one cpu_operator_cost per comparison per input tuple. We assume
1506          * all columns get compared at most of the tuples.
1507          */
1508         total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1509
1510         path->startup_cost = startup_cost;
1511         path->total_cost = total_cost;
1512 }
1513
1514 /*
1515  * If a nestloop's inner path is an indexscan, be sure to use its estimated
1516  * output row count, which may be lower than the restriction-clause-only row
1517  * count of its parent.  (We don't include this case in the PATH_ROWS macro
1518  * because it applies *only* to a nestloop's inner relation.)  We have to
1519  * be prepared to recurse through Append or MergeAppend nodes in case of an
1520  * appendrel.  (It's not clear MergeAppend can be seen here, but we may as
1521  * well handle it if so.)
1522  */
1523 static double
1524 nestloop_inner_path_rows(Path *path)
1525 {
1526         double          result;
1527
1528         if (IsA(path, IndexPath))
1529                 result = ((IndexPath *) path)->rows;
1530         else if (IsA(path, BitmapHeapPath))
1531                 result = ((BitmapHeapPath *) path)->rows;
1532         else if (IsA(path, AppendPath))
1533         {
1534                 ListCell   *l;
1535
1536                 result = 0;
1537                 foreach(l, ((AppendPath *) path)->subpaths)
1538                 {
1539                         result += nestloop_inner_path_rows((Path *) lfirst(l));
1540                 }
1541         }
1542         else if (IsA(path, MergeAppendPath))
1543         {
1544                 ListCell   *l;
1545
1546                 result = 0;
1547                 foreach(l, ((MergeAppendPath *) path)->subpaths)
1548                 {
1549                         result += nestloop_inner_path_rows((Path *) lfirst(l));
1550                 }
1551         }
1552         else
1553                 result = PATH_ROWS(path);
1554
1555         return result;
1556 }
1557
1558 /*
1559  * cost_nestloop
1560  *        Determines and returns the cost of joining two relations using the
1561  *        nested loop algorithm.
1562  *
1563  * 'path' is already filled in except for the cost fields
1564  * 'sjinfo' is extra info about the join for selectivity estimation
1565  */
1566 void
1567 cost_nestloop(NestPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1568 {
1569         Path       *outer_path = path->outerjoinpath;
1570         Path       *inner_path = path->innerjoinpath;
1571         Cost            startup_cost = 0;
1572         Cost            run_cost = 0;
1573         Cost            inner_rescan_start_cost;
1574         Cost            inner_rescan_total_cost;
1575         Cost            inner_run_cost;
1576         Cost            inner_rescan_run_cost;
1577         Cost            cpu_per_tuple;
1578         QualCost        restrict_qual_cost;
1579         double          outer_path_rows = PATH_ROWS(outer_path);
1580         double          inner_path_rows = nestloop_inner_path_rows(inner_path);
1581         double          ntuples;
1582         Selectivity outer_match_frac;
1583         Selectivity match_count;
1584         bool            indexed_join_quals;
1585
1586         if (!enable_nestloop)
1587                 startup_cost += disable_cost;
1588
1589         /* estimate costs to rescan the inner relation */
1590         cost_rescan(root, inner_path,
1591                                 &inner_rescan_start_cost,
1592                                 &inner_rescan_total_cost);
1593
1594         /* cost of source data */
1595
1596         /*
1597          * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1598          * before we can start returning tuples, so the join's startup cost is
1599          * their sum.  We'll also pay the inner path's rescan startup cost
1600          * multiple times.
1601          */
1602         startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1603         run_cost += outer_path->total_cost - outer_path->startup_cost;
1604         if (outer_path_rows > 1)
1605                 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1606
1607         inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1608         inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1609
1610         if (adjust_semi_join(root, path, sjinfo,
1611                                                  &outer_match_frac,
1612                                                  &match_count,
1613                                                  &indexed_join_quals))
1614         {
1615                 double          outer_matched_rows;
1616                 Selectivity inner_scan_frac;
1617
1618                 /*
1619                  * SEMI or ANTI join: executor will stop after first match.
1620                  *
1621                  * For an outer-rel row that has at least one match, we can expect the
1622                  * inner scan to stop after a fraction 1/(match_count+1) of the inner
1623                  * rows, if the matches are evenly distributed.  Since they probably
1624                  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1625                  * that fraction.  (If we used a larger fuzz factor, we'd have to
1626                  * clamp inner_scan_frac to at most 1.0; but since match_count is at
1627                  * least 1, no such clamp is needed now.)
1628                  *
1629                  * A complicating factor is that rescans may be cheaper than first
1630                  * scans.  If we never scan all the way to the end of the inner rel,
1631                  * it might be (depending on the plan type) that we'd never pay the
1632                  * whole inner first-scan run cost.  However it is difficult to
1633                  * estimate whether that will happen, so be conservative and always
1634                  * charge the whole first-scan cost once.
1635                  */
1636                 run_cost += inner_run_cost;
1637
1638                 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
1639                 inner_scan_frac = 2.0 / (match_count + 1.0);
1640
1641                 /* Add inner run cost for additional outer tuples having matches */
1642                 if (outer_matched_rows > 1)
1643                         run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1644
1645                 /* Compute number of tuples processed (not number emitted!) */
1646                 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1647
1648                 /*
1649                  * For unmatched outer-rel rows, there are two cases.  If the inner
1650                  * path is an indexscan using all the joinquals as indexquals, then an
1651                  * unmatched row results in an indexscan returning no rows, which is
1652                  * probably quite cheap.  We estimate this case as the same cost to
1653                  * return the first tuple of a nonempty scan.  Otherwise, the executor
1654                  * will have to scan the whole inner rel; not so cheap.
1655                  */
1656                 if (indexed_join_quals)
1657                 {
1658                         run_cost += (outer_path_rows - outer_matched_rows) *
1659                                 inner_rescan_run_cost / inner_path_rows;
1660
1661                         /*
1662                          * We won't be evaluating any quals at all for these rows, so
1663                          * don't add them to ntuples.
1664                          */
1665                 }
1666                 else
1667                 {
1668                         run_cost += (outer_path_rows - outer_matched_rows) *
1669                                 inner_rescan_run_cost;
1670                         ntuples += (outer_path_rows - outer_matched_rows) *
1671                                 inner_path_rows;
1672                 }
1673         }
1674         else
1675         {
1676                 /* Normal case; we'll scan whole input rel for each outer row */
1677                 run_cost += inner_run_cost;
1678                 if (outer_path_rows > 1)
1679                         run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1680
1681                 /* Compute number of tuples processed (not number emitted!) */
1682                 ntuples = outer_path_rows * inner_path_rows;
1683         }
1684
1685         /* CPU costs */
1686         cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1687         startup_cost += restrict_qual_cost.startup;
1688         cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1689         run_cost += cpu_per_tuple * ntuples;
1690
1691         path->path.startup_cost = startup_cost;
1692         path->path.total_cost = startup_cost + run_cost;
1693 }
1694
1695 /*
1696  * cost_mergejoin
1697  *        Determines and returns the cost of joining two relations using the
1698  *        merge join algorithm.
1699  *
1700  * Unlike other costsize functions, this routine makes one actual decision:
1701  * whether we should materialize the inner path.  We do that either because
1702  * the inner path can't support mark/restore, or because it's cheaper to
1703  * use an interposed Material node to handle mark/restore.      When the decision
1704  * is cost-based it would be logically cleaner to build and cost two separate
1705  * paths with and without that flag set; but that would require repeating most
1706  * of the calculations here, which are not all that cheap.      Since the choice
1707  * will not affect output pathkeys or startup cost, only total cost, there is
1708  * no possibility of wanting to keep both paths.  So it seems best to make
1709  * the decision here and record it in the path's materialize_inner field.
1710  *
1711  * 'path' is already filled in except for the cost fields and materialize_inner
1712  * 'sjinfo' is extra info about the join for selectivity estimation
1713  *
1714  * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
1715  * outersortkeys and innersortkeys are lists of the keys to be used
1716  * to sort the outer and inner relations, or NIL if no explicit
1717  * sort is needed because the source path is already ordered.
1718  */
1719 void
1720 cost_mergejoin(MergePath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1721 {
1722         Path       *outer_path = path->jpath.outerjoinpath;
1723         Path       *inner_path = path->jpath.innerjoinpath;
1724         List       *mergeclauses = path->path_mergeclauses;
1725         List       *outersortkeys = path->outersortkeys;
1726         List       *innersortkeys = path->innersortkeys;
1727         Cost            startup_cost = 0;
1728         Cost            run_cost = 0;
1729         Cost            cpu_per_tuple,
1730                                 inner_run_cost,
1731                                 bare_inner_cost,
1732                                 mat_inner_cost;
1733         QualCost        merge_qual_cost;
1734         QualCost        qp_qual_cost;
1735         double          outer_path_rows = PATH_ROWS(outer_path);
1736         double          inner_path_rows = PATH_ROWS(inner_path);
1737         double          outer_rows,
1738                                 inner_rows,
1739                                 outer_skip_rows,
1740                                 inner_skip_rows;
1741         double          mergejointuples,
1742                                 rescannedtuples;
1743         double          rescanratio;
1744         Selectivity outerstartsel,
1745                                 outerendsel,
1746                                 innerstartsel,
1747                                 innerendsel;
1748         Path            sort_path;              /* dummy for result of cost_sort */
1749
1750         /* Protect some assumptions below that rowcounts aren't zero or NaN */
1751         if (outer_path_rows <= 0 || isnan(outer_path_rows))
1752                 outer_path_rows = 1;
1753         if (inner_path_rows <= 0 || isnan(inner_path_rows))
1754                 inner_path_rows = 1;
1755
1756         if (!enable_mergejoin)
1757                 startup_cost += disable_cost;
1758
1759         /*
1760          * Compute cost of the mergequals and qpquals (other restriction clauses)
1761          * separately.
1762          */
1763         cost_qual_eval(&merge_qual_cost, mergeclauses, root);
1764         cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
1765         qp_qual_cost.startup -= merge_qual_cost.startup;
1766         qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
1767
1768         /*
1769          * Get approx # tuples passing the mergequals.  We use approx_tuple_count
1770          * here because we need an estimate done with JOIN_INNER semantics.
1771          */
1772         mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
1773
1774         /*
1775          * When there are equal merge keys in the outer relation, the mergejoin
1776          * must rescan any matching tuples in the inner relation. This means
1777          * re-fetching inner tuples; we have to estimate how often that happens.
1778          *
1779          * For regular inner and outer joins, the number of re-fetches can be
1780          * estimated approximately as size of merge join output minus size of
1781          * inner relation. Assume that the distinct key values are 1, 2, ..., and
1782          * denote the number of values of each key in the outer relation as m1,
1783          * m2, ...; in the inner relation, n1, n2, ...  Then we have
1784          *
1785          * size of join = m1 * n1 + m2 * n2 + ...
1786          *
1787          * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
1788          * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
1789          * relation
1790          *
1791          * This equation works correctly for outer tuples having no inner match
1792          * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
1793          * are effectively subtracting those from the number of rescanned tuples,
1794          * when we should not.  Can we do better without expensive selectivity
1795          * computations?
1796          *
1797          * The whole issue is moot if we are working from a unique-ified outer
1798          * input.
1799          */
1800         if (IsA(outer_path, UniquePath))
1801                 rescannedtuples = 0;
1802         else
1803         {
1804                 rescannedtuples = mergejointuples - inner_path_rows;
1805                 /* Must clamp because of possible underestimate */
1806                 if (rescannedtuples < 0)
1807                         rescannedtuples = 0;
1808         }
1809         /* We'll inflate various costs this much to account for rescanning */
1810         rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
1811
1812         /*
1813          * A merge join will stop as soon as it exhausts either input stream
1814          * (unless it's an outer join, in which case the outer side has to be
1815          * scanned all the way anyway).  Estimate fraction of the left and right
1816          * inputs that will actually need to be scanned.  Likewise, we can
1817          * estimate the number of rows that will be skipped before the first join
1818          * pair is found, which should be factored into startup cost. We use only
1819          * the first (most significant) merge clause for this purpose. Since
1820          * mergejoinscansel() is a fairly expensive computation, we cache the
1821          * results in the merge clause RestrictInfo.
1822          */
1823         if (mergeclauses && path->jpath.jointype != JOIN_FULL)
1824         {
1825                 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1826                 List       *opathkeys;
1827                 List       *ipathkeys;
1828                 PathKey    *opathkey;
1829                 PathKey    *ipathkey;
1830                 MergeScanSelCache *cache;
1831
1832                 /* Get the input pathkeys to determine the sort-order details */
1833                 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1834                 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1835                 Assert(opathkeys);
1836                 Assert(ipathkeys);
1837                 opathkey = (PathKey *) linitial(opathkeys);
1838                 ipathkey = (PathKey *) linitial(ipathkeys);
1839                 /* debugging check */
1840                 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1841                         opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
1842                         opathkey->pk_strategy != ipathkey->pk_strategy ||
1843                         opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1844                         elog(ERROR, "left and right pathkeys do not match in mergejoin");
1845
1846                 /* Get the selectivity with caching */
1847                 cache = cached_scansel(root, firstclause, opathkey);
1848
1849                 if (bms_is_subset(firstclause->left_relids,
1850                                                   outer_path->parent->relids))
1851                 {
1852                         /* left side of clause is outer */
1853                         outerstartsel = cache->leftstartsel;
1854                         outerendsel = cache->leftendsel;
1855                         innerstartsel = cache->rightstartsel;
1856                         innerendsel = cache->rightendsel;
1857                 }
1858                 else
1859                 {
1860                         /* left side of clause is inner */
1861                         outerstartsel = cache->rightstartsel;
1862                         outerendsel = cache->rightendsel;
1863                         innerstartsel = cache->leftstartsel;
1864                         innerendsel = cache->leftendsel;
1865                 }
1866                 if (path->jpath.jointype == JOIN_LEFT ||
1867                         path->jpath.jointype == JOIN_ANTI)
1868                 {
1869                         outerstartsel = 0.0;
1870                         outerendsel = 1.0;
1871                 }
1872                 else if (path->jpath.jointype == JOIN_RIGHT)
1873                 {
1874                         innerstartsel = 0.0;
1875                         innerendsel = 1.0;
1876                 }
1877         }
1878         else
1879         {
1880                 /* cope with clauseless or full mergejoin */
1881                 outerstartsel = innerstartsel = 0.0;
1882                 outerendsel = innerendsel = 1.0;
1883         }
1884
1885         /*
1886          * Convert selectivities to row counts.  We force outer_rows and
1887          * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1888          */
1889         outer_skip_rows = rint(outer_path_rows * outerstartsel);
1890         inner_skip_rows = rint(inner_path_rows * innerstartsel);
1891         outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1892         inner_rows = clamp_row_est(inner_path_rows * innerendsel);
1893
1894         Assert(outer_skip_rows <= outer_rows);
1895         Assert(inner_skip_rows <= inner_rows);
1896
1897         /*
1898          * Readjust scan selectivities to account for above rounding.  This is
1899          * normally an insignificant effect, but when there are only a few rows in
1900          * the inputs, failing to do this makes for a large percentage error.
1901          */
1902         outerstartsel = outer_skip_rows / outer_path_rows;
1903         innerstartsel = inner_skip_rows / inner_path_rows;
1904         outerendsel = outer_rows / outer_path_rows;
1905         innerendsel = inner_rows / inner_path_rows;
1906
1907         Assert(outerstartsel <= outerendsel);
1908         Assert(innerstartsel <= innerendsel);
1909
1910         /* cost of source data */
1911
1912         if (outersortkeys)                      /* do we need to sort outer? */
1913         {
1914                 cost_sort(&sort_path,
1915                                   root,
1916                                   outersortkeys,
1917                                   outer_path->total_cost,
1918                                   outer_path_rows,
1919                                   outer_path->parent->width,
1920                                   0.0,
1921                                   work_mem,
1922                                   -1.0);
1923                 startup_cost += sort_path.startup_cost;
1924                 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1925                         * outerstartsel;
1926                 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1927                         * (outerendsel - outerstartsel);
1928         }
1929         else
1930         {
1931                 startup_cost += outer_path->startup_cost;
1932                 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
1933                         * outerstartsel;
1934                 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1935                         * (outerendsel - outerstartsel);
1936         }
1937
1938         if (innersortkeys)                      /* do we need to sort inner? */
1939         {
1940                 cost_sort(&sort_path,
1941                                   root,
1942                                   innersortkeys,
1943                                   inner_path->total_cost,
1944                                   inner_path_rows,
1945                                   inner_path->parent->width,
1946                                   0.0,
1947                                   work_mem,
1948                                   -1.0);
1949                 startup_cost += sort_path.startup_cost;
1950                 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1951                         * innerstartsel;
1952                 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
1953                         * (innerendsel - innerstartsel);
1954         }
1955         else
1956         {
1957                 startup_cost += inner_path->startup_cost;
1958                 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
1959                         * innerstartsel;
1960                 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
1961                         * (innerendsel - innerstartsel);
1962         }
1963
1964         /*
1965          * Decide whether we want to materialize the inner input to shield it from
1966          * mark/restore and performing re-fetches.      Our cost model for regular
1967          * re-fetches is that a re-fetch costs the same as an original fetch,
1968          * which is probably an overestimate; but on the other hand we ignore the
1969          * bookkeeping costs of mark/restore.  Not clear if it's worth developing
1970          * a more refined model.  So we just need to inflate the inner run cost by
1971          * rescanratio.
1972          */
1973         bare_inner_cost = inner_run_cost * rescanratio;
1974
1975         /*
1976          * When we interpose a Material node the re-fetch cost is assumed to be
1977          * just cpu_operator_cost per tuple, independently of the underlying
1978          * plan's cost; and we charge an extra cpu_operator_cost per original
1979          * fetch as well.  Note that we're assuming the materialize node will
1980          * never spill to disk, since it only has to remember tuples back to the
1981          * last mark.  (If there are a huge number of duplicates, our other cost
1982          * factors will make the path so expensive that it probably won't get
1983          * chosen anyway.)      So we don't use cost_rescan here.
1984          *
1985          * Note: keep this estimate in sync with create_mergejoin_plan's labeling
1986          * of the generated Material node.
1987          */
1988         mat_inner_cost = inner_run_cost +
1989                 cpu_operator_cost * inner_path_rows * rescanratio;
1990
1991         /*
1992          * Prefer materializing if it looks cheaper, unless the user has asked to
1993          * suppress materialization.
1994          */
1995         if (enable_material && mat_inner_cost < bare_inner_cost)
1996                 path->materialize_inner = true;
1997
1998         /*
1999          * Even if materializing doesn't look cheaper, we *must* do it if the
2000          * inner path is to be used directly (without sorting) and it doesn't
2001          * support mark/restore.
2002          *
2003          * Since the inner side must be ordered, and only Sorts and IndexScans can
2004          * create order to begin with, and they both support mark/restore, you
2005          * might think there's no problem --- but you'd be wrong.  Nestloop and
2006          * merge joins can *preserve* the order of their inputs, so they can be
2007          * selected as the input of a mergejoin, and they don't support
2008          * mark/restore at present.
2009          *
2010          * We don't test the value of enable_material here, because
2011          * materialization is required for correctness in this case, and turning
2012          * it off does not entitle us to deliver an invalid plan.
2013          */
2014         else if (innersortkeys == NIL &&
2015                          !ExecSupportsMarkRestore(inner_path->pathtype))
2016                 path->materialize_inner = true;
2017
2018         /*
2019          * Also, force materializing if the inner path is to be sorted and the
2020          * sort is expected to spill to disk.  This is because the final merge
2021          * pass can be done on-the-fly if it doesn't have to support mark/restore.
2022          * We don't try to adjust the cost estimates for this consideration,
2023          * though.
2024          *
2025          * Since materialization is a performance optimization in this case,
2026          * rather than necessary for correctness, we skip it if enable_material is
2027          * off.
2028          */
2029         else if (enable_material && innersortkeys != NIL &&
2030                          relation_byte_size(inner_path_rows, inner_path->parent->width) >
2031                          (work_mem * 1024L))
2032                 path->materialize_inner = true;
2033         else
2034                 path->materialize_inner = false;
2035
2036         /* Charge the right incremental cost for the chosen case */
2037         if (path->materialize_inner)
2038                 run_cost += mat_inner_cost;
2039         else
2040                 run_cost += bare_inner_cost;
2041
2042         /* CPU costs */
2043
2044         /*
2045          * The number of tuple comparisons needed is approximately number of outer
2046          * rows plus number of inner rows plus number of rescanned tuples (can we
2047          * refine this?).  At each one, we need to evaluate the mergejoin quals.
2048          */
2049         startup_cost += merge_qual_cost.startup;
2050         startup_cost += merge_qual_cost.per_tuple *
2051                 (outer_skip_rows + inner_skip_rows * rescanratio);
2052         run_cost += merge_qual_cost.per_tuple *
2053                 ((outer_rows - outer_skip_rows) +
2054                  (inner_rows - inner_skip_rows) * rescanratio);
2055
2056         /*
2057          * For each tuple that gets through the mergejoin proper, we charge
2058          * cpu_tuple_cost plus the cost of evaluating additional restriction
2059          * clauses that are to be applied at the join.  (This is pessimistic since
2060          * not all of the quals may get evaluated at each tuple.)
2061          *
2062          * Note: we could adjust for SEMI/ANTI joins skipping some qual
2063          * evaluations here, but it's probably not worth the trouble.
2064          */
2065         startup_cost += qp_qual_cost.startup;
2066         cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2067         run_cost += cpu_per_tuple * mergejointuples;
2068
2069         path->jpath.path.startup_cost = startup_cost;
2070         path->jpath.path.total_cost = startup_cost + run_cost;
2071 }
2072
2073 /*
2074  * run mergejoinscansel() with caching
2075  */
2076 static MergeScanSelCache *
2077 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2078 {
2079         MergeScanSelCache *cache;
2080         ListCell   *lc;
2081         Selectivity leftstartsel,
2082                                 leftendsel,
2083                                 rightstartsel,
2084                                 rightendsel;
2085         MemoryContext oldcontext;
2086
2087         /* Do we have this result already? */
2088         foreach(lc, rinfo->scansel_cache)
2089         {
2090                 cache = (MergeScanSelCache *) lfirst(lc);
2091                 if (cache->opfamily == pathkey->pk_opfamily &&
2092                         cache->collation == pathkey->pk_eclass->ec_collation &&
2093                         cache->strategy == pathkey->pk_strategy &&
2094                         cache->nulls_first == pathkey->pk_nulls_first)
2095                         return cache;
2096         }
2097
2098         /* Nope, do the computation */
2099         mergejoinscansel(root,
2100                                          (Node *) rinfo->clause,
2101                                          pathkey->pk_opfamily,
2102                                          pathkey->pk_strategy,
2103                                          pathkey->pk_nulls_first,
2104                                          &leftstartsel,
2105                                          &leftendsel,
2106                                          &rightstartsel,
2107                                          &rightendsel);
2108
2109         /* Cache the result in suitably long-lived workspace */
2110         oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2111
2112         cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2113         cache->opfamily = pathkey->pk_opfamily;
2114         cache->collation = pathkey->pk_eclass->ec_collation;
2115         cache->strategy = pathkey->pk_strategy;
2116         cache->nulls_first = pathkey->pk_nulls_first;
2117         cache->leftstartsel = leftstartsel;
2118         cache->leftendsel = leftendsel;
2119         cache->rightstartsel = rightstartsel;
2120         cache->rightendsel = rightendsel;
2121
2122         rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2123
2124         MemoryContextSwitchTo(oldcontext);
2125
2126         return cache;
2127 }
2128
2129 /*
2130  * cost_hashjoin
2131  *        Determines and returns the cost of joining two relations using the
2132  *        hash join algorithm.
2133  *
2134  * 'path' is already filled in except for the cost fields
2135  * 'sjinfo' is extra info about the join for selectivity estimation
2136  *
2137  * Note: path's hashclauses should be a subset of the joinrestrictinfo list
2138  */
2139 void
2140 cost_hashjoin(HashPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
2141 {
2142         Path       *outer_path = path->jpath.outerjoinpath;
2143         Path       *inner_path = path->jpath.innerjoinpath;
2144         List       *hashclauses = path->path_hashclauses;
2145         Cost            startup_cost = 0;
2146         Cost            run_cost = 0;
2147         Cost            cpu_per_tuple;
2148         QualCost        hash_qual_cost;
2149         QualCost        qp_qual_cost;
2150         double          hashjointuples;
2151         double          outer_path_rows = PATH_ROWS(outer_path);
2152         double          inner_path_rows = PATH_ROWS(inner_path);
2153         int                     num_hashclauses = list_length(hashclauses);
2154         int                     numbuckets;
2155         int                     numbatches;
2156         int                     num_skew_mcvs;
2157         double          virtualbuckets;
2158         Selectivity innerbucketsize;
2159         Selectivity outer_match_frac;
2160         Selectivity match_count;
2161         ListCell   *hcl;
2162
2163         if (!enable_hashjoin)
2164                 startup_cost += disable_cost;
2165
2166         /*
2167          * Compute cost of the hashquals and qpquals (other restriction clauses)
2168          * separately.
2169          */
2170         cost_qual_eval(&hash_qual_cost, hashclauses, root);
2171         cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2172         qp_qual_cost.startup -= hash_qual_cost.startup;
2173         qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2174
2175         /* cost of source data */
2176         startup_cost += outer_path->startup_cost;
2177         run_cost += outer_path->total_cost - outer_path->startup_cost;
2178         startup_cost += inner_path->total_cost;
2179
2180         /*
2181          * Cost of computing hash function: must do it once per input tuple. We
2182          * charge one cpu_operator_cost for each column's hash function.  Also,
2183          * tack on one cpu_tuple_cost per inner row, to model the costs of
2184          * inserting the row into the hashtable.
2185          *
2186          * XXX when a hashclause is more complex than a single operator, we really
2187          * should charge the extra eval costs of the left or right side, as
2188          * appropriate, here.  This seems more work than it's worth at the moment.
2189          */
2190         startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2191                 * inner_path_rows;
2192         run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2193
2194         /*
2195          * Get hash table size that executor would use for inner relation.
2196          *
2197          * XXX for the moment, always assume that skew optimization will be
2198          * performed.  As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2199          * trying to determine that for sure.
2200          *
2201          * XXX at some point it might be interesting to try to account for skew
2202          * optimization in the cost estimate, but for now, we don't.
2203          */
2204         ExecChooseHashTableSize(inner_path_rows,
2205                                                         inner_path->parent->width,
2206                                                         true,           /* useskew */
2207                                                         &numbuckets,
2208                                                         &numbatches,
2209                                                         &num_skew_mcvs);
2210         virtualbuckets = (double) numbuckets *(double) numbatches;
2211
2212         /* mark the path with estimated # of batches */
2213         path->num_batches = numbatches;
2214
2215         /*
2216          * Determine bucketsize fraction for inner relation.  We use the smallest
2217          * bucketsize estimated for any individual hashclause; this is undoubtedly
2218          * conservative.
2219          *
2220          * BUT: if inner relation has been unique-ified, we can assume it's good
2221          * for hashing.  This is important both because it's the right answer, and
2222          * because we avoid contaminating the cache with a value that's wrong for
2223          * non-unique-ified paths.
2224          */
2225         if (IsA(inner_path, UniquePath))
2226                 innerbucketsize = 1.0 / virtualbuckets;
2227         else
2228         {
2229                 innerbucketsize = 1.0;
2230                 foreach(hcl, hashclauses)
2231                 {
2232                         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2233                         Selectivity thisbucketsize;
2234
2235                         Assert(IsA(restrictinfo, RestrictInfo));
2236
2237                         /*
2238                          * First we have to figure out which side of the hashjoin clause
2239                          * is the inner side.
2240                          *
2241                          * Since we tend to visit the same clauses over and over when
2242                          * planning a large query, we cache the bucketsize estimate in the
2243                          * RestrictInfo node to avoid repeated lookups of statistics.
2244                          */
2245                         if (bms_is_subset(restrictinfo->right_relids,
2246                                                           inner_path->parent->relids))
2247                         {
2248                                 /* righthand side is inner */
2249                                 thisbucketsize = restrictinfo->right_bucketsize;
2250                                 if (thisbucketsize < 0)
2251                                 {
2252                                         /* not cached yet */
2253                                         thisbucketsize =
2254                                                 estimate_hash_bucketsize(root,
2255                                                                                    get_rightop(restrictinfo->clause),
2256                                                                                                  virtualbuckets);
2257                                         restrictinfo->right_bucketsize = thisbucketsize;
2258                                 }
2259                         }
2260                         else
2261                         {
2262                                 Assert(bms_is_subset(restrictinfo->left_relids,
2263                                                                          inner_path->parent->relids));
2264                                 /* lefthand side is inner */
2265                                 thisbucketsize = restrictinfo->left_bucketsize;
2266                                 if (thisbucketsize < 0)
2267                                 {
2268                                         /* not cached yet */
2269                                         thisbucketsize =
2270                                                 estimate_hash_bucketsize(root,
2271                                                                                         get_leftop(restrictinfo->clause),
2272                                                                                                  virtualbuckets);
2273                                         restrictinfo->left_bucketsize = thisbucketsize;
2274                                 }
2275                         }
2276
2277                         if (innerbucketsize > thisbucketsize)
2278                                 innerbucketsize = thisbucketsize;
2279                 }
2280         }
2281
2282         /*
2283          * If inner relation is too big then we will need to "batch" the join,
2284          * which implies writing and reading most of the tuples to disk an extra
2285          * time.  Charge seq_page_cost per page, since the I/O should be nice and
2286          * sequential.  Writing the inner rel counts as startup cost, all the rest
2287          * as run cost.
2288          */
2289         if (numbatches > 1)
2290         {
2291                 double          outerpages = page_size(outer_path_rows,
2292                                                                                    outer_path->parent->width);
2293                 double          innerpages = page_size(inner_path_rows,
2294                                                                                    inner_path->parent->width);
2295
2296                 startup_cost += seq_page_cost * innerpages;
2297                 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2298         }
2299
2300         /* CPU costs */
2301
2302         if (adjust_semi_join(root, &path->jpath, sjinfo,
2303                                                  &outer_match_frac,
2304                                                  &match_count,
2305                                                  NULL))
2306         {
2307                 double          outer_matched_rows;
2308                 Selectivity inner_scan_frac;
2309
2310                 /*
2311                  * SEMI or ANTI join: executor will stop after first match.
2312                  *
2313                  * For an outer-rel row that has at least one match, we can expect the
2314                  * bucket scan to stop after a fraction 1/(match_count+1) of the
2315                  * bucket's rows, if the matches are evenly distributed.  Since they
2316                  * probably aren't quite evenly distributed, we apply a fuzz factor of
2317                  * 2.0 to that fraction.  (If we used a larger fuzz factor, we'd have
2318                  * to clamp inner_scan_frac to at most 1.0; but since match_count is
2319                  * at least 1, no such clamp is needed now.)
2320                  */
2321                 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
2322                 inner_scan_frac = 2.0 / (match_count + 1.0);
2323
2324                 startup_cost += hash_qual_cost.startup;
2325                 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2326                         clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2327
2328                 /*
2329                  * For unmatched outer-rel rows, the picture is quite a lot different.
2330                  * In the first place, there is no reason to assume that these rows
2331                  * preferentially hit heavily-populated buckets; instead assume they
2332                  * are uncorrelated with the inner distribution and so they see an
2333                  * average bucket size of inner_path_rows / virtualbuckets.  In the
2334                  * second place, it seems likely that they will have few if any exact
2335                  * hash-code matches and so very few of the tuples in the bucket will
2336                  * actually require eval of the hash quals.  We don't have any good
2337                  * way to estimate how many will, but for the moment assume that the
2338                  * effective cost per bucket entry is one-tenth what it is for
2339                  * matchable tuples.
2340                  */
2341                 run_cost += hash_qual_cost.per_tuple *
2342                         (outer_path_rows - outer_matched_rows) *
2343                         clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2344
2345                 /* Get # of tuples that will pass the basic join */
2346                 if (path->jpath.jointype == JOIN_SEMI)
2347                         hashjointuples = outer_matched_rows;
2348                 else
2349                         hashjointuples = outer_path_rows - outer_matched_rows;
2350         }
2351         else
2352         {
2353                 /*
2354                  * The number of tuple comparisons needed is the number of outer
2355                  * tuples times the typical number of tuples in a hash bucket, which
2356                  * is the inner relation size times its bucketsize fraction.  At each
2357                  * one, we need to evaluate the hashjoin quals.  But actually,
2358                  * charging the full qual eval cost at each tuple is pessimistic,
2359                  * since we don't evaluate the quals unless the hash values match
2360                  * exactly.  For lack of a better idea, halve the cost estimate to
2361                  * allow for that.
2362                  */
2363                 startup_cost += hash_qual_cost.startup;
2364                 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2365                         clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2366
2367                 /*
2368                  * Get approx # tuples passing the hashquals.  We use
2369                  * approx_tuple_count here because we need an estimate done with
2370                  * JOIN_INNER semantics.
2371                  */
2372                 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2373         }
2374
2375         /*
2376          * For each tuple that gets through the hashjoin proper, we charge
2377          * cpu_tuple_cost plus the cost of evaluating additional restriction
2378          * clauses that are to be applied at the join.  (This is pessimistic since
2379          * not all of the quals may get evaluated at each tuple.)
2380          */
2381         startup_cost += qp_qual_cost.startup;
2382         cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2383         run_cost += cpu_per_tuple * hashjointuples;
2384
2385         path->jpath.path.startup_cost = startup_cost;
2386         path->jpath.path.total_cost = startup_cost + run_cost;
2387 }
2388
2389
2390 /*
2391  * cost_subplan
2392  *              Figure the costs for a SubPlan (or initplan).
2393  *
2394  * Note: we could dig the subplan's Plan out of the root list, but in practice
2395  * all callers have it handy already, so we make them pass it.
2396  */
2397 void
2398 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2399 {
2400         QualCost        sp_cost;
2401
2402         /* Figure any cost for evaluating the testexpr */
2403         cost_qual_eval(&sp_cost,
2404                                    make_ands_implicit((Expr *) subplan->testexpr),
2405                                    root);
2406
2407         if (subplan->useHashTable)
2408         {
2409                 /*
2410                  * If we are using a hash table for the subquery outputs, then the
2411                  * cost of evaluating the query is a one-time cost.  We charge one
2412                  * cpu_operator_cost per tuple for the work of loading the hashtable,
2413                  * too.
2414                  */
2415                 sp_cost.startup += plan->total_cost +
2416                         cpu_operator_cost * plan->plan_rows;
2417
2418                 /*
2419                  * The per-tuple costs include the cost of evaluating the lefthand
2420                  * expressions, plus the cost of probing the hashtable.  We already
2421                  * accounted for the lefthand expressions as part of the testexpr, and
2422                  * will also have counted one cpu_operator_cost for each comparison
2423                  * operator.  That is probably too low for the probing cost, but it's
2424                  * hard to make a better estimate, so live with it for now.
2425                  */
2426         }
2427         else
2428         {
2429                 /*
2430                  * Otherwise we will be rescanning the subplan output on each
2431                  * evaluation.  We need to estimate how much of the output we will
2432                  * actually need to scan.  NOTE: this logic should agree with the
2433                  * tuple_fraction estimates used by make_subplan() in
2434                  * plan/subselect.c.
2435                  */
2436                 Cost            plan_run_cost = plan->total_cost - plan->startup_cost;
2437
2438                 if (subplan->subLinkType == EXISTS_SUBLINK)
2439                 {
2440                         /* we only need to fetch 1 tuple */
2441                         sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2442                 }
2443                 else if (subplan->subLinkType == ALL_SUBLINK ||
2444                                  subplan->subLinkType == ANY_SUBLINK)
2445                 {
2446                         /* assume we need 50% of the tuples */
2447                         sp_cost.per_tuple += 0.50 * plan_run_cost;
2448                         /* also charge a cpu_operator_cost per row examined */
2449                         sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2450                 }
2451                 else
2452                 {
2453                         /* assume we need all tuples */
2454                         sp_cost.per_tuple += plan_run_cost;
2455                 }
2456
2457                 /*
2458                  * Also account for subplan's startup cost. If the subplan is
2459                  * uncorrelated or undirect correlated, AND its topmost node is one
2460                  * that materializes its output, assume that we'll only need to pay
2461                  * its startup cost once; otherwise assume we pay the startup cost
2462                  * every time.
2463                  */
2464                 if (subplan->parParam == NIL &&
2465                         ExecMaterializesOutput(nodeTag(plan)))
2466                         sp_cost.startup += plan->startup_cost;
2467                 else
2468                         sp_cost.per_tuple += plan->startup_cost;
2469         }
2470
2471         subplan->startup_cost = sp_cost.startup;
2472         subplan->per_call_cost = sp_cost.per_tuple;
2473 }
2474
2475
2476 /*
2477  * cost_rescan
2478  *              Given a finished Path, estimate the costs of rescanning it after
2479  *              having done so the first time.  For some Path types a rescan is
2480  *              cheaper than an original scan (if no parameters change), and this
2481  *              function embodies knowledge about that.  The default is to return
2482  *              the same costs stored in the Path.      (Note that the cost estimates
2483  *              actually stored in Paths are always for first scans.)
2484  *
2485  * This function is not currently intended to model effects such as rescans
2486  * being cheaper due to disk block caching; what we are concerned with is
2487  * plan types wherein the executor caches results explicitly, or doesn't
2488  * redo startup calculations, etc.
2489  */
2490 static void
2491 cost_rescan(PlannerInfo *root, Path *path,
2492                         Cost *rescan_startup_cost,      /* output parameters */
2493                         Cost *rescan_total_cost)
2494 {
2495         switch (path->pathtype)
2496         {
2497                 case T_FunctionScan:
2498
2499                         /*
2500                          * Currently, nodeFunctionscan.c always executes the function to
2501                          * completion before returning any rows, and caches the results in
2502                          * a tuplestore.  So the function eval cost is all startup cost
2503                          * and isn't paid over again on rescans. However, all run costs
2504                          * will be paid over again.
2505                          */
2506                         *rescan_startup_cost = 0;
2507                         *rescan_total_cost = path->total_cost - path->startup_cost;
2508                         break;
2509                 case T_HashJoin:
2510
2511                         /*
2512                          * Assume that all of the startup cost represents hash table
2513                          * building, which we won't have to do over.
2514                          */
2515                         *rescan_startup_cost = 0;
2516                         *rescan_total_cost = path->total_cost - path->startup_cost;
2517                         break;
2518                 case T_CteScan:
2519                 case T_WorkTableScan:
2520                         {
2521                                 /*
2522                                  * These plan types materialize their final result in a
2523                                  * tuplestore or tuplesort object.      So the rescan cost is only
2524                                  * cpu_tuple_cost per tuple, unless the result is large enough
2525                                  * to spill to disk.
2526                                  */
2527                                 Cost            run_cost = cpu_tuple_cost * path->parent->rows;
2528                                 double          nbytes = relation_byte_size(path->parent->rows,
2529                                                                                                                 path->parent->width);
2530                                 long            work_mem_bytes = work_mem * 1024L;
2531
2532                                 if (nbytes > work_mem_bytes)
2533                                 {
2534                                         /* It will spill, so account for re-read cost */
2535                                         double          npages = ceil(nbytes / BLCKSZ);
2536
2537                                         run_cost += seq_page_cost * npages;
2538                                 }
2539                                 *rescan_startup_cost = 0;
2540                                 *rescan_total_cost = run_cost;
2541                         }
2542                         break;
2543                 case T_Material:
2544                 case T_Sort:
2545                         {
2546                                 /*
2547                                  * These plan types not only materialize their results, but do
2548                                  * not implement qual filtering or projection.  So they are
2549                                  * even cheaper to rescan than the ones above.  We charge only
2550                                  * cpu_operator_cost per tuple.  (Note: keep that in sync with
2551                                  * the run_cost charge in cost_sort, and also see comments in
2552                                  * cost_material before you change it.)
2553                                  */
2554                                 Cost            run_cost = cpu_operator_cost * path->parent->rows;
2555                                 double          nbytes = relation_byte_size(path->parent->rows,
2556                                                                                                                 path->parent->width);
2557                                 long            work_mem_bytes = work_mem * 1024L;
2558
2559                                 if (nbytes > work_mem_bytes)
2560                                 {
2561                                         /* It will spill, so account for re-read cost */
2562                                         double          npages = ceil(nbytes / BLCKSZ);
2563
2564                                         run_cost += seq_page_cost * npages;
2565                                 }
2566                                 *rescan_startup_cost = 0;
2567                                 *rescan_total_cost = run_cost;
2568                         }
2569                         break;
2570                 default:
2571                         *rescan_startup_cost = path->startup_cost;
2572                         *rescan_total_cost = path->total_cost;
2573                         break;
2574         }
2575 }
2576
2577
2578 /*
2579  * cost_qual_eval
2580  *              Estimate the CPU costs of evaluating a WHERE clause.
2581  *              The input can be either an implicitly-ANDed list of boolean
2582  *              expressions, or a list of RestrictInfo nodes.  (The latter is
2583  *              preferred since it allows caching of the results.)
2584  *              The result includes both a one-time (startup) component,
2585  *              and a per-evaluation component.
2586  */
2587 void
2588 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2589 {
2590         cost_qual_eval_context context;
2591         ListCell   *l;
2592
2593         context.root = root;
2594         context.total.startup = 0;
2595         context.total.per_tuple = 0;
2596
2597         /* We don't charge any cost for the implicit ANDing at top level ... */
2598
2599         foreach(l, quals)
2600         {
2601                 Node       *qual = (Node *) lfirst(l);
2602
2603                 cost_qual_eval_walker(qual, &context);
2604         }
2605
2606         *cost = context.total;
2607 }
2608
2609 /*
2610  * cost_qual_eval_node
2611  *              As above, for a single RestrictInfo or expression.
2612  */
2613 void
2614 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2615 {
2616         cost_qual_eval_context context;
2617
2618         context.root = root;
2619         context.total.startup = 0;
2620         context.total.per_tuple = 0;
2621
2622         cost_qual_eval_walker(qual, &context);
2623
2624         *cost = context.total;
2625 }
2626
2627 static bool
2628 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2629 {
2630         if (node == NULL)
2631                 return false;
2632
2633         /*
2634          * RestrictInfo nodes contain an eval_cost field reserved for this
2635          * routine's use, so that it's not necessary to evaluate the qual clause's
2636          * cost more than once.  If the clause's cost hasn't been computed yet,
2637          * the field's startup value will contain -1.
2638          */
2639         if (IsA(node, RestrictInfo))
2640         {
2641                 RestrictInfo *rinfo = (RestrictInfo *) node;
2642
2643                 if (rinfo->eval_cost.startup < 0)
2644                 {
2645                         cost_qual_eval_context locContext;
2646
2647                         locContext.root = context->root;
2648                         locContext.total.startup = 0;
2649                         locContext.total.per_tuple = 0;
2650
2651                         /*
2652                          * For an OR clause, recurse into the marked-up tree so that we
2653                          * set the eval_cost for contained RestrictInfos too.
2654                          */
2655                         if (rinfo->orclause)
2656                                 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2657                         else
2658                                 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2659
2660                         /*
2661                          * If the RestrictInfo is marked pseudoconstant, it will be tested
2662                          * only once, so treat its cost as all startup cost.
2663                          */
2664                         if (rinfo->pseudoconstant)
2665                         {
2666                                 /* count one execution during startup */
2667                                 locContext.total.startup += locContext.total.per_tuple;
2668                                 locContext.total.per_tuple = 0;
2669                         }
2670                         rinfo->eval_cost = locContext.total;
2671                 }
2672                 context->total.startup += rinfo->eval_cost.startup;
2673                 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2674                 /* do NOT recurse into children */
2675                 return false;
2676         }
2677
2678         /*
2679          * For each operator or function node in the given tree, we charge the
2680          * estimated execution cost given by pg_proc.procost (remember to multiply
2681          * this by cpu_operator_cost).
2682          *
2683          * Vars and Consts are charged zero, and so are boolean operators (AND,
2684          * OR, NOT). Simplistic, but a lot better than no model at all.
2685          *
2686          * Should we try to account for the possibility of short-circuit
2687          * evaluation of AND/OR?  Probably *not*, because that would make the
2688          * results depend on the clause ordering, and we are not in any position
2689          * to expect that the current ordering of the clauses is the one that's
2690          * going to end up being used.  The above per-RestrictInfo caching would
2691          * not mix well with trying to re-order clauses anyway.
2692          */
2693         if (IsA(node, FuncExpr))
2694         {
2695                 context->total.per_tuple +=
2696                         get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
2697         }
2698         else if (IsA(node, OpExpr) ||
2699                          IsA(node, DistinctExpr) ||
2700                          IsA(node, NullIfExpr))
2701         {
2702                 /* rely on struct equivalence to treat these all alike */
2703                 set_opfuncid((OpExpr *) node);
2704                 context->total.per_tuple +=
2705                         get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
2706         }
2707         else if (IsA(node, ScalarArrayOpExpr))
2708         {
2709                 /*
2710                  * Estimate that the operator will be applied to about half of the
2711                  * array elements before the answer is determined.
2712                  */
2713                 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2714                 Node       *arraynode = (Node *) lsecond(saop->args);
2715
2716                 set_sa_opfuncid(saop);
2717                 context->total.per_tuple += get_func_cost(saop->opfuncid) *
2718                         cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
2719         }
2720         else if (IsA(node, Aggref) ||
2721                          IsA(node, WindowFunc))
2722         {
2723                 /*
2724                  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
2725                  * ie, zero execution cost in the current model, because they behave
2726                  * essentially like Vars in execQual.c.  We disregard the costs of
2727                  * their input expressions for the same reason.  The actual execution
2728                  * costs of the aggregate/window functions and their arguments have to
2729                  * be factored into plan-node-specific costing of the Agg or WindowAgg
2730                  * plan node.
2731                  */
2732                 return false;                   /* don't recurse into children */
2733         }
2734         else if (IsA(node, CoerceViaIO))
2735         {
2736                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2737                 Oid                     iofunc;
2738                 Oid                     typioparam;
2739                 bool            typisvarlena;
2740
2741                 /* check the result type's input function */
2742                 getTypeInputInfo(iocoerce->resulttype,
2743                                                  &iofunc, &typioparam);
2744                 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2745                 /* check the input type's output function */
2746                 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
2747                                                   &iofunc, &typisvarlena);
2748                 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2749         }
2750         else if (IsA(node, ArrayCoerceExpr))
2751         {
2752                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2753                 Node       *arraynode = (Node *) acoerce->arg;
2754
2755                 if (OidIsValid(acoerce->elemfuncid))
2756                         context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
2757                                 cpu_operator_cost * estimate_array_length(arraynode);
2758         }
2759         else if (IsA(node, RowCompareExpr))
2760         {
2761                 /* Conservatively assume we will check all the columns */
2762                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2763                 ListCell   *lc;
2764
2765                 foreach(lc, rcexpr->opnos)
2766                 {
2767                         Oid                     opid = lfirst_oid(lc);
2768
2769                         context->total.per_tuple += get_func_cost(get_opcode(opid)) *
2770                                 cpu_operator_cost;
2771                 }
2772         }
2773         else if (IsA(node, CurrentOfExpr))
2774         {
2775                 /* Report high cost to prevent selection of anything but TID scan */
2776                 context->total.startup += disable_cost;
2777         }
2778         else if (IsA(node, SubLink))
2779         {
2780                 /* This routine should not be applied to un-planned expressions */
2781                 elog(ERROR, "cannot handle unplanned sub-select");
2782         }
2783         else if (IsA(node, SubPlan))
2784         {
2785                 /*
2786                  * A subplan node in an expression typically indicates that the
2787                  * subplan will be executed on each evaluation, so charge accordingly.
2788                  * (Sub-selects that can be executed as InitPlans have already been
2789                  * removed from the expression.)
2790                  */
2791                 SubPlan    *subplan = (SubPlan *) node;
2792
2793                 context->total.startup += subplan->startup_cost;
2794                 context->total.per_tuple += subplan->per_call_cost;
2795
2796                 /*
2797                  * We don't want to recurse into the testexpr, because it was already
2798                  * counted in the SubPlan node's costs.  So we're done.
2799                  */
2800                 return false;
2801         }
2802         else if (IsA(node, AlternativeSubPlan))
2803         {
2804                 /*
2805                  * Arbitrarily use the first alternative plan for costing.      (We should
2806                  * certainly only include one alternative, and we don't yet have
2807                  * enough information to know which one the executor is most likely to
2808                  * use.)
2809                  */
2810                 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2811
2812                 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
2813                                                                          context);
2814         }
2815
2816         /* recurse into children */
2817         return expression_tree_walker(node, cost_qual_eval_walker,
2818                                                                   (void *) context);
2819 }
2820
2821
2822 /*
2823  * adjust_semi_join
2824  *        Estimate how much of the inner input a SEMI or ANTI join
2825  *        can be expected to scan.
2826  *
2827  * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
2828  * inner rows as soon as it finds a match to the current outer row.
2829  * We should therefore adjust some of the cost components for this effect.
2830  * This function computes some estimates needed for these adjustments.
2831  *
2832  * 'path' is already filled in except for the cost fields
2833  * 'sjinfo' is extra info about the join for selectivity estimation
2834  *
2835  * Returns TRUE if this is a SEMI or ANTI join, FALSE if not.
2836  *
2837  * Output parameters (set only in TRUE-result case):
2838  * *outer_match_frac is set to the fraction of the outer tuples that are
2839  *              expected to have at least one match.
2840  * *match_count is set to the average number of matches expected for
2841  *              outer tuples that have at least one match.
2842  * *indexed_join_quals is set to TRUE if all the joinquals are used as
2843  *              inner index quals, FALSE if not.
2844  *
2845  * indexed_join_quals can be passed as NULL if that information is not
2846  * relevant (it is only useful for the nestloop case).
2847  */
2848 static bool
2849 adjust_semi_join(PlannerInfo *root, JoinPath *path, SpecialJoinInfo *sjinfo,
2850                                  Selectivity *outer_match_frac,
2851                                  Selectivity *match_count,
2852                                  bool *indexed_join_quals)
2853 {
2854         JoinType        jointype = path->jointype;
2855         Selectivity jselec;
2856         Selectivity nselec;
2857         Selectivity avgmatch;
2858         SpecialJoinInfo norm_sjinfo;
2859         List       *joinquals;
2860         ListCell   *l;
2861
2862         /* Fall out if it's not JOIN_SEMI or JOIN_ANTI */
2863         if (jointype != JOIN_SEMI && jointype != JOIN_ANTI)
2864                 return false;
2865
2866         /*
2867          * Note: it's annoying to repeat this selectivity estimation on each call,
2868          * when the joinclause list will be the same for all path pairs
2869          * implementing a given join.  clausesel.c will save us from the worst
2870          * effects of this by caching at the RestrictInfo level; but perhaps it'd
2871          * be worth finding a way to cache the results at a higher level.
2872          */
2873
2874         /*
2875          * In an ANTI join, we must ignore clauses that are "pushed down", since
2876          * those won't affect the match logic.  In a SEMI join, we do not
2877          * distinguish joinquals from "pushed down" quals, so just use the whole
2878          * restrictinfo list.
2879          */
2880         if (jointype == JOIN_ANTI)
2881         {
2882                 joinquals = NIL;
2883                 foreach(l, path->joinrestrictinfo)
2884                 {
2885                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2886
2887                         Assert(IsA(rinfo, RestrictInfo));
2888                         if (!rinfo->is_pushed_down)
2889                                 joinquals = lappend(joinquals, rinfo);
2890                 }
2891         }
2892         else
2893                 joinquals = path->joinrestrictinfo;
2894
2895         /*
2896          * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
2897          */
2898         jselec = clauselist_selectivity(root,
2899                                                                         joinquals,
2900                                                                         0,
2901                                                                         jointype,
2902                                                                         sjinfo);
2903
2904         /*
2905          * Also get the normal inner-join selectivity of the join clauses.
2906          */
2907         norm_sjinfo.type = T_SpecialJoinInfo;
2908         norm_sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2909         norm_sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2910         norm_sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2911         norm_sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2912         norm_sjinfo.jointype = JOIN_INNER;
2913         /* we don't bother trying to make the remaining fields valid */
2914         norm_sjinfo.lhs_strict = false;
2915         norm_sjinfo.delay_upper_joins = false;
2916         norm_sjinfo.join_quals = NIL;
2917
2918         nselec = clauselist_selectivity(root,
2919                                                                         joinquals,
2920                                                                         0,
2921                                                                         JOIN_INNER,
2922                                                                         &norm_sjinfo);
2923
2924         /* Avoid leaking a lot of ListCells */
2925         if (jointype == JOIN_ANTI)
2926                 list_free(joinquals);
2927
2928         /*
2929          * jselec can be interpreted as the fraction of outer-rel rows that have
2930          * any matches (this is true for both SEMI and ANTI cases).  And nselec is
2931          * the fraction of the Cartesian product that matches.  So, the average
2932          * number of matches for each outer-rel row that has at least one match is
2933          * nselec * inner_rows / jselec.
2934          *
2935          * Note: it is correct to use the inner rel's "rows" count here, not
2936          * PATH_ROWS(), even if the inner path under consideration is an inner
2937          * indexscan.  This is because we have included all the join clauses in
2938          * the selectivity estimate, even ones used in an inner indexscan.
2939          */
2940         if (jselec > 0)                         /* protect against zero divide */
2941         {
2942                 avgmatch = nselec * path->innerjoinpath->parent->rows / jselec;
2943                 /* Clamp to sane range */
2944                 avgmatch = Max(1.0, avgmatch);
2945         }
2946         else
2947                 avgmatch = 1.0;
2948
2949         *outer_match_frac = jselec;
2950         *match_count = avgmatch;
2951
2952         /*
2953          * If requested, check whether the inner path uses all the joinquals as
2954          * indexquals.  (If that's true, we can assume that an unmatched outer
2955          * tuple is cheap to process, whereas otherwise it's probably expensive.)
2956          */
2957         if (indexed_join_quals)
2958         {
2959                 if (path->joinrestrictinfo != NIL)
2960                 {
2961                         List       *nrclauses;
2962
2963                         nrclauses = select_nonredundant_join_clauses(root,
2964                                                                                                           path->joinrestrictinfo,
2965                                                                                                                  path->innerjoinpath);
2966                         *indexed_join_quals = (nrclauses == NIL);
2967                 }
2968                 else
2969                 {
2970                         /* a clauseless join does NOT qualify */
2971                         *indexed_join_quals = false;
2972                 }
2973         }
2974
2975         return true;
2976 }
2977
2978
2979 /*
2980  * approx_tuple_count
2981  *              Quick-and-dirty estimation of the number of join rows passing
2982  *              a set of qual conditions.
2983  *
2984  * The quals can be either an implicitly-ANDed list of boolean expressions,
2985  * or a list of RestrictInfo nodes (typically the latter).
2986  *
2987  * We intentionally compute the selectivity under JOIN_INNER rules, even
2988  * if it's some type of outer join.  This is appropriate because we are
2989  * trying to figure out how many tuples pass the initial merge or hash
2990  * join step.
2991  *
2992  * This is quick-and-dirty because we bypass clauselist_selectivity, and
2993  * simply multiply the independent clause selectivities together.  Now
2994  * clauselist_selectivity often can't do any better than that anyhow, but
2995  * for some situations (such as range constraints) it is smarter.  However,
2996  * we can't effectively cache the results of clauselist_selectivity, whereas
2997  * the individual clause selectivities can be and are cached.
2998  *
2999  * Since we are only using the results to estimate how many potential
3000  * output tuples are generated and passed through qpqual checking, it
3001  * seems OK to live with the approximation.
3002  */
3003 static double
3004 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
3005 {
3006         double          tuples;
3007         double          outer_tuples = path->outerjoinpath->parent->rows;
3008         double          inner_tuples = path->innerjoinpath->parent->rows;
3009         SpecialJoinInfo sjinfo;
3010         Selectivity selec = 1.0;
3011         ListCell   *l;
3012
3013         /*
3014          * Make up a SpecialJoinInfo for JOIN_INNER semantics.
3015          */
3016         sjinfo.type = T_SpecialJoinInfo;
3017         sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
3018         sjinfo.min_righthand = path->innerjoinpath->parent->relids;
3019         sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
3020         sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
3021         sjinfo.jointype = JOIN_INNER;
3022         /* we don't bother trying to make the remaining fields valid */
3023         sjinfo.lhs_strict = false;
3024         sjinfo.delay_upper_joins = false;
3025         sjinfo.join_quals = NIL;
3026
3027         /* Get the approximate selectivity */
3028         foreach(l, quals)
3029         {
3030                 Node       *qual = (Node *) lfirst(l);
3031
3032                 /* Note that clause_selectivity will be able to cache its result */
3033                 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
3034         }
3035
3036         /* Apply it to the input relation sizes */
3037         tuples = selec * outer_tuples * inner_tuples;
3038
3039         return clamp_row_est(tuples);
3040 }
3041
3042
3043 /*
3044  * set_baserel_size_estimates
3045  *              Set the size estimates for the given base relation.
3046  *
3047  * The rel's targetlist and restrictinfo list must have been constructed
3048  * already, and rel->tuples must be set.
3049  *
3050  * We set the following fields of the rel node:
3051  *      rows: the estimated number of output tuples (after applying
3052  *                restriction clauses).
3053  *      width: the estimated average output tuple width in bytes.
3054  *      baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
3055  */
3056 void
3057 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3058 {
3059         double          nrows;
3060
3061         /* Should only be applied to base relations */
3062         Assert(rel->relid > 0);
3063
3064         nrows = rel->tuples *
3065                 clauselist_selectivity(root,
3066                                                            rel->baserestrictinfo,
3067                                                            0,
3068                                                            JOIN_INNER,
3069                                                            NULL);
3070
3071         rel->rows = clamp_row_est(nrows);
3072
3073         cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3074
3075         set_rel_width(root, rel);
3076 }
3077
3078 /*
3079  * set_joinrel_size_estimates
3080  *              Set the size estimates for the given join relation.
3081  *
3082  * The rel's targetlist must have been constructed already, and a
3083  * restriction clause list that matches the given component rels must
3084  * be provided.
3085  *
3086  * Since there is more than one way to make a joinrel for more than two
3087  * base relations, the results we get here could depend on which component
3088  * rel pair is provided.  In theory we should get the same answers no matter
3089  * which pair is provided; in practice, since the selectivity estimation
3090  * routines don't handle all cases equally well, we might not.  But there's
3091  * not much to be done about it.  (Would it make sense to repeat the
3092  * calculations for each pair of input rels that's encountered, and somehow
3093  * average the results?  Probably way more trouble than it's worth.)
3094  *
3095  * We set only the rows field here.  The width field was already set by
3096  * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3097  */
3098 void
3099 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3100                                                    RelOptInfo *outer_rel,
3101                                                    RelOptInfo *inner_rel,
3102                                                    SpecialJoinInfo *sjinfo,
3103                                                    List *restrictlist)
3104 {
3105         JoinType        jointype = sjinfo->jointype;
3106         Selectivity jselec;
3107         Selectivity pselec;
3108         double          nrows;
3109
3110         /*
3111          * Compute joinclause selectivity.      Note that we are only considering
3112          * clauses that become restriction clauses at this join level; we are not
3113          * double-counting them because they were not considered in estimating the
3114          * sizes of the component rels.
3115          *
3116          * For an outer join, we have to distinguish the selectivity of the join's
3117          * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3118          * down".  For inner joins we just count them all as joinclauses.
3119          */
3120         if (IS_OUTER_JOIN(jointype))
3121         {
3122                 List       *joinquals = NIL;
3123                 List       *pushedquals = NIL;
3124                 ListCell   *l;
3125
3126                 /* Grovel through the clauses to separate into two lists */
3127                 foreach(l, restrictlist)
3128                 {
3129                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3130
3131                         Assert(IsA(rinfo, RestrictInfo));
3132                         if (rinfo->is_pushed_down)
3133                                 pushedquals = lappend(pushedquals, rinfo);
3134                         else
3135                                 joinquals = lappend(joinquals, rinfo);
3136                 }
3137
3138                 /* Get the separate selectivities */
3139                 jselec = clauselist_selectivity(root,
3140                                                                                 joinquals,
3141                                                                                 0,
3142                                                                                 jointype,
3143                                                                                 sjinfo);
3144                 pselec = clauselist_selectivity(root,
3145                                                                                 pushedquals,
3146                                                                                 0,
3147                                                                                 jointype,
3148                                                                                 sjinfo);
3149
3150                 /* Avoid leaking a lot of ListCells */
3151                 list_free(joinquals);
3152                 list_free(pushedquals);
3153         }
3154         else
3155         {
3156                 jselec = clauselist_selectivity(root,
3157                                                                                 restrictlist,
3158                                                                                 0,
3159                                                                                 jointype,
3160                                                                                 sjinfo);
3161                 pselec = 0.0;                   /* not used, keep compiler quiet */
3162         }
3163
3164         /*
3165          * Basically, we multiply size of Cartesian product by selectivity.
3166          *
3167          * If we are doing an outer join, take that into account: the joinqual
3168          * selectivity has to be clamped using the knowledge that the output must
3169          * be at least as large as the non-nullable input.      However, any
3170          * pushed-down quals are applied after the outer join, so their
3171          * selectivity applies fully.
3172          *
3173          * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3174          * of LHS rows that have matches, and we apply that straightforwardly.
3175          */
3176         switch (jointype)
3177         {
3178                 case JOIN_INNER:
3179                         nrows = outer_rel->rows * inner_rel->rows * jselec;
3180                         break;
3181                 case JOIN_LEFT:
3182                         nrows = outer_rel->rows * inner_rel->rows * jselec;
3183                         if (nrows < outer_rel->rows)
3184                                 nrows = outer_rel->rows;
3185                         nrows *= pselec;
3186                         break;
3187                 case JOIN_FULL:
3188                         nrows = outer_rel->rows * inner_rel->rows * jselec;
3189                         if (nrows < outer_rel->rows)
3190                                 nrows = outer_rel->rows;
3191                         if (nrows < inner_rel->rows)
3192                                 nrows = inner_rel->rows;
3193                         nrows *= pselec;
3194                         break;
3195                 case JOIN_SEMI:
3196                         nrows = outer_rel->rows * jselec;
3197                         /* pselec not used */
3198                         break;
3199                 case JOIN_ANTI:
3200                         nrows = outer_rel->rows * (1.0 - jselec);
3201                         nrows *= pselec;
3202                         break;
3203                 default:
3204                         /* other values not expected here */
3205                         elog(ERROR, "unrecognized join type: %d", (int) jointype);
3206                         nrows = 0;                      /* keep compiler quiet */
3207                         break;
3208         }
3209
3210         rel->rows = clamp_row_est(nrows);
3211 }
3212
3213 /*
3214  * set_subquery_size_estimates
3215  *              Set the size estimates for a base relation that is a subquery.
3216  *
3217  * The rel's targetlist and restrictinfo list must have been constructed
3218  * already, and the plan for the subquery must have been completed.
3219  * We look at the subquery's plan and PlannerInfo to extract data.
3220  *
3221  * We set the same fields as set_baserel_size_estimates.
3222  */
3223 void
3224 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3225                                                         PlannerInfo *subroot)
3226 {
3227         RangeTblEntry *rte;
3228         ListCell   *lc;
3229
3230         /* Should only be applied to base relations that are subqueries */
3231         Assert(rel->relid > 0);
3232         rte = planner_rt_fetch(rel->relid, root);
3233         Assert(rte->rtekind == RTE_SUBQUERY);
3234
3235         /* Copy raw number of output rows from subplan */
3236         rel->tuples = rel->subplan->plan_rows;
3237
3238         /*
3239          * Compute per-output-column width estimates by examining the subquery's
3240          * targetlist.  For any output that is a plain Var, get the width estimate
3241          * that was made while planning the subquery.  Otherwise, fall back on a
3242          * datatype-based estimate.
3243          */
3244         foreach(lc, subroot->parse->targetList)
3245         {
3246                 TargetEntry *te = (TargetEntry *) lfirst(lc);
3247                 Node       *texpr = (Node *) te->expr;
3248                 int32           item_width;
3249
3250                 Assert(IsA(te, TargetEntry));
3251                 /* junk columns aren't visible to upper query */
3252                 if (te->resjunk)
3253                         continue;
3254
3255                 /*
3256                  * XXX This currently doesn't work for subqueries containing set
3257                  * operations, because the Vars in their tlists are bogus references
3258                  * to the first leaf subquery, which wouldn't give the right answer
3259                  * even if we could still get to its PlannerInfo.  So fall back on
3260                  * datatype in that case.
3261                  */
3262                 if (IsA(texpr, Var) &&
3263                         subroot->parse->setOperations == NULL)
3264                 {
3265                         Var                *var = (Var *) texpr;
3266                         RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3267
3268                         item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3269                 }
3270                 else
3271                 {
3272                         item_width = get_typavgwidth(exprType(texpr), exprTypmod(texpr));
3273                 }
3274                 Assert(item_width > 0);
3275                 Assert(te->resno >= rel->min_attr && te->resno <= rel->max_attr);
3276                 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3277         }
3278
3279         /* Now estimate number of output rows, etc */
3280         set_baserel_size_estimates(root, rel);
3281 }
3282
3283 /*
3284  * set_function_size_estimates
3285  *              Set the size estimates for a base relation that is a function call.
3286  *
3287  * The rel's targetlist and restrictinfo list must have been constructed
3288  * already.
3289  *
3290  * We set the same fields as set_baserel_size_estimates.
3291  */
3292 void
3293 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3294 {
3295         RangeTblEntry *rte;
3296
3297         /* Should only be applied to base relations that are functions */
3298         Assert(rel->relid > 0);
3299         rte = planner_rt_fetch(rel->relid, root);
3300         Assert(rte->rtekind == RTE_FUNCTION);
3301
3302         /* Estimate number of rows the function itself will return */
3303         rel->tuples = clamp_row_est(expression_returns_set_rows(rte->funcexpr));
3304
3305         /* Now estimate number of output rows, etc */
3306         set_baserel_size_estimates(root, rel);
3307 }
3308
3309 /*
3310  * set_values_size_estimates
3311  *              Set the size estimates for a base relation that is a values list.
3312  *
3313  * The rel's targetlist and restrictinfo list must have been constructed
3314  * already.
3315  *
3316  * We set the same fields as set_baserel_size_estimates.
3317  */
3318 void
3319 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3320 {
3321         RangeTblEntry *rte;
3322
3323         /* Should only be applied to base relations that are values lists */
3324         Assert(rel->relid > 0);
3325         rte = planner_rt_fetch(rel->relid, root);
3326         Assert(rte->rtekind == RTE_VALUES);
3327
3328         /*
3329          * Estimate number of rows the values list will return. We know this
3330          * precisely based on the list length (well, barring set-returning
3331          * functions in list items, but that's a refinement not catered for
3332          * anywhere else either).
3333          */
3334         rel->tuples = list_length(rte->values_lists);
3335
3336         /* Now estimate number of output rows, etc */
3337         set_baserel_size_estimates(root, rel);
3338 }
3339
3340 /*
3341  * set_cte_size_estimates
3342  *              Set the size estimates for a base relation that is a CTE reference.
3343  *
3344  * The rel's targetlist and restrictinfo list must have been constructed
3345  * already, and we need the completed plan for the CTE (if a regular CTE)
3346  * or the non-recursive term (if a self-reference).
3347  *
3348  * We set the same fields as set_baserel_size_estimates.
3349  */
3350 void
3351 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3352 {
3353         RangeTblEntry *rte;
3354
3355         /* Should only be applied to base relations that are CTE references */
3356         Assert(rel->relid > 0);
3357         rte = planner_rt_fetch(rel->relid, root);
3358         Assert(rte->rtekind == RTE_CTE);
3359
3360         if (rte->self_reference)
3361         {
3362                 /*
3363                  * In a self-reference, arbitrarily assume the average worktable size
3364                  * is about 10 times the nonrecursive term's size.
3365                  */
3366                 rel->tuples = 10 * cteplan->plan_rows;
3367         }
3368         else
3369         {
3370                 /* Otherwise just believe the CTE plan's output estimate */
3371                 rel->tuples = cteplan->plan_rows;
3372         }
3373
3374         /* Now estimate number of output rows, etc */
3375         set_baserel_size_estimates(root, rel);
3376 }
3377
3378 /*
3379  * set_foreign_size_estimates
3380  *              Set the size estimates for a base relation that is a foreign table.
3381  *
3382  * There is not a whole lot that we can do here; the foreign-data wrapper
3383  * is responsible for producing useful estimates.  We can do a decent job
3384  * of estimating baserestrictcost, so we set that, and we also set up width
3385  * using what will be purely datatype-driven estimates from the targetlist.
3386  * There is no way to do anything sane with the rows value, so we just put
3387  * a default estimate and hope that the wrapper can improve on it.      The
3388  * wrapper's PlanForeignScan function will be called momentarily.
3389  *
3390  * The rel's targetlist and restrictinfo list must have been constructed
3391  * already.
3392  */
3393 void
3394 set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3395 {
3396         /* Should only be applied to base relations */
3397         Assert(rel->relid > 0);
3398
3399         rel->rows = 1000;                       /* entirely bogus default estimate */
3400
3401         cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3402
3403         set_rel_width(root, rel);
3404 }
3405
3406
3407 /*
3408  * set_rel_width
3409  *              Set the estimated output width of a base relation.
3410  *
3411  * The estimated output width is the sum of the per-attribute width estimates
3412  * for the actually-referenced columns, plus any PHVs or other expressions
3413  * that have to be calculated at this relation.  This is the amount of data
3414  * we'd need to pass upwards in case of a sort, hash, etc.
3415  *
3416  * NB: this works best on plain relations because it prefers to look at
3417  * real Vars.  For subqueries, set_subquery_size_estimates will already have
3418  * copied up whatever per-column estimates were made within the subquery,
3419  * and for other types of rels there isn't much we can do anyway.  We fall
3420  * back on (fairly stupid) datatype-based width estimates if we can't get
3421  * any better number.
3422  *
3423  * The per-attribute width estimates are cached for possible re-use while
3424  * building join relations.
3425  */
3426 static void
3427 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3428 {
3429         Oid                     reloid = planner_rt_fetch(rel->relid, root)->relid;
3430         int32           tuple_width = 0;
3431         bool            have_wholerow_var = false;
3432         ListCell   *lc;
3433
3434         foreach(lc, rel->reltargetlist)
3435         {
3436                 Node       *node = (Node *) lfirst(lc);
3437
3438                 if (IsA(node, Var))
3439                 {
3440                         Var                *var = (Var *) node;
3441                         int                     ndx;
3442                         int32           item_width;
3443
3444                         Assert(var->varno == rel->relid);
3445                         Assert(var->varattno >= rel->min_attr);
3446                         Assert(var->varattno <= rel->max_attr);
3447
3448                         ndx = var->varattno - rel->min_attr;
3449
3450                         /*
3451                          * If it's a whole-row Var, we'll deal with it below after we have
3452                          * already cached as many attr widths as possible.
3453                          */
3454                         if (var->varattno == 0)
3455                         {
3456                                 have_wholerow_var = true;
3457                                 continue;
3458                         }
3459
3460                         /*
3461                          * The width may have been cached already (especially if it's a
3462                          * subquery), so don't duplicate effort.
3463                          */
3464                         if (rel->attr_widths[ndx] > 0)
3465                         {
3466                                 tuple_width += rel->attr_widths[ndx];
3467                                 continue;
3468                         }
3469
3470                         /* Try to get column width from statistics */
3471                         if (reloid != InvalidOid && var->varattno > 0)
3472                         {
3473                                 item_width = get_attavgwidth(reloid, var->varattno);
3474                                 if (item_width > 0)
3475                                 {
3476                                         rel->attr_widths[ndx] = item_width;
3477                                         tuple_width += item_width;
3478                                         continue;
3479                                 }
3480                         }
3481
3482                         /*
3483                          * Not a plain relation, or can't find statistics for it. Estimate
3484                          * using just the type info.
3485                          */
3486                         item_width = get_typavgwidth(var->vartype, var->vartypmod);
3487                         Assert(item_width > 0);
3488                         rel->attr_widths[ndx] = item_width;
3489                         tuple_width += item_width;
3490                 }
3491                 else if (IsA(node, PlaceHolderVar))
3492                 {
3493                         PlaceHolderVar *phv = (PlaceHolderVar *) node;
3494                         PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
3495
3496                         tuple_width += phinfo->ph_width;
3497                 }
3498                 else
3499                 {
3500                         /*
3501                          * We could be looking at an expression pulled up from a subquery,
3502                          * or a ROW() representing a whole-row child Var, etc.  Do what we
3503                          * can using the expression type information.
3504                          */
3505                         int32           item_width;
3506
3507                         item_width = get_typavgwidth(exprType(node), exprTypmod(node));
3508                         Assert(item_width > 0);
3509                         tuple_width += item_width;
3510                 }
3511         }
3512
3513         /*
3514          * If we have a whole-row reference, estimate its width as the sum of
3515          * per-column widths plus sizeof(HeapTupleHeaderData).
3516          */
3517         if (have_wholerow_var)
3518         {
3519                 int32           wholerow_width = sizeof(HeapTupleHeaderData);
3520
3521                 if (reloid != InvalidOid)
3522                 {
3523                         /* Real relation, so estimate true tuple width */
3524                         wholerow_width += get_relation_data_width(reloid,
3525                                                                                    rel->attr_widths - rel->min_attr);
3526                 }
3527                 else
3528                 {
3529                         /* Do what we can with info for a phony rel */
3530                         AttrNumber      i;
3531
3532                         for (i = 1; i <= rel->max_attr; i++)
3533                                 wholerow_width += rel->attr_widths[i - rel->min_attr];
3534                 }
3535
3536                 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
3537
3538                 /*
3539                  * Include the whole-row Var as part of the output tuple.  Yes, that
3540                  * really is what happens at runtime.
3541                  */
3542                 tuple_width += wholerow_width;
3543         }
3544
3545         Assert(tuple_width >= 0);
3546         rel->width = tuple_width;
3547 }
3548
3549 /*
3550  * relation_byte_size
3551  *        Estimate the storage space in bytes for a given number of tuples
3552  *        of a given width (size in bytes).
3553  */
3554 static double
3555 relation_byte_size(double tuples, int width)
3556 {
3557         return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
3558 }
3559
3560 /*
3561  * page_size
3562  *        Returns an estimate of the number of pages covered by a given
3563  *        number of tuples of a given width (size in bytes).
3564  */
3565 static double
3566 page_size(double tuples, int width)
3567 {
3568         return ceil(relation_byte_size(tuples, width) / BLCKSZ);
3569 }