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