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),
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  */
1419 void
1421  RelOptInfo *baserel, ParamPathInfo *param_info)
1422 {
1423  Cost startup_cost;
1424  Cost run_cost;
1425  List *qpquals;
1426  QualCost qpqual_cost;
1427  Cost cpu_per_tuple;
1428 
1429  /* Should only be applied to base relations that are subqueries */
1430  Assert(baserel->relid > 0);
1431  Assert(baserel->rtekind == RTE_SUBQUERY);
1432 
1433  /*
1434  * We compute the rowcount estimate as the subplan's estimate times the
1435  * selectivity of relevant restriction clauses. In simple cases this will
1436  * come out the same as baserel->rows; but when dealing with parallelized
1437  * paths we must do it like this to get the right answer.
1438  */
1439  if (param_info)
1440  qpquals = list_concat_copy(param_info->ppi_clauses,
1441  baserel->baserestrictinfo);
1442  else
1443  qpquals = baserel->baserestrictinfo;
1444 
1445  path->path.rows = clamp_row_est(path->subpath->rows *
1447  qpquals,
1448  0,
1449  JOIN_INNER,
1450  NULL));
1451 
1452  /*
1453  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1454  * any restriction clauses and tlist that will be attached to the
1455  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1456  * projection overhead.
1457  */
1458  path->path.startup_cost = path->subpath->startup_cost;
1459  path->path.total_cost = path->subpath->total_cost;
1460 
1461  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1462 
1463  startup_cost = qpqual_cost.startup;
1464  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1465  run_cost = cpu_per_tuple * path->subpath->rows;
1466 
1467  /* tlist eval costs are paid per output row, not per tuple scanned */
1468  startup_cost += path->path.pathtarget->cost.startup;
1469  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1470 
1471  path->path.startup_cost += startup_cost;
1472  path->path.total_cost += startup_cost + run_cost;
1473 }
1474 
1475 /*
1476  * cost_functionscan
1477  * Determines and returns the cost of scanning a function RTE.
1478  *
1479  * 'baserel' is the relation to be scanned
1480  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1481  */
1482 void
1484  RelOptInfo *baserel, ParamPathInfo *param_info)
1485 {
1486  Cost startup_cost = 0;
1487  Cost run_cost = 0;
1488  QualCost qpqual_cost;
1489  Cost cpu_per_tuple;
1490  RangeTblEntry *rte;
1491  QualCost exprcost;
1492 
1493  /* Should only be applied to base relations that are functions */
1494  Assert(baserel->relid > 0);
1495  rte = planner_rt_fetch(baserel->relid, root);
1496  Assert(rte->rtekind == RTE_FUNCTION);
1497 
1498  /* Mark the path with the correct row estimate */
1499  if (param_info)
1500  path->rows = param_info->ppi_rows;
1501  else
1502  path->rows = baserel->rows;
1503 
1504  /*
1505  * Estimate costs of executing the function expression(s).
1506  *
1507  * Currently, nodeFunctionscan.c always executes the functions to
1508  * completion before returning any rows, and caches the results in a
1509  * tuplestore. So the function eval cost is all startup cost, and per-row
1510  * costs are minimal.
1511  *
1512  * XXX in principle we ought to charge tuplestore spill costs if the
1513  * number of rows is large. However, given how phony our rowcount
1514  * estimates for functions tend to be, there's not a lot of point in that
1515  * refinement right now.
1516  */
1517  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1518 
1519  startup_cost += exprcost.startup + exprcost.per_tuple;
1520 
1521  /* Add scanning CPU costs */
1522  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1523 
1524  startup_cost += qpqual_cost.startup;
1525  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1526  run_cost += cpu_per_tuple * baserel->tuples;
1527 
1528  /* tlist eval costs are paid per output row, not per tuple scanned */
1529  startup_cost += path->pathtarget->cost.startup;
1530  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1531 
1532  path->startup_cost = startup_cost;
1533  path->total_cost = startup_cost + run_cost;
1534 }
1535 
1536 /*
1537  * cost_tablefuncscan
1538  * Determines and returns the cost of scanning a table function.
1539  *
1540  * 'baserel' is the relation to be scanned
1541  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1542  */
1543 void
1545  RelOptInfo *baserel, ParamPathInfo *param_info)
1546 {
1547  Cost startup_cost = 0;
1548  Cost run_cost = 0;
1549  QualCost qpqual_cost;
1550  Cost cpu_per_tuple;
1551  RangeTblEntry *rte;
1552  QualCost exprcost;
1553 
1554  /* Should only be applied to base relations that are functions */
1555  Assert(baserel->relid > 0);
1556  rte = planner_rt_fetch(baserel->relid, root);
1557  Assert(rte->rtekind == RTE_TABLEFUNC);
1558 
1559  /* Mark the path with the correct row estimate */
1560  if (param_info)
1561  path->rows = param_info->ppi_rows;
1562  else
1563  path->rows = baserel->rows;
1564 
1565  /*
1566  * Estimate costs of executing the table func expression(s).
1567  *
1568  * XXX in principle we ought to charge tuplestore spill costs if the
1569  * number of rows is large. However, given how phony our rowcount
1570  * estimates for tablefuncs tend to be, there's not a lot of point in that
1571  * refinement right now.
1572  */
1573  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1574 
1575  startup_cost += exprcost.startup + exprcost.per_tuple;
1576 
1577  /* Add scanning CPU costs */
1578  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1579 
1580  startup_cost += qpqual_cost.startup;
1581  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1582  run_cost += cpu_per_tuple * baserel->tuples;
1583 
1584  /* tlist eval costs are paid per output row, not per tuple scanned */
1585  startup_cost += path->pathtarget->cost.startup;
1586  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1587 
1588  path->startup_cost = startup_cost;
1589  path->total_cost = startup_cost + run_cost;
1590 }
1591 
1592 /*
1593  * cost_valuesscan
1594  * Determines and returns the cost of scanning a VALUES RTE.
1595  *
1596  * 'baserel' is the relation to be scanned
1597  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
1598  */
1599 void
1601  RelOptInfo *baserel, ParamPathInfo *param_info)
1602 {
1603  Cost startup_cost = 0;
1604  Cost run_cost = 0;
1605  QualCost qpqual_cost;
1606  Cost cpu_per_tuple;
1607 
1608  /* Should only be applied to base relations that are values lists */
1609  Assert(baserel->relid > 0);
1610  Assert(baserel->rtekind == RTE_VALUES);
1611 
1612  /* Mark the path with the correct row estimate */
1613  if (param_info)
1614  path->rows = param_info->ppi_rows;
1615  else
1616  path->rows = baserel->rows;
1617 
1618  /*
1619  * For now, estimate list evaluation cost at one operator eval per list
1620  * (probably pretty bogus, but is it worth being smarter?)
1621  */
1622  cpu_per_tuple = cpu_operator_cost;
1623 
1624  /* Add scanning CPU costs */
1625  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1626 
1627  startup_cost += qpqual_cost.startup;
1628  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1629  run_cost += cpu_per_tuple * baserel->tuples;
1630 
1631  /* tlist eval costs are paid per output row, not per tuple scanned */
1632  startup_cost += path->pathtarget->cost.startup;
1633  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1634 
1635  path->startup_cost = startup_cost;
1636  path->total_cost = startup_cost + run_cost;
1637 }
1638 
1639 /*
1640  * cost_ctescan
1641  * Determines and returns the cost of scanning a CTE RTE.
1642  *
1643  * Note: this is used for both self-reference and regular CTEs; the
1644  * possible cost differences are below the threshold of what we could
1645  * estimate accurately anyway. Note that the costs of evaluating the
1646  * referenced CTE query are added into the final plan as initplan costs,
1647  * and should NOT be counted here.
1648  */
1649 void
1651  RelOptInfo *baserel, ParamPathInfo *param_info)
1652 {
1653  Cost startup_cost = 0;
1654  Cost run_cost = 0;
1655  QualCost qpqual_cost;
1656  Cost cpu_per_tuple;
1657 
1658  /* Should only be applied to base relations that are CTEs */
1659  Assert(baserel->relid > 0);
1660  Assert(baserel->rtekind == RTE_CTE);
1661 
1662  /* Mark the path with the correct row estimate */
1663  if (param_info)
1664  path->rows = param_info->ppi_rows;
1665  else
1666  path->rows = baserel->rows;
1667 
1668  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1669  cpu_per_tuple = cpu_tuple_cost;
1670 
1671  /* Add scanning CPU costs */
1672  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1673 
1674  startup_cost += qpqual_cost.startup;
1675  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1676  run_cost += cpu_per_tuple * baserel->tuples;
1677 
1678  /* tlist eval costs are paid per output row, not per tuple scanned */
1679  startup_cost += path->pathtarget->cost.startup;
1680  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1681 
1682  path->startup_cost = startup_cost;
1683  path->total_cost = startup_cost + run_cost;
1684 }
1685 
1686 /*
1687  * cost_namedtuplestorescan
1688  * Determines and returns the cost of scanning a named tuplestore.
1689  */
1690 void
1692  RelOptInfo *baserel, ParamPathInfo *param_info)
1693 {
1694  Cost startup_cost = 0;
1695  Cost run_cost = 0;
1696  QualCost qpqual_cost;
1697  Cost cpu_per_tuple;
1698 
1699  /* Should only be applied to base relations that are Tuplestores */
1700  Assert(baserel->relid > 0);
1701  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1702 
1703  /* Mark the path with the correct row estimate */
1704  if (param_info)
1705  path->rows = param_info->ppi_rows;
1706  else
1707  path->rows = baserel->rows;
1708 
1709  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1710  cpu_per_tuple = cpu_tuple_cost;
1711 
1712  /* Add scanning CPU costs */
1713  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1714 
1715  startup_cost += qpqual_cost.startup;
1716  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1717  run_cost += cpu_per_tuple * baserel->tuples;
1718 
1719  path->startup_cost = startup_cost;
1720  path->total_cost = startup_cost + run_cost;
1721 }
1722 
1723 /*
1724  * cost_resultscan
1725  * Determines and returns the cost of scanning an RTE_RESULT relation.
1726  */
1727 void
1729  RelOptInfo *baserel, ParamPathInfo *param_info)
1730 {
1731  Cost startup_cost = 0;
1732  Cost run_cost = 0;
1733  QualCost qpqual_cost;
1734  Cost cpu_per_tuple;
1735 
1736  /* Should only be applied to RTE_RESULT base relations */
1737  Assert(baserel->relid > 0);
1738  Assert(baserel->rtekind == RTE_RESULT);
1739 
1740  /* Mark the path with the correct row estimate */
1741  if (param_info)
1742  path->rows = param_info->ppi_rows;
1743  else
1744  path->rows = baserel->rows;
1745 
1746  /* We charge qual cost plus cpu_tuple_cost */
1747  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1748 
1749  startup_cost += qpqual_cost.startup;
1750  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1751  run_cost += cpu_per_tuple * baserel->tuples;
1752 
1753  path->startup_cost = startup_cost;
1754  path->total_cost = startup_cost + run_cost;
1755 }
1756 
1757 /*
1758  * cost_recursive_union
1759  * Determines and returns the cost of performing a recursive union,
1760  * and also the estimated output size.
1761  *
1762  * We are given Paths for the nonrecursive and recursive terms.
1763  */
1764 void
1765 cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
1766 {
1767  Cost startup_cost;
1768  Cost total_cost;
1769  double total_rows;
1770 
1771  /* We probably have decent estimates for the non-recursive term */
1772  startup_cost = nrterm->startup_cost;
1773  total_cost = nrterm->total_cost;
1774  total_rows = nrterm->rows;
1775 
1776  /*
1777  * We arbitrarily assume that about 10 recursive iterations will be
1778  * needed, and that we've managed to get a good fix on the cost and output
1779  * size of each one of them. These are mighty shaky assumptions but it's
1780  * hard to see how to do better.
1781  */
1782  total_cost += 10 * rterm->total_cost;
1783  total_rows += 10 * rterm->rows;
1784 
1785  /*
1786  * Also charge cpu_tuple_cost per row to account for the costs of
1787  * manipulating the tuplestores. (We don't worry about possible
1788  * spill-to-disk costs.)
1789  */
1790  total_cost += cpu_tuple_cost * total_rows;
1791 
1792  runion->startup_cost = startup_cost;
1793  runion->total_cost = total_cost;
1794  runion->rows = total_rows;
1795  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1796  rterm->pathtarget->width);
1797 }
1798 
1799 /*
1800  * is_fake_var
1801  * Workaround for generate_append_tlist() which generates fake Vars with
1802  * varno == 0, that will cause a fail of estimate_num_group() call
1803  *
1804  * XXX Ummm, why would estimate_num_group fail with this?
1805  */
1806 static bool
1808 {
1809  if (IsA(expr, RelabelType))
1810  expr = (Expr *) ((RelabelType *) expr)->arg;
1811 
1812  return (IsA(expr, Var) && ((Var *) expr)->varno == 0);
1813 }
1814 
1815 /*
1816  * get_width_cost_multiplier
1817  * Returns relative complexity of comparing two values based on its width.
1818  * The idea behind is that the comparison becomes more expensive the longer the
1819  * value is. Return value is in cpu_operator_cost units.
1820  */
1821 static double
1823 {
1824  double width = -1.0; /* fake value */
1825 
1826  if (IsA(expr, RelabelType))
1827  expr = (Expr *) ((RelabelType *) expr)->arg;
1828 
1829  /* Try to find actual stat in corresponding relation */
1830  if (IsA(expr, Var))
1831  {
1832  Var *var = (Var *) expr;
1833 
1834  if (var->varno > 0 && var->varno < root->simple_rel_array_size)
1835  {
1836  RelOptInfo *rel = root->simple_rel_array[var->varno];
1837 
1838  if (rel != NULL &&
1839  var->varattno >= rel->min_attr &&
1840  var->varattno <= rel->max_attr)
1841  {
1842  int ndx = var->varattno - rel->min_attr;
1843 
1844  if (rel->attr_widths[ndx] > 0)
1845  width = rel->attr_widths[ndx];
1846  }
1847  }
1848  }
1849 
1850  /* Didn't find any actual stats, try using type width instead. */
1851  if (width < 0.0)
1852  {
1853  Node *node = (Node *) expr;
1854 
1855  width = get_typavgwidth(exprType(node), exprTypmod(node));
1856  }
1857 
1858  /*
1859  * Values are passed as Datum type, so comparisons can't be cheaper than
1860  * comparing a Datum value.
1861  *
1862  * FIXME I find this reasoning questionable. We may pass int2, and
1863  * comparing it is probably a bit cheaper than comparing a bigint.
1864  */
1865  if (width <= sizeof(Datum))
1866  return 1.0;
1867 
1868  /*
1869  * We consider the cost of a comparison not to be directly proportional to
1870  * width of the argument, because widths of the arguments could be
1871  * slightly different (we only know the average width for the whole
1872  * column). So we use log16(width) as an estimate.
1873  */
1874  return 1.0 + 0.125 * LOG2(width / sizeof(Datum));
1875 }
1876 
1877 /*
1878  * compute_cpu_sort_cost
1879  * compute CPU cost of sort (i.e. in-memory)
1880  *
1881  * The main thing we need to calculate to estimate sort CPU costs is the number
1882  * of calls to the comparator functions. The difficulty is that for multi-column
1883  * sorts there may be different data types involved (for some of which the calls
1884  * may be much more expensive). Furthermore, columns may have a very different
1885  * number of distinct values - the higher the number, the fewer comparisons will
1886  * be needed for the following columns.
1887  *
1888  * The algorithm is incremental - we add pathkeys one by one, and at each step we
1889  * estimate the number of necessary comparisons (based on the number of distinct
1890  * groups in the current pathkey prefix and the new pathkey), and the comparison
1891  * costs (which is data type specific).
1892  *
1893  * Estimation of the number of comparisons is based on ideas from:
1894  *
1895  * "Quicksort Is Optimal", Robert Sedgewick, Jon Bentley, 2002
1896  * [https://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf]
1897  *
1898  * In term of that paper, let N - number of tuples, Xi - number of identical
1899  * tuples with value Ki, then the estimate of number of comparisons is:
1900  *
1901  * log(N! / (X1! * X2! * ..)) ~ sum(Xi * log(N/Xi))
1902  *
1903  * We assume all Xi the same because now we don't have any estimation of
1904  * group sizes, we have only know the estimate of number of groups (distinct
1905  * values). In that case, formula becomes:
1906  *
1907  * N * log(NumberOfGroups)
1908  *
1909  * For multi-column sorts we need to estimate the number of comparisons for
1910  * each individual column - for example with columns (c1, c2, ..., ck) we
1911  * can estimate that number of comparisons on ck is roughly
1912  *
1913  * ncomparisons(c1, c2, ..., ck) / ncomparisons(c1, c2, ..., c(k-1))
1914  *
1915  * Let k be a column number, Gk - number of groups defined by k columns, and Fk
1916  * the cost of the comparison is
1917  *
1918  * N * sum( Fk * log(Gk) )
1919  *
1920  * Note: We also consider column width, not just the comparator cost.
1921  *
1922  * NOTE: some callers currently pass NIL for pathkeys because they
1923  * can't conveniently supply the sort keys. In this case, it will fallback to
1924  * simple comparison cost estimate.
1925  */
1926 static Cost
1927 compute_cpu_sort_cost(PlannerInfo *root, List *pathkeys, int nPresortedKeys,
1928  Cost comparison_cost, double tuples, double output_tuples,
1929  bool heapSort)
1930 {
1931  Cost per_tuple_cost = 0.0;
1932  ListCell *lc;
1933  List *pathkeyExprs = NIL;
1934  double tuplesPerPrevGroup = tuples;
1935  double totalFuncCost = 1.0;
1936  bool has_fake_var = false;
1937  int i = 0;
1938  Oid prev_datatype = InvalidOid;
1939  List *cache_varinfos = NIL;
1940 
1941  /* fallback if pathkeys is unknown */
1942  if (list_length(pathkeys) == 0)
1943  {
1944  /*
1945  * If we'll use a bounded heap-sort keeping just K tuples in memory,
1946  * for a total number of tuple comparisons of N log2 K; but the
1947  * constant factor is a bit higher than for quicksort. Tweak it so
1948  * that the cost curve is continuous at the crossover point.
1949  */
1950  output_tuples = (heapSort) ? 2.0 * output_tuples : tuples;
1951  per_tuple_cost += 2.0 * cpu_operator_cost * LOG2(output_tuples);
1952 
1953  /* add cost provided by caller */
1954  per_tuple_cost += comparison_cost;
1955 
1956  return per_tuple_cost * tuples;
1957  }
1958 
1959  /*
1960  * Computing total cost of sorting takes into account the per-column
1961  * comparison function cost. We try to compute the needed number of
1962  * comparisons per column.
1963  */
1964  foreach(lc, pathkeys)
1965  {
1966  PathKey *pathkey = (PathKey *) lfirst(lc);
1967  EquivalenceMember *em;
1968  double nGroups,
1969  correctedNGroups;
1970  Cost funcCost = 1.0;
1971 
1972  /*
1973  * We believe that equivalence members aren't very different, so, to
1974  * estimate cost we consider just the first member.
1975  */
1976  em = (EquivalenceMember *) linitial(pathkey->pk_eclass->ec_members);
1977 
1978  if (em->em_datatype != InvalidOid)
1979  {
1980  /* do not lookup funcCost if the data type is the same */
1981  if (prev_datatype != em->em_datatype)
1982  {
1983  Oid sortop;
1984  QualCost cost;
1985 
1986  sortop = get_opfamily_member(pathkey->pk_opfamily,
1987  em->em_datatype, em->em_datatype,
1988  pathkey->pk_strategy);
1989 
1990  cost.startup = 0;
1991  cost.per_tuple = 0;
1992  add_function_cost(root, get_opcode(sortop), NULL, &cost);
1993 
1994  /*
1995  * add_function_cost returns the product of cpu_operator_cost
1996  * and procost, but we need just procost, co undo that.
1997  */
1998  funcCost = cost.per_tuple / cpu_operator_cost;
1999 
2000  prev_datatype = em->em_datatype;
2001  }
2002  }
2003 
2004  /* factor in the width of the values in this column */
2005  funcCost *= get_width_cost_multiplier(root, em->em_expr);
2006 
2007  /* now we have per-key cost, so add to the running total */
2008  totalFuncCost += funcCost;
2009 
2010  /* remember if we have found a fake Var in pathkeys */
2011  has_fake_var |= is_fake_var(em->em_expr);
2012  pathkeyExprs = lappend(pathkeyExprs, em->em_expr);
2013 
2014  /*
2015  * We need to calculate the number of comparisons for this column,
2016  * which requires knowing the group size. So we estimate the number of
2017  * groups by calling estimate_num_groups_incremental(), which
2018  * estimates the group size for "new" pathkeys.
2019  *
2020  * Note: estimate_num_groups_incremental does not handle fake Vars, so
2021  * use a default estimate otherwise.
2022  */
2023  if (!has_fake_var)
2024  nGroups = estimate_num_groups_incremental(root, pathkeyExprs,
2025  tuplesPerPrevGroup, NULL, NULL,
2026  &cache_varinfos,
2027  list_length(pathkeyExprs) - 1);
2028  else if (tuples > 4.0)
2029 
2030  /*
2031  * Use geometric mean as estimation if there are no stats.
2032  *
2033  * We don't use DEFAULT_NUM_DISTINCT here, because that's used for
2034  * a single column, but here we're dealing with multiple columns.
2035  */
2036  nGroups = ceil(2.0 + sqrt(tuples) * (i + 1) / list_length(pathkeys));
2037  else
2038  nGroups = tuples;
2039 
2040  /*
2041  * Presorted keys are not considered in the cost above, but we still
2042  * do have to compare them in the qsort comparator. So make sure to
2043  * factor in the cost in that case.
2044  */
2045  if (i >= nPresortedKeys)
2046  {
2047  if (heapSort)
2048  {
2049  /*
2050  * have to keep at least one group, and a multiple of group
2051  * size
2052  */
2053  correctedNGroups = ceil(output_tuples / tuplesPerPrevGroup);
2054  }
2055  else
2056  /* all groups in the input */
2057  correctedNGroups = nGroups;
2058 
2059  correctedNGroups = Max(1.0, ceil(correctedNGroups));
2060 
2061  per_tuple_cost += totalFuncCost * LOG2(correctedNGroups);
2062  }
2063 
2064  i++;
2065 
2066  /*
2067  * Uniform distributions with all groups being of the same size are
2068  * the best case, with nice smooth behavior. Real-world distributions
2069  * tend not to be uniform, though, and we don't have any reliable
2070  * easy-to-use information. As a basic defense against skewed
2071  * distributions, we use a 1.5 factor to make the expected group a bit
2072  * larger, but we need to be careful not to make the group larger than
2073  * in the preceding step.
2074  */
2075  tuplesPerPrevGroup = Min(tuplesPerPrevGroup,
2076  ceil(1.5 * tuplesPerPrevGroup / nGroups));
2077 
2078  /*
2079  * Once we get single-row group, it means tuples in the group are
2080  * unique and we can skip all remaining columns.
2081  */
2082  if (tuplesPerPrevGroup <= 1.0)
2083  break;
2084  }
2085 
2086  list_free(pathkeyExprs);
2087 
2088  /* per_tuple_cost is in cpu_operator_cost units */
2089  per_tuple_cost *= cpu_operator_cost;
2090 
2091  /*
2092  * Accordingly to "Introduction to algorithms", Thomas H. Cormen, Charles
2093  * E. Leiserson, Ronald L. Rivest, ISBN 0-07-013143-0, quicksort
2094  * estimation formula has additional term proportional to number of tuples
2095  * (see Chapter 8.2 and Theorem 4.1). That affects cases with a low number
2096  * of tuples, approximately less than 1e4. We could implement it as an
2097  * additional multiplier under the logarithm, but we use a bit more
2098  * complex formula which takes into account the number of unique tuples
2099  * and it's not clear how to combine the multiplier with the number of
2100  * groups. Estimate it as 10 cpu_operator_cost units.
2101  */
2102  per_tuple_cost += 10 * cpu_operator_cost;
2103 
2104  per_tuple_cost += comparison_cost;
2105 
2106  return tuples * per_tuple_cost;
2107 }
2108 
2109 /*
2110  * simple wrapper just to estimate best sort path
2111  */
2112 Cost
2113 cost_sort_estimate(PlannerInfo *root, List *pathkeys, int nPresortedKeys,
2114  double tuples)
2115 {
2116  return compute_cpu_sort_cost(root, pathkeys, nPresortedKeys,
2117  0, tuples, tuples, false);
2118 }
2119 
2120 /*
2121  * cost_tuplesort
2122  * Determines and returns the cost of sorting a relation using tuplesort,
2123  * not including the cost of reading the input data.
2124  *
2125  * If the total volume of data to sort is less than sort_mem, we will do
2126  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
2127  * comparisons for t tuples.
2128  *
2129  * If the total volume exceeds sort_mem, we switch to a tape-style merge
2130  * algorithm. There will still be about t*log2(t) tuple comparisons in
2131  * total, but we will also need to write and read each tuple once per
2132  * merge pass. We expect about ceil(logM(r)) merge passes where r is the
2133  * number of initial runs formed and M is the merge order used by tuplesort.c.
2134  * Since the average initial run should be about sort_mem, we have
2135  * disk traffic = 2 * relsize * ceil(logM(p / sort_mem))
2136  * and cpu cost (computed by compute_cpu_sort_cost()).
2137  *
2138  * If the sort is bounded (i.e., only the first k result tuples are needed)
2139  * and k tuples can fit into sort_mem, we use a heap method that keeps only
2140  * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
2141  *
2142  * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
2143  * accesses (XXX can't we refine that guess?)
2144  *
2145  * By default, we charge two operator evals per tuple comparison, which should
2146  * be in the right ballpark in most cases. The caller can tweak this by
2147  * specifying nonzero comparison_cost; typically that's used for any extra
2148  * work that has to be done to prepare the inputs to the comparison operators.
2149  *
2150  * 'tuples' is the number of tuples in the relation
2151  * 'width' is the average tuple width in bytes
2152  * 'comparison_cost' is the extra cost per comparison, if any
2153  * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
2154  * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
2155  * 'startup_cost' is expected to be 0 at input. If there is "input cost" it should
2156  * be added by caller later
2157  */
2158 static void
2159 cost_tuplesort(PlannerInfo *root, List *pathkeys, Cost *startup_cost, Cost *run_cost,
2160  double tuples, int width,
2161  Cost comparison_cost, int sort_mem,
2162  double limit_tuples)
2163 {
2164  double input_bytes = relation_byte_size(tuples, width);
2165  double output_bytes;
2166  double output_tuples;
2167  long sort_mem_bytes = sort_mem * 1024L;
2168 
2169  /*
2170  * We want to be sure the cost of a sort is never estimated as zero, even
2171  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
2172  */
2173  if (tuples < 2.0)
2174  tuples = 2.0;
2175 
2176  /* Do we have a useful LIMIT? */
2177  if (limit_tuples > 0 && limit_tuples < tuples)
2178  {
2179  output_tuples = limit_tuples;
2180  output_bytes = relation_byte_size(output_tuples, width);
2181  }
2182  else
2183  {
2184  output_tuples = tuples;
2185  output_bytes = input_bytes;
2186  }
2187 
2188  if (output_bytes > sort_mem_bytes)
2189  {
2190  /*
2191  * We'll have to use a disk-based sort of all the tuples
2192  */
2193  double npages = ceil(input_bytes / BLCKSZ);
2194  double nruns = input_bytes / sort_mem_bytes;
2195  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
2196  double log_runs;
2197  double npageaccesses;
2198 
2199  /* CPU costs */
2200  *startup_cost = compute_cpu_sort_cost(root, pathkeys, 0,
2201  comparison_cost, tuples,
2202  tuples, false);
2203 
2204  /* Disk costs */
2205 
2206  /* Compute logM(r) as log(r) / log(M) */
2207  if (nruns > mergeorder)
2208  log_runs = ceil(log(nruns) / log(mergeorder));
2209  else
2210  log_runs = 1.0;
2211  npageaccesses = 2.0 * npages * log_runs;
2212  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
2213  *startup_cost += npageaccesses *
2214  (seq_page_cost * 0.75 + random_page_cost * 0.25);
2215  }
2216  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
2217  {
2218  /* We'll use a bounded heap-sort keeping just K tuples in memory. */
2219  *startup_cost = compute_cpu_sort_cost(root, pathkeys, 0,
2220  comparison_cost, tuples,
2221  output_tuples, true);
2222  }
2223  else
2224  {
2225  /* We'll use plain quicksort on all the input tuples */
2226  *startup_cost = compute_cpu_sort_cost(root, pathkeys, 0,
2227  comparison_cost, tuples,
2228  tuples, false);
2229  }
2230 
2231  /*
2232  * Also charge a small amount (arbitrarily set equal to operator cost) per
2233  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
2234  * doesn't do qual-checking or projection, so it has less overhead than
2235  * most plan nodes. Note it's correct to use tuples not output_tuples
2236  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
2237  * counting the LIMIT otherwise.
2238  */
2239  *run_cost = cpu_operator_cost * tuples;
2240 }
2241 
2242 /*
2243  * cost_incremental_sort
2244  * Determines and returns the cost of sorting a relation incrementally, when
2245  * the input path is presorted by a prefix of the pathkeys.
2246  *
2247  * 'presorted_keys' is the number of leading pathkeys by which the input path
2248  * is sorted.
2249  *
2250  * We estimate the number of groups into which the relation is divided by the
2251  * leading pathkeys, and then calculate the cost of sorting a single group
2252  * with tuplesort using cost_tuplesort().
2253  */
2254 void
2256  PlannerInfo *root, List *pathkeys, int presorted_keys,
2257  Cost input_startup_cost, Cost input_total_cost,
2258  double input_tuples, int width, Cost comparison_cost, int sort_mem,
2259  double limit_tuples)
2260 {
2261  Cost startup_cost,
2262  run_cost,
2263  input_run_cost = input_total_cost - input_startup_cost;
2264  double group_tuples,
2265  input_groups;
2266  Cost group_startup_cost,
2267  group_run_cost,
2268  group_input_run_cost;
2269  List *presortedExprs = NIL;
2270  ListCell *l;
2271  int i = 0;
2272  bool unknown_varno = false;
2273 
2274  Assert(presorted_keys != 0);
2275 
2276  /*
2277  * We want to be sure the cost of a sort is never estimated as zero, even
2278  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
2279  */
2280  if (input_tuples < 2.0)
2281  input_tuples = 2.0;
2282 
2283  /* Default estimate of number of groups, capped to one group per row. */
2284  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
2285 
2286  /*
2287  * Extract presorted keys as list of expressions.
2288  *
2289  * We need to be careful about Vars containing "varno 0" which might have
2290  * been introduced by generate_append_tlist, which would confuse
2291  * estimate_num_groups (in fact it'd fail for such expressions). See
2292  * recurse_set_operations which has to deal with the same issue.
2293  *
2294  * Unlike recurse_set_operations we can't access the original target list
2295  * here, and even if we could it's not very clear how useful would that be
2296  * for a set operation combining multiple tables. So we simply detect if
2297  * there are any expressions with "varno 0" and use the default
2298  * DEFAULT_NUM_DISTINCT in that case.
2299  *
2300  * We might also use either 1.0 (a single group) or input_tuples (each row
2301  * being a separate group), pretty much the worst and best case for
2302  * incremental sort. But those are extreme cases and using something in
2303  * between seems reasonable. Furthermore, generate_append_tlist is used
2304  * for set operations, which are likely to produce mostly unique output
2305  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2306  * while maintaining lower startup cost.
2307  */
2308  foreach(l, pathkeys)
2309  {
2310  PathKey *key = (PathKey *) lfirst(l);
2311  EquivalenceMember *member = (EquivalenceMember *)
2312  linitial(key->pk_eclass->ec_members);
2313 
2314  /*
2315  * Check if the expression contains Var with "varno 0" so that we
2316  * don't call estimate_num_groups in that case.
2317  */
2318  if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2319  {
2320  unknown_varno = true;
2321  break;
2322  }
2323 
2324  /* expression not containing any Vars with "varno 0" */
2325  presortedExprs = lappend(presortedExprs, member->em_expr);
2326 
2327  i++;
2328  if (i >= presorted_keys)
2329  break;
2330  }
2331 
2332  /* Estimate number of groups with equal presorted keys. */
2333  if (!unknown_varno)
2334  input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2335  NULL, NULL);
2336 
2337  group_tuples = input_tuples / input_groups;
2338  group_input_run_cost = input_run_cost / input_groups;
2339 
2340  /*
2341  * Estimate average cost of sorting of one group where presorted keys are
2342  * equal. Incremental sort is sensitive to distribution of tuples to the
2343  * groups, where we're relying on quite rough assumptions. Thus, we're
2344  * pessimistic about incremental sort performance and increase its average
2345  * group size by half.
2346  */
2347  cost_tuplesort(root, pathkeys, &group_startup_cost, &group_run_cost,
2348  1.5 * group_tuples, width, comparison_cost, sort_mem,
2349  limit_tuples);
2350 
2351  /*
2352  * Startup cost of incremental sort is the startup cost of its first group
2353  * plus the cost of its input.
2354  */
2355  startup_cost = group_startup_cost
2356  + input_startup_cost + group_input_run_cost;
2357 
2358  /*
2359  * After we started producing tuples from the first group, the cost of
2360  * producing all the tuples is given by the cost to finish processing this
2361  * group, plus the total cost to process the remaining groups, plus the
2362  * remaining cost of input.
2363  */
2364  run_cost = group_run_cost
2365  + (group_run_cost + group_startup_cost) * (input_groups - 1)
2366  + group_input_run_cost * (input_groups - 1);
2367 
2368  /*
2369  * Incremental sort adds some overhead by itself. Firstly, it has to
2370  * detect the sort groups. This is roughly equal to one extra copy and
2371  * comparison per tuple. Secondly, it has to reset the tuplesort context
2372  * for every group.
2373  */
2374  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2375  run_cost += 2.0 * cpu_tuple_cost * input_groups;
2376 
2377  path->rows = input_tuples;
2378  path->startup_cost = startup_cost;
2379  path->total_cost = startup_cost + run_cost;
2380 }
2381 
2382 /*
2383  * cost_sort
2384  * Determines and returns the cost of sorting a relation, including
2385  * the cost of reading the input data.
2386  *
2387  * NOTE: some callers currently pass NIL for pathkeys because they
2388  * can't conveniently supply the sort keys. Since this routine doesn't
2389  * currently do anything with pathkeys anyway, that doesn't matter...
2390  * but if it ever does, it should react gracefully to lack of key data.
2391  * (Actually, the thing we'd most likely be interested in is just the number
2392  * of sort keys, which all callers *could* supply.)
2393  */
2394 void
2396  List *pathkeys, Cost input_cost, double tuples, int width,
2397  Cost comparison_cost, int sort_mem,
2398  double limit_tuples)
2399 
2400 {
2401  Cost startup_cost;
2402  Cost run_cost;
2403 
2404  cost_tuplesort(root, pathkeys, &startup_cost, &run_cost,
2405  tuples, width,
2406  comparison_cost, sort_mem,
2407  limit_tuples);
2408 
2409  if (!enable_sort)
2410  startup_cost += disable_cost;
2411 
2412  startup_cost += input_cost;
2413 
2414  path->rows = tuples;
2415  path->startup_cost = startup_cost;
2416  path->total_cost = startup_cost + run_cost;
2417 }
2418 
2419 /*
2420  * append_nonpartial_cost
2421  * Estimate the cost of the non-partial paths in a Parallel Append.
2422  * The non-partial paths are assumed to be the first "numpaths" paths
2423  * from the subpaths list, and to be in order of decreasing cost.
2424  */
2425 static Cost
2426 append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
2427 {
2428  Cost *costarr;
2429  int arrlen;
2430  ListCell *l;
2431  ListCell *cell;
2432  int i;
2433  int path_index;
2434  int min_index;
2435  int max_index;
2436 
2437  if (numpaths == 0)
2438  return 0;
2439 
2440  /*
2441  * Array length is number of workers or number of relevant paths,
2442  * whichever is less.
2443  */
2444  arrlen = Min(parallel_workers, numpaths);
2445  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2446 
2447  /* The first few paths will each be claimed by a different worker. */
2448  path_index = 0;
2449  foreach(cell, subpaths)
2450  {
2451  Path *subpath = (Path *) lfirst(cell);
2452 
2453  if (path_index == arrlen)
2454  break;
2455  costarr[path_index++] = subpath->total_cost;
2456  }
2457 
2458  /*
2459  * Since subpaths are sorted by decreasing cost, the last one will have
2460  * the minimum cost.
2461  */
2462  min_index = arrlen - 1;
2463 
2464  /*
2465  * For each of the remaining subpaths, add its cost to the array element
2466  * with minimum cost.
2467  */
2468  for_each_cell(l, subpaths, cell)
2469  {
2470  Path *subpath = (Path *) lfirst(l);
2471  int i;
2472 
2473  /* Consider only the non-partial paths */
2474  if (path_index++ == numpaths)
2475  break;
2476 
2477  costarr[min_index] += subpath->total_cost;
2478 
2479  /* Update the new min cost array index */
2480  for (min_index = i = 0; i < arrlen; i++)
2481  {
2482  if (costarr[i] < costarr[min_index])
2483  min_index = i;
2484  }
2485  }
2486 
2487  /* Return the highest cost from the array */
2488  for (max_index = i = 0; i < arrlen; i++)
2489  {
2490  if (costarr[i] > costarr[max_index])
2491  max_index = i;
2492  }
2493 
2494  return costarr[max_index];
2495 }
2496 
2497 /*
2498  * cost_append
2499  * Determines and returns the cost of an Append node.
2500  */
2501 void
2503 {
2504  ListCell *l;
2505 
2506  apath->path.startup_cost = 0;
2507  apath->path.total_cost = 0;
2508  apath->path.rows = 0;
2509 
2510  if (apath->subpaths == NIL)
2511  return;
2512 
2513  if (!apath->path.parallel_aware)
2514  {
2515  List *pathkeys = apath->path.pathkeys;
2516 
2517  if (pathkeys == NIL)
2518  {
2519  Path *subpath = (Path *) linitial(apath->subpaths);
2520 
2521  /*
2522  * For an unordered, non-parallel-aware Append we take the startup
2523  * cost as the startup cost of the first subpath.
2524  */
2525  apath->path.startup_cost = subpath->startup_cost;
2526 
2527  /* Compute rows and costs as sums of subplan rows and costs. */
2528  foreach(l, apath->subpaths)
2529  {
2530  Path *subpath = (Path *) lfirst(l);
2531 
2532  apath->path.rows += subpath->rows;
2533  apath->path.total_cost += subpath->total_cost;
2534  }
2535  }
2536  else
2537  {
2538  /*
2539  * For an ordered, non-parallel-aware Append we take the startup
2540  * cost as the sum of the subpath startup costs. This ensures
2541  * that we don't underestimate the startup cost when a query's
2542  * LIMIT is such that several of the children have to be run to
2543  * satisfy it. This might be overkill --- another plausible hack
2544  * would be to take the Append's startup cost as the maximum of
2545  * the child startup costs. But we don't want to risk believing
2546  * that an ORDER BY LIMIT query can be satisfied at small cost
2547  * when the first child has small startup cost but later ones
2548  * don't. (If we had the ability to deal with nonlinear cost
2549  * interpolation for partial retrievals, we would not need to be
2550  * so conservative about this.)
2551  *
2552  * This case is also different from the above in that we have to
2553  * account for possibly injecting sorts into subpaths that aren't
2554  * natively ordered.
2555  */
2556  foreach(l, apath->subpaths)
2557  {
2558  Path *subpath = (Path *) lfirst(l);
2559  Path sort_path; /* dummy for result of cost_sort */
2560 
2561  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2562  {
2563  /*
2564  * We'll need to insert a Sort node, so include costs for
2565  * that. We can use the parent's LIMIT if any, since we
2566  * certainly won't pull more than that many tuples from
2567  * any child.
2568  */
2569  cost_sort(&sort_path,
2570  root,
2571  pathkeys,
2572  subpath->total_cost,
2573  subpath->rows,
2574  subpath->pathtarget->width,
2575  0.0,
2576  work_mem,
2577  apath->limit_tuples);
2578  subpath = &sort_path;
2579  }
2580 
2581  apath->path.rows += subpath->rows;
2582  apath->path.startup_cost += subpath->startup_cost;
2583  apath->path.total_cost += subpath->total_cost;
2584  }
2585  }
2586  }
2587  else /* parallel-aware */
2588  {
2589  int i = 0;
2590  double parallel_divisor = get_parallel_divisor(&apath->path);
2591 
2592  /* Parallel-aware Append never produces ordered output. */
2593  Assert(apath->path.pathkeys == NIL);
2594 
2595  /* Calculate startup cost. */
2596  foreach(l, apath->subpaths)
2597  {
2598  Path *subpath = (Path *) lfirst(l);
2599 
2600  /*
2601  * Append will start returning tuples when the child node having
2602  * lowest startup cost is done setting up. We consider only the
2603  * first few subplans that immediately get a worker assigned.
2604  */
2605  if (i == 0)
2606  apath->path.startup_cost = subpath->startup_cost;
2607  else if (i < apath->path.parallel_workers)
2608  apath->path.startup_cost = Min(apath->path.startup_cost,
2609  subpath->startup_cost);
2610 
2611  /*
2612  * Apply parallel divisor to subpaths. Scale the number of rows
2613  * for each partial subpath based on the ratio of the parallel
2614  * divisor originally used for the subpath to the one we adopted.
2615  * Also add the cost of partial paths to the total cost, but
2616  * ignore non-partial paths for now.
2617  */
2618  if (i < apath->first_partial_path)
2619  apath->path.rows += subpath->rows / parallel_divisor;
2620  else
2621  {
2622  double subpath_parallel_divisor;
2623 
2624  subpath_parallel_divisor = get_parallel_divisor(subpath);
2625  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2626  parallel_divisor);
2627  apath->path.total_cost += subpath->total_cost;
2628  }
2629 
2630  apath->path.rows = clamp_row_est(apath->path.rows);
2631 
2632  i++;
2633  }
2634 
2635  /* Add cost for non-partial subpaths. */
2636  apath->path.total_cost +=
2638  apath->first_partial_path,
2639  apath->path.parallel_workers);
2640  }
2641 
2642  /*
2643  * Although Append does not do any selection or projection, it's not free;
2644  * add a small per-tuple overhead.
2645  */
2646  apath->path.total_cost +=
2648 }
2649 
2650 /*
2651  * cost_merge_append
2652  * Determines and returns the cost of a MergeAppend node.
2653  *
2654  * MergeAppend merges several pre-sorted input streams, using a heap that
2655  * at any given instant holds the next tuple from each stream. If there
2656  * are N streams, we need about N*log2(N) tuple comparisons to construct
2657  * the heap at startup, and then for each output tuple, about log2(N)
2658  * comparisons to replace the top entry.
2659  *
2660  * (The effective value of N will drop once some of the input streams are
2661  * exhausted, but it seems unlikely to be worth trying to account for that.)
2662  *
2663  * The heap is never spilled to disk, since we assume N is not very large.
2664  * So this is much simpler than cost_sort.
2665  *
2666  * As in cost_sort, we charge two operator evals per tuple comparison.
2667  *
2668  * 'pathkeys' is a list of sort keys
2669  * 'n_streams' is the number of input streams
2670  * 'input_startup_cost' is the sum of the input streams' startup costs
2671  * 'input_total_cost' is the sum of the input streams' total costs
2672  * 'tuples' is the number of tuples in all the streams
2673  */
2674 void
2676  List *pathkeys, int n_streams,
2677  Cost input_startup_cost, Cost input_total_cost,
2678  double tuples)
2679 {
2680  Cost startup_cost = 0;
2681  Cost run_cost = 0;
2682  Cost comparison_cost;
2683  double N;
2684  double logN;
2685 
2686  /*
2687  * Avoid log(0)...
2688  */
2689  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2690  logN = LOG2(N);
2691 
2692  /* Assumed cost per tuple comparison */
2693  comparison_cost = 2.0 * cpu_operator_cost;
2694 
2695  /* Heap creation cost */
2696  startup_cost += comparison_cost * N * logN;
2697 
2698  /* Per-tuple heap maintenance cost */
2699  run_cost += tuples * comparison_cost * logN;
2700 
2701  /*
2702  * Although MergeAppend does not do any selection or projection, it's not
2703  * free; add a small per-tuple overhead.
2704  */
2705  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2706 
2707  path->startup_cost = startup_cost + input_startup_cost;
2708  path->total_cost = startup_cost + run_cost + input_total_cost;
2709 }
2710 
2711 /*
2712  * cost_material
2713  * Determines and returns the cost of materializing a relation, including
2714  * the cost of reading the input data.
2715  *
2716  * If the total volume of data to materialize exceeds work_mem, we will need
2717  * to write it to disk, so the cost is much higher in that case.
2718  *
2719  * Note that here we are estimating the costs for the first scan of the
2720  * relation, so the materialization is all overhead --- any savings will
2721  * occur only on rescan, which is estimated in cost_rescan.
2722  */
2723 void
2725  Cost input_startup_cost, Cost input_total_cost,
2726  double tuples, int width)
2727 {
2728  Cost startup_cost = input_startup_cost;
2729  Cost run_cost = input_total_cost - input_startup_cost;
2730  double nbytes = relation_byte_size(tuples, width);
2731  long work_mem_bytes = work_mem * 1024L;
2732 
2733  path->rows = tuples;
2734 
2735  /*
2736  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2737  * reflect bookkeeping overhead. (This rate must be more than what
2738  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2739  * if it is exactly the same then there will be a cost tie between
2740  * nestloop with A outer, materialized B inner and nestloop with B outer,
2741  * materialized A inner. The extra cost ensures we'll prefer
2742  * materializing the smaller rel.) Note that this is normally a good deal
2743  * less than cpu_tuple_cost; which is OK because a Material plan node
2744  * doesn't do qual-checking or projection, so it's got less overhead than
2745  * most plan nodes.
2746  */
2747  run_cost += 2 * cpu_operator_cost * tuples;
2748 
2749  /*
2750  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2751  * This cost is assumed to be evenly spread through the plan run phase,
2752  * which isn't exactly accurate but our cost model doesn't allow for
2753  * nonuniform costs within the run phase.
2754  */
2755  if (nbytes > work_mem_bytes)
2756  {
2757  double npages = ceil(nbytes / BLCKSZ);
2758 
2759  run_cost += seq_page_cost * npages;
2760  }
2761 
2762  path->startup_cost = startup_cost;
2763  path->total_cost = startup_cost + run_cost;
2764 }
2765 
2766 /*
2767  * cost_memoize_rescan
2768  * Determines the estimated cost of rescanning a Memoize node.
2769  *
2770  * In order to estimate this, we must gain knowledge of how often we expect to
2771  * be called and how many distinct sets of parameters we are likely to be
2772  * called with. If we expect a good cache hit ratio, then we can set our
2773  * costs to account for that hit ratio, plus a little bit of cost for the
2774  * caching itself. Caching will not work out well if we expect to be called
2775  * with too many distinct parameter values. The worst-case here is that we
2776  * never see any parameter value twice, in which case we'd never get a cache
2777  * hit and caching would be a complete waste of effort.
2778  */
2779 static void
2781  Cost *rescan_startup_cost, Cost *rescan_total_cost)
2782 {
2783  EstimationInfo estinfo;
2784  Cost input_startup_cost = mpath->subpath->startup_cost;
2785  Cost input_total_cost = mpath->subpath->total_cost;
2786  double tuples = mpath->subpath->rows;
2787  double calls = mpath->calls;
2788  int width = mpath->subpath->pathtarget->width;
2789 
2790  double hash_mem_bytes;
2791  double est_entry_bytes;
2792  double est_cache_entries;
2793  double ndistinct;
2794  double evict_ratio;
2795  double hit_ratio;
2796  Cost startup_cost;
2797  Cost total_cost;
2798 
2799  /* available cache space */
2800  hash_mem_bytes = get_hash_memory_limit();
2801 
2802  /*
2803  * Set the number of bytes each cache entry should consume in the cache.
2804  * To provide us with better estimations on how many cache entries we can
2805  * store at once, we make a call to the executor here to ask it what
2806  * memory overheads there are for a single cache entry.
2807  *
2808  * XXX we also store the cache key, but that's not accounted for here.
2809  */
2810  est_entry_bytes = relation_byte_size(tuples, width) +
2812 
2813  /* estimate on the upper limit of cache entries we can hold at once */
2814  est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2815 
2816  /* estimate on the distinct number of parameter values */
2817  ndistinct = estimate_num_groups(root, mpath->param_exprs, calls, NULL,
2818  &estinfo);
2819 
2820  /*
2821  * When the estimation fell back on using a default value, it's a bit too
2822  * risky to assume that it's ok to use a Memoize node. The use of a
2823  * default could cause us to use a Memoize node when it's really
2824  * inappropriate to do so. If we see that this has been done, then we'll
2825  * assume that every call will have unique parameters, which will almost
2826  * certainly mean a MemoizePath will never survive add_path().
2827  */
2828  if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2829  ndistinct = calls;
2830 
2831  /*
2832  * Since we've already estimated the maximum number of entries we can
2833  * store at once and know the estimated number of distinct values we'll be
2834  * called with, we'll take this opportunity to set the path's est_entries.
2835  * This will ultimately determine the hash table size that the executor
2836  * will use. If we leave this at zero, the executor will just choose the
2837  * size itself. Really this is not the right place to do this, but it's
2838  * convenient since everything is already calculated.
2839  */
2840  mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2841  PG_UINT32_MAX);
2842 
2843  /*
2844  * When the number of distinct parameter values is above the amount we can
2845  * store in the cache, then we'll have to evict some entries from the
2846  * cache. This is not free. Here we estimate how often we'll incur the
2847  * cost of that eviction.
2848  */
2849  evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2850 
2851  /*
2852  * In order to estimate how costly a single scan will be, we need to
2853  * attempt to estimate what the cache hit ratio will be. To do that we
2854  * must look at how many scans are estimated in total for this node and
2855  * how many of those scans we expect to get a cache hit.
2856  */
2857  hit_ratio = 1.0 / ndistinct * Min(est_cache_entries, ndistinct) -
2858  (ndistinct / calls);
2859 
2860  /* Ensure we don't go negative */
2861  hit_ratio = Max(hit_ratio, 0.0);
2862 
2863  /*
2864  * Set the total_cost accounting for the expected cache hit ratio. We
2865  * also add on a cpu_operator_cost to account for a cache lookup. This
2866  * will happen regardless of whether it's a cache hit or not.
2867  */
2868  total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2869 
2870  /* Now adjust the total cost to account for cache evictions */
2871 
2872  /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2873  total_cost += cpu_tuple_cost * evict_ratio;
2874 
2875  /*
2876  * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2877  * The per-tuple eviction is really just a pfree, so charging a whole
2878  * cpu_operator_cost seems a little excessive.
2879  */
2880  total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2881 
2882  /*
2883  * Now adjust for storing things in the cache, since that's not free
2884  * either. Everything must go in the cache. We don't proportion this
2885  * over any ratio, just apply it once for the scan. We charge a
2886  * cpu_tuple_cost for the creation of the cache entry and also a
2887  * cpu_operator_cost for each tuple we expect to cache.
2888  */
2889  total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2890 
2891  /*
2892  * Getting the first row must be also be proportioned according to the
2893  * expected cache hit ratio.
2894  */
2895  startup_cost = input_startup_cost * (1.0 - hit_ratio);
2896 
2897  /*
2898  * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2899  * which we'll do regardless of whether it was a cache hit or not.
2900  */
2901  startup_cost += cpu_tuple_cost;
2902 
2903  *rescan_startup_cost = startup_cost;
2904  *rescan_total_cost = total_cost;
2905 }
2906 
2907 /*
2908  * cost_agg
2909  * Determines and returns the cost of performing an Agg plan node,
2910  * including the cost of its input.
2911  *
2912  * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
2913  * we are using a hashed Agg node just to do grouping).
2914  *
2915  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
2916  * are for appropriately-sorted input.
2917  */
2918 void
2920  AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
2921  int numGroupCols, double numGroups,
2922  List *quals,
2923  Cost input_startup_cost, Cost input_total_cost,
2924  double input_tuples, double input_width)
2925 {
2926  double output_tuples;
2927  Cost startup_cost;
2928  Cost total_cost;
2929  AggClauseCosts dummy_aggcosts;
2930 
2931  /* Use all-zero per-aggregate costs if NULL is passed */
2932  if (aggcosts == NULL)
2933  {
2934  Assert(aggstrategy == AGG_HASHED);
2935  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2936  aggcosts = &dummy_aggcosts;
2937  }
2938 
2939  /*
2940  * The transCost.per_tuple component of aggcosts should be charged once
2941  * per input tuple, corresponding to the costs of evaluating the aggregate
2942  * transfns and their input expressions. The finalCost.per_tuple component
2943  * is charged once per output tuple, corresponding to the costs of
2944  * evaluating the finalfns. Startup costs are of course charged but once.
2945  *
2946  * If we are grouping, we charge an additional cpu_operator_cost per
2947  * grouping column per input tuple for grouping comparisons.
2948  *
2949  * We will produce a single output tuple if not grouping, and a tuple per
2950  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2951  *
2952  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2953  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2954  * input path is already sorted appropriately, AGG_SORTED should be
2955  * preferred (since it has no risk of memory overflow). This will happen
2956  * as long as the computed total costs are indeed exactly equal --- but if
2957  * there's roundoff error we might do the wrong thing. So be sure that
2958  * the computations below form the same intermediate values in the same
2959  * order.
2960  */
2961  if (aggstrategy == AGG_PLAIN)
2962  {
2963  startup_cost = input_total_cost;
2964  startup_cost += aggcosts->transCost.startup;
2965  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2966  startup_cost += aggcosts->finalCost.startup;
2967  startup_cost += aggcosts->finalCost.per_tuple;
2968  /* we aren't grouping */
2969  total_cost = startup_cost + cpu_tuple_cost;
2970  output_tuples = 1;
2971  }
2972  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2973  {
2974  /* Here we are able to deliver output on-the-fly */
2975  startup_cost = input_startup_cost;
2976  total_cost = input_total_cost;
2977  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2978  {
2979  startup_cost += disable_cost;
2980  total_cost += disable_cost;
2981  }
2982  /* calcs phrased this way to match HASHED case, see note above */
2983  total_cost += aggcosts->transCost.startup;
2984  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2985  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2986  total_cost += aggcosts->finalCost.startup;
2987  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2988  total_cost += cpu_tuple_cost * numGroups;
2989  output_tuples = numGroups;
2990  }
2991  else
2992  {
2993  /* must be AGG_HASHED */
2994  startup_cost = input_total_cost;
2995  if (!enable_hashagg)
2996  startup_cost += disable_cost;
2997  startup_cost += aggcosts->transCost.startup;
2998  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2999  /* cost of computing hash value */
3000  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
3001  startup_cost += aggcosts->finalCost.startup;
3002 
3003  total_cost = startup_cost;
3004  total_cost += aggcosts->finalCost.per_tuple * numGroups;
3005  /* cost of retrieving from hash table */
3006  total_cost += cpu_tuple_cost * numGroups;
3007  output_tuples = numGroups;
3008  }
3009 
3010  /*
3011  * Add the disk costs of hash aggregation that spills to disk.
3012  *
3013  * Groups that go into the hash table stay in memory until finalized, so
3014  * spilling and reprocessing tuples doesn't incur additional invocations
3015  * of transCost or finalCost. Furthermore, the computed hash value is
3016  * stored with the spilled tuples, so we don't incur extra invocations of
3017  * the hash function.
3018  *
3019  * Hash Agg begins returning tuples after the first batch is complete.
3020  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
3021  * accrue reads only to total_cost.
3022  */
3023  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
3024  {
3025  double pages;
3026  double pages_written = 0.0;
3027  double pages_read = 0.0;
3028  double spill_cost;
3029  double hashentrysize;
3030  double nbatches;
3031  Size mem_limit;
3032  uint64 ngroups_limit;
3033  int num_partitions;
3034  int depth;
3035 
3036  /*
3037  * Estimate number of batches based on the computed limits. If less
3038  * than or equal to one, all groups are expected to fit in memory;
3039  * otherwise we expect to spill.
3040  */
3041  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
3042  input_width,
3043  aggcosts->transitionSpace);
3044  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
3045  &ngroups_limit, &num_partitions);
3046 
3047  nbatches = Max((numGroups * hashentrysize) / mem_limit,
3048  numGroups / ngroups_limit);
3049 
3050  nbatches = Max(ceil(nbatches), 1.0);
3051  num_partitions = Max(num_partitions, 2);
3052 
3053  /*
3054  * The number of partitions can change at different levels of
3055  * recursion; but for the purposes of this calculation assume it stays
3056  * constant.
3057  */
3058  depth = ceil(log(nbatches) / log(num_partitions));
3059 
3060  /*
3061  * Estimate number of pages read and written. For each level of
3062  * recursion, a tuple must be written and then later read.
3063  */
3064  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
3065  pages_written = pages_read = pages * depth;
3066 
3067  /*
3068  * HashAgg has somewhat worse IO behavior than Sort on typical
3069  * hardware/OS combinations. Account for this with a generic penalty.
3070  */
3071  pages_read *= 2.0;
3072  pages_written *= 2.0;
3073 
3074  startup_cost += pages_written * random_page_cost;
3075  total_cost += pages_written * random_page_cost;
3076  total_cost += pages_read * seq_page_cost;
3077 
3078  /* account for CPU cost of spilling a tuple and reading it back */
3079  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
3080  startup_cost += spill_cost;
3081  total_cost += spill_cost;
3082  }
3083 
3084  /*
3085  * If there are quals (HAVING quals), account for their cost and
3086  * selectivity.
3087  */
3088  if (quals)
3089  {
3090  QualCost qual_cost;
3091 
3092  cost_qual_eval(&qual_cost, quals, root);
3093  startup_cost += qual_cost.startup;
3094  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3095 
3096  output_tuples = clamp_row_est(output_tuples *
3098  quals,
3099  0,
3100  JOIN_INNER,
3101  NULL));
3102  }
3103 
3104  path->rows = output_tuples;
3105  path->startup_cost = startup_cost;
3106  path->total_cost = total_cost;
3107 }
3108 
3109 /*
3110  * cost_windowagg
3111  * Determines and returns the cost of performing a WindowAgg plan node,
3112  * including the cost of its input.
3113  *
3114  * Input is assumed already properly sorted.
3115  */
3116 void
3118  List *windowFuncs, int numPartCols, int numOrderCols,
3119  Cost input_startup_cost, Cost input_total_cost,
3120  double input_tuples)
3121 {
3122  Cost startup_cost;
3123  Cost total_cost;
3124  ListCell *lc;
3125 
3126  startup_cost = input_startup_cost;
3127  total_cost = input_total_cost;
3128 
3129  /*
3130  * Window functions are assumed to cost their stated execution cost, plus
3131  * the cost of evaluating their input expressions, per tuple. Since they
3132  * may in fact evaluate their inputs at multiple rows during each cycle,
3133  * this could be a drastic underestimate; but without a way to know how
3134  * many rows the window function will fetch, it's hard to do better. In
3135  * any case, it's a good estimate for all the built-in window functions,
3136  * so we'll just do this for now.
3137  */
3138  foreach(lc, windowFuncs)
3139  {
3140  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3141  Cost wfunccost;
3142  QualCost argcosts;
3143 
3144  argcosts.startup = argcosts.per_tuple = 0;
3145  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3146  &argcosts);
3147  startup_cost += argcosts.startup;
3148  wfunccost = argcosts.per_tuple;
3149 
3150  /* also add the input expressions' cost to per-input-row costs */
3151  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3152  startup_cost += argcosts.startup;
3153  wfunccost += argcosts.per_tuple;
3154 
3155  /*
3156  * Add the filter's cost to per-input-row costs. XXX We should reduce
3157  * input expression costs according to filter selectivity.
3158  */
3159  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3160  startup_cost += argcosts.startup;
3161  wfunccost += argcosts.per_tuple;
3162 
3163  total_cost += wfunccost * input_tuples;
3164  }
3165 
3166  /*
3167  * We also charge cpu_operator_cost per grouping column per tuple for
3168  * grouping comparisons, plus cpu_tuple_cost per tuple for general
3169  * overhead.
3170  *
3171  * XXX this neglects costs of spooling the data to disk when it overflows
3172  * work_mem. Sooner or later that should get accounted for.
3173  */
3174  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3175  total_cost += cpu_tuple_cost * input_tuples;
3176 
3177  path->rows = input_tuples;
3178  path->startup_cost = startup_cost;
3179  path->total_cost = total_cost;
3180 }
3181 
3182 /*
3183  * cost_group
3184  * Determines and returns the cost of performing a Group plan node,
3185  * including the cost of its input.
3186  *
3187  * Note: caller must ensure that input costs are for appropriately-sorted
3188  * input.
3189  */
3190 void
3192  int numGroupCols, double numGroups,
3193  List *quals,
3194  Cost input_startup_cost, Cost input_total_cost,
3195  double input_tuples)
3196 {
3197  double output_tuples;
3198  Cost startup_cost;
3199  Cost total_cost;
3200 
3201  output_tuples = numGroups;
3202  startup_cost = input_startup_cost;
3203  total_cost = input_total_cost;
3204 
3205  /*
3206  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3207  * all columns get compared at most of the tuples.
3208  */
3209  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3210 
3211  /*
3212  * If there are quals (HAVING quals), account for their cost and
3213  * selectivity.
3214  */
3215  if (quals)
3216  {
3217  QualCost qual_cost;
3218 
3219  cost_qual_eval(&qual_cost, quals, root);
3220  startup_cost += qual_cost.startup;
3221  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3222 
3223  output_tuples = clamp_row_est(output_tuples *
3225  quals,
3226  0,
3227  JOIN_INNER,
3228  NULL));
3229  }
3230 
3231  path->rows = output_tuples;
3232  path->startup_cost = startup_cost;
3233  path->total_cost = total_cost;
3234 }
3235 
3236 /*
3237  * initial_cost_nestloop
3238  * Preliminary estimate of the cost of a nestloop join path.
3239  *
3240  * This must quickly produce lower-bound estimates of the path's startup and
3241  * total costs. If we are unable to eliminate the proposed path from
3242  * consideration using the lower bounds, final_cost_nestloop will be called
3243  * to obtain the final estimates.
3244  *
3245  * The exact division of labor between this function and final_cost_nestloop
3246  * is private to them, and represents a tradeoff between speed of the initial
3247  * estimate and getting a tight lower bound. We choose to not examine the
3248  * join quals here, since that's by far the most expensive part of the
3249  * calculations. The end result is that CPU-cost considerations must be
3250  * left for the second phase; and for SEMI/ANTI joins, we must also postpone
3251  * incorporation of the inner path's run cost.
3252  *
3253  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
3254  * other data to be used by final_cost_nestloop
3255  * 'jointype' is the type of join to be performed
3256  * 'outer_path' is the outer input to the join
3257  * 'inner_path' is the inner input to the join
3258  * 'extra' contains miscellaneous information about the join
3259  */
3260 void
3262  JoinType jointype,
3263  Path *outer_path, Path *inner_path,
3264  JoinPathExtraData *extra)
3265 {
3266  Cost startup_cost = 0;
3267  Cost run_cost = 0;
3268  double outer_path_rows = outer_path->rows;
3269  Cost inner_rescan_start_cost;
3270  Cost inner_rescan_total_cost;
3271  Cost inner_run_cost;
3272  Cost inner_rescan_run_cost;
3273 
3274  /* estimate costs to rescan the inner relation */
3275  cost_rescan(root, inner_path,
3276  &inner_rescan_start_cost,
3277  &inner_rescan_total_cost);
3278 
3279  /* cost of source data */
3280 
3281  /*
3282  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3283  * before we can start returning tuples, so the join's startup cost is
3284  * their sum. We'll also pay the inner path's rescan startup cost
3285  * multiple times.
3286  */
3287  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3288  run_cost += outer_path->total_cost - outer_path->startup_cost;
3289  if (outer_path_rows > 1)
3290  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3291 
3292  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3293  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3294 
3295  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3296  extra->inner_unique)
3297  {
3298  /*
3299  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3300  * executor will stop after the first match.
3301  *
3302  * Getting decent estimates requires inspection of the join quals,
3303  * which we choose to postpone to final_cost_nestloop.
3304  */
3305 
3306  /* Save private data for final_cost_nestloop */
3307  workspace->inner_run_cost = inner_run_cost;
3308  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3309  }
3310  else
3311  {
3312  /* Normal case; we'll scan whole input rel for each outer row */
3313  run_cost += inner_run_cost;
3314  if (outer_path_rows > 1)
3315  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3316  }
3317 
3318  /* CPU costs left for later */
3319 
3320  /* Public result fields */
3321  workspace->startup_cost = startup_cost;
3322  workspace->total_cost = startup_cost + run_cost;
3323  /* Save private data for final_cost_nestloop */
3324  workspace->run_cost = run_cost;
3325 }
3326 
3327 /*
3328  * final_cost_nestloop
3329  * Final estimate of the cost and result size of a nestloop join path.
3330  *
3331  * 'path' is already filled in except for the rows and cost fields
3332  * 'workspace' is the result from initial_cost_nestloop
3333  * 'extra' contains miscellaneous information about the join
3334  */
3335 void
3337  JoinCostWorkspace *workspace,
3338  JoinPathExtraData *extra)
3339 {
3340  Path *outer_path = path->jpath.outerjoinpath;
3341  Path *inner_path = path->jpath.innerjoinpath;
3342  double outer_path_rows = outer_path->rows;
3343  double inner_path_rows = inner_path->rows;
3344  Cost startup_cost = workspace->startup_cost;
3345  Cost run_cost = workspace->run_cost;
3346  Cost cpu_per_tuple;
3347  QualCost restrict_qual_cost;
3348  double ntuples;
3349 
3350  /* Protect some assumptions below that rowcounts aren't zero */
3351  if (outer_path_rows <= 0)
3352  outer_path_rows = 1;
3353  if (inner_path_rows <= 0)
3354  inner_path_rows = 1;
3355  /* Mark the path with the correct row estimate */
3356  if (path->jpath.path.param_info)
3357  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3358  else
3359  path->jpath.path.rows = path->jpath.path.parent->rows;
3360 
3361  /* For partial paths, scale row estimate. */
3362  if (path->jpath.path.parallel_workers > 0)
3363  {
3364  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3365 
3366  path->jpath.path.rows =
3367  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3368  }
3369 
3370  /*
3371  * We could include disable_cost in the preliminary estimate, but that
3372  * would amount to optimizing for the case where the join method is
3373  * disabled, which doesn't seem like the way to bet.
3374  */
3375  if (!enable_nestloop)
3376  startup_cost += disable_cost;
3377 
3378  /* cost of inner-relation source data (we already dealt with outer rel) */
3379 
3380  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3381  extra->inner_unique)
3382  {
3383  /*
3384  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3385  * executor will stop after the first match.
3386  */
3387  Cost inner_run_cost = workspace->inner_run_cost;
3388  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3389  double outer_matched_rows;
3390  double outer_unmatched_rows;
3391  Selectivity inner_scan_frac;
3392 
3393  /*
3394  * For an outer-rel row that has at least one match, we can expect the
3395  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3396  * rows, if the matches are evenly distributed. Since they probably
3397  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3398  * that fraction. (If we used a larger fuzz factor, we'd have to
3399  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3400  * least 1, no such clamp is needed now.)
3401  */
3402  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3403  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3404  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3405 
3406  /*
3407  * Compute number of tuples processed (not number emitted!). First,
3408  * account for successfully-matched outer rows.
3409  */
3410  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3411 
3412  /*
3413  * Now we need to estimate the actual costs of scanning the inner
3414  * relation, which may be quite a bit less than N times inner_run_cost
3415  * due to early scan stops. We consider two cases. If the inner path
3416  * is an indexscan using all the joinquals as indexquals, then an
3417  * unmatched outer row results in an indexscan returning no rows,
3418  * which is probably quite cheap. Otherwise, the executor will have
3419  * to scan the whole inner rel for an unmatched row; not so cheap.
3420  */
3421  if (has_indexed_join_quals(path))
3422  {
3423  /*
3424  * Successfully-matched outer rows will only require scanning
3425  * inner_scan_frac of the inner relation. In this case, we don't
3426  * need to charge the full inner_run_cost even when that's more
3427  * than inner_rescan_run_cost, because we can assume that none of
3428  * the inner scans ever scan the whole inner relation. So it's
3429  * okay to assume that all the inner scan executions can be
3430  * fractions of the full cost, even if materialization is reducing
3431  * the rescan cost. At this writing, it's impossible to get here
3432  * for a materialized inner scan, so inner_run_cost and
3433  * inner_rescan_run_cost will be the same anyway; but just in
3434  * case, use inner_run_cost for the first matched tuple and
3435  * inner_rescan_run_cost for additional ones.
3436  */
3437  run_cost += inner_run_cost * inner_scan_frac;
3438  if (outer_matched_rows > 1)
3439  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3440 
3441  /*
3442  * Add the cost of inner-scan executions for unmatched outer rows.
3443  * We estimate this as the same cost as returning the first tuple
3444  * of a nonempty scan. We consider that these are all rescans,
3445  * since we used inner_run_cost once already.
3446  */
3447  run_cost += outer_unmatched_rows *
3448  inner_rescan_run_cost / inner_path_rows;
3449 
3450  /*
3451  * We won't be evaluating any quals at all for unmatched rows, so
3452  * don't add them to ntuples.
3453  */
3454  }
3455  else
3456  {
3457  /*
3458  * Here, a complicating factor is that rescans may be cheaper than
3459  * first scans. If we never scan all the way to the end of the
3460  * inner rel, it might be (depending on the plan type) that we'd
3461  * never pay the whole inner first-scan run cost. However it is
3462  * difficult to estimate whether that will happen (and it could
3463  * not happen if there are any unmatched outer rows!), so be
3464  * conservative and always charge the whole first-scan cost once.
3465  * We consider this charge to correspond to the first unmatched
3466  * outer row, unless there isn't one in our estimate, in which
3467  * case blame it on the first matched row.
3468  */
3469 
3470  /* First, count all unmatched join tuples as being processed */
3471  ntuples += outer_unmatched_rows * inner_path_rows;
3472 
3473  /* Now add the forced full scan, and decrement appropriate count */
3474  run_cost += inner_run_cost;
3475  if (outer_unmatched_rows >= 1)
3476  outer_unmatched_rows -= 1;
3477  else
3478  outer_matched_rows -= 1;
3479 
3480  /* Add inner run cost for additional outer tuples having matches */
3481  if (outer_matched_rows > 0)
3482  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3483 
3484  /* Add inner run cost for additional unmatched outer tuples */
3485  if (outer_unmatched_rows > 0)
3486  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3487  }
3488  }
3489  else
3490  {
3491  /* Normal-case source costs were included in preliminary estimate */
3492 
3493  /* Compute number of tuples processed (not number emitted!) */
3494  ntuples = outer_path_rows * inner_path_rows;
3495  }
3496 
3497  /* CPU costs */
3498  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3499  startup_cost += restrict_qual_cost.startup;
3500  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3501  run_cost += cpu_per_tuple * ntuples;
3502 
3503  /* tlist eval costs are paid per output row, not per tuple scanned */
3504  startup_cost += path->jpath.path.pathtarget->cost.startup;
3505  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3506 
3507  path->jpath.path.startup_cost = startup_cost;
3508  path->jpath.path.total_cost = startup_cost + run_cost;
3509 }
3510 
3511 /*
3512  * initial_cost_mergejoin
3513  * Preliminary estimate of the cost of a mergejoin path.
3514  *
3515  * This must quickly produce lower-bound estimates of the path's startup and
3516  * total costs. If we are unable to eliminate the proposed path from
3517  * consideration using the lower bounds, final_cost_mergejoin will be called
3518  * to obtain the final estimates.
3519  *
3520  * The exact division of labor between this function and final_cost_mergejoin
3521  * is private to them, and represents a tradeoff between speed of the initial
3522  * estimate and getting a tight lower bound. We choose to not examine the
3523  * join quals here, except for obtaining the scan selectivity estimate which
3524  * is really essential (but fortunately, use of caching keeps the cost of
3525  * getting that down to something reasonable).
3526  * We also assume that cost_sort is cheap enough to use here.
3527  *
3528  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
3529  * other data to be used by final_cost_mergejoin
3530  * 'jointype' is the type of join to be performed
3531  * 'mergeclauses' is the list of joinclauses to be used as merge clauses
3532  * 'outer_path' is the outer input to the join
3533  * 'inner_path' is the inner input to the join
3534  * 'outersortkeys' is the list of sort keys for the outer path
3535  * 'innersortkeys' is the list of sort keys for the inner path
3536  * 'extra' contains miscellaneous information about the join
3537  *
3538  * Note: outersortkeys and innersortkeys should be NIL if no explicit
3539  * sort is needed because the respective source path is already ordered.
3540  */
3541 void
3543  JoinType jointype,
3544  List *mergeclauses,
3545  Path *outer_path, Path *inner_path,
3546  List *outersortkeys, List *innersortkeys,
3547  JoinPathExtraData *extra)
3548 {
3549  Cost startup_cost = 0;
3550  Cost run_cost = 0;
3551  double outer_path_rows = outer_path->rows;
3552  double inner_path_rows = inner_path->rows;
3553  Cost inner_run_cost;
3554  double outer_rows,
3555  inner_rows,
3556  outer_skip_rows,
3557  inner_skip_rows;
3558  Selectivity outerstartsel,
3559  outerendsel,
3560  innerstartsel,
3561  innerendsel;
3562  Path sort_path; /* dummy for result of cost_sort */
3563 
3564  /* Protect some assumptions below that rowcounts aren't zero */
3565  if (outer_path_rows <= 0)
3566  outer_path_rows = 1;
3567  if (inner_path_rows <= 0)
3568  inner_path_rows = 1;
3569 
3570  /*
3571  * A merge join will stop as soon as it exhausts either input stream
3572  * (unless it's an outer join, in which case the outer side has to be
3573  * scanned all the way anyway). Estimate fraction of the left and right
3574  * inputs that will actually need to be scanned. Likewise, we can
3575  * estimate the number of rows that will be skipped before the first join
3576  * pair is found, which should be factored into startup cost. We use only
3577  * the first (most significant) merge clause for this purpose. Since
3578  * mergejoinscansel() is a fairly expensive computation, we cache the
3579  * results in the merge clause RestrictInfo.
3580  */
3581  if (mergeclauses && jointype != JOIN_FULL)
3582  {
3583  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3584  List *opathkeys;
3585  List *ipathkeys;
3586  PathKey *opathkey;
3587  PathKey *ipathkey;
3588  MergeScanSelCache *cache;
3589 
3590  /* Get the input pathkeys to determine the sort-order details */
3591  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3592  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3593  Assert(opathkeys);
3594  Assert(ipathkeys);
3595  opathkey = (PathKey *) linitial(opathkeys);
3596  ipathkey = (PathKey *) linitial(ipathkeys);
3597  /* debugging check */
3598  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3599  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3600  opathkey->pk_strategy != ipathkey->pk_strategy ||
3601  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3602  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3603 
3604  /* Get the selectivity with caching */
3605  cache = cached_scansel(root, firstclause, opathkey);
3606 
3607  if (bms_is_subset(firstclause->left_relids,
3608  outer_path->parent->relids))
3609  {
3610  /* left side of clause is outer */
3611  outerstartsel = cache->leftstartsel;
3612  outerendsel = cache->leftendsel;
3613  innerstartsel = cache->rightstartsel;
3614  innerendsel = cache->rightendsel;
3615  }
3616  else
3617  {
3618  /* left side of clause is inner */
3619  outerstartsel = cache->rightstartsel;
3620  outerendsel = cache->rightendsel;
3621  innerstartsel = cache->leftstartsel;
3622  innerendsel = cache->leftendsel;
3623  }
3624  if (jointype == JOIN_LEFT ||
3625  jointype == JOIN_ANTI)
3626  {
3627  outerstartsel = 0.0;
3628  outerendsel = 1.0;
3629  }
3630  else if (jointype == JOIN_RIGHT)
3631  {
3632  innerstartsel = 0.0;
3633  innerendsel = 1.0;
3634  }
3635  }
3636  else
3637  {
3638  /* cope with clauseless or full mergejoin */
3639  outerstartsel = innerstartsel = 0.0;
3640  outerendsel = innerendsel = 1.0;
3641  }
3642 
3643  /*
3644  * Convert selectivities to row counts. We force outer_rows and
3645  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3646  */
3647  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3648  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3649  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3650  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3651 
3652  Assert(outer_skip_rows <= outer_rows);
3653  Assert(inner_skip_rows <= inner_rows);
3654 
3655  /*
3656  * Readjust scan selectivities to account for above rounding. This is
3657  * normally an insignificant effect, but when there are only a few rows in
3658  * the inputs, failing to do this makes for a large percentage error.
3659  */
3660  outerstartsel = outer_skip_rows / outer_path_rows;
3661  innerstartsel = inner_skip_rows / inner_path_rows;
3662  outerendsel = outer_rows / outer_path_rows;
3663  innerendsel = inner_rows / inner_path_rows;
3664 
3665  Assert(outerstartsel <= outerendsel);
3666  Assert(innerstartsel <= innerendsel);
3667 
3668  /* cost of source data */
3669 
3670  if (outersortkeys) /* do we need to sort outer? */
3671  {
3672  cost_sort(&sort_path,
3673  root,
3674  outersortkeys,
3675  outer_path->total_cost,
3676  outer_path_rows,
3677  outer_path->pathtarget->width,
3678  0.0,
3679  work_mem,
3680  -1.0);
3681  startup_cost += sort_path.startup_cost;
3682  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3683  * outerstartsel;
3684  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3685  * (outerendsel - outerstartsel);
3686  }
3687  else
3688  {
3689  startup_cost += outer_path->startup_cost;
3690  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3691  * outerstartsel;
3692  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3693  * (outerendsel - outerstartsel);
3694  }
3695 
3696  if (innersortkeys) /* do we need to sort inner? */
3697  {
3698  cost_sort(&sort_path,
3699  root,
3700  innersortkeys,
3701  inner_path->total_cost,
3702  inner_path_rows,
3703  inner_path->pathtarget->width,
3704  0.0,
3705  work_mem,
3706  -1.0);
3707  startup_cost += sort_path.startup_cost;
3708  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3709  * innerstartsel;
3710  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3711  * (innerendsel - innerstartsel);
3712  }
3713  else
3714  {
3715  startup_cost += inner_path->startup_cost;
3716  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3717  * innerstartsel;
3718  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3719  * (innerendsel - innerstartsel);
3720  }
3721 
3722  /*
3723  * We can't yet determine whether rescanning occurs, or whether
3724  * materialization of the inner input should be done. The minimum
3725  * possible inner input cost, regardless of rescan and materialization
3726  * considerations, is inner_run_cost. We include that in
3727  * workspace->total_cost, but not yet in run_cost.
3728  */
3729 
3730  /* CPU costs left for later */
3731 
3732  /* Public result fields */
3733  workspace->startup_cost = startup_cost;
3734  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3735  /* Save private data for final_cost_mergejoin */
3736  workspace->run_cost = run_cost;
3737  workspace->inner_run_cost = inner_run_cost;
3738  workspace->outer_rows = outer_rows;
3739  workspace->inner_rows = inner_rows;
3740  workspace->outer_skip_rows = outer_skip_rows;
3741  workspace->inner_skip_rows = inner_skip_rows;
3742 }
3743 
3744 /*
3745  * final_cost_mergejoin
3746  * Final estimate of the cost and result size of a mergejoin path.
3747  *
3748  * Unlike other costsize functions, this routine makes two actual decisions:
3749  * whether the executor will need to do mark/restore, and whether we should
3750  * materialize the inner path. It would be logically cleaner to build
3751  * separate paths testing these alternatives, but that would require repeating
3752  * most of the cost calculations, which are not all that cheap. Since the
3753  * choice will not affect output pathkeys or startup cost, only total cost,
3754  * there is no possibility of wanting to keep more than one path. So it seems
3755  * best to make the decisions here and record them in the path's
3756  * skip_mark_restore and materialize_inner fields.
3757  *
3758  * Mark/restore overhead is usually required, but can be skipped if we know
3759  * that the executor need find only one match per outer tuple, and that the
3760  * mergeclauses are sufficient to identify a match.
3761  *
3762  * We materialize the inner path if we need mark/restore and either the inner
3763  * path can't support mark/restore, or it's cheaper to use an interposed
3764  * Material node to handle mark/restore.
3765  *
3766  * 'path' is already filled in except for the rows and cost fields and
3767  * skip_mark_restore and materialize_inner
3768  * 'workspace' is the result from initial_cost_mergejoin
3769  * 'extra' contains miscellaneous information about the join
3770  */
3771 void
3773  JoinCostWorkspace *workspace,
3774  JoinPathExtraData *extra)
3775 {
3776  Path *outer_path = path->jpath.outerjoinpath;
3777  Path *inner_path = path->jpath.innerjoinpath;
3778  double inner_path_rows = inner_path->rows;
3779  List *mergeclauses = path->path_mergeclauses;
3780  List *innersortkeys = path->innersortkeys;
3781  Cost startup_cost = workspace->startup_cost;
3782  Cost run_cost = workspace->run_cost;
3783  Cost inner_run_cost = workspace->inner_run_cost;
3784  double outer_rows = workspace->outer_rows;
3785  double inner_rows = workspace->inner_rows;
3786  double outer_skip_rows = workspace->outer_skip_rows;
3787  double inner_skip_rows = workspace->inner_skip_rows;
3788  Cost cpu_per_tuple,
3789  bare_inner_cost,
3790  mat_inner_cost;
3791  QualCost merge_qual_cost;
3792  QualCost qp_qual_cost;
3793  double mergejointuples,
3794  rescannedtuples;
3795  double rescanratio;
3796 
3797  /* Protect some assumptions below that rowcounts aren't zero */
3798  if (inner_path_rows <= 0)
3799  inner_path_rows = 1;
3800 
3801  /* Mark the path with the correct row estimate */
3802  if (path->jpath.path.param_info)
3803  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3804  else
3805  path->jpath.path.rows = path->jpath.path.parent->rows;
3806 
3807  /* For partial paths, scale row estimate. */
3808  if (path->jpath.path.parallel_workers > 0)
3809  {
3810  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3811 
3812  path->jpath.path.rows =
3813  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3814  }
3815 
3816  /*
3817  * We could include disable_cost in the preliminary estimate, but that
3818  * would amount to optimizing for the case where the join method is
3819  * disabled, which doesn't seem like the way to bet.
3820  */
3821  if (!enable_mergejoin)
3822  startup_cost += disable_cost;
3823 
3824  /*
3825  * Compute cost of the mergequals and qpquals (other restriction clauses)
3826  * separately.
3827  */
3828  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3829  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3830  qp_qual_cost.startup -= merge_qual_cost.startup;
3831  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3832 
3833  /*
3834  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3835  * executor will stop scanning for matches after the first match. When
3836  * all the joinclauses are merge clauses, this means we don't ever need to
3837  * back up the merge, and so we can skip mark/restore overhead.
3838  */
3839  if ((path->jpath.jointype == JOIN_SEMI ||
3840  path->jpath.jointype == JOIN_ANTI ||
3841  extra->inner_unique) &&
3844  path->skip_mark_restore = true;
3845  else
3846  path->skip_mark_restore = false;
3847 
3848  /*
3849  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3850  * here because we need an estimate done with JOIN_INNER semantics.
3851  */
3852  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3853 
3854  /*
3855  * When there are equal merge keys in the outer relation, the mergejoin
3856  * must rescan any matching tuples in the inner relation. This means
3857  * re-fetching inner tuples; we have to estimate how often that happens.
3858  *
3859  * For regular inner and outer joins, the number of re-fetches can be
3860  * estimated approximately as size of merge join output minus size of
3861  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3862  * denote the number of values of each key in the outer relation as m1,
3863  * m2, ...; in the inner relation, n1, n2, ... Then we have
3864  *
3865  * size of join = m1 * n1 + m2 * n2 + ...
3866  *
3867  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3868  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3869  * relation
3870  *
3871  * This equation works correctly for outer tuples having no inner match
3872  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3873  * are effectively subtracting those from the number of rescanned tuples,
3874  * when we should not. Can we do better without expensive selectivity
3875  * computations?
3876  *
3877  * The whole issue is moot if we are working from a unique-ified outer
3878  * input, or if we know we don't need to mark/restore at all.
3879  */
3880  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3881  rescannedtuples = 0;
3882  else
3883  {
3884  rescannedtuples = mergejointuples - inner_path_rows;
3885  /* Must clamp because of possible underestimate */
3886  if (rescannedtuples < 0)
3887  rescannedtuples = 0;
3888  }
3889 
3890  /*
3891  * We'll inflate various costs this much to account for rescanning. Note
3892  * that this is to be multiplied by something involving inner_rows, or
3893  * another number related to the portion of the inner rel we'll scan.
3894  */
3895  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3896 
3897  /*
3898  * Decide whether we want to materialize the inner input to shield it from
3899  * mark/restore and performing re-fetches. Our cost model for regular
3900  * re-fetches is that a re-fetch costs the same as an original fetch,
3901  * which is probably an overestimate; but on the other hand we ignore the
3902  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3903  * a more refined model. So we just need to inflate the inner run cost by
3904  * rescanratio.
3905  */
3906  bare_inner_cost = inner_run_cost * rescanratio;
3907 
3908  /*
3909  * When we interpose a Material node the re-fetch cost is assumed to be
3910  * just cpu_operator_cost per tuple, independently of the underlying
3911  * plan's cost; and we charge an extra cpu_operator_cost per original
3912  * fetch as well. Note that we're assuming the materialize node will
3913  * never spill to disk, since it only has to remember tuples back to the
3914  * last mark. (If there are a huge number of duplicates, our other cost
3915  * factors will make the path so expensive that it probably won't get
3916  * chosen anyway.) So we don't use cost_rescan here.
3917  *
3918  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3919  * of the generated Material node.
3920  */
3921  mat_inner_cost = inner_run_cost +
3922  cpu_operator_cost * inner_rows * rescanratio;
3923 
3924  /*
3925  * If we don't need mark/restore at all, we don't need materialization.
3926  */
3927  if (path->skip_mark_restore)
3928  path->materialize_inner = false;
3929 
3930  /*
3931  * Prefer materializing if it looks cheaper, unless the user has asked to
3932  * suppress materialization.
3933  */
3934  else if (enable_material && mat_inner_cost < bare_inner_cost)
3935  path->materialize_inner = true;
3936 
3937  /*
3938  * Even if materializing doesn't look cheaper, we *must* do it if the
3939  * inner path is to be used directly (without sorting) and it doesn't
3940  * support mark/restore.
3941  *
3942  * Since the inner side must be ordered, and only Sorts and IndexScans can
3943  * create order to begin with, and they both support mark/restore, you
3944  * might think there's no problem --- but you'd be wrong. Nestloop and
3945  * merge joins can *preserve* the order of their inputs, so they can be
3946  * selected as the input of a mergejoin, and they don't support
3947  * mark/restore at present.
3948  *
3949  * We don't test the value of enable_material here, because
3950  * materialization is required for correctness in this case, and turning
3951  * it off does not entitle us to deliver an invalid plan.
3952  */
3953  else if (innersortkeys == NIL &&
3954  !ExecSupportsMarkRestore(inner_path))
3955  path->materialize_inner = true;
3956 
3957  /*
3958  * Also, force materializing if the inner path is to be sorted and the
3959  * sort is expected to spill to disk. This is because the final merge
3960  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3961  * We don't try to adjust the cost estimates for this consideration,
3962  * though.
3963  *
3964  * Since materialization is a performance optimization in this case,
3965  * rather than necessary for correctness, we skip it if enable_material is
3966  * off.
3967  */
3968  else if (enable_material && innersortkeys != NIL &&
3969  relation_byte_size(inner_path_rows,
3970  inner_path->pathtarget->width) >
3971  (work_mem * 1024L))
3972  path->materialize_inner = true;
3973  else
3974  path->materialize_inner = false;
3975 
3976  /* Charge the right incremental cost for the chosen case */
3977  if (path->materialize_inner)
3978  run_cost += mat_inner_cost;
3979  else
3980  run_cost += bare_inner_cost;
3981 
3982  /* CPU costs */
3983 
3984  /*
3985  * The number of tuple comparisons needed is approximately number of outer
3986  * rows plus number of inner rows plus number of rescanned tuples (can we
3987  * refine this?). At each one, we need to evaluate the mergejoin quals.
3988  */
3989  startup_cost += merge_qual_cost.startup;
3990  startup_cost += merge_qual_cost.per_tuple *
3991  (outer_skip_rows + inner_skip_rows * rescanratio);
3992  run_cost += merge_qual_cost.per_tuple *
3993  ((outer_rows - outer_skip_rows) +
3994  (inner_rows - inner_skip_rows) * rescanratio);
3995 
3996  /*
3997  * For each tuple that gets through the mergejoin proper, we charge
3998  * cpu_tuple_cost plus the cost of evaluating additional restriction
3999  * clauses that are to be applied at the join. (This is pessimistic since
4000  * not all of the quals may get evaluated at each tuple.)
4001  *
4002  * Note: we could adjust for SEMI/ANTI joins skipping some qual
4003  * evaluations here, but it's probably not worth the trouble.
4004  */
4005  startup_cost += qp_qual_cost.startup;
4006  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4007  run_cost += cpu_per_tuple * mergejointuples;
4008 
4009  /* tlist eval costs are paid per output row, not per tuple scanned */
4010  startup_cost += path->jpath.path.pathtarget->cost.startup;
4011  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4012 
4013  path->jpath.path.startup_cost = startup_cost;
4014  path->jpath.path.total_cost = startup_cost + run_cost;
4015 }
4016 
4017 /*
4018  * run mergejoinscansel() with caching
4019  */
4020 static MergeScanSelCache *
4022 {
4023  MergeScanSelCache *cache;
4024  ListCell *lc;
4025  Selectivity leftstartsel,
4026  leftendsel,
4027  rightstartsel,
4028  rightendsel;
4029  MemoryContext oldcontext;
4030 
4031  /* Do we have this result already? */
4032  foreach(lc, rinfo->scansel_cache)
4033  {
4034  cache = (MergeScanSelCache *) lfirst(lc);
4035  if (cache->opfamily == pathkey->pk_opfamily &&
4036  cache->collation == pathkey->pk_eclass->ec_collation &&
4037  cache->strategy == pathkey->pk_strategy &&
4038  cache->nulls_first == pathkey->pk_nulls_first)
4039  return cache;
4040  }
4041 
4042  /* Nope, do the computation */
4043  mergejoinscansel(root,
4044  (Node *) rinfo->clause,
4045  pathkey->pk_opfamily,
4046  pathkey->pk_strategy,
4047  pathkey->pk_nulls_first,
4048  &leftstartsel,
4049  &leftendsel,
4050  &rightstartsel,
4051  &rightendsel);
4052 
4053  /* Cache the result in suitably long-lived workspace */
4054  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4055 
4056  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
4057  cache->opfamily = pathkey->pk_opfamily;
4058  cache->collation = pathkey->pk_eclass->ec_collation;
4059  cache->strategy = pathkey->pk_strategy;
4060  cache->nulls_first = pathkey->pk_nulls_first;
4061  cache->leftstartsel = leftstartsel;
4062  cache->leftendsel = leftendsel;
4063  cache->rightstartsel = rightstartsel;
4064  cache->rightendsel = rightendsel;
4065 
4066  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4067 
4068  MemoryContextSwitchTo(oldcontext);
4069 
4070  return cache;
4071 }
4072 
4073 /*
4074  * initial_cost_hashjoin
4075  * Preliminary estimate of the cost of a hashjoin path.
4076  *
4077  * This must quickly produce lower-bound estimates of the path's startup and
4078  * total costs. If we are unable to eliminate the proposed path from
4079  * consideration using the lower bounds, final_cost_hashjoin will be called
4080  * to obtain the final estimates.
4081  *
4082  * The exact division of labor between this function and final_cost_hashjoin
4083  * is private to them, and represents a tradeoff between speed of the initial
4084  * estimate and getting a tight lower bound. We choose to not examine the
4085  * join quals here (other than by counting the number of hash clauses),
4086  * so we can't do much with CPU costs. We do assume that
4087  * ExecChooseHashTableSize is cheap enough to use here.
4088  *
4089  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
4090  * other data to be used by final_cost_hashjoin
4091  * 'jointype' is the type of join to be performed
4092  * 'hashclauses' is the list of joinclauses to be used as hash clauses
4093  * 'outer_path' is the outer input to the join
4094  * 'inner_path' is the inner input to the join
4095  * 'extra' contains miscellaneous information about the join
4096  * 'parallel_hash' indicates that inner_path is partial and that a shared
4097  * hash table will be built in parallel
4098  */
4099 void
4101  JoinType jointype,
4102  List *hashclauses,
4103  Path *outer_path, Path *inner_path,
4104  JoinPathExtraData *extra,
4105  bool parallel_hash)
4106 {
4107  Cost startup_cost = 0;
4108  Cost run_cost = 0;
4109  double outer_path_rows = outer_path->rows;
4110  double inner_path_rows = inner_path->rows;
4111  double inner_path_rows_total = inner_path_rows;
4112  int num_hashclauses = list_length(hashclauses);
4113  int numbuckets;
4114  int numbatches;
4115  int num_skew_mcvs;
4116  size_t space_allowed; /* unused */
4117 
4118  /* cost of source data */
4119  startup_cost += outer_path->startup_cost;
4120  run_cost += outer_path->total_cost - outer_path->startup_cost;
4121  startup_cost += inner_path->total_cost;
4122 
4123  /*
4124  * Cost of computing hash function: must do it once per input tuple. We
4125  * charge one cpu_operator_cost for each column's hash function. Also,
4126  * tack on one cpu_tuple_cost per inner row, to model the costs of
4127  * inserting the row into the hashtable.
4128  *
4129  * XXX when a hashclause is more complex than a single operator, we really
4130  * should charge the extra eval costs of the left or right side, as
4131  * appropriate, here. This seems more work than it's worth at the moment.
4132  */
4133  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
4134  * inner_path_rows;
4135  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
4136 
4137  /*
4138  * If this is a parallel hash build, then the value we have for
4139  * inner_rows_total currently refers only to the rows returned by each
4140  * participant. For shared hash table size estimation, we need the total
4141  * number, so we need to undo the division.
4142  */
4143  if (parallel_hash)
4144  inner_path_rows_total *= get_parallel_divisor(inner_path);
4145 
4146  /*
4147  * Get hash table size that executor would use for inner relation.
4148  *
4149  * XXX for the moment, always assume that skew optimization will be
4150  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
4151  * trying to determine that for sure.
4152  *
4153  * XXX at some point it might be interesting to try to account for skew
4154  * optimization in the cost estimate, but for now, we don't.
4155  */
4156  ExecChooseHashTableSize(inner_path_rows_total,
4157  inner_path->pathtarget->width,
4158  true, /* useskew */
4159  parallel_hash, /* try_combined_hash_mem */
4160  outer_path->parallel_workers,
4161  &space_allowed,
4162  &numbuckets,
4163  &numbatches,
4164  &num_skew_mcvs);
4165 
4166  /*
4167  * If inner relation is too big then we will need to "batch" the join,
4168  * which implies writing and reading most of the tuples to disk an extra
4169  * time. Charge seq_page_cost per page, since the I/O should be nice and
4170  * sequential. Writing the inner rel counts as startup cost, all the rest
4171  * as run cost.
4172  */
4173  if (numbatches > 1)
4174  {
4175  double outerpages = page_size(outer_path_rows,
4176  outer_path->pathtarget->width);
4177  double innerpages = page_size(inner_path_rows,
4178  inner_path->pathtarget->width);
4179 
4180  startup_cost += seq_page_cost * innerpages;
4181  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4182  }
4183 
4184  /* CPU costs left for later */
4185 
4186  /* Public result fields */
4187  workspace->startup_cost = startup_cost;
4188  workspace->total_cost = startup_cost + run_cost;
4189  /* Save private data for final_cost_hashjoin */
4190  workspace->run_cost = run_cost;
4191  workspace->numbuckets = numbuckets;
4192  workspace->numbatches = numbatches;
4193  workspace->inner_rows_total = inner_path_rows_total;
4194 }
4195 
4196 /*
4197  * final_cost_hashjoin
4198  * Final estimate of the cost and result size of a hashjoin path.
4199  *
4200  * Note: the numbatches estimate is also saved into 'path' for use later
4201  *
4202  * 'path' is already filled in except for the rows and cost fields and
4203  * num_batches
4204  * 'workspace' is the result from initial_cost_hashjoin
4205  * 'extra' contains miscellaneous information about the join
4206  */
4207 void
4209  JoinCostWorkspace *workspace,
4210  JoinPathExtraData *extra)
4211 {
4212  Path *outer_path = path->jpath.outerjoinpath;
4213  Path *inner_path = path->jpath.innerjoinpath;
4214  double outer_path_rows = outer_path->rows;
4215  double inner_path_rows = inner_path->rows;
4216  double inner_path_rows_total = workspace->inner_rows_total;
4217  List *hashclauses = path->path_hashclauses;
4218  Cost startup_cost = workspace->startup_cost;
4219  Cost run_cost = workspace->run_cost;
4220  int numbuckets = workspace->numbuckets;
4221  int numbatches = workspace->numbatches;
4222  Cost cpu_per_tuple;
4223  QualCost hash_qual_cost;
4224  QualCost qp_qual_cost;
4225  double hashjointuples;
4226  double virtualbuckets;
4227  Selectivity innerbucketsize;
4228  Selectivity innermcvfreq;
4229  ListCell *hcl;
4230 
4231  /* Mark the path with the correct row estimate */
4232  if (path->jpath.path.param_info)
4233  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4234  else
4235  path->jpath.path.rows = path->jpath.path.parent->rows;
4236 
4237  /* For partial paths, scale row estimate. */
4238  if (path->jpath.path.parallel_workers > 0)
4239  {
4240  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4241 
4242  path->jpath.path.rows =
4243  clamp_row_est(path->jpath.path.rows / parallel_divisor);
4244  }
4245 
4246  /*
4247  * We could include disable_cost in the preliminary estimate, but that
4248  * would amount to optimizing for the case where the join method is
4249  * disabled, which doesn't seem like the way to bet.
4250  */
4251  if (!enable_hashjoin)
4252  startup_cost += disable_cost;
4253 
4254  /* mark the path with estimated # of batches */
4255  path->num_batches = numbatches;
4256 
4257  /* store the total number of tuples (sum of partial row estimates) */
4258  path->inner_rows_total = inner_path_rows_total;
4259 
4260  /* and compute the number of "virtual" buckets in the whole join */
4261  virtualbuckets = (double) numbuckets * (double) numbatches;
4262 
4263  /*
4264  * Determine bucketsize fraction and MCV frequency for the inner relation.
4265  * We use the smallest bucketsize or MCV frequency estimated for any
4266  * individual hashclause; this is undoubtedly conservative.
4267  *
4268  * BUT: if inner relation has been unique-ified, we can assume it's good
4269  * for hashing. This is important both because it's the right answer, and
4270  * because we avoid contaminating the cache with a value that's wrong for
4271  * non-unique-ified paths.
4272  */
4273  if (IsA(inner_path, UniquePath))
4274  {
4275  innerbucketsize = 1.0 / virtualbuckets;
4276  innermcvfreq = 0.0;
4277  }
4278  else
4279  {
4280  innerbucketsize = 1.0;
4281  innermcvfreq = 1.0;
4282  foreach(hcl, hashclauses)
4283  {
4284  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
4285  Selectivity thisbucketsize;
4286  Selectivity thismcvfreq;
4287 
4288  /*
4289  * First we have to figure out which side of the hashjoin clause
4290  * is the inner side.
4291  *
4292  * Since we tend to visit the same clauses over and over when
4293  * planning a large query, we cache the bucket stats estimates in
4294  * the RestrictInfo node to avoid repeated lookups of statistics.
4295  */
4296  if (bms_is_subset(restrictinfo->right_relids,
4297  inner_path->parent->relids))
4298  {
4299  /* righthand side is inner */
4300  thisbucketsize = restrictinfo->right_bucketsize;
4301  if (thisbucketsize < 0)
4302  {
4303  /* not cached yet */
4305  get_rightop(restrictinfo->clause),
4306  virtualbuckets,
4307  &restrictinfo->right_mcvfreq,
4308  &restrictinfo->right_bucketsize);
4309  thisbucketsize = restrictinfo->right_bucketsize;
4310  }
4311  thismcvfreq = restrictinfo->right_mcvfreq;
4312  }
4313  else
4314  {
4315  Assert(bms_is_subset(restrictinfo->left_relids,
4316  inner_path->parent->relids));
4317  /* lefthand side is inner */
4318  thisbucketsize = restrictinfo->left_bucketsize;
4319  if (thisbucketsize < 0)
4320  {
4321  /* not cached yet */
4323  get_leftop(restrictinfo->clause),
4324  virtualbuckets,
4325  &restrictinfo->left_mcvfreq,
4326  &restrictinfo->left_bucketsize);
4327  thisbucketsize = restrictinfo->left_bucketsize;
4328  }
4329  thismcvfreq = restrictinfo->left_mcvfreq;
4330  }
4331 
4332  if (innerbucketsize > thisbucketsize)
4333  innerbucketsize = thisbucketsize;
4334  if (innermcvfreq > thismcvfreq)
4335  innermcvfreq = thismcvfreq;
4336  }
4337  }
4338 
4339  /*
4340  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4341  * want to hash unless there is really no other alternative, so apply
4342  * disable_cost. (The executor normally copes with excessive memory usage
4343  * by splitting batches, but obviously it cannot separate equal values
4344  * that way, so it will be unable to drive the batch size below hash_mem
4345  * when this is true.)
4346  */
4347  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4348  inner_path->pathtarget->width) > get_hash_memory_limit())
4349  startup_cost += disable_cost;
4350 
4351  /*
4352  * Compute cost of the hashquals and qpquals (other restriction clauses)
4353  * separately.
4354  */
4355  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4356  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4357  qp_qual_cost.startup -= hash_qual_cost.startup;
4358  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4359 
4360  /* CPU costs */
4361 
4362  if (path->jpath.jointype == JOIN_SEMI ||
4363  path->jpath.jointype == JOIN_ANTI ||
4364  extra->inner_unique)
4365  {
4366  double outer_matched_rows;
4367  Selectivity inner_scan_frac;
4368 
4369  /*
4370  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4371  * executor will stop after the first match.
4372  *
4373  * For an outer-rel row that has at least one match, we can expect the
4374  * bucket scan to stop after a fraction 1/(match_count+1) of the
4375  * bucket's rows, if the matches are evenly distributed. Since they
4376  * probably aren't quite evenly distributed, we apply a fuzz factor of
4377  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4378  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4379  * at least 1, no such clamp is needed now.)
4380  */
4381  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4382  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4383 
4384  startup_cost += hash_qual_cost.startup;
4385  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4386  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4387 
4388  /*
4389  * For unmatched outer-rel rows, the picture is quite a lot different.
4390  * In the first place, there is no reason to assume that these rows
4391  * preferentially hit heavily-populated buckets; instead assume they
4392  * are uncorrelated with the inner distribution and so they see an
4393  * average bucket size of inner_path_rows / virtualbuckets. In the
4394  * second place, it seems likely that they will have few if any exact
4395  * hash-code matches and so very few of the tuples in the bucket will
4396  * actually require eval of the hash quals. We don't have any good
4397  * way to estimate how many will, but for the moment assume that the
4398  * effective cost per bucket entry is one-tenth what it is for
4399  * matchable tuples.
4400  */
4401  run_cost += hash_qual_cost.per_tuple *
4402  (outer_path_rows - outer_matched_rows) *
4403  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4404 
4405  /* Get # of tuples that will pass the basic join */
4406  if (path->jpath.jointype == JOIN_ANTI)
4407  hashjointuples = outer_path_rows - outer_matched_rows;
4408  else
4409  hashjointuples = outer_matched_rows;
4410  }
4411  else
4412  {
4413  /*
4414  * The number of tuple comparisons needed is the number of outer
4415  * tuples times the typical number of tuples in a hash bucket, which
4416  * is the inner relation size times its bucketsize fraction. At each
4417  * one, we need to evaluate the hashjoin quals. But actually,
4418  * charging the full qual eval cost at each tuple is pessimistic,
4419  * since we don't evaluate the quals unless the hash values match
4420  * exactly. For lack of a better idea, halve the cost estimate to
4421  * allow for that.
4422  */
4423  startup_cost += hash_qual_cost.startup;
4424  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4425  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4426 
4427  /*
4428  * Get approx # tuples passing the hashquals. We use
4429  * approx_tuple_count here because we need an estimate done with
4430  * JOIN_INNER semantics.
4431  */
4432  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4433  }
4434 
4435  /*
4436  * For each tuple that gets through the hashjoin proper, we charge
4437  * cpu_tuple_cost plus the cost of evaluating additional restriction
4438  * clauses that are to be applied at the join. (This is pessimistic since
4439  * not all of the quals may get evaluated at each tuple.)
4440  */
4441  startup_cost += qp_qual_cost.startup;
4442  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4443  run_cost += cpu_per_tuple * hashjointuples;
4444 
4445  /* tlist eval costs are paid per output row, not per tuple scanned */
4446  startup_cost += path->jpath.path.pathtarget->cost.startup;
4447  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4448 
4449  path->jpath.path.startup_cost = startup_cost;
4450  path->jpath.path.total_cost = startup_cost + run_cost;
4451 }
4452 
4453 
4454 /*
4455  * cost_subplan
4456  * Figure the costs for a SubPlan (or initplan).
4457  *
4458  * Note: we could dig the subplan's Plan out of the root list, but in practice
4459  * all callers have it handy already, so we make them pass it.
4460  */
4461 void
4462 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
4463 {
4464  QualCost sp_cost;
4465 
4466  /* Figure any cost for evaluating the testexpr */
4467  cost_qual_eval(&sp_cost,
4468  make_ands_implicit((Expr *) subplan->testexpr),
4469  root);
4470 
4471  if (subplan->useHashTable)
4472  {
4473  /*
4474  * If we are using a hash table for the subquery outputs, then the
4475  * cost of evaluating the query is a one-time cost. We charge one
4476  * cpu_operator_cost per tuple for the work of loading the hashtable,
4477  * too.
4478  */
4479  sp_cost.startup += plan->total_cost +
4480  cpu_operator_cost * plan->plan_rows;
4481 
4482  /*
4483  * The per-tuple costs include the cost of evaluating the lefthand
4484  * expressions, plus the cost of probing the hashtable. We already
4485  * accounted for the lefthand expressions as part of the testexpr, and
4486  * will also have counted one cpu_operator_cost for each comparison
4487  * operator. That is probably too low for the probing cost, but it's
4488  * hard to make a better estimate, so live with it for now.
4489  */
4490  }
4491  else
4492  {
4493  /*
4494  * Otherwise we will be rescanning the subplan output on each
4495  * evaluation. We need to estimate how much of the output we will
4496  * actually need to scan. NOTE: this logic should agree with the
4497  * tuple_fraction estimates used by make_subplan() in
4498  * plan/subselect.c.
4499  */
4500  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4501 
4502  if (subplan->subLinkType == EXISTS_SUBLINK)
4503  {
4504  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4505  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4506  }
4507  else if (subplan->subLinkType == ALL_SUBLINK ||
4508  subplan->subLinkType == ANY_SUBLINK)
4509  {
4510  /* assume we need 50% of the tuples */
4511  sp_cost.per_tuple += 0.50 * plan_run_cost;
4512  /* also charge a cpu_operator_cost per row examined */
4513  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4514  }
4515  else
4516  {
4517  /* assume we need all tuples */
4518  sp_cost.per_tuple += plan_run_cost;
4519  }
4520 
4521  /*
4522  * Also account for subplan's startup cost. If the subplan is
4523  * uncorrelated or undirect correlated, AND its topmost node is one
4524  * that materializes its output, assume that we'll only need to pay
4525  * its startup cost once; otherwise assume we pay the startup cost
4526  * every time.
4527  */
4528  if (subplan->parParam == NIL &&
4530  sp_cost.startup += plan->startup_cost;
4531  else
4532  sp_cost.per_tuple += plan->startup_cost;
4533  }
4534 
4535  subplan->startup_cost = sp_cost.startup;
4536  subplan->per_call_cost = sp_cost.per_tuple;
4537 }
4538 
4539 
4540 /*
4541  * cost_rescan
4542  * Given a finished Path, estimate the costs of rescanning it after
4543  * having done so the first time. For some Path types a rescan is
4544  * cheaper than an original scan (if no parameters change), and this
4545  * function embodies knowledge about that. The default is to return
4546  * the same costs stored in the Path. (Note that the cost estimates
4547  * actually stored in Paths are always for first scans.)
4548  *
4549  * This function is not currently intended to model effects such as rescans
4550  * being cheaper due to disk block caching; what we are concerned with is
4551  * plan types wherein the executor caches results explicitly, or doesn't
4552  * redo startup calculations, etc.
4553  */
4554 static void
4556  Cost *rescan_startup_cost, /* output parameters */
4557  Cost *rescan_total_cost)
4558 {
4559  switch (path->pathtype)
4560  {
4561  case T_FunctionScan:
4562 
4563  /*
4564  * Currently, nodeFunctionscan.c always executes the function to
4565  * completion before returning any rows, and caches the results in
4566  * a tuplestore. So the function eval cost is all startup cost
4567  * and isn't paid over again on rescans. However, all run costs
4568  * will be paid over again.
4569  */
4570  *rescan_startup_cost = 0;
4571  *rescan_total_cost = path->total_cost - path->startup_cost;
4572  break;
4573  case T_HashJoin:
4574 
4575  /*
4576  * If it's a single-batch join, we don't need to rebuild the hash
4577  * table during a rescan.
4578  */
4579  if (((HashPath *) path)->num_batches == 1)
4580  {
4581  /* Startup cost is exactly the cost of hash table building */
4582  *rescan_startup_cost = 0;
4583  *rescan_total_cost = path->total_cost - path->startup_cost;
4584  }
4585  else
4586  {
4587  /* Otherwise, no special treatment */
4588  *rescan_startup_cost = path->startup_cost;
4589  *rescan_total_cost = path->total_cost;
4590  }
4591  break;
4592  case T_CteScan:
4593  case T_WorkTableScan:
4594  {
4595  /*
4596  * These plan types materialize their final result in a
4597  * tuplestore or tuplesort object. So the rescan cost is only
4598  * cpu_tuple_cost per tuple, unless the result is large enough
4599  * to spill to disk.
4600  */
4601  Cost run_cost = cpu_tuple_cost * path->rows;
4602  double nbytes = relation_byte_size(path->rows,
4603  path->pathtarget->width);
4604  long work_mem_bytes = work_mem * 1024L;
4605 
4606  if (nbytes > work_mem_bytes)
4607  {
4608  /* It will spill, so account for re-read cost */
4609  double npages = ceil(nbytes / BLCKSZ);
4610 
4611  run_cost += seq_page_cost * npages;
4612  }
4613  *rescan_startup_cost = 0;
4614  *rescan_total_cost = run_cost;
4615  }
4616  break;
4617  case T_Material:
4618  case T_Sort:
4619  {
4620  /*
4621  * These plan types not only materialize their results, but do
4622  * not implement qual filtering or projection. So they are
4623  * even cheaper to rescan than the ones above. We charge only
4624  * cpu_operator_cost per tuple. (Note: keep that in sync with
4625  * the run_cost charge in cost_sort, and also see comments in
4626  * cost_material before you change it.)
4627  */
4628  Cost run_cost = cpu_operator_cost * path->rows;
4629  double nbytes = relation_byte_size(path->rows,
4630  path->pathtarget->width);
4631  long work_mem_bytes = work_mem * 1024L;
4632 
4633  if (nbytes > work_mem_bytes)
4634  {
4635  /* It will spill, so account for re-read cost */
4636  double npages = ceil(nbytes / BLCKSZ);
4637 
4638  run_cost += seq_page_cost * npages;
4639  }
4640  *rescan_startup_cost = 0;
4641  *rescan_total_cost = run_cost;
4642  }
4643  break;
4644  case T_Memoize:
4645  /* All the hard work is done by cost_memoize_rescan */
4646  cost_memoize_rescan(root, (MemoizePath *) path,
4647  rescan_startup_cost, rescan_total_cost);
4648  break;
4649  default:
4650  *rescan_startup_cost = path->startup_cost;
4651  *rescan_total_cost = path->total_cost;
4652  break;
4653  }
4654 }
4655 
4656 
4657 /*
4658  * cost_qual_eval
4659  * Estimate the CPU costs of evaluating a WHERE clause.
4660  * The input can be either an implicitly-ANDed list of boolean
4661  * expressions, or a list of RestrictInfo nodes. (The latter is
4662  * preferred since it allows caching of the results.)
4663  * The result includes both a one-time (startup) component,
4664  * and a per-evaluation component.
4665  */
4666 void
4668 {
4669  cost_qual_eval_context context;
4670  ListCell *l;
4671 
4672  context.root = root;
4673  context.total.startup = 0;
4674  context.total.per_tuple = 0;
4675 
4676  /* We don't charge any cost for the implicit ANDing at top level ... */
4677 
4678  foreach(l, quals)
4679  {
4680  Node *qual = (Node *) lfirst(l);
4681 
4682  cost_qual_eval_walker(qual, &context);
4683  }
4684 
4685  *cost = context.total;
4686 }
4687 
4688 /*
4689  * cost_qual_eval_node
4690  * As above, for a single RestrictInfo or expression.
4691  */
4692 void
4694 {
4695  cost_qual_eval_context context;
4696 
4697  context.root = root;
4698  context.total.startup = 0;
4699  context.total.per_tuple = 0;
4700 
4701  cost_qual_eval_walker(qual, &context);
4702 
4703  *cost = context.total;
4704 }
4705 
4706 static bool
4708 {
4709  if (node == NULL)
4710  return false;
4711 
4712  /*
4713  * RestrictInfo nodes contain an eval_cost field reserved for this
4714  * routine's use, so that it's not necessary to evaluate the qual clause's
4715  * cost more than once. If the clause's cost hasn't been computed yet,
4716  * the field's startup value will contain -1.
4717  */
4718  if (IsA(node, RestrictInfo))
4719  {
4720  RestrictInfo *rinfo = (RestrictInfo *) node;
4721 
4722  if (rinfo->eval_cost.startup < 0)
4723  {
4724  cost_qual_eval_context locContext;
4725 
4726  locContext.root = context->root;
4727  locContext.total.startup = 0;
4728  locContext.total.per_tuple = 0;
4729 
4730  /*
4731  * For an OR clause, recurse into the marked-up tree so that we
4732  * set the eval_cost for contained RestrictInfos too.
4733  */
4734  if (rinfo->orclause)
4735  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4736  else
4737  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4738 
4739  /*
4740  * If the RestrictInfo is marked pseudoconstant, it will be tested
4741  * only once, so treat its cost as all startup cost.
4742  */
4743  if (rinfo->pseudoconstant)
4744  {
4745  /* count one execution during startup */
4746  locContext.total.startup += locContext.total.per_tuple;
4747  locContext.total.per_tuple = 0;
4748  }
4749  rinfo->eval_cost = locContext.total;
4750  }
4751  context->total.startup += rinfo->eval_cost.startup;
4752  context->total.per_tuple += rinfo->eval_cost.per_tuple;
4753  /* do NOT recurse into children */
4754  return false;
4755  }
4756 
4757  /*
4758  * For each operator or function node in the given tree, we charge the
4759  * estimated execution cost given by pg_proc.procost (remember to multiply
4760  * this by cpu_operator_cost).
4761  *
4762  * Vars and Consts are charged zero, and so are boolean operators (AND,
4763  * OR, NOT). Simplistic, but a lot better than no model at all.
4764  *
4765  * Should we try to account for the possibility of short-circuit
4766  * evaluation of AND/OR? Probably *not*, because that would make the
4767  * results depend on the clause ordering, and we are not in any position
4768  * to expect that the current ordering of the clauses is the one that's
4769  * going to end up being used. The above per-RestrictInfo caching would
4770  * not mix well with trying to re-order clauses anyway.
4771  *
4772  * Another issue that is entirely ignored here is that if a set-returning
4773  * function is below top level in the tree, the functions/operators above
4774  * it will need to be evaluated multiple times. In practical use, such
4775  * cases arise so seldom as to not be worth the added complexity needed;
4776  * moreover, since our rowcount estimates for functions tend to be pretty
4777  * phony, the results would also be pretty phony.
4778  */
4779  if (IsA(node, FuncExpr))
4780  {
4781  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4782  &context->total);
4783  }
4784  else if (IsA(node, OpExpr) ||
4785  IsA(node, DistinctExpr) ||
4786  IsA(node, NullIfExpr))
4787  {
4788  /* rely on struct equivalence to treat these all alike */
4789  set_opfuncid((OpExpr *) node);
4790  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4791  &context->total);
4792  }
4793  else if (IsA(node, ScalarArrayOpExpr))
4794  {
4795  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4796  Node *arraynode = (Node *) lsecond(saop->args);
4797  QualCost sacosts;
4798  QualCost hcosts;
4799  int estarraylen = estimate_array_length(arraynode);
4800 
4801  set_sa_opfuncid(saop);
4802  sacosts.startup = sacosts.per_tuple = 0;
4803  add_function_cost(context->root, saop->opfuncid, NULL,
4804  &sacosts);
4805 
4806  if (OidIsValid(saop->hashfuncid))
4807  {
4808  /* Handle costs for hashed ScalarArrayOpExpr */
4809  hcosts.startup = hcosts.per_tuple = 0;
4810 
4811  add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
4812  context->total.startup += sacosts.startup + hcosts.startup;
4813 
4814  /* Estimate the cost of building the hashtable. */
4815  context->total.startup += estarraylen * hcosts.per_tuple;
4816 
4817  /*
4818  * XXX should we charge a little bit for sacosts.per_tuple when
4819  * building the table, or is it ok to assume there will be zero
4820  * hash collision?
4821  */
4822 
4823  /*
4824  * Charge for hashtable lookups. Charge a single hash and a
4825  * single comparison.
4826  */
4827  context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
4828  }
4829  else
4830  {
4831  /*
4832  * Estimate that the operator will be applied to about half of the
4833  * array elements before the answer is determined.
4834  */
4835  context->total.startup += sacosts.startup;
4836  context->total.per_tuple += sacosts.per_tuple *
4837  estimate_array_length(arraynode) * 0.5;
4838  }
4839  }
4840  else if (IsA(node, Aggref) ||
4841  IsA(node, WindowFunc))
4842  {
4843  /*
4844  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4845  * ie, zero execution cost in the current model, because they behave
4846  * essentially like Vars at execution. We disregard the costs of
4847  * their input expressions for the same reason. The actual execution
4848  * costs of the aggregate/window functions and their arguments have to
4849  * be factored into plan-node-specific costing of the Agg or WindowAgg
4850  * plan node.
4851  */
4852  return false; /* don't recurse into children */
4853  }
4854  else if (IsA(node, GroupingFunc))
4855  {
4856  /* Treat this as having cost 1 */
4857  context->total.per_tuple += cpu_operator_cost;
4858  return false; /* don't recurse into children */
4859  }
4860  else if (IsA(node, CoerceViaIO))
4861  {
4862  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4863  Oid iofunc;
4864  Oid typioparam;
4865  bool typisvarlena;
4866 
4867  /* check the result type's input function */
4868  getTypeInputInfo(iocoerce->resulttype,
4869  &iofunc, &typioparam);
4870  add_function_cost(context->root, iofunc, NULL,
4871  &context->total);
4872  /* check the input type's output function */
4873  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4874  &iofunc, &typisvarlena);
4875  add_function_cost(context->root, iofunc, NULL,
4876  &context->total);
4877  }
4878  else if (IsA(node, ArrayCoerceExpr))
4879  {
4880  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4881  QualCost perelemcost;
4882 
4883  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4884  context->root);
4885  context->total.startup += perelemcost.startup;
4886  if (perelemcost.per_tuple > 0)
4887  context->total.per_tuple += perelemcost.per_tuple *
4888  estimate_array_length((Node *) acoerce->arg);
4889  }
4890  else if (IsA(node, RowCompareExpr))
4891  {
4892  /* Conservatively assume we will check all the columns */
4893  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4894  ListCell *lc;
4895 
4896  foreach(lc, rcexpr->opnos)
4897  {
4898  Oid opid = lfirst_oid(lc);
4899 
4900  add_function_cost(context->root, get_opcode(opid), NULL,
4901  &context->total);
4902  }
4903  }
4904  else if (IsA(node, MinMaxExpr) ||
4905  IsA(node, SQLValueFunction) ||
4906  IsA(node, XmlExpr) ||
4907  IsA(node, CoerceToDomain) ||
4908  IsA(node, NextValueExpr) ||
4909  IsA(node, JsonExpr))
4910  {
4911  /* Treat all these as having cost 1 */
4912  context->total.per_tuple += cpu_operator_cost;
4913  }
4914  else if (IsA(node, CurrentOfExpr))
4915  {
4916  /* Report high cost to prevent selection of anything but TID scan */
4917  context->total.startup += disable_cost;
4918  }
4919  else if (IsA(node, SubLink))
4920  {
4921  /* This routine should not be applied to un-planned expressions */
4922  elog(ERROR, "cannot handle unplanned sub-select");
4923  }
4924  else if (IsA(node, SubPlan))
4925  {
4926  /*
4927  * A subplan node in an expression typically indicates that the
4928  * subplan will be executed on each evaluation, so charge accordingly.
4929  * (Sub-selects that can be executed as InitPlans have already been
4930  * removed from the expression.)
4931  */
4932  SubPlan *subplan = (SubPlan *) node;
4933 
4934  context->total.startup += subplan->startup_cost;
4935  context->total.per_tuple += subplan->per_call_cost;
4936 
4937  /*
4938  * We don't want to recurse into the testexpr, because it was already
4939  * counted in the SubPlan node's costs. So we're done.
4940  */
4941  return false;
4942  }
4943  else if (IsA(node, AlternativeSubPlan))
4944  {
4945  /*
4946  * Arbitrarily use the first alternative plan for costing. (We should
4947  * certainly only include one alternative, and we don't yet have
4948  * enough information to know which one the executor is most likely to
4949  * use.)
4950  */
4951  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4952 
4953  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4954  context);
4955  }
4956  else if (IsA(node, PlaceHolderVar))
4957  {
4958  /*
4959  * A PlaceHolderVar should be given cost zero when considering general
4960  * expression evaluation costs. The expense of doing the contained
4961  * expression is charged as part of the tlist eval costs of the scan
4962  * or join where the PHV is first computed (see set_rel_width and
4963  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4964  * double-counting the cost for each level of plan that the PHV
4965  * bubbles up through. Hence, return without recursing into the
4966  * phexpr.
4967  */
4968  return false;
4969  }
4970 
4971  /* recurse into children */
4973  (void *) context);
4974 }
4975 
4976 /*
4977  * get_restriction_qual_cost
4978  * Compute evaluation costs of a baserel's restriction quals, plus any
4979  * movable join quals that have been pushed down to the scan.
4980  * Results are returned into *qpqual_cost.
4981  *
4982  * This is a convenience subroutine that works for seqscans and other cases
4983  * where all the given quals will be evaluated the hard way. It's not useful
4984  * for cost_index(), for example, where the index machinery takes care of
4985  * some of the quals. We assume baserestrictcost was previously set by
4986  * set_baserel_size_estimates().
4987  */
4988 static void
4990  ParamPathInfo *param_info,
4991  QualCost *qpqual_cost)
4992 {
4993  if (param_info)
4994  {
4995  /* Include costs of pushed-down clauses */
4996  cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
4997 
4998  qpqual_cost->startup += baserel->baserestrictcost.startup;
4999  qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
5000  }
5001  else
5002  *qpqual_cost = baserel->baserestrictcost;
5003 }
5004 
5005 
5006 /*
5007  * compute_semi_anti_join_factors
5008  * Estimate how much of the inner input a SEMI, ANTI, or inner_unique join
5009  * can be expected to scan.
5010  *
5011  * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
5012  * inner rows as soon as it finds a match to the current outer row.
5013  * The same happens if we have detected the inner rel is unique.
5014  * We should therefore adjust some of the cost components for this effect.
5015  * This function computes some estimates needed for these adjustments.
5016  * These estimates will be the same regardless of the particular paths used
5017  * for the outer and inner relation, so we compute these once and then pass
5018  * them to all the join cost estimation functions.
5019  *
5020  * Input parameters:
5021  * joinrel: join relation under consideration
5022  * outerrel: outer relation under consideration
5023  * innerrel: inner relation under consideration
5024  * jointype: if not JOIN_SEMI or JOIN_ANTI, we assume it's inner_unique
5025  * sjinfo: SpecialJoinInfo relevant to this join
5026  * restrictlist: join quals
5027  * Output parameters:
5028  * *semifactors is filled in (see pathnodes.h for field definitions)
5029  */
5030 void
5032  RelOptInfo *joinrel,
5033  RelOptInfo *outerrel,
5034  RelOptInfo *innerrel,
5035  JoinType jointype,
5036  SpecialJoinInfo *sjinfo,
5037  List *restrictlist,
5038  SemiAntiJoinFactors *semifactors)
5039 {
5040  Selectivity jselec;
5041  Selectivity nselec;
5042  Selectivity avgmatch;
5043  SpecialJoinInfo norm_sjinfo;
5044  List *joinquals;
5045  ListCell *l;
5046 
5047  /*
5048  * In an ANTI join, we must ignore clauses that are "pushed down", since
5049  * those won't affect the match logic. In a SEMI join, we do not
5050  * distinguish joinquals from "pushed down" quals, so just use the whole
5051  * restrictinfo list. For other outer join types, we should consider only
5052  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5053  */
5054  if (IS_OUTER_JOIN(jointype))
5055  {
5056  joinquals = NIL;
5057  foreach(l, restrictlist)
5058  {
5059  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5060 
5061  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5062  joinquals = lappend(joinquals, rinfo);
5063  }
5064  }
5065  else
5066  joinquals = restrictlist;
5067 
5068  /*
5069  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5070  */
5071  jselec = clauselist_selectivity(root,
5072  joinquals,
5073  0,
5074  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5075  sjinfo);
5076 
5077  /*
5078  * Also get the normal inner-join selectivity of the join clauses.
5079  */
5080  norm_sjinfo.type = T_SpecialJoinInfo;
5081  norm_sjinfo.min_lefthand = outerrel->relids;
5082  norm_sjinfo.min_righthand = innerrel->relids;
5083  norm_sjinfo.syn_lefthand = outerrel->relids;
5084  norm_sjinfo.syn_righthand = innerrel->relids;
5085  norm_sjinfo.jointype = JOIN_INNER;
5086  /* we don't bother trying to make the remaining fields valid */
5087  norm_sjinfo.lhs_strict = false;
5088  norm_sjinfo.delay_upper_joins = false;
5089  norm_sjinfo.semi_can_btree = false;
5090  norm_sjinfo.semi_can_hash = false;
5091  norm_sjinfo.semi_operators = NIL;
5092  norm_sjinfo.semi_rhs_exprs = NIL;
5093 
5094  nselec = clauselist_selectivity(root,
5095  joinquals,
5096  0,
5097  JOIN_INNER,
5098  &norm_sjinfo);
5099 
5100  /* Avoid leaking a lot of ListCells */
5101  if (IS_OUTER_JOIN(jointype))
5102  list_free(joinquals);
5103 
5104  /*
5105  * jselec can be interpreted as the fraction of outer-rel rows that have
5106  * any matches (this is true for both SEMI and ANTI cases). And nselec is
5107  * the fraction of the Cartesian product that matches. So, the average
5108  * number of matches for each outer-rel row that has at least one match is
5109  * nselec * inner_rows / jselec.
5110  *
5111  * Note: it is correct to use the inner rel's "rows" count here, even
5112  * though we might later be considering a parameterized inner path with
5113  * fewer rows. This is because we have included all the join clauses in
5114  * the selectivity estimate.
5115  */
5116  if (jselec > 0) /* protect against zero divide */
5117  {
5118  avgmatch = nselec * innerrel->rows / jselec;
5119  /* Clamp to sane range */
5120  avgmatch = Max(1.0, avgmatch);
5121  }
5122  else
5123  avgmatch = 1.0;
5124 
5125  semifactors->outer_match_frac = jselec;
5126  semifactors->match_count = avgmatch;
5127 }
5128 
5129 /*
5130  * has_indexed_join_quals
5131  * Check whether all the joinquals of a nestloop join are used as
5132  * inner index quals.
5133  *
5134  * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
5135  * indexscan) that uses all the joinquals as indexquals, we can assume that an
5136  * unmatched outer tuple is cheap to process, whereas otherwise it's probably
5137  * expensive.
5138  */
5139 static bool
5141 {
5142  JoinPath *joinpath = &path->jpath;
5143  Relids joinrelids = joinpath->path.parent->relids;
5144  Path *innerpath = joinpath->innerjoinpath;
5145  List *indexclauses;
5146  bool found_one;
5147  ListCell *lc;
5148 
5149  /* If join still has quals to evaluate, it's not fast */
5150  if (joinpath->joinrestrictinfo != NIL)
5151  return false;
5152  /* Nor if the inner path isn't parameterized at all */
5153  if (innerpath->param_info == NULL)
5154  return false;
5155 
5156  /* Find the indexclauses list for the inner scan */
5157  switch (innerpath->pathtype)
5158  {
5159  case T_IndexScan:
5160  case T_IndexOnlyScan:
5161  indexclauses = ((IndexPath *) innerpath)->indexclauses;
5162  break;
5163  case T_BitmapHeapScan:
5164  {
5165  /* Accept only a simple bitmap scan, not AND/OR cases */
5166  Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
5167 
5168  if (IsA(bmqual, IndexPath))
5169  indexclauses = ((IndexPath *) bmqual)->indexclauses;
5170  else
5171  return false;
5172  break;
5173  }
5174  default:
5175 
5176  /*
5177  * If it's not a simple indexscan, it probably doesn't run quickly
5178  * for zero rows out, even if it's a parameterized path using all
5179  * the joinquals.
5180  */
5181  return false;
5182  }
5183 
5184  /*
5185  * Examine the inner path's param clauses. Any that are from the outer
5186  * path must be found in the indexclauses list, either exactly or in an
5187  * equivalent form generated by equivclass.c. Also, we must find at least
5188  * one such clause, else it's a clauseless join which isn't fast.
5189  */
5190  found_one = false;
5191  foreach(lc, innerpath->param_info->ppi_clauses)
5192  {
5193  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
5194 
5195  if (join_clause_is_movable_into(rinfo,
5196  innerpath->parent->relids,
5197  joinrelids))
5198  {
5199  if (!is_redundant_with_indexclauses(rinfo, indexclauses))
5200  return false;
5201  found_one = true;
5202  }
5203  }
5204  return found_one;
5205 }
5206 
5207 
5208 /*
5209  * approx_tuple_count
5210  * Quick-and-dirty estimation of the number of join rows passing
5211  * a set of qual conditions.
5212  *
5213  * The quals can be either an implicitly-ANDed list of boolean expressions,
5214  * or a list of RestrictInfo nodes (typically the latter).
5215  *
5216  * We intentionally compute the selectivity under JOIN_INNER rules, even
5217  * if it's some type of outer join. This is appropriate because we are
5218  * trying to figure out how many tuples pass the initial merge or hash
5219  * join step.
5220  *
5221  * This is quick-and-dirty because we bypass clauselist_selectivity, and
5222  * simply multiply the independent clause selectivities together. Now
5223  * clauselist_selectivity often can't do any better than that anyhow, but
5224  * for some situations (such as range constraints) it is smarter. However,
5225  * we can't effectively cache the results of clauselist_selectivity, whereas
5226  * the individual clause selectivities can be and are cached.
5227  *
5228  * Since we are only using the results to estimate how many potential
5229  * output tuples are generated and passed through qpqual checking, it
5230  * seems OK to live with the approximation.
5231  */
5232 static double
5234 {
5235  double tuples;
5236  double outer_tuples = path->outerjoinpath->rows;
5237  double inner_tuples = path->innerjoinpath->rows;
5238  SpecialJoinInfo sjinfo;
5239  Selectivity selec = 1.0;
5240  ListCell *l;
5241 
5242  /*
5243  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5244  */
5245  sjinfo.type = T_SpecialJoinInfo;
5246  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
5247  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
5248  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
5249  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
5250  sjinfo.jointype = JOIN_INNER;
5251  /* we don't bother trying to make the remaining fields valid */
5252  sjinfo.lhs_strict = false;
5253  sjinfo.delay_upper_joins = false;
5254  sjinfo.semi_can_btree = false;
5255  sjinfo.semi_can_hash = false;
5256  sjinfo.semi_operators = NIL;
5257  sjinfo.semi_rhs_exprs = NIL;
5258 
5259  /* Get the approximate selectivity */
5260  foreach(l, quals)
5261  {
5262  Node *qual = (Node *) lfirst(l);
5263 
5264  /* Note that clause_selectivity will be able to cache its result */
5265  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5266  }
5267 
5268  /* Apply it to the input relation sizes */
5269  tuples = selec * outer_tuples * inner_tuples;
5270 
5271  return clamp_row_est(tuples);
5272 }
5273 
5274 
5275 /*
5276  * set_baserel_size_estimates
5277  * Set the size estimates for the given base relation.
5278  *
5279  * The rel's targetlist and restrictinfo list must have been constructed
5280  * already, and rel->tuples must be set.
5281  *
5282  * We set the following fields of the rel node:
5283  * rows: the estimated number of output tuples (after applying
5284  * restriction clauses).
5285  * width: the estimated average output tuple width in bytes.
5286  * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
5287  */
5288 void
5290 {
5291  double nrows;
5292 
5293  /* Should only be applied to base relations */
5294  Assert(rel->relid > 0);
5295 
5296  nrows = rel->tuples *
5298  rel->baserestrictinfo,
5299  0,
5300  JOIN_INNER,
5301  NULL);
5302 
5303  rel->rows = clamp_row_est(nrows);
5304 
5306 
5307  set_rel_width(root, rel);
5308 }
5309 
5310 /*
5311  * get_parameterized_baserel_size
5312  * Make a size estimate for a parameterized scan of a base relation.
5313  *
5314  * 'param_clauses' lists the additional join clauses to be used.
5315  *
5316  * set_baserel_size_estimates must have been applied already.
5317  */
5318 double
5320  List *param_clauses)
5321 {
5322  List *allclauses;
5323  double nrows;
5324 
5325  /*
5326  * Estimate the number of rows returned by the parameterized scan, knowing
5327  * that it will apply all the extra join clauses as well as the rel's own
5328  * restriction clauses. Note that we force the clauses to be treated as
5329  * non-join clauses during selectivity estimation.
5330  */
5331  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5332  nrows = rel->tuples *
5334  allclauses,
5335  rel->relid, /* do not use 0! */
5336  JOIN_INNER,
5337  NULL);
5338  nrows = clamp_row_est(nrows);
5339  /* For safety, make sure result is not more than the base estimate */
5340  if (nrows > rel->rows)
5341  nrows = rel->rows;
5342  return nrows;
5343 }
5344 
5345 /*
5346  * set_joinrel_size_estimates
5347  * Set the size estimates for the given join relation.
5348  *
5349  * The rel's targetlist must have been constructed already, and a
5350  * restriction clause list that matches the given component rels must
5351  * be provided.
5352  *
5353  * Since there is more than one way to make a joinrel for more than two
5354  * base relations, the results we get here could depend on which component
5355  * rel pair is provided. In theory we should get the same answers no matter
5356  * which pair is provided; in practice, since the selectivity estimation
5357  * routines don't handle all cases equally well, we might not. But there's
5358  * not much to be done about it. (Would it make sense to repeat the
5359  * calculations for each pair of input rels that's encountered, and somehow
5360  * average the results? Probably way more trouble than it's worth, and
5361  * anyway we must keep the rowcount estimate the same for all paths for the
5362  * joinrel.)
5363  *
5364  * We set only the rows field here. The reltarget field was already set by
5365  * build_joinrel_tlist, and baserestrictcost is not used for join rels.
5366  */
5367 void
5369  RelOptInfo *outer_rel,
5370  RelOptInfo *inner_rel,
5371  SpecialJoinInfo *sjinfo,
5372  List *restrictlist)
5373 {
5374  rel->rows = calc_joinrel_size_estimate(root,
5375  rel,
5376  outer_rel,
5377  inner_rel,
5378  outer_rel->rows,
5379  inner_rel->rows,
5380  sjinfo,
5381  restrictlist);
5382 }
5383 
5384 /*
5385  * get_parameterized_joinrel_size
5386  * Make a size estimate for a parameterized scan of a join relation.
5387  *
5388  * 'rel' is the joinrel under consideration.
5389  * 'outer_path', 'inner_path' are (probably also parameterized) Paths that
5390  * produce the relations being joined.
5391  * 'sjinfo' is any SpecialJoinInfo relevant to this join.
5392  * 'restrict_clauses' lists the join clauses that need to be applied at the
5393  * join node (including any movable clauses that were moved down to this join,
5394  * and not including any movable clauses that were pushed down into the
5395  * child paths).
5396  *
5397  * set_joinrel_size_estimates must have been applied already.
5398  */
5399 double
5401  Path *outer_path,
5402  Path *inner_path,
5403  SpecialJoinInfo *sjinfo,
5404  List *restrict_clauses)
5405 {
5406  double nrows;
5407 
5408  /*
5409  * Estimate the number of rows returned by the parameterized join as the
5410  * sizes of the input paths times the selectivity of the clauses that have
5411  * ended up at this join node.
5412  *
5413  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5414  * on the pair of input paths provided, though ideally we'd get the same
5415  * estimate for any pair with the same parameterization.
5416  */
5417  nrows = calc_joinrel_size_estimate(root,
5418  rel,
5419  outer_path->parent,
5420  inner_path->parent,
5421  outer_path->rows,
5422  inner_path->rows,
5423  sjinfo,
5424  restrict_clauses);
5425  /* For safety, make sure result is not more than the base estimate */
5426  if (nrows > rel->rows)
5427  nrows = rel->rows;
5428  return nrows;
5429 }
5430 
5431 /*
5432  * calc_joinrel_size_estimate
5433  * Workhorse for set_joinrel_size_estimates and
5434  * get_parameterized_joinrel_size.
5435  *
5436  * outer_rel/inner_rel are the relations being joined, but they should be
5437  * assumed to have sizes outer_rows/inner_rows; those numbers might be less
5438  * than what rel->rows says, when we are considering parameterized paths.
5439  */
5440 static double
5442  RelOptInfo *joinrel,
5443  RelOptInfo *outer_rel,
5444  RelOptInfo *inner_rel,
5445  double outer_rows,
5446  double inner_rows,
5447  SpecialJoinInfo *sjinfo,
5448  List *restrictlist_in)
5449 {
5450  /* This apparently-useless variable dodges a compiler bug in VS2013: */
5451  List *restrictlist = restrictlist_in;
5452  JoinType jointype = sjinfo->jointype;
5453  Selectivity fkselec;
5454  Selectivity jselec;
5455  Selectivity pselec;
5456  double nrows;
5457 
5458  /*
5459  * Compute joinclause selectivity. Note that we are only considering
5460  * clauses that become restriction clauses at this join level; we are not
5461  * double-counting them because they were not considered in estimating the
5462  * sizes of the component rels.
5463  *
5464  * First, see whether any of the joinclauses can be matched to known FK
5465  * constraints. If so, drop those clauses from the restrictlist, and
5466  * instead estimate their selectivity using FK semantics. (We do this
5467  * without regard to whether said clauses are local or "pushed down".
5468  * Probably, an FK-matching clause could never be seen as pushed down at
5469  * an outer join, since it would be strict and hence would be grounds for
5470  * join strength reduction.) fkselec gets the net selectivity for
5471  * FK-matching clauses, or 1.0 if there are none.
5472  */
5473  fkselec = get_foreign_key_join_selectivity(root,
5474  outer_rel->relids,
5475  inner_rel->relids,
5476  sjinfo,
5477  &restrictlist);
5478 
5479  /*
5480  * For an outer join, we have to distinguish the selectivity of the join's
5481  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5482  * down". For inner joins we just count them all as joinclauses.
5483  */
5484  if (IS_OUTER_JOIN(jointype))
5485  {
5486  List *joinquals = NIL;
5487  List *pushedquals = NIL;
5488  ListCell *l;
5489 
5490  /* Grovel through the clauses to separate into two lists */
5491  foreach(l, restrictlist)
5492  {
5493  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5494 
5495  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5496  pushedquals = lappend(pushedquals, rinfo);
5497  else
5498  joinquals = lappend(joinquals, rinfo);
5499  }
5500 
5501  /* Get the separate selectivities */
5502  jselec = clauselist_selectivity(root,
5503  joinquals,
5504  0,
5505  jointype,
5506  sjinfo);
5507  pselec = clauselist_selectivity(root,
5508  pushedquals,
5509  0,
5510  jointype,
5511  sjinfo);
5512 
5513  /* Avoid leaking a lot of ListCells */
5514  list_free(joinquals);
5515  list_free(pushedquals);
5516  }
5517  else
5518  {
5519  jselec = clauselist_selectivity(root,
5520  restrictlist,
5521  0,
5522  jointype,
5523  sjinfo);
5524  pselec = 0.0; /* not used, keep compiler quiet */
5525  }
5526 
5527  /*
5528  * Basically, we multiply size of Cartesian product by selectivity.
5529  *
5530  * If we are doing an outer join, take that into account: the joinqual
5531  * selectivity has to be clamped using the knowledge that the output must
5532  * be at least as large as the non-nullable input. However, any
5533  * pushed-down quals are applied after the outer join, so their
5534  * selectivity applies fully.
5535  *
5536  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5537  * of LHS rows that have matches, and we apply that straightforwardly.
5538  */
5539  switch (jointype)
5540  {
5541  case JOIN_INNER:
5542  nrows = outer_rows * inner_rows * fkselec * jselec;
5543  /* pselec not used */
5544  break;
5545  case JOIN_LEFT:
5546  nrows = outer_rows * inner_rows * fkselec * jselec;
5547  if (nrows < outer_rows)
5548  nrows = outer_rows;
5549  nrows *= pselec;
5550  break;
5551  case JOIN_FULL:
5552  nrows = outer_rows * inner_rows * fkselec * jselec;
5553  if (nrows < outer_rows)
5554  nrows = outer_rows;
5555  if (nrows < inner_rows)
5556  nrows = inner_rows;
5557  nrows *= pselec;
5558  break;
5559  case JOIN_SEMI:
5560  nrows = outer_rows * fkselec * jselec;
5561  /* pselec not used */
5562  break;
5563  case JOIN_ANTI:
5564  nrows = outer_rows * (1.0 - fkselec * jselec);
5565  nrows *= pselec;
5566  break;
5567  default:
5568  /* other values not expected here */
5569  elog(ERROR, "unrecognized join type: %d", (int) jointype);
5570  nrows = 0; /* keep compiler quiet */
5571  break;
5572  }
5573 
5574  return clamp_row_est(nrows);
5575 }
5576 
5577 /*
5578  * get_foreign_key_join_selectivity
5579  * Estimate join selectivity for foreign-key-related clauses.
5580  *
5581  * Remove any clauses that can be matched to FK constraints from *restrictlist,
5582  * and return a substitute estimate of their selectivity. 1.0 is returned
5583  * when there are no such clauses.
5584  *
5585  * The reason for treating such clauses specially is that we can get better
5586  * estimates this way than by relying on clauselist_selectivity(), especially
5587  * for multi-column FKs where that function's assumption that the clauses are
5588  * independent falls down badly. But even with single-column FKs, we may be
5589  * able to get a better answer when the pg_statistic stats are missing or out
5590  * of date.
5591  */
5592 static Selectivity
5594  Relids outer_relids,
5595  Relids inner_relids,
5596  SpecialJoinInfo *sjinfo,
5597  List **restrictlist)
5598 {
5599  Selectivity fkselec = 1.0;
5600  JoinType jointype = sjinfo->jointype;
5601  List *worklist = *restrictlist;
5602  ListCell *lc;
5603 
5604  /* Consider each FK constraint that is known to match the query */
5605  foreach(lc, root->fkey_list)
5606  {
5607  ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
5608  bool ref_is_outer;
5609  List *removedlist;
5610  ListCell *cell;
5611 
5612  /*
5613  * This FK is not relevant unless it connects a baserel on one side of
5614  * this join to a baserel on the other side.
5615  */
5616  if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5617  bms_is_member(fkinfo->ref_relid, inner_relids))
5618  ref_is_outer = false;
5619  else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5620  bms_is_member(fkinfo->con_relid, inner_relids))
5621  ref_is_outer = true;
5622  else
5623  continue;
5624 
5625  /*
5626  * If we're dealing with a semi/anti join, and the FK's referenced
5627  * relation is on the outside, then knowledge of the FK doesn't help
5628  * us figure out what we need to know (which is the fraction of outer
5629  * rows that have matches). On the other hand, if the referenced rel
5630  * is on the inside, then all outer rows must have matches in the
5631  * referenced table (ignoring nulls). But any restriction or join
5632  * clauses that filter that table will reduce the fraction of matches.
5633  * We can account for restriction clauses, but it's too hard to guess
5634  * how many table rows would get through a join that's inside the RHS.
5635  * Hence, if either case applies, punt and ignore the FK.
5636  */
5637  if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
5638  (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
5639  continue;
5640 
5641  /*
5642  * Modify the restrictlist by removing clauses that match the FK (and
5643  * putting them into removedlist instead). It seems unsafe to modify
5644  * the originally-passed List structure, so we make a shallow copy the
5645  * first time through.
5646  */
5647  if (worklist == *restrictlist)
5648  worklist = list_copy(worklist);
5649 
5650  removedlist = NIL;
5651  foreach(cell, worklist)
5652  {
5653  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5654  bool remove_it = false;
5655  int i;
5656 
5657  /* Drop this clause if it matches any column of the FK */
5658  for (i = 0; i < fkinfo->nkeys; i++)
5659  {
5660  if (rinfo->parent_ec)
5661  {
5662  /*
5663  * EC-derived clauses can only match by EC. It is okay to
5664  * consider any clause derived from the same EC as
5665  * matching the FK: even if equivclass.c chose to generate
5666  * a clause equating some other pair of Vars, it could
5667  * have generated one equating the FK's Vars. So for
5668  * purposes of estimation, we can act as though it did so.
5669  *
5670  * Note: checking parent_ec is a bit of a cheat because
5671  * there are EC-derived clauses that don't have parent_ec
5672  * set; but such clauses must compare expressions that
5673  * aren't just Vars, so they cannot match the FK anyway.
5674  */
5675  if (fkinfo->eclass[i] == rinfo->parent_ec)
5676  {
5677  remove_it = true;
5678  break;
5679  }
5680  }
5681  else
5682  {
5683  /*
5684  * Otherwise, see if rinfo was previously matched to FK as
5685  * a "loose" clause.
5686  */
5687  if (list_member_ptr(fkinfo->rinfos[i], rinfo))
5688  {
5689  remove_it = true;
5690  break;
5691  }
5692  }
5693  }
5694  if (remove_it)
5695  {
5696  worklist = foreach_delete_current(worklist, cell);
5697  removedlist = lappend(removedlist, rinfo);
5698  }
5699  }
5700 
5701  /*
5702  * If we failed to remove all the matching clauses we expected to
5703  * find, chicken out and ignore this FK; applying its selectivity
5704  * might result in double-counting. Put any clauses we did manage to
5705  * remove back into the worklist.
5706  *
5707  * Since the matching clauses are known not outerjoin-delayed, they
5708  * would normally have appeared in the initial joinclause list. If we
5709  * didn't find them, there are two possibilities:
5710  *
5711  * 1. If the FK match is based on an EC that is ec_has_const, it won't
5712  * have generated any join clauses at all. We discount such ECs while
5713  * checking to see if we have "all" the clauses. (Below, we'll adjust
5714  * the selectivity estimate for this case.)
5715  *
5716  * 2. The clauses were matched to some other FK in a previous
5717  * iteration of this loop, and thus removed from worklist. (A likely
5718  * case is that two FKs are matched to the same EC; there will be only
5719  * one EC-derived clause in the initial list, so the first FK will
5720  * consume it.) Applying both FKs' selectivity independently risks
5721  * underestimating the join size; in particular, this would undo one
5722  * of the main things that ECs were invented for, namely to avoid
5723  * double-counting the selectivity of redundant equality conditions.
5724  * Later we might think of a reasonable way to combine the estimates,
5725  * but for now, just punt, since this is a fairly uncommon situation.
5726  */
5727  if (removedlist == NIL ||
5728  list_length(removedlist) !=
5729  (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
5730  {
5731  worklist = list_concat(worklist, removedlist);
5732  continue;
5733  }
5734 
5735  /*
5736  * Finally we get to the payoff: estimate selectivity using the
5737  * knowledge that each referencing row will match exactly one row in
5738  * the referenced table.
5739  *
5740  * XXX that's not true in the presence of nulls in the referencing
5741  * column(s), so in principle we should derate the estimate for those.
5742  * However (1) if there are any strict restriction clauses for the
5743  * referencing column(s) elsewhere in the query, derating here would
5744  * be double-counting the null fraction, and (2) it's not very clear
5745  * how to combine null fractions for multiple referencing columns. So
5746  * we do nothing for now about correcting for nulls.
5747  *
5748  * XXX another point here is that if either side of an FK constraint
5749  * is an inheritance parent, we estimate as though the constraint
5750  * covers all its children as well. This is not an unreasonable
5751  * assumption for a referencing table, ie the user probably applied
5752  * identical constraints to all child tables (though perhaps we ought
5753  * to check that). But it's not possible to have done that for a
5754  * referenced table. Fortunately, precisely because that doesn't
5755  * work, it is uncommon in practice to have an FK referencing a parent
5756  * table. So, at least for now, disregard inheritance here.
5757  */
5758  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
5759  {
5760  /*
5761  * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
5762  * referenced table is exactly the inside of the join. The join
5763  * selectivity is defined as the fraction of LHS rows that have
5764  * matches. The FK implies that every LHS row has a match *in the
5765  * referenced table*; but any restriction clauses on it will
5766  * reduce the number of matches. Hence we take the join
5767  * selectivity as equal to the selectivity of the table's
5768  * restriction clauses, which is rows / tuples; but we must guard
5769  * against tuples == 0.
5770  */
5771  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5772  double ref_tuples = Max(ref_rel->tuples, 1.0);
5773 
5774  fkselec *= ref_rel->rows / ref_tuples;
5775  }
5776  else
5777  {
5778  /*
5779  * Otherwise, selectivity is exactly 1/referenced-table-size; but
5780  * guard against tuples == 0. Note we should use the raw table
5781  * tuple count, not any estimate of its filtered or joined size.
5782  */
5783  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5784  double ref_tuples = Max(ref_rel->tuples, 1.0);
5785 
5786  fkselec *= 1.0 / ref_tuples;
5787  }
5788 
5789  /*
5790  * If any of the FK columns participated in ec_has_const ECs, then
5791  * equivclass.c will have generated "var = const" restrictions for
5792  * each side of the join, thus reducing the sizes of both input
5793  * relations. Taking the fkselec at face value would amount to
5794  * double-counting the selectivity of the constant restriction for the
5795  * referencing Var. Hence, look for the restriction clause(s) that
5796  * were applied to the referencing Var(s), and divide out their
5797  * selectivity to correct for this.
5798  */
5799  if (fkinfo->nconst_ec > 0)
5800  {
5801  for (int i = 0; i < fkinfo->nkeys; i++)
5802  {
5803  EquivalenceClass *ec = fkinfo->eclass[i];
5804 
5805  if (ec && ec->ec_has_const)
5806  {
5807  EquivalenceMember *em = fkinfo->fk_eclass_member[i];
5809  em);
5810 
5811  if (rinfo)
5812  {
5813  Selectivity s0;
5814 
5815  s0 = clause_selectivity(root,
5816  (Node *) rinfo,
5817  0,
5818  jointype,
5819  sjinfo);
5820  if (s0 > 0)
5821  fkselec /= s0;
5822  }
5823  }
5824  }
5825  }
5826  }
5827 
5828  *restrictlist = worklist;
5829  CLAMP_PROBABILITY(fkselec);
5830  return fkselec;
5831 }
5832 
5833 /*
5834  * set_subquery_size_estimates
5835  * Set the size estimates for a base relation that is a subquery.
5836  *
5837  * The rel's targetlist and restrictinfo list must have been constructed
5838  * already, and the Paths for the subquery must have been completed.
5839  * We look at the subquery's PlannerInfo to extract data.
5840  *
5841  * We set the same fields as set_baserel_size_estimates.
5842  */
5843 void
5845 {
5846  PlannerInfo *subroot = rel->subroot;
5847  RelOptInfo *sub_final_rel;
5848  ListCell *lc;
5849 
5850  /* Should only be applied to base relations that are subqueries */
5851  Assert(rel->relid > 0);
5852  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5853 
5854  /*
5855  * Copy raw number of output rows from subquery. All of its paths should
5856  * have the same output rowcount, so just look at cheapest-total.
5857  */
5858  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5859  rel->tuples = sub_final_rel->cheapest_total_path->rows;
5860 
5861  /*
5862  * Compute per-output-column width estimates by examining the subquery's
5863  * targetlist. For any output that is a plain Var, get the width estimate
5864  * that was made while planning the subquery. Otherwise, we leave it to
5865  * set_rel_width to fill in a datatype-based default estimate.
5866  */
5867  foreach(lc, subroot->parse->targetList)
5868  {
5869  TargetEntry *te = lfirst_node(TargetEntry, lc);
5870  Node *texpr = (Node *) te->expr;
5871  int32 item_width = 0;
5872 
5873  /* junk columns aren't visible to upper query */
5874  if (te->resjunk)
5875  continue;
5876 
5877  /*
5878  * The subquery could be an expansion of a view that's had columns
5879  * added to it since the current query was parsed, so that there are
5880  * non-junk tlist columns in it that don't correspond to any column
5881  * visible at our query level. Ignore such columns.
5882  */
5883  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5884  continue;
5885 
5886  /*
5887  * XXX This currently doesn't work for subqueries containing set
5888  * operations, because the Vars in their tlists are bogus references
5889  * to the first leaf subquery, which wouldn't give the right answer
5890  * even if we could still get to its PlannerInfo.
5891  *
5892  * Also, the subquery could be an appendrel for which all branches are
5893  * known empty due to constraint exclusion, in which case
5894  * set_append_rel_pathlist will have left the attr_widths set to zero.
5895  *
5896  * In either case, we just leave the width estimate zero until
5897  * set_rel_width fixes it.
5898  */
5899  if (IsA(texpr, Var) &&
5900  subroot->parse->setOperations == NULL)
5901  {
5902  Var *var = (Var *) texpr;
5903  RelOptInfo</