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