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