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