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