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