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