PostgreSQL Source Code  git master
pathnode.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pathnode.c
4  * Routines to manipulate pathlists and create path nodes
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/optimizer/util/pathnode.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <math.h>
18 
19 #include "miscadmin.h"
20 #include "nodes/nodeFuncs.h"
21 #include "nodes/extensible.h"
22 #include "optimizer/clauses.h"
23 #include "optimizer/cost.h"
24 #include "optimizer/pathnode.h"
25 #include "optimizer/paths.h"
26 #include "optimizer/planmain.h"
27 #include "optimizer/prep.h"
28 #include "optimizer/restrictinfo.h"
29 #include "optimizer/tlist.h"
30 #include "optimizer/var.h"
31 #include "parser/parsetree.h"
32 #include "foreign/fdwapi.h"
33 #include "utils/lsyscache.h"
34 #include "utils/memutils.h"
35 #include "utils/selfuncs.h"
36 
37 
38 typedef enum
39 {
40  COSTS_EQUAL, /* path costs are fuzzily equal */
41  COSTS_BETTER1, /* first path is cheaper than second */
42  COSTS_BETTER2, /* second path is cheaper than first */
43  COSTS_DIFFERENT /* neither path dominates the other on cost */
45 
46 /*
47  * STD_FUZZ_FACTOR is the normal fuzz factor for compare_path_costs_fuzzily.
48  * XXX is it worth making this user-controllable? It provides a tradeoff
49  * between planner runtime and the accuracy of path cost comparisons.
50  */
51 #define STD_FUZZ_FACTOR 1.01
52 
53 static List *translate_sub_tlist(List *tlist, int relid);
55  List *pathlist,
56  RelOptInfo *child_rel);
57 
58 
59 /*****************************************************************************
60  * MISC. PATH UTILITIES
61  *****************************************************************************/
62 
63 /*
64  * compare_path_costs
65  * Return -1, 0, or +1 according as path1 is cheaper, the same cost,
66  * or more expensive than path2 for the specified criterion.
67  */
68 int
69 compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
70 {
71  if (criterion == STARTUP_COST)
72  {
73  if (path1->startup_cost < path2->startup_cost)
74  return -1;
75  if (path1->startup_cost > path2->startup_cost)
76  return +1;
77 
78  /*
79  * If paths have the same startup cost (not at all unlikely), order
80  * them by total cost.
81  */
82  if (path1->total_cost < path2->total_cost)
83  return -1;
84  if (path1->total_cost > path2->total_cost)
85  return +1;
86  }
87  else
88  {
89  if (path1->total_cost < path2->total_cost)
90  return -1;
91  if (path1->total_cost > path2->total_cost)
92  return +1;
93 
94  /*
95  * If paths have the same total cost, order them by startup cost.
96  */
97  if (path1->startup_cost < path2->startup_cost)
98  return -1;
99  if (path1->startup_cost > path2->startup_cost)
100  return +1;
101  }
102  return 0;
103 }
104 
105 /*
106  * compare_path_fractional_costs
107  * Return -1, 0, or +1 according as path1 is cheaper, the same cost,
108  * or more expensive than path2 for fetching the specified fraction
109  * of the total tuples.
110  *
111  * If fraction is <= 0 or > 1, we interpret it as 1, ie, we select the
112  * path with the cheaper total_cost.
113  */
114 int
116  double fraction)
117 {
118  Cost cost1,
119  cost2;
120 
121  if (fraction <= 0.0 || fraction >= 1.0)
122  return compare_path_costs(path1, path2, TOTAL_COST);
123  cost1 = path1->startup_cost +
124  fraction * (path1->total_cost - path1->startup_cost);
125  cost2 = path2->startup_cost +
126  fraction * (path2->total_cost - path2->startup_cost);
127  if (cost1 < cost2)
128  return -1;
129  if (cost1 > cost2)
130  return +1;
131  return 0;
132 }
133 
134 /*
135  * compare_path_costs_fuzzily
136  * Compare the costs of two paths to see if either can be said to
137  * dominate the other.
138  *
139  * We use fuzzy comparisons so that add_path() can avoid keeping both of
140  * a pair of paths that really have insignificantly different cost.
141  *
142  * The fuzz_factor argument must be 1.0 plus delta, where delta is the
143  * fraction of the smaller cost that is considered to be a significant
144  * difference. For example, fuzz_factor = 1.01 makes the fuzziness limit
145  * be 1% of the smaller cost.
146  *
147  * The two paths are said to have "equal" costs if both startup and total
148  * costs are fuzzily the same. Path1 is said to be better than path2 if
149  * it has fuzzily better startup cost and fuzzily no worse total cost,
150  * or if it has fuzzily better total cost and fuzzily no worse startup cost.
151  * Path2 is better than path1 if the reverse holds. Finally, if one path
152  * is fuzzily better than the other on startup cost and fuzzily worse on
153  * total cost, we just say that their costs are "different", since neither
154  * dominates the other across the whole performance spectrum.
155  *
156  * This function also enforces a policy rule that paths for which the relevant
157  * one of parent->consider_startup and parent->consider_param_startup is false
158  * cannot survive comparisons solely on the grounds of good startup cost, so
159  * we never return COSTS_DIFFERENT when that is true for the total-cost loser.
160  * (But if total costs are fuzzily equal, we compare startup costs anyway,
161  * in hopes of eliminating one path or the other.)
162  */
163 static PathCostComparison
164 compare_path_costs_fuzzily(Path *path1, Path *path2, double fuzz_factor)
165 {
166 #define CONSIDER_PATH_STARTUP_COST(p) \
167  ((p)->param_info == NULL ? (p)->parent->consider_startup : (p)->parent->consider_param_startup)
168 
169  /*
170  * Check total cost first since it's more likely to be different; many
171  * paths have zero startup cost.
172  */
173  if (path1->total_cost > path2->total_cost * fuzz_factor)
174  {
175  /* path1 fuzzily worse on total cost */
176  if (CONSIDER_PATH_STARTUP_COST(path1) &&
177  path2->startup_cost > path1->startup_cost * fuzz_factor)
178  {
179  /* ... but path2 fuzzily worse on startup, so DIFFERENT */
180  return COSTS_DIFFERENT;
181  }
182  /* else path2 dominates */
183  return COSTS_BETTER2;
184  }
185  if (path2->total_cost > path1->total_cost * fuzz_factor)
186  {
187  /* path2 fuzzily worse on total cost */
188  if (CONSIDER_PATH_STARTUP_COST(path2) &&
189  path1->startup_cost > path2->startup_cost * fuzz_factor)
190  {
191  /* ... but path1 fuzzily worse on startup, so DIFFERENT */
192  return COSTS_DIFFERENT;
193  }
194  /* else path1 dominates */
195  return COSTS_BETTER1;
196  }
197  /* fuzzily the same on total cost ... */
198  if (path1->startup_cost > path2->startup_cost * fuzz_factor)
199  {
200  /* ... but path1 fuzzily worse on startup, so path2 wins */
201  return COSTS_BETTER2;
202  }
203  if (path2->startup_cost > path1->startup_cost * fuzz_factor)
204  {
205  /* ... but path2 fuzzily worse on startup, so path1 wins */
206  return COSTS_BETTER1;
207  }
208  /* fuzzily the same on both costs */
209  return COSTS_EQUAL;
210 
211 #undef CONSIDER_PATH_STARTUP_COST
212 }
213 
214 /*
215  * set_cheapest
216  * Find the minimum-cost paths from among a relation's paths,
217  * and save them in the rel's cheapest-path fields.
218  *
219  * cheapest_total_path is normally the cheapest-total-cost unparameterized
220  * path; but if there are no unparameterized paths, we assign it to be the
221  * best (cheapest least-parameterized) parameterized path. However, only
222  * unparameterized paths are considered candidates for cheapest_startup_path,
223  * so that will be NULL if there are no unparameterized paths.
224  *
225  * The cheapest_parameterized_paths list collects all parameterized paths
226  * that have survived the add_path() tournament for this relation. (Since
227  * add_path ignores pathkeys for a parameterized path, these will be paths
228  * that have best cost or best row count for their parameterization. We
229  * may also have both a parallel-safe and a non-parallel-safe path in some
230  * cases for the same parameterization in some cases, but this should be
231  * relatively rare since, most typically, all paths for the same relation
232  * will be parallel-safe or none of them will.)
233  *
234  * cheapest_parameterized_paths always includes the cheapest-total
235  * unparameterized path, too, if there is one; the users of that list find
236  * it more convenient if that's included.
237  *
238  * This is normally called only after we've finished constructing the path
239  * list for the rel node.
240  */
241 void
243 {
244  Path *cheapest_startup_path;
245  Path *cheapest_total_path;
246  Path *best_param_path;
247  List *parameterized_paths;
248  ListCell *p;
249 
250  Assert(IsA(parent_rel, RelOptInfo));
251 
252  if (parent_rel->pathlist == NIL)
253  elog(ERROR, "could not devise a query plan for the given query");
254 
255  cheapest_startup_path = cheapest_total_path = best_param_path = NULL;
256  parameterized_paths = NIL;
257 
258  foreach(p, parent_rel->pathlist)
259  {
260  Path *path = (Path *) lfirst(p);
261  int cmp;
262 
263  if (path->param_info)
264  {
265  /* Parameterized path, so add it to parameterized_paths */
266  parameterized_paths = lappend(parameterized_paths, path);
267 
268  /*
269  * If we have an unparameterized cheapest-total, we no longer care
270  * about finding the best parameterized path, so move on.
271  */
272  if (cheapest_total_path)
273  continue;
274 
275  /*
276  * Otherwise, track the best parameterized path, which is the one
277  * with least total cost among those of the minimum
278  * parameterization.
279  */
280  if (best_param_path == NULL)
281  best_param_path = path;
282  else
283  {
284  switch (bms_subset_compare(PATH_REQ_OUTER(path),
285  PATH_REQ_OUTER(best_param_path)))
286  {
287  case BMS_EQUAL:
288  /* keep the cheaper one */
289  if (compare_path_costs(path, best_param_path,
290  TOTAL_COST) < 0)
291  best_param_path = path;
292  break;
293  case BMS_SUBSET1:
294  /* new path is less-parameterized */
295  best_param_path = path;
296  break;
297  case BMS_SUBSET2:
298  /* old path is less-parameterized, keep it */
299  break;
300  case BMS_DIFFERENT:
301 
302  /*
303  * This means that neither path has the least possible
304  * parameterization for the rel. We'll sit on the old
305  * path until something better comes along.
306  */
307  break;
308  }
309  }
310  }
311  else
312  {
313  /* Unparameterized path, so consider it for cheapest slots */
314  if (cheapest_total_path == NULL)
315  {
316  cheapest_startup_path = cheapest_total_path = path;
317  continue;
318  }
319 
320  /*
321  * If we find two paths of identical costs, try to keep the
322  * better-sorted one. The paths might have unrelated sort
323  * orderings, in which case we can only guess which might be
324  * better to keep, but if one is superior then we definitely
325  * should keep that one.
326  */
327  cmp = compare_path_costs(cheapest_startup_path, path, STARTUP_COST);
328  if (cmp > 0 ||
329  (cmp == 0 &&
330  compare_pathkeys(cheapest_startup_path->pathkeys,
331  path->pathkeys) == PATHKEYS_BETTER2))
332  cheapest_startup_path = path;
333 
334  cmp = compare_path_costs(cheapest_total_path, path, TOTAL_COST);
335  if (cmp > 0 ||
336  (cmp == 0 &&
337  compare_pathkeys(cheapest_total_path->pathkeys,
338  path->pathkeys) == PATHKEYS_BETTER2))
339  cheapest_total_path = path;
340  }
341  }
342 
343  /* Add cheapest unparameterized path, if any, to parameterized_paths */
344  if (cheapest_total_path)
345  parameterized_paths = lcons(cheapest_total_path, parameterized_paths);
346 
347  /*
348  * If there is no unparameterized path, use the best parameterized path as
349  * cheapest_total_path (but not as cheapest_startup_path).
350  */
351  if (cheapest_total_path == NULL)
352  cheapest_total_path = best_param_path;
353  Assert(cheapest_total_path != NULL);
354 
355  parent_rel->cheapest_startup_path = cheapest_startup_path;
356  parent_rel->cheapest_total_path = cheapest_total_path;
357  parent_rel->cheapest_unique_path = NULL; /* computed only if needed */
358  parent_rel->cheapest_parameterized_paths = parameterized_paths;
359 }
360 
361 /*
362  * add_path
363  * Consider a potential implementation path for the specified parent rel,
364  * and add it to the rel's pathlist if it is worthy of consideration.
365  * A path is worthy if it has a better sort order (better pathkeys) or
366  * cheaper cost (on either dimension), or generates fewer rows, than any
367  * existing path that has the same or superset parameterization rels.
368  * We also consider parallel-safe paths more worthy than others.
369  *
370  * We also remove from the rel's pathlist any old paths that are dominated
371  * by new_path --- that is, new_path is cheaper, at least as well ordered,
372  * generates no more rows, requires no outer rels not required by the old
373  * path, and is no less parallel-safe.
374  *
375  * In most cases, a path with a superset parameterization will generate
376  * fewer rows (since it has more join clauses to apply), so that those two
377  * figures of merit move in opposite directions; this means that a path of
378  * one parameterization can seldom dominate a path of another. But such
379  * cases do arise, so we make the full set of checks anyway.
380  *
381  * There are two policy decisions embedded in this function, along with
382  * its sibling add_path_precheck. First, we treat all parameterized paths
383  * as having NIL pathkeys, so that they cannot win comparisons on the
384  * basis of sort order. This is to reduce the number of parameterized
385  * paths that are kept; see discussion in src/backend/optimizer/README.
386  *
387  * Second, we only consider cheap startup cost to be interesting if
388  * parent_rel->consider_startup is true for an unparameterized path, or
389  * parent_rel->consider_param_startup is true for a parameterized one.
390  * Again, this allows discarding useless paths sooner.
391  *
392  * The pathlist is kept sorted by total_cost, with cheaper paths
393  * at the front. Within this routine, that's simply a speed hack:
394  * doing it that way makes it more likely that we will reject an inferior
395  * path after a few comparisons, rather than many comparisons.
396  * However, add_path_precheck relies on this ordering to exit early
397  * when possible.
398  *
399  * NOTE: discarded Path objects are immediately pfree'd to reduce planner
400  * memory consumption. We dare not try to free the substructure of a Path,
401  * since much of it may be shared with other Paths or the query tree itself;
402  * but just recycling discarded Path nodes is a very useful savings in
403  * a large join tree. We can recycle the List nodes of pathlist, too.
404  *
405  * As noted in optimizer/README, deleting a previously-accepted Path is
406  * safe because we know that Paths of this rel cannot yet be referenced
407  * from any other rel, such as a higher-level join. However, in some cases
408  * it is possible that a Path is referenced by another Path for its own
409  * rel; we must not delete such a Path, even if it is dominated by the new
410  * Path. Currently this occurs only for IndexPath objects, which may be
411  * referenced as children of BitmapHeapPaths as well as being paths in
412  * their own right. Hence, we don't pfree IndexPaths when rejecting them.
413  *
414  * 'parent_rel' is the relation entry to which the path corresponds.
415  * 'new_path' is a potential path for parent_rel.
416  *
417  * Returns nothing, but modifies parent_rel->pathlist.
418  */
419 void
420 add_path(RelOptInfo *parent_rel, Path *new_path)
421 {
422  bool accept_new = true; /* unless we find a superior old path */
423  ListCell *insert_after = NULL; /* where to insert new item */
424  List *new_path_pathkeys;
425  ListCell *p1;
426  ListCell *p1_prev;
427  ListCell *p1_next;
428 
429  /*
430  * This is a convenient place to check for query cancel --- no part of the
431  * planner goes very long without calling add_path().
432  */
434 
435  /* Pretend parameterized paths have no pathkeys, per comment above */
436  new_path_pathkeys = new_path->param_info ? NIL : new_path->pathkeys;
437 
438  /*
439  * Loop to check proposed new path against old paths. Note it is possible
440  * for more than one old path to be tossed out because new_path dominates
441  * it.
442  *
443  * We can't use foreach here because the loop body may delete the current
444  * list cell.
445  */
446  p1_prev = NULL;
447  for (p1 = list_head(parent_rel->pathlist); p1 != NULL; p1 = p1_next)
448  {
449  Path *old_path = (Path *) lfirst(p1);
450  bool remove_old = false; /* unless new proves superior */
451  PathCostComparison costcmp;
452  PathKeysComparison keyscmp;
453  BMS_Comparison outercmp;
454 
455  p1_next = lnext(p1);
456 
457  /*
458  * Do a fuzzy cost comparison with standard fuzziness limit.
459  */
460  costcmp = compare_path_costs_fuzzily(new_path, old_path,
462 
463  /*
464  * If the two paths compare differently for startup and total cost,
465  * then we want to keep both, and we can skip comparing pathkeys and
466  * required_outer rels. If they compare the same, proceed with the
467  * other comparisons. Row count is checked last. (We make the tests
468  * in this order because the cost comparison is most likely to turn
469  * out "different", and the pathkeys comparison next most likely. As
470  * explained above, row count very seldom makes a difference, so even
471  * though it's cheap to compare there's not much point in checking it
472  * earlier.)
473  */
474  if (costcmp != COSTS_DIFFERENT)
475  {
476  /* Similarly check to see if either dominates on pathkeys */
477  List *old_path_pathkeys;
478 
479  old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
480  keyscmp = compare_pathkeys(new_path_pathkeys,
481  old_path_pathkeys);
482  if (keyscmp != PATHKEYS_DIFFERENT)
483  {
484  switch (costcmp)
485  {
486  case COSTS_EQUAL:
487  outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
488  PATH_REQ_OUTER(old_path));
489  if (keyscmp == PATHKEYS_BETTER1)
490  {
491  if ((outercmp == BMS_EQUAL ||
492  outercmp == BMS_SUBSET1) &&
493  new_path->rows <= old_path->rows &&
494  new_path->parallel_safe >= old_path->parallel_safe)
495  remove_old = true; /* new dominates old */
496  }
497  else if (keyscmp == PATHKEYS_BETTER2)
498  {
499  if ((outercmp == BMS_EQUAL ||
500  outercmp == BMS_SUBSET2) &&
501  new_path->rows >= old_path->rows &&
502  new_path->parallel_safe <= old_path->parallel_safe)
503  accept_new = false; /* old dominates new */
504  }
505  else /* keyscmp == PATHKEYS_EQUAL */
506  {
507  if (outercmp == BMS_EQUAL)
508  {
509  /*
510  * Same pathkeys and outer rels, and fuzzily
511  * the same cost, so keep just one; to decide
512  * which, first check parallel-safety, then
513  * rows, then do a fuzzy cost comparison with
514  * very small fuzz limit. (We used to do an
515  * exact cost comparison, but that results in
516  * annoying platform-specific plan variations
517  * due to roundoff in the cost estimates.) If
518  * things are still tied, arbitrarily keep
519  * only the old path. Notice that we will
520  * keep only the old path even if the
521  * less-fuzzy comparison decides the startup
522  * and total costs compare differently.
523  */
524  if (new_path->parallel_safe >
525  old_path->parallel_safe)
526  remove_old = true; /* new dominates old */
527  else if (new_path->parallel_safe <
528  old_path->parallel_safe)
529  accept_new = false; /* old dominates new */
530  else if (new_path->rows < old_path->rows)
531  remove_old = true; /* new dominates old */
532  else if (new_path->rows > old_path->rows)
533  accept_new = false; /* old dominates new */
534  else if (compare_path_costs_fuzzily(new_path,
535  old_path,
536  1.0000000001) == COSTS_BETTER1)
537  remove_old = true; /* new dominates old */
538  else
539  accept_new = false; /* old equals or
540  * dominates new */
541  }
542  else if (outercmp == BMS_SUBSET1 &&
543  new_path->rows <= old_path->rows &&
544  new_path->parallel_safe >= old_path->parallel_safe)
545  remove_old = true; /* new dominates old */
546  else if (outercmp == BMS_SUBSET2 &&
547  new_path->rows >= old_path->rows &&
548  new_path->parallel_safe <= old_path->parallel_safe)
549  accept_new = false; /* old dominates new */
550  /* else different parameterizations, keep both */
551  }
552  break;
553  case COSTS_BETTER1:
554  if (keyscmp != PATHKEYS_BETTER2)
555  {
556  outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
557  PATH_REQ_OUTER(old_path));
558  if ((outercmp == BMS_EQUAL ||
559  outercmp == BMS_SUBSET1) &&
560  new_path->rows <= old_path->rows &&
561  new_path->parallel_safe >= old_path->parallel_safe)
562  remove_old = true; /* new dominates old */
563  }
564  break;
565  case COSTS_BETTER2:
566  if (keyscmp != PATHKEYS_BETTER1)
567  {
568  outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
569  PATH_REQ_OUTER(old_path));
570  if ((outercmp == BMS_EQUAL ||
571  outercmp == BMS_SUBSET2) &&
572  new_path->rows >= old_path->rows &&
573  new_path->parallel_safe <= old_path->parallel_safe)
574  accept_new = false; /* old dominates new */
575  }
576  break;
577  case COSTS_DIFFERENT:
578 
579  /*
580  * can't get here, but keep this case to keep compiler
581  * quiet
582  */
583  break;
584  }
585  }
586  }
587 
588  /*
589  * Remove current element from pathlist if dominated by new.
590  */
591  if (remove_old)
592  {
593  parent_rel->pathlist = list_delete_cell(parent_rel->pathlist,
594  p1, p1_prev);
595 
596  /*
597  * Delete the data pointed-to by the deleted cell, if possible
598  */
599  if (!IsA(old_path, IndexPath))
600  pfree(old_path);
601  /* p1_prev does not advance */
602  }
603  else
604  {
605  /* new belongs after this old path if it has cost >= old's */
606  if (new_path->total_cost >= old_path->total_cost)
607  insert_after = p1;
608  /* p1_prev advances */
609  p1_prev = p1;
610  }
611 
612  /*
613  * If we found an old path that dominates new_path, we can quit
614  * scanning the pathlist; we will not add new_path, and we assume
615  * new_path cannot dominate any other elements of the pathlist.
616  */
617  if (!accept_new)
618  break;
619  }
620 
621  if (accept_new)
622  {
623  /* Accept the new path: insert it at proper place in pathlist */
624  if (insert_after)
625  lappend_cell(parent_rel->pathlist, insert_after, new_path);
626  else
627  parent_rel->pathlist = lcons(new_path, parent_rel->pathlist);
628  }
629  else
630  {
631  /* Reject and recycle the new path */
632  if (!IsA(new_path, IndexPath))
633  pfree(new_path);
634  }
635 }
636 
637 /*
638  * add_path_precheck
639  * Check whether a proposed new path could possibly get accepted.
640  * We assume we know the path's pathkeys and parameterization accurately,
641  * and have lower bounds for its costs.
642  *
643  * Note that we do not know the path's rowcount, since getting an estimate for
644  * that is too expensive to do before prechecking. We assume here that paths
645  * of a superset parameterization will generate fewer rows; if that holds,
646  * then paths with different parameterizations cannot dominate each other
647  * and so we can simply ignore existing paths of another parameterization.
648  * (In the infrequent cases where that rule of thumb fails, add_path will
649  * get rid of the inferior path.)
650  *
651  * At the time this is called, we haven't actually built a Path structure,
652  * so the required information has to be passed piecemeal.
653  */
654 bool
656  Cost startup_cost, Cost total_cost,
657  List *pathkeys, Relids required_outer)
658 {
659  List *new_path_pathkeys;
660  bool consider_startup;
661  ListCell *p1;
662 
663  /* Pretend parameterized paths have no pathkeys, per add_path policy */
664  new_path_pathkeys = required_outer ? NIL : pathkeys;
665 
666  /* Decide whether new path's startup cost is interesting */
667  consider_startup = required_outer ? parent_rel->consider_param_startup : parent_rel->consider_startup;
668 
669  foreach(p1, parent_rel->pathlist)
670  {
671  Path *old_path = (Path *) lfirst(p1);
672  PathKeysComparison keyscmp;
673 
674  /*
675  * We are looking for an old_path with the same parameterization (and
676  * by assumption the same rowcount) that dominates the new path on
677  * pathkeys as well as both cost metrics. If we find one, we can
678  * reject the new path.
679  *
680  * Cost comparisons here should match compare_path_costs_fuzzily.
681  */
682  if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
683  {
684  /* new path can win on startup cost only if consider_startup */
685  if (startup_cost > old_path->startup_cost * STD_FUZZ_FACTOR ||
686  !consider_startup)
687  {
688  /* new path loses on cost, so check pathkeys... */
689  List *old_path_pathkeys;
690 
691  old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
692  keyscmp = compare_pathkeys(new_path_pathkeys,
693  old_path_pathkeys);
694  if (keyscmp == PATHKEYS_EQUAL ||
695  keyscmp == PATHKEYS_BETTER2)
696  {
697  /* new path does not win on pathkeys... */
698  if (bms_equal(required_outer, PATH_REQ_OUTER(old_path)))
699  {
700  /* Found an old path that dominates the new one */
701  return false;
702  }
703  }
704  }
705  }
706  else
707  {
708  /*
709  * Since the pathlist is sorted by total_cost, we can stop looking
710  * once we reach a path with a total_cost larger than the new
711  * path's.
712  */
713  break;
714  }
715  }
716 
717  return true;
718 }
719 
720 /*
721  * add_partial_path
722  * Like add_path, our goal here is to consider whether a path is worthy
723  * of being kept around, but the considerations here are a bit different.
724  * A partial path is one which can be executed in any number of workers in
725  * parallel such that each worker will generate a subset of the path's
726  * overall result.
727  *
728  * As in add_path, the partial_pathlist is kept sorted with the cheapest
729  * total path in front. This is depended on by multiple places, which
730  * just take the front entry as the cheapest path without searching.
731  *
732  * We don't generate parameterized partial paths for several reasons. Most
733  * importantly, they're not safe to execute, because there's nothing to
734  * make sure that a parallel scan within the parameterized portion of the
735  * plan is running with the same value in every worker at the same time.
736  * Fortunately, it seems unlikely to be worthwhile anyway, because having
737  * each worker scan the entire outer relation and a subset of the inner
738  * relation will generally be a terrible plan. The inner (parameterized)
739  * side of the plan will be small anyway. There could be rare cases where
740  * this wins big - e.g. if join order constraints put a 1-row relation on
741  * the outer side of the topmost join with a parameterized plan on the inner
742  * side - but we'll have to be content not to handle such cases until
743  * somebody builds an executor infrastructure that can cope with them.
744  *
745  * Because we don't consider parameterized paths here, we also don't
746  * need to consider the row counts as a measure of quality: every path will
747  * produce the same number of rows. Neither do we need to consider startup
748  * costs: parallelism is only used for plans that will be run to completion.
749  * Therefore, this routine is much simpler than add_path: it needs to
750  * consider only pathkeys and total cost.
751  *
752  * As with add_path, we pfree paths that are found to be dominated by
753  * another partial path; this requires that there be no other references to
754  * such paths yet. Hence, GatherPaths must not be created for a rel until
755  * we're done creating all partial paths for it. Unlike add_path, we don't
756  * take an exception for IndexPaths as partial index paths won't be
757  * referenced by partial BitmapHeapPaths.
758  */
759 void
760 add_partial_path(RelOptInfo *parent_rel, Path *new_path)
761 {
762  bool accept_new = true; /* unless we find a superior old path */
763  ListCell *insert_after = NULL; /* where to insert new item */
764  ListCell *p1;
765  ListCell *p1_prev;
766  ListCell *p1_next;
767 
768  /* Check for query cancel. */
770 
771  /*
772  * As in add_path, throw out any paths which are dominated by the new
773  * path, but throw out the new path if some existing path dominates it.
774  */
775  p1_prev = NULL;
776  for (p1 = list_head(parent_rel->partial_pathlist); p1 != NULL;
777  p1 = p1_next)
778  {
779  Path *old_path = (Path *) lfirst(p1);
780  bool remove_old = false; /* unless new proves superior */
781  PathKeysComparison keyscmp;
782 
783  p1_next = lnext(p1);
784 
785  /* Compare pathkeys. */
786  keyscmp = compare_pathkeys(new_path->pathkeys, old_path->pathkeys);
787 
788  /* Unless pathkeys are incompable, keep just one of the two paths. */
789  if (keyscmp != PATHKEYS_DIFFERENT)
790  {
791  if (new_path->total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
792  {
793  /* New path costs more; keep it only if pathkeys are better. */
794  if (keyscmp != PATHKEYS_BETTER1)
795  accept_new = false;
796  }
797  else if (old_path->total_cost > new_path->total_cost
798  * STD_FUZZ_FACTOR)
799  {
800  /* Old path costs more; keep it only if pathkeys are better. */
801  if (keyscmp != PATHKEYS_BETTER2)
802  remove_old = true;
803  }
804  else if (keyscmp == PATHKEYS_BETTER1)
805  {
806  /* Costs are about the same, new path has better pathkeys. */
807  remove_old = true;
808  }
809  else if (keyscmp == PATHKEYS_BETTER2)
810  {
811  /* Costs are about the same, old path has better pathkeys. */
812  accept_new = false;
813  }
814  else if (old_path->total_cost > new_path->total_cost * 1.0000000001)
815  {
816  /* Pathkeys are the same, and the old path costs more. */
817  remove_old = true;
818  }
819  else
820  {
821  /*
822  * Pathkeys are the same, and new path isn't materially
823  * cheaper.
824  */
825  accept_new = false;
826  }
827  }
828 
829  /*
830  * Remove current element from partial_pathlist if dominated by new.
831  */
832  if (remove_old)
833  {
834  parent_rel->partial_pathlist =
835  list_delete_cell(parent_rel->partial_pathlist, p1, p1_prev);
836  pfree(old_path);
837  /* p1_prev does not advance */
838  }
839  else
840  {
841  /* new belongs after this old path if it has cost >= old's */
842  if (new_path->total_cost >= old_path->total_cost)
843  insert_after = p1;
844  /* p1_prev advances */
845  p1_prev = p1;
846  }
847 
848  /*
849  * If we found an old path that dominates new_path, we can quit
850  * scanning the partial_pathlist; we will not add new_path, and we
851  * assume new_path cannot dominate any later path.
852  */
853  if (!accept_new)
854  break;
855  }
856 
857  if (accept_new)
858  {
859  /* Accept the new path: insert it at proper place */
860  if (insert_after)
861  lappend_cell(parent_rel->partial_pathlist, insert_after, new_path);
862  else
863  parent_rel->partial_pathlist =
864  lcons(new_path, parent_rel->partial_pathlist);
865  }
866  else
867  {
868  /* Reject and recycle the new path */
869  pfree(new_path);
870  }
871 }
872 
873 /*
874  * add_partial_path_precheck
875  * Check whether a proposed new partial path could possibly get accepted.
876  *
877  * Unlike add_path_precheck, we can ignore startup cost and parameterization,
878  * since they don't matter for partial paths (see add_partial_path). But
879  * we do want to make sure we don't add a partial path if there's already
880  * a complete path that dominates it, since in that case the proposed path
881  * is surely a loser.
882  */
883 bool
884 add_partial_path_precheck(RelOptInfo *parent_rel, Cost total_cost,
885  List *pathkeys)
886 {
887  ListCell *p1;
888 
889  /*
890  * Our goal here is twofold. First, we want to find out whether this path
891  * is clearly inferior to some existing partial path. If so, we want to
892  * reject it immediately. Second, we want to find out whether this path
893  * is clearly superior to some existing partial path -- at least, modulo
894  * final cost computations. If so, we definitely want to consider it.
895  *
896  * Unlike add_path(), we always compare pathkeys here. This is because we
897  * expect partial_pathlist to be very short, and getting a definitive
898  * answer at this stage avoids the need to call add_path_precheck.
899  */
900  foreach(p1, parent_rel->partial_pathlist)
901  {
902  Path *old_path = (Path *) lfirst(p1);
903  PathKeysComparison keyscmp;
904 
905  keyscmp = compare_pathkeys(pathkeys, old_path->pathkeys);
906  if (keyscmp != PATHKEYS_DIFFERENT)
907  {
908  if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR &&
909  keyscmp != PATHKEYS_BETTER1)
910  return false;
911  if (old_path->total_cost > total_cost * STD_FUZZ_FACTOR &&
912  keyscmp != PATHKEYS_BETTER2)
913  return true;
914  }
915  }
916 
917  /*
918  * This path is neither clearly inferior to an existing partial path nor
919  * clearly good enough that it might replace one. Compare it to
920  * non-parallel plans. If it loses even before accounting for the cost of
921  * the Gather node, we should definitely reject it.
922  *
923  * Note that we pass the total_cost to add_path_precheck twice. This is
924  * because it's never advantageous to consider the startup cost of a
925  * partial path; the resulting plans, if run in parallel, will be run to
926  * completion.
927  */
928  if (!add_path_precheck(parent_rel, total_cost, total_cost, pathkeys,
929  NULL))
930  return false;
931 
932  return true;
933 }
934 
935 
936 /*****************************************************************************
937  * PATH NODE CREATION ROUTINES
938  *****************************************************************************/
939 
940 /*
941  * create_seqscan_path
942  * Creates a path corresponding to a sequential scan, returning the
943  * pathnode.
944  */
945 Path *
947  Relids required_outer, int parallel_workers)
948 {
949  Path *pathnode = makeNode(Path);
950 
951  pathnode->pathtype = T_SeqScan;
952  pathnode->parent = rel;
953  pathnode->pathtarget = rel->reltarget;
954  pathnode->param_info = get_baserel_parampathinfo(root, rel,
955  required_outer);
956  pathnode->parallel_aware = parallel_workers > 0 ? true : false;
957  pathnode->parallel_safe = rel->consider_parallel;
958  pathnode->parallel_workers = parallel_workers;
959  pathnode->pathkeys = NIL; /* seqscan has unordered result */
960 
961  cost_seqscan(pathnode, root, rel, pathnode->param_info);
962 
963  return pathnode;
964 }
965 
966 /*
967  * create_samplescan_path
968  * Creates a path node for a sampled table scan.
969  */
970 Path *
972 {
973  Path *pathnode = makeNode(Path);
974 
975  pathnode->pathtype = T_SampleScan;
976  pathnode->parent = rel;
977  pathnode->pathtarget = rel->reltarget;
978  pathnode->param_info = get_baserel_parampathinfo(root, rel,
979  required_outer);
980  pathnode->parallel_aware = false;
981  pathnode->parallel_safe = rel->consider_parallel;
982  pathnode->parallel_workers = 0;
983  pathnode->pathkeys = NIL; /* samplescan has unordered result */
984 
985  cost_samplescan(pathnode, root, rel, pathnode->param_info);
986 
987  return pathnode;
988 }
989 
990 /*
991  * create_index_path
992  * Creates a path node for an index scan.
993  *
994  * 'index' is a usable index.
995  * 'indexclauses' is a list of RestrictInfo nodes representing clauses
996  * to be used as index qual conditions in the scan.
997  * 'indexclausecols' is an integer list of index column numbers (zero based)
998  * the indexclauses can be used with.
999  * 'indexorderbys' is a list of bare expressions (no RestrictInfos)
1000  * to be used as index ordering operators in the scan.
1001  * 'indexorderbycols' is an integer list of index column numbers (zero based)
1002  * the ordering operators can be used with.
1003  * 'pathkeys' describes the ordering of the path.
1004  * 'indexscandir' is ForwardScanDirection or BackwardScanDirection
1005  * for an ordered index, or NoMovementScanDirection for
1006  * an unordered index.
1007  * 'indexonly' is true if an index-only scan is wanted.
1008  * 'required_outer' is the set of outer relids for a parameterized path.
1009  * 'loop_count' is the number of repetitions of the indexscan to factor into
1010  * estimates of caching behavior.
1011  * 'partial_path' is true if constructing a parallel index scan path.
1012  *
1013  * Returns the new path node.
1014  */
1015 IndexPath *
1018  List *indexclauses,
1019  List *indexclausecols,
1020  List *indexorderbys,
1021  List *indexorderbycols,
1022  List *pathkeys,
1023  ScanDirection indexscandir,
1024  bool indexonly,
1025  Relids required_outer,
1026  double loop_count,
1027  bool partial_path)
1028 {
1029  IndexPath *pathnode = makeNode(IndexPath);
1030  RelOptInfo *rel = index->rel;
1031  List *indexquals,
1032  *indexqualcols;
1033 
1034  pathnode->path.pathtype = indexonly ? T_IndexOnlyScan : T_IndexScan;
1035  pathnode->path.parent = rel;
1036  pathnode->path.pathtarget = rel->reltarget;
1037  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1038  required_outer);
1039  pathnode->path.parallel_aware = false;
1040  pathnode->path.parallel_safe = rel->consider_parallel;
1041  pathnode->path.parallel_workers = 0;
1042  pathnode->path.pathkeys = pathkeys;
1043 
1044  /* Convert clauses to indexquals the executor can handle */
1045  expand_indexqual_conditions(index, indexclauses, indexclausecols,
1046  &indexquals, &indexqualcols);
1047 
1048  /* Fill in the pathnode */
1049  pathnode->indexinfo = index;
1050  pathnode->indexclauses = indexclauses;
1051  pathnode->indexquals = indexquals;
1052  pathnode->indexqualcols = indexqualcols;
1053  pathnode->indexorderbys = indexorderbys;
1054  pathnode->indexorderbycols = indexorderbycols;
1055  pathnode->indexscandir = indexscandir;
1056 
1057  cost_index(pathnode, root, loop_count, partial_path);
1058 
1059  return pathnode;
1060 }
1061 
1062 /*
1063  * create_bitmap_heap_path
1064  * Creates a path node for a bitmap scan.
1065  *
1066  * 'bitmapqual' is a tree of IndexPath, BitmapAndPath, and BitmapOrPath nodes.
1067  * 'required_outer' is the set of outer relids for a parameterized path.
1068  * 'loop_count' is the number of repetitions of the indexscan to factor into
1069  * estimates of caching behavior.
1070  *
1071  * loop_count should match the value used when creating the component
1072  * IndexPaths.
1073  */
1076  RelOptInfo *rel,
1077  Path *bitmapqual,
1078  Relids required_outer,
1079  double loop_count,
1080  int parallel_degree)
1081 {
1082  BitmapHeapPath *pathnode = makeNode(BitmapHeapPath);
1083 
1084  pathnode->path.pathtype = T_BitmapHeapScan;
1085  pathnode->path.parent = rel;
1086  pathnode->path.pathtarget = rel->reltarget;
1087  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1088  required_outer);
1089  pathnode->path.parallel_aware = parallel_degree > 0 ? true : false;
1090  pathnode->path.parallel_safe = rel->consider_parallel;
1091  pathnode->path.parallel_workers = parallel_degree;
1092  pathnode->path.pathkeys = NIL; /* always unordered */
1093 
1094  pathnode->bitmapqual = bitmapqual;
1095 
1096  cost_bitmap_heap_scan(&pathnode->path, root, rel,
1097  pathnode->path.param_info,
1098  bitmapqual, loop_count);
1099 
1100  return pathnode;
1101 }
1102 
1103 /*
1104  * create_bitmap_and_path
1105  * Creates a path node representing a BitmapAnd.
1106  */
1107 BitmapAndPath *
1109  RelOptInfo *rel,
1110  List *bitmapquals)
1111 {
1112  BitmapAndPath *pathnode = makeNode(BitmapAndPath);
1113 
1114  pathnode->path.pathtype = T_BitmapAnd;
1115  pathnode->path.parent = rel;
1116  pathnode->path.pathtarget = rel->reltarget;
1117  pathnode->path.param_info = NULL; /* not used in bitmap trees */
1118 
1119  /*
1120  * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1121  * parallel-safe if and only if rel->consider_parallel is set. So, we can
1122  * set the flag for this path based only on the relation-level flag,
1123  * without actually iterating over the list of children.
1124  */
1125  pathnode->path.parallel_aware = false;
1126  pathnode->path.parallel_safe = rel->consider_parallel;
1127  pathnode->path.parallel_workers = 0;
1128 
1129  pathnode->path.pathkeys = NIL; /* always unordered */
1130 
1131  pathnode->bitmapquals = bitmapquals;
1132 
1133  /* this sets bitmapselectivity as well as the regular cost fields: */
1134  cost_bitmap_and_node(pathnode, root);
1135 
1136  return pathnode;
1137 }
1138 
1139 /*
1140  * create_bitmap_or_path
1141  * Creates a path node representing a BitmapOr.
1142  */
1143 BitmapOrPath *
1145  RelOptInfo *rel,
1146  List *bitmapquals)
1147 {
1148  BitmapOrPath *pathnode = makeNode(BitmapOrPath);
1149 
1150  pathnode->path.pathtype = T_BitmapOr;
1151  pathnode->path.parent = rel;
1152  pathnode->path.pathtarget = rel->reltarget;
1153  pathnode->path.param_info = NULL; /* not used in bitmap trees */
1154 
1155  /*
1156  * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1157  * parallel-safe if and only if rel->consider_parallel is set. So, we can
1158  * set the flag for this path based only on the relation-level flag,
1159  * without actually iterating over the list of children.
1160  */
1161  pathnode->path.parallel_aware = false;
1162  pathnode->path.parallel_safe = rel->consider_parallel;
1163  pathnode->path.parallel_workers = 0;
1164 
1165  pathnode->path.pathkeys = NIL; /* always unordered */
1166 
1167  pathnode->bitmapquals = bitmapquals;
1168 
1169  /* this sets bitmapselectivity as well as the regular cost fields: */
1170  cost_bitmap_or_node(pathnode, root);
1171 
1172  return pathnode;
1173 }
1174 
1175 /*
1176  * create_tidscan_path
1177  * Creates a path corresponding to a scan by TID, returning the pathnode.
1178  */
1179 TidPath *
1181  Relids required_outer)
1182 {
1183  TidPath *pathnode = makeNode(TidPath);
1184 
1185  pathnode->path.pathtype = T_TidScan;
1186  pathnode->path.parent = rel;
1187  pathnode->path.pathtarget = rel->reltarget;
1188  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1189  required_outer);
1190  pathnode->path.parallel_aware = false;
1191  pathnode->path.parallel_safe = rel->consider_parallel;
1192  pathnode->path.parallel_workers = 0;
1193  pathnode->path.pathkeys = NIL; /* always unordered */
1194 
1195  pathnode->tidquals = tidquals;
1196 
1197  cost_tidscan(&pathnode->path, root, rel, tidquals,
1198  pathnode->path.param_info);
1199 
1200  return pathnode;
1201 }
1202 
1203 /*
1204  * create_append_path
1205  * Creates a path corresponding to an Append plan, returning the
1206  * pathnode.
1207  *
1208  * Note that we must handle subpaths = NIL, representing a dummy access path.
1209  */
1210 AppendPath *
1211 create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer,
1212  int parallel_workers, List *partitioned_rels)
1213 {
1214  AppendPath *pathnode = makeNode(AppendPath);
1215  ListCell *l;
1216 
1217  pathnode->path.pathtype = T_Append;
1218  pathnode->path.parent = rel;
1219  pathnode->path.pathtarget = rel->reltarget;
1221  required_outer);
1222  pathnode->path.parallel_aware = false;
1223  pathnode->path.parallel_safe = rel->consider_parallel;
1224  pathnode->path.parallel_workers = parallel_workers;
1225  pathnode->path.pathkeys = NIL; /* result is always considered unsorted */
1226  pathnode->partitioned_rels = list_copy(partitioned_rels);
1227  pathnode->subpaths = subpaths;
1228 
1229  /*
1230  * We don't bother with inventing a cost_append(), but just do it here.
1231  *
1232  * Compute rows and costs as sums of subplan rows and costs. We charge
1233  * nothing extra for the Append itself, which perhaps is too optimistic,
1234  * but since it doesn't do any selection or projection, it is a pretty
1235  * cheap node.
1236  */
1237  pathnode->path.rows = 0;
1238  pathnode->path.startup_cost = 0;
1239  pathnode->path.total_cost = 0;
1240  foreach(l, subpaths)
1241  {
1242  Path *subpath = (Path *) lfirst(l);
1243 
1244  pathnode->path.rows += subpath->rows;
1245 
1246  if (l == list_head(subpaths)) /* first node? */
1247  pathnode->path.startup_cost = subpath->startup_cost;
1248  pathnode->path.total_cost += subpath->total_cost;
1249  pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1250  subpath->parallel_safe;
1251 
1252  /* All child paths must have same parameterization */
1253  Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1254  }
1255 
1256  return pathnode;
1257 }
1258 
1259 /*
1260  * create_merge_append_path
1261  * Creates a path corresponding to a MergeAppend plan, returning the
1262  * pathnode.
1263  */
1266  RelOptInfo *rel,
1267  List *subpaths,
1268  List *pathkeys,
1269  Relids required_outer,
1270  List *partitioned_rels)
1271 {
1273  Cost input_startup_cost;
1274  Cost input_total_cost;
1275  ListCell *l;
1276 
1277  pathnode->path.pathtype = T_MergeAppend;
1278  pathnode->path.parent = rel;
1279  pathnode->path.pathtarget = rel->reltarget;
1281  required_outer);
1282  pathnode->path.parallel_aware = false;
1283  pathnode->path.parallel_safe = rel->consider_parallel;
1284  pathnode->path.parallel_workers = 0;
1285  pathnode->path.pathkeys = pathkeys;
1286  pathnode->partitioned_rels = list_copy(partitioned_rels);
1287  pathnode->subpaths = subpaths;
1288 
1289  /*
1290  * Apply query-wide LIMIT if known and path is for sole base relation.
1291  * (Handling this at this low level is a bit klugy.)
1292  */
1293  if (bms_equal(rel->relids, root->all_baserels))
1294  pathnode->limit_tuples = root->limit_tuples;
1295  else
1296  pathnode->limit_tuples = -1.0;
1297 
1298  /*
1299  * Add up the sizes and costs of the input paths.
1300  */
1301  pathnode->path.rows = 0;
1302  input_startup_cost = 0;
1303  input_total_cost = 0;
1304  foreach(l, subpaths)
1305  {
1306  Path *subpath = (Path *) lfirst(l);
1307 
1308  pathnode->path.rows += subpath->rows;
1309  pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1310  subpath->parallel_safe;
1311 
1312  if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1313  {
1314  /* Subpath is adequately ordered, we won't need to sort it */
1315  input_startup_cost += subpath->startup_cost;
1316  input_total_cost += subpath->total_cost;
1317  }
1318  else
1319  {
1320  /* We'll need to insert a Sort node, so include cost for that */
1321  Path sort_path; /* dummy for result of cost_sort */
1322 
1323  cost_sort(&sort_path,
1324  root,
1325  pathkeys,
1326  subpath->total_cost,
1327  subpath->parent->tuples,
1328  subpath->pathtarget->width,
1329  0.0,
1330  work_mem,
1331  pathnode->limit_tuples);
1332  input_startup_cost += sort_path.startup_cost;
1333  input_total_cost += sort_path.total_cost;
1334  }
1335 
1336  /* All child paths must have same parameterization */
1337  Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1338  }
1339 
1340  /* Now we can compute total costs of the MergeAppend */
1341  cost_merge_append(&pathnode->path, root,
1342  pathkeys, list_length(subpaths),
1343  input_startup_cost, input_total_cost,
1344  pathnode->path.rows);
1345 
1346  return pathnode;
1347 }
1348 
1349 /*
1350  * create_result_path
1351  * Creates a path representing a Result-and-nothing-else plan.
1352  *
1353  * This is only used for degenerate cases, such as a query with an empty
1354  * jointree.
1355  */
1356 ResultPath *
1358  PathTarget *target, List *resconstantqual)
1359 {
1360  ResultPath *pathnode = makeNode(ResultPath);
1361 
1362  pathnode->path.pathtype = T_Result;
1363  pathnode->path.parent = rel;
1364  pathnode->path.pathtarget = target;
1365  pathnode->path.param_info = NULL; /* there are no other rels... */
1366  pathnode->path.parallel_aware = false;
1367  pathnode->path.parallel_safe = rel->consider_parallel;
1368  pathnode->path.parallel_workers = 0;
1369  pathnode->path.pathkeys = NIL;
1370  pathnode->quals = resconstantqual;
1371 
1372  /* Hardly worth defining a cost_result() function ... just do it */
1373  pathnode->path.rows = 1;
1374  pathnode->path.startup_cost = target->cost.startup;
1375  pathnode->path.total_cost = target->cost.startup +
1376  cpu_tuple_cost + target->cost.per_tuple;
1377 
1378  /*
1379  * Add cost of qual, if any --- but we ignore its selectivity, since our
1380  * rowcount estimate should be 1 no matter what the qual is.
1381  */
1382  if (resconstantqual)
1383  {
1384  QualCost qual_cost;
1385 
1386  cost_qual_eval(&qual_cost, resconstantqual, root);
1387  /* resconstantqual is evaluated once at startup */
1388  pathnode->path.startup_cost += qual_cost.startup + qual_cost.per_tuple;
1389  pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
1390  }
1391 
1392  return pathnode;
1393 }
1394 
1395 /*
1396  * create_material_path
1397  * Creates a path corresponding to a Material plan, returning the
1398  * pathnode.
1399  */
1400 MaterialPath *
1402 {
1403  MaterialPath *pathnode = makeNode(MaterialPath);
1404 
1405  Assert(subpath->parent == rel);
1406 
1407  pathnode->path.pathtype = T_Material;
1408  pathnode->path.parent = rel;
1409  pathnode->path.pathtarget = rel->reltarget;
1410  pathnode->path.param_info = subpath->param_info;
1411  pathnode->path.parallel_aware = false;
1412  pathnode->path.parallel_safe = rel->consider_parallel &&
1413  subpath->parallel_safe;
1414  pathnode->path.parallel_workers = subpath->parallel_workers;
1415  pathnode->path.pathkeys = subpath->pathkeys;
1416 
1417  pathnode->subpath = subpath;
1418 
1419  cost_material(&pathnode->path,
1420  subpath->startup_cost,
1421  subpath->total_cost,
1422  subpath->rows,
1423  subpath->pathtarget->width);
1424 
1425  return pathnode;
1426 }
1427 
1428 /*
1429  * create_unique_path
1430  * Creates a path representing elimination of distinct rows from the
1431  * input data. Distinct-ness is defined according to the needs of the
1432  * semijoin represented by sjinfo. If it is not possible to identify
1433  * how to make the data unique, NULL is returned.
1434  *
1435  * If used at all, this is likely to be called repeatedly on the same rel;
1436  * and the input subpath should always be the same (the cheapest_total path
1437  * for the rel). So we cache the result.
1438  */
1439 UniquePath *
1441  SpecialJoinInfo *sjinfo)
1442 {
1443  UniquePath *pathnode;
1444  Path sort_path; /* dummy for result of cost_sort */
1445  Path agg_path; /* dummy for result of cost_agg */
1446  MemoryContext oldcontext;
1447  int numCols;
1448 
1449  /* Caller made a mistake if subpath isn't cheapest_total ... */
1450  Assert(subpath == rel->cheapest_total_path);
1451  Assert(subpath->parent == rel);
1452  /* ... or if SpecialJoinInfo is the wrong one */
1453  Assert(sjinfo->jointype == JOIN_SEMI);
1454  Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
1455 
1456  /* If result already cached, return it */
1457  if (rel->cheapest_unique_path)
1458  return (UniquePath *) rel->cheapest_unique_path;
1459 
1460  /* If it's not possible to unique-ify, return NULL */
1461  if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
1462  return NULL;
1463 
1464  /*
1465  * We must ensure path struct and subsidiary data are allocated in main
1466  * planning context; otherwise GEQO memory management causes trouble.
1467  */
1468  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1469 
1470  pathnode = makeNode(UniquePath);
1471 
1472  pathnode->path.pathtype = T_Unique;
1473  pathnode->path.parent = rel;
1474  pathnode->path.pathtarget = rel->reltarget;
1475  pathnode->path.param_info = subpath->param_info;
1476  pathnode->path.parallel_aware = false;
1477  pathnode->path.parallel_safe = rel->consider_parallel &&
1478  subpath->parallel_safe;
1479  pathnode->path.parallel_workers = subpath->parallel_workers;
1480 
1481  /*
1482  * Assume the output is unsorted, since we don't necessarily have pathkeys
1483  * to represent it. (This might get overridden below.)
1484  */
1485  pathnode->path.pathkeys = NIL;
1486 
1487  pathnode->subpath = subpath;
1488  pathnode->in_operators = sjinfo->semi_operators;
1489  pathnode->uniq_exprs = sjinfo->semi_rhs_exprs;
1490 
1491  /*
1492  * If the input is a relation and it has a unique index that proves the
1493  * semi_rhs_exprs are unique, then we don't need to do anything. Note
1494  * that relation_has_unique_index_for automatically considers restriction
1495  * clauses for the rel, as well.
1496  */
1497  if (rel->rtekind == RTE_RELATION && sjinfo->semi_can_btree &&
1499  sjinfo->semi_rhs_exprs,
1500  sjinfo->semi_operators))
1501  {
1502  pathnode->umethod = UNIQUE_PATH_NOOP;
1503  pathnode->path.rows = rel->rows;
1504  pathnode->path.startup_cost = subpath->startup_cost;
1505  pathnode->path.total_cost = subpath->total_cost;
1506  pathnode->path.pathkeys = subpath->pathkeys;
1507 
1508  rel->cheapest_unique_path = (Path *) pathnode;
1509 
1510  MemoryContextSwitchTo(oldcontext);
1511 
1512  return pathnode;
1513  }
1514 
1515  /*
1516  * If the input is a subquery whose output must be unique already, then we
1517  * don't need to do anything. The test for uniqueness has to consider
1518  * exactly which columns we are extracting; for example "SELECT DISTINCT
1519  * x,y" doesn't guarantee that x alone is distinct. So we cannot check for
1520  * this optimization unless semi_rhs_exprs consists only of simple Vars
1521  * referencing subquery outputs. (Possibly we could do something with
1522  * expressions in the subquery outputs, too, but for now keep it simple.)
1523  */
1524  if (rel->rtekind == RTE_SUBQUERY)
1525  {
1526  RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1527 
1529  {
1530  List *sub_tlist_colnos;
1531 
1532  sub_tlist_colnos = translate_sub_tlist(sjinfo->semi_rhs_exprs,
1533  rel->relid);
1534 
1535  if (sub_tlist_colnos &&
1537  sub_tlist_colnos,
1538  sjinfo->semi_operators))
1539  {
1540  pathnode->umethod = UNIQUE_PATH_NOOP;
1541  pathnode->path.rows = rel->rows;
1542  pathnode->path.startup_cost = subpath->startup_cost;
1543  pathnode->path.total_cost = subpath->total_cost;
1544  pathnode->path.pathkeys = subpath->pathkeys;
1545 
1546  rel->cheapest_unique_path = (Path *) pathnode;
1547 
1548  MemoryContextSwitchTo(oldcontext);
1549 
1550  return pathnode;
1551  }
1552  }
1553  }
1554 
1555  /* Estimate number of output rows */
1556  pathnode->path.rows = estimate_num_groups(root,
1557  sjinfo->semi_rhs_exprs,
1558  rel->rows,
1559  NULL);
1560  numCols = list_length(sjinfo->semi_rhs_exprs);
1561 
1562  if (sjinfo->semi_can_btree)
1563  {
1564  /*
1565  * Estimate cost for sort+unique implementation
1566  */
1567  cost_sort(&sort_path, root, NIL,
1568  subpath->total_cost,
1569  rel->rows,
1570  subpath->pathtarget->width,
1571  0.0,
1572  work_mem,
1573  -1.0);
1574 
1575  /*
1576  * Charge one cpu_operator_cost per comparison per input tuple. We
1577  * assume all columns get compared at most of the tuples. (XXX
1578  * probably this is an overestimate.) This should agree with
1579  * create_upper_unique_path.
1580  */
1581  sort_path.total_cost += cpu_operator_cost * rel->rows * numCols;
1582  }
1583 
1584  if (sjinfo->semi_can_hash)
1585  {
1586  /*
1587  * Estimate the overhead per hashtable entry at 64 bytes (same as in
1588  * planner.c).
1589  */
1590  int hashentrysize = subpath->pathtarget->width + 64;
1591 
1592  if (hashentrysize * pathnode->path.rows > work_mem * 1024L)
1593  {
1594  /*
1595  * We should not try to hash. Hack the SpecialJoinInfo to
1596  * remember this, in case we come through here again.
1597  */
1598  sjinfo->semi_can_hash = false;
1599  }
1600  else
1601  cost_agg(&agg_path, root,
1602  AGG_HASHED, NULL,
1603  numCols, pathnode->path.rows,
1604  NIL,
1605  subpath->startup_cost,
1606  subpath->total_cost,
1607  rel->rows);
1608  }
1609 
1610  if (sjinfo->semi_can_btree && sjinfo->semi_can_hash)
1611  {
1612  if (agg_path.total_cost < sort_path.total_cost)
1613  pathnode->umethod = UNIQUE_PATH_HASH;
1614  else
1615  pathnode->umethod = UNIQUE_PATH_SORT;
1616  }
1617  else if (sjinfo->semi_can_btree)
1618  pathnode->umethod = UNIQUE_PATH_SORT;
1619  else if (sjinfo->semi_can_hash)
1620  pathnode->umethod = UNIQUE_PATH_HASH;
1621  else
1622  {
1623  /* we can get here only if we abandoned hashing above */
1624  MemoryContextSwitchTo(oldcontext);
1625  return NULL;
1626  }
1627 
1628  if (pathnode->umethod == UNIQUE_PATH_HASH)
1629  {
1630  pathnode->path.startup_cost = agg_path.startup_cost;
1631  pathnode->path.total_cost = agg_path.total_cost;
1632  }
1633  else
1634  {
1635  pathnode->path.startup_cost = sort_path.startup_cost;
1636  pathnode->path.total_cost = sort_path.total_cost;
1637  }
1638 
1639  rel->cheapest_unique_path = (Path *) pathnode;
1640 
1641  MemoryContextSwitchTo(oldcontext);
1642 
1643  return pathnode;
1644 }
1645 
1646 /*
1647  * create_gather_merge_path
1648  *
1649  * Creates a path corresponding to a gather merge scan, returning
1650  * the pathnode.
1651  */
1654  PathTarget *target, List *pathkeys,
1655  Relids required_outer, double *rows)
1656 {
1658  Cost input_startup_cost = 0;
1659  Cost input_total_cost = 0;
1660 
1661  Assert(subpath->parallel_safe);
1662  Assert(pathkeys);
1663 
1664  pathnode->path.pathtype = T_GatherMerge;
1665  pathnode->path.parent = rel;
1666  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1667  required_outer);
1668  pathnode->path.parallel_aware = false;
1669 
1670  pathnode->subpath = subpath;
1671  pathnode->num_workers = subpath->parallel_workers;
1672  pathnode->path.pathkeys = pathkeys;
1673  pathnode->path.pathtarget = target ? target : rel->reltarget;
1674  pathnode->path.rows += subpath->rows;
1675 
1676  if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1677  {
1678  /* Subpath is adequately ordered, we won't need to sort it */
1679  input_startup_cost += subpath->startup_cost;
1680  input_total_cost += subpath->total_cost;
1681  }
1682  else
1683  {
1684  /* We'll need to insert a Sort node, so include cost for that */
1685  Path sort_path; /* dummy for result of cost_sort */
1686 
1687  cost_sort(&sort_path,
1688  root,
1689  pathkeys,
1690  subpath->total_cost,
1691  subpath->rows,
1692  subpath->pathtarget->width,
1693  0.0,
1694  work_mem,
1695  -1);
1696  input_startup_cost += sort_path.startup_cost;
1697  input_total_cost += sort_path.total_cost;
1698  }
1699 
1700  cost_gather_merge(pathnode, root, rel, pathnode->path.param_info,
1701  input_startup_cost, input_total_cost, rows);
1702 
1703  return pathnode;
1704 }
1705 
1706 /*
1707  * translate_sub_tlist - get subquery column numbers represented by tlist
1708  *
1709  * The given targetlist usually contains only Vars referencing the given relid.
1710  * Extract their varattnos (ie, the column numbers of the subquery) and return
1711  * as an integer List.
1712  *
1713  * If any of the tlist items is not a simple Var, we cannot determine whether
1714  * the subquery's uniqueness condition (if any) matches ours, so punt and
1715  * return NIL.
1716  */
1717 static List *
1718 translate_sub_tlist(List *tlist, int relid)
1719 {
1720  List *result = NIL;
1721  ListCell *l;
1722 
1723  foreach(l, tlist)
1724  {
1725  Var *var = (Var *) lfirst(l);
1726 
1727  if (!var || !IsA(var, Var) ||
1728  var->varno != relid)
1729  return NIL; /* punt */
1730 
1731  result = lappend_int(result, var->varattno);
1732  }
1733  return result;
1734 }
1735 
1736 /*
1737  * create_gather_path
1738  * Creates a path corresponding to a gather scan, returning the
1739  * pathnode.
1740  *
1741  * 'rows' may optionally be set to override row estimates from other sources.
1742  */
1743 GatherPath *
1745  PathTarget *target, Relids required_outer, double *rows)
1746 {
1747  GatherPath *pathnode = makeNode(GatherPath);
1748 
1749  Assert(subpath->parallel_safe);
1750 
1751  pathnode->path.pathtype = T_Gather;
1752  pathnode->path.parent = rel;
1753  pathnode->path.pathtarget = target;
1754  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1755  required_outer);
1756  pathnode->path.parallel_aware = false;
1757  pathnode->path.parallel_safe = false;
1758  pathnode->path.parallel_workers = 0;
1759  pathnode->path.pathkeys = NIL; /* Gather has unordered result */
1760 
1761  pathnode->subpath = subpath;
1762  pathnode->num_workers = subpath->parallel_workers;
1763  pathnode->single_copy = false;
1764 
1765  if (pathnode->num_workers == 0)
1766  {
1767  pathnode->path.pathkeys = subpath->pathkeys;
1768  pathnode->num_workers = 1;
1769  pathnode->single_copy = true;
1770  }
1771 
1772  cost_gather(pathnode, root, rel, pathnode->path.param_info, rows);
1773 
1774  return pathnode;
1775 }
1776 
1777 /*
1778  * create_subqueryscan_path
1779  * Creates a path corresponding to a scan of a subquery,
1780  * returning the pathnode.
1781  */
1784  List *pathkeys, Relids required_outer)
1785 {
1787 
1788  pathnode->path.pathtype = T_SubqueryScan;
1789  pathnode->path.parent = rel;
1790  pathnode->path.pathtarget = rel->reltarget;
1791  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1792  required_outer);
1793  pathnode->path.parallel_aware = false;
1794  pathnode->path.parallel_safe = rel->consider_parallel &&
1795  subpath->parallel_safe;
1796  pathnode->path.parallel_workers = subpath->parallel_workers;
1797  pathnode->path.pathkeys = pathkeys;
1798  pathnode->subpath = subpath;
1799 
1800  cost_subqueryscan(pathnode, root, rel, pathnode->path.param_info);
1801 
1802  return pathnode;
1803 }
1804 
1805 /*
1806  * create_functionscan_path
1807  * Creates a path corresponding to a sequential scan of a function,
1808  * returning the pathnode.
1809  */
1810 Path *
1812  List *pathkeys, Relids required_outer)
1813 {
1814  Path *pathnode = makeNode(Path);
1815 
1816  pathnode->pathtype = T_FunctionScan;
1817  pathnode->parent = rel;
1818  pathnode->pathtarget = rel->reltarget;
1819  pathnode->param_info = get_baserel_parampathinfo(root, rel,
1820  required_outer);
1821  pathnode->parallel_aware = false;
1822  pathnode->parallel_safe = rel->consider_parallel;
1823  pathnode->parallel_workers = 0;
1824  pathnode->pathkeys = pathkeys;
1825 
1826  cost_functionscan(pathnode, root, rel, pathnode->param_info);
1827 
1828  return pathnode;
1829 }
1830 
1831 /*
1832  * create_tablefuncscan_path
1833  * Creates a path corresponding to a sequential scan of a table function,
1834  * returning the pathnode.
1835  */
1836 Path *
1838  Relids required_outer)
1839 {
1840  Path *pathnode = makeNode(Path);
1841 
1842  pathnode->pathtype = T_TableFuncScan;
1843  pathnode->parent = rel;
1844  pathnode->pathtarget = rel->reltarget;
1845  pathnode->param_info = get_baserel_parampathinfo(root, rel,
1846  required_outer);
1847  pathnode->parallel_aware = false;
1848  pathnode->parallel_safe = rel->consider_parallel;
1849  pathnode->parallel_workers = 0;
1850  pathnode->pathkeys = NIL; /* result is always unordered */
1851 
1852  cost_tablefuncscan(pathnode, root, rel, pathnode->param_info);
1853 
1854  return pathnode;
1855 }
1856 
1857 /*
1858  * create_valuesscan_path
1859  * Creates a path corresponding to a scan of a VALUES list,
1860  * returning the pathnode.
1861  */
1862 Path *
1864  Relids required_outer)
1865 {
1866  Path *pathnode = makeNode(Path);
1867 
1868  pathnode->pathtype = T_ValuesScan;
1869  pathnode->parent = rel;
1870  pathnode->pathtarget = rel->reltarget;
1871  pathnode->param_info = get_baserel_parampathinfo(root, rel,
1872  required_outer);
1873  pathnode->parallel_aware = false;
1874  pathnode->parallel_safe = rel->consider_parallel;
1875  pathnode->parallel_workers = 0;
1876  pathnode->pathkeys = NIL; /* result is always unordered */
1877 
1878  cost_valuesscan(pathnode, root, rel, pathnode->param_info);
1879 
1880  return pathnode;
1881 }
1882 
1883 /*
1884  * create_ctescan_path
1885  * Creates a path corresponding to a scan of a non-self-reference CTE,
1886  * returning the pathnode.
1887  */
1888 Path *
1889 create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
1890 {
1891  Path *pathnode = makeNode(Path);
1892 
1893  pathnode->pathtype = T_CteScan;
1894  pathnode->parent = rel;
1895  pathnode->pathtarget = rel->reltarget;
1896  pathnode->param_info = get_baserel_parampathinfo(root, rel,
1897  required_outer);
1898  pathnode->parallel_aware = false;
1899  pathnode->parallel_safe = rel->consider_parallel;
1900  pathnode->parallel_workers = 0;
1901  pathnode->pathkeys = NIL; /* XXX for now, result is always unordered */
1902 
1903  cost_ctescan(pathnode, root, rel, pathnode->param_info);
1904 
1905  return pathnode;
1906 }
1907 
1908 /*
1909  * create_namedtuplestorescan_path
1910  * Creates a path corresponding to a scan of a named tuplestore, returning
1911  * the pathnode.
1912  */
1913 Path *
1915  Relids required_outer)
1916 {
1917  Path *pathnode = makeNode(Path);
1918 
1919  pathnode->pathtype = T_NamedTuplestoreScan;
1920  pathnode->parent = rel;
1921  pathnode->pathtarget = rel->reltarget;
1922  pathnode->param_info = get_baserel_parampathinfo(root, rel,
1923  required_outer);
1924  pathnode->parallel_aware = false;
1925  pathnode->parallel_safe = rel->consider_parallel;
1926  pathnode->parallel_workers = 0;
1927  pathnode->pathkeys = NIL; /* result is always unordered */
1928 
1929  cost_namedtuplestorescan(pathnode, root, rel, pathnode->param_info);
1930 
1931  return pathnode;
1932 }
1933 
1934 /*
1935  * create_worktablescan_path
1936  * Creates a path corresponding to a scan of a self-reference CTE,
1937  * returning the pathnode.
1938  */
1939 Path *
1941  Relids required_outer)
1942 {
1943  Path *pathnode = makeNode(Path);
1944 
1945  pathnode->pathtype = T_WorkTableScan;
1946  pathnode->parent = rel;
1947  pathnode->pathtarget = rel->reltarget;
1948  pathnode->param_info = get_baserel_parampathinfo(root, rel,
1949  required_outer);
1950  pathnode->parallel_aware = false;
1951  pathnode->parallel_safe = rel->consider_parallel;
1952  pathnode->parallel_workers = 0;
1953  pathnode->pathkeys = NIL; /* result is always unordered */
1954 
1955  /* Cost is the same as for a regular CTE scan */
1956  cost_ctescan(pathnode, root, rel, pathnode->param_info);
1957 
1958  return pathnode;
1959 }
1960 
1961 /*
1962  * create_foreignscan_path
1963  * Creates a path corresponding to a scan of a foreign table, foreign join,
1964  * or foreign upper-relation processing, returning the pathnode.
1965  *
1966  * This function is never called from core Postgres; rather, it's expected
1967  * to be called by the GetForeignPaths, GetForeignJoinPaths, or
1968  * GetForeignUpperPaths function of a foreign data wrapper. We make the FDW
1969  * supply all fields of the path, since we do not have any way to calculate
1970  * them in core. However, there is a usually-sane default for the pathtarget
1971  * (rel->reltarget), so we let a NULL for "target" select that.
1972  */
1973 ForeignPath *
1975  PathTarget *target,
1976  double rows, Cost startup_cost, Cost total_cost,
1977  List *pathkeys,
1978  Relids required_outer,
1979  Path *fdw_outerpath,
1980  List *fdw_private)
1981 {
1982  ForeignPath *pathnode = makeNode(ForeignPath);
1983 
1984  pathnode->path.pathtype = T_ForeignScan;
1985  pathnode->path.parent = rel;
1986  pathnode->path.pathtarget = target ? target : rel->reltarget;
1987  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1988  required_outer);
1989  pathnode->path.parallel_aware = false;
1990  pathnode->path.parallel_safe = rel->consider_parallel;
1991  pathnode->path.parallel_workers = 0;
1992  pathnode->path.rows = rows;
1993  pathnode->path.startup_cost = startup_cost;
1994  pathnode->path.total_cost = total_cost;
1995  pathnode->path.pathkeys = pathkeys;
1996 
1997  pathnode->fdw_outerpath = fdw_outerpath;
1998  pathnode->fdw_private = fdw_private;
1999 
2000  return pathnode;
2001 }
2002 
2003 /*
2004  * calc_nestloop_required_outer
2005  * Compute the required_outer set for a nestloop join path
2006  *
2007  * Note: result must not share storage with either input
2008  */
2009 Relids
2011  Relids outer_paramrels,
2012  Relids innerrelids,
2013  Relids inner_paramrels)
2014 {
2015  Relids required_outer;
2016 
2017  /* inner_path can require rels from outer path, but not vice versa */
2018  Assert(!bms_overlap(outer_paramrels, innerrelids));
2019  /* easy case if inner path is not parameterized */
2020  if (!inner_paramrels)
2021  return bms_copy(outer_paramrels);
2022  /* else, form the union ... */
2023  required_outer = bms_union(outer_paramrels, inner_paramrels);
2024  /* ... and remove any mention of now-satisfied outer rels */
2025  required_outer = bms_del_members(required_outer,
2026  outerrelids);
2027  /* maintain invariant that required_outer is exactly NULL if empty */
2028  if (bms_is_empty(required_outer))
2029  {
2030  bms_free(required_outer);
2031  required_outer = NULL;
2032  }
2033  return required_outer;
2034 }
2035 
2036 /*
2037  * calc_non_nestloop_required_outer
2038  * Compute the required_outer set for a merge or hash join path
2039  *
2040  * Note: result must not share storage with either input
2041  */
2042 Relids
2043 calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
2044 {
2045  Relids outer_paramrels = PATH_REQ_OUTER(outer_path);
2046  Relids inner_paramrels = PATH_REQ_OUTER(inner_path);
2047  Relids required_outer;
2048 
2049  /* neither path can require rels from the other */
2050  Assert(!bms_overlap(outer_paramrels, inner_path->parent->relids));
2051  Assert(!bms_overlap(inner_paramrels, outer_path->parent->relids));
2052  /* form the union ... */
2053  required_outer = bms_union(outer_paramrels, inner_paramrels);
2054  /* we do not need an explicit test for empty; bms_union gets it right */
2055  return required_outer;
2056 }
2057 
2058 /*
2059  * create_nestloop_path
2060  * Creates a pathnode corresponding to a nestloop join between two
2061  * relations.
2062  *
2063  * 'joinrel' is the join relation.
2064  * 'jointype' is the type of join required
2065  * 'workspace' is the result from initial_cost_nestloop
2066  * 'extra' contains various information about the join
2067  * 'outer_path' is the outer path
2068  * 'inner_path' is the inner path
2069  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2070  * 'pathkeys' are the path keys of the new join path
2071  * 'required_outer' is the set of required outer rels
2072  *
2073  * Returns the resulting path node.
2074  */
2075 NestPath *
2077  RelOptInfo *joinrel,
2078  JoinType jointype,
2079  JoinCostWorkspace *workspace,
2080  JoinPathExtraData *extra,
2081  Path *outer_path,
2082  Path *inner_path,
2083  List *restrict_clauses,
2084  List *pathkeys,
2085  Relids required_outer)
2086 {
2087  NestPath *pathnode = makeNode(NestPath);
2088  Relids inner_req_outer = PATH_REQ_OUTER(inner_path);
2089 
2090  /*
2091  * If the inner path is parameterized by the outer, we must drop any
2092  * restrict_clauses that are due to be moved into the inner path. We have
2093  * to do this now, rather than postpone the work till createplan time,
2094  * because the restrict_clauses list can affect the size and cost
2095  * estimates for this path.
2096  */
2097  if (bms_overlap(inner_req_outer, outer_path->parent->relids))
2098  {
2099  Relids inner_and_outer = bms_union(inner_path->parent->relids,
2100  inner_req_outer);
2101  List *jclauses = NIL;
2102  ListCell *lc;
2103 
2104  foreach(lc, restrict_clauses)
2105  {
2106  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2107 
2108  if (!join_clause_is_movable_into(rinfo,
2109  inner_path->parent->relids,
2110  inner_and_outer))
2111  jclauses = lappend(jclauses, rinfo);
2112  }
2113  restrict_clauses = jclauses;
2114  }
2115 
2116  pathnode->path.pathtype = T_NestLoop;
2117  pathnode->path.parent = joinrel;
2118  pathnode->path.pathtarget = joinrel->reltarget;
2119  pathnode->path.param_info =
2121  joinrel,
2122  outer_path,
2123  inner_path,
2124  extra->sjinfo,
2125  required_outer,
2126  &restrict_clauses);
2127  pathnode->path.parallel_aware = false;
2128  pathnode->path.parallel_safe = joinrel->consider_parallel &&
2129  outer_path->parallel_safe && inner_path->parallel_safe;
2130  /* This is a foolish way to estimate parallel_workers, but for now... */
2131  pathnode->path.parallel_workers = outer_path->parallel_workers;
2132  pathnode->path.pathkeys = pathkeys;
2133  pathnode->jointype = jointype;
2134  pathnode->inner_unique = extra->inner_unique;
2135  pathnode->outerjoinpath = outer_path;
2136  pathnode->innerjoinpath = inner_path;
2137  pathnode->joinrestrictinfo = restrict_clauses;
2138 
2139  final_cost_nestloop(root, pathnode, workspace, extra);
2140 
2141  return pathnode;
2142 }
2143 
2144 /*
2145  * create_mergejoin_path
2146  * Creates a pathnode corresponding to a mergejoin join between
2147  * two relations
2148  *
2149  * 'joinrel' is the join relation
2150  * 'jointype' is the type of join required
2151  * 'workspace' is the result from initial_cost_mergejoin
2152  * 'extra' contains various information about the join
2153  * 'outer_path' is the outer path
2154  * 'inner_path' is the inner path
2155  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2156  * 'pathkeys' are the path keys of the new join path
2157  * 'required_outer' is the set of required outer rels
2158  * 'mergeclauses' are the RestrictInfo nodes to use as merge clauses
2159  * (this should be a subset of the restrict_clauses list)
2160  * 'outersortkeys' are the sort varkeys for the outer relation
2161  * 'innersortkeys' are the sort varkeys for the inner relation
2162  */
2163 MergePath *
2165  RelOptInfo *joinrel,
2166  JoinType jointype,
2167  JoinCostWorkspace *workspace,
2168  JoinPathExtraData *extra,
2169  Path *outer_path,
2170  Path *inner_path,
2171  List *restrict_clauses,
2172  List *pathkeys,
2173  Relids required_outer,
2174  List *mergeclauses,
2175  List *outersortkeys,
2176  List *innersortkeys)
2177 {
2178  MergePath *pathnode = makeNode(MergePath);
2179 
2180  pathnode->jpath.path.pathtype = T_MergeJoin;
2181  pathnode->jpath.path.parent = joinrel;
2182  pathnode->jpath.path.pathtarget = joinrel->reltarget;
2183  pathnode->jpath.path.param_info =
2185  joinrel,
2186  outer_path,
2187  inner_path,
2188  extra->sjinfo,
2189  required_outer,
2190  &restrict_clauses);
2191  pathnode->jpath.path.parallel_aware = false;
2192  pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2193  outer_path->parallel_safe && inner_path->parallel_safe;
2194  /* This is a foolish way to estimate parallel_workers, but for now... */
2195  pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2196  pathnode->jpath.path.pathkeys = pathkeys;
2197  pathnode->jpath.jointype = jointype;
2198  pathnode->jpath.inner_unique = extra->inner_unique;
2199  pathnode->jpath.outerjoinpath = outer_path;
2200  pathnode->jpath.innerjoinpath = inner_path;
2201  pathnode->jpath.joinrestrictinfo = restrict_clauses;
2202  pathnode->path_mergeclauses = mergeclauses;
2203  pathnode->outersortkeys = outersortkeys;
2204  pathnode->innersortkeys = innersortkeys;
2205  /* pathnode->skip_mark_restore will be set by final_cost_mergejoin */
2206  /* pathnode->materialize_inner will be set by final_cost_mergejoin */
2207 
2208  final_cost_mergejoin(root, pathnode, workspace, extra);
2209 
2210  return pathnode;
2211 }
2212 
2213 /*
2214  * create_hashjoin_path
2215  * Creates a pathnode corresponding to a hash join between two relations.
2216  *
2217  * 'joinrel' is the join relation
2218  * 'jointype' is the type of join required
2219  * 'workspace' is the result from initial_cost_hashjoin
2220  * 'extra' contains various information about the join
2221  * 'outer_path' is the cheapest outer path
2222  * 'inner_path' is the cheapest inner path
2223  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2224  * 'required_outer' is the set of required outer rels
2225  * 'hashclauses' are the RestrictInfo nodes to use as hash clauses
2226  * (this should be a subset of the restrict_clauses list)
2227  */
2228 HashPath *
2230  RelOptInfo *joinrel,
2231  JoinType jointype,
2232  JoinCostWorkspace *workspace,
2233  JoinPathExtraData *extra,
2234  Path *outer_path,
2235  Path *inner_path,
2236  List *restrict_clauses,
2237  Relids required_outer,
2238  List *hashclauses)
2239 {
2240  HashPath *pathnode = makeNode(HashPath);
2241 
2242  pathnode->jpath.path.pathtype = T_HashJoin;
2243  pathnode->jpath.path.parent = joinrel;
2244  pathnode->jpath.path.pathtarget = joinrel->reltarget;
2245  pathnode->jpath.path.param_info =
2247  joinrel,
2248  outer_path,
2249  inner_path,
2250  extra->sjinfo,
2251  required_outer,
2252  &restrict_clauses);
2253  pathnode->jpath.path.parallel_aware = false;
2254  pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2255  outer_path->parallel_safe && inner_path->parallel_safe;
2256  /* This is a foolish way to estimate parallel_workers, but for now... */
2257  pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2258 
2259  /*
2260  * A hashjoin never has pathkeys, since its output ordering is
2261  * unpredictable due to possible batching. XXX If the inner relation is
2262  * small enough, we could instruct the executor that it must not batch,
2263  * and then we could assume that the output inherits the outer relation's
2264  * ordering, which might save a sort step. However there is considerable
2265  * downside if our estimate of the inner relation size is badly off. For
2266  * the moment we don't risk it. (Note also that if we wanted to take this
2267  * seriously, joinpath.c would have to consider many more paths for the
2268  * outer rel than it does now.)
2269  */
2270  pathnode->jpath.path.pathkeys = NIL;
2271  pathnode->jpath.jointype = jointype;
2272  pathnode->jpath.inner_unique = extra->inner_unique;
2273  pathnode->jpath.outerjoinpath = outer_path;
2274  pathnode->jpath.innerjoinpath = inner_path;
2275  pathnode->jpath.joinrestrictinfo = restrict_clauses;
2276  pathnode->path_hashclauses = hashclauses;
2277  /* final_cost_hashjoin will fill in pathnode->num_batches */
2278 
2279  final_cost_hashjoin(root, pathnode, workspace, extra);
2280 
2281  return pathnode;
2282 }
2283 
2284 /*
2285  * create_projection_path
2286  * Creates a pathnode that represents performing a projection.
2287  *
2288  * 'rel' is the parent relation associated with the result
2289  * 'subpath' is the path representing the source of data
2290  * 'target' is the PathTarget to be computed
2291  */
2294  RelOptInfo *rel,
2295  Path *subpath,
2296  PathTarget *target)
2297 {
2298  ProjectionPath *pathnode = makeNode(ProjectionPath);
2299  PathTarget *oldtarget = subpath->pathtarget;
2300 
2301  pathnode->path.pathtype = T_Result;
2302  pathnode->path.parent = rel;
2303  pathnode->path.pathtarget = target;
2304  /* For now, assume we are above any joins, so no parameterization */
2305  pathnode->path.param_info = NULL;
2306  pathnode->path.parallel_aware = false;
2307  pathnode->path.parallel_safe = rel->consider_parallel &&
2308  subpath->parallel_safe &&
2309  is_parallel_safe(root, (Node *) target->exprs);
2310  pathnode->path.parallel_workers = subpath->parallel_workers;
2311  /* Projection does not change the sort order */
2312  pathnode->path.pathkeys = subpath->pathkeys;
2313 
2314  pathnode->subpath = subpath;
2315 
2316  /*
2317  * We might not need a separate Result node. If the input plan node type
2318  * can project, we can just tell it to project something else. Or, if it
2319  * can't project but the desired target has the same expression list as
2320  * what the input will produce anyway, we can still give it the desired
2321  * tlist (possibly changing its ressortgroupref labels, but nothing else).
2322  * Note: in the latter case, create_projection_plan has to recheck our
2323  * conclusion; see comments therein.
2324  */
2325  if (is_projection_capable_path(subpath) ||
2326  equal(oldtarget->exprs, target->exprs))
2327  {
2328  /* No separate Result node needed */
2329  pathnode->dummypp = true;
2330 
2331  /*
2332  * Set cost of plan as subpath's cost, adjusted for tlist replacement.
2333  */
2334  pathnode->path.rows = subpath->rows;
2335  pathnode->path.startup_cost = subpath->startup_cost +
2336  (target->cost.startup - oldtarget->cost.startup);
2337  pathnode->path.total_cost = subpath->total_cost +
2338  (target->cost.startup - oldtarget->cost.startup) +
2339  (target->cost.per_tuple - oldtarget->cost.per_tuple) * subpath->rows;
2340  }
2341  else
2342  {
2343  /* We really do need the Result node */
2344  pathnode->dummypp = false;
2345 
2346  /*
2347  * The Result node's cost is cpu_tuple_cost per row, plus the cost of
2348  * evaluating the tlist. There is no qual to worry about.
2349  */
2350  pathnode->path.rows = subpath->rows;
2351  pathnode->path.startup_cost = subpath->startup_cost +
2352  target->cost.startup;
2353  pathnode->path.total_cost = subpath->total_cost +
2354  target->cost.startup +
2355  (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows;
2356  }
2357 
2358  return pathnode;
2359 }
2360 
2361 /*
2362  * apply_projection_to_path
2363  * Add a projection step, or just apply the target directly to given path.
2364  *
2365  * This has the same net effect as create_projection_path(), except that if
2366  * a separate Result plan node isn't needed, we just replace the given path's
2367  * pathtarget with the desired one. This must be used only when the caller
2368  * knows that the given path isn't referenced elsewhere and so can be modified
2369  * in-place.
2370  *
2371  * If the input path is a GatherPath or GatherMergePath, we try to push the
2372  * new target down to its input as well; this is a yet more invasive
2373  * modification of the input path, which create_projection_path() can't do.
2374  *
2375  * Note that we mustn't change the source path's parent link; so when it is
2376  * add_path'd to "rel" things will be a bit inconsistent. So far that has
2377  * not caused any trouble.
2378  *
2379  * 'rel' is the parent relation associated with the result
2380  * 'path' is the path representing the source of data
2381  * 'target' is the PathTarget to be computed
2382  */
2383 Path *
2385  RelOptInfo *rel,
2386  Path *path,
2387  PathTarget *target)
2388 {
2389  QualCost oldcost;
2390 
2391  /*
2392  * If given path can't project, we might need a Result node, so make a
2393  * separate ProjectionPath.
2394  */
2395  if (!is_projection_capable_path(path))
2396  return (Path *) create_projection_path(root, rel, path, target);
2397 
2398  /*
2399  * We can just jam the desired tlist into the existing path, being sure to
2400  * update its cost estimates appropriately.
2401  */
2402  oldcost = path->pathtarget->cost;
2403  path->pathtarget = target;
2404 
2405  path->startup_cost += target->cost.startup - oldcost.startup;
2406  path->total_cost += target->cost.startup - oldcost.startup +
2407  (target->cost.per_tuple - oldcost.per_tuple) * path->rows;
2408 
2409  /*
2410  * If the path happens to be a Gather or GatherMerge path, we'd like to
2411  * arrange for the subpath to return the required target list so that
2412  * workers can help project. But if there is something that is not
2413  * parallel-safe in the target expressions, then we can't.
2414  */
2415  if ((IsA(path, GatherPath) || IsA(path, GatherMergePath)) &&
2416  is_parallel_safe(root, (Node *) target->exprs))
2417  {
2418  /*
2419  * We always use create_projection_path here, even if the subpath is
2420  * projection-capable, so as to avoid modifying the subpath in place.
2421  * It seems unlikely at present that there could be any other
2422  * references to the subpath, but better safe than sorry.
2423  *
2424  * Note that we don't change the parallel path's cost estimates; it might
2425  * be appropriate to do so, to reflect the fact that the bulk of the
2426  * target evaluation will happen in workers.
2427  */
2428  if (IsA(path, GatherPath))
2429  {
2430  GatherPath *gpath = (GatherPath *) path;
2431 
2432  gpath->subpath = (Path *)
2434  gpath->subpath->parent,
2435  gpath->subpath,
2436  target);
2437  }
2438  else
2439  {
2440  GatherMergePath *gmpath = (GatherMergePath *) path;
2441 
2442  gmpath->subpath = (Path *)
2444  gmpath->subpath->parent,
2445  gmpath->subpath,
2446  target);
2447  }
2448  }
2449  else if (path->parallel_safe &&
2450  !is_parallel_safe(root, (Node *) target->exprs))
2451  {
2452  /*
2453  * We're inserting a parallel-restricted target list into a path
2454  * currently marked parallel-safe, so we have to mark it as no longer
2455  * safe.
2456  */
2457  path->parallel_safe = false;
2458  }
2459 
2460  return path;
2461 }
2462 
2463 /*
2464  * create_set_projection_path
2465  * Creates a pathnode that represents performing a projection that
2466  * includes set-returning functions.
2467  *
2468  * 'rel' is the parent relation associated with the result
2469  * 'subpath' is the path representing the source of data
2470  * 'target' is the PathTarget to be computed
2471  */
2474  RelOptInfo *rel,
2475  Path *subpath,
2476  PathTarget *target)
2477 {
2478  ProjectSetPath *pathnode = makeNode(ProjectSetPath);
2479  double tlist_rows;
2480  ListCell *lc;
2481 
2482  pathnode->path.pathtype = T_ProjectSet;
2483  pathnode->path.parent = rel;
2484  pathnode->path.pathtarget = target;
2485  /* For now, assume we are above any joins, so no parameterization */
2486  pathnode->path.param_info = NULL;
2487  pathnode->path.parallel_aware = false;
2488  pathnode->path.parallel_safe = rel->consider_parallel &&
2489  subpath->parallel_safe &&
2490  is_parallel_safe(root, (Node *) target->exprs);
2491  pathnode->path.parallel_workers = subpath->parallel_workers;
2492  /* Projection does not change the sort order XXX? */
2493  pathnode->path.pathkeys = subpath->pathkeys;
2494 
2495  pathnode->subpath = subpath;
2496 
2497  /*
2498  * Estimate number of rows produced by SRFs for each row of input; if
2499  * there's more than one in this node, use the maximum.
2500  */
2501  tlist_rows = 1;
2502  foreach(lc, target->exprs)
2503  {
2504  Node *node = (Node *) lfirst(lc);
2505  double itemrows;
2506 
2507  itemrows = expression_returns_set_rows(node);
2508  if (tlist_rows < itemrows)
2509  tlist_rows = itemrows;
2510  }
2511 
2512  /*
2513  * In addition to the cost of evaluating the tlist, charge cpu_tuple_cost
2514  * per input row, and half of cpu_tuple_cost for each added output row.
2515  * This is slightly bizarre maybe, but it's what 9.6 did; we may revisit
2516  * this estimate later.
2517  */
2518  pathnode->path.rows = subpath->rows * tlist_rows;
2519  pathnode->path.startup_cost = subpath->startup_cost +
2520  target->cost.startup;
2521  pathnode->path.total_cost = subpath->total_cost +
2522  target->cost.startup +
2523  (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows +
2524  (pathnode->path.rows - subpath->rows) * cpu_tuple_cost / 2;
2525 
2526  return pathnode;
2527 }
2528 
2529 /*
2530  * create_sort_path
2531  * Creates a pathnode that represents performing an explicit sort.
2532  *
2533  * 'rel' is the parent relation associated with the result
2534  * 'subpath' is the path representing the source of data
2535  * 'pathkeys' represents the desired sort order
2536  * 'limit_tuples' is the estimated bound on the number of output tuples,
2537  * or -1 if no LIMIT or couldn't estimate
2538  */
2539 SortPath *
2541  RelOptInfo *rel,
2542  Path *subpath,
2543  List *pathkeys,
2544  double limit_tuples)
2545 {
2546  SortPath *pathnode = makeNode(SortPath);
2547 
2548  pathnode->path.pathtype = T_Sort;
2549  pathnode->path.parent = rel;
2550  /* Sort doesn't project, so use source path's pathtarget */
2551  pathnode->path.pathtarget = subpath->pathtarget;
2552  /* For now, assume we are above any joins, so no parameterization */
2553  pathnode->path.param_info = NULL;
2554  pathnode->path.parallel_aware = false;
2555  pathnode->path.parallel_safe = rel->consider_parallel &&
2556  subpath->parallel_safe;
2557  pathnode->path.parallel_workers = subpath->parallel_workers;
2558  pathnode->path.pathkeys = pathkeys;
2559 
2560  pathnode->subpath = subpath;
2561 
2562  cost_sort(&pathnode->path, root, pathkeys,
2563  subpath->total_cost,
2564  subpath->rows,
2565  subpath->pathtarget->width,
2566  0.0, /* XXX comparison_cost shouldn't be 0? */
2567  work_mem, limit_tuples);
2568 
2569  return pathnode;
2570 }
2571 
2572 /*
2573  * create_group_path
2574  * Creates a pathnode that represents performing grouping of presorted input
2575  *
2576  * 'rel' is the parent relation associated with the result
2577  * 'subpath' is the path representing the source of data
2578  * 'target' is the PathTarget to be computed
2579  * 'groupClause' is a list of SortGroupClause's representing the grouping
2580  * 'qual' is the HAVING quals if any
2581  * 'numGroups' is the estimated number of groups
2582  */
2583 GroupPath *
2585  RelOptInfo *rel,
2586  Path *subpath,
2587  PathTarget *target,
2588  List *groupClause,
2589  List *qual,
2590  double numGroups)
2591 {
2592  GroupPath *pathnode = makeNode(GroupPath);
2593 
2594  pathnode->path.pathtype = T_Group;
2595  pathnode->path.parent = rel;
2596  pathnode->path.pathtarget = target;
2597  /* For now, assume we are above any joins, so no parameterization */
2598  pathnode->path.param_info = NULL;
2599  pathnode->path.parallel_aware = false;
2600  pathnode->path.parallel_safe = rel->consider_parallel &&
2601  subpath->parallel_safe;
2602  pathnode->path.parallel_workers = subpath->parallel_workers;
2603  /* Group doesn't change sort ordering */
2604  pathnode->path.pathkeys = subpath->pathkeys;
2605 
2606  pathnode->subpath = subpath;
2607 
2608  pathnode->groupClause = groupClause;
2609  pathnode->qual = qual;
2610 
2611  cost_group(&pathnode->path, root,
2612  list_length(groupClause),
2613  numGroups,
2614  qual,
2615  subpath->startup_cost, subpath->total_cost,
2616  subpath->rows);
2617 
2618  /* add tlist eval cost for each output row */
2619  pathnode->path.startup_cost += target->cost.startup;
2620  pathnode->path.total_cost += target->cost.startup +
2621  target->cost.per_tuple * pathnode->path.rows;
2622 
2623  return pathnode;
2624 }
2625 
2626 /*
2627  * create_upper_unique_path
2628  * Creates a pathnode that represents performing an explicit Unique step
2629  * on presorted input.
2630  *
2631  * This produces a Unique plan node, but the use-case is so different from
2632  * create_unique_path that it doesn't seem worth trying to merge the two.
2633  *
2634  * 'rel' is the parent relation associated with the result
2635  * 'subpath' is the path representing the source of data
2636  * 'numCols' is the number of grouping columns
2637  * 'numGroups' is the estimated number of groups
2638  *
2639  * The input path must be sorted on the grouping columns, plus possibly
2640  * additional columns; so the first numCols pathkeys are the grouping columns
2641  */
2644  RelOptInfo *rel,
2645  Path *subpath,
2646  int numCols,
2647  double numGroups)
2648 {
2650 
2651  pathnode->path.pathtype = T_Unique;
2652  pathnode->path.parent = rel;
2653  /* Unique doesn't project, so use source path's pathtarget */
2654  pathnode->path.pathtarget = subpath->pathtarget;
2655  /* For now, assume we are above any joins, so no parameterization */
2656  pathnode->path.param_info = NULL;
2657  pathnode->path.parallel_aware = false;
2658  pathnode->path.parallel_safe = rel->consider_parallel &&
2659  subpath->parallel_safe;
2660  pathnode->path.parallel_workers = subpath->parallel_workers;
2661  /* Unique doesn't change the input ordering */
2662  pathnode->path.pathkeys = subpath->pathkeys;
2663 
2664  pathnode->subpath = subpath;
2665  pathnode->numkeys = numCols;
2666 
2667  /*
2668  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2669  * all columns get compared at most of the tuples. (XXX probably this is
2670  * an overestimate.)
2671  */
2672  pathnode->path.startup_cost = subpath->startup_cost;
2673  pathnode->path.total_cost = subpath->total_cost +
2674  cpu_operator_cost * subpath->rows * numCols;
2675  pathnode->path.rows = numGroups;
2676 
2677  return pathnode;
2678 }
2679 
2680 /*
2681  * create_agg_path
2682  * Creates a pathnode that represents performing aggregation/grouping
2683  *
2684  * 'rel' is the parent relation associated with the result
2685  * 'subpath' is the path representing the source of data
2686  * 'target' is the PathTarget to be computed
2687  * 'aggstrategy' is the Agg node's basic implementation strategy
2688  * 'aggsplit' is the Agg node's aggregate-splitting mode
2689  * 'groupClause' is a list of SortGroupClause's representing the grouping
2690  * 'qual' is the HAVING quals if any
2691  * 'aggcosts' contains cost info about the aggregate functions to be computed
2692  * 'numGroups' is the estimated number of groups (1 if not grouping)
2693  */
2694 AggPath *
2696  RelOptInfo *rel,
2697  Path *subpath,
2698  PathTarget *target,
2699  AggStrategy aggstrategy,
2700  AggSplit aggsplit,
2701  List *groupClause,
2702  List *qual,
2703  const AggClauseCosts *aggcosts,
2704  double numGroups)
2705 {
2706  AggPath *pathnode = makeNode(AggPath);
2707 
2708  pathnode->path.pathtype = T_Agg;
2709  pathnode->path.parent = rel;
2710  pathnode->path.pathtarget = target;
2711  /* For now, assume we are above any joins, so no parameterization */
2712  pathnode->path.param_info = NULL;
2713  pathnode->path.parallel_aware = false;
2714  pathnode->path.parallel_safe = rel->consider_parallel &&
2715  subpath->parallel_safe;
2716  pathnode->path.parallel_workers = subpath->parallel_workers;
2717  if (aggstrategy == AGG_SORTED)
2718  pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */
2719  else
2720  pathnode->path.pathkeys = NIL; /* output is unordered */
2721  pathnode->subpath = subpath;
2722 
2723  pathnode->aggstrategy = aggstrategy;
2724  pathnode->aggsplit = aggsplit;
2725  pathnode->numGroups = numGroups;
2726  pathnode->groupClause = groupClause;
2727  pathnode->qual = qual;
2728 
2729  cost_agg(&pathnode->path, root,
2730  aggstrategy, aggcosts,
2731  list_length(groupClause), numGroups,
2732  qual,
2733  subpath->startup_cost, subpath->total_cost,
2734  subpath->rows);
2735 
2736  /* add tlist eval cost for each output row */
2737  pathnode->path.startup_cost += target->cost.startup;
2738  pathnode->path.total_cost += target->cost.startup +
2739  target->cost.per_tuple * pathnode->path.rows;
2740 
2741  return pathnode;
2742 }
2743 
2744 /*
2745  * create_groupingsets_path
2746  * Creates a pathnode that represents performing GROUPING SETS aggregation
2747  *
2748  * GroupingSetsPath represents sorted grouping with one or more grouping sets.
2749  * The input path's result must be sorted to match the last entry in
2750  * rollup_groupclauses.
2751  *
2752  * 'rel' is the parent relation associated with the result
2753  * 'subpath' is the path representing the source of data
2754  * 'target' is the PathTarget to be computed
2755  * 'having_qual' is the HAVING quals if any
2756  * 'rollups' is a list of RollupData nodes
2757  * 'agg_costs' contains cost info about the aggregate functions to be computed
2758  * 'numGroups' is the estimated total number of groups
2759  */
2762  RelOptInfo *rel,
2763  Path *subpath,
2764  PathTarget *target,
2765  List *having_qual,
2766  AggStrategy aggstrategy,
2767  List *rollups,
2768  const AggClauseCosts *agg_costs,
2769  double numGroups)
2770 {
2772  ListCell *lc;
2773  bool is_first = true;
2774  bool is_first_sort = true;
2775 
2776  /* The topmost generated Plan node will be an Agg */
2777  pathnode->path.pathtype = T_Agg;
2778  pathnode->path.parent = rel;
2779  pathnode->path.pathtarget = target;
2780  pathnode->path.param_info = subpath->param_info;
2781  pathnode->path.parallel_aware = false;
2782  pathnode->path.parallel_safe = rel->consider_parallel &&
2783  subpath->parallel_safe;
2784  pathnode->path.parallel_workers = subpath->parallel_workers;
2785  pathnode->subpath = subpath;
2786 
2787  /*
2788  * Simplify callers by downgrading AGG_SORTED to AGG_PLAIN, and AGG_MIXED
2789  * to AGG_HASHED, here if possible.
2790  */
2791  if (aggstrategy == AGG_SORTED &&
2792  list_length(rollups) == 1 &&
2793  ((RollupData *) linitial(rollups))->groupClause == NIL)
2794  aggstrategy = AGG_PLAIN;
2795 
2796  if (aggstrategy == AGG_MIXED &&
2797  list_length(rollups) == 1)
2798  aggstrategy = AGG_HASHED;
2799 
2800  /*
2801  * Output will be in sorted order by group_pathkeys if, and only if, there
2802  * is a single rollup operation on a non-empty list of grouping
2803  * expressions.
2804  */
2805  if (aggstrategy == AGG_SORTED && list_length(rollups) == 1)
2806  pathnode->path.pathkeys = root->group_pathkeys;
2807  else
2808  pathnode->path.pathkeys = NIL;
2809 
2810  pathnode->aggstrategy = aggstrategy;
2811  pathnode->rollups = rollups;
2812  pathnode->qual = having_qual;
2813 
2814  Assert(rollups != NIL);
2815  Assert(aggstrategy != AGG_PLAIN || list_length(rollups) == 1);
2816  Assert(aggstrategy != AGG_MIXED || list_length(rollups) > 1);
2817 
2818  foreach(lc, rollups)
2819  {
2820  RollupData *rollup = lfirst(lc);
2821  List *gsets = rollup->gsets;
2822  int numGroupCols = list_length(linitial(gsets));
2823 
2824  /*
2825  * In AGG_SORTED or AGG_PLAIN mode, the first rollup takes the
2826  * (already-sorted) input, and following ones do their own sort.
2827  *
2828  * In AGG_HASHED mode, there is one rollup for each grouping set.
2829  *
2830  * In AGG_MIXED mode, the first rollups are hashed, the first
2831  * non-hashed one takes the (already-sorted) input, and following ones
2832  * do their own sort.
2833  */
2834  if (is_first)
2835  {
2836  cost_agg(&pathnode->path, root,
2837  aggstrategy,
2838  agg_costs,
2839  numGroupCols,
2840  rollup->numGroups,
2841  having_qual,
2842  subpath->startup_cost,
2843  subpath->total_cost,
2844  subpath->rows);
2845  is_first = false;
2846  if (!rollup->is_hashed)
2847  is_first_sort = false;
2848  }
2849  else
2850  {
2851  Path sort_path; /* dummy for result of cost_sort */
2852  Path agg_path; /* dummy for result of cost_agg */
2853 
2854  if (rollup->is_hashed || is_first_sort)
2855  {
2856  /*
2857  * Account for cost of aggregation, but don't charge input
2858  * cost again
2859  */
2860  cost_agg(&agg_path, root,
2861  rollup->is_hashed ? AGG_HASHED : AGG_SORTED,
2862  agg_costs,
2863  numGroupCols,
2864  rollup->numGroups,
2865  having_qual,
2866  0.0, 0.0,
2867  subpath->rows);
2868  if (!rollup->is_hashed)
2869  is_first_sort = false;
2870  }
2871  else
2872  {
2873  /* Account for cost of sort, but don't charge input cost again */
2874  cost_sort(&sort_path, root, NIL,
2875  0.0,
2876  subpath->rows,
2877  subpath->pathtarget->width,
2878  0.0,
2879  work_mem,
2880  -1.0);
2881 
2882  /* Account for cost of aggregation */
2883 
2884  cost_agg(&agg_path, root,
2885  AGG_SORTED,
2886  agg_costs,
2887  numGroupCols,
2888  rollup->numGroups,
2889  having_qual,
2890  sort_path.startup_cost,
2891  sort_path.total_cost,
2892  sort_path.rows);
2893  }
2894 
2895  pathnode->path.total_cost += agg_path.total_cost;
2896  pathnode->path.rows += agg_path.rows;
2897  }
2898  }
2899 
2900  /* add tlist eval cost for each output row */
2901  pathnode->path.startup_cost += target->cost.startup;
2902  pathnode->path.total_cost += target->cost.startup +
2903  target->cost.per_tuple * pathnode->path.rows;
2904 
2905  return pathnode;
2906 }
2907 
2908 /*
2909  * create_minmaxagg_path
2910  * Creates a pathnode that represents computation of MIN/MAX aggregates
2911  *
2912  * 'rel' is the parent relation associated with the result
2913  * 'target' is the PathTarget to be computed
2914  * 'mmaggregates' is a list of MinMaxAggInfo structs
2915  * 'quals' is the HAVING quals if any
2916  */
2917 MinMaxAggPath *
2919  RelOptInfo *rel,
2920  PathTarget *target,
2921  List *mmaggregates,
2922  List *quals)
2923 {
2924  MinMaxAggPath *pathnode = makeNode(MinMaxAggPath);
2925  Cost initplan_cost;
2926  ListCell *lc;
2927 
2928  /* The topmost generated Plan node will be a Result */
2929  pathnode->path.pathtype = T_Result;
2930  pathnode->path.parent = rel;
2931  pathnode->path.pathtarget = target;
2932  /* For now, assume we are above any joins, so no parameterization */
2933  pathnode->path.param_info = NULL;
2934  pathnode->path.parallel_aware = false;
2935  /* A MinMaxAggPath implies use of subplans, so cannot be parallel-safe */
2936  pathnode->path.parallel_safe = false;
2937  pathnode->path.parallel_workers = 0;
2938  /* Result is one unordered row */
2939  pathnode->path.rows = 1;
2940  pathnode->path.pathkeys = NIL;
2941 
2942  pathnode->mmaggregates = mmaggregates;
2943  pathnode->quals = quals;
2944 
2945  /* Calculate cost of all the initplans ... */
2946  initplan_cost = 0;
2947  foreach(lc, mmaggregates)
2948  {
2949  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
2950 
2951  initplan_cost += mminfo->pathcost;
2952  }
2953 
2954  /* add tlist eval cost for each output row, plus cpu_tuple_cost */
2955  pathnode->path.startup_cost = initplan_cost + target->cost.startup;
2956  pathnode->path.total_cost = initplan_cost + target->cost.startup +
2957  target->cost.per_tuple + cpu_tuple_cost;
2958 
2959  /*
2960  * Add cost of qual, if any --- but we ignore its selectivity, since our
2961  * rowcount estimate should be 1 no matter what the qual is.
2962  */
2963  if (quals)
2964  {
2965  QualCost qual_cost;
2966 
2967  cost_qual_eval(&qual_cost, quals, root);
2968  pathnode->path.startup_cost += qual_cost.startup;
2969  pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
2970  }
2971 
2972  return pathnode;
2973 }
2974 
2975 /*
2976  * create_windowagg_path
2977  * Creates a pathnode that represents computation of window functions
2978  *
2979  * 'rel' is the parent relation associated with the result
2980  * 'subpath' is the path representing the source of data
2981  * 'target' is the PathTarget to be computed
2982  * 'windowFuncs' is a list of WindowFunc structs
2983  * 'winclause' is a WindowClause that is common to all the WindowFuncs
2984  * 'winpathkeys' is the pathkeys for the PARTITION keys + ORDER keys
2985  *
2986  * The actual sort order of the input must match winpathkeys, but might
2987  * have additional keys after those.
2988  */
2989 WindowAggPath *
2991  RelOptInfo *rel,
2992  Path *subpath,
2993  PathTarget *target,
2994  List *windowFuncs,
2995  WindowClause *winclause,
2996  List *winpathkeys)
2997 {
2998  WindowAggPath *pathnode = makeNode(WindowAggPath);
2999 
3000  pathnode->path.pathtype = T_WindowAgg;
3001  pathnode->path.parent = rel;
3002  pathnode->path.pathtarget = target;
3003  /* For now, assume we are above any joins, so no parameterization */
3004  pathnode->path.param_info = NULL;
3005  pathnode->path.parallel_aware = false;
3006  pathnode->path.parallel_safe = rel->consider_parallel &&
3007  subpath->parallel_safe;
3008  pathnode->path.parallel_workers = subpath->parallel_workers;
3009  /* WindowAgg preserves the input sort order */
3010  pathnode->path.pathkeys = subpath->pathkeys;
3011 
3012  pathnode->subpath = subpath;
3013  pathnode->winclause = winclause;
3014  pathnode->winpathkeys = winpathkeys;
3015 
3016  /*
3017  * For costing purposes, assume that there are no redundant partitioning
3018  * or ordering columns; it's not worth the trouble to deal with that
3019  * corner case here. So we just pass the unmodified list lengths to
3020  * cost_windowagg.
3021  */
3022  cost_windowagg(&pathnode->path, root,
3023  windowFuncs,
3024  list_length(winclause->partitionClause),
3025  list_length(winclause->orderClause),
3026  subpath->startup_cost,
3027  subpath->total_cost,
3028  subpath->rows);
3029 
3030  /* add tlist eval cost for each output row */
3031  pathnode->path.startup_cost += target->cost.startup;
3032  pathnode->path.total_cost += target->cost.startup +
3033  target->cost.per_tuple * pathnode->path.rows;
3034 
3035  return pathnode;
3036 }
3037 
3038 /*
3039  * create_setop_path
3040  * Creates a pathnode that represents computation of INTERSECT or EXCEPT
3041  *
3042  * 'rel' is the parent relation associated with the result
3043  * 'subpath' is the path representing the source of data
3044  * 'cmd' is the specific semantics (INTERSECT or EXCEPT, with/without ALL)
3045  * 'strategy' is the implementation strategy (sorted or hashed)
3046  * 'distinctList' is a list of SortGroupClause's representing the grouping
3047  * 'flagColIdx' is the column number where the flag column will be, if any
3048  * 'firstFlag' is the flag value for the first input relation when hashing;
3049  * or -1 when sorting
3050  * 'numGroups' is the estimated number of distinct groups
3051  * 'outputRows' is the estimated number of output rows
3052  */
3053 SetOpPath *
3055  RelOptInfo *rel,
3056  Path *subpath,
3057  SetOpCmd cmd,
3058  SetOpStrategy strategy,
3059  List *distinctList,
3060  AttrNumber flagColIdx,
3061  int firstFlag,
3062  double numGroups,
3063  double outputRows)
3064 {
3065  SetOpPath *pathnode = makeNode(SetOpPath);
3066 
3067  pathnode->path.pathtype = T_SetOp;
3068  pathnode->path.parent = rel;
3069  /* SetOp doesn't project, so use source path's pathtarget */
3070  pathnode->path.pathtarget = subpath->pathtarget;
3071  /* For now, assume we are above any joins, so no parameterization */
3072  pathnode->path.param_info = NULL;
3073  pathnode->path.parallel_aware = false;
3074  pathnode->path.parallel_safe = rel->consider_parallel &&
3075  subpath->parallel_safe;
3076  pathnode->path.parallel_workers = subpath->parallel_workers;
3077  /* SetOp preserves the input sort order if in sort mode */
3078  pathnode->path.pathkeys =
3079  (strategy == SETOP_SORTED) ? subpath->pathkeys : NIL;
3080 
3081  pathnode->subpath = subpath;
3082  pathnode->cmd = cmd;
3083  pathnode->strategy = strategy;
3084  pathnode->distinctList = distinctList;
3085  pathnode->flagColIdx = flagColIdx;
3086  pathnode->firstFlag = firstFlag;
3087  pathnode->numGroups = numGroups;
3088 
3089  /*
3090  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3091  * all columns get compared at most of the tuples.
3092  */
3093  pathnode->path.startup_cost = subpath->startup_cost;
3094  pathnode->path.total_cost = subpath->total_cost +
3095  cpu_operator_cost * subpath->rows * list_length(distinctList);
3096  pathnode->path.rows = outputRows;
3097 
3098  return pathnode;
3099 }
3100 
3101 /*
3102  * create_recursiveunion_path
3103  * Creates a pathnode that represents a recursive UNION node
3104  *
3105  * 'rel' is the parent relation associated with the result
3106  * 'leftpath' is the source of data for the non-recursive term
3107  * 'rightpath' is the source of data for the recursive term
3108  * 'target' is the PathTarget to be computed
3109  * 'distinctList' is a list of SortGroupClause's representing the grouping
3110  * 'wtParam' is the ID of Param representing work table
3111  * 'numGroups' is the estimated number of groups
3112  *
3113  * For recursive UNION ALL, distinctList is empty and numGroups is zero
3114  */
3117  RelOptInfo *rel,
3118  Path *leftpath,
3119  Path *rightpath,
3120  PathTarget *target,
3121  List *distinctList,
3122  int wtParam,
3123  double numGroups)
3124 {
3126 
3127  pathnode->path.pathtype = T_RecursiveUnion;
3128  pathnode->path.parent = rel;
3129  pathnode->path.pathtarget = target;
3130  /* For now, assume we are above any joins, so no parameterization */
3131  pathnode->path.param_info = NULL;
3132  pathnode->path.parallel_aware = false;
3133  pathnode->path.parallel_safe = rel->consider_parallel &&
3134  leftpath->parallel_safe && rightpath->parallel_safe;
3135  /* Foolish, but we'll do it like joins for now: */
3136  pathnode->path.parallel_workers = leftpath->parallel_workers;
3137  /* RecursiveUnion result is always unsorted */
3138  pathnode->path.pathkeys = NIL;
3139 
3140  pathnode->leftpath = leftpath;
3141  pathnode->rightpath = rightpath;
3142  pathnode->distinctList = distinctList;
3143  pathnode->wtParam = wtParam;
3144  pathnode->numGroups = numGroups;
3145 
3146  cost_recursive_union(&pathnode->path, leftpath, rightpath);
3147 
3148  return pathnode;
3149 }
3150 
3151 /*
3152  * create_lockrows_path
3153  * Creates a pathnode that represents acquiring row locks
3154  *
3155  * 'rel' is the parent relation associated with the result
3156  * 'subpath' is the path representing the source of data
3157  * 'rowMarks' is a list of PlanRowMark's
3158  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3159  */
3160 LockRowsPath *
3162  Path *subpath, List *rowMarks, int epqParam)
3163 {
3164  LockRowsPath *pathnode = makeNode(LockRowsPath);
3165 
3166  pathnode->path.pathtype = T_LockRows;
3167  pathnode->path.parent = rel;
3168  /* LockRows doesn't project, so use source path's pathtarget */
3169  pathnode->path.pathtarget = subpath->pathtarget;
3170  /* For now, assume we are above any joins, so no parameterization */
3171  pathnode->path.param_info = NULL;
3172  pathnode->path.parallel_aware = false;
3173  pathnode->path.parallel_safe = false;
3174  pathnode->path.parallel_workers = 0;
3175  pathnode->path.rows = subpath->rows;
3176 
3177  /*
3178  * The result cannot be assumed sorted, since locking might cause the sort
3179  * key columns to be replaced with new values.
3180  */
3181  pathnode->path.pathkeys = NIL;
3182 
3183  pathnode->subpath = subpath;
3184  pathnode->rowMarks = rowMarks;
3185  pathnode->epqParam = epqParam;
3186 
3187  /*
3188  * We should charge something extra for the costs of row locking and
3189  * possible refetches, but it's hard to say how much. For now, use
3190  * cpu_tuple_cost per row.
3191  */
3192  pathnode->path.startup_cost = subpath->startup_cost;
3193  pathnode->path.total_cost = subpath->total_cost +
3194  cpu_tuple_cost * subpath->rows;
3195 
3196  return pathnode;
3197 }
3198 
3199 /*
3200  * create_modifytable_path
3201  * Creates a pathnode that represents performing INSERT/UPDATE/DELETE mods
3202  *
3203  * 'rel' is the parent relation associated with the result
3204  * 'operation' is the operation type
3205  * 'canSetTag' is true if we set the command tag/es_processed
3206  * 'nominalRelation' is the parent RT index for use of EXPLAIN
3207  * 'partitioned_rels' is an integer list of RT indexes of non-leaf tables in
3208  * the partition tree, if this is an UPDATE/DELETE to a partitioned table.
3209  * Otherwise NIL.
3210  * 'resultRelations' is an integer list of actual RT indexes of target rel(s)
3211  * 'subpaths' is a list of Path(s) producing source data (one per rel)
3212  * 'subroots' is a list of PlannerInfo structs (one per rel)
3213  * 'withCheckOptionLists' is a list of WCO lists (one per rel)
3214  * 'returningLists' is a list of RETURNING tlists (one per rel)
3215  * 'rowMarks' is a list of PlanRowMarks (non-locking only)
3216  * 'onconflict' is the ON CONFLICT clause, or NULL
3217  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3218  */
3221  CmdType operation, bool canSetTag,
3222  Index nominalRelation, List *partitioned_rels,
3223  List *resultRelations, List *subpaths,
3224  List *subroots,
3225  List *withCheckOptionLists, List *returningLists,
3226  List *rowMarks, OnConflictExpr *onconflict,
3227  int epqParam)
3228 {
3230  double total_size;
3231  ListCell *lc;
3232 
3233  Assert(list_length(resultRelations) == list_length(subpaths));
3234  Assert(list_length(resultRelations) == list_length(subroots));
3235  Assert(withCheckOptionLists == NIL ||
3236  list_length(resultRelations) == list_length(withCheckOptionLists));
3237  Assert(returningLists == NIL ||
3238  list_length(resultRelations) == list_length(returningLists));
3239 
3240  pathnode->path.pathtype = T_ModifyTable;
3241  pathnode->path.parent = rel;
3242  /* pathtarget is not interesting, just make it minimally valid */
3243  pathnode->path.pathtarget = rel->reltarget;
3244  /* For now, assume we are above any joins, so no parameterization */
3245  pathnode->path.param_info = NULL;
3246  pathnode->path.parallel_aware = false;
3247  pathnode->path.parallel_safe = false;
3248  pathnode->path.parallel_workers = 0;
3249  pathnode->path.pathkeys = NIL;
3250 
3251  /*
3252  * Compute cost & rowcount as sum of subpath costs & rowcounts.
3253  *
3254  * Currently, we don't charge anything extra for the actual table
3255  * modification work, nor for the WITH CHECK OPTIONS or RETURNING
3256  * expressions if any. It would only be window dressing, since
3257  * ModifyTable is always a top-level node and there is no way for the
3258  * costs to change any higher-level planning choices. But we might want
3259  * to make it look better sometime.
3260  */
3261  pathnode->path.startup_cost = 0;
3262  pathnode->path.total_cost = 0;
3263  pathnode->path.rows = 0;
3264  total_size = 0;
3265  foreach(lc, subpaths)
3266  {
3267  Path *subpath = (Path *) lfirst(lc);
3268 
3269  if (lc == list_head(subpaths)) /* first node? */
3270  pathnode->path.startup_cost = subpath->startup_cost;
3271  pathnode->path.total_cost += subpath->total_cost;
3272  pathnode->path.rows += subpath->rows;
3273  total_size += subpath->pathtarget->width * subpath->rows;
3274  }
3275 
3276  /*
3277  * Set width to the average width of the subpath outputs. XXX this is
3278  * totally wrong: we should report zero if no RETURNING, else an average
3279  * of the RETURNING tlist widths. But it's what happened historically,
3280  * and improving it is a task for another day.
3281  */
3282  if (pathnode->path.rows > 0)
3283  total_size /= pathnode->path.rows;
3284  pathnode->path.pathtarget->width = rint(total_size);
3285 
3286  pathnode->operation = operation;
3287  pathnode->canSetTag = canSetTag;
3288  pathnode->nominalRelation = nominalRelation;
3289  pathnode->partitioned_rels = list_copy(partitioned_rels);
3290  pathnode->resultRelations = resultRelations;
3291  pathnode->subpaths = subpaths;
3292  pathnode->subroots = subroots;
3293  pathnode->withCheckOptionLists = withCheckOptionLists;
3294  pathnode->returningLists = returningLists;
3295  pathnode->rowMarks = rowMarks;
3296  pathnode->onconflict = onconflict;
3297  pathnode->epqParam = epqParam;
3298 
3299  return pathnode;
3300 }
3301 
3302 /*
3303  * create_limit_path
3304  * Creates a pathnode that represents performing LIMIT/OFFSET
3305  *
3306  * In addition to providing the actual OFFSET and LIMIT expressions,
3307  * the caller must provide estimates of their values for costing purposes.
3308  * The estimates are as computed by preprocess_limit(), ie, 0 represents
3309  * the clause not being present, and -1 means it's present but we could
3310  * not estimate its value.
3311  *
3312  * 'rel' is the parent relation associated with the result
3313  * 'subpath' is the path representing the source of data
3314  * 'limitOffset' is the actual OFFSET expression, or NULL
3315  * 'limitCount' is the actual LIMIT expression, or NULL
3316  * 'offset_est' is the estimated value of the OFFSET expression
3317  * 'count_est' is the estimated value of the LIMIT expression
3318  */
3319 LimitPath *
3321  Path *subpath,
3322  Node *limitOffset, Node *limitCount,
3323  int64 offset_est, int64 count_est)
3324 {
3325  LimitPath *pathnode = makeNode(LimitPath);
3326 
3327  pathnode->path.pathtype = T_Limit;
3328  pathnode->path.parent = rel;
3329  /* Limit doesn't project, so use source path's pathtarget */
3330  pathnode->path.pathtarget = subpath->pathtarget;
3331  /* For now, assume we are above any joins, so no parameterization */
3332  pathnode->path.param_info = NULL;
3333  pathnode->path.parallel_aware = false;
3334  pathnode->path.parallel_safe = rel->consider_parallel &&
3335  subpath->parallel_safe;
3336  pathnode->path.parallel_workers = subpath->parallel_workers;
3337  pathnode->path.rows = subpath->rows;
3338  pathnode->path.startup_cost = subpath->startup_cost;
3339  pathnode->path.total_cost = subpath->total_cost;
3340  pathnode->path.pathkeys = subpath->pathkeys;
3341  pathnode->subpath = subpath;
3342  pathnode->limitOffset = limitOffset;
3343  pathnode->limitCount = limitCount;
3344 
3345  /*
3346  * Adjust the output rows count and costs according to the offset/limit.
3347  * This is only a cosmetic issue if we are at top level, but if we are
3348  * building a subquery then it's important to report correct info to the
3349  * outer planner.
3350  *
3351  * When the offset or count couldn't be estimated, use 10% of the
3352  * estimated number of rows emitted from the subpath.
3353  *
3354  * XXX we don't bother to add eval costs of the offset/limit expressions
3355  * themselves to the path costs. In theory we should, but in most cases
3356  * those expressions are trivial and it's just not worth the trouble.
3357  */
3358  if (offset_est != 0)
3359  {
3360  double offset_rows;
3361 
3362  if (offset_est > 0)
3363  offset_rows = (double) offset_est;
3364  else
3365  offset_rows = clamp_row_est(subpath->rows * 0.10);
3366  if (offset_rows > pathnode->path.rows)
3367  offset_rows = pathnode->path.rows;
3368  if (subpath->rows > 0)
3369  pathnode->path.startup_cost +=
3370  (subpath->total_cost - subpath->startup_cost)
3371  * offset_rows / subpath->rows;
3372  pathnode->path.rows -= offset_rows;
3373  if (pathnode->path.rows < 1)
3374  pathnode->path.rows = 1;
3375  }
3376 
3377  if (count_est != 0)
3378  {
3379  double count_rows;
3380 
3381  if (count_est > 0)
3382  count_rows = (double) count_est;
3383  else
3384  count_rows = clamp_row_est(subpath->rows * 0.10);
3385  if (count_rows > pathnode->path.rows)
3386  count_rows = pathnode->path.rows;
3387  if (subpath->rows > 0)
3388  pathnode->path.total_cost = pathnode->path.startup_cost +
3389  (subpath->total_cost - subpath->startup_cost)
3390  * count_rows / subpath->rows;
3391  pathnode->path.rows = count_rows;
3392  if (pathnode->path.rows < 1)
3393  pathnode->path.rows = 1;
3394  }
3395 
3396  return pathnode;
3397 }
3398 
3399 
3400 /*
3401  * reparameterize_path
3402  * Attempt to modify a Path to have greater parameterization
3403  *
3404  * We use this to attempt to bring all child paths of an appendrel to the
3405  * same parameterization level, ensuring that they all enforce the same set
3406  * of join quals (and thus that that parameterization can be attributed to
3407  * an append path built from such paths). Currently, only a few path types
3408  * are supported here, though more could be added at need. We return NULL
3409  * if we can't reparameterize the given path.
3410  *
3411  * Note: we intentionally do not pass created paths to add_path(); it would
3412  * possibly try to delete them on the grounds of being cost-inferior to the
3413  * paths they were made from, and we don't want that. Paths made here are
3414  * not necessarily of general-purpose usefulness, but they can be useful
3415  * as members of an append path.
3416  */
3417 Path *
3419  Relids required_outer,
3420  double loop_count)
3421 {
3422  RelOptInfo *rel = path->parent;
3423 
3424  /* Can only increase, not decrease, path's parameterization */
3425  if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
3426  return NULL;
3427  switch (path->pathtype)
3428  {
3429  case T_SeqScan:
3430  return create_seqscan_path(root, rel, required_outer, 0);
3431  case T_SampleScan:
3432  return (Path *) create_samplescan_path(root, rel, required_outer);
3433  case T_IndexScan:
3434  case T_IndexOnlyScan:
3435  {
3436  IndexPath *ipath = (IndexPath *) path;
3437  IndexPath *newpath = makeNode(IndexPath);
3438 
3439  /*
3440  * We can't use create_index_path directly, and would not want
3441  * to because it would re-compute the indexqual conditions
3442  * which is wasted effort. Instead we hack things a bit:
3443  * flat-copy the path node, revise its param_info, and redo
3444  * the cost estimate.
3445  */
3446  memcpy(newpath, ipath, sizeof(IndexPath));
3447  newpath->path.param_info =
3448  get_baserel_parampathinfo(root, rel, required_outer);
3449  cost_index(newpath, root, loop_count, false);
3450  return (Path *) newpath;
3451  }
3452  case T_BitmapHeapScan:
3453  {
3454  BitmapHeapPath *bpath = (BitmapHeapPath *) path;
3455 
3456  return (Path *) create_bitmap_heap_path(root,
3457  rel,
3458  bpath->bitmapqual,
3459  required_outer,
3460  loop_count, 0);
3461  }
3462  case T_SubqueryScan:
3463  {
3464  SubqueryScanPath *spath = (SubqueryScanPath *) path;
3465 
3466  return (Path *) create_subqueryscan_path(root,
3467  rel,
3468  spath->subpath,
3469  spath->path.pathkeys,
3470  required_outer);
3471  }
3472  default:
3473  break;
3474  }
3475  return NULL;
3476 }
3477 
3478 /*
3479  * reparameterize_path_by_child
3480  * Given a path parameterized by the parent of the given child relation,
3481  * translate the path to be parameterized by the given child relation.
3482  *
3483  * The function creates a new path of the same type as the given path, but
3484  * parameterized by the given child relation. Most fields from the original
3485  * path can simply be flat-copied, but any expressions must be adjusted to
3486  * refer to the correct varnos, and any paths must be recursively
3487  * reparameterized. Other fields that refer to specific relids also need
3488  * adjustment.
3489  *
3490  * The cost, number of rows, width and parallel path properties depend upon
3491  * path->parent, which does not change during the translation. Hence those
3492  * members are copied as they are.
3493  *
3494  * If the given path can not be reparameterized, the function returns NULL.
3495  */
3496 Path *
3498  RelOptInfo *child_rel)
3499 {
3500 
3501 #define FLAT_COPY_PATH(newnode, node, nodetype) \
3502  ( (newnode) = makeNode(nodetype), \
3503  memcpy((newnode), (node), sizeof(nodetype)) )
3504 
3505 #define ADJUST_CHILD_ATTRS(node) \
3506  ((node) = \
3507  (List *) adjust_appendrel_attrs_multilevel(root, (Node *) (node), \
3508  child_rel->relids, \
3509  child_rel->top_parent_relids))
3510 
3511 #define REPARAMETERIZE_CHILD_PATH(path) \
3512 do { \
3513  (path) = reparameterize_path_by_child(root, (path), child_rel); \
3514  if ((path) == NULL) \
3515  return NULL; \
3516 } while(0);
3517 
3518 #define REPARAMETERIZE_CHILD_PATH_LIST(pathlist) \
3519 do { \
3520  if ((pathlist) != NIL) \
3521  { \
3522  (pathlist) = reparameterize_pathlist_by_child(root, (pathlist), \
3523  child_rel); \
3524  if ((pathlist) == NIL) \
3525  return NULL; \
3526  } \
3527 } while(0);
3528 
3529  Path *new_path;
3530  ParamPathInfo *new_ppi;
3531  ParamPathInfo *old_ppi;
3532  Relids required_outer;
3533 
3534  /*
3535  * If the path is not parameterized by parent of the given relation, it
3536  * doesn't need reparameterization.
3537  */
3538  if (!path->param_info ||
3539  !bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
3540  return path;
3541 
3542  /* Reparameterize a copy of given path. */
3543  switch (nodeTag(path))
3544  {
3545  case T_Path:
3546  FLAT_COPY_PATH(new_path, path, Path);
3547  break;
3548 
3549  case T_IndexPath:
3550  {
3551  IndexPath *ipath;
3552 
3553  FLAT_COPY_PATH(ipath, path, IndexPath);
3556  new_path = (Path *) ipath;
3557  }
3558  break;
3559 
3560  case T_BitmapHeapPath:
3561  {
3562  BitmapHeapPath *bhpath;
3563 
3564  FLAT_COPY_PATH(bhpath, path, BitmapHeapPath);
3566  new_path = (Path *) bhpath;
3567  }
3568  break;
3569 
3570  case T_BitmapAndPath:
3571  {
3572  BitmapAndPath *bapath;
3573 
3574  FLAT_COPY_PATH(bapath, path, BitmapAndPath);
3576  new_path = (Path *) bapath;
3577  }
3578  break;
3579 
3580  case T_BitmapOrPath:
3581  {
3582  BitmapOrPath *bopath;
3583 
3584  FLAT_COPY_PATH(bopath, path, BitmapOrPath);
3586  new_path = (Path *) bopath;
3587  }
3588  break;
3589 
3590  case T_TidPath:
3591  {
3592  TidPath *tpath;
3593 
3594  /*
3595  * TidPath contains tidquals, which do not contain any
3596  * external parameters per create_tidscan_path(). So don't
3597  * bother to translate those.
3598  */
3599  FLAT_COPY_PATH(tpath, path, TidPath);
3600  new_path = (Path *) tpath;
3601  }
3602  break;
3603 
3604  case T_ForeignPath:
3605  {
3606  ForeignPath *fpath;
3608 
3609  FLAT_COPY_PATH(fpath, path, ForeignPath);
3610  if (fpath->fdw_outerpath)
3612 
3613  /* Hand over to FDW if needed. */
3614  rfpc_func =
3616  if (rfpc_func)
3617  fpath->fdw_private = rfpc_func(root, fpath->fdw_private,
3618  child_rel);
3619  new_path = (Path *) fpath;
3620  }
3621  break;
3622 
3623  case T_CustomPath:
3624  {
3625  CustomPath *cpath;
3626 
3627  FLAT_COPY_PATH(cpath, path, CustomPath);
3629  if (cpath->methods &&
3631  cpath->custom_private =
3633  cpath->custom_private,
3634  child_rel);
3635  new_path = (Path *) cpath;
3636  }
3637  break;
3638 
3639  case T_NestPath:
3640  {
3641  JoinPath *jpath;
3642 
3643  FLAT_COPY_PATH(jpath, path, NestPath);
3644 
3648  new_path = (Path *) jpath;
3649  }
3650  break;
3651 
3652  case T_MergePath:
3653  {
3654  JoinPath *jpath;
3655  MergePath *mpath;
3656 
3657  FLAT_COPY_PATH(mpath, path, MergePath);
3658 
3659  jpath = (JoinPath *) mpath;
3664  new_path = (Path *) mpath;
3665  }
3666  break;
3667 
3668  case T_HashPath:
3669  {
3670  JoinPath *jpath;
3671  HashPath *hpath;
3672 
3673  FLAT_COPY_PATH(hpath, path, HashPath);
3674 
3675  jpath = (JoinPath *) hpath;
3680  new_path = (Path *) hpath;
3681  }
3682  break;
3683 
3684  case T_AppendPath:
3685  {
3686  AppendPath *apath;
3687 
3688  FLAT_COPY_PATH(apath, path, AppendPath);
3690  new_path = (Path *) apath;
3691  }
3692  break;
3693 
3694  case T_MergeAppend:
3695  {
3696  MergeAppendPath *mapath;
3697 
3698  FLAT_COPY_PATH(mapath, path, MergeAppendPath);
3700  new_path = (Path *) mapath;
3701  }
3702  break;
3703 
3704  case T_MaterialPath:
3705  {
3706  MaterialPath *mpath;
3707 
3708  FLAT_COPY_PATH(mpath, path, MaterialPath);
3710  new_path = (Path *) mpath;
3711  }
3712  break;
3713 
3714  case T_UniquePath:
3715  {
3716  UniquePath *upath;
3717 
3718  FLAT_COPY_PATH(upath, path, UniquePath);
3721  new_path = (Path *) upath;
3722  }
3723  break;
3724 
3725  case T_GatherPath:
3726  {
3727  GatherPath *gpath;
3728 
3729  FLAT_COPY_PATH(gpath, path, GatherPath);
3731  new_path = (Path *) gpath;
3732  }
3733  break;
3734 
3735  case T_GatherMergePath:
3736  {
3737  GatherMergePath *gmpath;
3738 
3739  FLAT_COPY_PATH(gmpath, path, GatherMergePath);
3741  new_path = (Path *) gmpath;
3742  }
3743  break;
3744 
3745  default:
3746 
3747  /* We don't know how to reparameterize this path. */
3748  return NULL;
3749  }
3750 
3751  /*
3752  * Adjust the parameterization information, which refers to the topmost
3753  * parent. The topmost parent can be multiple levels away from the given
3754  * child, hence use multi-level expression adjustment routines.
3755  */
3756  old_ppi = new_path->param_info;
3757  required_outer =
3759  child_rel->relids,
3760  child_rel->top_parent_relids);
3761 
3762  /* If we already have a PPI for this parameterization, just return it */
3763  new_ppi = find_param_path_info(new_path->parent, required_outer);
3764 
3765  /*
3766  * If not, build a new one and link it to the list of PPIs. For the same
3767  * reason as explained in mark_dummy_rel(), allocate new PPI in the same
3768  * context the given RelOptInfo is in.
3769  */
3770  if (new_ppi == NULL)
3771  {
3772  MemoryContext oldcontext;
3773  RelOptInfo *rel = path->parent;
3774 
3775  oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
3776 
3777  new_ppi = makeNode(ParamPathInfo);
3778  new_ppi->ppi_req_outer = bms_copy(required_outer);
3779  new_ppi->ppi_rows = old_ppi->ppi_rows;
3780  new_ppi->ppi_clauses = old_ppi->ppi_clauses;
3781  ADJUST_CHILD_ATTRS(new_ppi->ppi_clauses);
3782  rel->ppilist = lappend(rel->ppilist, new_ppi);
3783 
3784  MemoryContextSwitchTo(oldcontext);
3785  }
3786  bms_free(required_outer);
3787 
3788  new_path->param_info = new_ppi;
3789 
3790  /*
3791  * Adjust the path target if the parent of the outer relation is
3792  * referenced in the targetlist. This can happen when only the parent of
3793  * outer relation is laterally referenced in this relation.
3794  */
3795  if (bms_overlap(path->parent->lateral_relids,
3796  child_rel->top_parent_relids))
3797  {
3798  new_path->pathtarget = copy_pathtarget(new_path->pathtarget);
3799  ADJUST_CHILD_ATTRS(new_path->pathtarget->exprs);
3800  }
3801 
3802  return new_path;
3803 }
3804 
3805 /*
3806  * reparameterize_pathlist_by_child
3807  * Helper function to reparameterize a list of paths by given child rel.
3808  */
3809 static List *
3811  List *pathlist,
3812  RelOptInfo *child_rel)
3813 {
3814  ListCell *lc;
3815  List *result = NIL;
3816 
3817  foreach(lc, pathlist)
3818  {
3819  Path *path = reparameterize_path_by_child(root, lfirst(lc),
3820  child_rel);
3821 
3822  if (path == NULL)
3823  {
3824  list_free(result);
3825  return NIL;
3826  }
3827 
3828  result = lappend(result, path);
3829  }
3830 
3831  return result;
3832 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2384
struct Path * cheapest_unique_path
Definition: relation.h:604
List * indexorderbycols
Definition: relation.h:1124
List * group_pathkeys
Definition: relation.h:264
#define NIL
Definition: pg_list.h:69
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:629
void final_cost_hashjoin(PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
Definition: costsize.c:3057
List * qual
Definition: relation.h:1522
bool semi_can_btree
Definition: relation.h:2015
ParamPathInfo * find_param_path_info(RelOptInfo *rel, Relids required_outer)
Definition: relnode.c:1573
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3360
List * path_mergeclauses
Definition: relation.h:1440
List * outersortkeys
Definition: relation.h:1441
List * distinctList
Definition: relation.h:1625
MinMaxAggPath * create_minmaxagg_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *mmaggregates, List *quals)
Definition: pathnode.c:2918
Definition: nodes.h:77
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1744
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
JoinPath jpath
Definition: relation.h:1458
PathTarget * pathtarget
Definition: relation.h:1043
List * returningLists
Definition: relation.h:1674
bool query_is_distinct_for(Query *query, List *colnos, List *opids)
Definition: analyzejoins.c:782
OnConflictExpr * onconflict
Definition: relation.h:1676
void cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
Definition: costsize.c:929
Node * limitOffset
Definition: relation.h:1687
Path * subpath
Definition: relation.h:1534
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:420
Path path
Definition: relation.h:1118
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1783
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:111
Path * subpath
Definition: relation.h:1506
IndexOptInfo * indexinfo
Definition: relation.h:1119
ParamPathInfo * get_baserel_parampathinfo(PlannerInfo *root, RelOptInfo *baserel, Relids required_outer)
Definition: relnode.c:1253
Index nominalRelation
Definition: relation.h:1667
Path * fdw_outerpath
Definition: relation.h:1219
void cost_tidscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
Definition: costsize.c:1165
void cost_windowagg(Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
Definition: costsize.c:1992
List * custom_paths
Definition: relation.h:1249
Definition: nodes.h:79
SetOpStrategy strategy
Definition: relation.h:1624
AggStrategy aggstrategy
Definition: relation.h:1549
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition: pathnode.c:3161
void cost_gather_merge(GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, Cost input_startup_cost, Cost input_total_cost, double *rows)
Definition: costsize.c:388
SetOpPath * create_setop_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, SetOpCmd cmd, SetOpStrategy strategy, List *distinctList, AttrNumber flagColIdx, int firstFlag, double numGroups, double outputRows)
Definition: pathnode.c:3054
ParamPathInfo * get_joinrel_parampathinfo(PlannerInfo *root, RelOptInfo *joinrel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, Relids required_outer, List **restrict_clauses)
Definition: relnode.c:1340
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2974
List * qual
Definition: relation.h:1553
double expression_returns_set_rows(Node *clause)
Definition: clauses.c:802
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:2643
void cost_agg(Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
Definition: costsize.c:1874
bool add_partial_path_precheck(RelOptInfo *parent_rel, Cost total_cost, List *pathkeys)
Definition: pathnode.c:884
bool add_path_precheck(RelOptInfo *parent_rel, Cost startup_cost, Cost total_cost, List *pathkeys, Relids required_outer)
Definition: pathnode.c:655
Path * innerjoinpath
Definition: relation.h:1385
void cost_namedtuplestorescan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1525
struct Path * cheapest_startup_path
Definition: relation.h:602
double tuples
Definition: relation.h:625
Path * subpath
Definition: relation.h:1622
List * rowMarks
Definition: relation.h:1675
BitmapOrPath * create_bitmap_or_path(PlannerInfo *root, RelOptInfo *rel, List *bitmapquals)
Definition: pathnode.c:1144
int parallel_workers
Definition: relation.h:1049
bool consider_param_startup
Definition: relation.h:592
void cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
Definition: costsize.c:1073
MaterialPath * create_material_path(RelOptInfo *rel, Path *subpath)
Definition: pathnode.c:1401
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
struct List *(* ReparameterizeCustomPathByChild)(PlannerInfo *root, List *custom_private, RelOptInfo *child_rel)
Definition: extensible.h:99
bool is_hashed
Definition: relation.h:1575
ParamPathInfo * param_info
Definition: relation.h:1045
Relids calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
Definition: pathnode.c:2043
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:510
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2293
Definition: nodes.h:48
List * partial_pathlist
Definition: relation.h:601
AttrNumber varattno
Definition: primnodes.h:168
void cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1434
IndexPath * create_index_path(PlannerInfo *root, IndexOptInfo *index, List *indexclauses, List *indexclausecols, List *indexorderbys, List *indexorderbycols, List *pathkeys, ScanDirection indexscandir, bool indexonly, Relids required_outer, double loop_count, bool partial_path)
Definition: pathnode.c:1016
void cost_ctescan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1484
List * cheapest_parameterized_paths
Definition: relation.h:605
bool single_copy
Definition: relation.h:1354
UniquePathMethod umethod
Definition: relation.h:1340
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:278
Definition: nodes.h:75
UniquePath * create_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, SpecialJoinInfo *sjinfo)
Definition: pathnode.c:1440
Path * subpath
Definition: relation.h:1314
List * indexclauses
Definition: relation.h:1120
AggSplit aggsplit
Definition: relation.h:1550
List * partitioned_rels
Definition: relation.h:1287
MergePath * create_mergejoin_path(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, JoinCostWorkspace *workspace, JoinPathExtraData *extra, Path *outer_path, Path *inner_path, List *restrict_clauses, List *pathkeys, Relids required_outer, List *mergeclauses, List *outersortkeys, List *innersortkeys)
Definition: pathnode.c:2164
List * quals
Definition: relation.h:1598
Definition: primnodes.h:163
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers, List *partitioned_rels)
Definition: pathnode.c:1211
LimitPath * create_limit_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, Node *limitOffset, Node *limitCount, int64 offset_est, int64 count_est)
Definition: pathnode.c:3320
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1811
double numGroups
Definition: relation.h:1551
double numGroups
Definition: relation.h:1628
SetOpStrategy
Definition: nodes.h:788
#define ADJUST_CHILD_ATTRS(node)
List * rowMarks
Definition: relation.h:1651
List * winpathkeys
Definition: relation.h:1613
double numGroups
Definition: relation.h:1573
Cost startup
Definition: relation.h:45
List * bitmapquals
Definition: relation.h:1162
Path path
Definition: relation.h:1265
List * custom_private
Definition: relation.h:1250
JoinType
Definition: nodes.h:674
WindowClause * winclause
Definition: relation.h:1612
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1863
List * bitmapquals
Definition: relation.h:1175
int num_workers
Definition: relation.h:1355
Definition: type.h:89
NodeTag pathtype
Definition: relation.h:1040
Relids syn_righthand
Definition: relation.h:2010
List * subpaths
Definition: relation.h:1268
SetOpCmd cmd
Definition: relation.h:1623
void final_cost_nestloop(PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
Definition: costsize.c:2207
ListCell * lappend_cell(List *list, ListCell *prev, void *datum)
Definition: list.c:209
static List * reparameterize_pathlist_by_child(PlannerInfo *root, List *pathlist, RelOptInfo *child_rel)
Definition: pathnode.c:3810
#define true
Definition: c.h:251
bool consider_startup
Definition: relation.h:591
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1087
void cost_seqscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:198
Relids lateral_relids
Definition: relation.h:610
Relids adjust_child_relids_multilevel(PlannerInfo *root, Relids relids, Relids child_relids, Relids top_parent_relids)
Definition: prepunion.c:2280
Cost per_tuple
Definition: relation.h:46
GroupingSetsPath * create_groupingsets_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *having_qual, AggStrategy aggstrategy, List *rollups, const AggClauseCosts *agg_costs, double numGroups)
Definition: pathnode.c:2761
const struct CustomPathMethods * methods
Definition: relation.h:1251
List * indexquals
Definition: relation.h:1121
Path * subpath
Definition: relation.h:1611
void pfree(void *pointer)
Definition: mcxt.c:949
RelOptInfo * rel
Definition: relation.h:721
SpecialJoinInfo * sjinfo
Definition: relation.h:2273
Path path
Definition: relation.h:1301
#define linitial(l)
Definition: pg_list.h:111
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
Definition: nodes.h:45
Relids all_baserels
Definition: relation.h:196
#define ERROR
Definition: elog.h:43
static List * translate_sub_tlist(List *tlist, int relid)
Definition: pathnode.c:1718
double limit_tuples
Definition: relation.h:295
List * partitionClause
Definition: parsenodes.h:1289
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3508
void expand_indexqual_conditions(IndexOptInfo *index, List *indexclauses, List *indexclausecols, List **indexquals_p, List **indexqualcols_p)
Definition: indxpath.c:3526
Cost startup_cost
Definition: relation.h:1053
RecursiveUnionPath * create_recursiveunion_path(PlannerInfo *root, RelOptInfo *rel, Path *leftpath, Path *rightpath, PathTarget *target, List *distinctList, int wtParam, double numGroups)
Definition: pathnode.c:3116
List * semi_rhs_exprs
Definition: relation.h:2018
void cost_subqueryscan(SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1268
void cost_group(Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
Definition: costsize.c:2062
bool semi_can_hash
Definition: relation.h:2016
Path * subpath
Definition: relation.h:1686
List * joinrestrictinfo
Definition: relation.h:1387
List * subroots
Definition: relation.h:1672
RelOptInfo * parent
Definition: relation.h:1042
List * uniq_exprs
Definition: relation.h:1342
Path * reparameterize_path_by_child(PlannerInfo *root, Path *path, RelOptInfo *child_rel)
Definition: pathnode.c:3497
Path * bitmapqual
Definition: relation.h:1150
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
Definition: nodes.h:76
Path path
Definition: relation.h:1519
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:69
NestPath * create_nestloop_path(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, JoinCostWorkspace *workspace, JoinPathExtraData *extra, Path *outer_path, Path *inner_path, List *restrict_clauses, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2076
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition: pathnode.c:2695
struct Path * cheapest_total_path
Definition: relation.h:603
ForeignPath * create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, double rows, Cost startup_cost, Cost total_cost, List *pathkeys, Relids required_outer, Path *fdw_outerpath, List *fdw_private)
Definition: pathnode.c:1974
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2473
struct FdwRoutine * fdwroutine
Definition: relation.h:636
static PathCostComparison compare_path_costs_fuzzily(Path *path1, Path *path2, double fuzz_factor)
Definition: pathnode.c:164
ScanDirection
Definition: sdir.h:22
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2584
List * subpaths
Definition: relation.h:1671
List * groupClause
Definition: relation.h:1552
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
AttrNumber flagColIdx
Definition: relation.h:1626
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer, List *partitioned_rels)
Definition: pathnode.c:1265
Relids relids
Definition: relation.h:585
AggStrategy aggstrategy
Definition: relation.h:1586
double cpu_operator_cost
Definition: costsize.c:108
Path * subpath
Definition: relation.h:1353
double rint(double x)
Definition: rint.c:22
void cost_samplescan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:275
#define lnext(lc)
Definition: pg_list.h:105
bool join_clause_is_movable_into(RestrictInfo *rinfo, Relids currentrelids, Relids current_and_outer)
Definition: restrictinfo.c:510
List * ppilist
Definition: relation.h:600
List * lappend_int(List *list, int datum)
Definition: list.c:146
Index relid
Definition: relation.h:613
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1940
List * lappend(List *list, void *datum)
Definition: list.c:128
Path * subpath
Definition: relation.h:1650
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
#define FLAT_COPY_PATH(newnode, node, nodetype)
Index varno
Definition: primnodes.h:166
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:242
List * exprs
Definition: relation.h:972
#define REPARAMETERIZE_CHILD_PATH(path)
BitmapAndPath * create_bitmap_and_path(PlannerInfo *root, RelOptInfo *rel, List *bitmapquals)
Definition: pathnode.c:1108
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
Path * outerjoinpath
Definition: relation.h:1384
void cost_index(IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
Definition: costsize.c:463
List * indexorderbys
Definition: relation.h:1123
void cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
Definition: costsize.c:1565
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause, List *winpathkeys)
Definition: pathnode.c:2990
Path * create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:971
List * groupClause
Definition: relation.h:1521
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1837
List * mmaggregates
Definition: relation.h:1597
List * partitioned_rels
Definition: relation.h:1669
List * tidquals
Definition: relation.h:1189
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1645
int work_mem
Definition: globals.c:113
Path * subpath
Definition: relation.h:1520
#define REPARAMETERIZE_CHILD_PATH_LIST(pathlist)
unsigned int Index
Definition: c.h:413
RTEKind rtekind
Definition: relation.h:615
PathCostComparison
Definition: pathnode.c:38
List * in_operators
Definition: relation.h:1341
double rows
Definition: relation.h:588
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1653
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2540
BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:345
Cost total_cost
Definition: relation.h:1054
void cost_material(Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
Definition: costsize.c:1820
int firstFlag
Definition: relation.h:1627
List * lcons(void *datum, List *list)
Definition: list.c:259
List * pathkeys
Definition: relation.h:1056
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define makeNode(_type_)
Definition: nodes.h:558
void cost_tablefuncscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1378
void cost_merge_append(Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
Definition: costsize.c:1769
#define CONSIDER_PATH_STARTUP_COST(p)
Path path
Definition: relation.h:1377
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
Path * subpath
Definition: relation.h:1492
double rows
Definition: relation.h:1052
bool parallel_safe
Definition: relation.h:1048
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, CmdType operation, bool canSetTag, Index nominalRelation, List *partitioned_rels, List *resultRelations, List *subpaths, List *subroots, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: pathnode.c:3220
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:115
List * quals
Definition: relation.h:1302
#define PATH_REQ_OUTER(path)
Definition: relation.h:1061
JoinType jointype
Definition: relation.h:2011
List * ppi_clauses
Definition: relation.h:1003
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
#define STD_FUZZ_FACTOR
Definition: pathnode.c:51
QualCost cost
Definition: relation.h:974
AggSplit
Definition: nodes.h:758
static int list_length(const List *l)
Definition: pg_list.h:89
Relids calc_nestloop_required_outer(Relids outerrelids, Relids outer_paramrels, Relids innerrelids, Relids inner_paramrels)
Definition: pathnode.c:2010
CostSelector
Definition: relation.h:34
bool inner_unique
Definition: relation.h:1381
bool consider_parallel
Definition: relation.h:593
List * innersortkeys
Definition: relation.h:1442
double cpu_tuple_cost
Definition: costsize.c:106
Path * subpath
Definition: relation.h:1548
bool query_supports_distinctness(Query *query)
Definition: analyzejoins.c:745
List * partitioned_rels
Definition: relation.h:1267
void cost_gather(GatherPath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, double *rows)
Definition: costsize.c:350
#define nodeTag(nodeptr)
Definition: nodes.h:515
Path * subpath
Definition: relation.h:1366
double ppi_rows
Definition: relation.h:1002
Path path
Definition: relation.h:1685
Path path
Definition: relation.h:1188
List * withCheckOptionLists
Definition: relation.h:1673
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:817
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:443
List * indexqualcols
Definition: relation.h:1122
Definition: nodes.h:83
List * orderClause
Definition: parsenodes.h:1290
PathKeysComparison
Definition: paths.h:181
int width
Definition: relation.h:975
Query * subquery
Definition: parsenodes.h:974
AggStrategy
Definition: nodes.h:736
bool is_projection_capable_path(Path *path)
Definition: createplan.c:6569
TidPath * create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals, Relids required_outer)
Definition: pathnode.c:1180
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3418
HashPath * create_hashjoin_path(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, JoinCostWorkspace *workspace, JoinPathExtraData *extra, Path *outer_path, Path *inner_path, List *restrict_clauses, Relids required_outer, List *hashclauses)
Definition: pathnode.c:2229
void cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1317
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:760
List * fdw_private
Definition: relation.h:1220
SetOpCmd
Definition: nodes.h:780
JoinType jointype
Definition: relation.h:1379
List * semi_operators
Definition: relation.h:2017
ScanDirection indexscandir
Definition: relation.h:1125
CmdType operation
Definition: relation.h:1665
void list_free(List *list)
Definition: list.c:1133
Definition: nodes.h:80
List * resultRelations
Definition: relation.h:1670
void cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
Definition: costsize.c:1117
JoinPath jpath
Definition: relation.h:1439
ResultPath * create_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *resconstantqual)
Definition: pathnode.c:1357
bool parallel_aware
Definition: relation.h:1047
List * path_hashclauses
Definition: relation.h:1459
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
List *(* ReparameterizeForeignPathByChild_function)(PlannerInfo *root, List *fdw_private, RelOptInfo *child_rel)
Definition: fdwapi.h:161
List * pathlist
Definition: relation.h:599
List * subpaths
Definition: relation.h:1288
Relids ppi_req_outer
Definition: relation.h:1001
MemoryContext planner_cxt
Definition: relation.h:290
#define elog
Definition: elog.h:219
ParamPathInfo * get_appendrel_parampathinfo(RelOptInfo *appendrel, Relids required_outer)
Definition: relnode.c:1544
bool relation_has_unique_index_for(PlannerInfo *root, RelOptInfo *rel, List *restrictlist, List *exprlist, List *oprlist)
Definition: indxpath.c:2960
Path * subpath
Definition: relation.h:1480
Path path
Definition: relation.h:1352
Definition: nodes.h:221
double clamp_row_est(double nrows)
Definition: costsize.c:174
Node * limitCount
Definition: relation.h:1688
Definition: pg_list.h:45
Path path
Definition: relation.h:1505
struct PathTarget * reltarget
Definition: relation.h:596
int16 AttrNumber
Definition: attnum.h:21
Path path
Definition: relation.h:1621
Path path
Definition: relation.h:1338
CmdType
Definition: nodes.h:650
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:946
Path path
Definition: relation.h:1547
double limit_tuples
Definition: relation.h:1289
BMS_Comparison
Definition: bitmapset.h:45
double Cost
Definition: nodes.h:641
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:131
Relids top_parent_relids
Definition: relation.h:654
static MemoryContext GetMemoryChunkContext(void *pointer)
Definition: memutils.h:107
void final_cost_mergejoin(PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
Definition: costsize.c:2644
List * gsets
Definition: relation.h:1571
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:742
Path * subpath
Definition: relation.h:1339
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1075
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1914
Definition: nodes.h:85
ReparameterizeForeignPathByChild_function ReparameterizeForeignPathByChild
Definition: fdwapi.h:238
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1889