PostgreSQL Source Code  git master
costsize.c
Go to the documentation of this file.
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  * parallel_tuple_cost Cost of CPU time to pass a tuple from worker to leader backend
15  * parallel_setup_cost Cost of setting up shared memory for parallelism
16  *
17  * We expect that the kernel will typically do some amount of read-ahead
18  * optimization; this in conjunction with seek costs means that seq_page_cost
19  * is normally considerably less than random_page_cost. (However, if the
20  * database is fully cached in RAM, it is reasonable to set them equal.)
21  *
22  * We also use a rough estimate "effective_cache_size" of the number of
23  * disk pages in Postgres + OS-level disk cache. (We can't simply use
24  * NBuffers for this purpose because that would ignore the effects of
25  * the kernel's disk cache.)
26  *
27  * Obviously, taking constants for these values is an oversimplification,
28  * but it's tough enough to get any useful estimates even at this level of
29  * detail. Note that all of these parameters are user-settable, in case
30  * the default values are drastically off for a particular platform.
31  *
32  * seq_page_cost and random_page_cost can also be overridden for an individual
33  * tablespace, in case some data is on a fast disk and other data is on a slow
34  * disk. Per-tablespace overrides never apply to temporary work files such as
35  * an external sort or a materialize node that overflows work_mem.
36  *
37  * We compute two separate costs for each path:
38  * total_cost: total estimated cost to fetch all tuples
39  * startup_cost: cost that is expended before first tuple is fetched
40  * In some scenarios, such as when there is a LIMIT or we are implementing
41  * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
42  * path's result. A caller can estimate the cost of fetching a partial
43  * result by interpolating between startup_cost and total_cost. In detail:
44  * actual_cost = startup_cost +
45  * (total_cost - startup_cost) * tuples_to_fetch / path->rows;
46  * Note that a base relation's rows count (and, by extension, plan_rows for
47  * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
48  * that this equation works properly. (Note: while path->rows is never zero
49  * for ordinary relations, it is zero for paths for provably-empty relations,
50  * so beware of division-by-zero.) The LIMIT is applied as a top-level
51  * plan node.
52  *
53  * For largely historical reasons, most of the routines in this module use
54  * the passed result Path only to store their results (rows, startup_cost and
55  * total_cost) into. All the input data they need is passed as separate
56  * parameters, even though much of it could be extracted from the Path.
57  * An exception is made for the cost_XXXjoin() routines, which expect all
58  * the other fields of the passed XXXPath to be filled in, and similarly
59  * cost_index() assumes the passed IndexPath is valid except for its output
60  * values.
61  *
62  *
63  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
64  * Portions Copyright (c) 1994, Regents of the University of California
65  *
66  * IDENTIFICATION
67  * src/backend/optimizer/path/costsize.c
68  *
69  *-------------------------------------------------------------------------
70  */
71 
72 #include "postgres.h"
73 
74 #include <limits.h>
75 #include <math.h>
76 
77 #include "access/amapi.h"
78 #include "access/htup_details.h"
79 #include "access/tsmapi.h"
80 #include "executor/executor.h"
81 #include "executor/nodeAgg.h"
82 #include "executor/nodeHash.h"
83 #include "executor/nodeMemoize.h"
84 #include "miscadmin.h"
85 #include "nodes/makefuncs.h"
86 #include "nodes/nodeFuncs.h"
87 #include "optimizer/clauses.h"
88 #include "optimizer/cost.h"
89 #include "optimizer/optimizer.h"
90 #include "optimizer/pathnode.h"
91 #include "optimizer/paths.h"
92 #include "optimizer/placeholder.h"
93 #include "optimizer/plancat.h"
94 #include "optimizer/planmain.h"
95 #include "optimizer/restrictinfo.h"
96 #include "parser/parsetree.h"
97 #include "utils/lsyscache.h"
98 #include "utils/selfuncs.h"
99 #include "utils/spccache.h"
100 #include "utils/tuplesort.h"
101 
102 
103 #define LOG2(x) (log(x) / 0.693147180559945)
104 
105 /*
106  * Append and MergeAppend nodes are less expensive than some other operations
107  * which use cpu_tuple_cost; instead of adding a separate GUC, estimate the
108  * per-tuple cost as cpu_tuple_cost multiplied by this value.
109  */
110 #define APPEND_CPU_COST_MULTIPLIER 0.5
111 
112 /*
113  * Maximum value for row estimates. We cap row estimates to this to help
114  * ensure that costs based on these estimates remain within the range of what
115  * double can represent. add_path() wouldn't act sanely given infinite or NaN
116  * cost values.
117  */
118 #define MAXIMUM_ROWCOUNT 1e100
119 
128 
130 
132 
134 
135 bool enable_seqscan = true;
136 bool enable_indexscan = true;
138 bool enable_bitmapscan = true;
139 bool enable_tidscan = true;
140 bool enable_sort = true;
142 bool enable_hashagg = true;
143 bool enable_nestloop = true;
144 bool enable_material = true;
145 bool enable_memoize = true;
146 bool enable_mergejoin = true;
147 bool enable_hashjoin = true;
148 bool enable_gathermerge = true;
155 
156 typedef struct
157 {
161 
162 static List *extract_nonindex_conditions(List *qual_clauses, List *indexclauses);
164  RestrictInfo *rinfo,
165  PathKey *pathkey);
166 static void cost_rescan(PlannerInfo *root, Path *path,
167  Cost *rescan_startup_cost, Cost *rescan_total_cost);
168 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
169 static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
170  ParamPathInfo *param_info,
171  QualCost *qpqual_cost);
172 static bool has_indexed_join_quals(NestPath *path);
173 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
174  List *quals);
175 static double calc_joinrel_size_estimate(PlannerInfo *root,
176  RelOptInfo *joinrel,
177  RelOptInfo *outer_rel,
178  RelOptInfo *inner_rel,
179  double outer_rows,
180  double inner_rows,
181  SpecialJoinInfo *sjinfo,
182  List *restrictlist);
184  Relids outer_relids,
185  Relids inner_relids,
186  SpecialJoinInfo *sjinfo,
187  List **restrictlist);
188 static Cost append_nonpartial_cost(List *subpaths, int numpaths,
189  int parallel_workers);
190 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
191 static double relation_byte_size(double tuples, int width);
192 static double page_size(double tuples, int width);
193 static double get_parallel_divisor(Path *path);
194 
195 
196 /*
197  * clamp_row_est
198  * Force a row-count estimate to a sane value.
199  */
200 double
201 clamp_row_est(double nrows)
202 {
203  /*
204  * Avoid infinite and NaN row estimates. Costs derived from such values
205  * are going to be useless. Also force the estimate to be at least one
206  * row, to make explain output look better and to avoid possible
207  * divide-by-zero when interpolating costs. Make it an integer, too.
208  */
209  if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
210  nrows = MAXIMUM_ROWCOUNT;
211  else if (nrows <= 1.0)
212  nrows = 1.0;
213  else
214  nrows = rint(nrows);
215 
216  return nrows;
217 }
218 
219 /*
220  * clamp_cardinality_to_long
221  * Cast a Cardinality value to a sane long value.
222  */
223 long
225 {
226  /*
227  * Just for paranoia's sake, ensure we do something sane with negative or
228  * NaN values.
229  */
230  if (isnan(x))
231  return LONG_MAX;
232  if (x <= 0)
233  return 0;
234 
235  /*
236  * If "long" is 64 bits, then LONG_MAX cannot be represented exactly as a
237  * double. Casting it to double and back may well result in overflow due
238  * to rounding, so avoid doing that. We trust that any double value that
239  * compares strictly less than "(double) LONG_MAX" will cast to a
240  * representable "long" value.
241  */
242  return (x < (double) LONG_MAX) ? (long) x : LONG_MAX;
243 }
244 
245 
246 /*
247  * cost_seqscan
248  * Determines and returns the cost of scanning a relation sequentially.
249  *
250  * 'baserel' is the relation to be scanned
251  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
252  */
253 void
255  RelOptInfo *baserel, ParamPathInfo *param_info)
256 {
257  Cost startup_cost = 0;
258  Cost cpu_run_cost;
259  Cost disk_run_cost;
260  double spc_seq_page_cost;
261  QualCost qpqual_cost;
262  Cost cpu_per_tuple;
263 
264  /* Should only be applied to base relations */
265  Assert(baserel->relid > 0);
266  Assert(baserel->rtekind == RTE_RELATION);
267 
268  /* Mark the path with the correct row estimate */
269  if (param_info)
270  path->rows = param_info->ppi_rows;
271  else
272  path->rows = baserel->rows;
273 
274  if (!enable_seqscan)
275  startup_cost += disable_cost;
276 
277  /* fetch estimated page cost for tablespace containing table */
279  NULL,
280  &spc_seq_page_cost);
281 
282  /*
283  * disk costs
284  */
285  disk_run_cost = spc_seq_page_cost * baserel->pages;
286 
287  /* CPU costs */
288  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
289 
290  startup_cost += qpqual_cost.startup;
291  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
292  cpu_run_cost = cpu_per_tuple * baserel->tuples;
293  /* tlist eval costs are paid per output row, not per tuple scanned */
294  startup_cost += path->pathtarget->cost.startup;
295  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
296 
297  /* Adjust costing for parallelism, if used. */
298  if (path->parallel_workers > 0)
299  {
300  double parallel_divisor = get_parallel_divisor(path);
301 
302  /* The CPU cost is divided among all the workers. */
303  cpu_run_cost /= parallel_divisor;
304 
305  /*
306  * It may be possible to amortize some of the I/O cost, but probably
307  * not very much, because most operating systems already do aggressive
308  * prefetching. For now, we assume that the disk run cost can't be
309  * amortized at all.
310  */
311 
312  /*
313  * In the case of a parallel plan, the row count needs to represent
314  * the number of tuples processed per worker.
315  */
316  path->rows = clamp_row_est(path->rows / parallel_divisor);
317  }
318 
319  path->startup_cost = startup_cost;
320  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
321 }
322 
323 /*
324  * cost_samplescan
325  * Determines and returns the cost of scanning a relation using sampling.
326  *
327  * 'baserel' is the relation to be scanned
328  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
329  */
330 void
332  RelOptInfo *baserel, ParamPathInfo *param_info)
333 {
334  Cost startup_cost = 0;
335  Cost run_cost = 0;
336  RangeTblEntry *rte;
337  TableSampleClause *tsc;
338  TsmRoutine *tsm;
339  double spc_seq_page_cost,
340  spc_random_page_cost,
341  spc_page_cost;
342  QualCost qpqual_cost;
343  Cost cpu_per_tuple;
344 
345  /* Should only be applied to base relations with tablesample clauses */
346  Assert(baserel->relid > 0);
347  rte = planner_rt_fetch(baserel->relid, root);
348  Assert(rte->rtekind == RTE_RELATION);
349  tsc = rte->tablesample;
350  Assert(tsc != NULL);
351  tsm = GetTsmRoutine(tsc->tsmhandler);
352 
353  /* Mark the path with the correct row estimate */
354  if (param_info)
355  path->rows = param_info->ppi_rows;
356  else
357  path->rows = baserel->rows;
358 
359  /* fetch estimated page cost for tablespace containing table */
361  &spc_random_page_cost,
362  &spc_seq_page_cost);
363 
364  /* if NextSampleBlock is used, assume random access, else sequential */
365  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
366  spc_random_page_cost : spc_seq_page_cost;
367 
368  /*
369  * disk costs (recall that baserel->pages has already been set to the
370  * number of pages the sampling method will visit)
371  */
372  run_cost += spc_page_cost * baserel->pages;
373 
374  /*
375  * CPU costs (recall that baserel->tuples has already been set to the
376  * number of tuples the sampling method will select). Note that we ignore
377  * execution cost of the TABLESAMPLE parameter expressions; they will be
378  * evaluated only once per scan, and in most usages they'll likely be
379  * simple constants anyway. We also don't charge anything for the
380  * calculations the sampling method might do internally.
381  */
382  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
383 
384  startup_cost += qpqual_cost.startup;
385  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
386  run_cost += cpu_per_tuple * baserel->tuples;
387  /* tlist eval costs are paid per output row, not per tuple scanned */
388  startup_cost += path->pathtarget->cost.startup;
389  run_cost += path->pathtarget->cost.per_tuple * path->rows;
390 
391  path->startup_cost = startup_cost;
392  path->total_cost = startup_cost + run_cost;
393 }
394 
395 /*
396  * cost_gather
397  * Determines and returns the cost of gather path.
398  *
399  * 'rel' is the relation to be operated upon
400  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
401  * 'rows' may be used to point to a row estimate; if non-NULL, it overrides
402  * both 'rel' and 'param_info'. This is useful when the path doesn't exactly
403  * correspond to any particular RelOptInfo.
404  */
405 void
407  RelOptInfo *rel, ParamPathInfo *param_info,
408  double *rows)
409 {
410  Cost startup_cost = 0;
411  Cost run_cost = 0;
412 
413  /* Mark the path with the correct row estimate */
414  if (rows)
415  path->path.rows = *rows;
416  else if (param_info)
417  path->path.rows = param_info->ppi_rows;
418  else
419  path->path.rows = rel->rows;
420 
421  startup_cost = path->subpath->startup_cost;
422 
423  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
424 
425  /* Parallel setup and communication cost. */
426  startup_cost += parallel_setup_cost;
427  run_cost += parallel_tuple_cost * path->path.rows;
428 
429  path->path.startup_cost = startup_cost;
430  path->path.total_cost = (startup_cost + run_cost);
431 }
432 
433 /*
434  * cost_gather_merge
435  * Determines and returns the cost of gather merge path.
436  *
437  * GatherMerge merges several pre-sorted input streams, using a heap that at
438  * any given instant holds the next tuple from each stream. If there are N
439  * streams, we need about N*log2(N) tuple comparisons to construct the heap at
440  * startup, and then for each output tuple, about log2(N) comparisons to
441  * replace the top heap entry with the next tuple from the same stream.
442  */
443 void
445  RelOptInfo *rel, ParamPathInfo *param_info,
446  Cost input_startup_cost, Cost input_total_cost,
447  double *rows)
448 {
449  Cost startup_cost = 0;
450  Cost run_cost = 0;
451  Cost comparison_cost;
452  double N;
453  double logN;
454 
455  /* Mark the path with the correct row estimate */
456  if (rows)
457  path->path.rows = *rows;
458  else if (param_info)
459  path->path.rows = param_info->ppi_rows;
460  else
461  path->path.rows = rel->rows;
462 
463  if (!enable_gathermerge)
464  startup_cost += disable_cost;
465 
466  /*
467  * Add one to the number of workers to account for the leader. This might
468  * be overgenerous since the leader will do less work than other workers
469  * in typical cases, but we'll go with it for now.
470  */
471  Assert(path->num_workers > 0);
472  N = (double) path->num_workers + 1;
473  logN = LOG2(N);
474 
475  /* Assumed cost per tuple comparison */
476  comparison_cost = 2.0 * cpu_operator_cost;
477 
478  /* Heap creation cost */
479  startup_cost += comparison_cost * N * logN;
480 
481  /* Per-tuple heap maintenance cost */
482  run_cost += path->path.rows * comparison_cost * logN;
483 
484  /* small cost for heap management, like cost_merge_append */
485  run_cost += cpu_operator_cost * path->path.rows;
486 
487  /*
488  * Parallel setup and communication cost. Since Gather Merge, unlike
489  * Gather, requires us to block until a tuple is available from every
490  * worker, we bump the IPC cost up a little bit as compared with Gather.
491  * For lack of a better idea, charge an extra 5%.
492  */
493  startup_cost += parallel_setup_cost;
494  run_cost += parallel_tuple_cost * path->path.rows * 1.05;
495 
496  path->path.startup_cost = startup_cost + input_startup_cost;
497  path->path.total_cost = (startup_cost + run_cost + input_total_cost);
498 }
499 
500 /*
501  * cost_index
502  * Determines and returns the cost of scanning a relation using an index.
503  *
504  * 'path' describes the indexscan under consideration, and is complete
505  * except for the fields to be set by this routine
506  * 'loop_count' is the number of repetitions of the indexscan to factor into
507  * estimates of caching behavior
508  *
509  * In addition to rows, startup_cost and total_cost, cost_index() sets the
510  * path's indextotalcost and indexselectivity fields. These values will be
511  * needed if the IndexPath is used in a BitmapIndexScan.
512  *
513  * NOTE: path->indexquals must contain only clauses usable as index
514  * restrictions. Any additional quals evaluated as qpquals may reduce the
515  * number of returned tuples, but they won't reduce the number of tuples
516  * we have to fetch from the table, so they don't reduce the scan cost.
517  */
518 void
519 cost_index(IndexPath *path, PlannerInfo *root, double loop_count,
520  bool partial_path)
521 {
522  IndexOptInfo *index = path->indexinfo;
523  RelOptInfo *baserel = index->rel;
524  bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
525  amcostestimate_function amcostestimate;
526  List *qpquals;
527  Cost startup_cost = 0;
528  Cost run_cost = 0;
529  Cost cpu_run_cost = 0;
530  Cost indexStartupCost;
531  Cost indexTotalCost;
532  Selectivity indexSelectivity;
533  double indexCorrelation,
534  csquared;
535  double spc_seq_page_cost,
536  spc_random_page_cost;
537  Cost min_IO_cost,
538  max_IO_cost;
539  QualCost qpqual_cost;
540  Cost cpu_per_tuple;
541  double tuples_fetched;
542  double pages_fetched;
543  double rand_heap_pages;
544  double index_pages;
545 
546  /* Should only be applied to base relations */
547  Assert(IsA(baserel, RelOptInfo) &&
549  Assert(baserel->relid > 0);
550  Assert(baserel->rtekind == RTE_RELATION);
551 
552  /*
553  * Mark the path with the correct row estimate, and identify which quals
554  * will need to be enforced as qpquals. We need not check any quals that
555  * are implied by the index's predicate, so we can use indrestrictinfo not
556  * baserestrictinfo as the list of relevant restriction clauses for the
557  * rel.
558  */
559  if (path->path.param_info)
560  {
561  path->path.rows = path->path.param_info->ppi_rows;
562  /* qpquals come from the rel's restriction clauses and ppi_clauses */
564  path->indexclauses),
565  extract_nonindex_conditions(path->path.param_info->ppi_clauses,
566  path->indexclauses));
567  }
568  else
569  {
570  path->path.rows = baserel->rows;
571  /* qpquals come from just the rel's restriction clauses */
573  path->indexclauses);
574  }
575 
576  if (!enable_indexscan)
577  startup_cost += disable_cost;
578  /* we don't need to check enable_indexonlyscan; indxpath.c does that */
579 
580  /*
581  * Call index-access-method-specific code to estimate the processing cost
582  * for scanning the index, as well as the selectivity of the index (ie,
583  * the fraction of main-table tuples we will have to retrieve) and its
584  * correlation to the main-table tuple order. We need a cast here because
585  * pathnodes.h uses a weak function type to avoid including amapi.h.
586  */
587  amcostestimate = (amcostestimate_function) index->amcostestimate;
588  amcostestimate(root, path, loop_count,
589  &indexStartupCost, &indexTotalCost,
590  &indexSelectivity, &indexCorrelation,
591  &index_pages);
592 
593  /*
594  * Save amcostestimate's results for possible use in bitmap scan planning.
595  * We don't bother to save indexStartupCost or indexCorrelation, because a
596  * bitmap scan doesn't care about either.
597  */
598  path->indextotalcost = indexTotalCost;
599  path->indexselectivity = indexSelectivity;
600 
601  /* all costs for touching index itself included here */
602  startup_cost += indexStartupCost;
603  run_cost += indexTotalCost - indexStartupCost;
604 
605  /* estimate number of main-table tuples fetched */
606  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
607 
608  /* fetch estimated page costs for tablespace containing table */
610  &spc_random_page_cost,
611  &spc_seq_page_cost);
612 
613  /*----------
614  * Estimate number of main-table pages fetched, and compute I/O cost.
615  *
616  * When the index ordering is uncorrelated with the table ordering,
617  * we use an approximation proposed by Mackert and Lohman (see
618  * index_pages_fetched() for details) to compute the number of pages
619  * fetched, and then charge spc_random_page_cost per page fetched.
620  *
621  * When the index ordering is exactly correlated with the table ordering
622  * (just after a CLUSTER, for example), the number of pages fetched should
623  * be exactly selectivity * table_size. What's more, all but the first
624  * will be sequential fetches, not the random fetches that occur in the
625  * uncorrelated case. So if the number of pages is more than 1, we
626  * ought to charge
627  * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
628  * For partially-correlated indexes, we ought to charge somewhere between
629  * these two estimates. We currently interpolate linearly between the
630  * estimates based on the correlation squared (XXX is that appropriate?).
631  *
632  * If it's an index-only scan, then we will not need to fetch any heap
633  * pages for which the visibility map shows all tuples are visible.
634  * Hence, reduce the estimated number of heap fetches accordingly.
635  * We use the measured fraction of the entire heap that is all-visible,
636  * which might not be particularly relevant to the subset of the heap
637  * that this query will fetch; but it's not clear how to do better.
638  *----------
639  */
640  if (loop_count > 1)
641  {
642  /*
643  * For repeated indexscans, the appropriate estimate for the
644  * uncorrelated case is to scale up the number of tuples fetched in
645  * the Mackert and Lohman formula by the number of scans, so that we
646  * estimate the number of pages fetched by all the scans; then
647  * pro-rate the costs for one scan. In this case we assume all the
648  * fetches are random accesses.
649  */
650  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
651  baserel->pages,
652  (double) index->pages,
653  root);
654 
655  if (indexonly)
656  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
657 
658  rand_heap_pages = pages_fetched;
659 
660  max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
661 
662  /*
663  * In the perfectly correlated case, the number of pages touched by
664  * each scan is selectivity * table_size, and we can use the Mackert
665  * and Lohman formula at the page level to estimate how much work is
666  * saved by caching across scans. We still assume all the fetches are
667  * random, though, which is an overestimate that's hard to correct for
668  * without double-counting the cache effects. (But in most cases
669  * where such a plan is actually interesting, only one page would get
670  * fetched per scan anyway, so it shouldn't matter much.)
671  */
672  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
673 
674  pages_fetched = index_pages_fetched(pages_fetched * loop_count,
675  baserel->pages,
676  (double) index->pages,
677  root);
678 
679  if (indexonly)
680  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
681 
682  min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
683  }
684  else
685  {
686  /*
687  * Normal case: apply the Mackert and Lohman formula, and then
688  * interpolate between that and the correlation-derived result.
689  */
690  pages_fetched = index_pages_fetched(tuples_fetched,
691  baserel->pages,
692  (double) index->pages,
693  root);
694 
695  if (indexonly)
696  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
697 
698  rand_heap_pages = pages_fetched;
699 
700  /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
701  max_IO_cost = pages_fetched * spc_random_page_cost;
702 
703  /* min_IO_cost is for the perfectly correlated case (csquared=1) */
704  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
705 
706  if (indexonly)
707  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
708 
709  if (pages_fetched > 0)
710  {
711  min_IO_cost = spc_random_page_cost;
712  if (pages_fetched > 1)
713  min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
714  }
715  else
716  min_IO_cost = 0;
717  }
718 
719  if (partial_path)
720  {
721  /*
722  * For index only scans compute workers based on number of index pages
723  * fetched; the number of heap pages we fetch might be so small as to
724  * effectively rule out parallelism, which we don't want to do.
725  */
726  if (indexonly)
727  rand_heap_pages = -1;
728 
729  /*
730  * Estimate the number of parallel workers required to scan index. Use
731  * the number of heap pages computed considering heap fetches won't be
732  * sequential as for parallel scans the pages are accessed in random
733  * order.
734  */
736  rand_heap_pages,
737  index_pages,
739 
740  /*
741  * Fall out if workers can't be assigned for parallel scan, because in
742  * such a case this path will be rejected. So there is no benefit in
743  * doing extra computation.
744  */
745  if (path->path.parallel_workers <= 0)
746  return;
747 
748  path->path.parallel_aware = true;
749  }
750 
751  /*
752  * Now interpolate based on estimated index order correlation to get total
753  * disk I/O cost for main table accesses.
754  */
755  csquared = indexCorrelation * indexCorrelation;
756 
757  run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
758 
759  /*
760  * Estimate CPU costs per tuple.
761  *
762  * What we want here is cpu_tuple_cost plus the evaluation costs of any
763  * qual clauses that we have to evaluate as qpquals.
764  */
765  cost_qual_eval(&qpqual_cost, qpquals, root);
766 
767  startup_cost += qpqual_cost.startup;
768  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
769 
770  cpu_run_cost += cpu_per_tuple * tuples_fetched;
771 
772  /* tlist eval costs are paid per output row, not per tuple scanned */
773  startup_cost += path->path.pathtarget->cost.startup;
774  cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
775 
776  /* Adjust costing for parallelism, if used. */
777  if (path->path.parallel_workers > 0)
778  {
779  double parallel_divisor = get_parallel_divisor(&path->path);
780 
781  path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
782 
783  /* The CPU cost is divided among all the workers. */
784  cpu_run_cost /= parallel_divisor;
785  }
786 
787  run_cost += cpu_run_cost;
788 
789  path->path.startup_cost = startup_cost;
790  path->path.total_cost = startup_cost + run_cost;
791 }
792 
793 /*
794  * extract_nonindex_conditions
795  *
796  * Given a list of quals to be enforced in an indexscan, extract the ones that
797  * will have to be applied as qpquals (ie, the index machinery won't handle
798  * them). Here we detect only whether a qual clause is directly redundant
799  * with some indexclause. If the index path is chosen for use, createplan.c
800  * will try a bit harder to get rid of redundant qual conditions; specifically
801  * it will see if quals can be proven to be implied by the indexquals. But
802  * it does not seem worth the cycles to try to factor that in at this stage,
803  * since we're only trying to estimate qual eval costs. Otherwise this must
804  * match the logic in create_indexscan_plan().
805  *
806  * qual_clauses, and the result, are lists of RestrictInfos.
807  * indexclauses is a list of IndexClauses.
808  */
809 static List *
810 extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
811 {
812  List *result = NIL;
813  ListCell *lc;
814 
815  foreach(lc, qual_clauses)
816  {
817  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
818 
819  if (rinfo->pseudoconstant)
820  continue; /* we may drop pseudoconstants here */
821  if (is_redundant_with_indexclauses(rinfo, indexclauses))
822  continue; /* dup or derived from same EquivalenceClass */
823  /* ... skip the predicate proof attempt createplan.c will try ... */
824  result = lappend(result, rinfo);
825  }
826  return result;
827 }
828 
829 /*
830  * index_pages_fetched
831  * Estimate the number of pages actually fetched after accounting for
832  * cache effects.
833  *
834  * We use an approximation proposed by Mackert and Lohman, "Index Scans
835  * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
836  * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
837  * The Mackert and Lohman approximation is that the number of pages
838  * fetched is
839  * PF =
840  * min(2TNs/(2T+Ns), T) when T <= b
841  * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
842  * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
843  * where
844  * T = # pages in table
845  * N = # tuples in table
846  * s = selectivity = fraction of table to be scanned
847  * b = # buffer pages available (we include kernel space here)
848  *
849  * We assume that effective_cache_size is the total number of buffer pages
850  * available for the whole query, and pro-rate that space across all the
851  * tables in the query and the index currently under consideration. (This
852  * ignores space needed for other indexes used by the query, but since we
853  * don't know which indexes will get used, we can't estimate that very well;
854  * and in any case counting all the tables may well be an overestimate, since
855  * depending on the join plan not all the tables may be scanned concurrently.)
856  *
857  * The product Ns is the number of tuples fetched; we pass in that
858  * product rather than calculating it here. "pages" is the number of pages
859  * in the object under consideration (either an index or a table).
860  * "index_pages" is the amount to add to the total table space, which was
861  * computed for us by make_one_rel.
862  *
863  * Caller is expected to have ensured that tuples_fetched is greater than zero
864  * and rounded to integer (see clamp_row_est). The result will likewise be
865  * greater than zero and integral.
866  */
867 double
868 index_pages_fetched(double tuples_fetched, BlockNumber pages,
869  double index_pages, PlannerInfo *root)
870 {
871  double pages_fetched;
872  double total_pages;
873  double T,
874  b;
875 
876  /* T is # pages in table, but don't allow it to be zero */
877  T = (pages > 1) ? (double) pages : 1.0;
878 
879  /* Compute number of pages assumed to be competing for cache space */
880  total_pages = root->total_table_pages + index_pages;
881  total_pages = Max(total_pages, 1.0);
882  Assert(T <= total_pages);
883 
884  /* b is pro-rated share of effective_cache_size */
885  b = (double) effective_cache_size * T / total_pages;
886 
887  /* force it positive and integral */
888  if (b <= 1.0)
889  b = 1.0;
890  else
891  b = ceil(b);
892 
893  /* This part is the Mackert and Lohman formula */
894  if (T <= b)
895  {
896  pages_fetched =
897  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
898  if (pages_fetched >= T)
899  pages_fetched = T;
900  else
901  pages_fetched = ceil(pages_fetched);
902  }
903  else
904  {
905  double lim;
906 
907  lim = (2.0 * T * b) / (2.0 * T - b);
908  if (tuples_fetched <= lim)
909  {
910  pages_fetched =
911  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
912  }
913  else
914  {
915  pages_fetched =
916  b + (tuples_fetched - lim) * (T - b) / T;
917  }
918  pages_fetched = ceil(pages_fetched);
919  }
920  return pages_fetched;
921 }
922 
923 /*
924  * get_indexpath_pages
925  * Determine the total size of the indexes used in a bitmap index path.
926  *
927  * Note: if the same index is used more than once in a bitmap tree, we will
928  * count it multiple times, which perhaps is the wrong thing ... but it's
929  * not completely clear, and detecting duplicates is difficult, so ignore it
930  * for now.
931  */
932 static double
934 {
935  double result = 0;
936  ListCell *l;
937 
938  if (IsA(bitmapqual, BitmapAndPath))
939  {
940  BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
941 
942  foreach(l, apath->bitmapquals)
943  {
944  result += get_indexpath_pages((Path *) lfirst(l));
945  }
946  }
947  else if (IsA(bitmapqual, BitmapOrPath))
948  {
949  BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
950 
951  foreach(l, opath->bitmapquals)
952  {
953  result += get_indexpath_pages((Path *) lfirst(l));
954  }
955  }
956  else if (IsA(bitmapqual, IndexPath))
957  {
958  IndexPath *ipath = (IndexPath *) bitmapqual;
959 
960  result = (double) ipath->indexinfo->pages;
961  }
962  else
963  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
964 
965  return result;
966 }
967 
968 /*
969  * cost_bitmap_heap_scan
970  * Determines and returns the cost of scanning a relation using a bitmap
971  * index-then-heap plan.
972  *
973  * 'baserel' is the relation to be scanned
974  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
975  * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
976  * 'loop_count' is the number of repetitions of the indexscan to factor into
977  * estimates of caching behavior
978  *
979  * Note: the component IndexPaths in bitmapqual should have been costed
980  * using the same loop_count.
981  */
982 void
984  ParamPathInfo *param_info,
985  Path *bitmapqual, double loop_count)
986 {
987  Cost startup_cost = 0;
988  Cost run_cost = 0;
989  Cost indexTotalCost;
990  QualCost qpqual_cost;
991  Cost cpu_per_tuple;
992  Cost cost_per_page;
993  Cost cpu_run_cost;
994  double tuples_fetched;
995  double pages_fetched;
996  double spc_seq_page_cost,
997  spc_random_page_cost;
998  double T;
999 
1000  /* Should only be applied to base relations */
1001  Assert(IsA(baserel, RelOptInfo));
1002  Assert(baserel->relid > 0);
1003  Assert(baserel->rtekind == RTE_RELATION);
1004 
1005  /* Mark the path with the correct row estimate */
1006  if (param_info)
1007  path->rows = param_info->ppi_rows;
1008  else
1009  path->rows = baserel->rows;
1010 
1011  if (!enable_bitmapscan)
1012  startup_cost += disable_cost;
1013 
1014  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
1015  loop_count, &indexTotalCost,
1016  &tuples_fetched);
1017 
1018  startup_cost += indexTotalCost;
1019  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1020 
1021  /* Fetch estimated page costs for tablespace containing table. */
1023  &spc_random_page_cost,
1024  &spc_seq_page_cost);
1025 
1026  /*
1027  * For small numbers of pages we should charge spc_random_page_cost
1028  * apiece, while if nearly all the table's pages are being read, it's more
1029  * appropriate to charge spc_seq_page_cost apiece. The effect is
1030  * nonlinear, too. For lack of a better idea, interpolate like this to
1031  * determine the cost per page.
1032  */
1033  if (pages_fetched >= 2.0)
1034  cost_per_page = spc_random_page_cost -
1035  (spc_random_page_cost - spc_seq_page_cost)
1036  * sqrt(pages_fetched / T);
1037  else
1038  cost_per_page = spc_random_page_cost;
1039 
1040  run_cost += pages_fetched * cost_per_page;
1041 
1042  /*
1043  * Estimate CPU costs per tuple.
1044  *
1045  * Often the indexquals don't need to be rechecked at each tuple ... but
1046  * not always, especially not if there are enough tuples involved that the
1047  * bitmaps become lossy. For the moment, just assume they will be
1048  * rechecked always. This means we charge the full freight for all the
1049  * scan clauses.
1050  */
1051  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1052 
1053  startup_cost += qpqual_cost.startup;
1054  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1055  cpu_run_cost = cpu_per_tuple * tuples_fetched;
1056 
1057  /* Adjust costing for parallelism, if used. */
1058  if (path->parallel_workers > 0)
1059  {
1060  double parallel_divisor = get_parallel_divisor(path);
1061 
1062  /* The CPU cost is divided among all the workers. */
1063  cpu_run_cost /= parallel_divisor;
1064 
1065  path->rows = clamp_row_est(path->rows / parallel_divisor);
1066  }
1067 
1068 
1069  run_cost += cpu_run_cost;
1070 
1071  /* tlist eval costs are paid per output row, not per tuple scanned */
1072  startup_cost += path->pathtarget->cost.startup;
1073  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1074 
1075  path->startup_cost = startup_cost;
1076  path->total_cost = startup_cost + run_cost;
1077 }
1078 
1079 /*
1080  * cost_bitmap_tree_node
1081  * Extract cost and selectivity from a bitmap tree node (index/and/or)
1082  */
1083 void
1085 {
1086  if (IsA(path, IndexPath))
1087  {
1088  *cost = ((IndexPath *) path)->indextotalcost;
1089  *selec = ((IndexPath *) path)->indexselectivity;
1090 
1091  /*
1092  * Charge a small amount per retrieved tuple to reflect the costs of
1093  * manipulating the bitmap. This is mostly to make sure that a bitmap
1094  * scan doesn't look to be the same cost as an indexscan to retrieve a
1095  * single tuple.
1096  */
1097  *cost += 0.1 * cpu_operator_cost * path->rows;
1098  }
1099  else if (IsA(path, BitmapAndPath))
1100  {
1101  *cost = path->total_cost;
1102  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1103  }
1104  else if (IsA(path, BitmapOrPath))
1105  {
1106  *cost = path->total_cost;
1107  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1108  }
1109  else
1110  {
1111  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1112  *cost = *selec = 0; /* keep compiler quiet */
1113  }
1114 }
1115 
1116 /*
1117  * cost_bitmap_and_node
1118  * Estimate the cost of a BitmapAnd node
1119  *
1120  * Note that this considers only the costs of index scanning and bitmap
1121  * creation, not the eventual heap access. In that sense the object isn't
1122  * truly a Path, but it has enough path-like properties (costs in particular)
1123  * to warrant treating it as one. We don't bother to set the path rows field,
1124  * however.
1125  */
1126 void
1128 {
1129  Cost totalCost;
1130  Selectivity selec;
1131  ListCell *l;
1132 
1133  /*
1134  * We estimate AND selectivity on the assumption that the inputs are
1135  * independent. This is probably often wrong, but we don't have the info
1136  * to do better.
1137  *
1138  * The runtime cost of the BitmapAnd itself is estimated at 100x
1139  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1140  * definitely too simplistic?
1141  */
1142  totalCost = 0.0;
1143  selec = 1.0;
1144  foreach(l, path->bitmapquals)
1145  {
1146  Path *subpath = (Path *) lfirst(l);
1147  Cost subCost;
1148  Selectivity subselec;
1149 
1150  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1151 
1152  selec *= subselec;
1153 
1154  totalCost += subCost;
1155  if (l != list_head(path->bitmapquals))
1156  totalCost += 100.0 * cpu_operator_cost;
1157  }
1158  path->bitmapselectivity = selec;
1159  path->path.rows = 0; /* per above, not used */
1160  path->path.startup_cost = totalCost;
1161  path->path.total_cost = totalCost;
1162 }
1163 
1164 /*
1165  * cost_bitmap_or_node
1166  * Estimate the cost of a BitmapOr node
1167  *
1168  * See comments for cost_bitmap_and_node.
1169  */
1170 void
1172 {
1173  Cost totalCost;
1174  Selectivity selec;
1175  ListCell *l;
1176 
1177  /*
1178  * We estimate OR selectivity on the assumption that the inputs are
1179  * non-overlapping, since that's often the case in "x IN (list)" type
1180  * situations. Of course, we clamp to 1.0 at the end.
1181  *
1182  * The runtime cost of the BitmapOr itself is estimated at 100x
1183  * cpu_operator_cost for each tbm_union needed. Probably too small,
1184  * definitely too simplistic? We are aware that the tbm_unions are
1185  * optimized out when the inputs are BitmapIndexScans.
1186  */
1187  totalCost = 0.0;
1188  selec = 0.0;
1189  foreach(l, path->bitmapquals)
1190  {
1191  Path *subpath = (Path *) lfirst(l);
1192  Cost subCost;
1193  Selectivity subselec;
1194 
1195  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1196 
1197  selec += subselec;
1198 
1199  totalCost += subCost;
1200  if (l != list_head(path->bitmapquals) &&
1201  !IsA(subpath, IndexPath))
1202  totalCost += 100.0 * cpu_operator_cost;
1203  }
1204  path->bitmapselectivity = Min(selec, 1.0);
1205  path->path.rows = 0; /* per above, not used */
1206  path->path.startup_cost = totalCost;
1207  path->path.total_cost = totalCost;
1208 }
1209 
1210 /*
1211  * cost_tidscan
1212  * Determines and returns the cost of scanning a relation using TIDs.
1213  *
1214  * 'baserel' is the relation to be scanned
1215  * 'tidquals' is the list of TID-checkable quals
1216  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1217  */
1218 void
1220  RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
1221 {
1222  Cost startup_cost = 0;
1223  Cost run_cost = 0;
1224  bool isCurrentOf = false;
1225  QualCost qpqual_cost;
1226  Cost cpu_per_tuple;
1227  QualCost tid_qual_cost;
1228  int ntuples;
1229  ListCell *l;
1230  double spc_random_page_cost;
1231 
1232  /* Should only be applied to base relations */
1233  Assert(baserel->relid > 0);
1234  Assert(baserel->rtekind == RTE_RELATION);
1235 
1236  /* Mark the path with the correct row estimate */
1237  if (param_info)
1238  path->rows = param_info->ppi_rows;
1239  else
1240  path->rows = baserel->rows;
1241 
1242  /* Count how many tuples we expect to retrieve */
1243  ntuples = 0;
1244  foreach(l, tidquals)
1245  {
1246  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1247  Expr *qual = rinfo->clause;
1248 
1249  if (IsA(qual, ScalarArrayOpExpr))
1250  {
1251  /* Each element of the array yields 1 tuple */
1252  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1253  Node *arraynode = (Node *) lsecond(saop->args);
1254 
1255  ntuples += estimate_array_length(arraynode);
1256  }
1257  else if (IsA(qual, CurrentOfExpr))
1258  {
1259  /* CURRENT OF yields 1 tuple */
1260  isCurrentOf = true;
1261  ntuples++;
1262  }
1263  else
1264  {
1265  /* It's just CTID = something, count 1 tuple */
1266  ntuples++;
1267  }
1268  }
1269 
1270  /*
1271  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1272  * understands how to do it correctly. Therefore, honor enable_tidscan
1273  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1274  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1275  * subtract off here; that's to prevent other plan types such as seqscan
1276  * from winning.
1277  */
1278  if (isCurrentOf)
1279  {
1281  startup_cost -= disable_cost;
1282  }
1283  else if (!enable_tidscan)
1284  startup_cost += disable_cost;
1285 
1286  /*
1287  * The TID qual expressions will be computed once, any other baserestrict
1288  * quals once per retrieved tuple.
1289  */
1290  cost_qual_eval(&tid_qual_cost, tidquals, root);
1291 
1292  /* fetch estimated page cost for tablespace containing table */
1294  &spc_random_page_cost,
1295  NULL);
1296 
1297  /* disk costs --- assume each tuple on a different page */
1298  run_cost += spc_random_page_cost * ntuples;
1299 
1300  /* Add scanning CPU costs */
1301  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1302 
1303  /* XXX currently we assume TID quals are a subset of qpquals */
1304  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1305  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1306  tid_qual_cost.per_tuple;
1307  run_cost += cpu_per_tuple * ntuples;
1308 
1309  /* tlist eval costs are paid per output row, not per tuple scanned */
1310  startup_cost += path->pathtarget->cost.startup;
1311  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1312 
1313  path->startup_cost = startup_cost;
1314  path->total_cost = startup_cost + run_cost;
1315 }
1316 
1317 /*
1318  * cost_tidrangescan
1319  * Determines and sets the costs of scanning a relation using a range of
1320  * TIDs for 'path'
1321  *
1322  * 'baserel' is the relation to be scanned
1323  * 'tidrangequals' is the list of TID-checkable range quals
1324  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1325  */
1326 void
1328  RelOptInfo *baserel, List *tidrangequals,
1329  ParamPathInfo *param_info)
1330 {
1331  Selectivity selectivity;
1332  double pages;
1333  Cost startup_cost = 0;
1334  Cost run_cost = 0;
1335  QualCost qpqual_cost;
1336  Cost cpu_per_tuple;
1337  QualCost tid_qual_cost;
1338  double ntuples;
1339  double nseqpages;
1340  double spc_random_page_cost;
1341  double spc_seq_page_cost;
1342 
1343  /* Should only be applied to base relations */
1344  Assert(baserel->relid > 0);
1345  Assert(baserel->rtekind == RTE_RELATION);
1346 
1347  /* Mark the path with the correct row estimate */
1348  if (param_info)
1349  path->rows = param_info->ppi_rows;
1350  else
1351  path->rows = baserel->rows;
1352 
1353  /* Count how many tuples and pages we expect to scan */
1354  selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1355  JOIN_INNER, NULL);
1356  pages = ceil(selectivity * baserel->pages);
1357 
1358  if (pages <= 0.0)
1359  pages = 1.0;
1360 
1361  /*
1362  * The first page in a range requires a random seek, but each subsequent
1363  * page is just a normal sequential page read. NOTE: it's desirable for
1364  * TID Range Scans to cost more than the equivalent Sequential Scans,
1365  * because Seq Scans have some performance advantages such as scan
1366  * synchronization and parallelizability, and we'd prefer one of them to
1367  * be picked unless a TID Range Scan really is better.
1368  */
1369  ntuples = selectivity * baserel->tuples;
1370  nseqpages = pages - 1.0;
1371 
1372  if (!enable_tidscan)
1373  startup_cost += disable_cost;
1374 
1375  /*
1376  * The TID qual expressions will be computed once, any other baserestrict
1377  * quals once per retrieved tuple.
1378  */
1379  cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1380 
1381  /* fetch estimated page cost for tablespace containing table */
1383  &spc_random_page_cost,
1384  &spc_seq_page_cost);
1385 
1386  /* disk costs; 1 random page and the remainder as seq pages */
1387  run_cost += spc_random_page_cost + spc_seq_page_cost * nseqpages;
1388 
1389  /* Add scanning CPU costs */
1390  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1391 
1392  /*
1393  * XXX currently we assume TID quals are a subset of qpquals at this
1394  * point; they will be removed (if possible) when we create the plan, so
1395  * we subtract their cost from the total qpqual cost. (If the TID quals
1396  * can't be removed, this is a mistake and we're going to underestimate
1397  * the CPU cost a bit.)
1398  */
1399  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1400  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1401  tid_qual_cost.per_tuple;
1402  run_cost += cpu_per_tuple * ntuples;
1403 
1404  /* tlist eval costs are paid per output row, not per tuple scanned */
1405  startup_cost += path->pathtarget->cost.startup;
1406  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1407 
1408  path->startup_cost = startup_cost;
1409  path->total_cost = startup_cost + run_cost;
1410 }
1411 
1412 /*
1413  * cost_subqueryscan
1414  * Determines and returns the cost of scanning a subquery RTE.
1415  *
1416  * 'baserel' is the relation to be scanned
1417  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1418  * 'trivial_pathtarget' is true if the pathtarget is believed to be trivial.
1419  */
1420 void
1422  RelOptInfo *baserel, ParamPathInfo *param_info,
1423  bool trivial_pathtarget)
1424 {
1425  Cost startup_cost;
1426  Cost run_cost;
1427  List *qpquals;
1428  QualCost qpqual_cost;
1429  Cost cpu_per_tuple;
1430 
1431  /* Should only be applied to base relations that are subqueries */
1432  Assert(baserel->relid > 0);
1433  Assert(baserel->rtekind == RTE_SUBQUERY);
1434 
1435  /*
1436  * We compute the rowcount estimate as the subplan's estimate times the
1437  * selectivity of relevant restriction clauses. In simple cases this will
1438  * come out the same as baserel->rows; but when dealing with parallelized
1439  * paths we must do it like this to get the right answer.
1440  */
1441  if (param_info)
1442  qpquals = list_concat_copy(param_info->ppi_clauses,
1443  baserel->baserestrictinfo);
1444  else
1445  qpquals = baserel->baserestrictinfo;
1446 
1447  path->path.rows = clamp_row_est(path->subpath->rows *
1449  qpquals,
1450  0,
1451  JOIN_INNER,
1452  NULL));
1453 
1454  /*
1455  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1456  * any restriction clauses and tlist that will be attached to the
1457  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1458  * projection overhead.
1459  */
1460  path->path.startup_cost = path->subpath->startup_cost;
1461  path->path.total_cost = path->subpath->total_cost;
1462 
1463  /*
1464  * However, if there are no relevant restriction clauses and the
1465  * pathtarget is trivial, then we expect that setrefs.c will optimize away
1466  * the SubqueryScan plan node altogether, so we should just make its cost
1467  * and rowcount equal to the input path's.
1468  *
1469  * Note: there are some edge cases where createplan.c will apply a
1470  * different targetlist to the SubqueryScan node, thus falsifying our
1471  * current estimate of whether the target is trivial, and making the cost
1472  * estimate (though not the rowcount) wrong. It does not seem worth the
1473  * extra complication to try to account for that exactly, especially since
1474  * that behavior falsifies other cost estimates as well.
1475  */
1476  if (qpquals == NIL && trivial_pathtarget)
1477  return;
1478 
1479  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1480 
1481  startup_cost = qpqual_cost.startup;
1482  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1483  run_cost = cpu_per_tuple * path->subpath->rows;
1484 
1485  /* tlist eval costs are paid per output row, not per tuple scanned */
1486  startup_cost += path->path.pathtarget->cost.startup;
1487  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1488 
1489  path->path.startup_cost += startup_cost;
1490  path->path.total_cost += startup_cost + run_cost;
1491 }
1492 
1493 /*
1494  * cost_functionscan
1495  * Determines and returns the cost of scanning a function RTE.
1496  *
1497  * 'baserel' is the relation to be scanned
1498  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1499  */
1500 void
1502  RelOptInfo *baserel, ParamPathInfo *param_info)
1503 {
1504  Cost startup_cost = 0;
1505  Cost run_cost = 0;
1506  QualCost qpqual_cost;
1507  Cost cpu_per_tuple;
1508  RangeTblEntry *rte;
1509  QualCost exprcost;
1510 
1511  /* Should only be applied to base relations that are functions */
1512  Assert(baserel->relid > 0);
1513  rte = planner_rt_fetch(baserel->relid, root);
1514  Assert(rte->rtekind == RTE_FUNCTION);
1515 
1516  /* Mark the path with the correct row estimate */
1517  if (param_info)
1518  path->rows = param_info->ppi_rows;
1519  else
1520  path->rows = baserel->rows;
1521 
1522  /*
1523  * Estimate costs of executing the function expression(s).
1524  *
1525  * Currently, nodeFunctionscan.c always executes the functions to
1526  * completion before returning any rows, and caches the results in a
1527  * tuplestore. So the function eval cost is all startup cost, and per-row
1528  * costs are minimal.
1529  *
1530  * XXX in principle we ought to charge tuplestore spill costs if the
1531  * number of rows is large. However, given how phony our rowcount
1532  * estimates for functions tend to be, there's not a lot of point in that
1533  * refinement right now.
1534  */
1535  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1536 
1537  startup_cost += exprcost.startup + exprcost.per_tuple;
1538 
1539  /* Add scanning CPU costs */
1540  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1541 
1542  startup_cost += qpqual_cost.startup;
1543  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1544  run_cost += cpu_per_tuple * baserel->tuples;
1545 
1546  /* tlist eval costs are paid per output row, not per tuple scanned */
1547  startup_cost += path->pathtarget->cost.startup;
1548  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1549 
1550  path->startup_cost = startup_cost;
1551  path->total_cost = startup_cost + run_cost;
1552 }
1553 
1554 /*
1555  * cost_tablefuncscan
1556  * Determines and returns the cost of scanning a table function.
1557  *
1558  * 'baserel' is the relation to be scanned
1559  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1560  */
1561 void
1563  RelOptInfo *baserel, ParamPathInfo *param_info)
1564 {
1565  Cost startup_cost = 0;
1566  Cost run_cost = 0;
1567  QualCost qpqual_cost;
1568  Cost cpu_per_tuple;
1569  RangeTblEntry *rte;
1570  QualCost exprcost;
1571 
1572  /* Should only be applied to base relations that are functions */
1573  Assert(baserel->relid > 0);
1574  rte = planner_rt_fetch(baserel->relid, root);
1575  Assert(rte->rtekind == RTE_TABLEFUNC);
1576 
1577  /* Mark the path with the correct row estimate */
1578  if (param_info)
1579  path->rows = param_info->ppi_rows;
1580  else
1581  path->rows = baserel->rows;
1582 
1583  /*
1584  * Estimate costs of executing the table func expression(s).
1585  *
1586  * XXX in principle we ought to charge tuplestore spill costs if the
1587  * number of rows is large. However, given how phony our rowcount
1588  * estimates for tablefuncs tend to be, there's not a lot of point in that
1589  * refinement right now.
1590  */
1591  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1592 
1593  startup_cost += exprcost.startup + exprcost.per_tuple;
1594 
1595  /* Add scanning CPU costs */
1596  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1597 
1598  startup_cost += qpqual_cost.startup;
1599  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1600  run_cost += cpu_per_tuple * baserel->tuples;
1601 
1602  /* tlist eval costs are paid per output row, not per tuple scanned */
1603  startup_cost += path->pathtarget->cost.startup;
1604  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1605 
1606  path->startup_cost = startup_cost;
1607  path->total_cost = startup_cost + run_cost;
1608 }
1609 
1610 /*
1611  * cost_valuesscan
1612  * Determines and returns the cost of scanning a VALUES RTE.
1613  *
1614  * 'baserel' is the relation to be scanned
1615  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1616  */
1617 void
1619  RelOptInfo *baserel, ParamPathInfo *param_info)
1620 {
1621  Cost startup_cost = 0;
1622  Cost run_cost = 0;
1623  QualCost qpqual_cost;
1624  Cost cpu_per_tuple;
1625 
1626  /* Should only be applied to base relations that are values lists */
1627  Assert(baserel->relid > 0);
1628  Assert(baserel->rtekind == RTE_VALUES);
1629 
1630  /* Mark the path with the correct row estimate */
1631  if (param_info)
1632  path->rows = param_info->ppi_rows;
1633  else
1634  path->rows = baserel->rows;
1635 
1636  /*
1637  * For now, estimate list evaluation cost at one operator eval per list
1638  * (probably pretty bogus, but is it worth being smarter?)
1639  */
1640  cpu_per_tuple = cpu_operator_cost;
1641 
1642  /* Add scanning CPU costs */
1643  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1644 
1645  startup_cost += qpqual_cost.startup;
1646  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1647  run_cost += cpu_per_tuple * baserel->tuples;
1648 
1649  /* tlist eval costs are paid per output row, not per tuple scanned */
1650  startup_cost += path->pathtarget->cost.startup;
1651  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1652 
1653  path->startup_cost = startup_cost;
1654  path->total_cost = startup_cost + run_cost;
1655 }
1656 
1657 /*
1658  * cost_ctescan
1659  * Determines and returns the cost of scanning a CTE RTE.
1660  *
1661  * Note: this is used for both self-reference and regular CTEs; the
1662  * possible cost differences are below the threshold of what we could
1663  * estimate accurately anyway. Note that the costs of evaluating the
1664  * referenced CTE query are added into the final plan as initplan costs,
1665  * and should NOT be counted here.
1666  */
1667 void
1669  RelOptInfo *baserel, ParamPathInfo *param_info)
1670 {
1671  Cost startup_cost = 0;
1672  Cost run_cost = 0;
1673  QualCost qpqual_cost;
1674  Cost cpu_per_tuple;
1675 
1676  /* Should only be applied to base relations that are CTEs */
1677  Assert(baserel->relid > 0);
1678  Assert(baserel->rtekind == RTE_CTE);
1679 
1680  /* Mark the path with the correct row estimate */
1681  if (param_info)
1682  path->rows = param_info->ppi_rows;
1683  else
1684  path->rows = baserel->rows;
1685 
1686  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1687  cpu_per_tuple = cpu_tuple_cost;
1688 
1689  /* Add scanning CPU costs */
1690  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1691 
1692  startup_cost += qpqual_cost.startup;
1693  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1694  run_cost += cpu_per_tuple * baserel->tuples;
1695 
1696  /* tlist eval costs are paid per output row, not per tuple scanned */
1697  startup_cost += path->pathtarget->cost.startup;
1698  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1699 
1700  path->startup_cost = startup_cost;
1701  path->total_cost = startup_cost + run_cost;
1702 }
1703 
1704 /*
1705  * cost_namedtuplestorescan
1706  * Determines and returns the cost of scanning a named tuplestore.
1707  */
1708 void
1710  RelOptInfo *baserel, ParamPathInfo *param_info)
1711 {
1712  Cost startup_cost = 0;
1713  Cost run_cost = 0;
1714  QualCost qpqual_cost;
1715  Cost cpu_per_tuple;
1716 
1717  /* Should only be applied to base relations that are Tuplestores */
1718  Assert(baserel->relid > 0);
1719  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1720 
1721  /* Mark the path with the correct row estimate */
1722  if (param_info)
1723  path->rows = param_info->ppi_rows;
1724  else
1725  path->rows = baserel->rows;
1726 
1727  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1728  cpu_per_tuple = cpu_tuple_cost;
1729 
1730  /* Add scanning CPU costs */
1731  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1732 
1733  startup_cost += qpqual_cost.startup;
1734  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1735  run_cost += cpu_per_tuple * baserel->tuples;
1736 
1737  path->startup_cost = startup_cost;
1738  path->total_cost = startup_cost + run_cost;
1739 }
1740 
1741 /*
1742  * cost_resultscan
1743  * Determines and returns the cost of scanning an RTE_RESULT relation.
1744  */
1745 void
1747  RelOptInfo *baserel, ParamPathInfo *param_info)
1748 {
1749  Cost startup_cost = 0;
1750  Cost run_cost = 0;
1751  QualCost qpqual_cost;
1752  Cost cpu_per_tuple;
1753 
1754  /* Should only be applied to RTE_RESULT base relations */
1755  Assert(baserel->relid > 0);
1756  Assert(baserel->rtekind == RTE_RESULT);
1757 
1758  /* Mark the path with the correct row estimate */
1759  if (param_info)
1760  path->rows = param_info->ppi_rows;
1761  else
1762  path->rows = baserel->rows;
1763 
1764  /* We charge qual cost plus cpu_tuple_cost */
1765  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1766 
1767  startup_cost += qpqual_cost.startup;
1768  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1769  run_cost += cpu_per_tuple * baserel->tuples;
1770 
1771  path->startup_cost = startup_cost;
1772  path->total_cost = startup_cost + run_cost;
1773 }
1774 
1775 /*
1776  * cost_recursive_union
1777  * Determines and returns the cost of performing a recursive union,
1778  * and also the estimated output size.
1779  *
1780  * We are given Paths for the nonrecursive and recursive terms.
1781  */
1782 void
1783 cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
1784 {
1785  Cost startup_cost;
1786  Cost total_cost;
1787  double total_rows;
1788 
1789  /* We probably have decent estimates for the non-recursive term */
1790  startup_cost = nrterm->startup_cost;
1791  total_cost = nrterm->total_cost;
1792  total_rows = nrterm->rows;
1793 
1794  /*
1795  * We arbitrarily assume that about 10 recursive iterations will be
1796  * needed, and that we've managed to get a good fix on the cost and output
1797  * size of each one of them. These are mighty shaky assumptions but it's
1798  * hard to see how to do better.
1799  */
1800  total_cost += 10 * rterm->total_cost;
1801  total_rows += 10 * rterm->rows;
1802 
1803  /*
1804  * Also charge cpu_tuple_cost per row to account for the costs of
1805  * manipulating the tuplestores. (We don't worry about possible
1806  * spill-to-disk costs.)
1807  */
1808  total_cost += cpu_tuple_cost * total_rows;
1809 
1810  runion->startup_cost = startup_cost;
1811  runion->total_cost = total_cost;
1812  runion->rows = total_rows;
1813  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1814  rterm->pathtarget->width);
1815 }
1816 
1817 /*
1818  * cost_tuplesort
1819  * Determines and returns the cost of sorting a relation using tuplesort,
1820  * not including the cost of reading the input data.
1821  *
1822  * If the total volume of data to sort is less than sort_mem, we will do
1823  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1824  * comparisons for t tuples.
1825  *
1826  * If the total volume exceeds sort_mem, we switch to a tape-style merge
1827  * algorithm. There will still be about t*log2(t) tuple comparisons in
1828  * total, but we will also need to write and read each tuple once per
1829  * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1830  * number of initial runs formed and M is the merge order used by tuplesort.c.
1831  * Since the average initial run should be about sort_mem, we have
1832  * disk traffic = 2 * relsize * ceil(logM(p / sort_mem))
1833  * cpu = comparison_cost * t * log2(t)
1834  *
1835  * If the sort is bounded (i.e., only the first k result tuples are needed)
1836  * and k tuples can fit into sort_mem, we use a heap method that keeps only
1837  * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1838  *
1839  * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1840  * accesses (XXX can't we refine that guess?)
1841  *
1842  * By default, we charge two operator evals per tuple comparison, which should
1843  * be in the right ballpark in most cases. The caller can tweak this by
1844  * specifying nonzero comparison_cost; typically that's used for any extra
1845  * work that has to be done to prepare the inputs to the comparison operators.
1846  *
1847  * 'tuples' is the number of tuples in the relation
1848  * 'width' is the average tuple width in bytes
1849  * 'comparison_cost' is the extra cost per comparison, if any
1850  * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1851  * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1852  */
1853 static void
1854 cost_tuplesort(Cost *startup_cost, Cost *run_cost,
1855  double tuples, int width,
1856  Cost comparison_cost, int sort_mem,
1857  double limit_tuples)
1858 {
1859  double input_bytes = relation_byte_size(tuples, width);
1860  double output_bytes;
1861  double output_tuples;
1862  long sort_mem_bytes = sort_mem * 1024L;
1863 
1864  /*
1865  * We want to be sure the cost of a sort is never estimated as zero, even
1866  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1867  */
1868  if (tuples < 2.0)
1869  tuples = 2.0;
1870 
1871  /* Include the default cost-per-comparison */
1872  comparison_cost += 2.0 * cpu_operator_cost;
1873 
1874  /* Do we have a useful LIMIT? */
1875  if (limit_tuples > 0 && limit_tuples < tuples)
1876  {
1877  output_tuples = limit_tuples;
1878  output_bytes = relation_byte_size(output_tuples, width);
1879  }
1880  else
1881  {
1882  output_tuples = tuples;
1883  output_bytes = input_bytes;
1884  }
1885 
1886  if (output_bytes > sort_mem_bytes)
1887  {
1888  /*
1889  * We'll have to use a disk-based sort of all the tuples
1890  */
1891  double npages = ceil(input_bytes / BLCKSZ);
1892  double nruns = input_bytes / sort_mem_bytes;
1893  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1894  double log_runs;
1895  double npageaccesses;
1896 
1897  /*
1898  * CPU costs
1899  *
1900  * Assume about N log2 N comparisons
1901  */
1902  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1903 
1904  /* Disk costs */
1905 
1906  /* Compute logM(r) as log(r) / log(M) */
1907  if (nruns > mergeorder)
1908  log_runs = ceil(log(nruns) / log(mergeorder));
1909  else
1910  log_runs = 1.0;
1911  npageaccesses = 2.0 * npages * log_runs;
1912  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1913  *startup_cost += npageaccesses *
1914  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1915  }
1916  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1917  {
1918  /*
1919  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1920  * a total number of tuple comparisons of N log2 K; but the constant
1921  * factor is a bit higher than for quicksort. Tweak it so that the
1922  * cost curve is continuous at the crossover point.
1923  */
1924  *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
1925  }
1926  else
1927  {
1928  /* We'll use plain quicksort on all the input tuples */
1929  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1930  }
1931 
1932  /*
1933  * Also charge a small amount (arbitrarily set equal to operator cost) per
1934  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1935  * doesn't do qual-checking or projection, so it has less overhead than
1936  * most plan nodes. Note it's correct to use tuples not output_tuples
1937  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1938  * counting the LIMIT otherwise.
1939  */
1940  *run_cost = cpu_operator_cost * tuples;
1941 }
1942 
1943 /*
1944  * cost_incremental_sort
1945  * Determines and returns the cost of sorting a relation incrementally, when
1946  * the input path is presorted by a prefix of the pathkeys.
1947  *
1948  * 'presorted_keys' is the number of leading pathkeys by which the input path
1949  * is sorted.
1950  *
1951  * We estimate the number of groups into which the relation is divided by the
1952  * leading pathkeys, and then calculate the cost of sorting a single group
1953  * with tuplesort using cost_tuplesort().
1954  */
1955 void
1957  PlannerInfo *root, List *pathkeys, int presorted_keys,
1958  Cost input_startup_cost, Cost input_total_cost,
1959  double input_tuples, int width, Cost comparison_cost, int sort_mem,
1960  double limit_tuples)
1961 {
1962  Cost startup_cost = 0,
1963  run_cost = 0,
1964  input_run_cost = input_total_cost - input_startup_cost;
1965  double group_tuples,
1966  input_groups;
1967  Cost group_startup_cost,
1968  group_run_cost,
1969  group_input_run_cost;
1970  List *presortedExprs = NIL;
1971  ListCell *l;
1972  int i = 0;
1973  bool unknown_varno = false;
1974 
1975  Assert(presorted_keys != 0);
1976 
1977  /*
1978  * We want to be sure the cost of a sort is never estimated as zero, even
1979  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1980  */
1981  if (input_tuples < 2.0)
1982  input_tuples = 2.0;
1983 
1984  /* Default estimate of number of groups, capped to one group per row. */
1985  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
1986 
1987  /*
1988  * Extract presorted keys as list of expressions.
1989  *
1990  * We need to be careful about Vars containing "varno 0" which might have
1991  * been introduced by generate_append_tlist, which would confuse
1992  * estimate_num_groups (in fact it'd fail for such expressions). See
1993  * recurse_set_operations which has to deal with the same issue.
1994  *
1995  * Unlike recurse_set_operations we can't access the original target list
1996  * here, and even if we could it's not very clear how useful would that be
1997  * for a set operation combining multiple tables. So we simply detect if
1998  * there are any expressions with "varno 0" and use the default
1999  * DEFAULT_NUM_DISTINCT in that case.
2000  *
2001  * We might also use either 1.0 (a single group) or input_tuples (each row
2002  * being a separate group), pretty much the worst and best case for
2003  * incremental sort. But those are extreme cases and using something in
2004  * between seems reasonable. Furthermore, generate_append_tlist is used
2005  * for set operations, which are likely to produce mostly unique output
2006  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2007  * while maintaining lower startup cost.
2008  */
2009  foreach(l, pathkeys)
2010  {
2011  PathKey *key = (PathKey *) lfirst(l);
2012  EquivalenceMember *member = (EquivalenceMember *)
2013  linitial(key->pk_eclass->ec_members);
2014 
2015  /*
2016  * Check if the expression contains Var with "varno 0" so that we
2017  * don't call estimate_num_groups in that case.
2018  */
2019  if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2020  {
2021  unknown_varno = true;
2022  break;
2023  }
2024 
2025  /* expression not containing any Vars with "varno 0" */
2026  presortedExprs = lappend(presortedExprs, member->em_expr);
2027 
2028  i++;
2029  if (i >= presorted_keys)
2030  break;
2031  }
2032 
2033  /* Estimate number of groups with equal presorted keys. */
2034  if (!unknown_varno)
2035  input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2036  NULL, NULL);
2037 
2038  group_tuples = input_tuples / input_groups;
2039  group_input_run_cost = input_run_cost / input_groups;
2040 
2041  /*
2042  * Estimate average cost of sorting of one group where presorted keys are
2043  * equal. Incremental sort is sensitive to distribution of tuples to the
2044  * groups, where we're relying on quite rough assumptions. Thus, we're
2045  * pessimistic about incremental sort performance and increase its average
2046  * group size by half.
2047  */
2048  cost_tuplesort(&group_startup_cost, &group_run_cost,
2049  1.5 * group_tuples, width, comparison_cost, sort_mem,
2050  limit_tuples);
2051 
2052  /*
2053  * Startup cost of incremental sort is the startup cost of its first group
2054  * plus the cost of its input.
2055  */
2056  startup_cost += group_startup_cost
2057  + input_startup_cost + group_input_run_cost;
2058 
2059  /*
2060  * After we started producing tuples from the first group, the cost of
2061  * producing all the tuples is given by the cost to finish processing this
2062  * group, plus the total cost to process the remaining groups, plus the
2063  * remaining cost of input.
2064  */
2065  run_cost += group_run_cost
2066  + (group_run_cost + group_startup_cost) * (input_groups - 1)
2067  + group_input_run_cost * (input_groups - 1);
2068 
2069  /*
2070  * Incremental sort adds some overhead by itself. Firstly, it has to
2071  * detect the sort groups. This is roughly equal to one extra copy and
2072  * comparison per tuple. Secondly, it has to reset the tuplesort context
2073  * for every group.
2074  */
2075  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2076  run_cost += 2.0 * cpu_tuple_cost * input_groups;
2077 
2078  path->rows = input_tuples;
2079  path->startup_cost = startup_cost;
2080  path->total_cost = startup_cost + run_cost;
2081 }
2082 
2083 /*
2084  * cost_sort
2085  * Determines and returns the cost of sorting a relation, including
2086  * the cost of reading the input data.
2087  *
2088  * NOTE: some callers currently pass NIL for pathkeys because they
2089  * can't conveniently supply the sort keys. Since this routine doesn't
2090  * currently do anything with pathkeys anyway, that doesn't matter...
2091  * but if it ever does, it should react gracefully to lack of key data.
2092  * (Actually, the thing we'd most likely be interested in is just the number
2093  * of sort keys, which all callers *could* supply.)
2094  */
2095 void
2097  List *pathkeys, Cost input_cost, double tuples, int width,
2098  Cost comparison_cost, int sort_mem,
2099  double limit_tuples)
2100 
2101 {
2102  Cost startup_cost;
2103  Cost run_cost;
2104 
2105  cost_tuplesort(&startup_cost, &run_cost,
2106  tuples, width,
2107  comparison_cost, sort_mem,
2108  limit_tuples);
2109 
2110  if (!enable_sort)
2111  startup_cost += disable_cost;
2112 
2113  startup_cost += input_cost;
2114 
2115  path->rows = tuples;
2116  path->startup_cost = startup_cost;
2117  path->total_cost = startup_cost + run_cost;
2118 }
2119 
2120 /*
2121  * append_nonpartial_cost
2122  * Estimate the cost of the non-partial paths in a Parallel Append.
2123  * The non-partial paths are assumed to be the first "numpaths" paths
2124  * from the subpaths list, and to be in order of decreasing cost.
2125  */
2126 static Cost
2127 append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
2128 {
2129  Cost *costarr;
2130  int arrlen;
2131  ListCell *l;
2132  ListCell *cell;
2133  int path_index;
2134  int min_index;
2135  int max_index;
2136 
2137  if (numpaths == 0)
2138  return 0;
2139 
2140  /*
2141  * Array length is number of workers or number of relevant paths,
2142  * whichever is less.
2143  */
2144  arrlen = Min(parallel_workers, numpaths);
2145  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2146 
2147  /* The first few paths will each be claimed by a different worker. */
2148  path_index = 0;
2149  foreach(cell, subpaths)
2150  {
2151  Path *subpath = (Path *) lfirst(cell);
2152 
2153  if (path_index == arrlen)
2154  break;
2155  costarr[path_index++] = subpath->total_cost;
2156  }
2157 
2158  /*
2159  * Since subpaths are sorted by decreasing cost, the last one will have
2160  * the minimum cost.
2161  */
2162  min_index = arrlen - 1;
2163 
2164  /*
2165  * For each of the remaining subpaths, add its cost to the array element
2166  * with minimum cost.
2167  */
2168  for_each_cell(l, subpaths, cell)
2169  {
2170  Path *subpath = (Path *) lfirst(l);
2171 
2172  /* Consider only the non-partial paths */
2173  if (path_index++ == numpaths)
2174  break;
2175 
2176  costarr[min_index] += subpath->total_cost;
2177 
2178  /* Update the new min cost array index */
2179  min_index = 0;
2180  for (int i = 0; i < arrlen; i++)
2181  {
2182  if (costarr[i] < costarr[min_index])
2183  min_index = i;
2184  }
2185  }
2186 
2187  /* Return the highest cost from the array */
2188  max_index = 0;
2189  for (int i = 0; i < arrlen; i++)
2190  {
2191  if (costarr[i] > costarr[max_index])
2192  max_index = i;
2193  }
2194 
2195  return costarr[max_index];
2196 }
2197 
2198 /*
2199  * cost_append
2200  * Determines and returns the cost of an Append node.
2201  */
2202 void
2204 {
2205  ListCell *l;
2206 
2207  apath->path.startup_cost = 0;
2208  apath->path.total_cost = 0;
2209  apath->path.rows = 0;
2210 
2211  if (apath->subpaths == NIL)
2212  return;
2213 
2214  if (!apath->path.parallel_aware)
2215  {
2216  List *pathkeys = apath->path.pathkeys;
2217 
2218  if (pathkeys == NIL)
2219  {
2220  Path *firstsubpath = (Path *) linitial(apath->subpaths);
2221 
2222  /*
2223  * For an unordered, non-parallel-aware Append we take the startup
2224  * cost as the startup cost of the first subpath.
2225  */
2226  apath->path.startup_cost = firstsubpath->startup_cost;
2227 
2228  /* Compute rows and costs as sums of subplan rows and costs. */
2229  foreach(l, apath->subpaths)
2230  {
2231  Path *subpath = (Path *) lfirst(l);
2232 
2233  apath->path.rows += subpath->rows;
2234  apath->path.total_cost += subpath->total_cost;
2235  }
2236  }
2237  else
2238  {
2239  /*
2240  * For an ordered, non-parallel-aware Append we take the startup
2241  * cost as the sum of the subpath startup costs. This ensures
2242  * that we don't underestimate the startup cost when a query's
2243  * LIMIT is such that several of the children have to be run to
2244  * satisfy it. This might be overkill --- another plausible hack
2245  * would be to take the Append's startup cost as the maximum of
2246  * the child startup costs. But we don't want to risk believing
2247  * that an ORDER BY LIMIT query can be satisfied at small cost
2248  * when the first child has small startup cost but later ones
2249  * don't. (If we had the ability to deal with nonlinear cost
2250  * interpolation for partial retrievals, we would not need to be
2251  * so conservative about this.)
2252  *
2253  * This case is also different from the above in that we have to
2254  * account for possibly injecting sorts into subpaths that aren't
2255  * natively ordered.
2256  */
2257  foreach(l, apath->subpaths)
2258  {
2259  Path *subpath = (Path *) lfirst(l);
2260  Path sort_path; /* dummy for result of cost_sort */
2261 
2262  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2263  {
2264  /*
2265  * We'll need to insert a Sort node, so include costs for
2266  * that. We can use the parent's LIMIT if any, since we
2267  * certainly won't pull more than that many tuples from
2268  * any child.
2269  */
2270  cost_sort(&sort_path,
2271  NULL, /* doesn't currently need root */
2272  pathkeys,
2273  subpath->total_cost,
2274  subpath->rows,
2275  subpath->pathtarget->width,
2276  0.0,
2277  work_mem,
2278  apath->limit_tuples);
2279  subpath = &sort_path;
2280  }
2281 
2282  apath->path.rows += subpath->rows;
2283  apath->path.startup_cost += subpath->startup_cost;
2284  apath->path.total_cost += subpath->total_cost;
2285  }
2286  }
2287  }
2288  else /* parallel-aware */
2289  {
2290  int i = 0;
2291  double parallel_divisor = get_parallel_divisor(&apath->path);
2292 
2293  /* Parallel-aware Append never produces ordered output. */
2294  Assert(apath->path.pathkeys == NIL);
2295 
2296  /* Calculate startup cost. */
2297  foreach(l, apath->subpaths)
2298  {
2299  Path *subpath = (Path *) lfirst(l);
2300 
2301  /*
2302  * Append will start returning tuples when the child node having
2303  * lowest startup cost is done setting up. We consider only the
2304  * first few subplans that immediately get a worker assigned.
2305  */
2306  if (i == 0)
2307  apath->path.startup_cost = subpath->startup_cost;
2308  else if (i < apath->path.parallel_workers)
2309  apath->path.startup_cost = Min(apath->path.startup_cost,
2310  subpath->startup_cost);
2311 
2312  /*
2313  * Apply parallel divisor to subpaths. Scale the number of rows
2314  * for each partial subpath based on the ratio of the parallel
2315  * divisor originally used for the subpath to the one we adopted.
2316  * Also add the cost of partial paths to the total cost, but
2317  * ignore non-partial paths for now.
2318  */
2319  if (i < apath->first_partial_path)
2320  apath->path.rows += subpath->rows / parallel_divisor;
2321  else
2322  {
2323  double subpath_parallel_divisor;
2324 
2325  subpath_parallel_divisor = get_parallel_divisor(subpath);
2326  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2327  parallel_divisor);
2328  apath->path.total_cost += subpath->total_cost;
2329  }
2330 
2331  apath->path.rows = clamp_row_est(apath->path.rows);
2332 
2333  i++;
2334  }
2335 
2336  /* Add cost for non-partial subpaths. */
2337  apath->path.total_cost +=
2339  apath->first_partial_path,
2340  apath->path.parallel_workers);
2341  }
2342 
2343  /*
2344  * Although Append does not do any selection or projection, it's not free;
2345  * add a small per-tuple overhead.
2346  */
2347  apath->path.total_cost +=
2349 }
2350 
2351 /*
2352  * cost_merge_append
2353  * Determines and returns the cost of a MergeAppend node.
2354  *
2355  * MergeAppend merges several pre-sorted input streams, using a heap that
2356  * at any given instant holds the next tuple from each stream. If there
2357  * are N streams, we need about N*log2(N) tuple comparisons to construct
2358  * the heap at startup, and then for each output tuple, about log2(N)
2359  * comparisons to replace the top entry.
2360  *
2361  * (The effective value of N will drop once some of the input streams are
2362  * exhausted, but it seems unlikely to be worth trying to account for that.)
2363  *
2364  * The heap is never spilled to disk, since we assume N is not very large.
2365  * So this is much simpler than cost_sort.
2366  *
2367  * As in cost_sort, we charge two operator evals per tuple comparison.
2368  *
2369  * 'pathkeys' is a list of sort keys
2370  * 'n_streams' is the number of input streams
2371  * 'input_startup_cost' is the sum of the input streams' startup costs
2372  * 'input_total_cost' is the sum of the input streams' total costs
2373  * 'tuples' is the number of tuples in all the streams
2374  */
2375 void
2377  List *pathkeys, int n_streams,
2378  Cost input_startup_cost, Cost input_total_cost,
2379  double tuples)
2380 {
2381  Cost startup_cost = 0;
2382  Cost run_cost = 0;
2383  Cost comparison_cost;
2384  double N;
2385  double logN;
2386 
2387  /*
2388  * Avoid log(0)...
2389  */
2390  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2391  logN = LOG2(N);
2392 
2393  /* Assumed cost per tuple comparison */
2394  comparison_cost = 2.0 * cpu_operator_cost;
2395 
2396  /* Heap creation cost */
2397  startup_cost += comparison_cost * N * logN;
2398 
2399  /* Per-tuple heap maintenance cost */
2400  run_cost += tuples * comparison_cost * logN;
2401 
2402  /*
2403  * Although MergeAppend does not do any selection or projection, it's not
2404  * free; add a small per-tuple overhead.
2405  */
2406  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2407 
2408  path->startup_cost = startup_cost + input_startup_cost;
2409  path->total_cost = startup_cost + run_cost + input_total_cost;
2410 }
2411 
2412 /*
2413  * cost_material
2414  * Determines and returns the cost of materializing a relation, including
2415  * the cost of reading the input data.
2416  *
2417  * If the total volume of data to materialize exceeds work_mem, we will need
2418  * to write it to disk, so the cost is much higher in that case.
2419  *
2420  * Note that here we are estimating the costs for the first scan of the
2421  * relation, so the materialization is all overhead --- any savings will
2422  * occur only on rescan, which is estimated in cost_rescan.
2423  */
2424 void
2426  Cost input_startup_cost, Cost input_total_cost,
2427  double tuples, int width)
2428 {
2429  Cost startup_cost = input_startup_cost;
2430  Cost run_cost = input_total_cost - input_startup_cost;
2431  double nbytes = relation_byte_size(tuples, width);
2432  long work_mem_bytes = work_mem * 1024L;
2433 
2434  path->rows = tuples;
2435 
2436  /*
2437  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2438  * reflect bookkeeping overhead. (This rate must be more than what
2439  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2440  * if it is exactly the same then there will be a cost tie between
2441  * nestloop with A outer, materialized B inner and nestloop with B outer,
2442  * materialized A inner. The extra cost ensures we'll prefer
2443  * materializing the smaller rel.) Note that this is normally a good deal
2444  * less than cpu_tuple_cost; which is OK because a Material plan node
2445  * doesn't do qual-checking or projection, so it's got less overhead than
2446  * most plan nodes.
2447  */
2448  run_cost += 2 * cpu_operator_cost * tuples;
2449 
2450  /*
2451  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2452  * This cost is assumed to be evenly spread through the plan run phase,
2453  * which isn't exactly accurate but our cost model doesn't allow for
2454  * nonuniform costs within the run phase.
2455  */
2456  if (nbytes > work_mem_bytes)
2457  {
2458  double npages = ceil(nbytes / BLCKSZ);
2459 
2460  run_cost += seq_page_cost * npages;
2461  }
2462 
2463  path->startup_cost = startup_cost;
2464  path->total_cost = startup_cost + run_cost;
2465 }
2466 
2467 /*
2468  * cost_memoize_rescan
2469  * Determines the estimated cost of rescanning a Memoize node.
2470  *
2471  * In order to estimate this, we must gain knowledge of how often we expect to
2472  * be called and how many distinct sets of parameters we are likely to be
2473  * called with. If we expect a good cache hit ratio, then we can set our
2474  * costs to account for that hit ratio, plus a little bit of cost for the
2475  * caching itself. Caching will not work out well if we expect to be called
2476  * with too many distinct parameter values. The worst-case here is that we
2477  * never see any parameter value twice, in which case we'd never get a cache
2478  * hit and caching would be a complete waste of effort.
2479  */
2480 static void
2482  Cost *rescan_startup_cost, Cost *rescan_total_cost)
2483 {
2484  EstimationInfo estinfo;
2485  Cost input_startup_cost = mpath->subpath->startup_cost;
2486  Cost input_total_cost = mpath->subpath->total_cost;
2487  double tuples = mpath->subpath->rows;
2488  double calls = mpath->calls;
2489  int width = mpath->subpath->pathtarget->width;
2490 
2491  double hash_mem_bytes;
2492  double est_entry_bytes;
2493  double est_cache_entries;
2494  double ndistinct;
2495  double evict_ratio;
2496  double hit_ratio;
2497  Cost startup_cost;
2498  Cost total_cost;
2499 
2500  /* available cache space */
2501  hash_mem_bytes = get_hash_memory_limit();
2502 
2503  /*
2504  * Set the number of bytes each cache entry should consume in the cache.
2505  * To provide us with better estimations on how many cache entries we can
2506  * store at once, we make a call to the executor here to ask it what
2507  * memory overheads there are for a single cache entry.
2508  *
2509  * XXX we also store the cache key, but that's not accounted for here.
2510  */
2511  est_entry_bytes = relation_byte_size(tuples, width) +
2513 
2514  /* estimate on the upper limit of cache entries we can hold at once */
2515  est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2516 
2517  /* estimate on the distinct number of parameter values */
2518  ndistinct = estimate_num_groups(root, mpath->param_exprs, calls, NULL,
2519  &estinfo);
2520 
2521  /*
2522  * When the estimation fell back on using a default value, it's a bit too
2523  * risky to assume that it's ok to use a Memoize node. The use of a
2524  * default could cause us to use a Memoize node when it's really
2525  * inappropriate to do so. If we see that this has been done, then we'll
2526  * assume that every call will have unique parameters, which will almost
2527  * certainly mean a MemoizePath will never survive add_path().
2528  */
2529  if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2530  ndistinct = calls;
2531 
2532  /*
2533  * Since we've already estimated the maximum number of entries we can
2534  * store at once and know the estimated number of distinct values we'll be
2535  * called with, we'll take this opportunity to set the path's est_entries.
2536  * This will ultimately determine the hash table size that the executor
2537  * will use. If we leave this at zero, the executor will just choose the
2538  * size itself. Really this is not the right place to do this, but it's
2539  * convenient since everything is already calculated.
2540  */
2541  mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2542  PG_UINT32_MAX);
2543 
2544  /*
2545  * When the number of distinct parameter values is above the amount we can
2546  * store in the cache, then we'll have to evict some entries from the
2547  * cache. This is not free. Here we estimate how often we'll incur the
2548  * cost of that eviction.
2549  */
2550  evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2551 
2552  /*
2553  * In order to estimate how costly a single scan will be, we need to
2554  * attempt to estimate what the cache hit ratio will be. To do that we
2555  * must look at how many scans are estimated in total for this node and
2556  * how many of those scans we expect to get a cache hit.
2557  */
2558  hit_ratio = 1.0 / ndistinct * Min(est_cache_entries, ndistinct) -
2559  (ndistinct / calls);
2560 
2561  /* Ensure we don't go negative */
2562  hit_ratio = Max(hit_ratio, 0.0);
2563 
2564  /*
2565  * Set the total_cost accounting for the expected cache hit ratio. We
2566  * also add on a cpu_operator_cost to account for a cache lookup. This
2567  * will happen regardless of whether it's a cache hit or not.
2568  */
2569  total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2570 
2571  /* Now adjust the total cost to account for cache evictions */
2572 
2573  /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2574  total_cost += cpu_tuple_cost * evict_ratio;
2575 
2576  /*
2577  * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2578  * The per-tuple eviction is really just a pfree, so charging a whole
2579  * cpu_operator_cost seems a little excessive.
2580  */
2581  total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2582 
2583  /*
2584  * Now adjust for storing things in the cache, since that's not free
2585  * either. Everything must go in the cache. We don't proportion this
2586  * over any ratio, just apply it once for the scan. We charge a
2587  * cpu_tuple_cost for the creation of the cache entry and also a
2588  * cpu_operator_cost for each tuple we expect to cache.
2589  */
2590  total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2591 
2592  /*
2593  * Getting the first row must be also be proportioned according to the
2594  * expected cache hit ratio.
2595  */
2596  startup_cost = input_startup_cost * (1.0 - hit_ratio);
2597 
2598  /*
2599  * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2600  * which we'll do regardless of whether it was a cache hit or not.
2601  */
2602  startup_cost += cpu_tuple_cost;
2603 
2604  *rescan_startup_cost = startup_cost;
2605  *rescan_total_cost = total_cost;
2606 }
2607 
2608 /*
2609  * cost_agg
2610  * Determines and returns the cost of performing an Agg plan node,
2611  * including the cost of its input.
2612  *
2613  * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
2614  * we are using a hashed Agg node just to do grouping).
2615  *
2616  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
2617  * are for appropriately-sorted input.
2618  */
2619 void
2621  AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
2622  int numGroupCols, double numGroups,
2623  List *quals,
2624  Cost input_startup_cost, Cost input_total_cost,
2625  double input_tuples, double input_width)
2626 {
2627  double output_tuples;
2628  Cost startup_cost;
2629  Cost total_cost;
2630  AggClauseCosts dummy_aggcosts;
2631 
2632  /* Use all-zero per-aggregate costs if NULL is passed */
2633  if (aggcosts == NULL)
2634  {
2635  Assert(aggstrategy == AGG_HASHED);
2636  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2637  aggcosts = &dummy_aggcosts;
2638  }
2639 
2640  /*
2641  * The transCost.per_tuple component of aggcosts should be charged once
2642  * per input tuple, corresponding to the costs of evaluating the aggregate
2643  * transfns and their input expressions. The finalCost.per_tuple component
2644  * is charged once per output tuple, corresponding to the costs of
2645  * evaluating the finalfns. Startup costs are of course charged but once.
2646  *
2647  * If we are grouping, we charge an additional cpu_operator_cost per
2648  * grouping column per input tuple for grouping comparisons.
2649  *
2650  * We will produce a single output tuple if not grouping, and a tuple per
2651  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2652  *
2653  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2654  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2655  * input path is already sorted appropriately, AGG_SORTED should be
2656  * preferred (since it has no risk of memory overflow). This will happen
2657  * as long as the computed total costs are indeed exactly equal --- but if
2658  * there's roundoff error we might do the wrong thing. So be sure that
2659  * the computations below form the same intermediate values in the same
2660  * order.
2661  */
2662  if (aggstrategy == AGG_PLAIN)
2663  {
2664  startup_cost = input_total_cost;
2665  startup_cost += aggcosts->transCost.startup;
2666  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2667  startup_cost += aggcosts->finalCost.startup;
2668  startup_cost += aggcosts->finalCost.per_tuple;
2669  /* we aren't grouping */
2670  total_cost = startup_cost + cpu_tuple_cost;
2671  output_tuples = 1;
2672  }
2673  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2674  {
2675  /* Here we are able to deliver output on-the-fly */
2676  startup_cost = input_startup_cost;
2677  total_cost = input_total_cost;
2678  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2679  {
2680  startup_cost += disable_cost;
2681  total_cost += disable_cost;
2682  }
2683  /* calcs phrased this way to match HASHED case, see note above */
2684  total_cost += aggcosts->transCost.startup;
2685  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2686  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2687  total_cost += aggcosts->finalCost.startup;
2688  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2689  total_cost += cpu_tuple_cost * numGroups;
2690  output_tuples = numGroups;
2691  }
2692  else
2693  {
2694  /* must be AGG_HASHED */
2695  startup_cost = input_total_cost;
2696  if (!enable_hashagg)
2697  startup_cost += disable_cost;
2698  startup_cost += aggcosts->transCost.startup;
2699  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2700  /* cost of computing hash value */
2701  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2702  startup_cost += aggcosts->finalCost.startup;
2703 
2704  total_cost = startup_cost;
2705  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2706  /* cost of retrieving from hash table */
2707  total_cost += cpu_tuple_cost * numGroups;
2708  output_tuples = numGroups;
2709  }
2710 
2711  /*
2712  * Add the disk costs of hash aggregation that spills to disk.
2713  *
2714  * Groups that go into the hash table stay in memory until finalized, so
2715  * spilling and reprocessing tuples doesn't incur additional invocations
2716  * of transCost or finalCost. Furthermore, the computed hash value is
2717  * stored with the spilled tuples, so we don't incur extra invocations of
2718  * the hash function.
2719  *
2720  * Hash Agg begins returning tuples after the first batch is complete.
2721  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2722  * accrue reads only to total_cost.
2723  */
2724  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2725  {
2726  double pages;
2727  double pages_written = 0.0;
2728  double pages_read = 0.0;
2729  double spill_cost;
2730  double hashentrysize;
2731  double nbatches;
2732  Size mem_limit;
2733  uint64 ngroups_limit;
2734  int num_partitions;
2735  int depth;
2736 
2737  /*
2738  * Estimate number of batches based on the computed limits. If less
2739  * than or equal to one, all groups are expected to fit in memory;
2740  * otherwise we expect to spill.
2741  */
2742  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2743  input_width,
2744  aggcosts->transitionSpace);
2745  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2746  &ngroups_limit, &num_partitions);
2747 
2748  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2749  numGroups / ngroups_limit);
2750 
2751  nbatches = Max(ceil(nbatches), 1.0);
2752  num_partitions = Max(num_partitions, 2);
2753 
2754  /*
2755  * The number of partitions can change at different levels of
2756  * recursion; but for the purposes of this calculation assume it stays
2757  * constant.
2758  */
2759  depth = ceil(log(nbatches) / log(num_partitions));
2760 
2761  /*
2762  * Estimate number of pages read and written. For each level of
2763  * recursion, a tuple must be written and then later read.
2764  */
2765  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2766  pages_written = pages_read = pages * depth;
2767 
2768  /*
2769  * HashAgg has somewhat worse IO behavior than Sort on typical
2770  * hardware/OS combinations. Account for this with a generic penalty.
2771  */
2772  pages_read *= 2.0;
2773  pages_written *= 2.0;
2774 
2775  startup_cost += pages_written * random_page_cost;
2776  total_cost += pages_written * random_page_cost;
2777  total_cost += pages_read * seq_page_cost;
2778 
2779  /* account for CPU cost of spilling a tuple and reading it back */
2780  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2781  startup_cost += spill_cost;
2782  total_cost += spill_cost;
2783  }
2784 
2785  /*
2786  * If there are quals (HAVING quals), account for their cost and
2787  * selectivity.
2788  */
2789  if (quals)
2790  {
2791  QualCost qual_cost;
2792 
2793  cost_qual_eval(&qual_cost, quals, root);
2794  startup_cost += qual_cost.startup;
2795  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2796 
2797  output_tuples = clamp_row_est(output_tuples *
2799  quals,
2800  0,
2801  JOIN_INNER,
2802  NULL));
2803  }
2804 
2805  path->rows = output_tuples;
2806  path->startup_cost = startup_cost;
2807  path->total_cost = total_cost;
2808 }
2809 
2810 /*
2811  * cost_windowagg
2812  * Determines and returns the cost of performing a WindowAgg plan node,
2813  * including the cost of its input.
2814  *
2815  * Input is assumed already properly sorted.
2816  */
2817 void
2819  List *windowFuncs, int numPartCols, int numOrderCols,
2820  Cost input_startup_cost, Cost input_total_cost,
2821  double input_tuples)
2822 {
2823  Cost startup_cost;
2824  Cost total_cost;
2825  ListCell *lc;
2826 
2827  startup_cost = input_startup_cost;
2828  total_cost = input_total_cost;
2829 
2830  /*
2831  * Window functions are assumed to cost their stated execution cost, plus
2832  * the cost of evaluating their input expressions, per tuple. Since they
2833  * may in fact evaluate their inputs at multiple rows during each cycle,
2834  * this could be a drastic underestimate; but without a way to know how
2835  * many rows the window function will fetch, it's hard to do better. In
2836  * any case, it's a good estimate for all the built-in window functions,
2837  * so we'll just do this for now.
2838  */
2839  foreach(lc, windowFuncs)
2840  {
2841  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2842  Cost wfunccost;
2843  QualCost argcosts;
2844 
2845  argcosts.startup = argcosts.per_tuple = 0;
2846  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2847  &argcosts);
2848  startup_cost += argcosts.startup;
2849  wfunccost = argcosts.per_tuple;
2850 
2851  /* also add the input expressions' cost to per-input-row costs */
2852  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2853  startup_cost += argcosts.startup;
2854  wfunccost += argcosts.per_tuple;
2855 
2856  /*
2857  * Add the filter's cost to per-input-row costs. XXX We should reduce
2858  * input expression costs according to filter selectivity.
2859  */
2860  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2861  startup_cost += argcosts.startup;
2862  wfunccost += argcosts.per_tuple;
2863 
2864  total_cost += wfunccost * input_tuples;
2865  }
2866 
2867  /*
2868  * We also charge cpu_operator_cost per grouping column per tuple for
2869  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2870  * overhead.
2871  *
2872  * XXX this neglects costs of spooling the data to disk when it overflows
2873  * work_mem. Sooner or later that should get accounted for.
2874  */
2875  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2876  total_cost += cpu_tuple_cost * input_tuples;
2877 
2878  path->rows = input_tuples;
2879  path->startup_cost = startup_cost;
2880  path->total_cost = total_cost;
2881 }
2882 
2883 /*
2884  * cost_group
2885  * Determines and returns the cost of performing a Group plan node,
2886  * including the cost of its input.
2887  *
2888  * Note: caller must ensure that input costs are for appropriately-sorted
2889  * input.
2890  */
2891 void
2893  int numGroupCols, double numGroups,
2894  List *quals,
2895  Cost input_startup_cost, Cost input_total_cost,
2896  double input_tuples)
2897 {
2898  double output_tuples;
2899  Cost startup_cost;
2900  Cost total_cost;
2901 
2902  output_tuples = numGroups;
2903  startup_cost = input_startup_cost;
2904  total_cost = input_total_cost;
2905 
2906  /*
2907  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2908  * all columns get compared at most of the tuples.
2909  */
2910  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2911 
2912  /*
2913  * If there are quals (HAVING quals), account for their cost and
2914  * selectivity.
2915  */
2916  if (quals)
2917  {
2918  QualCost qual_cost;
2919 
2920  cost_qual_eval(&qual_cost, quals, root);
2921  startup_cost += qual_cost.startup;
2922  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2923 
2924  output_tuples = clamp_row_est(output_tuples *
2926  quals,
2927  0,
2928  JOIN_INNER,
2929  NULL));
2930  }
2931 
2932  path->rows = output_tuples;
2933  path->startup_cost = startup_cost;
2934  path->total_cost = total_cost;
2935 }
2936 
2937 /*
2938  * initial_cost_nestloop
2939  * Preliminary estimate of the cost of a nestloop join path.
2940  *
2941  * This must quickly produce lower-bound estimates of the path's startup and
2942  * total costs. If we are unable to eliminate the proposed path from
2943  * consideration using the lower bounds, final_cost_nestloop will be called
2944  * to obtain the final estimates.
2945  *
2946  * The exact division of labor between this function and final_cost_nestloop
2947  * is private to them, and represents a tradeoff between speed of the initial
2948  * estimate and getting a tight lower bound. We choose to not examine the
2949  * join quals here, since that's by far the most expensive part of the
2950  * calculations. The end result is that CPU-cost considerations must be
2951  * left for the second phase; and for SEMI/ANTI joins, we must also postpone
2952  * incorporation of the inner path's run cost.
2953  *
2954  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
2955  * other data to be used by final_cost_nestloop
2956  * 'jointype' is the type of join to be performed
2957  * 'outer_path' is the outer input to the join
2958  * 'inner_path' is the inner input to the join
2959  * 'extra' contains miscellaneous information about the join
2960  */
2961 void
2963  JoinType jointype,
2964  Path *outer_path, Path *inner_path,
2965  JoinPathExtraData *extra)
2966 {
2967  Cost startup_cost = 0;
2968  Cost run_cost = 0;
2969  double outer_path_rows = outer_path->rows;
2970  Cost inner_rescan_start_cost;
2971  Cost inner_rescan_total_cost;
2972  Cost inner_run_cost;
2973  Cost inner_rescan_run_cost;
2974 
2975  /* estimate costs to rescan the inner relation */
2976  cost_rescan(root, inner_path,
2977  &inner_rescan_start_cost,
2978  &inner_rescan_total_cost);
2979 
2980  /* cost of source data */
2981 
2982  /*
2983  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
2984  * before we can start returning tuples, so the join's startup cost is
2985  * their sum. We'll also pay the inner path's rescan startup cost
2986  * multiple times.
2987  */
2988  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
2989  run_cost += outer_path->total_cost - outer_path->startup_cost;
2990  if (outer_path_rows > 1)
2991  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
2992 
2993  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
2994  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
2995 
2996  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
2997  extra->inner_unique)
2998  {
2999  /*
3000  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3001  * executor will stop after the first match.
3002  *
3003  * Getting decent estimates requires inspection of the join quals,
3004  * which we choose to postpone to final_cost_nestloop.
3005  */
3006 
3007  /* Save private data for final_cost_nestloop */
3008  workspace->inner_run_cost = inner_run_cost;
3009  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3010  }
3011  else
3012  {
3013  /* Normal case; we'll scan whole input rel for each outer row */
3014  run_cost += inner_run_cost;
3015  if (outer_path_rows > 1)
3016  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3017  }
3018 
3019  /* CPU costs left for later */
3020 
3021  /* Public result fields */
3022  workspace->startup_cost = startup_cost;
3023  workspace->total_cost = startup_cost + run_cost;
3024  /* Save private data for final_cost_nestloop */
3025  workspace->run_cost = run_cost;
3026 }
3027 
3028 /*
3029  * final_cost_nestloop
3030  * Final estimate of the cost and result size of a nestloop join path.
3031  *
3032  * 'path' is already filled in except for the rows and cost fields
3033  * 'workspace' is the result from initial_cost_nestloop
3034  * 'extra' contains miscellaneous information about the join
3035  */
3036 void
3038  JoinCostWorkspace *workspace,
3039  JoinPathExtraData *extra)
3040 {
3041  Path *outer_path = path->jpath.outerjoinpath;
3042  Path *inner_path = path->jpath.innerjoinpath;
3043  double outer_path_rows = outer_path->rows;
3044  double inner_path_rows = inner_path->rows;
3045  Cost startup_cost = workspace->startup_cost;
3046  Cost run_cost = workspace->run_cost;
3047  Cost cpu_per_tuple;
3048  QualCost restrict_qual_cost;
3049  double ntuples;
3050 
3051  /* Protect some assumptions below that rowcounts aren't zero */
3052  if (outer_path_rows <= 0)
3053  outer_path_rows = 1;
3054  if (inner_path_rows <= 0)
3055  inner_path_rows = 1;
3056  /* Mark the path with the correct row estimate */
3057  if (path->jpath.path.param_info)
3058  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3059  else
3060  path->jpath.path.rows = path->jpath.path.parent->rows;
3061 
3062  /* For partial paths, scale row estimate. */
3063  if (path->jpath.path.parallel_workers > 0)
3064  {
3065  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3066 
3067  path->jpath.path.rows =
3068  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3069  }
3070 
3071  /*
3072  * We could include disable_cost in the preliminary estimate, but that
3073  * would amount to optimizing for the case where the join method is
3074  * disabled, which doesn't seem like the way to bet.
3075  */
3076  if (!enable_nestloop)
3077  startup_cost += disable_cost;
3078 
3079  /* cost of inner-relation source data (we already dealt with outer rel) */
3080 
3081  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3082  extra->inner_unique)
3083  {
3084  /*
3085  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3086  * executor will stop after the first match.
3087  */
3088  Cost inner_run_cost = workspace->inner_run_cost;
3089  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3090  double outer_matched_rows;
3091  double outer_unmatched_rows;
3092  Selectivity inner_scan_frac;
3093 
3094  /*
3095  * For an outer-rel row that has at least one match, we can expect the
3096  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3097  * rows, if the matches are evenly distributed. Since they probably
3098  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3099  * that fraction. (If we used a larger fuzz factor, we'd have to
3100  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3101  * least 1, no such clamp is needed now.)
3102  */
3103  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3104  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3105  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3106 
3107  /*
3108  * Compute number of tuples processed (not number emitted!). First,
3109  * account for successfully-matched outer rows.
3110  */
3111  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3112 
3113  /*
3114  * Now we need to estimate the actual costs of scanning the inner
3115  * relation, which may be quite a bit less than N times inner_run_cost
3116  * due to early scan stops. We consider two cases. If the inner path
3117  * is an indexscan using all the joinquals as indexquals, then an
3118  * unmatched outer row results in an indexscan returning no rows,
3119  * which is probably quite cheap. Otherwise, the executor will have
3120  * to scan the whole inner rel for an unmatched row; not so cheap.
3121  */
3122  if (has_indexed_join_quals(path))
3123  {
3124  /*
3125  * Successfully-matched outer rows will only require scanning
3126  * inner_scan_frac of the inner relation. In this case, we don't
3127  * need to charge the full inner_run_cost even when that's more
3128  * than inner_rescan_run_cost, because we can assume that none of
3129  * the inner scans ever scan the whole inner relation. So it's
3130  * okay to assume that all the inner scan executions can be
3131  * fractions of the full cost, even if materialization is reducing
3132  * the rescan cost. At this writing, it's impossible to get here
3133  * for a materialized inner scan, so inner_run_cost and
3134  * inner_rescan_run_cost will be the same anyway; but just in
3135  * case, use inner_run_cost for the first matched tuple and
3136  * inner_rescan_run_cost for additional ones.
3137  */
3138  run_cost += inner_run_cost * inner_scan_frac;
3139  if (outer_matched_rows > 1)
3140  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3141 
3142  /*
3143  * Add the cost of inner-scan executions for unmatched outer rows.
3144  * We estimate this as the same cost as returning the first tuple
3145  * of a nonempty scan. We consider that these are all rescans,
3146  * since we used inner_run_cost once already.
3147  */
3148  run_cost += outer_unmatched_rows *
3149  inner_rescan_run_cost / inner_path_rows;
3150 
3151  /*
3152  * We won't be evaluating any quals at all for unmatched rows, so
3153  * don't add them to ntuples.
3154  */
3155  }
3156  else
3157  {
3158  /*
3159  * Here, a complicating factor is that rescans may be cheaper than
3160  * first scans. If we never scan all the way to the end of the
3161  * inner rel, it might be (depending on the plan type) that we'd
3162  * never pay the whole inner first-scan run cost. However it is
3163  * difficult to estimate whether that will happen (and it could
3164  * not happen if there are any unmatched outer rows!), so be
3165  * conservative and always charge the whole first-scan cost once.
3166  * We consider this charge to correspond to the first unmatched
3167  * outer row, unless there isn't one in our estimate, in which
3168  * case blame it on the first matched row.
3169  */
3170 
3171  /* First, count all unmatched join tuples as being processed */
3172  ntuples += outer_unmatched_rows * inner_path_rows;
3173 
3174  /* Now add the forced full scan, and decrement appropriate count */
3175  run_cost += inner_run_cost;
3176  if (outer_unmatched_rows >= 1)
3177  outer_unmatched_rows -= 1;
3178  else
3179  outer_matched_rows -= 1;
3180 
3181  /* Add inner run cost for additional outer tuples having matches */
3182  if (outer_matched_rows > 0)
3183  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3184 
3185  /* Add inner run cost for additional unmatched outer tuples */
3186  if (outer_unmatched_rows > 0)
3187  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3188  }
3189  }
3190  else
3191  {
3192  /* Normal-case source costs were included in preliminary estimate */
3193 
3194  /* Compute number of tuples processed (not number emitted!) */
3195  ntuples = outer_path_rows * inner_path_rows;
3196  }
3197 
3198  /* CPU costs */
3199  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3200  startup_cost += restrict_qual_cost.startup;
3201  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3202  run_cost += cpu_per_tuple * ntuples;
3203 
3204  /* tlist eval costs are paid per output row, not per tuple scanned */
3205  startup_cost += path->jpath.path.pathtarget->cost.startup;
3206  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3207 
3208  path->jpath.path.startup_cost = startup_cost;
3209  path->jpath.path.total_cost = startup_cost + run_cost;
3210 }
3211 
3212 /*
3213  * initial_cost_mergejoin
3214  * Preliminary estimate of the cost of a mergejoin path.
3215  *
3216  * This must quickly produce lower-bound estimates of the path's startup and
3217  * total costs. If we are unable to eliminate the proposed path from
3218  * consideration using the lower bounds, final_cost_mergejoin will be called
3219  * to obtain the final estimates.
3220  *
3221  * The exact division of labor between this function and final_cost_mergejoin
3222  * is private to them, and represents a tradeoff between speed of the initial
3223  * estimate and getting a tight lower bound. We choose to not examine the
3224  * join quals here, except for obtaining the scan selectivity estimate which
3225  * is really essential (but fortunately, use of caching keeps the cost of
3226  * getting that down to something reasonable).
3227  * We also assume that cost_sort is cheap enough to use here.
3228  *
3229  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
3230  * other data to be used by final_cost_mergejoin
3231  * 'jointype' is the type of join to be performed
3232  * 'mergeclauses' is the list of joinclauses to be used as merge clauses
3233  * 'outer_path' is the outer input to the join
3234  * 'inner_path' is the inner input to the join
3235  * 'outersortkeys' is the list of sort keys for the outer path
3236  * 'innersortkeys' is the list of sort keys for the inner path
3237  * 'extra' contains miscellaneous information about the join
3238  *
3239  * Note: outersortkeys and innersortkeys should be NIL if no explicit
3240  * sort is needed because the respective source path is already ordered.
3241  */
3242 void
3244  JoinType jointype,
3245  List *mergeclauses,
3246  Path *outer_path, Path *inner_path,
3247  List *outersortkeys, List *innersortkeys,
3248  JoinPathExtraData *extra)
3249 {
3250  Cost startup_cost = 0;
3251  Cost run_cost = 0;
3252  double outer_path_rows = outer_path->rows;
3253  double inner_path_rows = inner_path->rows;
3254  Cost inner_run_cost;
3255  double outer_rows,
3256  inner_rows,
3257  outer_skip_rows,
3258  inner_skip_rows;
3259  Selectivity outerstartsel,
3260  outerendsel,
3261  innerstartsel,
3262  innerendsel;
3263  Path sort_path; /* dummy for result of cost_sort */
3264 
3265  /* Protect some assumptions below that rowcounts aren't zero */
3266  if (outer_path_rows <= 0)
3267  outer_path_rows = 1;
3268  if (inner_path_rows <= 0)
3269  inner_path_rows = 1;
3270 
3271  /*
3272  * A merge join will stop as soon as it exhausts either input stream
3273  * (unless it's an outer join, in which case the outer side has to be
3274  * scanned all the way anyway). Estimate fraction of the left and right
3275  * inputs that will actually need to be scanned. Likewise, we can
3276  * estimate the number of rows that will be skipped before the first join
3277  * pair is found, which should be factored into startup cost. We use only
3278  * the first (most significant) merge clause for this purpose. Since
3279  * mergejoinscansel() is a fairly expensive computation, we cache the
3280  * results in the merge clause RestrictInfo.
3281  */
3282  if (mergeclauses && jointype != JOIN_FULL)
3283  {
3284  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3285  List *opathkeys;
3286  List *ipathkeys;
3287  PathKey *opathkey;
3288  PathKey *ipathkey;
3289  MergeScanSelCache *cache;
3290 
3291  /* Get the input pathkeys to determine the sort-order details */
3292  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3293  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3294  Assert(opathkeys);
3295  Assert(ipathkeys);
3296  opathkey = (PathKey *) linitial(opathkeys);
3297  ipathkey = (PathKey *) linitial(ipathkeys);
3298  /* debugging check */
3299  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3300  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3301  opathkey->pk_strategy != ipathkey->pk_strategy ||
3302  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3303  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3304 
3305  /* Get the selectivity with caching */
3306  cache = cached_scansel(root, firstclause, opathkey);
3307 
3308  if (bms_is_subset(firstclause->left_relids,
3309  outer_path->parent->relids))
3310  {
3311  /* left side of clause is outer */
3312  outerstartsel = cache->leftstartsel;
3313  outerendsel = cache->leftendsel;
3314  innerstartsel = cache->rightstartsel;
3315  innerendsel = cache->rightendsel;
3316  }
3317  else
3318  {
3319  /* left side of clause is inner */
3320  outerstartsel = cache->rightstartsel;
3321  outerendsel = cache->rightendsel;
3322  innerstartsel = cache->leftstartsel;
3323  innerendsel = cache->leftendsel;
3324  }
3325  if (jointype == JOIN_LEFT ||
3326  jointype == JOIN_ANTI)
3327  {
3328  outerstartsel = 0.0;
3329  outerendsel = 1.0;
3330  }
3331  else if (jointype == JOIN_RIGHT)
3332  {
3333  innerstartsel = 0.0;
3334  innerendsel = 1.0;
3335  }
3336  }
3337  else
3338  {
3339  /* cope with clauseless or full mergejoin */
3340  outerstartsel = innerstartsel = 0.0;
3341  outerendsel = innerendsel = 1.0;
3342  }
3343 
3344  /*
3345  * Convert selectivities to row counts. We force outer_rows and
3346  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3347  */
3348  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3349  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3350  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3351  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3352 
3353  Assert(outer_skip_rows <= outer_rows);
3354  Assert(inner_skip_rows <= inner_rows);
3355 
3356  /*
3357  * Readjust scan selectivities to account for above rounding. This is
3358  * normally an insignificant effect, but when there are only a few rows in
3359  * the inputs, failing to do this makes for a large percentage error.
3360  */
3361  outerstartsel = outer_skip_rows / outer_path_rows;
3362  innerstartsel = inner_skip_rows / inner_path_rows;
3363  outerendsel = outer_rows / outer_path_rows;
3364  innerendsel = inner_rows / inner_path_rows;
3365 
3366  Assert(outerstartsel <= outerendsel);
3367  Assert(innerstartsel <= innerendsel);
3368 
3369  /* cost of source data */
3370 
3371  if (outersortkeys) /* do we need to sort outer? */
3372  {
3373  cost_sort(&sort_path,
3374  root,
3375  outersortkeys,
3376  outer_path->total_cost,
3377  outer_path_rows,
3378  outer_path->pathtarget->width,
3379  0.0,
3380  work_mem,
3381  -1.0);
3382  startup_cost += sort_path.startup_cost;
3383  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3384  * outerstartsel;
3385  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3386  * (outerendsel - outerstartsel);
3387  }
3388  else
3389  {
3390  startup_cost += outer_path->startup_cost;
3391  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3392  * outerstartsel;
3393  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3394  * (outerendsel - outerstartsel);
3395  }
3396 
3397  if (innersortkeys) /* do we need to sort inner? */
3398  {
3399  cost_sort(&sort_path,
3400  root,
3401  innersortkeys,
3402  inner_path->total_cost,
3403  inner_path_rows,
3404  inner_path->pathtarget->width,
3405  0.0,
3406  work_mem,
3407  -1.0);
3408  startup_cost += sort_path.startup_cost;
3409  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3410  * innerstartsel;
3411  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3412  * (innerendsel - innerstartsel);
3413  }
3414  else
3415  {
3416  startup_cost += inner_path->startup_cost;
3417  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3418  * innerstartsel;
3419  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3420  * (innerendsel - innerstartsel);
3421  }
3422 
3423  /*
3424  * We can't yet determine whether rescanning occurs, or whether
3425  * materialization of the inner input should be done. The minimum
3426  * possible inner input cost, regardless of rescan and materialization
3427  * considerations, is inner_run_cost. We include that in
3428  * workspace->total_cost, but not yet in run_cost.
3429  */
3430 
3431  /* CPU costs left for later */
3432 
3433  /* Public result fields */
3434  workspace->startup_cost = startup_cost;
3435  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3436  /* Save private data for final_cost_mergejoin */
3437  workspace->run_cost = run_cost;
3438  workspace->inner_run_cost = inner_run_cost;
3439  workspace->outer_rows = outer_rows;
3440  workspace->inner_rows = inner_rows;
3441  workspace->outer_skip_rows = outer_skip_rows;
3442  workspace->inner_skip_rows = inner_skip_rows;
3443 }
3444 
3445 /*
3446  * final_cost_mergejoin
3447  * Final estimate of the cost and result size of a mergejoin path.
3448  *
3449  * Unlike other costsize functions, this routine makes two actual decisions:
3450  * whether the executor will need to do mark/restore, and whether we should
3451  * materialize the inner path. It would be logically cleaner to build
3452  * separate paths testing these alternatives, but that would require repeating
3453  * most of the cost calculations, which are not all that cheap. Since the
3454  * choice will not affect output pathkeys or startup cost, only total cost,
3455  * there is no possibility of wanting to keep more than one path. So it seems
3456  * best to make the decisions here and record them in the path's
3457  * skip_mark_restore and materialize_inner fields.
3458  *
3459  * Mark/restore overhead is usually required, but can be skipped if we know
3460  * that the executor need find only one match per outer tuple, and that the
3461  * mergeclauses are sufficient to identify a match.
3462  *
3463  * We materialize the inner path if we need mark/restore and either the inner
3464  * path can't support mark/restore, or it's cheaper to use an interposed
3465  * Material node to handle mark/restore.
3466  *
3467  * 'path' is already filled in except for the rows and cost fields and
3468  * skip_mark_restore and materialize_inner
3469  * 'workspace' is the result from initial_cost_mergejoin
3470  * 'extra' contains miscellaneous information about the join
3471  */
3472 void
3474  JoinCostWorkspace *workspace,
3475  JoinPathExtraData *extra)
3476 {
3477  Path *outer_path = path->jpath.outerjoinpath;
3478  Path *inner_path = path->jpath.innerjoinpath;
3479  double inner_path_rows = inner_path->rows;
3480  List *mergeclauses = path->path_mergeclauses;
3481  List *innersortkeys = path->innersortkeys;
3482  Cost startup_cost = workspace->startup_cost;
3483  Cost run_cost = workspace->run_cost;
3484  Cost inner_run_cost = workspace->inner_run_cost;
3485  double outer_rows = workspace->outer_rows;
3486  double inner_rows = workspace->inner_rows;
3487  double outer_skip_rows = workspace->outer_skip_rows;
3488  double inner_skip_rows = workspace->inner_skip_rows;
3489  Cost cpu_per_tuple,
3490  bare_inner_cost,
3491  mat_inner_cost;
3492  QualCost merge_qual_cost;
3493  QualCost qp_qual_cost;
3494  double mergejointuples,
3495  rescannedtuples;
3496  double rescanratio;
3497 
3498  /* Protect some assumptions below that rowcounts aren't zero */
3499  if (inner_path_rows <= 0)
3500  inner_path_rows = 1;
3501 
3502  /* Mark the path with the correct row estimate */
3503  if (path->jpath.path.param_info)
3504  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3505  else
3506  path->jpath.path.rows = path->jpath.path.parent->rows;
3507 
3508  /* For partial paths, scale row estimate. */
3509  if (path->jpath.path.parallel_workers > 0)
3510  {
3511  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3512 
3513  path->jpath.path.rows =
3514  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3515  }
3516 
3517  /*
3518  * We could include disable_cost in the preliminary estimate, but that
3519  * would amount to optimizing for the case where the join method is
3520  * disabled, which doesn't seem like the way to bet.
3521  */
3522  if (!enable_mergejoin)
3523  startup_cost += disable_cost;
3524 
3525  /*
3526  * Compute cost of the mergequals and qpquals (other restriction clauses)
3527  * separately.
3528  */
3529  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3530  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3531  qp_qual_cost.startup -= merge_qual_cost.startup;
3532  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3533 
3534  /*
3535  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3536  * executor will stop scanning for matches after the first match. When
3537  * all the joinclauses are merge clauses, this means we don't ever need to
3538  * back up the merge, and so we can skip mark/restore overhead.
3539  */
3540  if ((path->jpath.jointype == JOIN_SEMI ||
3541  path->jpath.jointype == JOIN_ANTI ||
3542  extra->inner_unique) &&
3545  path->skip_mark_restore = true;
3546  else
3547  path->skip_mark_restore = false;
3548 
3549  /*
3550  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3551  * here because we need an estimate done with JOIN_INNER semantics.
3552  */
3553  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3554 
3555  /*
3556  * When there are equal merge keys in the outer relation, the mergejoin
3557  * must rescan any matching tuples in the inner relation. This means
3558  * re-fetching inner tuples; we have to estimate how often that happens.
3559  *
3560  * For regular inner and outer joins, the number of re-fetches can be
3561  * estimated approximately as size of merge join output minus size of
3562  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3563  * denote the number of values of each key in the outer relation as m1,
3564  * m2, ...; in the inner relation, n1, n2, ... Then we have
3565  *
3566  * size of join = m1 * n1 + m2 * n2 + ...
3567  *
3568  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3569  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3570  * relation
3571  *
3572  * This equation works correctly for outer tuples having no inner match
3573  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3574  * are effectively subtracting those from the number of rescanned tuples,
3575  * when we should not. Can we do better without expensive selectivity
3576  * computations?
3577  *
3578  * The whole issue is moot if we are working from a unique-ified outer
3579  * input, or if we know we don't need to mark/restore at all.
3580  */
3581  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3582  rescannedtuples = 0;
3583  else
3584  {
3585  rescannedtuples = mergejointuples - inner_path_rows;
3586  /* Must clamp because of possible underestimate */
3587  if (rescannedtuples < 0)
3588  rescannedtuples = 0;
3589  }
3590 
3591  /*
3592  * We'll inflate various costs this much to account for rescanning. Note
3593  * that this is to be multiplied by something involving inner_rows, or
3594  * another number related to the portion of the inner rel we'll scan.
3595  */
3596  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3597 
3598  /*
3599  * Decide whether we want to materialize the inner input to shield it from
3600  * mark/restore and performing re-fetches. Our cost model for regular
3601  * re-fetches is that a re-fetch costs the same as an original fetch,
3602  * which is probably an overestimate; but on the other hand we ignore the
3603  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3604  * a more refined model. So we just need to inflate the inner run cost by
3605  * rescanratio.
3606  */
3607  bare_inner_cost = inner_run_cost * rescanratio;
3608 
3609  /*
3610  * When we interpose a Material node the re-fetch cost is assumed to be
3611  * just cpu_operator_cost per tuple, independently of the underlying
3612  * plan's cost; and we charge an extra cpu_operator_cost per original
3613  * fetch as well. Note that we're assuming the materialize node will
3614  * never spill to disk, since it only has to remember tuples back to the
3615  * last mark. (If there are a huge number of duplicates, our other cost
3616  * factors will make the path so expensive that it probably won't get
3617  * chosen anyway.) So we don't use cost_rescan here.
3618  *
3619  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3620  * of the generated Material node.
3621  */
3622  mat_inner_cost = inner_run_cost +
3623  cpu_operator_cost * inner_rows * rescanratio;
3624 
3625  /*
3626  * If we don't need mark/restore at all, we don't need materialization.
3627  */
3628  if (path->skip_mark_restore)
3629  path->materialize_inner = false;
3630 
3631  /*
3632  * Prefer materializing if it looks cheaper, unless the user has asked to
3633  * suppress materialization.
3634  */
3635  else if (enable_material && mat_inner_cost < bare_inner_cost)
3636  path->materialize_inner = true;
3637 
3638  /*
3639  * Even if materializing doesn't look cheaper, we *must* do it if the
3640  * inner path is to be used directly (without sorting) and it doesn't
3641  * support mark/restore.
3642  *
3643  * Since the inner side must be ordered, and only Sorts and IndexScans can
3644  * create order to begin with, and they both support mark/restore, you
3645  * might think there's no problem --- but you'd be wrong. Nestloop and
3646  * merge joins can *preserve* the order of their inputs, so they can be
3647  * selected as the input of a mergejoin, and they don't support
3648  * mark/restore at present.
3649  *
3650  * We don't test the value of enable_material here, because
3651  * materialization is required for correctness in this case, and turning
3652  * it off does not entitle us to deliver an invalid plan.
3653  */
3654  else if (innersortkeys == NIL &&
3655  !ExecSupportsMarkRestore(inner_path))
3656  path->materialize_inner = true;
3657 
3658  /*
3659  * Also, force materializing if the inner path is to be sorted and the
3660  * sort is expected to spill to disk. This is because the final merge
3661  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3662  * We don't try to adjust the cost estimates for this consideration,
3663  * though.
3664  *
3665  * Since materialization is a performance optimization in this case,
3666  * rather than necessary for correctness, we skip it if enable_material is
3667  * off.
3668  */
3669  else if (enable_material && innersortkeys != NIL &&
3670  relation_byte_size(inner_path_rows,
3671  inner_path->pathtarget->width) >
3672  (work_mem * 1024L))
3673  path->materialize_inner = true;
3674  else
3675  path->materialize_inner = false;
3676 
3677  /* Charge the right incremental cost for the chosen case */
3678  if (path->materialize_inner)
3679  run_cost += mat_inner_cost;
3680  else
3681  run_cost += bare_inner_cost;
3682 
3683  /* CPU costs */
3684 
3685  /*
3686  * The number of tuple comparisons needed is approximately number of outer
3687  * rows plus number of inner rows plus number of rescanned tuples (can we
3688  * refine this?). At each one, we need to evaluate the mergejoin quals.
3689  */
3690  startup_cost += merge_qual_cost.startup;
3691  startup_cost += merge_qual_cost.per_tuple *
3692  (outer_skip_rows + inner_skip_rows * rescanratio);
3693  run_cost += merge_qual_cost.per_tuple *
3694  ((outer_rows - outer_skip_rows) +
3695  (inner_rows - inner_skip_rows) * rescanratio);
3696 
3697  /*
3698  * For each tuple that gets through the mergejoin proper, we charge
3699  * cpu_tuple_cost plus the cost of evaluating additional restriction
3700  * clauses that are to be applied at the join. (This is pessimistic since
3701  * not all of the quals may get evaluated at each tuple.)
3702  *
3703  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3704  * evaluations here, but it's probably not worth the trouble.
3705  */
3706  startup_cost += qp_qual_cost.startup;
3707  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3708  run_cost += cpu_per_tuple * mergejointuples;
3709 
3710  /* tlist eval costs are paid per output row, not per tuple scanned */
3711  startup_cost += path->jpath.path.pathtarget->cost.startup;
3712  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3713 
3714  path->jpath.path.startup_cost = startup_cost;
3715  path->jpath.path.total_cost = startup_cost + run_cost;
3716 }
3717 
3718 /*
3719  * run mergejoinscansel() with caching
3720  */
3721 static MergeScanSelCache *
3723 {
3724  MergeScanSelCache *cache;
3725  ListCell *lc;
3726  Selectivity leftstartsel,
3727  leftendsel,
3728  rightstartsel,
3729  rightendsel;
3730  MemoryContext oldcontext;
3731 
3732  /* Do we have this result already? */
3733  foreach(lc, rinfo->scansel_cache)
3734  {
3735  cache = (MergeScanSelCache *) lfirst(lc);
3736  if (cache->opfamily == pathkey->pk_opfamily &&
3737  cache->collation == pathkey->pk_eclass->ec_collation &&
3738  cache->strategy == pathkey->pk_strategy &&
3739  cache->nulls_first == pathkey->pk_nulls_first)
3740  return cache;
3741  }
3742 
3743  /* Nope, do the computation */
3744  mergejoinscansel(root,
3745  (Node *) rinfo->clause,
3746  pathkey->pk_opfamily,
3747  pathkey->pk_strategy,
3748  pathkey->pk_nulls_first,
3749  &leftstartsel,
3750  &leftendsel,
3751  &rightstartsel,
3752  &rightendsel);
3753 
3754  /* Cache the result in suitably long-lived workspace */
3755  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3756 
3757  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
3758  cache->opfamily = pathkey->pk_opfamily;
3759  cache->collation = pathkey->pk_eclass->ec_collation;
3760  cache->strategy = pathkey->pk_strategy;
3761  cache->nulls_first = pathkey->pk_nulls_first;
3762  cache->leftstartsel = leftstartsel;
3763  cache->leftendsel = leftendsel;
3764  cache->rightstartsel = rightstartsel;
3765  cache->rightendsel = rightendsel;
3766 
3767  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
3768 
3769  MemoryContextSwitchTo(oldcontext);
3770 
3771  return cache;
3772 }
3773 
3774 /*
3775  * initial_cost_hashjoin
3776  * Preliminary estimate of the cost of a hashjoin path.
3777  *
3778  * This must quickly produce lower-bound estimates of the path's startup and
3779  * total costs. If we are unable to eliminate the proposed path from
3780  * consideration using the lower bounds, final_cost_hashjoin will be called
3781  * to obtain the final estimates.
3782  *
3783  * The exact division of labor between this function and final_cost_hashjoin
3784  * is private to them, and represents a tradeoff between speed of the initial
3785  * estimate and getting a tight lower bound. We choose to not examine the
3786  * join quals here (other than by counting the number of hash clauses),
3787  * so we can't do much with CPU costs. We do assume that
3788  * ExecChooseHashTableSize is cheap enough to use here.
3789  *
3790  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
3791  * other data to be used by final_cost_hashjoin
3792  * 'jointype' is the type of join to be performed
3793  * 'hashclauses' is the list of joinclauses to be used as hash clauses
3794  * 'outer_path' is the outer input to the join
3795  * 'inner_path' is the inner input to the join
3796  * 'extra' contains miscellaneous information about the join
3797  * 'parallel_hash' indicates that inner_path is partial and that a shared
3798  * hash table will be built in parallel
3799  */
3800 void
3802  JoinType jointype,
3803  List *hashclauses,
3804  Path *outer_path, Path *inner_path,
3805  JoinPathExtraData *extra,
3806  bool parallel_hash)
3807 {
3808  Cost startup_cost = 0;
3809  Cost run_cost = 0;
3810  double outer_path_rows = outer_path->rows;
3811  double inner_path_rows = inner_path->rows;
3812  double inner_path_rows_total = inner_path_rows;
3813  int num_hashclauses = list_length(hashclauses);
3814  int numbuckets;
3815  int numbatches;
3816  int num_skew_mcvs;
3817  size_t space_allowed; /* unused */
3818 
3819  /* cost of source data */
3820  startup_cost += outer_path->startup_cost;
3821  run_cost += outer_path->total_cost - outer_path->startup_cost;
3822  startup_cost += inner_path->total_cost;
3823 
3824  /*
3825  * Cost of computing hash function: must do it once per input tuple. We
3826  * charge one cpu_operator_cost for each column's hash function. Also,
3827  * tack on one cpu_tuple_cost per inner row, to model the costs of
3828  * inserting the row into the hashtable.
3829  *
3830  * XXX when a hashclause is more complex than a single operator, we really
3831  * should charge the extra eval costs of the left or right side, as
3832  * appropriate, here. This seems more work than it's worth at the moment.
3833  */
3834  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
3835  * inner_path_rows;
3836  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
3837 
3838  /*
3839  * If this is a parallel hash build, then the value we have for
3840  * inner_rows_total currently refers only to the rows returned by each
3841  * participant. For shared hash table size estimation, we need the total
3842  * number, so we need to undo the division.
3843  */
3844  if (parallel_hash)
3845  inner_path_rows_total *= get_parallel_divisor(inner_path);
3846 
3847  /*
3848  * Get hash table size that executor would use for inner relation.
3849  *
3850  * XXX for the moment, always assume that skew optimization will be
3851  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
3852  * trying to determine that for sure.
3853  *
3854  * XXX at some point it might be interesting to try to account for skew
3855  * optimization in the cost estimate, but for now, we don't.
3856  */
3857  ExecChooseHashTableSize(inner_path_rows_total,
3858  inner_path->pathtarget->width,
3859  true, /* useskew */
3860  parallel_hash, /* try_combined_hash_mem */
3861  outer_path->parallel_workers,
3862  &space_allowed,
3863  &numbuckets,
3864  &numbatches,
3865  &num_skew_mcvs);
3866 
3867  /*
3868  * If inner relation is too big then we will need to "batch" the join,
3869  * which implies writing and reading most of the tuples to disk an extra
3870  * time. Charge seq_page_cost per page, since the I/O should be nice and
3871  * sequential. Writing the inner rel counts as startup cost, all the rest
3872  * as run cost.
3873  */
3874  if (numbatches > 1)
3875  {
3876  double outerpages = page_size(outer_path_rows,
3877  outer_path->pathtarget->width);
3878  double innerpages = page_size(inner_path_rows,
3879  inner_path->pathtarget->width);
3880 
3881  startup_cost += seq_page_cost * innerpages;
3882  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
3883  }
3884 
3885  /* CPU costs left for later */
3886 
3887  /* Public result fields */
3888  workspace->startup_cost = startup_cost;
3889  workspace->total_cost = startup_cost + run_cost;
3890  /* Save private data for final_cost_hashjoin */
3891  workspace->run_cost = run_cost;
3892  workspace->numbuckets = numbuckets;
3893  workspace->numbatches = numbatches;
3894  workspace->inner_rows_total = inner_path_rows_total;
3895 }
3896 
3897 /*
3898  * final_cost_hashjoin
3899  * Final estimate of the cost and result size of a hashjoin path.
3900  *
3901  * Note: the numbatches estimate is also saved into 'path' for use later
3902  *
3903  * 'path' is already filled in except for the rows and cost fields and
3904  * num_batches
3905  * 'workspace' is the result from initial_cost_hashjoin
3906  * 'extra' contains miscellaneous information about the join
3907  */
3908 void
3910  JoinCostWorkspace *workspace,
3911  JoinPathExtraData *extra)
3912 {
3913  Path *outer_path = path->jpath.outerjoinpath;
3914  Path *inner_path = path->jpath.innerjoinpath;
3915  double outer_path_rows = outer_path->rows;
3916  double inner_path_rows = inner_path->rows;
3917  double inner_path_rows_total = workspace->inner_rows_total;
3918  List *hashclauses = path->path_hashclauses;
3919  Cost startup_cost = workspace->startup_cost;
3920  Cost run_cost = workspace->run_cost;
3921  int numbuckets = workspace->numbuckets;
3922  int numbatches = workspace->numbatches;
3923  Cost cpu_per_tuple;
3924  QualCost hash_qual_cost;
3925  QualCost qp_qual_cost;
3926  double hashjointuples;
3927  double virtualbuckets;
3928  Selectivity innerbucketsize;
3929  Selectivity innermcvfreq;
3930  ListCell *hcl;
3931 
3932  /* Mark the path with the correct row estimate */
3933  if (path->jpath.path.param_info)
3934  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3935  else
3936  path->jpath.path.rows = path->jpath.path.parent->rows;
3937 
3938  /* For partial paths, scale row estimate. */
3939  if (path->jpath.path.parallel_workers > 0)
3940  {
3941  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3942 
3943  path->jpath.path.rows =
3944  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3945  }
3946 
3947  /*
3948  * We could include disable_cost in the preliminary estimate, but that
3949  * would amount to optimizing for the case where the join method is
3950  * disabled, which doesn't seem like the way to bet.
3951  */
3952  if (!enable_hashjoin)
3953  startup_cost += disable_cost;
3954 
3955  /* mark the path with estimated # of batches */
3956  path->num_batches = numbatches;
3957 
3958  /* store the total number of tuples (sum of partial row estimates) */
3959  path->inner_rows_total = inner_path_rows_total;
3960 
3961  /* and compute the number of "virtual" buckets in the whole join */
3962  virtualbuckets = (double) numbuckets * (double) numbatches;
3963 
3964  /*
3965  * Determine bucketsize fraction and MCV frequency for the inner relation.
3966  * We use the smallest bucketsize or MCV frequency estimated for any
3967  * individual hashclause; this is undoubtedly conservative.
3968  *
3969  * BUT: if inner relation has been unique-ified, we can assume it's good
3970  * for hashing. This is important both because it's the right answer, and
3971  * because we avoid contaminating the cache with a value that's wrong for
3972  * non-unique-ified paths.
3973  */
3974  if (IsA(inner_path, UniquePath))
3975  {
3976  innerbucketsize = 1.0 / virtualbuckets;
3977  innermcvfreq = 0.0;
3978  }
3979  else
3980  {
3981  innerbucketsize = 1.0;
3982  innermcvfreq = 1.0;
3983  foreach(hcl, hashclauses)
3984  {
3985  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3986  Selectivity thisbucketsize;
3987  Selectivity thismcvfreq;
3988 
3989  /*
3990  * First we have to figure out which side of the hashjoin clause
3991  * is the inner side.
3992  *
3993  * Since we tend to visit the same clauses over and over when
3994  * planning a large query, we cache the bucket stats estimates in
3995  * the RestrictInfo node to avoid repeated lookups of statistics.
3996  */
3997  if (bms_is_subset(restrictinfo->right_relids,
3998  inner_path->parent->relids))
3999  {
4000  /* righthand side is inner */
4001  thisbucketsize = restrictinfo->right_bucketsize;
4002  if (thisbucketsize < 0)
4003  {
4004  /* not cached yet */
4006  get_rightop(restrictinfo->clause),
4007  virtualbuckets,
4008  &restrictinfo->right_mcvfreq,
4009  &restrictinfo->right_bucketsize);
4010  thisbucketsize = restrictinfo->right_bucketsize;
4011  }
4012  thismcvfreq = restrictinfo->right_mcvfreq;
4013  }
4014  else
4015  {
4016  Assert(bms_is_subset(restrictinfo->left_relids,
4017  inner_path->parent->relids));
4018  /* lefthand side is inner */
4019  thisbucketsize = restrictinfo->left_bucketsize;
4020  if (thisbucketsize < 0)
4021  {
4022  /* not cached yet */
4024  get_leftop(restrictinfo->clause),
4025  virtualbuckets,
4026  &restrictinfo->left_mcvfreq,
4027  &restrictinfo->left_bucketsize);
4028  thisbucketsize = restrictinfo->left_bucketsize;
4029  }
4030  thismcvfreq = restrictinfo->left_mcvfreq;
4031  }
4032 
4033  if (innerbucketsize > thisbucketsize)
4034  innerbucketsize = thisbucketsize;
4035  if (innermcvfreq > thismcvfreq)
4036  innermcvfreq = thismcvfreq;
4037  }
4038  }
4039 
4040  /*
4041  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4042  * want to hash unless there is really no other alternative, so apply
4043  * disable_cost. (The executor normally copes with excessive memory usage
4044  * by splitting batches, but obviously it cannot separate equal values
4045  * that way, so it will be unable to drive the batch size below hash_mem
4046  * when this is true.)
4047  */
4048  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4049  inner_path->pathtarget->width) > get_hash_memory_limit())
4050  startup_cost += disable_cost;
4051 
4052  /*
4053  * Compute cost of the hashquals and qpquals (other restriction clauses)
4054  * separately.
4055  */
4056  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4057  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4058  qp_qual_cost.startup -= hash_qual_cost.startup;
4059  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4060 
4061  /* CPU costs */
4062 
4063  if (path->jpath.jointype == JOIN_SEMI ||
4064  path->jpath.jointype == JOIN_ANTI ||
4065  extra->inner_unique)
4066  {
4067  double outer_matched_rows;
4068  Selectivity inner_scan_frac;
4069 
4070  /*
4071  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4072  * executor will stop after the first match.
4073  *
4074  * For an outer-rel row that has at least one match, we can expect the
4075  * bucket scan to stop after a fraction 1/(match_count+1) of the
4076  * bucket's rows, if the matches are evenly distributed. Since they
4077  * probably aren't quite evenly distributed, we apply a fuzz factor of
4078  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4079  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4080  * at least 1, no such clamp is needed now.)
4081  */
4082  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4083  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4084 
4085  startup_cost += hash_qual_cost.startup;
4086  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4087  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4088 
4089  /*
4090  * For unmatched outer-rel rows, the picture is quite a lot different.
4091  * In the first place, there is no reason to assume that these rows
4092  * preferentially hit heavily-populated buckets; instead assume they
4093  * are uncorrelated with the inner distribution and so they see an
4094  * average bucket size of inner_path_rows / virtualbuckets. In the
4095  * second place, it seems likely that they will have few if any exact
4096  * hash-code matches and so very few of the tuples in the bucket will
4097  * actually require eval of the hash quals. We don't have any good
4098  * way to estimate how many will, but for the moment assume that the
4099  * effective cost per bucket entry is one-tenth what it is for
4100  * matchable tuples.
4101  */
4102  run_cost += hash_qual_cost.per_tuple *
4103  (outer_path_rows - outer_matched_rows) *
4104  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4105 
4106  /* Get # of tuples that will pass the basic join */
4107  if (path->jpath.jointype == JOIN_ANTI)
4108  hashjointuples = outer_path_rows - outer_matched_rows;
4109  else
4110  hashjointuples = outer_matched_rows;
4111  }
4112  else
4113  {
4114  /*
4115  * The number of tuple comparisons needed is the number of outer
4116  * tuples times the typical number of tuples in a hash bucket, which
4117  * is the inner relation size times its bucketsize fraction. At each
4118  * one, we need to evaluate the hashjoin quals. But actually,
4119  * charging the full qual eval cost at each tuple is pessimistic,
4120  * since we don't evaluate the quals unless the hash values match
4121  * exactly. For lack of a better idea, halve the cost estimate to
4122  * allow for that.
4123  */
4124  startup_cost += hash_qual_cost.startup;
4125  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4126  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4127 
4128  /*
4129  * Get approx # tuples passing the hashquals. We use
4130  * approx_tuple_count here because we need an estimate done with
4131  * JOIN_INNER semantics.
4132  */
4133  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4134  }
4135 
4136  /*
4137  * For each tuple that gets through the hashjoin proper, we charge
4138  * cpu_tuple_cost plus the cost of evaluating additional restriction
4139  * clauses that are to be applied at the join. (This is pessimistic since
4140  * not all of the quals may get evaluated at each tuple.)
4141  */
4142  startup_cost += qp_qual_cost.startup;
4143  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4144  run_cost += cpu_per_tuple * hashjointuples;
4145 
4146  /* tlist eval costs are paid per output row, not per tuple scanned */
4147  startup_cost += path->jpath.path.pathtarget->cost.startup;
4148  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4149 
4150  path->jpath.path.startup_cost = startup_cost;
4151  path->jpath.path.total_cost = startup_cost + run_cost;
4152 }
4153 
4154 
4155 /*
4156  * cost_subplan
4157  * Figure the costs for a SubPlan (or initplan).
4158  *
4159  * Note: we could dig the subplan's Plan out of the root list, but in practice
4160  * all callers have it handy already, so we make them pass it.
4161  */
4162 void
4163 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
4164 {
4165  QualCost sp_cost;
4166 
4167  /* Figure any cost for evaluating the testexpr */
4168  cost_qual_eval(&sp_cost,
4169  make_ands_implicit((Expr *) subplan->testexpr),
4170  root);
4171 
4172  if (subplan->useHashTable)
4173  {
4174  /*
4175  * If we are using a hash table for the subquery outputs, then the
4176  * cost of evaluating the query is a one-time cost. We charge one
4177  * cpu_operator_cost per tuple for the work of loading the hashtable,
4178  * too.
4179  */
4180  sp_cost.startup += plan->total_cost +
4181  cpu_operator_cost * plan->plan_rows;
4182 
4183  /*
4184  * The per-tuple costs include the cost of evaluating the lefthand
4185  * expressions, plus the cost of probing the hashtable. We already
4186  * accounted for the lefthand expressions as part of the testexpr, and
4187  * will also have counted one cpu_operator_cost for each comparison
4188  * operator. That is probably too low for the probing cost, but it's
4189  * hard to make a better estimate, so live with it for now.
4190  */
4191  }
4192  else
4193  {
4194  /*
4195  * Otherwise we will be rescanning the subplan output on each
4196  * evaluation. We need to estimate how much of the output we will
4197  * actually need to scan. NOTE: this logic should agree with the
4198  * tuple_fraction estimates used by make_subplan() in
4199  * plan/subselect.c.
4200  */
4201  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4202 
4203  if (subplan->subLinkType == EXISTS_SUBLINK)
4204  {
4205  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4206  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4207  }
4208  else if (subplan->subLinkType == ALL_SUBLINK ||
4209  subplan->subLinkType == ANY_SUBLINK)
4210  {
4211  /* assume we need 50% of the tuples */
4212  sp_cost.per_tuple += 0.50 * plan_run_cost;
4213  /* also charge a cpu_operator_cost per row examined */
4214  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4215  }
4216  else
4217  {
4218  /* assume we need all tuples */
4219  sp_cost.per_tuple += plan_run_cost;
4220  }
4221 
4222  /*
4223  * Also account for subplan's startup cost. If the subplan is
4224  * uncorrelated or undirect correlated, AND its topmost node is one
4225  * that materializes its output, assume that we'll only need to pay
4226  * its startup cost once; otherwise assume we pay the startup cost
4227  * every time.
4228  */
4229  if (subplan->parParam == NIL &&
4231  sp_cost.startup += plan->startup_cost;
4232  else
4233  sp_cost.per_tuple += plan->startup_cost;
4234  }
4235 
4236  subplan->startup_cost = sp_cost.startup;
4237  subplan->per_call_cost = sp_cost.per_tuple;
4238 }
4239 
4240 
4241 /*
4242  * cost_rescan
4243  * Given a finished Path, estimate the costs of rescanning it after
4244  * having done so the first time. For some Path types a rescan is
4245  * cheaper than an original scan (if no parameters change), and this
4246  * function embodies knowledge about that. The default is to return
4247  * the same costs stored in the Path. (Note that the cost estimates
4248  * actually stored in Paths are always for first scans.)
4249  *
4250  * This function is not currently intended to model effects such as rescans
4251  * being cheaper due to disk block caching; what we are concerned with is
4252  * plan types wherein the executor caches results explicitly, or doesn't
4253  * redo startup calculations, etc.
4254  */
4255 static void
4257  Cost *rescan_startup_cost, /* output parameters */
4258  Cost *rescan_total_cost)
4259 {
4260  switch (path->pathtype)
4261  {
4262  case T_FunctionScan:
4263 
4264  /*
4265  * Currently, nodeFunctionscan.c always executes the function to
4266  * completion before returning any rows, and caches the results in
4267  * a tuplestore. So the function eval cost is all startup cost
4268  * and isn't paid over again on rescans. However, all run costs
4269  * will be paid over again.
4270  */
4271  *rescan_startup_cost = 0;
4272  *rescan_total_cost = path->total_cost - path->startup_cost;
4273  break;
4274  case T_HashJoin:
4275 
4276  /*
4277  * If it's a single-batch join, we don't need to rebuild the hash
4278  * table during a rescan.
4279  */
4280  if (((HashPath *) path)->num_batches == 1)
4281  {
4282  /* Startup cost is exactly the cost of hash table building */
4283  *rescan_startup_cost = 0;
4284  *rescan_total_cost = path->total_cost - path->startup_cost;
4285  }
4286  else
4287  {
4288  /* Otherwise, no special treatment */
4289  *rescan_startup_cost = path->startup_cost;
4290  *rescan_total_cost = path->total_cost;
4291  }
4292  break;
4293  case T_CteScan:
4294  case T_WorkTableScan:
4295  {
4296  /*
4297  * These plan types materialize their final result in a
4298  * tuplestore or tuplesort object. So the rescan cost is only
4299  * cpu_tuple_cost per tuple, unless the result is large enough
4300  * to spill to disk.
4301  */
4302  Cost run_cost = cpu_tuple_cost * path->rows;
4303  double nbytes = relation_byte_size(path->rows,
4304  path->pathtarget->width);
4305  long work_mem_bytes = work_mem * 1024L;
4306 
4307  if (nbytes > work_mem_bytes)
4308  {
4309  /* It will spill, so account for re-read cost */
4310  double npages = ceil(nbytes / BLCKSZ);
4311 
4312  run_cost += seq_page_cost * npages;
4313  }
4314  *rescan_startup_cost = 0;
4315  *rescan_total_cost = run_cost;
4316  }
4317  break;
4318  case T_Material:
4319  case T_Sort:
4320  {
4321  /*
4322  * These plan types not only materialize their results, but do
4323  * not implement qual filtering or projection. So they are
4324  * even cheaper to rescan than the ones above. We charge only
4325  * cpu_operator_cost per tuple. (Note: keep that in sync with
4326  * the run_cost charge in cost_sort, and also see comments in
4327  * cost_material before you change it.)
4328  */
4329  Cost run_cost = cpu_operator_cost * path->rows;
4330  double nbytes = relation_byte_size(path->rows,
4331  path->pathtarget->width);
4332  long work_mem_bytes = work_mem * 1024L;
4333 
4334  if (nbytes > work_mem_bytes)
4335  {
4336  /* It will spill, so account for re-read cost */
4337  double npages = ceil(nbytes / BLCKSZ);
4338 
4339  run_cost += seq_page_cost * npages;
4340  }
4341  *rescan_startup_cost = 0;
4342  *rescan_total_cost = run_cost;
4343  }
4344  break;
4345  case T_Memoize:
4346  /* All the hard work is done by cost_memoize_rescan */
4347  cost_memoize_rescan(root, (MemoizePath *) path,
4348  rescan_startup_cost, rescan_total_cost);
4349  break;
4350  default:
4351  *rescan_startup_cost = path->startup_cost;
4352  *rescan_total_cost = path->total_cost;
4353  break;
4354  }
4355 }
4356 
4357 
4358 /*
4359  * cost_qual_eval
4360  * Estimate the CPU costs of evaluating a WHERE clause.
4361  * The input can be either an implicitly-ANDed list of boolean
4362  * expressions, or a list of RestrictInfo nodes. (The latter is
4363  * preferred since it allows caching of the results.)
4364  * The result includes both a one-time (startup) component,
4365  * and a per-evaluation component.
4366  */
4367 void
4369 {
4370  cost_qual_eval_context context;
4371  ListCell *l;
4372 
4373  context.root = root;
4374  context.total.startup = 0;
4375  context.total.per_tuple = 0;
4376 
4377  /* We don't charge any cost for the implicit ANDing at top level ... */
4378 
4379  foreach(l, quals)
4380  {
4381  Node *qual = (Node *) lfirst(l);
4382 
4383  cost_qual_eval_walker(qual, &context);
4384  }
4385 
4386  *cost = context.total;
4387 }
4388 
4389 /*
4390  * cost_qual_eval_node
4391  * As above, for a single RestrictInfo or expression.
4392  */
4393 void
4395 {
4396  cost_qual_eval_context context;
4397 
4398  context.root = root;
4399  context.total.startup = 0;
4400  context.total.per_tuple = 0;
4401 
4402  cost_qual_eval_walker(qual, &context);
4403 
4404  *cost = context.total;
4405 }
4406 
4407 static bool
4409 {
4410  if (node == NULL)
4411  return false;
4412 
4413  /*
4414  * RestrictInfo nodes contain an eval_cost field reserved for this
4415  * routine's use, so that it's not necessary to evaluate the qual clause's
4416  * cost more than once. If the clause's cost hasn't been computed yet,
4417  * the field's startup value will contain -1.
4418  */
4419  if (IsA(node, RestrictInfo))
4420  {
4421  RestrictInfo *rinfo = (RestrictInfo *) node;
4422 
4423  if (rinfo->eval_cost.startup < 0)
4424  {
4425  cost_qual_eval_context locContext;
4426 
4427  locContext.root = context->root;
4428  locContext.total.startup = 0;
4429  locContext.total.per_tuple = 0;
4430 
4431  /*
4432  * For an OR clause, recurse into the marked-up tree so that we
4433  * set the eval_cost for contained RestrictInfos too.
4434  */
4435  if (rinfo->orclause)
4436  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4437  else
4438  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4439 
4440  /*
4441  * If the RestrictInfo is marked pseudoconstant, it will be tested
4442  * only once, so treat its cost as all startup cost.
4443  */
4444  if (rinfo->pseudoconstant)
4445  {
4446  /* count one execution during startup */
4447  locContext.total.startup += locContext.total.per_tuple;
4448  locContext.total.per_tuple = 0;
4449  }
4450  rinfo->eval_cost = locContext.total;
4451  }
4452  context->total.startup += rinfo->eval_cost.startup;
4453  context->total.per_tuple += rinfo->eval_cost.per_tuple;
4454  /* do NOT recurse into children */
4455  return false;
4456  }
4457 
4458  /*
4459  * For each operator or function node in the given tree, we charge the
4460  * estimated execution cost given by pg_proc.procost (remember to multiply
4461  * this by cpu_operator_cost).
4462  *
4463  * Vars and Consts are charged zero, and so are boolean operators (AND,
4464  * OR, NOT). Simplistic, but a lot better than no model at all.
4465  *
4466  * Should we try to account for the possibility of short-circuit
4467  * evaluation of AND/OR? Probably *not*, because that would make the
4468  * results depend on the clause ordering, and we are not in any position
4469  * to expect that the current ordering of the clauses is the one that's
4470  * going to end up being used. The above per-RestrictInfo caching would
4471  * not mix well with trying to re-order clauses anyway.
4472  *
4473  * Another issue that is entirely ignored here is that if a set-returning
4474  * function is below top level in the tree, the functions/operators above
4475  * it will need to be evaluated multiple times. In practical use, such
4476  * cases arise so seldom as to not be worth the added complexity needed;
4477  * moreover, since our rowcount estimates for functions tend to be pretty
4478  * phony, the results would also be pretty phony.
4479  */
4480  if (IsA(node, FuncExpr))
4481  {
4482  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4483  &context->total);
4484  }
4485  else if (IsA(node, OpExpr) ||
4486  IsA(node, DistinctExpr) ||
4487  IsA(node, NullIfExpr))
4488  {
4489  /* rely on struct equivalence to treat these all alike */
4490  set_opfuncid((OpExpr *) node);
4491  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4492  &context->total);
4493  }
4494  else if (IsA(node, ScalarArrayOpExpr))
4495  {
4496  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4497  Node *arraynode = (Node *) lsecond(saop->args);
4498  QualCost sacosts;
4499  QualCost hcosts;
4500  int estarraylen = estimate_array_length(arraynode);
4501 
4502  set_sa_opfuncid(saop);
4503  sacosts.startup = sacosts.per_tuple = 0;
4504  add_function_cost(context->root, saop->opfuncid, NULL,
4505  &sacosts);
4506 
4507  if (OidIsValid(saop->hashfuncid))
4508  {
4509  /* Handle costs for hashed ScalarArrayOpExpr */
4510  hcosts.startup = hcosts.per_tuple = 0;
4511 
4512  add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
4513  context->total.startup += sacosts.startup + hcosts.startup;
4514 
4515  /* Estimate the cost of building the hashtable. */
4516  context->total.startup += estarraylen * hcosts.per_tuple;
4517 
4518  /*
4519  * XXX should we charge a little bit for sacosts.per_tuple when
4520  * building the table, or is it ok to assume there will be zero
4521  * hash collision?
4522  */
4523 
4524  /*
4525  * Charge for hashtable lookups. Charge a single hash and a
4526  * single comparison.
4527  */
4528  context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
4529  }
4530  else
4531  {
4532  /*
4533  * Estimate that the operator will be applied to about half of the
4534  * array elements before the answer is determined.
4535  */
4536  context->total.startup += sacosts.startup;
4537  context->total.per_tuple += sacosts.per_tuple *
4538  estimate_array_length(arraynode) * 0.5;
4539  }
4540  }
4541  else if (IsA(node, Aggref) ||
4542  IsA(node, WindowFunc))
4543  {
4544  /*
4545  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4546  * ie, zero execution cost in the current model, because they behave
4547  * essentially like Vars at execution. We disregard the costs of
4548  * their input expressions for the same reason. The actual execution
4549  * costs of the aggregate/window functions and their arguments have to
4550  * be factored into plan-node-specific costing of the Agg or WindowAgg
4551  * plan node.
4552  */
4553  return false; /* don't recurse into children */
4554  }
4555  else if (IsA(node, GroupingFunc))
4556  {
4557  /* Treat this as having cost 1 */
4558  context->total.per_tuple += cpu_operator_cost;
4559  return false; /* don't recurse into children */
4560  }
4561  else if (IsA(node, CoerceViaIO))
4562  {
4563  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4564  Oid iofunc;
4565  Oid typioparam;
4566  bool typisvarlena;
4567 
4568  /* check the result type's input function */
4569  getTypeInputInfo(iocoerce->resulttype,
4570  &iofunc, &typioparam);
4571  add_function_cost(context->root, iofunc, NULL,
4572  &context->total);
4573  /* check the input type's output function */
4574  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4575  &iofunc, &typisvarlena);
4576  add_function_cost(context->root, iofunc, NULL,
4577  &context->total);
4578  }
4579  else if (IsA(node, ArrayCoerceExpr))
4580  {
4581  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4582  QualCost perelemcost;
4583 
4584  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4585  context->root);
4586  context->total.startup += perelemcost.startup;
4587  if (perelemcost.per_tuple > 0)
4588  context->total.per_tuple += perelemcost.per_tuple *
4589  estimate_array_length((Node *) acoerce->arg);
4590  }
4591  else if (IsA(node, RowCompareExpr))
4592  {
4593  /* Conservatively assume we will check all the columns */
4594  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4595  ListCell *lc;
4596 
4597  foreach(lc, rcexpr->opnos)
4598  {
4599  Oid opid = lfirst_oid(lc);
4600 
4601  add_function_cost(context->root, get_opcode(opid), NULL,
4602  &context->total);
4603  }
4604  }
4605  else if (IsA(node, MinMaxExpr) ||
4606  IsA(node, XmlExpr) ||
4607  IsA(node, CoerceToDomain) ||
4608  IsA(node, NextValueExpr))
4609  {
4610  /* Treat all these as having cost 1 */
4611  context->total.per_tuple += cpu_operator_cost;
4612  }
4613  else if (IsA(node, CurrentOfExpr))
4614  {
4615  /* Report high cost to prevent selection of anything but TID scan */
4616  context->total.startup += disable_cost;
4617  }
4618  else if (IsA(node, SubLink))
4619  {
4620  /* This routine should not be applied to un-planned expressions */
4621  elog(ERROR, "cannot handle unplanned sub-select");
4622  }
4623  else if (IsA(node, SubPlan))
4624  {
4625  /*
4626  * A subplan node in an expression typically indicates that the
4627  * subplan will be executed on each evaluation, so charge accordingly.
4628  * (Sub-selects that can be executed as InitPlans have already been
4629  * removed from the expression.)
4630  */
4631  SubPlan *subplan = (SubPlan *) node;
4632 
4633  context->total.startup += subplan->startup_cost;
4634  context->total.per_tuple += subplan->per_call_cost;
4635 
4636  /*
4637  * We don't want to recurse into the testexpr, because it was already
4638  * counted in the SubPlan node's costs. So we're done.
4639  */
4640  return false;
4641  }
4642  else if (IsA(node, AlternativeSubPlan))
4643  {
4644  /*
4645  * Arbitrarily use the first alternative plan for costing. (We should
4646  * certainly only include one alternative, and we don't yet have
4647  * enough information to know which one the executor is most likely to
4648  * use.)
4649  */
4650  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4651 
4652  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4653  context);
4654  }
4655  else if (IsA(node, PlaceHolderVar))
4656  {
4657  /*
4658  * A PlaceHolderVar should be given cost zero when considering general
4659  * expression evaluation costs. The expense of doing the contained
4660  * expression is charged as part of the tlist eval costs of the scan
4661  * or join where the PHV is first computed (see set_rel_width and
4662  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4663  * double-counting the cost for each level of plan that the PHV
4664  * bubbles up through. Hence, return without recursing into the
4665  * phexpr.
4666  */
4667  return false;
4668  }
4669 
4670  /* recurse into children */
4672  (void *) context);
4673 }
4674 
4675 /*
4676  * get_restriction_qual_cost
4677  * Compute evaluation costs of a baserel's restriction quals, plus any
4678  * movable join quals that have been pushed down to the scan.
4679  * Results are returned into *qpqual_cost.
4680  *
4681  * This is a convenience subroutine that works for seqscans and other cases
4682  * where all the given quals will be evaluated the hard way. It's not useful
4683  * for cost_index(), for example, where the index machinery takes care of
4684  * some of the quals. We assume baserestrictcost was previously set by
4685  * set_baserel_size_estimates().
4686  */
4687 static void
4689  ParamPathInfo *param_info,
4690  QualCost *qpqual_cost)
4691 {
4692  if (param_info)
4693  {
4694  /* Include costs of pushed-down clauses */
4695  cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
4696 
4697  qpqual_cost->startup += baserel->baserestrictcost.startup;
4698  qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
4699  }
4700  else
4701  *qpqual_cost = baserel->baserestrictcost;
4702 }
4703 
4704 
4705 /*
4706  * compute_semi_anti_join_factors
4707  * Estimate how much of the inner input a SEMI, ANTI, or inner_unique join
4708  * can be expected to scan.
4709  *
4710  * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
4711  * inner rows as soon as it finds a match to the current outer row.
4712  * The same happens if we have detected the inner rel is unique.
4713  * We should therefore adjust some of the cost components for this effect.
4714  * This function computes some estimates needed for these adjustments.
4715  * These estimates will be the same regardless of the particular paths used
4716  * for the outer and inner relation, so we compute these once and then pass
4717  * them to all the join cost estimation functions.
4718  *
4719  * Input parameters:
4720  * joinrel: join relation under consideration
4721  * outerrel: outer relation under consideration
4722  * innerrel: inner relation under consideration
4723  * jointype: if not JOIN_SEMI or JOIN_ANTI, we assume it's inner_unique
4724  * sjinfo: SpecialJoinInfo relevant to this join
4725  * restrictlist: join quals
4726  * Output parameters:
4727  * *semifactors is filled in (see pathnodes.h for field definitions)
4728  */
4729 void
4731  RelOptInfo *joinrel,
4732  RelOptInfo *outerrel,
4733  RelOptInfo *innerrel,
4734  JoinType jointype,
4735  SpecialJoinInfo *sjinfo,
4736  List *restrictlist,
4737  SemiAntiJoinFactors *semifactors)
4738 {
4739  Selectivity jselec;
4740  Selectivity nselec;
4741  Selectivity avgmatch;
4742  SpecialJoinInfo norm_sjinfo;
4743  List *joinquals;
4744  ListCell *l;
4745 
4746  /*
4747  * In an ANTI join, we must ignore clauses that are "pushed down", since
4748  * those won't affect the match logic. In a SEMI join, we do not
4749  * distinguish joinquals from "pushed down" quals, so just use the whole
4750  * restrictinfo list. For other outer join types, we should consider only
4751  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4752  */
4753  if (IS_OUTER_JOIN(jointype))
4754  {
4755  joinquals = NIL;
4756  foreach(l, restrictlist)
4757  {
4758  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4759 
4760  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4761  joinquals = lappend(joinquals, rinfo);
4762  }
4763  }
4764  else
4765  joinquals = restrictlist;
4766 
4767  /*
4768  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4769  */
4770  jselec = clauselist_selectivity(root,
4771  joinquals,
4772  0,
4773  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4774  sjinfo);
4775 
4776  /*
4777  * Also get the normal inner-join selectivity of the join clauses.
4778  */
4779  norm_sjinfo.type = T_SpecialJoinInfo;
4780  norm_sjinfo.min_lefthand = outerrel->relids;
4781  norm_sjinfo.min_righthand = innerrel->relids;
4782  norm_sjinfo.syn_lefthand = outerrel->relids;
4783  norm_sjinfo.syn_righthand = innerrel->relids;
4784  norm_sjinfo.jointype = JOIN_INNER;
4785  /* we don't bother trying to make the remaining fields valid */
4786  norm_sjinfo.lhs_strict = false;
4787  norm_sjinfo.delay_upper_joins = false;
4788  norm_sjinfo.semi_can_btree = false;
4789  norm_sjinfo.semi_can_hash = false;
4790  norm_sjinfo.semi_operators = NIL;
4791  norm_sjinfo.semi_rhs_exprs = NIL;
4792 
4793  nselec = clauselist_selectivity(root,
4794  joinquals,
4795  0,
4796  JOIN_INNER,
4797  &norm_sjinfo);
4798 
4799  /* Avoid leaking a lot of ListCells */
4800  if (IS_OUTER_JOIN(jointype))
4801  list_free(joinquals);
4802 
4803  /*
4804  * jselec can be interpreted as the fraction of outer-rel rows that have
4805  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4806  * the fraction of the Cartesian product that matches. So, the average
4807  * number of matches for each outer-rel row that has at least one match is
4808  * nselec * inner_rows / jselec.
4809  *
4810  * Note: it is correct to use the inner rel's "rows" count here, even
4811  * though we might later be considering a parameterized inner path with
4812  * fewer rows. This is because we have included all the join clauses in
4813  * the selectivity estimate.
4814  */
4815  if (jselec > 0) /* protect against zero divide */
4816  {
4817  avgmatch = nselec * innerrel->rows / jselec;
4818  /* Clamp to sane range */
4819  avgmatch = Max(1.0, avgmatch);
4820  }
4821  else
4822  avgmatch = 1.0;
4823 
4824  semifactors->outer_match_frac = jselec;
4825  semifactors->match_count = avgmatch;
4826 }
4827 
4828 /*
4829  * has_indexed_join_quals
4830  * Check whether all the joinquals of a nestloop join are used as
4831  * inner index quals.
4832  *
4833  * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
4834  * indexscan) that uses all the joinquals as indexquals, we can assume that an
4835  * unmatched outer tuple is cheap to process, whereas otherwise it's probably
4836  * expensive.
4837  */
4838 static bool
4840 {
4841  JoinPath *joinpath = &path->jpath;
4842  Relids joinrelids = joinpath->path.parent->relids;
4843  Path *innerpath = joinpath->innerjoinpath;
4844  List *indexclauses;
4845  bool found_one;
4846  ListCell *lc;
4847 
4848  /* If join still has quals to evaluate, it's not fast */
4849  if (joinpath->joinrestrictinfo != NIL)
4850  return false;
4851  /* Nor if the inner path isn't parameterized at all */
4852  if (innerpath->param_info == NULL)
4853  return false;
4854 
4855  /* Find the indexclauses list for the inner scan */
4856  switch (innerpath->pathtype)
4857  {
4858  case T_IndexScan:
4859  case T_IndexOnlyScan:
4860  indexclauses = ((IndexPath *) innerpath)->indexclauses;
4861  break;
4862  case T_BitmapHeapScan:
4863  {
4864  /* Accept only a simple bitmap scan, not AND/OR cases */
4865  Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
4866 
4867  if (IsA(bmqual, IndexPath))
4868  indexclauses = ((IndexPath *) bmqual)->indexclauses;
4869  else
4870  return false;
4871  break;
4872  }
4873  default:
4874 
4875  /*
4876  * If it's not a simple indexscan, it probably doesn't run quickly
4877  * for zero rows out, even if it's a parameterized path using all
4878  * the joinquals.
4879  */
4880  return false;
4881  }
4882 
4883  /*
4884  * Examine the inner path's param clauses. Any that are from the outer
4885  * path must be found in the indexclauses list, either exactly or in an
4886  * equivalent form generated by equivclass.c. Also, we must find at least
4887  * one such clause, else it's a clauseless join which isn't fast.
4888  */
4889  found_one = false;
4890  foreach(lc, innerpath->param_info->ppi_clauses)
4891  {
4892  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4893 
4894  if (join_clause_is_movable_into(rinfo,
4895  innerpath->parent->relids,
4896  joinrelids))
4897  {
4898  if (!is_redundant_with_indexclauses(rinfo, indexclauses))
4899  return false;
4900  found_one = true;
4901  }
4902  }
4903  return found_one;
4904 }
4905 
4906 
4907 /*
4908  * approx_tuple_count
4909  * Quick-and-dirty estimation of the number of join rows passing
4910  * a set of qual conditions.
4911  *
4912  * The quals can be either an implicitly-ANDed list of boolean expressions,
4913  * or a list of RestrictInfo nodes (typically the latter).
4914  *
4915  * We intentionally compute the selectivity under JOIN_INNER rules, even
4916  * if it's some type of outer join. This is appropriate because we are
4917  * trying to figure out how many tuples pass the initial merge or hash
4918  * join step.
4919  *
4920  * This is quick-and-dirty because we bypass clauselist_selectivity, and
4921  * simply multiply the independent clause selectivities together. Now
4922  * clauselist_selectivity often can't do any better than that anyhow, but
4923  * for some situations (such as range constraints) it is smarter. However,
4924  * we can't effectively cache the results of clauselist_selectivity, whereas
4925  * the individual clause selectivities can be and are cached.
4926  *
4927  * Since we are only using the results to estimate how many potential
4928  * output tuples are generated and passed through qpqual checking, it
4929  * seems OK to live with the approximation.
4930  */
4931 static double
4933 {
4934  double tuples;
4935  double outer_tuples = path->outerjoinpath->rows;
4936  double inner_tuples = path->innerjoinpath->rows;
4937  SpecialJoinInfo sjinfo;
4938  Selectivity selec = 1.0;
4939  ListCell *l;
4940 
4941  /*
4942  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
4943  */
4944  sjinfo.type = T_SpecialJoinInfo;
4945  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
4946  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
4947  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
4948  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
4949  sjinfo.jointype = JOIN_INNER;
4950  /* we don't bother trying to make the remaining fields valid */
4951  sjinfo.lhs_strict = false;
4952  sjinfo.delay_upper_joins = false;
4953  sjinfo.semi_can_btree = false;
4954  sjinfo.semi_can_hash = false;
4955  sjinfo.semi_operators = NIL;
4956  sjinfo.semi_rhs_exprs = NIL;
4957 
4958  /* Get the approximate selectivity */
4959  foreach(l, quals)
4960  {
4961  Node *qual = (Node *) lfirst(l);
4962 
4963  /* Note that clause_selectivity will be able to cache its result */
4964  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
4965  }
4966 
4967  /* Apply it to the input relation sizes */
4968  tuples = selec * outer_tuples * inner_tuples;
4969 
4970  return clamp_row_est(tuples);
4971 }
4972 
4973 
4974 /*
4975  * set_baserel_size_estimates
4976  * Set the size estimates for the given base relation.
4977  *
4978  * The rel's targetlist and restrictinfo list must have been constructed
4979  * already, and rel->tuples must be set.
4980  *
4981  * We set the following fields of the rel node:
4982  * rows: the estimated number of output tuples (after applying
4983  * restriction clauses).
4984  * width: the estimated average output tuple width in bytes.
4985  * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
4986  */
4987 void
4989 {
4990  double nrows;
4991 
4992  /* Should only be applied to base relations */
4993  Assert(rel->relid > 0);
4994 
4995  nrows = rel->tuples *
4997  rel->baserestrictinfo,
4998  0,
4999  JOIN_INNER,
5000  NULL);
5001 
5002  rel->rows = clamp_row_est(nrows);
5003 
5005 
5006  set_rel_width(root, rel);
5007 }
5008 
5009 /*
5010  * get_parameterized_baserel_size
5011  * Make a size estimate for a parameterized scan of a base relation.
5012  *
5013  * 'param_clauses' lists the additional join clauses to be used.
5014  *
5015  * set_baserel_size_estimates must have been applied already.
5016  */
5017 double
5019  List *param_clauses)
5020 {
5021  List *allclauses;
5022  double nrows;
5023 
5024  /*
5025  * Estimate the number of rows returned by the parameterized scan, knowing
5026  * that it will apply all the extra join clauses as well as the rel's own
5027  * restriction clauses. Note that we force the clauses to be treated as
5028  * non-join clauses during selectivity estimation.
5029  */
5030  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5031  nrows = rel->tuples *
5033  allclauses,
5034  rel->relid, /* do not use 0! */
5035  JOIN_INNER,
5036  NULL);
5037  nrows = clamp_row_est(nrows);
5038  /* For safety, make sure result is not more than the base estimate */
5039  if (nrows > rel->rows)
5040  nrows = rel->rows;
5041  return nrows;
5042 }
5043 
5044 /*
5045  * set_joinrel_size_estimates
5046  * Set the size estimates for the given join relation.
5047  *
5048  * The rel's targetlist must have been constructed already, and a
5049  * restriction clause list that matches the given component rels must
5050  * be provided.
5051  *
5052  * Since there is more than one way to make a joinrel for more than two
5053  * base relations, the results we get here could depend on which component
5054  * rel pair is provided. In theory we should get the same answers no matter
5055  * which pair is provided; in practice, since the selectivity estimation
5056  * routines don't handle all cases equally well, we might not. But there's
5057  * not much to be done about it. (Would it make sense to repeat the
5058  * calculations for each pair of input rels that's encountered, and somehow
5059  * average the results? Probably way more trouble than it's worth, and
5060  * anyway we must keep the rowcount estimate the same for all paths for the
5061  * joinrel.)
5062  *
5063  * We set only the rows field here. The reltarget field was already set by
5064  * build_joinrel_tlist, and baserestrictcost is not used for join rels.
5065  */
5066 void
5068  RelOptInfo *outer_rel,
5069  RelOptInfo *inner_rel,
5070  SpecialJoinInfo *sjinfo,
5071  List *restrictlist)
5072 {
5073  rel->rows = calc_joinrel_size_estimate(root,
5074  rel,
5075  outer_rel,
5076  inner_rel,
5077  outer_rel->rows,
5078  inner_rel->rows,
5079  sjinfo,
5080  restrictlist);
5081 }
5082 
5083 /*
5084  * get_parameterized_joinrel_size
5085  * Make a size estimate for a parameterized scan of a join relation.
5086  *
5087  * 'rel' is the joinrel under consideration.
5088  * 'outer_path', 'inner_path' are (probably also parameterized) Paths that
5089  * produce the relations being joined.
5090  * 'sjinfo' is any SpecialJoinInfo relevant to this join.
5091  * 'restrict_clauses' lists the join clauses that need to be applied at the
5092  * join node (including any movable clauses that were moved down to this join,
5093  * and not including any movable clauses that were pushed down into the
5094  * child paths).
5095  *
5096  * set_joinrel_size_estimates must have been applied already.
5097  */
5098 double
5100  Path *outer_path,
5101  Path *inner_path,
5102  SpecialJoinInfo *sjinfo,
5103  List *restrict_clauses)
5104 {
5105  double nrows;
5106 
5107  /*
5108  * Estimate the number of rows returned by the parameterized join as the
5109  * sizes of the input paths times the selectivity of the clauses that have
5110  * ended up at this join node.
5111  *
5112  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5113  * on the pair of input paths provided, though ideally we'd get the same
5114  * estimate for any pair with the same parameterization.
5115  */
5116  nrows = calc_joinrel_size_estimate(root,
5117  rel,
5118  outer_path->parent,
5119  inner_path->parent,
5120  outer_path->rows,
5121  inner_path->rows,
5122  sjinfo,
5123  restrict_clauses);
5124  /* For safety, make sure result is not more than the base estimate */
5125  if (nrows > rel->rows)
5126  nrows = rel->rows;
5127  return nrows;
5128 }
5129 
5130 /*
5131  * calc_joinrel_size_estimate
5132  * Workhorse for set_joinrel_size_estimates and
5133  * get_parameterized_joinrel_size.
5134  *
5135  * outer_rel/inner_rel are the relations being joined, but they should be
5136  * assumed to have sizes outer_rows/inner_rows; those numbers might be less
5137  * than what rel->rows says, when we are considering parameterized paths.
5138  */
5139 static double
5141  RelOptInfo *joinrel,
5142  RelOptInfo *outer_rel,
5143  RelOptInfo *inner_rel,
5144  double outer_rows,
5145  double inner_rows,
5146  SpecialJoinInfo *sjinfo,
5147  List *restrictlist)
5148 {
5149  JoinType jointype = sjinfo->jointype;
5150  Selectivity fkselec;
5151  Selectivity jselec;
5152  Selectivity pselec;
5153  double nrows;
5154 
5155  /*
5156  * Compute joinclause selectivity. Note that we are only considering
5157  * clauses that become restriction clauses at this join level; we are not
5158  * double-counting them because they were not considered in estimating the
5159  * sizes of the component rels.
5160  *
5161  * First, see whether any of the joinclauses can be matched to known FK
5162  * constraints. If so, drop those clauses from the restrictlist, and
5163  * instead estimate their selectivity using FK semantics. (We do this
5164  * without regard to whether said clauses are local or "pushed down".
5165  * Probably, an FK-matching clause could never be seen as pushed down at
5166  * an outer join, since it would be strict and hence would be grounds for
5167  * join strength reduction.) fkselec gets the net selectivity for
5168  * FK-matching clauses, or 1.0 if there are none.
5169  */
5170  fkselec = get_foreign_key_join_selectivity(root,
5171  outer_rel->relids,
5172  inner_rel->relids,
5173  sjinfo,
5174  &restrictlist);
5175 
5176  /*
5177  * For an outer join, we have to distinguish the selectivity of the join's
5178  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5179  * down". For inner joins we just count them all as joinclauses.
5180  */
5181  if (IS_OUTER_JOIN(jointype))
5182  {
5183  List *joinquals = NIL;
5184  List *pushedquals = NIL;
5185  ListCell *l;
5186 
5187  /* Grovel through the clauses to separate into two lists */
5188  foreach(l, restrictlist)
5189  {
5190  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5191 
5192  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5193  pushedquals = lappend(pushedquals, rinfo);
5194  else
5195  joinquals = lappend(joinquals, rinfo);
5196  }
5197 
5198  /* Get the separate selectivities */
5199  jselec = clauselist_selectivity(root,
5200  joinquals,
5201  0,
5202  jointype,
5203  sjinfo);
5204  pselec = clauselist_selectivity(root,
5205  pushedquals,
5206  0,
5207  jointype,
5208  sjinfo);
5209 
5210  /* Avoid leaking a lot of ListCells */
5211  list_free(joinquals);
5212  list_free(pushedquals);
5213  }
5214  else
5215  {
5216  jselec = clauselist_selectivity(root,
5217  restrictlist,
5218  0,
5219  jointype,
5220  sjinfo);
5221  pselec = 0.0; /* not used, keep compiler quiet */
5222  }
5223 
5224  /*
5225  * Basically, we multiply size of Cartesian product by selectivity.
5226  *
5227  * If we are doing an outer join, take that into account: the joinqual
5228  * selectivity has to be clamped using the knowledge that the output must
5229  * be at least as large as the non-nullable input. However, any
5230  * pushed-down quals are applied after the outer join, so their
5231  * selectivity applies fully.
5232  *
5233  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5234  * of LHS rows that have matches, and we apply that straightforwardly.
5235  */
5236  switch (jointype)
5237  {
5238  case JOIN_INNER:
5239  nrows = outer_rows * inner_rows * fkselec * jselec;
5240  /* pselec not used */
5241  break;
5242  case JOIN_LEFT:
5243  nrows = outer_rows * inner_rows * fkselec * jselec;
5244  if (nrows < outer_rows)
5245  nrows = outer_rows;
5246  nrows *= pselec;
5247  break;
5248  case JOIN_FULL:
5249  nrows = outer_rows * inner_rows * fkselec * jselec;
5250  if (nrows < outer_rows)
5251  nrows = outer_rows;
5252  if (nrows < inner_rows)
5253  nrows = inner_rows;
5254  nrows *= pselec;
5255  break;
5256  case JOIN_SEMI:
5257  nrows = outer_rows * fkselec * jselec;
5258  /* pselec not used */
5259  break;
5260  case JOIN_ANTI:
5261  nrows = outer_rows * (1.0 - fkselec * jselec);
5262  nrows *= pselec;
5263  break;
5264  default:
5265  /* other values not expected here */
5266  elog(ERROR, "unrecognized join type: %d", (int) jointype);
5267  nrows = 0; /* keep compiler quiet */
5268  break;
5269  }
5270 
5271  return clamp_row_est(nrows);
5272 }
5273 
5274 /*
5275  * get_foreign_key_join_selectivity
5276  * Estimate join selectivity for foreign-key-related clauses.
5277  *
5278  * Remove any clauses that can be matched to FK constraints from *restrictlist,
5279  * and return a substitute estimate of their selectivity. 1.0 is returned
5280  * when there are no such clauses.
5281  *
5282  * The reason for treating such clauses specially is that we can get better
5283  * estimates this way than by relying on clauselist_selectivity(), especially
5284  * for multi-column FKs where that function's assumption that the clauses are
5285  * independent falls down badly. But even with single-column FKs, we may be
5286  * able to get a better answer when the pg_statistic stats are missing or out
5287  * of date.
5288  */
5289 static Selectivity
5291  Relids outer_relids,
5292  Relids inner_relids,
5293  SpecialJoinInfo *sjinfo,
5294  List **restrictlist)
5295 {
5296  Selectivity fkselec = 1.0;
5297  JoinType jointype = sjinfo->jointype;
5298  List *worklist = *restrictlist;
5299  ListCell *lc;
5300 
5301  /* Consider each FK constraint that is known to match the query */
5302  foreach(lc, root->fkey_list)
5303  {
5304  ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
5305  bool ref_is_outer;
5306  List *removedlist;
5307  ListCell *cell;
5308 
5309  /*
5310  * This FK is not relevant unless it connects a baserel on one side of
5311  * this join to a baserel on the other side.
5312  */
5313  if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5314  bms_is_member(fkinfo->ref_relid, inner_relids))
5315  ref_is_outer = false;
5316  else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5317  bms_is_member(fkinfo->con_relid, inner_relids))
5318  ref_is_outer = true;
5319  else
5320  continue;
5321 
5322  /*
5323  * If we're dealing with a semi/anti join, and the FK's referenced
5324  * relation is on the outside, then knowledge of the FK doesn't help
5325  * us figure out what we need to know (which is the fraction of outer
5326  * rows that have matches). On the other hand, if the referenced rel
5327  * is on the inside, then all outer rows must have matches in the
5328  * referenced table (ignoring nulls). But any restriction or join
5329  * clauses that filter that table will reduce the fraction of matches.
5330  * We can account for restriction clauses, but it's too hard to guess
5331  * how many table rows would get through a join that's inside the RHS.
5332  * Hence, if either case applies, punt and ignore the FK.
5333  */
5334  if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
5335  (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
5336  continue;
5337 
5338  /*
5339  * Modify the restrictlist by removing clauses that match the FK (and
5340  * putting them into removedlist instead). It seems unsafe to modify
5341  * the originally-passed List structure, so we make a shallow copy the
5342  * first time through.
5343  */
5344  if (worklist == *restrictlist)
5345  worklist = list_copy(worklist);
5346 
5347  removedlist = NIL;
5348  foreach(cell, worklist)
5349  {
5350  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5351  bool remove_it = false;
5352  int i;
5353 
5354  /* Drop this clause if it matches any column of the FK */
5355  for (i = 0; i < fkinfo->nkeys; i++)
5356  {
5357  if (rinfo->parent_ec)
5358  {
5359  /*
5360  * EC-derived clauses can only match by EC. It is okay to
5361  * consider any clause derived from the same EC as
5362  * matching the FK: even if equivclass.c chose to generate
5363  * a clause equating some other pair of Vars, it could
5364  * have generated one equating the FK's Vars. So for
5365  * purposes of estimation, we can act as though it did so.
5366  *
5367  * Note: checking parent_ec is a bit of a cheat because
5368  * there are EC-derived clauses that don't have parent_ec
5369  * set; but such clauses must compare expressions that
5370  * aren't just Vars, so they cannot match the FK anyway.
5371  */
5372  if (fkinfo->eclass[i] == rinfo->parent_ec)
5373  {
5374  remove_it = true;
5375  break;
5376  }
5377  }
5378  else
5379  {
5380  /*
5381  * Otherwise, see if rinfo was previously matched to FK as
5382  * a "loose" clause.
5383  */
5384  if (list_member_ptr(fkinfo->rinfos[i], rinfo))
5385  {
5386  remove_it = true;
5387  break;
5388  }
5389  }
5390  }
5391  if (remove_it)
5392  {
5393  worklist = foreach_delete_current(worklist, cell);
5394  removedlist = lappend(removedlist, rinfo);
5395  }
5396  }
5397 
5398  /*
5399  * If we failed to remove all the matching clauses we expected to
5400  * find, chicken out and ignore this FK; applying its selectivity
5401  * might result in double-counting. Put any clauses we did manage to
5402  * remove back into the worklist.
5403  *
5404  * Since the matching clauses are known not outerjoin-delayed, they
5405  * would normally have appeared in the initial joinclause list. If we
5406  * didn't find them, there are two possibilities:
5407  *
5408  * 1. If the FK match is based on an EC that is ec_has_const, it won't
5409  * have generated any join clauses at all. We discount such ECs while
5410  * checking to see if we have "all" the clauses. (Below, we'll adjust
5411  * the selectivity estimate for this case.)
5412  *
5413  * 2. The clauses were matched to some other FK in a previous
5414  * iteration of this loop, and thus removed from worklist. (A likely
5415  * case is that two FKs are matched to the same EC; there will be only
5416  * one EC-derived clause in the initial list, so the first FK will
5417  * consume it.) Applying both FKs' selectivity independently risks
5418  * underestimating the join size; in particular, this would undo one
5419  * of the main things that ECs were invented for, namely to avoid
5420  * double-counting the selectivity of redundant equality conditions.
5421  * Later we might think of a reasonable way to combine the estimates,
5422  * but for now, just punt, since this is a fairly uncommon situation.
5423  */
5424  if (removedlist == NIL ||
5425  list_length(removedlist) !=
5426  (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
5427  {
5428  worklist = list_concat(worklist, removedlist);
5429  continue;
5430  }
5431 
5432  /*
5433  * Finally we get to the payoff: estimate selectivity using the
5434  * knowledge that each referencing row will match exactly one row in
5435  * the referenced table.
5436  *
5437  * XXX that's not true in the presence of nulls in the referencing
5438  * column(s), so in principle we should derate the estimate for those.
5439  * However (1) if there are any strict restriction clauses for the
5440  * referencing column(s) elsewhere in the query, derating here would
5441  * be double-counting the null fraction, and (2) it's not very clear
5442  * how to combine null fractions for multiple referencing columns. So
5443  * we do nothing for now about correcting for nulls.
5444  *
5445  * XXX another point here is that if either side of an FK constraint
5446  * is an inheritance parent, we estimate as though the constraint
5447  * covers all its children as well. This is not an unreasonable
5448  * assumption for a referencing table, ie the user probably applied
5449  * identical constraints to all child tables (though perhaps we ought
5450  * to check that). But it's not possible to have done that for a
5451  * referenced table. Fortunately, precisely because that doesn't
5452  * work, it is uncommon in practice to have an FK referencing a parent
5453  * table. So, at least for now, disregard inheritance here.
5454  */
5455  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
5456  {
5457  /*
5458  * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
5459  * referenced table is exactly the inside of the join. The join
5460  * selectivity is defined as the fraction of LHS rows that have
5461  * matches. The FK implies that every LHS row has a match *in the
5462  * referenced table*; but any restriction clauses on it will
5463  * reduce the number of matches. Hence we take the join
5464  * selectivity as equal to the selectivity of the table's
5465  * restriction clauses, which is rows / tuples; but we must guard
5466  * against tuples == 0.
5467  */
5468  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5469  double ref_tuples = Max(ref_rel->tuples, 1.0);
5470 
5471  fkselec *= ref_rel->rows / ref_tuples;
5472  }
5473  else
5474  {
5475  /*
5476  * Otherwise, selectivity is exactly 1/referenced-table-size; but
5477  * guard against tuples == 0. Note we should use the raw table
5478  * tuple count, not any estimate of its filtered or joined size.
5479  */
5480  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5481  double ref_tuples = Max(ref_rel->tuples, 1.0);
5482 
5483  fkselec *= 1.0 / ref_tuples;
5484  }
5485 
5486  /*
5487  * If any of the FK columns participated in ec_has_const ECs, then
5488  * equivclass.c will have generated "var = const" restrictions for
5489  * each side of the join, thus reducing the sizes of both input
5490  * relations. Taking the fkselec at face value would amount to
5491  * double-counting the selectivity of the constant restriction for the
5492  * referencing Var. Hence, look for the restriction clause(s) that
5493  * were applied to the referencing Var(s), and divide out their
5494  * selectivity to correct for this.
5495  */
5496  if (fkinfo->nconst_ec > 0)
5497  {
5498  for (int i = 0; i < fkinfo->nkeys; i++)
5499  {
5500  EquivalenceClass *ec = fkinfo->eclass[i];
5501 
5502  if (ec && ec->ec_has_const)
5503  {
5504  EquivalenceMember *em = fkinfo->fk_eclass_member[i];
5506  em);
5507 
5508  if (rinfo)
5509  {
5510  Selectivity s0;
5511 
5512  s0 = clause_selectivity(root,
5513  (Node *) rinfo,
5514  0,
5515  jointype,
5516  sjinfo);
5517  if (s0 > 0)
5518  fkselec /= s0;
5519  }
5520  }
5521  }
5522  }
5523  }
5524 
5525  *restrictlist = worklist;
5526  CLAMP_PROBABILITY(fkselec);
5527  return fkselec;
5528 }
5529 
5530 /*
5531  * set_subquery_size_estimates
5532  * Set the size estimates for a base relation that is a subquery.
5533  *
5534  * The rel's targetlist and restrictinfo list must have been constructed
5535  * already, and the Paths for the subquery must have been completed.
5536  * We look at the subquery's PlannerInfo to extract data.
5537  *
5538  * We set the same fields as set_baserel_size_estimates.
5539  */
5540 void
5542 {
5543  PlannerInfo *subroot = rel->subroot;
5544  RelOptInfo *sub_final_rel;
5545  ListCell *lc;
5546 
5547  /* Should only be applied to base relations that are subqueries */
5548  Assert(rel->relid > 0);
5549  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5550 
5551  /*
5552  * Copy raw number of output rows from subquery. All of its paths should
5553  * have the same output rowcount, so just look at cheapest-total.
5554  */
5555  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5556  rel->tuples = sub_final_rel->cheapest_total_path->rows;
5557 
5558  /*
5559  * Compute per-output-column width estimates by examining the subquery's
5560  * targetlist. For any output that is a plain Var, get the width estimate
5561  * that was made while planning the subquery. Otherwise, we leave it to
5562  * set_rel_width to fill in a datatype-based default estimate.
5563  */
5564  foreach(lc, subroot->parse->targetList)
5565  {
5566  TargetEntry *te = lfirst_node(TargetEntry, lc);
5567  Node *texpr = (Node *) te->expr;
5568  int32 item_width = 0;
5569 
5570  /* junk columns aren't visible to upper query */
5571  if (te->resjunk)
5572  continue;
5573 
5574  /*
5575  * The subquery could be an expansion of a view that's had columns
5576  * added to it since the current query was parsed, so that there are
5577  * non-junk tlist columns in it that don't correspond to any column
5578  * visible at our query level. Ignore such columns.
5579  */
5580  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5581  continue;
5582 
5583  /*
5584  * XXX This currently doesn't work for subqueries containing set
5585  * operations, because the Vars in their tlists are bogus references
5586  * to the first leaf subquery, which wouldn't give the right answer
5587  * even if we could still get to its PlannerInfo.
5588  *
5589  * Also, the subquery could be an appendrel for which all branches are
5590  * known empty due to constraint exclusion, in which case
5591  * set_append_rel_pathlist will have left the attr_widths set to zero.
5592  *
5593  * In either case, we just leave the width estimate zero until
5594  * set_rel_width fixes it.
5595  */
5596  if (IsA(texpr, Var) &&
5597  subroot->parse->setOperations == NULL)
5598  {
5599  Var *var = (Var *) texpr;
5600  RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5601 
5602  item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5603  }
5604  rel->attr_widths[te->resno - rel->min_attr] = item_width;
5605  }
5606 
5607  /* Now estimate number of output rows, etc */
5608  set_baserel_size_estimates(root, rel);
5609 }
5610 
5611 /*
5612  * set_function_size_estimates
5613  * Set the size estimates for a base relation that is a function call.
5614  *
5615  * The rel's targetlist and restrictinfo list must have been constructed
5616  * already.
5617  *
5618  * We set the same fields as set_baserel_size_estimates.
5619  */
5620 void
5622 {
5623  RangeTblEntry *rte;
5624  ListCell *lc;
5625 
5626  /* Should only be applied to base relations that are functions */
5627  Assert(rel->relid > 0);
5628  rte = planner_rt_fetch(rel->relid, root);
5629  Assert(rte->rtekind == RTE_FUNCTION);
5630 
5631  /*
5632  * Estimate number of rows the functions will return. The rowcount of the
5633  * node is that of the largest function result.
5634  */
5635  rel->tuples = 0;
5636  foreach(lc, rte->functions)
5637  {
5638  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
5639  double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
5640 
5641  if (ntup > rel->tuples)
5642  rel->tuples = ntup;
5643  }
5644 
5645  /* Now estimate number of output rows, etc */
5646  set_baserel_size_estimates(root, rel);
5647 }
5648 
5649 /*
5650  * set_function_size_estimates
5651  * Set the size estimates for a base relation that is a function call.
5652  *
5653  * The rel's targetlist and restrictinfo list must have been constructed
5654  * already.
5655  *
5656  * We set the same fields as set_tablefunc_size_estimates.
5657  */
5658 void
5660 {
5661  /* Should only be applied to base relations that are functions */
5662  Assert(rel->relid > 0);
5663  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
5664 
5665  rel->tuples = 100;
5666 
5667  /* Now estimate number of output rows, etc */
5668  set_baserel_size_estimates(root, rel);
5669 }
5670 
5671 /*
5672  * set_values_size_estimates
5673  * Set the size estimates for a base relation that is a values list.
5674  *
5675  * The rel's targetlist and restrictinfo list must have been constructed
5676  * already.
5677  *
5678  * We set the same fields as set_baserel_size_estimates.
5679  */
5680 void
5682 {
5683  RangeTblEntry *rte;
5684 
5685  /* Should only be applied to base relations that are values lists */
5686  Assert(rel->relid > 0);
5687  rte = planner_rt_fetch(rel->relid, root);
5688  Assert(rte->rtekind == RTE_VALUES);
5689 
5690  /*
5691  * Estimate number of rows the values list will return. We know this
5692  * precisely based on the list length (well, barring set-returning
5693  * functions in list items, but that's a refinement not catered for
5694  * anywhere else either).
5695  */
5696  rel->tuples = list_length(rte->values_lists);
5697 
5698  /* Now estimate number of output rows, etc */
5699  set_baserel_size_estimates(root, rel);
5700 }
5701 
5702 /*
5703  * set_cte_size_estimates
5704  * Set the size estimates for a base relation that is a CTE reference.
5705  *
5706  * The rel's targetlist and restrictinfo list must have been constructed
5707  * already, and we need an estimate of the number of rows returned by the CTE
5708  * (if a regular CTE) or the non-recursive term (if a self-reference).
5709  *
5710  * We set the same fields as set_baserel_size_estimates.
5711  */
5712 void
5713 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
5714 {
5715  RangeTblEntry *rte;
5716 
5717  /* Should only be applied to base relations that are CTE references */
5718  Assert(rel->relid > 0);
5719  rte = planner_rt_fetch(rel->relid, root);
5720  Assert(rte->rtekind == RTE_CTE);
5721 
5722  if (rte->self_reference)
5723  {
5724  /*
5725  * In a self-reference, we assume the average worktable size is a
5726  * multiple of the nonrecursive term's size. The best multiplier will
5727  * vary depending on query "fan-out", so make its value adjustable.
5728  */
5729  rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
5730  }
5731  else
5732  {
5733  /* Otherwise just believe the CTE's rowcount estimate */
5734  rel->tuples = cte_rows;
5735  }
5736 
5737  /* Now estimate number of output rows, etc */
5738  set_baserel_size_estimates(root, rel);
5739 }
5740 
5741 /*
5742  * set_namedtuplestore_size_estimates
5743  * Set the size estimates for a base relation that is a tuplestore reference.
5744  *
5745  * The rel's targetlist and restrictinfo list must have been constructed
5746  * already.
5747  *
5748  * We set the same fields as set_baserel_size_estimates.
5749  */
5750 void
5752 {
5753  RangeTblEntry *rte;
5754 
5755  /* Should only be applied to base relations that are tuplestore references */
5756  Assert(rel->relid > 0);
5757  rte = planner_rt_fetch(rel->relid, root);
5759 
5760  /*
5761  * Use the estimate provided by the code which is generating the named
5762  * tuplestore. In some cases, the actual number might be available; in
5763  * others the same plan will be re-used, so a "typical" value might be
5764  * estimated and used.
5765  */
5766  rel->tuples = rte->enrtuples;
5767  if (rel->tuples < 0)
5768  rel->tuples = 1000;
5769 
5770  /* Now estimate number of output rows, etc */
5771  set_baserel_size_estimates(root, rel);
5772 }
5773 
5774 /*
5775  * set_result_size_estimates
5776  * Set the size estimates for an RTE_RESULT base relation
5777  *
5778  * The rel's targetlist and restrictinfo list must have been constructed
5779  * already.
5780  *
5781  * We set the same fields as set_baserel_size_estimates.
5782  */
5783 void
5785 {
5786  /* Should only be applied to RTE_RESULT base relations */
5787  Assert(rel->relid > 0);
5788  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
5789 
5790  /* RTE_RESULT always generates a single row, natively */
5791  rel->tuples = 1;
5792 
5793  /* Now estimate number of output rows, etc */
5794  set_baserel_size_estimates(root, rel);
5795 }
5796 
5797 /*
5798  * set_foreign_size_estimates
5799  * Set the size estimates for a base relation that is a foreign table.
5800  *
5801  * There is not a whole lot that we can do here; the foreign-data wrapper
5802  * is responsible for producing useful estimates. We can do a decent job
5803  * of estimating baserestrictcost, so we set that, and we also set up width
5804  * using what will be purely datatype-driven estimates from the targetlist.
5805  * There is no way to do anything sane with the rows value, so we just put
5806  * a default estimate and hope that the wrapper can improve on it. The
5807  * wrapper's GetForeignRelSize function will be called momentarily.
5808  *
5809  * The rel's targetlist and restrictinfo list must have been constructed
5810  * already.
5811  */
5812 void
5814 {
5815  /* Should only be applied to base relations */
5816  Assert(rel->relid > 0);
5817 
5818  rel->rows = 1000; /* entirely bogus default estimate */
5819 
5821 
5822  set_rel_width(root, rel);
5823 }
5824 
5825 
5826 /*
5827  * set_rel_width
5828  * Set the estimated output width of a base relation.
5829  *
5830  * The estimated output width is the sum of the per-attribute width estimates
5831  * for the actually-referenced columns, plus any PHVs or other expressions
5832  * that have to be calculated at this relation. This is the amount of data
5833  * we'd need to pass upwards in case of a sort, hash, etc.
5834  *
5835  * This function also sets reltarget->cost, so it's a bit misnamed now.
5836  *
5837  * NB: this works best on plain relations because it prefers to look at
5838  * real Vars. For subqueries, set_subquery_size_estimates will already have
5839  * copied up whatever per-column estimates were made within the subquery,
5840  * and for other types of rels there isn't much we can do anyway. We fall
5841  * back on (fairly stupid) datatype-based width estimates if we can't get
5842  * any better number.
5843  *
5844  * The per-attribute width estimates are cached for possible re-use while
5845  * building join relations or post-scan/join pathtargets.
5846  */
5847 static void
5849 {
5850  Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
5851  int32 tuple_width = 0;
5852  bool have_wholerow_var = false;
5853  ListCell *lc;
5854 
5855  /* Vars are assumed to have cost zero, but other exprs do not */
5856  rel->reltarget->cost.startup = 0;
5857  rel->reltarget->cost.per_tuple = 0;
5858 
5859  foreach(lc, rel->reltarget->exprs)
5860  {
5861  Node *node = (Node *) lfirst(lc);
5862 
5863  /*
5864  * Ordinarily, a Var in a rel's targetlist must belong to that rel;
5865  * but there are corner cases involving LATERAL references where that
5866  * isn't so. If the Var has the wrong varno, fall through to the
5867  * generic case (it doesn't seem worth the trouble to be any smarter).
5868  */
5869  if (IsA(node, Var) &&
5870  ((Var *) node)->varno == rel->relid)
5871  {
5872  Var *var = (Var *) node;
5873  int ndx;
5874  int32 item_width;
5875 
5876  Assert(var->varattno >= rel->min_attr);
5877  Assert(var->varattno <= rel->max_attr);
5878 
5879  ndx = var->varattno - rel->min_attr;
5880 
5881  /*
5882  * If it's a whole-row Var, we'll deal with it below after we have
5883  * already cached as many attr widths as possible.
5884  */
5885  if (var->varattno == 0)
5886  {
5887  have_wholerow_var = true;
5888  continue;
5889  }
5890 
5891  /*
5892  * The width may have been cached already (especially if it's a
5893  * subquery), so don't duplicate effort.
5894  */
5895  if (rel->attr_widths[ndx] > 0)
5896  {
5897  tuple_width += rel->attr_widths[ndx];
5898  continue;
5899  }
5900 
5901  /* Try to get column width from statistics */
5902  if (reloid != InvalidOid && var->varattno > 0)
5903  {
5904  item_width = get_attavgwidth(reloid, var->varattno);
5905  if (item_width > 0)
5906  {
5907  rel->attr_widths[ndx] = item_width;
5908  tuple_width += item_width;
5909  continue;
5910  }
5911  }
5912 
5913  /*
5914  * Not a plain relation, or can't find statistics for it. Estimate
5915  * using just the type info.
5916  */
5917  item_width = get_typavgwidth(var->vartype, var->vartypmod);
5918  Assert(item_width > 0);
5919  rel->attr_widths[ndx] = item_width;
5920  tuple_width += item_width;
5921  }
5922  else if (IsA(node, PlaceHolderVar))
5923  {
5924  /*
5925  * We will need to evaluate the PHV's contained expression while
5926  * scanning this rel, so be sure to include it in reltarget->cost.
5927  */
5928  PlaceHolderVar *phv = (PlaceHolderVar *) node;
5929  PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
5930  QualCost cost;
5931 
5932  tuple_width += phinfo->ph_width;
5933  cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
5934  rel->reltarget->cost.startup += cost.startup;
5935  rel->reltarget->cost.per_tuple += cost.per_tuple;
5936  }
5937  else
5938  {
5939  /*
5940  * We could be looking at an expression pulled up from a subquery,
5941  * or a ROW() representing a whole-row child Var, etc. Do what we
5942  * can using the expression type information.
5943  */
5944  int32 item_width;
5945  QualCost cost;
5946 
5947  item_width = get_typavgwidth(exprType(node), exprTypmod(node));
5948  Assert(item_width > 0);
5949  tuple_width += item_width;
5950  /* Not entirely clear if we need to account for cost, but do so */
5951  cost_qual_eval_node(&cost, node, root);
5952  rel->reltarget->cost.startup += cost.startup;
5953  rel->reltarget->cost.per_tuple += cost.per_tuple;
5954  }
5955  }
5956 
5957  /*
5958  * If we have a whole-row reference, estimate its width as the sum of
5959  * per-column widths plus heap tuple header overhead.
5960  */
5961  if (have_wholerow_var)
5962  {
5963  int32 wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
5964 
5965  if (reloid != InvalidOid)
5966  {
5967  /* Real relation, so estimate true tuple width */
5968  wholerow_width += get_relation_data_width(reloid,
5969  rel->attr_widths - rel->min_attr);
5970  }
5971  else
5972  {
5973  /* Do what we can with info for a phony rel */
5974  AttrNumber i;
5975 
5976  for (i = 1; i <= rel->max_attr; i++)
5977  wholerow_width += rel->attr_widths[i - rel->min_attr];
5978  }
5979 
5980  rel->attr_widths[0 - rel->min_attr] = wholerow_width;
5981 
5982  /*
5983  * Include the whole-row Var as part of the output tuple. Yes, that
5984  * really is what happens at runtime.
5985  */
5986  tuple_width += wholerow_width;
5987  }
5988 
5989  Assert(tuple_width >= 0);
5990  rel->reltarget->width = tuple_width;
5991 }
5992 
5993 /*
5994  * set_pathtarget_cost_width
5995  * Set the estimated eval cost and output width of a PathTarget tlist.
5996  *
5997  * As a notational convenience, returns the same PathTarget pointer passed in.
5998  *
5999  * Most, though not quite all, uses of this function occur after we've run
6000  * set_rel_width() for base relations; so we can usually obtain cached width
6001  * estimates for Vars. If we can't, fall back on datatype-based width
6002  * estimates. Present early-planning uses of PathTargets don't need accurate
6003  * widths badly enough to justify going to the catalogs for better data.
6004  */
6005 PathTarget *
6007 {
6008  int32 tuple_width = 0;
6009  ListCell *lc;
6010 
6011  /* Vars are assumed to have cost zero, but other exprs do not */
6012  target->cost.startup = 0;
6013  target->cost.per_tuple = 0;
6014 
6015  foreach(lc, target->exprs)
6016  {
6017  Node *node = (Node *) lfirst(lc);
6018 
6019  if (IsA(node, Var))