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_fractional_path_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, bool binary_mode, 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->binary_mode = binary_mode;
1607  pathnode->calls = calls;
1608 
1609  /*
1610  * For now we set est_entries to 0. cost_memoize_rescan() does all the
1611  * hard work to determine how many cache entries there are likely to be,
1612  * so it seems best to leave it up to that function to fill this field in.
1613  * If left at 0, the executor will make a guess at a good value.
1614  */
1615  pathnode->est_entries = 0;
1616 
1617  /*
1618  * Add a small additional charge for caching the first entry. All the
1619  * harder calculations for rescans are performed in cost_memoize_rescan().
1620  */
1621  pathnode->path.startup_cost = subpath->startup_cost + cpu_tuple_cost;
1622  pathnode->path.total_cost = subpath->total_cost + cpu_tuple_cost;
1623  pathnode->path.rows = subpath->rows;
1624 
1625  return pathnode;
1626 }
1627 
1628 /*
1629  * create_unique_path
1630  * Creates a path representing elimination of distinct rows from the
1631  * input data. Distinct-ness is defined according to the needs of the
1632  * semijoin represented by sjinfo. If it is not possible to identify
1633  * how to make the data unique, NULL is returned.
1634  *
1635  * If used at all, this is likely to be called repeatedly on the same rel;
1636  * and the input subpath should always be the same (the cheapest_total path
1637  * for the rel). So we cache the result.
1638  */
1639 UniquePath *
1641  SpecialJoinInfo *sjinfo)
1642 {
1643  UniquePath *pathnode;
1644  Path sort_path; /* dummy for result of cost_sort */
1645  Path agg_path; /* dummy for result of cost_agg */
1646  MemoryContext oldcontext;
1647  int numCols;
1648 
1649  /* Caller made a mistake if subpath isn't cheapest_total ... */
1651  Assert(subpath->parent == rel);
1652  /* ... or if SpecialJoinInfo is the wrong one */
1653  Assert(sjinfo->jointype == JOIN_SEMI);
1654  Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
1655 
1656  /* If result already cached, return it */
1657  if (rel->cheapest_unique_path)
1658  return (UniquePath *) rel->cheapest_unique_path;
1659 
1660  /* If it's not possible to unique-ify, return NULL */
1661  if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
1662  return NULL;
1663 
1664  /*
1665  * When called during GEQO join planning, we are in a short-lived memory
1666  * context. We must make sure that the path and any subsidiary data
1667  * structures created for a baserel survive the GEQO cycle, else the
1668  * baserel is trashed for future GEQO cycles. On the other hand, when we
1669  * are creating those for a joinrel during GEQO, we don't want them to
1670  * clutter the main planning context. Upshot is that the best solution is
1671  * to explicitly allocate memory in the same context the given RelOptInfo
1672  * is in.
1673  */
1674  oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
1675 
1676  pathnode = makeNode(UniquePath);
1677 
1678  pathnode->path.pathtype = T_Unique;
1679  pathnode->path.parent = rel;
1680  pathnode->path.pathtarget = rel->reltarget;
1681  pathnode->path.param_info = subpath->param_info;
1682  pathnode->path.parallel_aware = false;
1683  pathnode->path.parallel_safe = rel->consider_parallel &&
1684  subpath->parallel_safe;
1685  pathnode->path.parallel_workers = subpath->parallel_workers;
1686 
1687  /*
1688  * Assume the output is unsorted, since we don't necessarily have pathkeys
1689  * to represent it. (This might get overridden below.)
1690  */
1691  pathnode->path.pathkeys = NIL;
1692 
1693  pathnode->subpath = subpath;
1694  pathnode->in_operators = sjinfo->semi_operators;
1695  pathnode->uniq_exprs = sjinfo->semi_rhs_exprs;
1696 
1697  /*
1698  * If the input is a relation and it has a unique index that proves the
1699  * semi_rhs_exprs are unique, then we don't need to do anything. Note
1700  * that relation_has_unique_index_for automatically considers restriction
1701  * clauses for the rel, as well.
1702  */
1703  if (rel->rtekind == RTE_RELATION && sjinfo->semi_can_btree &&
1705  sjinfo->semi_rhs_exprs,
1706  sjinfo->semi_operators))
1707  {
1708  pathnode->umethod = UNIQUE_PATH_NOOP;
1709  pathnode->path.rows = rel->rows;
1710  pathnode->path.startup_cost = subpath->startup_cost;
1711  pathnode->path.total_cost = subpath->total_cost;
1712  pathnode->path.pathkeys = subpath->pathkeys;
1713 
1714  rel->cheapest_unique_path = (Path *) pathnode;
1715 
1716  MemoryContextSwitchTo(oldcontext);
1717 
1718  return pathnode;
1719  }
1720 
1721  /*
1722  * If the input is a subquery whose output must be unique already, then we
1723  * don't need to do anything. The test for uniqueness has to consider
1724  * exactly which columns we are extracting; for example "SELECT DISTINCT
1725  * x,y" doesn't guarantee that x alone is distinct. So we cannot check for
1726  * this optimization unless semi_rhs_exprs consists only of simple Vars
1727  * referencing subquery outputs. (Possibly we could do something with
1728  * expressions in the subquery outputs, too, but for now keep it simple.)
1729  */
1730  if (rel->rtekind == RTE_SUBQUERY)
1731  {
1732  RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1733 
1735  {
1736  List *sub_tlist_colnos;
1737 
1738  sub_tlist_colnos = translate_sub_tlist(sjinfo->semi_rhs_exprs,
1739  rel->relid);
1740 
1741  if (sub_tlist_colnos &&
1743  sub_tlist_colnos,
1744  sjinfo->semi_operators))
1745  {
1746  pathnode->umethod = UNIQUE_PATH_NOOP;
1747  pathnode->path.rows = rel->rows;
1748  pathnode->path.startup_cost = subpath->startup_cost;
1749  pathnode->path.total_cost = subpath->total_cost;
1750  pathnode->path.pathkeys = subpath->pathkeys;
1751 
1752  rel->cheapest_unique_path = (Path *) pathnode;
1753 
1754  MemoryContextSwitchTo(oldcontext);
1755 
1756  return pathnode;
1757  }
1758  }
1759  }
1760 
1761  /* Estimate number of output rows */
1762  pathnode->path.rows = estimate_num_groups(root,
1763  sjinfo->semi_rhs_exprs,
1764  rel->rows,
1765  NULL,
1766  NULL);
1767  numCols = list_length(sjinfo->semi_rhs_exprs);
1768 
1769  if (sjinfo->semi_can_btree)
1770  {
1771  /*
1772  * Estimate cost for sort+unique implementation
1773  */
1774  cost_sort(&sort_path, root, NIL,
1775  subpath->total_cost,
1776  rel->rows,
1777  subpath->pathtarget->width,
1778  0.0,
1779  work_mem,
1780  -1.0);
1781 
1782  /*
1783  * Charge one cpu_operator_cost per comparison per input tuple. We
1784  * assume all columns get compared at most of the tuples. (XXX
1785  * probably this is an overestimate.) This should agree with
1786  * create_upper_unique_path.
1787  */
1788  sort_path.total_cost += cpu_operator_cost * rel->rows * numCols;
1789  }
1790 
1791  if (sjinfo->semi_can_hash)
1792  {
1793  /*
1794  * Estimate the overhead per hashtable entry at 64 bytes (same as in
1795  * planner.c).
1796  */
1797  int hashentrysize = subpath->pathtarget->width + 64;
1798 
1799  if (hashentrysize * pathnode->path.rows > get_hash_memory_limit())
1800  {
1801  /*
1802  * We should not try to hash. Hack the SpecialJoinInfo to
1803  * remember this, in case we come through here again.
1804  */
1805  sjinfo->semi_can_hash = false;
1806  }
1807  else
1808  cost_agg(&agg_path, root,
1809  AGG_HASHED, NULL,
1810  numCols, pathnode->path.rows,
1811  NIL,
1812  subpath->startup_cost,
1813  subpath->total_cost,
1814  rel->rows,
1815  subpath->pathtarget->width);
1816  }
1817 
1818  if (sjinfo->semi_can_btree && sjinfo->semi_can_hash)
1819  {
1820  if (agg_path.total_cost < sort_path.total_cost)
1821  pathnode->umethod = UNIQUE_PATH_HASH;
1822  else
1823  pathnode->umethod = UNIQUE_PATH_SORT;
1824  }
1825  else if (sjinfo->semi_can_btree)
1826  pathnode->umethod = UNIQUE_PATH_SORT;
1827  else if (sjinfo->semi_can_hash)
1828  pathnode->umethod = UNIQUE_PATH_HASH;
1829  else
1830  {
1831  /* we can get here only if we abandoned hashing above */
1832  MemoryContextSwitchTo(oldcontext);
1833  return NULL;
1834  }
1835 
1836  if (pathnode->umethod == UNIQUE_PATH_HASH)
1837  {
1838  pathnode->path.startup_cost = agg_path.startup_cost;
1839  pathnode->path.total_cost = agg_path.total_cost;
1840  }
1841  else
1842  {
1843  pathnode->path.startup_cost = sort_path.startup_cost;
1844  pathnode->path.total_cost = sort_path.total_cost;
1845  }
1846 
1847  rel->cheapest_unique_path = (Path *) pathnode;
1848 
1849  MemoryContextSwitchTo(oldcontext);
1850 
1851  return pathnode;
1852 }
1853 
1854 /*
1855  * create_gather_merge_path
1856  *
1857  * Creates a path corresponding to a gather merge scan, returning
1858  * the pathnode.
1859  */
1862  PathTarget *target, List *pathkeys,
1863  Relids required_outer, double *rows)
1864 {
1866  Cost input_startup_cost = 0;
1867  Cost input_total_cost = 0;
1868 
1869  Assert(subpath->parallel_safe);
1870  Assert(pathkeys);
1871 
1872  pathnode->path.pathtype = T_GatherMerge;
1873  pathnode->path.parent = rel;
1874  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1875  required_outer);
1876  pathnode->path.parallel_aware = false;
1877 
1878  pathnode->subpath = subpath;
1879  pathnode->num_workers = subpath->parallel_workers;
1880  pathnode->path.pathkeys = pathkeys;
1881  pathnode->path.pathtarget = target ? target : rel->reltarget;
1882  pathnode->path.rows += subpath->rows;
1883 
1884  if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1885  {
1886  /* Subpath is adequately ordered, we won't need to sort it */
1887  input_startup_cost += subpath->startup_cost;
1888  input_total_cost += subpath->total_cost;
1889  }
1890  else
1891  {
1892  /* We'll need to insert a Sort node, so include cost for that */
1893  Path sort_path; /* dummy for result of cost_sort */
1894 
1895  cost_sort(&sort_path,
1896  root,
1897  pathkeys,
1898  subpath->total_cost,
1899  subpath->rows,
1900  subpath->pathtarget->width,
1901  0.0,
1902  work_mem,
1903  -1);
1904  input_startup_cost += sort_path.startup_cost;
1905  input_total_cost += sort_path.total_cost;
1906  }
1907 
1908  cost_gather_merge(pathnode, root, rel, pathnode->path.param_info,
1909  input_startup_cost, input_total_cost, rows);
1910 
1911  return pathnode;
1912 }
1913 
1914 /*
1915  * translate_sub_tlist - get subquery column numbers represented by tlist
1916  *
1917  * The given targetlist usually contains only Vars referencing the given relid.
1918  * Extract their varattnos (ie, the column numbers of the subquery) and return
1919  * as an integer List.
1920  *
1921  * If any of the tlist items is not a simple Var, we cannot determine whether
1922  * the subquery's uniqueness condition (if any) matches ours, so punt and
1923  * return NIL.
1924  */
1925 static List *
1926 translate_sub_tlist(List *tlist, int relid)
1927 {
1928  List *result = NIL;
1929  ListCell *l;
1930 
1931  foreach(l, tlist)
1932  {
1933  Var *var = (Var *) lfirst(l);
1934 
1935  if (!var || !IsA(var, Var) ||
1936  var->varno != relid)
1937  return NIL; /* punt */
1938 
1939  result = lappend_int(result, var->varattno);
1940  }
1941  return result;
1942 }
1943 
1944 /*
1945  * create_gather_path
1946  * Creates a path corresponding to a gather scan, returning the
1947  * pathnode.
1948  *
1949  * 'rows' may optionally be set to override row estimates from other sources.
1950  */
1951 GatherPath *
1953  PathTarget *target, Relids required_outer, double *rows)
1954 {
1955  GatherPath *pathnode = makeNode(GatherPath);
1956 
1957  Assert(subpath->parallel_safe);
1958 
1959  pathnode->path.pathtype = T_Gather;
1960  pathnode->path.parent = rel;
1961  pathnode->path.pathtarget = target;
1962  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1963  required_outer);
1964  pathnode->path.parallel_aware = false;
1965  pathnode->path.parallel_safe = false;
1966  pathnode->path.parallel_workers = 0;
1967  pathnode->path.pathkeys = NIL; /* Gather has unordered result */
1968 
1969  pathnode->subpath = subpath;
1970  pathnode->num_workers = subpath->parallel_workers;
1971  pathnode->single_copy = false;
1972 
1973  if (pathnode->num_workers == 0)
1974  {
1975  pathnode->path.pathkeys = subpath->pathkeys;
1976  pathnode->num_workers = 1;
1977  pathnode->single_copy = true;
1978  }
1979 
1980  cost_gather(pathnode, root, rel, pathnode->path.param_info, rows);
1981 
1982  return pathnode;
1983 }
1984 
1985 /*
1986  * create_subqueryscan_path
1987  * Creates a path corresponding to a scan of a subquery,
1988  * returning the pathnode.
1989  */
1992  List *pathkeys, Relids required_outer)
1993 {
1995 
1996  pathnode->path.pathtype = T_SubqueryScan;
1997  pathnode->path.parent = rel;
1998  pathnode->path.pathtarget = rel->reltarget;
1999  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
2000  required_outer);
2001  pathnode->path.parallel_aware = false;
2002  pathnode->path.parallel_safe = rel->consider_parallel &&
2003  subpath->parallel_safe;
2004  pathnode->path.parallel_workers = subpath->parallel_workers;
2005  pathnode->path.pathkeys = pathkeys;
2006  pathnode->subpath = subpath;
2007 
2008  cost_subqueryscan(pathnode, root, rel, pathnode->path.param_info);
2009 
2010  return pathnode;
2011 }
2012 
2013 /*
2014  * create_functionscan_path
2015  * Creates a path corresponding to a sequential scan of a function,
2016  * returning the pathnode.
2017  */
2018 Path *
2020  List *pathkeys, Relids required_outer)
2021 {
2022  Path *pathnode = makeNode(Path);
2023 
2024  pathnode->pathtype = T_FunctionScan;
2025  pathnode->parent = rel;
2026  pathnode->pathtarget = rel->reltarget;
2027  pathnode->param_info = get_baserel_parampathinfo(root, rel,
2028  required_outer);
2029  pathnode->parallel_aware = false;
2030  pathnode->parallel_safe = rel->consider_parallel;
2031  pathnode->parallel_workers = 0;
2032  pathnode->pathkeys = pathkeys;
2033 
2034  cost_functionscan(pathnode, root, rel, pathnode->param_info);
2035 
2036  return pathnode;
2037 }
2038 
2039 /*
2040  * create_tablefuncscan_path
2041  * Creates a path corresponding to a sequential scan of a table function,
2042  * returning the pathnode.
2043  */
2044 Path *
2046  Relids required_outer)
2047 {
2048  Path *pathnode = makeNode(Path);
2049 
2050  pathnode->pathtype = T_TableFuncScan;
2051  pathnode->parent = rel;
2052  pathnode->pathtarget = rel->reltarget;
2053  pathnode->param_info = get_baserel_parampathinfo(root, rel,
2054  required_outer);
2055  pathnode->parallel_aware = false;
2056  pathnode->parallel_safe = rel->consider_parallel;
2057  pathnode->parallel_workers = 0;
2058  pathnode->pathkeys = NIL; /* result is always unordered */
2059 
2060  cost_tablefuncscan(pathnode, root, rel, pathnode->param_info);
2061 
2062  return pathnode;
2063 }
2064 
2065 /*
2066  * create_valuesscan_path
2067  * Creates a path corresponding to a scan of a VALUES list,
2068  * returning the pathnode.
2069  */
2070 Path *
2072  Relids required_outer)
2073 {
2074  Path *pathnode = makeNode(Path);
2075 
2076  pathnode->pathtype = T_ValuesScan;
2077  pathnode->parent = rel;
2078  pathnode->pathtarget = rel->reltarget;
2079  pathnode->param_info = get_baserel_parampathinfo(root, rel,
2080  required_outer);
2081  pathnode->parallel_aware = false;
2082  pathnode->parallel_safe = rel->consider_parallel;
2083  pathnode->parallel_workers = 0;
2084  pathnode->pathkeys = NIL; /* result is always unordered */
2085 
2086  cost_valuesscan(pathnode, root, rel, pathnode->param_info);
2087 
2088  return pathnode;
2089 }
2090 
2091 /*
2092  * create_ctescan_path
2093  * Creates a path corresponding to a scan of a non-self-reference CTE,
2094  * returning the pathnode.
2095  */
2096 Path *
2097 create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
2098 {
2099  Path *pathnode = makeNode(Path);
2100 
2101  pathnode->pathtype = T_CteScan;
2102  pathnode->parent = rel;
2103  pathnode->pathtarget = rel->reltarget;
2104  pathnode->param_info = get_baserel_parampathinfo(root, rel,
2105  required_outer);
2106  pathnode->parallel_aware = false;
2107  pathnode->parallel_safe = rel->consider_parallel;
2108  pathnode->parallel_workers = 0;
2109  pathnode->pathkeys = NIL; /* XXX for now, result is always unordered */
2110 
2111  cost_ctescan(pathnode, root, rel, pathnode->param_info);
2112 
2113  return pathnode;
2114 }
2115 
2116 /*
2117  * create_namedtuplestorescan_path
2118  * Creates a path corresponding to a scan of a named tuplestore, returning
2119  * the pathnode.
2120  */
2121 Path *
2123  Relids required_outer)
2124 {
2125  Path *pathnode = makeNode(Path);
2126 
2127  pathnode->pathtype = T_NamedTuplestoreScan;
2128  pathnode->parent = rel;
2129  pathnode->pathtarget = rel->reltarget;
2130  pathnode->param_info = get_baserel_parampathinfo(root, rel,
2131  required_outer);
2132  pathnode->parallel_aware = false;
2133  pathnode->parallel_safe = rel->consider_parallel;
2134  pathnode->parallel_workers = 0;
2135  pathnode->pathkeys = NIL; /* result is always unordered */
2136 
2137  cost_namedtuplestorescan(pathnode, root, rel, pathnode->param_info);
2138 
2139  return pathnode;
2140 }
2141 
2142 /*
2143  * create_resultscan_path
2144  * Creates a path corresponding to a scan of an RTE_RESULT relation,
2145  * returning the pathnode.
2146  */
2147 Path *
2149  Relids required_outer)
2150 {
2151  Path *pathnode = makeNode(Path);
2152 
2153  pathnode->pathtype = T_Result;
2154  pathnode->parent = rel;
2155  pathnode->pathtarget = rel->reltarget;
2156  pathnode->param_info = get_baserel_parampathinfo(root, rel,
2157  required_outer);
2158  pathnode->parallel_aware = false;
2159  pathnode->parallel_safe = rel->consider_parallel;
2160  pathnode->parallel_workers = 0;
2161  pathnode->pathkeys = NIL; /* result is always unordered */
2162 
2163  cost_resultscan(pathnode, root, rel, pathnode->param_info);
2164 
2165  return pathnode;
2166 }
2167 
2168 /*
2169  * create_worktablescan_path
2170  * Creates a path corresponding to a scan of a self-reference CTE,
2171  * returning the pathnode.
2172  */
2173 Path *
2175  Relids required_outer)
2176 {
2177  Path *pathnode = makeNode(Path);
2178 
2179  pathnode->pathtype = T_WorkTableScan;
2180  pathnode->parent = rel;
2181  pathnode->pathtarget = rel->reltarget;
2182  pathnode->param_info = get_baserel_parampathinfo(root, rel,
2183  required_outer);
2184  pathnode->parallel_aware = false;
2185  pathnode->parallel_safe = rel->consider_parallel;
2186  pathnode->parallel_workers = 0;
2187  pathnode->pathkeys = NIL; /* result is always unordered */
2188 
2189  /* Cost is the same as for a regular CTE scan */
2190  cost_ctescan(pathnode, root, rel, pathnode->param_info);
2191 
2192  return pathnode;
2193 }
2194 
2195 /*
2196  * create_foreignscan_path
2197  * Creates a path corresponding to a scan of a foreign base table,
2198  * returning the pathnode.
2199  *
2200  * This function is never called from core Postgres; rather, it's expected
2201  * to be called by the GetForeignPaths function of a foreign data wrapper.
2202  * We make the FDW supply all fields of the path, since we do not have any way
2203  * to calculate them in core. However, there is a usually-sane default for
2204  * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2205  */
2206 ForeignPath *
2208  PathTarget *target,
2209  double rows, Cost startup_cost, Cost total_cost,
2210  List *pathkeys,
2211  Relids required_outer,
2212  Path *fdw_outerpath,
2213  List *fdw_private)
2214 {
2215  ForeignPath *pathnode = makeNode(ForeignPath);
2216 
2217  /* Historically some FDWs were confused about when to use this */
2218  Assert(IS_SIMPLE_REL(rel));
2219 
2220  pathnode->path.pathtype = T_ForeignScan;
2221  pathnode->path.parent = rel;
2222  pathnode->path.pathtarget = target ? target : rel->reltarget;
2223  pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
2224  required_outer);
2225  pathnode->path.parallel_aware = false;
2226  pathnode->path.parallel_safe = rel->consider_parallel;
2227  pathnode->path.parallel_workers = 0;
2228  pathnode->path.rows = rows;
2229  pathnode->path.startup_cost = startup_cost;
2230  pathnode->path.total_cost = total_cost;
2231  pathnode->path.pathkeys = pathkeys;
2232 
2233  pathnode->fdw_outerpath = fdw_outerpath;
2234  pathnode->fdw_private = fdw_private;
2235 
2236  return pathnode;
2237 }
2238 
2239 /*
2240  * create_foreign_join_path
2241  * Creates a path corresponding to a scan of a foreign join,
2242  * returning the pathnode.
2243  *
2244  * This function is never called from core Postgres; rather, it's expected
2245  * to be called by the GetForeignJoinPaths function of a foreign data wrapper.
2246  * We make the FDW supply all fields of the path, since we do not have any way
2247  * to calculate them in core. However, there is a usually-sane default for
2248  * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2249  */
2250 ForeignPath *
2252  PathTarget *target,
2253  double rows, Cost startup_cost, Cost total_cost,
2254  List *pathkeys,
2255  Relids required_outer,
2256  Path *fdw_outerpath,
2257  List *fdw_private)
2258 {
2259  ForeignPath *pathnode = makeNode(ForeignPath);
2260 
2261  /*
2262  * We should use get_joinrel_parampathinfo to handle parameterized paths,
2263  * but the API of this function doesn't support it, and existing
2264  * extensions aren't yet trying to build such paths anyway. For the
2265  * moment just throw an error if someone tries it; eventually we should
2266  * revisit this.
2267  */
2268  if (!bms_is_empty(required_outer) || !bms_is_empty(rel->lateral_relids))
2269  elog(ERROR, "parameterized foreign joins are not supported yet");
2270 
2271  pathnode->path.pathtype = T_ForeignScan;
2272  pathnode->path.parent = rel;
2273  pathnode->path.pathtarget = target ? target : rel->reltarget;
2274  pathnode->path.param_info = NULL; /* XXX see above */
2275  pathnode->path.parallel_aware = false;
2276  pathnode->path.parallel_safe = rel->consider_parallel;
2277  pathnode->path.parallel_workers = 0;
2278  pathnode->path.rows = rows;
2279  pathnode->path.startup_cost = startup_cost;
2280  pathnode->path.total_cost = total_cost;
2281  pathnode->path.pathkeys = pathkeys;
2282 
2283  pathnode->fdw_outerpath = fdw_outerpath;
2284  pathnode->fdw_private = fdw_private;
2285 
2286  return pathnode;
2287 }
2288 
2289 /*
2290  * create_foreign_upper_path
2291  * Creates a path corresponding to an upper relation that's computed
2292  * directly by an FDW, returning the pathnode.
2293  *
2294  * This function is never called from core Postgres; rather, it's expected to
2295  * be called by the GetForeignUpperPaths function of a foreign data wrapper.
2296  * We make the FDW supply all fields of the path, since we do not have any way
2297  * to calculate them in core. However, there is a usually-sane default for
2298  * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2299  */
2300 ForeignPath *
2302  PathTarget *target,
2303  double rows, Cost startup_cost, Cost total_cost,
2304  List *pathkeys,
2305  Path *fdw_outerpath,
2306  List *fdw_private)
2307 {
2308  ForeignPath *pathnode = makeNode(ForeignPath);
2309 
2310  /*
2311  * Upper relations should never have any lateral references, since joining
2312  * is complete.
2313  */
2315 
2316  pathnode->path.pathtype = T_ForeignScan;
2317  pathnode->path.parent = rel;
2318  pathnode->path.pathtarget = target ? target : rel->reltarget;
2319  pathnode->path.param_info = NULL;
2320  pathnode->path.parallel_aware = false;
2321  pathnode->path.parallel_safe = rel->consider_parallel;
2322  pathnode->path.parallel_workers = 0;
2323  pathnode->path.rows = rows;
2324  pathnode->path.startup_cost = startup_cost;
2325  pathnode->path.total_cost = total_cost;
2326  pathnode->path.pathkeys = pathkeys;
2327 
2328  pathnode->fdw_outerpath = fdw_outerpath;
2329  pathnode->fdw_private = fdw_private;
2330 
2331  return pathnode;
2332 }
2333 
2334 /*
2335  * calc_nestloop_required_outer
2336  * Compute the required_outer set for a nestloop join path
2337  *
2338  * Note: result must not share storage with either input
2339  */
2340 Relids
2342  Relids outer_paramrels,
2343  Relids innerrelids,
2344  Relids inner_paramrels)
2345 {
2346  Relids required_outer;
2347 
2348  /* inner_path can require rels from outer path, but not vice versa */
2349  Assert(!bms_overlap(outer_paramrels, innerrelids));
2350  /* easy case if inner path is not parameterized */
2351  if (!inner_paramrels)
2352  return bms_copy(outer_paramrels);
2353  /* else, form the union ... */
2354  required_outer = bms_union(outer_paramrels, inner_paramrels);
2355  /* ... and remove any mention of now-satisfied outer rels */
2356  required_outer = bms_del_members(required_outer,
2357  outerrelids);
2358  /* maintain invariant that required_outer is exactly NULL if empty */
2359  if (bms_is_empty(required_outer))
2360  {
2361  bms_free(required_outer);
2362  required_outer = NULL;
2363  }
2364  return required_outer;
2365 }
2366 
2367 /*
2368  * calc_non_nestloop_required_outer
2369  * Compute the required_outer set for a merge or hash join path
2370  *
2371  * Note: result must not share storage with either input
2372  */
2373 Relids
2374 calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
2375 {
2376  Relids outer_paramrels = PATH_REQ_OUTER(outer_path);
2377  Relids inner_paramrels = PATH_REQ_OUTER(inner_path);
2378  Relids required_outer;
2379 
2380  /* neither path can require rels from the other */
2381  Assert(!bms_overlap(outer_paramrels, inner_path->parent->relids));
2382  Assert(!bms_overlap(inner_paramrels, outer_path->parent->relids));
2383  /* form the union ... */
2384  required_outer = bms_union(outer_paramrels, inner_paramrels);
2385  /* we do not need an explicit test for empty; bms_union gets it right */
2386  return required_outer;
2387 }
2388 
2389 /*
2390  * create_nestloop_path
2391  * Creates a pathnode corresponding to a nestloop join between two
2392  * relations.
2393  *
2394  * 'joinrel' is the join relation.
2395  * 'jointype' is the type of join required
2396  * 'workspace' is the result from initial_cost_nestloop
2397  * 'extra' contains various information about the join
2398  * 'outer_path' is the outer path
2399  * 'inner_path' is the inner path
2400  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2401  * 'pathkeys' are the path keys of the new join path
2402  * 'required_outer' is the set of required outer rels
2403  *
2404  * Returns the resulting path node.
2405  */
2406 NestPath *
2408  RelOptInfo *joinrel,
2409  JoinType jointype,
2410  JoinCostWorkspace *workspace,
2411  JoinPathExtraData *extra,
2412  Path *outer_path,
2413  Path *inner_path,
2414  List *restrict_clauses,
2415  List *pathkeys,
2416  Relids required_outer)
2417 {
2418  NestPath *pathnode = makeNode(NestPath);
2419  Relids inner_req_outer = PATH_REQ_OUTER(inner_path);
2420 
2421  /*
2422  * If the inner path is parameterized by the outer, we must drop any
2423  * restrict_clauses that are due to be moved into the inner path. We have
2424  * to do this now, rather than postpone the work till createplan time,
2425  * because the restrict_clauses list can affect the size and cost
2426  * estimates for this path.
2427  */
2428  if (bms_overlap(inner_req_outer, outer_path->parent->relids))
2429  {
2430  Relids inner_and_outer = bms_union(inner_path->parent->relids,
2431  inner_req_outer);
2432  List *jclauses = NIL;
2433  ListCell *lc;
2434 
2435  foreach(lc, restrict_clauses)
2436  {
2437  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2438 
2439  if (!join_clause_is_movable_into(rinfo,
2440  inner_path->parent->relids,
2441  inner_and_outer))
2442  jclauses = lappend(jclauses, rinfo);
2443  }
2444  restrict_clauses = jclauses;
2445  }
2446 
2447  pathnode->jpath.path.pathtype = T_NestLoop;
2448  pathnode->jpath.path.parent = joinrel;
2449  pathnode->jpath.path.pathtarget = joinrel->reltarget;
2450  pathnode->jpath.path.param_info =
2452  joinrel,
2453  outer_path,
2454  inner_path,
2455  extra->sjinfo,
2456  required_outer,
2457  &restrict_clauses);
2458  pathnode->jpath.path.parallel_aware = false;
2459  pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2460  outer_path->parallel_safe && inner_path->parallel_safe;
2461  /* This is a foolish way to estimate parallel_workers, but for now... */
2462  pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2463  pathnode->jpath.path.pathkeys = pathkeys;
2464  pathnode->jpath.jointype = jointype;
2465  pathnode->jpath.inner_unique = extra->inner_unique;
2466  pathnode->jpath.outerjoinpath = outer_path;
2467  pathnode->jpath.innerjoinpath = inner_path;
2468  pathnode->jpath.joinrestrictinfo = restrict_clauses;
2469 
2470  final_cost_nestloop(root, pathnode, workspace, extra);
2471 
2472  return pathnode;
2473 }
2474 
2475 /*
2476  * create_mergejoin_path
2477  * Creates a pathnode corresponding to a mergejoin join between
2478  * two relations
2479  *
2480  * 'joinrel' is the join relation
2481  * 'jointype' is the type of join required
2482  * 'workspace' is the result from initial_cost_mergejoin
2483  * 'extra' contains various information about the join
2484  * 'outer_path' is the outer path
2485  * 'inner_path' is the inner path
2486  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2487  * 'pathkeys' are the path keys of the new join path
2488  * 'required_outer' is the set of required outer rels
2489  * 'mergeclauses' are the RestrictInfo nodes to use as merge clauses
2490  * (this should be a subset of the restrict_clauses list)
2491  * 'outersortkeys' are the sort varkeys for the outer relation
2492  * 'innersortkeys' are the sort varkeys for the inner relation
2493  */
2494 MergePath *
2496  RelOptInfo *joinrel,
2497  JoinType jointype,
2498  JoinCostWorkspace *workspace,
2499  JoinPathExtraData *extra,
2500  Path *outer_path,
2501  Path *inner_path,
2502  List *restrict_clauses,
2503  List *pathkeys,
2504  Relids required_outer,
2505  List *mergeclauses,
2506  List *outersortkeys,
2507  List *innersortkeys)
2508 {
2509  MergePath *pathnode = makeNode(MergePath);
2510 
2511  pathnode->jpath.path.pathtype = T_MergeJoin;
2512  pathnode->jpath.path.parent = joinrel;
2513  pathnode->jpath.path.pathtarget = joinrel->reltarget;
2514  pathnode->jpath.path.param_info =
2516  joinrel,
2517  outer_path,
2518  inner_path,
2519  extra->sjinfo,
2520  required_outer,
2521  &restrict_clauses);
2522  pathnode->jpath.path.parallel_aware = false;
2523  pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2524  outer_path->parallel_safe && inner_path->parallel_safe;
2525  /* This is a foolish way to estimate parallel_workers, but for now... */
2526  pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2527  pathnode->jpath.path.pathkeys = pathkeys;
2528  pathnode->jpath.jointype = jointype;
2529  pathnode->jpath.inner_unique = extra->inner_unique;
2530  pathnode->jpath.outerjoinpath = outer_path;
2531  pathnode->jpath.innerjoinpath = inner_path;
2532  pathnode->jpath.joinrestrictinfo = restrict_clauses;
2533  pathnode->path_mergeclauses = mergeclauses;
2534  pathnode->outersortkeys = outersortkeys;
2535  pathnode->innersortkeys = innersortkeys;
2536  /* pathnode->skip_mark_restore will be set by final_cost_mergejoin */
2537  /* pathnode->materialize_inner will be set by final_cost_mergejoin */
2538 
2539  final_cost_mergejoin(root, pathnode, workspace, extra);
2540 
2541  return pathnode;
2542 }
2543 
2544 /*
2545  * create_hashjoin_path
2546  * Creates a pathnode corresponding to a hash join between two relations.
2547  *
2548  * 'joinrel' is the join relation
2549  * 'jointype' is the type of join required
2550  * 'workspace' is the result from initial_cost_hashjoin
2551  * 'extra' contains various information about the join
2552  * 'outer_path' is the cheapest outer path
2553  * 'inner_path' is the cheapest inner path
2554  * 'parallel_hash' to select Parallel Hash of inner path (shared hash table)
2555  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2556  * 'required_outer' is the set of required outer rels
2557  * 'hashclauses' are the RestrictInfo nodes to use as hash clauses
2558  * (this should be a subset of the restrict_clauses list)
2559  */
2560 HashPath *
2562  RelOptInfo *joinrel,
2563  JoinType jointype,
2564  JoinCostWorkspace *workspace,
2565  JoinPathExtraData *extra,
2566  Path *outer_path,
2567  Path *inner_path,
2568  bool parallel_hash,
2569  List *restrict_clauses,
2570  Relids required_outer,
2571  List *hashclauses)
2572 {
2573  HashPath *pathnode = makeNode(HashPath);
2574 
2575  pathnode->jpath.path.pathtype = T_HashJoin;
2576  pathnode->jpath.path.parent = joinrel;
2577  pathnode->jpath.path.pathtarget = joinrel->reltarget;
2578  pathnode->jpath.path.param_info =
2580  joinrel,
2581  outer_path,
2582  inner_path,
2583  extra->sjinfo,
2584  required_outer,
2585  &restrict_clauses);
2586  pathnode->jpath.path.parallel_aware =
2587  joinrel->consider_parallel && parallel_hash;
2588  pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2589  outer_path->parallel_safe && inner_path->parallel_safe;
2590  /* This is a foolish way to estimate parallel_workers, but for now... */
2591  pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2592 
2593  /*
2594  * A hashjoin never has pathkeys, since its output ordering is
2595  * unpredictable due to possible batching. XXX If the inner relation is
2596  * small enough, we could instruct the executor that it must not batch,
2597  * and then we could assume that the output inherits the outer relation's
2598  * ordering, which might save a sort step. However there is considerable
2599  * downside if our estimate of the inner relation size is badly off. For
2600  * the moment we don't risk it. (Note also that if we wanted to take this
2601  * seriously, joinpath.c would have to consider many more paths for the
2602  * outer rel than it does now.)
2603  */
2604  pathnode->jpath.path.pathkeys = NIL;
2605  pathnode->jpath.jointype = jointype;
2606  pathnode->jpath.inner_unique = extra->inner_unique;
2607  pathnode->jpath.outerjoinpath = outer_path;
2608  pathnode->jpath.innerjoinpath = inner_path;
2609  pathnode->jpath.joinrestrictinfo = restrict_clauses;
2610  pathnode->path_hashclauses = hashclauses;
2611  /* final_cost_hashjoin will fill in pathnode->num_batches */
2612 
2613  final_cost_hashjoin(root, pathnode, workspace, extra);
2614 
2615  return pathnode;
2616 }
2617 
2618 /*
2619  * create_projection_path
2620  * Creates a pathnode that represents performing a projection.
2621  *
2622  * 'rel' is the parent relation associated with the result
2623  * 'subpath' is the path representing the source of data
2624  * 'target' is the PathTarget to be computed
2625  */
2628  RelOptInfo *rel,
2629  Path *subpath,
2630  PathTarget *target)
2631 {
2632  ProjectionPath *pathnode = makeNode(ProjectionPath);
2633  PathTarget *oldtarget;
2634 
2635  /*
2636  * We mustn't put a ProjectionPath directly above another; it's useless
2637  * and will confuse create_projection_plan. Rather than making sure all
2638  * callers handle that, let's implement it here, by stripping off any
2639  * ProjectionPath in what we're given. Given this rule, there won't be
2640  * more than one.
2641  */
2642  if (IsA(subpath, ProjectionPath))
2643  {
2644  ProjectionPath *subpp = (ProjectionPath *) subpath;
2645 
2646  Assert(subpp->path.parent == rel);
2647  subpath = subpp->subpath;
2649  }
2650 
2651  pathnode->path.pathtype = T_Result;
2652  pathnode->path.parent = rel;
2653  pathnode->path.pathtarget = target;
2654  /* For now, assume we are above any joins, so no parameterization */
2655  pathnode->path.param_info = NULL;
2656  pathnode->path.parallel_aware = false;
2657  pathnode->path.parallel_safe = rel->consider_parallel &&
2658  subpath->parallel_safe &&
2659  is_parallel_safe(root, (Node *) target->exprs);
2660  pathnode->path.parallel_workers = subpath->parallel_workers;
2661  /* Projection does not change the sort order */
2662  pathnode->path.pathkeys = subpath->pathkeys;
2663 
2664  pathnode->subpath = subpath;
2665 
2666  /*
2667  * We might not need a separate Result node. If the input plan node type
2668  * can project, we can just tell it to project something else. Or, if it
2669  * can't project but the desired target has the same expression list as
2670  * what the input will produce anyway, we can still give it the desired
2671  * tlist (possibly changing its ressortgroupref labels, but nothing else).
2672  * Note: in the latter case, create_projection_plan has to recheck our
2673  * conclusion; see comments therein.
2674  */
2675  oldtarget = subpath->pathtarget;
2677  equal(oldtarget->exprs, target->exprs))
2678  {
2679  /* No separate Result node needed */
2680  pathnode->dummypp = true;
2681 
2682  /*
2683  * Set cost of plan as subpath's cost, adjusted for tlist replacement.
2684  */
2685  pathnode->path.rows = subpath->rows;
2686  pathnode->path.startup_cost = subpath->startup_cost +
2687  (target->cost.startup - oldtarget->cost.startup);
2688  pathnode->path.total_cost = subpath->total_cost +
2689  (target->cost.startup - oldtarget->cost.startup) +
2690  (target->cost.per_tuple - oldtarget->cost.per_tuple) * subpath->rows;
2691  }
2692  else
2693  {
2694  /* We really do need the Result node */
2695  pathnode->dummypp = false;
2696 
2697  /*
2698  * The Result node's cost is cpu_tuple_cost per row, plus the cost of
2699  * evaluating the tlist. There is no qual to worry about.
2700  */
2701  pathnode->path.rows = subpath->rows;
2702  pathnode->path.startup_cost = subpath->startup_cost +
2703  target->cost.startup;
2704  pathnode->path.total_cost = subpath->total_cost +
2705  target->cost.startup +
2706  (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows;
2707  }
2708 
2709  return pathnode;
2710 }
2711 
2712 /*
2713  * apply_projection_to_path
2714  * Add a projection step, or just apply the target directly to given path.
2715  *
2716  * This has the same net effect as create_projection_path(), except that if
2717  * a separate Result plan node isn't needed, we just replace the given path's
2718  * pathtarget with the desired one. This must be used only when the caller
2719  * knows that the given path isn't referenced elsewhere and so can be modified
2720  * in-place.
2721  *
2722  * If the input path is a GatherPath or GatherMergePath, we try to push the
2723  * new target down to its input as well; this is a yet more invasive
2724  * modification of the input path, which create_projection_path() can't do.
2725  *
2726  * Note that we mustn't change the source path's parent link; so when it is
2727  * add_path'd to "rel" things will be a bit inconsistent. So far that has
2728  * not caused any trouble.
2729  *
2730  * 'rel' is the parent relation associated with the result
2731  * 'path' is the path representing the source of data
2732  * 'target' is the PathTarget to be computed
2733  */
2734 Path *
2736  RelOptInfo *rel,
2737  Path *path,
2738  PathTarget *target)
2739 {
2740  QualCost oldcost;
2741 
2742  /*
2743  * If given path can't project, we might need a Result node, so make a
2744  * separate ProjectionPath.
2745  */
2746  if (!is_projection_capable_path(path))
2747  return (Path *) create_projection_path(root, rel, path, target);
2748 
2749  /*
2750  * We can just jam the desired tlist into the existing path, being sure to
2751  * update its cost estimates appropriately.
2752  */
2753  oldcost = path->pathtarget->cost;
2754  path->pathtarget = target;
2755 
2756  path->startup_cost += target->cost.startup - oldcost.startup;
2757  path->total_cost += target->cost.startup - oldcost.startup +
2758  (target->cost.per_tuple - oldcost.per_tuple) * path->rows;
2759 
2760  /*
2761  * If the path happens to be a Gather or GatherMerge path, we'd like to
2762  * arrange for the subpath to return the required target list so that
2763  * workers can help project. But if there is something that is not
2764  * parallel-safe in the target expressions, then we can't.
2765  */
2766  if ((IsA(path, GatherPath) || IsA(path, GatherMergePath)) &&
2767  is_parallel_safe(root, (Node *) target->exprs))
2768  {
2769  /*
2770  * We always use create_projection_path here, even if the subpath is
2771  * projection-capable, so as to avoid modifying the subpath in place.
2772  * It seems unlikely at present that there could be any other
2773  * references to the subpath, but better safe than sorry.
2774  *
2775  * Note that we don't change the parallel path's cost estimates; it
2776  * might be appropriate to do so, to reflect the fact that the bulk of
2777  * the target evaluation will happen in workers.
2778  */
2779  if (IsA(path, GatherPath))
2780  {
2781  GatherPath *gpath = (GatherPath *) path;
2782 
2783  gpath->subpath = (Path *)
2785  gpath->subpath->parent,
2786  gpath->subpath,
2787  target);
2788  }
2789  else
2790  {
2791  GatherMergePath *gmpath = (GatherMergePath *) path;
2792 
2793  gmpath->subpath = (Path *)
2795  gmpath->subpath->parent,
2796  gmpath->subpath,
2797  target);
2798  }
2799  }
2800  else if (path->parallel_safe &&
2801  !is_parallel_safe(root, (Node *) target->exprs))
2802  {
2803  /*
2804  * We're inserting a parallel-restricted target list into a path
2805  * currently marked parallel-safe, so we have to mark it as no longer
2806  * safe.
2807  */
2808  path->parallel_safe = false;
2809  }
2810 
2811  return path;
2812 }
2813 
2814 /*
2815  * create_set_projection_path
2816  * Creates a pathnode that represents performing a projection that
2817  * includes set-returning functions.
2818  *
2819  * 'rel' is the parent relation associated with the result
2820  * 'subpath' is the path representing the source of data
2821  * 'target' is the PathTarget to be computed
2822  */
2825  RelOptInfo *rel,
2826  Path *subpath,
2827  PathTarget *target)
2828 {
2829  ProjectSetPath *pathnode = makeNode(ProjectSetPath);
2830  double tlist_rows;
2831  ListCell *lc;
2832 
2833  pathnode->path.pathtype = T_ProjectSet;
2834  pathnode->path.parent = rel;
2835  pathnode->path.pathtarget = target;
2836  /* For now, assume we are above any joins, so no parameterization */
2837  pathnode->path.param_info = NULL;
2838  pathnode->path.parallel_aware = false;
2839  pathnode->path.parallel_safe = rel->consider_parallel &&
2840  subpath->parallel_safe &&
2841  is_parallel_safe(root, (Node *) target->exprs);
2842  pathnode->path.parallel_workers = subpath->parallel_workers;
2843  /* Projection does not change the sort order XXX? */
2844  pathnode->path.pathkeys = subpath->pathkeys;
2845 
2846  pathnode->subpath = subpath;
2847 
2848  /*
2849  * Estimate number of rows produced by SRFs for each row of input; if
2850  * there's more than one in this node, use the maximum.
2851  */
2852  tlist_rows = 1;
2853  foreach(lc, target->exprs)
2854  {
2855  Node *node = (Node *) lfirst(lc);
2856  double itemrows;
2857 
2858  itemrows = expression_returns_set_rows(root, node);
2859  if (tlist_rows < itemrows)
2860  tlist_rows = itemrows;
2861  }
2862 
2863  /*
2864  * In addition to the cost of evaluating the tlist, charge cpu_tuple_cost
2865  * per input row, and half of cpu_tuple_cost for each added output row.
2866  * This is slightly bizarre maybe, but it's what 9.6 did; we may revisit
2867  * this estimate later.
2868  */
2869  pathnode->path.rows = subpath->rows * tlist_rows;
2870  pathnode->path.startup_cost = subpath->startup_cost +
2871  target->cost.startup;
2872  pathnode->path.total_cost = subpath->total_cost +
2873  target->cost.startup +
2874  (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows +
2875  (pathnode->path.rows - subpath->rows) * cpu_tuple_cost / 2;
2876 
2877  return pathnode;
2878 }
2879 
2880 /*
2881  * create_incremental_sort_path
2882  * Creates a pathnode that represents performing an incremental sort.
2883  *
2884  * 'rel' is the parent relation associated with the result
2885  * 'subpath' is the path representing the source of data
2886  * 'pathkeys' represents the desired sort order
2887  * 'presorted_keys' is the number of keys by which the input path is
2888  * already sorted
2889  * 'limit_tuples' is the estimated bound on the number of output tuples,
2890  * or -1 if no LIMIT or couldn't estimate
2891  */
2894  RelOptInfo *rel,
2895  Path *subpath,
2896  List *pathkeys,
2897  int presorted_keys,
2898  double limit_tuples)
2899 {
2901  SortPath *pathnode = &sort->spath;
2902 
2903  pathnode->path.pathtype = T_IncrementalSort;
2904  pathnode->path.parent = rel;
2905  /* Sort doesn't project, so use source path's pathtarget */
2906  pathnode->path.pathtarget = subpath->pathtarget;
2907  /* For now, assume we are above any joins, so no parameterization */
2908  pathnode->path.param_info = NULL;
2909  pathnode->path.parallel_aware = false;
2910  pathnode->path.parallel_safe = rel->consider_parallel &&
2911  subpath->parallel_safe;
2912  pathnode->path.parallel_workers = subpath->parallel_workers;
2913  pathnode->path.pathkeys = pathkeys;
2914 
2915  pathnode->subpath = subpath;
2916 
2917  cost_incremental_sort(&pathnode->path,
2918  root, pathkeys, presorted_keys,
2919  subpath->startup_cost,
2920  subpath->total_cost,
2921  subpath->rows,
2922  subpath->pathtarget->width,
2923  0.0, /* XXX comparison_cost shouldn't be 0? */
2924  work_mem, limit_tuples);
2925 
2926  sort->nPresortedCols = presorted_keys;
2927 
2928  return sort;
2929 }
2930 
2931 /*
2932  * create_sort_path
2933  * Creates a pathnode that represents performing an explicit sort.
2934  *
2935  * 'rel' is the parent relation associated with the result
2936  * 'subpath' is the path representing the source of data
2937  * 'pathkeys' represents the desired sort order
2938  * 'limit_tuples' is the estimated bound on the number of output tuples,
2939  * or -1 if no LIMIT or couldn't estimate
2940  */
2941 SortPath *
2943  RelOptInfo *rel,
2944  Path *subpath,
2945  List *pathkeys,
2946  double limit_tuples)
2947 {
2948  SortPath *pathnode = makeNode(SortPath);
2949 
2950  pathnode->path.pathtype = T_Sort;
2951  pathnode->path.parent = rel;
2952  /* Sort doesn't project, so use source path's pathtarget */
2953  pathnode->path.pathtarget = subpath->pathtarget;
2954  /* For now, assume we are above any joins, so no parameterization */
2955  pathnode->path.param_info = NULL;
2956  pathnode->path.parallel_aware = false;
2957  pathnode->path.parallel_safe = rel->consider_parallel &&
2958  subpath->parallel_safe;
2959  pathnode->path.parallel_workers = subpath->parallel_workers;
2960  pathnode->path.pathkeys = pathkeys;
2961 
2962  pathnode->subpath = subpath;
2963 
2964  cost_sort(&pathnode->path, root, pathkeys,
2965  subpath->total_cost,
2966  subpath->rows,
2967  subpath->pathtarget->width,
2968  0.0, /* XXX comparison_cost shouldn't be 0? */
2969  work_mem, limit_tuples);
2970 
2971  return pathnode;
2972 }
2973 
2974 /*
2975  * create_group_path
2976  * Creates a pathnode that represents performing grouping of presorted input
2977  *
2978  * 'rel' is the parent relation associated with the result
2979  * 'subpath' is the path representing the source of data
2980  * 'target' is the PathTarget to be computed
2981  * 'groupClause' is a list of SortGroupClause's representing the grouping
2982  * 'qual' is the HAVING quals if any
2983  * 'numGroups' is the estimated number of groups
2984  */
2985 GroupPath *
2987  RelOptInfo *rel,
2988  Path *subpath,
2989  List *groupClause,
2990  List *qual,
2991  double numGroups)
2992 {
2993  GroupPath *pathnode = makeNode(GroupPath);
2994  PathTarget *target = rel->reltarget;
2995 
2996  pathnode->path.pathtype = T_Group;
2997  pathnode->path.parent = rel;
2998  pathnode->path.pathtarget = target;
2999  /* For now, assume we are above any joins, so no parameterization */
3000  pathnode->path.param_info = NULL;
3001  pathnode->path.parallel_aware = false;
3002  pathnode->path.parallel_safe = rel->consider_parallel &&
3003  subpath->parallel_safe;
3004  pathnode->path.parallel_workers = subpath->parallel_workers;
3005  /* Group doesn't change sort ordering */
3006  pathnode->path.pathkeys = subpath->pathkeys;
3007 
3008  pathnode->subpath = subpath;
3009 
3010  pathnode->groupClause = groupClause;
3011  pathnode->qual = qual;
3012 
3013  cost_group(&pathnode->path, root,
3014  list_length(groupClause),
3015  numGroups,
3016  qual,
3017  subpath->startup_cost, subpath->total_cost,
3018  subpath->rows);
3019 
3020  /* add tlist eval cost for each output row */
3021  pathnode->path.startup_cost += target->cost.startup;
3022  pathnode->path.total_cost += target->cost.startup +
3023  target->cost.per_tuple * pathnode->path.rows;
3024 
3025  return pathnode;
3026 }
3027 
3028 /*
3029  * create_upper_unique_path
3030  * Creates a pathnode that represents performing an explicit Unique step
3031  * on presorted input.
3032  *
3033  * This produces a Unique plan node, but the use-case is so different from
3034  * create_unique_path that it doesn't seem worth trying to merge the two.
3035  *
3036  * 'rel' is the parent relation associated with the result
3037  * 'subpath' is the path representing the source of data
3038  * 'numCols' is the number of grouping columns
3039  * 'numGroups' is the estimated number of groups
3040  *
3041  * The input path must be sorted on the grouping columns, plus possibly
3042  * additional columns; so the first numCols pathkeys are the grouping columns
3043  */
3046  RelOptInfo *rel,
3047  Path *subpath,
3048  int numCols,
3049  double numGroups)
3050 {
3052 
3053  pathnode->path.pathtype = T_Unique;
3054  pathnode->path.parent = rel;
3055  /* Unique doesn't project, so use source path's pathtarget */
3056  pathnode->path.pathtarget = subpath->pathtarget;
3057  /* For now, assume we are above any joins, so no parameterization */
3058  pathnode->path.param_info = NULL;
3059  pathnode->path.parallel_aware = false;
3060  pathnode->path.parallel_safe = rel->consider_parallel &&
3061  subpath->parallel_safe;
3062  pathnode->path.parallel_workers = subpath->parallel_workers;
3063  /* Unique doesn't change the input ordering */
3064  pathnode->path.pathkeys = subpath->pathkeys;
3065 
3066  pathnode->subpath = subpath;
3067  pathnode->numkeys = numCols;
3068 
3069  /*
3070  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3071  * all columns get compared at most of the tuples. (XXX probably this is
3072  * an overestimate.)
3073  */
3074  pathnode->path.startup_cost = subpath->startup_cost;
3075  pathnode->path.total_cost = subpath->total_cost +
3076  cpu_operator_cost * subpath->rows * numCols;
3077  pathnode->path.rows = numGroups;
3078 
3079  return pathnode;
3080 }
3081 
3082 /*
3083  * create_agg_path
3084  * Creates a pathnode that represents performing aggregation/grouping
3085  *
3086  * 'rel' is the parent relation associated with the result
3087  * 'subpath' is the path representing the source of data
3088  * 'target' is the PathTarget to be computed
3089  * 'aggstrategy' is the Agg node's basic implementation strategy
3090  * 'aggsplit' is the Agg node's aggregate-splitting mode
3091  * 'groupClause' is a list of SortGroupClause's representing the grouping
3092  * 'qual' is the HAVING quals if any
3093  * 'aggcosts' contains cost info about the aggregate functions to be computed
3094  * 'numGroups' is the estimated number of groups (1 if not grouping)
3095  */
3096 AggPath *
3098  RelOptInfo *rel,
3099  Path *subpath,
3100  PathTarget *target,
3101  AggStrategy aggstrategy,
3102  AggSplit aggsplit,
3103  List *groupClause,
3104  List *qual,
3105  const AggClauseCosts *aggcosts,
3106  double numGroups)
3107 {
3108  AggPath *pathnode = makeNode(AggPath);
3109 
3110  pathnode->path.pathtype = T_Agg;
3111  pathnode->path.parent = rel;
3112  pathnode->path.pathtarget = target;
3113  /* For now, assume we are above any joins, so no parameterization */
3114  pathnode->path.param_info = NULL;
3115  pathnode->path.parallel_aware = false;
3116  pathnode->path.parallel_safe = rel->consider_parallel &&
3117  subpath->parallel_safe;
3118  pathnode->path.parallel_workers = subpath->parallel_workers;
3119  if (aggstrategy == AGG_SORTED)
3120  pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */
3121  else
3122  pathnode->path.pathkeys = NIL; /* output is unordered */
3123  pathnode->subpath = subpath;
3124 
3125  pathnode->aggstrategy = aggstrategy;
3126  pathnode->aggsplit = aggsplit;
3127  pathnode->numGroups = numGroups;
3128  pathnode->transitionSpace = aggcosts ? aggcosts->transitionSpace : 0;
3129  pathnode->groupClause = groupClause;
3130  pathnode->qual = qual;
3131 
3132  cost_agg(&pathnode->path, root,
3133  aggstrategy, aggcosts,
3134  list_length(groupClause), numGroups,
3135  qual,
3136  subpath->startup_cost, subpath->total_cost,
3137  subpath->rows, subpath->pathtarget->width);
3138 
3139  /* add tlist eval cost for each output row */
3140  pathnode->path.startup_cost += target->cost.startup;
3141  pathnode->path.total_cost += target->cost.startup +
3142  target->cost.per_tuple * pathnode->path.rows;
3143 
3144  return pathnode;
3145 }
3146 
3147 /*
3148  * create_groupingsets_path
3149  * Creates a pathnode that represents performing GROUPING SETS aggregation
3150  *
3151  * GroupingSetsPath represents sorted grouping with one or more grouping sets.
3152  * The input path's result must be sorted to match the last entry in
3153  * rollup_groupclauses.
3154  *
3155  * 'rel' is the parent relation associated with the result
3156  * 'subpath' is the path representing the source of data
3157  * 'target' is the PathTarget to be computed
3158  * 'having_qual' is the HAVING quals if any
3159  * 'rollups' is a list of RollupData nodes
3160  * 'agg_costs' contains cost info about the aggregate functions to be computed
3161  * 'numGroups' is the estimated total number of groups
3162  */
3165  RelOptInfo *rel,
3166  Path *subpath,
3167  List *having_qual,
3168  AggStrategy aggstrategy,
3169  List *rollups,
3170  const AggClauseCosts *agg_costs,
3171  double numGroups)
3172 {
3174  PathTarget *target = rel->reltarget;
3175  ListCell *lc;
3176  bool is_first = true;
3177  bool is_first_sort = true;
3178 
3179  /* The topmost generated Plan node will be an Agg */
3180  pathnode->path.pathtype = T_Agg;
3181  pathnode->path.parent = rel;
3182  pathnode->path.pathtarget = target;
3183  pathnode->path.param_info = subpath->param_info;
3184  pathnode->path.parallel_aware = false;
3185  pathnode->path.parallel_safe = rel->consider_parallel &&
3186  subpath->parallel_safe;
3187  pathnode->path.parallel_workers = subpath->parallel_workers;
3188  pathnode->subpath = subpath;
3189 
3190  /*
3191  * Simplify callers by downgrading AGG_SORTED to AGG_PLAIN, and AGG_MIXED
3192  * to AGG_HASHED, here if possible.
3193  */
3194  if (aggstrategy == AGG_SORTED &&
3195  list_length(rollups) == 1 &&
3196  ((RollupData *) linitial(rollups))->groupClause == NIL)
3197  aggstrategy = AGG_PLAIN;
3198 
3199  if (aggstrategy == AGG_MIXED &&
3200  list_length(rollups) == 1)
3201  aggstrategy = AGG_HASHED;
3202 
3203  /*
3204  * Output will be in sorted order by group_pathkeys if, and only if, there
3205  * is a single rollup operation on a non-empty list of grouping
3206  * expressions.
3207  */
3208  if (aggstrategy == AGG_SORTED && list_length(rollups) == 1)
3209  pathnode->path.pathkeys = root->group_pathkeys;
3210  else
3211  pathnode->path.pathkeys = NIL;
3212 
3213  pathnode->aggstrategy = aggstrategy;
3214  pathnode->rollups = rollups;
3215  pathnode->qual = having_qual;
3216  pathnode->transitionSpace = agg_costs ? agg_costs->transitionSpace : 0;
3217 
3218  Assert(rollups != NIL);
3219  Assert(aggstrategy != AGG_PLAIN || list_length(rollups) == 1);
3220  Assert(aggstrategy != AGG_MIXED || list_length(rollups) > 1);
3221 
3222  foreach(lc, rollups)
3223  {
3224  RollupData *rollup = lfirst(lc);
3225  List *gsets = rollup->gsets;
3226  int numGroupCols = list_length(linitial(gsets));
3227 
3228  /*
3229  * In AGG_SORTED or AGG_PLAIN mode, the first rollup takes the
3230  * (already-sorted) input, and following ones do their own sort.
3231  *
3232  * In AGG_HASHED mode, there is one rollup for each grouping set.
3233  *
3234  * In AGG_MIXED mode, the first rollups are hashed, the first
3235  * non-hashed one takes the (already-sorted) input, and following ones
3236  * do their own sort.
3237  */
3238  if (is_first)
3239  {
3240  cost_agg(&pathnode->path, root,
3241  aggstrategy,
3242  agg_costs,
3243  numGroupCols,
3244  rollup->numGroups,
3245  having_qual,
3246  subpath->startup_cost,
3247  subpath->total_cost,
3248  subpath->rows,
3249  subpath->pathtarget->width);
3250  is_first = false;
3251  if (!rollup->is_hashed)
3252  is_first_sort = false;
3253  }
3254  else
3255  {
3256  Path sort_path; /* dummy for result of cost_sort */
3257  Path agg_path; /* dummy for result of cost_agg */
3258 
3259  if (rollup->is_hashed || is_first_sort)
3260  {
3261  /*
3262  * Account for cost of aggregation, but don't charge input
3263  * cost again
3264  */
3265  cost_agg(&agg_path, root,
3266  rollup->is_hashed ? AGG_HASHED : AGG_SORTED,
3267  agg_costs,
3268  numGroupCols,
3269  rollup->numGroups,
3270  having_qual,
3271  0.0, 0.0,
3272  subpath->rows,
3273  subpath->pathtarget->width);
3274  if (!rollup->is_hashed)
3275  is_first_sort = false;
3276  }
3277  else
3278  {
3279  /* Account for cost of sort, but don't charge input cost again */
3280  cost_sort(&sort_path, root, NIL,
3281  0.0,
3282  subpath->rows,
3283  subpath->pathtarget->width,
3284  0.0,
3285  work_mem,
3286  -1.0);
3287 
3288  /* Account for cost of aggregation */
3289 
3290  cost_agg(&agg_path, root,
3291  AGG_SORTED,
3292  agg_costs,
3293  numGroupCols,
3294  rollup->numGroups,
3295  having_qual,
3296  sort_path.startup_cost,
3297  sort_path.total_cost,
3298  sort_path.rows,
3299  subpath->pathtarget->width);
3300  }
3301 
3302  pathnode->path.total_cost += agg_path.total_cost;
3303  pathnode->path.rows += agg_path.rows;
3304  }
3305  }
3306 
3307  /* add tlist eval cost for each output row */
3308  pathnode->path.startup_cost += target->cost.startup;
3309  pathnode->path.total_cost += target->cost.startup +
3310  target->cost.per_tuple * pathnode->path.rows;
3311 
3312  return pathnode;
3313 }
3314 
3315 /*
3316  * create_minmaxagg_path
3317  * Creates a pathnode that represents computation of MIN/MAX aggregates
3318  *
3319  * 'rel' is the parent relation associated with the result
3320  * 'target' is the PathTarget to be computed
3321  * 'mmaggregates' is a list of MinMaxAggInfo structs
3322  * 'quals' is the HAVING quals if any
3323  */
3324 MinMaxAggPath *
3326  RelOptInfo *rel,
3327  PathTarget *target,
3328  List *mmaggregates,
3329  List *quals)
3330 {
3331  MinMaxAggPath *pathnode = makeNode(MinMaxAggPath);
3332  Cost initplan_cost;
3333  ListCell *lc;
3334 
3335  /* The topmost generated Plan node will be a Result */
3336  pathnode->path.pathtype = T_Result;
3337  pathnode->path.parent = rel;
3338  pathnode->path.pathtarget = target;
3339  /* For now, assume we are above any joins, so no parameterization */
3340  pathnode->path.param_info = NULL;
3341  pathnode->path.parallel_aware = false;
3342  /* A MinMaxAggPath implies use of subplans, so cannot be parallel-safe */
3343  pathnode->path.parallel_safe = false;
3344  pathnode->path.parallel_workers = 0;
3345  /* Result is one unordered row */
3346  pathnode->path.rows = 1;
3347  pathnode->path.pathkeys = NIL;
3348 
3349  pathnode->mmaggregates = mmaggregates;
3350  pathnode->quals = quals;
3351 
3352  /* Calculate cost of all the initplans ... */
3353  initplan_cost = 0;
3354  foreach(lc, mmaggregates)
3355  {
3356  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3357 
3358  initplan_cost += mminfo->pathcost;
3359  }
3360 
3361  /* add tlist eval cost for each output row, plus cpu_tuple_cost */
3362  pathnode->path.startup_cost = initplan_cost + target->cost.startup;
3363  pathnode->path.total_cost = initplan_cost + target->cost.startup +
3364  target->cost.per_tuple + cpu_tuple_cost;
3365 
3366  /*
3367  * Add cost of qual, if any --- but we ignore its selectivity, since our
3368  * rowcount estimate should be 1 no matter what the qual is.
3369  */
3370  if (quals)
3371  {
3372  QualCost qual_cost;
3373 
3374  cost_qual_eval(&qual_cost, quals, root);
3375  pathnode->path.startup_cost += qual_cost.startup;
3376  pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
3377  }
3378 
3379  return pathnode;
3380 }
3381 
3382 /*
3383  * create_windowagg_path
3384  * Creates a pathnode that represents computation of window functions
3385  *
3386  * 'rel' is the parent relation associated with the result
3387  * 'subpath' is the path representing the source of data
3388  * 'target' is the PathTarget to be computed
3389  * 'windowFuncs' is a list of WindowFunc structs
3390  * 'winclause' is a WindowClause that is common to all the WindowFuncs
3391  *
3392  * The input must be sorted according to the WindowClause's PARTITION keys
3393  * plus ORDER BY keys.
3394  */
3395 WindowAggPath *
3397  RelOptInfo *rel,
3398  Path *subpath,
3399  PathTarget *target,
3400  List *windowFuncs,
3401  WindowClause *winclause)
3402 {
3403  WindowAggPath *pathnode = makeNode(WindowAggPath);
3404 
3405  pathnode->path.pathtype = T_WindowAgg;
3406  pathnode->path.parent = rel;
3407  pathnode->path.pathtarget = target;
3408  /* For now, assume we are above any joins, so no parameterization */
3409  pathnode->path.param_info = NULL;
3410  pathnode->path.parallel_aware = false;
3411  pathnode->path.parallel_safe = rel->consider_parallel &&
3412  subpath->parallel_safe;
3413  pathnode->path.parallel_workers = subpath->parallel_workers;
3414  /* WindowAgg preserves the input sort order */
3415  pathnode->path.pathkeys = subpath->pathkeys;
3416 
3417  pathnode->subpath = subpath;
3418  pathnode->winclause = winclause;
3419 
3420  /*
3421  * For costing purposes, assume that there are no redundant partitioning
3422  * or ordering columns; it's not worth the trouble to deal with that
3423  * corner case here. So we just pass the unmodified list lengths to
3424  * cost_windowagg.
3425  */
3426  cost_windowagg(&pathnode->path, root,
3427  windowFuncs,
3428  list_length(winclause->partitionClause),
3429  list_length(winclause->orderClause),
3430  subpath->startup_cost,
3431  subpath->total_cost,
3432  subpath->rows);
3433 
3434  /* add tlist eval cost for each output row */
3435  pathnode->path.startup_cost += target->cost.startup;
3436  pathnode->path.total_cost += target->cost.startup +
3437  target->cost.per_tuple * pathnode->path.rows;
3438 
3439  return pathnode;
3440 }
3441 
3442 /*
3443  * create_setop_path
3444  * Creates a pathnode that represents computation of INTERSECT or EXCEPT
3445  *
3446  * 'rel' is the parent relation associated with the result
3447  * 'subpath' is the path representing the source of data
3448  * 'cmd' is the specific semantics (INTERSECT or EXCEPT, with/without ALL)
3449  * 'strategy' is the implementation strategy (sorted or hashed)
3450  * 'distinctList' is a list of SortGroupClause's representing the grouping
3451  * 'flagColIdx' is the column number where the flag column will be, if any
3452  * 'firstFlag' is the flag value for the first input relation when hashing;
3453  * or -1 when sorting
3454  * 'numGroups' is the estimated number of distinct groups
3455  * 'outputRows' is the estimated number of output rows
3456  */
3457 SetOpPath *
3459  RelOptInfo *rel,
3460  Path *subpath,
3461  SetOpCmd cmd,
3462  SetOpStrategy strategy,
3463  List *distinctList,
3464  AttrNumber flagColIdx,
3465  int firstFlag,
3466  double numGroups,
3467  double outputRows)
3468 {
3469  SetOpPath *pathnode = makeNode(SetOpPath);
3470 
3471  pathnode->path.pathtype = T_SetOp;
3472  pathnode->path.parent = rel;
3473  /* SetOp doesn't project, so use source path's pathtarget */
3474  pathnode->path.pathtarget = subpath->pathtarget;
3475  /* For now, assume we are above any joins, so no parameterization */
3476  pathnode->path.param_info = NULL;
3477  pathnode->path.parallel_aware = false;
3478  pathnode->path.parallel_safe = rel->consider_parallel &&
3479  subpath->parallel_safe;
3480  pathnode->path.parallel_workers = subpath->parallel_workers;
3481  /* SetOp preserves the input sort order if in sort mode */
3482  pathnode->path.pathkeys =
3483  (strategy == SETOP_SORTED) ? subpath->pathkeys : NIL;
3484 
3485  pathnode->subpath = subpath;
3486  pathnode->cmd = cmd;
3487  pathnode->strategy = strategy;
3488  pathnode->distinctList = distinctList;
3489  pathnode->flagColIdx = flagColIdx;
3490  pathnode->firstFlag = firstFlag;
3491  pathnode->numGroups = numGroups;
3492 
3493  /*
3494  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3495  * all columns get compared at most of the tuples.
3496  */
3497  pathnode->path.startup_cost = subpath->startup_cost;
3498  pathnode->path.total_cost = subpath->total_cost +
3499  cpu_operator_cost * subpath->rows * list_length(distinctList);
3500  pathnode->path.rows = outputRows;
3501 
3502  return pathnode;
3503 }
3504 
3505 /*
3506  * create_recursiveunion_path
3507  * Creates a pathnode that represents a recursive UNION node
3508  *
3509  * 'rel' is the parent relation associated with the result
3510  * 'leftpath' is the source of data for the non-recursive term
3511  * 'rightpath' is the source of data for the recursive term
3512  * 'target' is the PathTarget to be computed
3513  * 'distinctList' is a list of SortGroupClause's representing the grouping
3514  * 'wtParam' is the ID of Param representing work table
3515  * 'numGroups' is the estimated number of groups
3516  *
3517  * For recursive UNION ALL, distinctList is empty and numGroups is zero
3518  */
3521  RelOptInfo *rel,
3522  Path *leftpath,
3523  Path *rightpath,
3524  PathTarget *target,
3525  List *distinctList,
3526  int wtParam,
3527  double numGroups)
3528 {
3530 
3531  pathnode->path.pathtype = T_RecursiveUnion;
3532  pathnode->path.parent = rel;
3533  pathnode->path.pathtarget = target;
3534  /* For now, assume we are above any joins, so no parameterization */
3535  pathnode->path.param_info = NULL;
3536  pathnode->path.parallel_aware = false;
3537  pathnode->path.parallel_safe = rel->consider_parallel &&
3538  leftpath->parallel_safe && rightpath->parallel_safe;
3539  /* Foolish, but we'll do it like joins for now: */
3540  pathnode->path.parallel_workers = leftpath->parallel_workers;
3541  /* RecursiveUnion result is always unsorted */
3542  pathnode->path.pathkeys = NIL;
3543 
3544  pathnode->leftpath = leftpath;
3545  pathnode->rightpath = rightpath;
3546  pathnode->distinctList = distinctList;
3547  pathnode->wtParam = wtParam;
3548  pathnode->numGroups = numGroups;
3549 
3550  cost_recursive_union(&pathnode->path, leftpath, rightpath);
3551 
3552  return pathnode;
3553 }
3554 
3555 /*
3556  * create_lockrows_path
3557  * Creates a pathnode that represents acquiring row locks
3558  *
3559  * 'rel' is the parent relation associated with the result
3560  * 'subpath' is the path representing the source of data
3561  * 'rowMarks' is a list of PlanRowMark's
3562  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3563  */
3564 LockRowsPath *
3566  Path *subpath, List *rowMarks, int epqParam)
3567 {
3568  LockRowsPath *pathnode = makeNode(LockRowsPath);
3569 
3570  pathnode->path.pathtype = T_LockRows;
3571  pathnode->path.parent = rel;
3572  /* LockRows doesn't project, so use source path's pathtarget */
3573  pathnode->path.pathtarget = subpath->pathtarget;
3574  /* For now, assume we are above any joins, so no parameterization */
3575  pathnode->path.param_info = NULL;
3576  pathnode->path.parallel_aware = false;
3577  pathnode->path.parallel_safe = false;
3578  pathnode->path.parallel_workers = 0;
3579  pathnode->path.rows = subpath->rows;
3580 
3581  /*
3582  * The result cannot be assumed sorted, since locking might cause the sort
3583  * key columns to be replaced with new values.
3584  */
3585  pathnode->path.pathkeys = NIL;
3586 
3587  pathnode->subpath = subpath;
3588  pathnode->rowMarks = rowMarks;
3589  pathnode->epqParam = epqParam;
3590 
3591  /*
3592  * We should charge something extra for the costs of row locking and
3593  * possible refetches, but it's hard to say how much. For now, use
3594  * cpu_tuple_cost per row.
3595  */
3596  pathnode->path.startup_cost = subpath->startup_cost;
3597  pathnode->path.total_cost = subpath->total_cost +
3598  cpu_tuple_cost * subpath->rows;
3599 
3600  return pathnode;
3601 }
3602 
3603 /*
3604  * create_modifytable_path
3605  * Creates a pathnode that represents performing INSERT/UPDATE/DELETE mods
3606  *
3607  * 'rel' is the parent relation associated with the result
3608  * 'subpath' is a Path producing source data
3609  * 'operation' is the operation type
3610  * 'canSetTag' is true if we set the command tag/es_processed
3611  * 'nominalRelation' is the parent RT index for use of EXPLAIN
3612  * 'rootRelation' is the partitioned table root RT index, or 0 if none
3613  * 'partColsUpdated' is true if any partitioning columns are being updated,
3614  * either from the target relation or a descendent partitioned table.
3615  * 'resultRelations' is an integer list of actual RT indexes of target rel(s)
3616  * 'updateColnosLists' is a list of UPDATE target column number lists
3617  * (one sublist per rel); or NIL if not an UPDATE
3618  * 'withCheckOptionLists' is a list of WCO lists (one per rel)
3619  * 'returningLists' is a list of RETURNING tlists (one per rel)
3620  * 'rowMarks' is a list of PlanRowMarks (non-locking only)
3621  * 'onconflict' is the ON CONFLICT clause, or NULL
3622  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3623  */
3626  Path *subpath,
3627  CmdType operation, bool canSetTag,
3628  Index nominalRelation, Index rootRelation,
3629  bool partColsUpdated,
3630  List *resultRelations,
3631  List *updateColnosLists,
3632  List *withCheckOptionLists, List *returningLists,
3633  List *rowMarks, OnConflictExpr *onconflict,
3634  int epqParam)
3635 {
3637 
3638  Assert(operation == CMD_UPDATE ?
3639  list_length(resultRelations) == list_length(updateColnosLists) :
3640  updateColnosLists == NIL);
3641  Assert(withCheckOptionLists == NIL ||
3642  list_length(resultRelations) == list_length(withCheckOptionLists));
3643  Assert(returningLists == NIL ||
3644  list_length(resultRelations) == list_length(returningLists));
3645 
3646  pathnode->path.pathtype = T_ModifyTable;
3647  pathnode->path.parent = rel;
3648  /* pathtarget is not interesting, just make it minimally valid */
3649  pathnode->path.pathtarget = rel->reltarget;
3650  /* For now, assume we are above any joins, so no parameterization */
3651  pathnode->path.param_info = NULL;
3652  pathnode->path.parallel_aware = false;
3653  pathnode->path.parallel_safe = false;
3654  pathnode->path.parallel_workers = 0;
3655  pathnode->path.pathkeys = NIL;
3656 
3657  /*
3658  * Compute cost & rowcount as subpath cost & rowcount (if RETURNING)
3659  *
3660  * Currently, we don't charge anything extra for the actual table
3661  * modification work, nor for the WITH CHECK OPTIONS or RETURNING
3662  * expressions if any. It would only be window dressing, since
3663  * ModifyTable is always a top-level node and there is no way for the
3664  * costs to change any higher-level planning choices. But we might want
3665  * to make it look better sometime.
3666  */
3667  pathnode->path.startup_cost = subpath->startup_cost;
3668  pathnode->path.total_cost = subpath->total_cost;
3669  if (returningLists != NIL)
3670  {
3671  pathnode->path.rows = subpath->rows;
3672 
3673  /*
3674  * Set width to match the subpath output. XXX this is totally wrong:
3675  * we should return an average of the RETURNING tlist widths. But
3676  * it's what happened historically, and improving it is a task for
3677  * another day. (Again, it's mostly window dressing.)
3678  */
3679  pathnode->path.pathtarget->width = subpath->pathtarget->width;
3680  }
3681  else
3682  {
3683  pathnode->path.rows = 0;
3684  pathnode->path.pathtarget->width = 0;
3685  }
3686 
3687  pathnode->subpath = subpath;
3688  pathnode->operation = operation;
3689  pathnode->canSetTag = canSetTag;
3690  pathnode->nominalRelation = nominalRelation;
3691  pathnode->rootRelation = rootRelation;
3692  pathnode->partColsUpdated = partColsUpdated;
3693  pathnode->resultRelations = resultRelations;
3694  pathnode->updateColnosLists = updateColnosLists;
3695  pathnode->withCheckOptionLists = withCheckOptionLists;
3696  pathnode->returningLists = returningLists;
3697  pathnode->rowMarks = rowMarks;
3698  pathnode->onconflict = onconflict;
3699  pathnode->epqParam = epqParam;
3700 
3701  return pathnode;
3702 }
3703 
3704 /*
3705  * create_limit_path
3706  * Creates a pathnode that represents performing LIMIT/OFFSET
3707  *
3708  * In addition to providing the actual OFFSET and LIMIT expressions,
3709  * the caller must provide estimates of their values for costing purposes.
3710  * The estimates are as computed by preprocess_limit(), ie, 0 represents
3711  * the clause not being present, and -1 means it's present but we could
3712  * not estimate its value.
3713  *
3714  * 'rel' is the parent relation associated with the result
3715  * 'subpath' is the path representing the source of data
3716  * 'limitOffset' is the actual OFFSET expression, or NULL
3717  * 'limitCount' is the actual LIMIT expression, or NULL
3718  * 'offset_est' is the estimated value of the OFFSET expression
3719  * 'count_est' is the estimated value of the LIMIT expression
3720  */
3721 LimitPath *
3723  Path *subpath,
3724  Node *limitOffset, Node *limitCount,
3725  LimitOption limitOption,
3726  int64 offset_est, int64 count_est)
3727 {
3728  LimitPath *pathnode = makeNode(LimitPath);
3729 
3730  pathnode->path.pathtype = T_Limit;
3731  pathnode->path.parent = rel;
3732  /* Limit doesn't project, so use source path's pathtarget */
3733  pathnode->path.pathtarget = subpath->pathtarget;
3734  /* For now, assume we are above any joins, so no parameterization */
3735  pathnode->path.param_info = NULL;
3736  pathnode->path.parallel_aware = false;
3737  pathnode->path.parallel_safe = rel->consider_parallel &&
3738  subpath->parallel_safe;
3739  pathnode->path.parallel_workers = subpath->parallel_workers;
3740  pathnode->path.rows = subpath->rows;
3741  pathnode->path.startup_cost = subpath->startup_cost;
3742  pathnode->path.total_cost = subpath->total_cost;
3743  pathnode->path.pathkeys = subpath->pathkeys;
3744  pathnode->subpath = subpath;
3745  pathnode->limitOffset = limitOffset;
3746  pathnode->limitCount = limitCount;
3747  pathnode->limitOption = limitOption;
3748 
3749  /*
3750  * Adjust the output rows count and costs according to the offset/limit.
3751  */
3752  adjust_limit_rows_costs(&pathnode->path.rows,
3753  &pathnode->path.startup_cost,
3754  &pathnode->path.total_cost,
3755  offset_est, count_est);
3756 
3757  return pathnode;
3758 }
3759 
3760 /*
3761  * adjust_limit_rows_costs
3762  * Adjust the size and cost estimates for a LimitPath node according to the
3763  * offset/limit.
3764  *
3765  * This is only a cosmetic issue if we are at top level, but if we are
3766  * building a subquery then it's important to report correct info to the outer
3767  * planner.
3768  *
3769  * When the offset or count couldn't be estimated, use 10% of the estimated
3770  * number of rows emitted from the subpath.
3771  *
3772  * XXX we don't bother to add eval costs of the offset/limit expressions
3773  * themselves to the path costs. In theory we should, but in most cases those
3774  * expressions are trivial and it's just not worth the trouble.
3775  */
3776 void
3777 adjust_limit_rows_costs(double *rows, /* in/out parameter */
3778  Cost *startup_cost, /* in/out parameter */
3779  Cost *total_cost, /* in/out parameter */
3780  int64 offset_est,
3781  int64 count_est)
3782 {
3783  double input_rows = *rows;
3784  Cost input_startup_cost = *startup_cost;
3785  Cost input_total_cost = *total_cost;
3786 
3787  if (offset_est != 0)
3788  {
3789  double offset_rows;
3790 
3791  if (offset_est > 0)
3792  offset_rows = (double) offset_est;
3793  else
3794  offset_rows = clamp_row_est(input_rows * 0.10);
3795  if (offset_rows > *rows)
3796  offset_rows = *rows;
3797  if (input_rows > 0)
3798  *startup_cost +=
3799  (input_total_cost - input_startup_cost)
3800  * offset_rows / input_rows;
3801  *rows -= offset_rows;
3802  if (*rows < 1)
3803  *rows = 1;
3804  }
3805 
3806  if (count_est != 0)
3807  {
3808  double count_rows;
3809 
3810  if (count_est > 0)
3811  count_rows = (double) count_est;
3812  else
3813  count_rows = clamp_row_est(input_rows * 0.10);
3814  if (count_rows > *rows)
3815  count_rows = *rows;
3816  if (input_rows > 0)
3817  *total_cost = *startup_cost +
3818  (input_total_cost - input_startup_cost)
3819  * count_rows / input_rows;
3820  *rows = count_rows;
3821  if (*rows < 1)
3822  *rows = 1;
3823  }
3824 }
3825 
3826 
3827 /*
3828  * reparameterize_path
3829  * Attempt to modify a Path to have greater parameterization
3830  *
3831  * We use this to attempt to bring all child paths of an appendrel to the
3832  * same parameterization level, ensuring that they all enforce the same set
3833  * of join quals (and thus that that parameterization can be attributed to
3834  * an append path built from such paths). Currently, only a few path types
3835  * are supported here, though more could be added at need. We return NULL
3836  * if we can't reparameterize the given path.
3837  *
3838  * Note: we intentionally do not pass created paths to add_path(); it would
3839  * possibly try to delete them on the grounds of being cost-inferior to the
3840  * paths they were made from, and we don't want that. Paths made here are
3841  * not necessarily of general-purpose usefulness, but they can be useful
3842  * as members of an append path.
3843  */
3844 Path *
3846  Relids required_outer,
3847  double loop_count)
3848 {
3849  RelOptInfo *rel = path->parent;
3850 
3851  /* Can only increase, not decrease, path's parameterization */
3852  if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
3853  return NULL;
3854  switch (path->pathtype)
3855  {
3856  case T_SeqScan:
3857  return create_seqscan_path(root, rel, required_outer, 0);
3858  case T_SampleScan:
3859  return (Path *) create_samplescan_path(root, rel, required_outer);
3860  case T_IndexScan:
3861  case T_IndexOnlyScan:
3862  {
3863  IndexPath *ipath = (IndexPath *) path;
3864  IndexPath *newpath = makeNode(IndexPath);
3865 
3866  /*
3867  * We can't use create_index_path directly, and would not want
3868  * to because it would re-compute the indexqual conditions
3869  * which is wasted effort. Instead we hack things a bit:
3870  * flat-copy the path node, revise its param_info, and redo
3871  * the cost estimate.
3872  */
3873  memcpy(newpath, ipath, sizeof(IndexPath));
3874  newpath->path.param_info =
3875  get_baserel_parampathinfo(root, rel, required_outer);
3876  cost_index(newpath, root, loop_count, false);
3877  return (Path *) newpath;
3878  }
3879  case T_BitmapHeapScan:
3880  {
3881  BitmapHeapPath *bpath = (BitmapHeapPath *) path;
3882 
3883  return (Path *) create_bitmap_heap_path(root,
3884  rel,
3885  bpath->bitmapqual,
3886  required_outer,
3887  loop_count, 0);
3888  }
3889  case T_SubqueryScan:
3890  {
3891  SubqueryScanPath *spath = (SubqueryScanPath *) path;
3892 
3893  return (Path *) create_subqueryscan_path(root,
3894  rel,
3895  spath->subpath,
3896  spath->path.pathkeys,
3897  required_outer);
3898  }
3899  case T_Result:
3900  /* Supported only for RTE_RESULT scan paths */
3901  if (IsA(path, Path))
3902  return create_resultscan_path(root, rel, required_outer);
3903  break;
3904  case T_Append:
3905  {
3906  AppendPath *apath = (AppendPath *) path;
3907  List *childpaths = NIL;
3908  List *partialpaths = NIL;
3909  int i;
3910  ListCell *lc;
3911 
3912  /* Reparameterize the children */
3913  i = 0;
3914  foreach(lc, apath->subpaths)
3915  {
3916  Path *spath = (Path *) lfirst(lc);
3917 
3918  spath = reparameterize_path(root, spath,
3919  required_outer,
3920  loop_count);
3921  if (spath == NULL)
3922  return NULL;
3923  /* We have to re-split the regular and partial paths */
3924  if (i < apath->first_partial_path)
3925  childpaths = lappend(childpaths, spath);
3926  else
3927  partialpaths = lappend(partialpaths, spath);
3928  i++;
3929  }
3930  return (Path *)
3931  create_append_path(root, rel, childpaths, partialpaths,
3932  apath->path.pathkeys, required_outer,
3933  apath->path.parallel_workers,
3934  apath->path.parallel_aware,
3935  -1);
3936  }
3937  case T_Memoize:
3938  {
3939  MemoizePath *mpath = (MemoizePath *) path;
3940 
3941  return (Path *) create_memoize_path(root, rel,
3942  mpath->subpath,
3943  mpath->param_exprs,
3944  mpath->hash_operators,
3945  mpath->singlerow,
3946  mpath->binary_mode,
3947  mpath->calls);
3948  }
3949  default:
3950  break;
3951  }
3952  return NULL;
3953 }
3954 
3955 /*
3956  * reparameterize_path_by_child
3957  * Given a path parameterized by the parent of the given child relation,
3958  * translate the path to be parameterized by the given child relation.
3959  *
3960  * The function creates a new path of the same type as the given path, but
3961  * parameterized by the given child relation. Most fields from the original
3962  * path can simply be flat-copied, but any expressions must be adjusted to
3963  * refer to the correct varnos, and any paths must be recursively
3964  * reparameterized. Other fields that refer to specific relids also need
3965  * adjustment.
3966  *
3967  * The cost, number of rows, width and parallel path properties depend upon
3968  * path->parent, which does not change during the translation. Hence those
3969  * members are copied as they are.
3970  *
3971  * If the given path can not be reparameterized, the function returns NULL.
3972  */
3973 Path *
3975  RelOptInfo *child_rel)
3976 {
3977 
3978 #define FLAT_COPY_PATH(newnode, node, nodetype) \
3979  ( (newnode) = makeNode(nodetype), \
3980  memcpy((newnode), (node), sizeof(nodetype)) )
3981 
3982 #define ADJUST_CHILD_ATTRS(node) \
3983  ((node) = \
3984  (List *) adjust_appendrel_attrs_multilevel(root, (Node *) (node), \
3985  child_rel->relids, \
3986  child_rel->top_parent_relids))
3987 
3988 #define REPARAMETERIZE_CHILD_PATH(path) \
3989 do { \
3990  (path) = reparameterize_path_by_child(root, (path), child_rel); \
3991  if ((path) == NULL) \
3992  return NULL; \
3993 } while(0)
3994 
3995 #define REPARAMETERIZE_CHILD_PATH_LIST(pathlist) \
3996 do { \
3997  if ((pathlist) != NIL) \
3998  { \
3999  (pathlist) = reparameterize_pathlist_by_child(root, (pathlist), \
4000  child_rel); \
4001  if ((pathlist) == NIL) \
4002  return NULL; \
4003  } \
4004 } while(0)
4005 
4006  Path *new_path;
4007  ParamPathInfo *new_ppi;
4008  ParamPathInfo *old_ppi;
4009  Relids required_outer;
4010 
4011  /*
4012  * If the path is not parameterized by parent of the given relation, it
4013  * doesn't need reparameterization.
4014  */
4015  if (!path->param_info ||
4016  !bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
4017  return path;
4018 
4019  /*
4020  * If possible, reparameterize the given path, making a copy.
4021  *
4022  * This function is currently only applied to the inner side of a nestloop
4023  * join that is being partitioned by the partitionwise-join code. Hence,
4024  * we need only support path types that plausibly arise in that context.
4025  * (In particular, supporting sorted path types would be a waste of code
4026  * and cycles: even if we translated them here, they'd just lose in
4027  * subsequent cost comparisons.) If we do see an unsupported path type,
4028  * that just means we won't be able to generate a partitionwise-join plan
4029  * using that path type.
4030  */
4031  switch (nodeTag(path))
4032  {
4033  case T_Path:
4034  FLAT_COPY_PATH(new_path, path, Path);
4035  break;
4036 
4037  case T_IndexPath:
4038  {
4039  IndexPath *ipath;
4040 
4041  FLAT_COPY_PATH(ipath, path, IndexPath);
4043  new_path = (Path *) ipath;
4044  }
4045  break;
4046 
4047  case T_BitmapHeapPath:
4048  {
4049  BitmapHeapPath *bhpath;
4050 
4051  FLAT_COPY_PATH(bhpath, path, BitmapHeapPath);
4053  new_path = (Path *) bhpath;
4054  }
4055  break;
4056 
4057  case T_BitmapAndPath:
4058  {
4059  BitmapAndPath *bapath;
4060 
4061  FLAT_COPY_PATH(bapath, path, BitmapAndPath);
4063  new_path = (Path *) bapath;
4064  }
4065  break;
4066 
4067  case T_BitmapOrPath:
4068  {
4069  BitmapOrPath *bopath;
4070 
4071  FLAT_COPY_PATH(bopath, path, BitmapOrPath);
4073  new_path = (Path *) bopath;
4074  }
4075  break;
4076 
4077  case T_ForeignPath:
4078  {
4079  ForeignPath *fpath;
4081 
4082  FLAT_COPY_PATH(fpath, path, ForeignPath);
4083  if (fpath->fdw_outerpath)
4085 
4086  /* Hand over to FDW if needed. */
4087  rfpc_func =
4089  if (rfpc_func)
4090  fpath->fdw_private = rfpc_func(root, fpath->fdw_private,
4091  child_rel);
4092  new_path = (Path *) fpath;
4093  }
4094  break;
4095 
4096  case T_CustomPath:
4097  {
4098  CustomPath *cpath;
4099 
4100  FLAT_COPY_PATH(cpath, path, CustomPath);
4102  if (cpath->methods &&
4104  cpath->custom_private =
4106  cpath->custom_private,
4107  child_rel);
4108  new_path = (Path *) cpath;
4109  }
4110  break;
4111 
4112  case T_NestPath:
4113  {
4114  JoinPath *jpath;
4115  NestPath *npath;
4116 
4117  FLAT_COPY_PATH(npath, path, NestPath);
4118 
4119  jpath = (JoinPath *) npath;
4123  new_path = (Path *) npath;
4124  }
4125  break;
4126 
4127  case T_MergePath:
4128  {
4129  JoinPath *jpath;
4130  MergePath *mpath;
4131 
4132  FLAT_COPY_PATH(mpath, path, MergePath);
4133 
4134  jpath = (JoinPath *) mpath;
4139  new_path = (Path *) mpath;
4140  }
4141  break;
4142 
4143  case T_HashPath:
4144  {
4145  JoinPath *jpath;
4146  HashPath *hpath;
4147 
4148  FLAT_COPY_PATH(hpath, path, HashPath);
4149 
4150  jpath = (JoinPath *) hpath;
4155  new_path = (Path *) hpath;
4156  }
4157  break;
4158 
4159  case T_AppendPath:
4160  {
4161  AppendPath *apath;
4162 
4163  FLAT_COPY_PATH(apath, path, AppendPath);
4165  new_path = (Path *) apath;
4166  }
4167  break;
4168 
4169  case T_MemoizePath:
4170  {
4171  MemoizePath *mpath;
4172 
4173  FLAT_COPY_PATH(mpath, path, MemoizePath);
4175  new_path = (Path *) mpath;
4176  }
4177  break;
4178 
4179  case T_GatherPath:
4180  {
4181  GatherPath *gpath;
4182 
4183  FLAT_COPY_PATH(gpath, path, GatherPath);
4185  new_path = (Path *) gpath;
4186  }
4187  break;
4188 
4189  default:
4190 
4191  /* We don't know how to reparameterize this path. */
4192  return NULL;
4193  }
4194 
4195  /*
4196  * Adjust the parameterization information, which refers to the topmost
4197  * parent. The topmost parent can be multiple levels away from the given
4198  * child, hence use multi-level expression adjustment routines.
4199  */
4200  old_ppi = new_path->param_info;
4201  required_outer =
4203  child_rel->relids,
4204  child_rel->top_parent_relids);
4205 
4206  /* If we already have a PPI for this parameterization, just return it */
4207  new_ppi = find_param_path_info(new_path->parent, required_outer);
4208 
4209  /*
4210  * If not, build a new one and link it to the list of PPIs. For the same
4211  * reason as explained in mark_dummy_rel(), allocate new PPI in the same
4212  * context the given RelOptInfo is in.
4213  */
4214  if (new_ppi == NULL)
4215  {
4216  MemoryContext oldcontext;
4217  RelOptInfo *rel = path->parent;
4218 
4219  oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
4220 
4221  new_ppi = makeNode(ParamPathInfo);
4222  new_ppi->ppi_req_outer = bms_copy(required_outer);
4223  new_ppi->ppi_rows = old_ppi->ppi_rows;
4224  new_ppi->ppi_clauses = old_ppi->ppi_clauses;
4225  ADJUST_CHILD_ATTRS(new_ppi->ppi_clauses);
4226  rel->ppilist = lappend(rel->ppilist, new_ppi);
4227 
4228  MemoryContextSwitchTo(oldcontext);
4229  }
4230  bms_free(required_outer);
4231 
4232  new_path->param_info = new_ppi;
4233 
4234  /*
4235  * Adjust the path target if the parent of the outer relation is
4236  * referenced in the targetlist. This can happen when only the parent of
4237  * outer relation is laterally referenced in this relation.
4238  */
4239  if (bms_overlap(path->parent->lateral_relids,
4240  child_rel->top_parent_relids))
4241  {
4242  new_path->pathtarget = copy_pathtarget(new_path->pathtarget);
4243  ADJUST_CHILD_ATTRS(new_path->pathtarget->exprs);
4244  }
4245 
4246  return new_path;
4247 }
4248 
4249 /*
4250  * reparameterize_pathlist_by_child
4251  * Helper function to reparameterize a list of paths by given child rel.
4252  */
4253 static List *
4255  List *pathlist,
4256  RelOptInfo *child_rel)
4257 {
4258  ListCell *lc;
4259  List *result = NIL;
4260 
4261  foreach(lc, pathlist)
4262  {
4263  Path *path = reparameterize_path_by_child(root, lfirst(lc),
4264  child_rel);
4265 
4266  if (path == NULL)
4267  {
4268  list_free(result);
4269  return NIL;
4270  }
4271 
4272  result = lappend(result, path);
4273  }
4274 
4275  return result;
4276 }
Datum sort(PG_FUNCTION_ARGS)
Definition: _int_op.c:195
bool query_is_distinct_for(Query *query, List *colnos, List *opids)
Definition: analyzejoins.c:775
bool query_supports_distinctness(Query *query)
Definition: analyzejoins.c:738
Relids adjust_child_relids_multilevel(PlannerInfo *root, Relids relids, Relids child_relids, Relids top_parent_relids)
Definition: appendinfo.c:562
int16 AttrNumber
Definition: attnum.h:21
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94
BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:352
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:795
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:930
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:703
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
int bms_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:147
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
BMS_Comparison
Definition: bitmapset.h:58
@ BMS_DIFFERENT
Definition: bitmapset.h:62
@ BMS_SUBSET1
Definition: bitmapset.h:60
@ BMS_EQUAL
Definition: bitmapset.h:59
@ BMS_SUBSET2
Definition: bitmapset.h:61
unsigned int Index
Definition: c.h:549
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:640
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:288
double cpu_operator_cost
Definition: costsize.c:123
void final_cost_hashjoin(PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
Definition: costsize.c:3849
void final_cost_mergejoin(PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
Definition: costsize.c:3413
void cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1441
void cost_material(Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
Definition: costsize.c:2365
void cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
Definition: costsize.c:955
void cost_tidrangescan(Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, ParamPathInfo *param_info)
Definition: costsize.c:1299
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
void final_cost_nestloop(PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
Definition: costsize.c:2977
void cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
Definition: costsize.c:1723
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
void cost_tablefuncscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1502
double cpu_tuple_cost
Definition: costsize.c:121
void cost_samplescan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:303
void cost_gather(GatherPath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, double *rows)
Definition: costsize.c:378
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
void cost_namedtuplestorescan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1649
void cost_seqscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:226
void cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1558
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
void cost_resultscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1686
void cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
Definition: costsize.c:1099
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
void cost_tidscan(Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
Definition: costsize.c:1191
double clamp_row_est(double nrows)
Definition: costsize.c:199
void cost_append(AppendPath *apath)
Definition: costsize.c:2143
void cost_ctescan(Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1608
void cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
Definition: costsize.c:1143
void cost_subqueryscan(SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
Definition: costsize.c:1392
void cost_index(IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
Definition: costsize.c:491
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
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
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
bool is_projection_capable_path(Path *path)
Definition: createplan.c:7037
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3161
List *(* ReparameterizeForeignPathByChild_function)(PlannerInfo *root, List *fdw_private, RelOptInfo *child_rel)
Definition: fdwapi.h:182
int work_mem
Definition: globals.c:124
bool relation_has_unique_index_for(PlannerInfo *root, RelOptInfo *rel, List *restrictlist, List *exprlist, List *oprlist)
Definition: indxpath.c:3511
int b
Definition: isn.c:70
int a
Definition: isn.c:69
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1612
List * list_insert_nth(List *list, int pos, void *datum)
Definition: list.c:418
List * lappend(List *list, void *datum)
Definition: list.c:336
List * lappend_int(List *list, int datum)
Definition: list.c:354
void list_free(List *list)
Definition: list.c:1505
List * list_concat(List *list1, const List *list2)
Definition: list.c:540
List * lcons(void *datum, List *list)
Definition: list.c:474
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void pfree(void *pointer)
Definition: mcxt.c:1169
static MemoryContext GetMemoryChunkContext(void *pointer)
Definition: memutils.h:114
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3401
SetOpCmd
Definition: nodes.h:813
SetOpStrategy
Definition: nodes.h:821
@ SETOP_SORTED
Definition: nodes.h:822
#define IsA(nodeptr, _type_)
Definition: nodes.h:589
double Cost
Definition: nodes.h:672
#define nodeTag(nodeptr)
Definition: nodes.h:543
CmdType
Definition: nodes.h:683
@ CMD_UPDATE
Definition: nodes.h:686
AggStrategy
Definition: nodes.h:769
@ AGG_SORTED
Definition: nodes.h:771
@ AGG_HASHED
Definition: nodes.h:772
@ AGG_MIXED
Definition: nodes.h:773
@ AGG_PLAIN
Definition: nodes.h:770
@ T_Unique
Definition: nodes.h:83
@ T_NamedTuplestoreScan
Definition: nodes.h:68
@ T_HashPath
Definition: nodes.h:241
@ T_TidRangeScan
Definition: nodes.h:62
@ T_TableFuncScan
Definition: nodes.h:66
@ T_FunctionScan
Definition: nodes.h:64
@ T_NestPath
Definition: nodes.h:239
@ T_BitmapOr
Definition: nodes.h:53
@ T_CustomPath
Definition: nodes.h:238
@ T_Material
Definition: nodes.h:76
@ T_IndexOnlyScan
Definition: nodes.h:58
@ T_Append
Definition: nodes.h:49
@ T_Gather
Definition: nodes.h:84
@ T_RecursiveUnion
Definition: nodes.h:51
@ T_LockRows
Definition: nodes.h:88
@ T_TidScan
Definition: nodes.h:61
@ T_Limit
Definition: nodes.h:89
@ T_MemoizePath
Definition: nodes.h:246
@ T_Memoize
Definition: nodes.h:77
@ T_Sort
Definition: nodes.h:78
@ T_BitmapAndPath
Definition: nodes.h:232
@ T_SeqScan
Definition: nodes.h:55
@ T_WindowAgg
Definition: nodes.h:82
@ T_ForeignPath
Definition: nodes.h:237
@ T_ProjectSet
Definition: nodes.h:47
@ T_MergeJoin
Definition: nodes.h:74
@ T_SampleScan
Definition: nodes.h:56
@ T_ValuesScan
Definition: nodes.h:65
@ T_BitmapAnd
Definition: nodes.h:52
@ T_MergeAppend
Definition: nodes.h:50
@ T_BitmapHeapPath
Definition: nodes.h:231
@ T_Agg
Definition: nodes.h:81
@ T_CteScan
Definition: nodes.h:67
@ T_NestLoop
Definition: nodes.h:73
@ T_IncrementalSort
Definition: nodes.h:79
@ T_Group
Definition: nodes.h:80
@ T_ModifyTable
Definition: nodes.h:48
@ T_GatherMerge
Definition: nodes.h:85
@ T_SubqueryScan
Definition: nodes.h:63
@ T_MergePath
Definition: nodes.h:240
@ T_SetOp
Definition: nodes.h:87
@ T_Result
Definition: nodes.h:46
@ T_AppendPath
Definition: nodes.h:242
@ T_IndexScan
Definition: nodes.h:57
@ T_BitmapOrPath
Definition: nodes.h:233
@ T_BitmapHeapScan
Definition: nodes.h:60
@ T_WorkTableScan
Definition: nodes.h:69
@ T_ForeignScan
Definition: nodes.h:70
@ T_HashJoin
Definition: nodes.h:75
@ T_Path
Definition: nodes.h:229
@ T_GatherPath
Definition: nodes.h:248
@ T_IndexPath
Definition: nodes.h:230
AggSplit
Definition: nodes.h:791
LimitOption
Definition: nodes.h:846
#define makeNode(_type_)
Definition: nodes.h:586
JoinType
Definition: nodes.h:707
@ JOIN_SEMI
Definition: nodes.h:726
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
@ RTE_SUBQUERY
Definition: parsenodes.h:990
@ RTE_RELATION
Definition: parsenodes.h:989
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:285
#define REPARAMETERIZE_CHILD_PATH_LIST(pathlist)
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:2301
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
static int append_startup_cost_compare(const ListCell *a, const ListCell *b)
Definition: pathnode.c:1386
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2942
TidPath * create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals, Relids required_outer)
Definition: pathnode.c:1183
#define REPARAMETERIZE_CHILD_PATH(path)
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition: pathnode.c:1504
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:2407
Relids calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
Definition: pathnode.c:2374
UniquePath * create_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, SpecialJoinInfo *sjinfo)
Definition: pathnode.c:1640
static PathCostComparison compare_path_costs_fuzzily(Path *path1, Path *path2, double fuzz_factor)
Definition: pathnode.c:166
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
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:3722
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:2207
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2627
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1861
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:3045
#define STD_FUZZ_FACTOR
Definition: pathnode.c:51
Relids calc_nestloop_required_outer(Relids outerrelids, Relids outer_paramrels, Relids innerrelids, Relids inner_paramrels)
Definition: pathnode.c:2341
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:3164
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2045
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2122
#define FLAT_COPY_PATH(newnode, node, nodetype)
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:3625
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition: pathnode.c:3565
Path * reparameterize_path_by_child(PlannerInfo *root, Path *path, RelOptInfo *child_rel)
Definition: pathnode.c:3974
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:2495
static List * reparameterize_pathlist_by_child(PlannerInfo *root, List *pathlist, RelOptInfo *child_rel)
Definition: pathnode.c:4254
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1952
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2148
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause)
Definition: pathnode.c:3396
Path * create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:954
MemoizePath * create_memoize_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *param_exprs, List *hash_operators, bool singlerow, bool binary_mode, double calls)
Definition: pathnode.c:1584
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1404
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3845
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2824
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2097
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
MaterialPath * create_material_path(RelOptInfo *rel, Path *subpath)
Definition: pathnode.c:1552
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2019
#define ADJUST_CHILD_ATTRS(node)
BitmapOrPath * create_bitmap_or_path(PlannerInfo *root, RelOptInfo *rel, List *bitmapquals)
Definition: pathnode.c:1131
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2986
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:2251
PathCostComparison
Definition: pathnode.c:39
@ COSTS_EQUAL
Definition: pathnode.c:40
@ COSTS_BETTER1
Definition: pathnode.c:41
@ COSTS_BETTER2
Definition: pathnode.c:42
@ COSTS_DIFFERENT
Definition: pathnode.c:43
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:2561
bool add_partial_path_precheck(RelOptInfo *parent_rel, Cost total_cost, List *pathkeys)
Definition: pathnode.c:867
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:3458
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1991
RecursiveUnionPath * create_recursiveunion_path(PlannerInfo *root, RelOptInfo *rel, Path *leftpath, Path *rightpath, PathTarget *target, List *distinctList, int wtParam, double numGroups)
Definition: pathnode.c:3520
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2893
MinMaxAggPath * create_minmaxagg_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *mmaggregates, List *quals)
Definition: pathnode.c:3325
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2174
#define CONSIDER_PATH_STARTUP_COST(p)
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:3097
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2071
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:71
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2735
static int append_total_cost_compare(const ListCell *a, const ListCell *b)
Definition: pathnode.c:1364
BitmapAndPath * create_bitmap_and_path(PlannerInfo *root, RelOptInfo *rel, List *bitmapquals)
Definition: pathnode.c:1079
TidRangePath * create_tidrangescan_path(PlannerInfo *root, RelOptInfo *rel, List *tidrangequals, Relids required_outer)
Definition: pathnode.c:1212
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:929
void adjust_limit_rows_costs(double *rows, Cost *startup_cost, Cost *total_cost, int64 offset_est, int64 count_est)
Definition: pathnode.c:3777
static List * translate_sub_tlist(List *tlist, int relid)
Definition: pathnode.c:1926
bool add_path_precheck(RelOptInfo *parent_rel, Cost startup_cost, Cost total_cost, List *pathkeys, Relids required_outer)
Definition: pathnode.c:644
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1046
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:654
@ UNIQUE_PATH_SORT
Definition: pathnodes.h:1542
@ UNIQUE_PATH_NOOP
Definition: pathnodes.h:1540
@ UNIQUE_PATH_HASH
Definition: pathnodes.h:1541
CostSelector
Definition: pathnodes.h:35
@ TOTAL_COST
Definition: pathnodes.h:36
@ STARTUP_COST
Definition: pathnodes.h:36
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:786
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1201
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:388
@ RELOPT_BASEREL
Definition: pathnodes.h:641
PathKeysComparison
Definition: paths.h:196
@ PATHKEYS_BETTER2
Definition: paths.h:199
@ PATHKEYS_BETTER1
Definition: paths.h:198
@ PATHKEYS_DIFFERENT
Definition: paths.h:200
@ PATHKEYS_EQUAL
Definition: paths.h:197
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define NIL
Definition: pg_list.h:65
#define linitial(l)
Definition: pg_list.h:174
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
#define foreach_current_index(cell)
Definition: pg_list.h:382
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:747
ParamPathInfo * get_baserel_parampathinfo(PlannerInfo *root, RelOptInfo *baserel, Relids required_outer)
Definition: relnode.c:1297
ParamPathInfo * get_appendrel_parampathinfo(RelOptInfo *appendrel, Relids required_outer)
Definition: relnode.c:1594
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
ParamPathInfo * find_param_path_info(RelOptInfo *rel, Relids required_outer)
Definition: relnode.c:1626
bool join_clause_is_movable_into(RestrictInfo *rinfo, Relids currentrelids, Relids current_and_outer)
Definition: restrictinfo.c:600
ScanDirection
Definition: sdir.h:23
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3368
Size transitionSpace
Definition: pathnodes.h:60
Path * subpath
Definition: pathnodes.h:1772
Cardinality numGroups
Definition: pathnodes.h:1775
AggSplit aggsplit
Definition: pathnodes.h:1774
List * groupClause
Definition: pathnodes.h:1777
uint64 transitionSpace
Definition: pathnodes.h:1776
AggStrategy aggstrategy
Definition: pathnodes.h:1773
Path path
Definition: pathnodes.h:1771
List * qual
Definition: pathnodes.h:1778
int first_partial_path
Definition: pathnodes.h:1454
Cardinality limit_tuples
Definition: pathnodes.h:1455
List * subpaths
Definition: pathnodes.h:1452
List * bitmapquals
Definition: pathnodes.h:1330
Path * bitmapqual
Definition: pathnodes.h:1318
List * bitmapquals
Definition: pathnodes.h:1343
struct List *(* ReparameterizeCustomPathByChild)(PlannerInfo *root, List *custom_private, RelOptInfo *child_rel)
Definition: extensible.h:101
const struct CustomPathMethods * methods
Definition: pathnodes.h:1431
List * custom_paths
Definition: pathnodes.h:1429
List * custom_private
Definition: pathnodes.h:1430
ReparameterizeForeignPathByChild_function ReparameterizeForeignPathByChild
Definition: fdwapi.h:274
Path * fdw_outerpath
Definition: pathnodes.h:1399
List * fdw_private
Definition: pathnodes.h:1400
bool single_copy
Definition: pathnodes.h:1563
Path * subpath
Definition: pathnodes.h:1562
int num_workers
Definition: pathnodes.h:1564
List * qual
Definition: pathnodes.h:1746
List * groupClause
Definition: pathnodes.h:1745
Path * subpath
Definition: pathnodes.h:1744
Path path
Definition: pathnodes.h:1743
uint64 transitionSpace
Definition: pathnodes.h:1814
AggStrategy aggstrategy
Definition: pathnodes.h:1811
List * path_hashclauses
Definition: pathnodes.h:1670
JoinPath jpath
Definition: pathnodes.h:1669
List * indexclauses
Definition: pathnodes.h:1246
ScanDirection indexscandir
Definition: pathnodes.h:1249
Path path
Definition: pathnodes.h:1244
List * indexorderbycols
Definition: pathnodes.h:1248
List * indexorderbys
Definition: pathnodes.h:1247
IndexOptInfo * indexinfo
Definition: pathnodes.h:1245
SpecialJoinInfo * sjinfo
Definition: pathnodes.h:2535
Path * outerjoinpath
Definition: pathnodes.h:1592
Path path
Definition: pathnodes.h:1585
Path * innerjoinpath
Definition: pathnodes.h:1593
JoinType jointype
Definition: pathnodes.h:1587
bool inner_unique
Definition: pathnodes.h:1589
List * joinrestrictinfo
Definition: pathnodes.h:1595
Path path
Definition: pathnodes.h:1906
Path * subpath
Definition: pathnodes.h:1907
LimitOption limitOption
Definition: pathnodes.h:1910
Node * limitOffset
Definition: pathnodes.h:1908
Node * limitCount
Definition: pathnodes.h:1909
Definition: pg_list.h:51
Path * subpath
Definition: pathnodes.h:1871
List * rowMarks
Definition: pathnodes.h:1872
Path * subpath
Definition: pathnodes.h:1502
bool singlerow
Definition: pathnodes.h:1516
List * hash_operators
Definition: pathnodes.h:1514
uint32 est_entries
Definition: pathnodes.h:1521
bool binary_mode
Definition: pathnodes.h:1518
Cardinality calls
Definition: pathnodes.h:1520
Path * subpath
Definition: pathnodes.h:1513
List * param_exprs
Definition: pathnodes.h:1515
Cardinality limit_tuples
Definition: pathnodes.h:1477
List * outersortkeys
Definition: pathnodes.h:1652
List * innersortkeys
Definition: pathnodes.h:1653
JoinPath jpath
Definition: pathnodes.h:1650
List * path_mergeclauses
Definition: pathnodes.h:1651
List * quals
Definition: pathnodes.h:1824
List * mmaggregates
Definition: pathnodes.h:1823
bool partColsUpdated
Definition: pathnodes.h:1891
List * returningLists
Definition: pathnodes.h:1895
List * resultRelations
Definition: pathnodes.h:1892
List * withCheckOptionLists
Definition: pathnodes.h:1894
List * updateColnosLists
Definition: pathnodes.h:1893
OnConflictExpr * onconflict
Definition: pathnodes.h:1897
CmdType operation
Definition: pathnodes.h:1887
Index rootRelation
Definition: pathnodes.h:1890
Index nominalRelation
Definition: pathnodes.h:1889
JoinPath jpath
Definition: pathnodes.h:1610
Definition: nodes.h:539
Cardinality ppi_rows
Definition: pathnodes.h:1142
List * ppi_clauses
Definition: pathnodes.h:1143
Relids ppi_req_outer
Definition: pathnodes.h:1141
List * exprs
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1112
List * pathkeys
Definition: pathnodes.h:1196
NodeTag pathtype
Definition: pathnodes.h:1180
RelOptInfo * parent
Definition: pathnodes.h:1182
Cardinality rows
Definition: pathnodes.h:1192
Cost startup_cost
Definition: pathnodes.h:1193
int parallel_workers
Definition: pathnodes.h:1189
ParamPathInfo * param_info
Definition: pathnodes.h:1185
PathTarget * pathtarget
Definition: pathnodes.h:1183
Cost total_cost
Definition: pathnodes.h:1194
bool parallel_aware
Definition: pathnodes.h:1187
bool parallel_safe
Definition: pathnodes.h:1188
List * group_pathkeys
Definition: pathnodes.h:296
Cardinality limit_tuples
Definition: pathnodes.h:341
Relids all_baserels
Definition: pathnodes.h:210
Path * subpath
Definition: pathnodes.h:1704
Path * subpath
Definition: pathnodes.h:1692
Cost per_tuple
Definition: pathnodes.h:46
Cost startup
Definition: pathnodes.h:45
Query * subquery
Definition: parsenodes.h:1041
Cardinality numGroups
Definition: pathnodes.h:1862
bool consider_param_startup
Definition: pathnodes.h:688
List * ppilist
Definition: pathnodes.h:696
Relids relids
Definition: pathnodes.h:681
struct PathTarget * reltarget
Definition: pathnodes.h:692
Index relid
Definition: pathnodes.h:709
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
bool consider_parallel
Definition: pathnodes.h:689
Relids top_parent_relids
Definition: pathnodes.h:756
Relids lateral_relids
Definition: pathnodes.h:706
List * cheapest_parameterized_paths
Definition: pathnodes.h:701
List * pathlist
Definition: pathnodes.h:695
RelOptKind reloptkind
Definition: pathnodes.h:678
struct Path * cheapest_unique_path
Definition: pathnodes.h:700
struct Path * cheapest_startup_path
Definition: pathnodes.h:698
struct Path * cheapest_total_path
Definition: pathnodes.h:699
bool consider_startup
Definition: pathnodes.h:687
List * partial_pathlist
Definition: pathnodes.h:697
Cardinality rows
Definition: pathnodes.h:684
RTEKind rtekind
Definition: pathnodes.h:711
Cardinality numGroups
Definition: pathnodes.h:1798
List * gsets
Definition: pathnodes.h:1796
bool is_hashed
Definition: pathnodes.h:1800
List * distinctList
Definition: pathnodes.h:1846
Cardinality numGroups
Definition: pathnodes.h:1849
int firstFlag
Definition: pathnodes.h:1848
Path * subpath
Definition: pathnodes.h:1843
SetOpCmd cmd
Definition: pathnodes.h:1844
Path path
Definition: pathnodes.h:1842
SetOpStrategy strategy
Definition: pathnodes.h:1845
AttrNumber flagColIdx
Definition: pathnodes.h:1847
Path path
Definition: pathnodes.h:1717
Path * subpath
Definition: pathnodes.h:1718
List * semi_rhs_exprs
Definition: pathnodes.h:2266
JoinType jointype
Definition: pathnodes.h:2259
Relids syn_righthand
Definition: pathnodes.h:2258
List * semi_operators
Definition: pathnodes.h:2265
List * tidquals
Definition: pathnodes.h:1357
Path path
Definition: pathnodes.h:1356
List * tidrangequals
Definition: pathnodes.h:1369
Path * subpath
Definition: pathnodes.h:1548
List * uniq_exprs
Definition: pathnodes.h:1551
UniquePathMethod umethod
Definition: pathnodes.h:1549
List * in_operators
Definition: pathnodes.h:1550
Definition: primnodes.h:187
AttrNumber varattno
Definition: primnodes.h:191
int varno
Definition: primnodes.h:189
Path * subpath
Definition: pathnodes.h:1833
WindowClause * winclause
Definition: pathnodes.h:1834
List * partitionClause
Definition: parsenodes.h:1390
List * orderClause
Definition: parsenodes.h:1391
Definition: type.h:90
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:646