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