1 /*-------------------------------------------------------------------------
4 * Routines to manipulate pathlists and create path nodes
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/optimizer/util/pathnode.c
13 *-------------------------------------------------------------------------
19 #include "miscadmin.h"
20 #include "foreign/fdwapi.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"
41 COSTS_EQUAL, /* path costs are fuzzily equal */
42 COSTS_BETTER1, /* first path is cheaper than second */
43 COSTS_BETTER2, /* second path is cheaper than first */
44 COSTS_DIFFERENT /* neither path dominates the other on cost */
48 * STD_FUZZ_FACTOR is the normal fuzz factor for compare_path_costs_fuzzily.
49 * XXX is it worth making this user-controllable? It provides a tradeoff
50 * between planner runtime and the accuracy of path cost comparisons.
52 #define STD_FUZZ_FACTOR 1.01
54 static List *translate_sub_tlist(List *tlist, int relid);
55 static int append_total_cost_compare(const void *a, const void *b);
56 static int append_startup_cost_compare(const void *a, const void *b);
57 static List *reparameterize_pathlist_by_child(PlannerInfo *root,
59 RelOptInfo *child_rel);
62 /*****************************************************************************
63 * MISC. PATH UTILITIES
64 *****************************************************************************/
68 * Return -1, 0, or +1 according as path1 is cheaper, the same cost,
69 * or more expensive than path2 for the specified criterion.
72 compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
74 if (criterion == STARTUP_COST)
76 if (path1->startup_cost < path2->startup_cost)
78 if (path1->startup_cost > path2->startup_cost)
82 * If paths have the same startup cost (not at all unlikely), order
85 if (path1->total_cost < path2->total_cost)
87 if (path1->total_cost > path2->total_cost)
92 if (path1->total_cost < path2->total_cost)
94 if (path1->total_cost > path2->total_cost)
98 * If paths have the same total cost, order them by startup cost.
100 if (path1->startup_cost < path2->startup_cost)
102 if (path1->startup_cost > path2->startup_cost)
109 * compare_path_fractional_costs
110 * Return -1, 0, or +1 according as path1 is cheaper, the same cost,
111 * or more expensive than path2 for fetching the specified fraction
112 * of the total tuples.
114 * If fraction is <= 0 or > 1, we interpret it as 1, ie, we select the
115 * path with the cheaper total_cost.
118 compare_fractional_path_costs(Path *path1, Path *path2,
124 if (fraction <= 0.0 || fraction >= 1.0)
125 return compare_path_costs(path1, path2, TOTAL_COST);
126 cost1 = path1->startup_cost +
127 fraction * (path1->total_cost - path1->startup_cost);
128 cost2 = path2->startup_cost +
129 fraction * (path2->total_cost - path2->startup_cost);
138 * compare_path_costs_fuzzily
139 * Compare the costs of two paths to see if either can be said to
140 * dominate the other.
142 * We use fuzzy comparisons so that add_path() can avoid keeping both of
143 * a pair of paths that really have insignificantly different cost.
145 * The fuzz_factor argument must be 1.0 plus delta, where delta is the
146 * fraction of the smaller cost that is considered to be a significant
147 * difference. For example, fuzz_factor = 1.01 makes the fuzziness limit
148 * be 1% of the smaller cost.
150 * The two paths are said to have "equal" costs if both startup and total
151 * costs are fuzzily the same. Path1 is said to be better than path2 if
152 * it has fuzzily better startup cost and fuzzily no worse total cost,
153 * or if it has fuzzily better total cost and fuzzily no worse startup cost.
154 * Path2 is better than path1 if the reverse holds. Finally, if one path
155 * is fuzzily better than the other on startup cost and fuzzily worse on
156 * total cost, we just say that their costs are "different", since neither
157 * dominates the other across the whole performance spectrum.
159 * This function also enforces a policy rule that paths for which the relevant
160 * one of parent->consider_startup and parent->consider_param_startup is false
161 * cannot survive comparisons solely on the grounds of good startup cost, so
162 * we never return COSTS_DIFFERENT when that is true for the total-cost loser.
163 * (But if total costs are fuzzily equal, we compare startup costs anyway,
164 * in hopes of eliminating one path or the other.)
166 static PathCostComparison
167 compare_path_costs_fuzzily(Path *path1, Path *path2, double fuzz_factor)
169 #define CONSIDER_PATH_STARTUP_COST(p) \
170 ((p)->param_info == NULL ? (p)->parent->consider_startup : (p)->parent->consider_param_startup)
173 * Check total cost first since it's more likely to be different; many
174 * paths have zero startup cost.
176 if (path1->total_cost > path2->total_cost * fuzz_factor)
178 /* path1 fuzzily worse on total cost */
179 if (CONSIDER_PATH_STARTUP_COST(path1) &&
180 path2->startup_cost > path1->startup_cost * fuzz_factor)
182 /* ... but path2 fuzzily worse on startup, so DIFFERENT */
183 return COSTS_DIFFERENT;
185 /* else path2 dominates */
186 return COSTS_BETTER2;
188 if (path2->total_cost > path1->total_cost * fuzz_factor)
190 /* path2 fuzzily worse on total cost */
191 if (CONSIDER_PATH_STARTUP_COST(path2) &&
192 path1->startup_cost > path2->startup_cost * fuzz_factor)
194 /* ... but path1 fuzzily worse on startup, so DIFFERENT */
195 return COSTS_DIFFERENT;
197 /* else path1 dominates */
198 return COSTS_BETTER1;
200 /* fuzzily the same on total cost ... */
201 if (path1->startup_cost > path2->startup_cost * fuzz_factor)
203 /* ... but path1 fuzzily worse on startup, so path2 wins */
204 return COSTS_BETTER2;
206 if (path2->startup_cost > path1->startup_cost * fuzz_factor)
208 /* ... but path2 fuzzily worse on startup, so path1 wins */
209 return COSTS_BETTER1;
211 /* fuzzily the same on both costs */
214 #undef CONSIDER_PATH_STARTUP_COST
219 * Find the minimum-cost paths from among a relation's paths,
220 * and save them in the rel's cheapest-path fields.
222 * cheapest_total_path is normally the cheapest-total-cost unparameterized
223 * path; but if there are no unparameterized paths, we assign it to be the
224 * best (cheapest least-parameterized) parameterized path. However, only
225 * unparameterized paths are considered candidates for cheapest_startup_path,
226 * so that will be NULL if there are no unparameterized paths.
228 * The cheapest_parameterized_paths list collects all parameterized paths
229 * that have survived the add_path() tournament for this relation. (Since
230 * add_path ignores pathkeys for a parameterized path, these will be paths
231 * that have best cost or best row count for their parameterization. We
232 * may also have both a parallel-safe and a non-parallel-safe path in some
233 * cases for the same parameterization in some cases, but this should be
234 * relatively rare since, most typically, all paths for the same relation
235 * will be parallel-safe or none of them will.)
237 * cheapest_parameterized_paths always includes the cheapest-total
238 * unparameterized path, too, if there is one; the users of that list find
239 * it more convenient if that's included.
241 * This is normally called only after we've finished constructing the path
242 * list for the rel node.
245 set_cheapest(RelOptInfo *parent_rel)
247 Path *cheapest_startup_path;
248 Path *cheapest_total_path;
249 Path *best_param_path;
250 List *parameterized_paths;
253 Assert(IsA(parent_rel, RelOptInfo));
255 if (parent_rel->pathlist == NIL)
256 elog(ERROR, "could not devise a query plan for the given query");
258 cheapest_startup_path = cheapest_total_path = best_param_path = NULL;
259 parameterized_paths = NIL;
261 foreach(p, parent_rel->pathlist)
263 Path *path = (Path *) lfirst(p);
266 if (path->param_info)
268 /* Parameterized path, so add it to parameterized_paths */
269 parameterized_paths = lappend(parameterized_paths, path);
272 * If we have an unparameterized cheapest-total, we no longer care
273 * about finding the best parameterized path, so move on.
275 if (cheapest_total_path)
279 * Otherwise, track the best parameterized path, which is the one
280 * with least total cost among those of the minimum
283 if (best_param_path == NULL)
284 best_param_path = path;
287 switch (bms_subset_compare(PATH_REQ_OUTER(path),
288 PATH_REQ_OUTER(best_param_path)))
291 /* keep the cheaper one */
292 if (compare_path_costs(path, best_param_path,
294 best_param_path = path;
297 /* new path is less-parameterized */
298 best_param_path = path;
301 /* old path is less-parameterized, keep it */
306 * This means that neither path has the least possible
307 * parameterization for the rel. We'll sit on the old
308 * path until something better comes along.
316 /* Unparameterized path, so consider it for cheapest slots */
317 if (cheapest_total_path == NULL)
319 cheapest_startup_path = cheapest_total_path = path;
324 * If we find two paths of identical costs, try to keep the
325 * better-sorted one. The paths might have unrelated sort
326 * orderings, in which case we can only guess which might be
327 * better to keep, but if one is superior then we definitely
328 * should keep that one.
330 cmp = compare_path_costs(cheapest_startup_path, path, STARTUP_COST);
333 compare_pathkeys(cheapest_startup_path->pathkeys,
334 path->pathkeys) == PATHKEYS_BETTER2))
335 cheapest_startup_path = path;
337 cmp = compare_path_costs(cheapest_total_path, path, TOTAL_COST);
340 compare_pathkeys(cheapest_total_path->pathkeys,
341 path->pathkeys) == PATHKEYS_BETTER2))
342 cheapest_total_path = path;
346 /* Add cheapest unparameterized path, if any, to parameterized_paths */
347 if (cheapest_total_path)
348 parameterized_paths = lcons(cheapest_total_path, parameterized_paths);
351 * If there is no unparameterized path, use the best parameterized path as
352 * cheapest_total_path (but not as cheapest_startup_path).
354 if (cheapest_total_path == NULL)
355 cheapest_total_path = best_param_path;
356 Assert(cheapest_total_path != NULL);
358 parent_rel->cheapest_startup_path = cheapest_startup_path;
359 parent_rel->cheapest_total_path = cheapest_total_path;
360 parent_rel->cheapest_unique_path = NULL; /* computed only if needed */
361 parent_rel->cheapest_parameterized_paths = parameterized_paths;
366 * Consider a potential implementation path for the specified parent rel,
367 * and add it to the rel's pathlist if it is worthy of consideration.
368 * A path is worthy if it has a better sort order (better pathkeys) or
369 * cheaper cost (on either dimension), or generates fewer rows, than any
370 * existing path that has the same or superset parameterization rels.
371 * We also consider parallel-safe paths more worthy than others.
373 * We also remove from the rel's pathlist any old paths that are dominated
374 * by new_path --- that is, new_path is cheaper, at least as well ordered,
375 * generates no more rows, requires no outer rels not required by the old
376 * path, and is no less parallel-safe.
378 * In most cases, a path with a superset parameterization will generate
379 * fewer rows (since it has more join clauses to apply), so that those two
380 * figures of merit move in opposite directions; this means that a path of
381 * one parameterization can seldom dominate a path of another. But such
382 * cases do arise, so we make the full set of checks anyway.
384 * There are two policy decisions embedded in this function, along with
385 * its sibling add_path_precheck. First, we treat all parameterized paths
386 * as having NIL pathkeys, so that they cannot win comparisons on the
387 * basis of sort order. This is to reduce the number of parameterized
388 * paths that are kept; see discussion in src/backend/optimizer/README.
390 * Second, we only consider cheap startup cost to be interesting if
391 * parent_rel->consider_startup is true for an unparameterized path, or
392 * parent_rel->consider_param_startup is true for a parameterized one.
393 * Again, this allows discarding useless paths sooner.
395 * The pathlist is kept sorted by total_cost, with cheaper paths
396 * at the front. Within this routine, that's simply a speed hack:
397 * doing it that way makes it more likely that we will reject an inferior
398 * path after a few comparisons, rather than many comparisons.
399 * However, add_path_precheck relies on this ordering to exit early
402 * NOTE: discarded Path objects are immediately pfree'd to reduce planner
403 * memory consumption. We dare not try to free the substructure of a Path,
404 * since much of it may be shared with other Paths or the query tree itself;
405 * but just recycling discarded Path nodes is a very useful savings in
406 * a large join tree. We can recycle the List nodes of pathlist, too.
408 * As noted in optimizer/README, deleting a previously-accepted Path is
409 * safe because we know that Paths of this rel cannot yet be referenced
410 * from any other rel, such as a higher-level join. However, in some cases
411 * it is possible that a Path is referenced by another Path for its own
412 * rel; we must not delete such a Path, even if it is dominated by the new
413 * Path. Currently this occurs only for IndexPath objects, which may be
414 * referenced as children of BitmapHeapPaths as well as being paths in
415 * their own right. Hence, we don't pfree IndexPaths when rejecting them.
417 * 'parent_rel' is the relation entry to which the path corresponds.
418 * 'new_path' is a potential path for parent_rel.
420 * Returns nothing, but modifies parent_rel->pathlist.
423 add_path(RelOptInfo *parent_rel, Path *new_path)
425 bool accept_new = true; /* unless we find a superior old path */
426 ListCell *insert_after = NULL; /* where to insert new item */
427 List *new_path_pathkeys;
433 * This is a convenient place to check for query cancel --- no part of the
434 * planner goes very long without calling add_path().
436 CHECK_FOR_INTERRUPTS();
438 /* Pretend parameterized paths have no pathkeys, per comment above */
439 new_path_pathkeys = new_path->param_info ? NIL : new_path->pathkeys;
442 * Loop to check proposed new path against old paths. Note it is possible
443 * for more than one old path to be tossed out because new_path dominates
446 * We can't use foreach here because the loop body may delete the current
450 for (p1 = list_head(parent_rel->pathlist); p1 != NULL; p1 = p1_next)
452 Path *old_path = (Path *) lfirst(p1);
453 bool remove_old = false; /* unless new proves superior */
454 PathCostComparison costcmp;
455 PathKeysComparison keyscmp;
456 BMS_Comparison outercmp;
461 * Do a fuzzy cost comparison with standard fuzziness limit.
463 costcmp = compare_path_costs_fuzzily(new_path, old_path,
467 * If the two paths compare differently for startup and total cost,
468 * then we want to keep both, and we can skip comparing pathkeys and
469 * required_outer rels. If they compare the same, proceed with the
470 * other comparisons. Row count is checked last. (We make the tests
471 * in this order because the cost comparison is most likely to turn
472 * out "different", and the pathkeys comparison next most likely. As
473 * explained above, row count very seldom makes a difference, so even
474 * though it's cheap to compare there's not much point in checking it
477 if (costcmp != COSTS_DIFFERENT)
479 /* Similarly check to see if either dominates on pathkeys */
480 List *old_path_pathkeys;
482 old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
483 keyscmp = compare_pathkeys(new_path_pathkeys,
485 if (keyscmp != PATHKEYS_DIFFERENT)
490 outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
491 PATH_REQ_OUTER(old_path));
492 if (keyscmp == PATHKEYS_BETTER1)
494 if ((outercmp == BMS_EQUAL ||
495 outercmp == BMS_SUBSET1) &&
496 new_path->rows <= old_path->rows &&
497 new_path->parallel_safe >= old_path->parallel_safe)
498 remove_old = true; /* new dominates old */
500 else if (keyscmp == PATHKEYS_BETTER2)
502 if ((outercmp == BMS_EQUAL ||
503 outercmp == BMS_SUBSET2) &&
504 new_path->rows >= old_path->rows &&
505 new_path->parallel_safe <= old_path->parallel_safe)
506 accept_new = false; /* old dominates new */
508 else /* keyscmp == PATHKEYS_EQUAL */
510 if (outercmp == BMS_EQUAL)
513 * Same pathkeys and outer rels, and fuzzily
514 * the same cost, so keep just one; to decide
515 * which, first check parallel-safety, then
516 * rows, then do a fuzzy cost comparison with
517 * very small fuzz limit. (We used to do an
518 * exact cost comparison, but that results in
519 * annoying platform-specific plan variations
520 * due to roundoff in the cost estimates.) If
521 * things are still tied, arbitrarily keep
522 * only the old path. Notice that we will
523 * keep only the old path even if the
524 * less-fuzzy comparison decides the startup
525 * and total costs compare differently.
527 if (new_path->parallel_safe >
528 old_path->parallel_safe)
529 remove_old = true; /* new dominates old */
530 else if (new_path->parallel_safe <
531 old_path->parallel_safe)
532 accept_new = false; /* old dominates new */
533 else if (new_path->rows < old_path->rows)
534 remove_old = true; /* new dominates old */
535 else if (new_path->rows > old_path->rows)
536 accept_new = false; /* old dominates new */
537 else if (compare_path_costs_fuzzily(new_path,
539 1.0000000001) == COSTS_BETTER1)
540 remove_old = true; /* new dominates old */
542 accept_new = false; /* old equals or
545 else if (outercmp == BMS_SUBSET1 &&
546 new_path->rows <= old_path->rows &&
547 new_path->parallel_safe >= old_path->parallel_safe)
548 remove_old = true; /* new dominates old */
549 else if (outercmp == BMS_SUBSET2 &&
550 new_path->rows >= old_path->rows &&
551 new_path->parallel_safe <= old_path->parallel_safe)
552 accept_new = false; /* old dominates new */
553 /* else different parameterizations, keep both */
557 if (keyscmp != PATHKEYS_BETTER2)
559 outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
560 PATH_REQ_OUTER(old_path));
561 if ((outercmp == BMS_EQUAL ||
562 outercmp == BMS_SUBSET1) &&
563 new_path->rows <= old_path->rows &&
564 new_path->parallel_safe >= old_path->parallel_safe)
565 remove_old = true; /* new dominates old */
569 if (keyscmp != PATHKEYS_BETTER1)
571 outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
572 PATH_REQ_OUTER(old_path));
573 if ((outercmp == BMS_EQUAL ||
574 outercmp == BMS_SUBSET2) &&
575 new_path->rows >= old_path->rows &&
576 new_path->parallel_safe <= old_path->parallel_safe)
577 accept_new = false; /* old dominates new */
580 case COSTS_DIFFERENT:
583 * can't get here, but keep this case to keep compiler
592 * Remove current element from pathlist if dominated by new.
596 parent_rel->pathlist = list_delete_cell(parent_rel->pathlist,
600 * Delete the data pointed-to by the deleted cell, if possible
602 if (!IsA(old_path, IndexPath))
604 /* p1_prev does not advance */
608 /* new belongs after this old path if it has cost >= old's */
609 if (new_path->total_cost >= old_path->total_cost)
611 /* p1_prev advances */
616 * If we found an old path that dominates new_path, we can quit
617 * scanning the pathlist; we will not add new_path, and we assume
618 * new_path cannot dominate any other elements of the pathlist.
626 /* Accept the new path: insert it at proper place in pathlist */
628 lappend_cell(parent_rel->pathlist, insert_after, new_path);
630 parent_rel->pathlist = lcons(new_path, parent_rel->pathlist);
634 /* Reject and recycle the new path */
635 if (!IsA(new_path, IndexPath))
642 * Check whether a proposed new path could possibly get accepted.
643 * We assume we know the path's pathkeys and parameterization accurately,
644 * and have lower bounds for its costs.
646 * Note that we do not know the path's rowcount, since getting an estimate for
647 * that is too expensive to do before prechecking. We assume here that paths
648 * of a superset parameterization will generate fewer rows; if that holds,
649 * then paths with different parameterizations cannot dominate each other
650 * and so we can simply ignore existing paths of another parameterization.
651 * (In the infrequent cases where that rule of thumb fails, add_path will
652 * get rid of the inferior path.)
654 * At the time this is called, we haven't actually built a Path structure,
655 * so the required information has to be passed piecemeal.
658 add_path_precheck(RelOptInfo *parent_rel,
659 Cost startup_cost, Cost total_cost,
660 List *pathkeys, Relids required_outer)
662 List *new_path_pathkeys;
663 bool consider_startup;
666 /* Pretend parameterized paths have no pathkeys, per add_path policy */
667 new_path_pathkeys = required_outer ? NIL : pathkeys;
669 /* Decide whether new path's startup cost is interesting */
670 consider_startup = required_outer ? parent_rel->consider_param_startup : parent_rel->consider_startup;
672 foreach(p1, parent_rel->pathlist)
674 Path *old_path = (Path *) lfirst(p1);
675 PathKeysComparison keyscmp;
678 * We are looking for an old_path with the same parameterization (and
679 * by assumption the same rowcount) that dominates the new path on
680 * pathkeys as well as both cost metrics. If we find one, we can
681 * reject the new path.
683 * Cost comparisons here should match compare_path_costs_fuzzily.
685 if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
687 /* new path can win on startup cost only if consider_startup */
688 if (startup_cost > old_path->startup_cost * STD_FUZZ_FACTOR ||
691 /* new path loses on cost, so check pathkeys... */
692 List *old_path_pathkeys;
694 old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
695 keyscmp = compare_pathkeys(new_path_pathkeys,
697 if (keyscmp == PATHKEYS_EQUAL ||
698 keyscmp == PATHKEYS_BETTER2)
700 /* new path does not win on pathkeys... */
701 if (bms_equal(required_outer, PATH_REQ_OUTER(old_path)))
703 /* Found an old path that dominates the new one */
712 * Since the pathlist is sorted by total_cost, we can stop looking
713 * once we reach a path with a total_cost larger than the new
725 * Like add_path, our goal here is to consider whether a path is worthy
726 * of being kept around, but the considerations here are a bit different.
727 * A partial path is one which can be executed in any number of workers in
728 * parallel such that each worker will generate a subset of the path's
731 * As in add_path, the partial_pathlist is kept sorted with the cheapest
732 * total path in front. This is depended on by multiple places, which
733 * just take the front entry as the cheapest path without searching.
735 * We don't generate parameterized partial paths for several reasons. Most
736 * importantly, they're not safe to execute, because there's nothing to
737 * make sure that a parallel scan within the parameterized portion of the
738 * plan is running with the same value in every worker at the same time.
739 * Fortunately, it seems unlikely to be worthwhile anyway, because having
740 * each worker scan the entire outer relation and a subset of the inner
741 * relation will generally be a terrible plan. The inner (parameterized)
742 * side of the plan will be small anyway. There could be rare cases where
743 * this wins big - e.g. if join order constraints put a 1-row relation on
744 * the outer side of the topmost join with a parameterized plan on the inner
745 * side - but we'll have to be content not to handle such cases until
746 * somebody builds an executor infrastructure that can cope with them.
748 * Because we don't consider parameterized paths here, we also don't
749 * need to consider the row counts as a measure of quality: every path will
750 * produce the same number of rows. Neither do we need to consider startup
751 * costs: parallelism is only used for plans that will be run to completion.
752 * Therefore, this routine is much simpler than add_path: it needs to
753 * consider only pathkeys and total cost.
755 * As with add_path, we pfree paths that are found to be dominated by
756 * another partial path; this requires that there be no other references to
757 * such paths yet. Hence, GatherPaths must not be created for a rel until
758 * we're done creating all partial paths for it. Unlike add_path, we don't
759 * take an exception for IndexPaths as partial index paths won't be
760 * referenced by partial BitmapHeapPaths.
763 add_partial_path(RelOptInfo *parent_rel, Path *new_path)
765 bool accept_new = true; /* unless we find a superior old path */
766 ListCell *insert_after = NULL; /* where to insert new item */
771 /* Check for query cancel. */
772 CHECK_FOR_INTERRUPTS();
774 /* Path to be added must be parallel safe. */
775 Assert(new_path->parallel_safe);
777 /* Relation should be OK for parallelism, too. */
778 Assert(parent_rel->consider_parallel);
781 * As in add_path, throw out any paths which are dominated by the new
782 * path, but throw out the new path if some existing path dominates it.
785 for (p1 = list_head(parent_rel->partial_pathlist); p1 != NULL;
788 Path *old_path = (Path *) lfirst(p1);
789 bool remove_old = false; /* unless new proves superior */
790 PathKeysComparison keyscmp;
794 /* Compare pathkeys. */
795 keyscmp = compare_pathkeys(new_path->pathkeys, old_path->pathkeys);
797 /* Unless pathkeys are incompable, keep just one of the two paths. */
798 if (keyscmp != PATHKEYS_DIFFERENT)
800 if (new_path->total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
802 /* New path costs more; keep it only if pathkeys are better. */
803 if (keyscmp != PATHKEYS_BETTER1)
806 else if (old_path->total_cost > new_path->total_cost
809 /* Old path costs more; keep it only if pathkeys are better. */
810 if (keyscmp != PATHKEYS_BETTER2)
813 else if (keyscmp == PATHKEYS_BETTER1)
815 /* Costs are about the same, new path has better pathkeys. */
818 else if (keyscmp == PATHKEYS_BETTER2)
820 /* Costs are about the same, old path has better pathkeys. */
823 else if (old_path->total_cost > new_path->total_cost * 1.0000000001)
825 /* Pathkeys are the same, and the old path costs more. */
831 * Pathkeys are the same, and new path isn't materially
839 * Remove current element from partial_pathlist if dominated by new.
843 parent_rel->partial_pathlist =
844 list_delete_cell(parent_rel->partial_pathlist, p1, p1_prev);
846 /* p1_prev does not advance */
850 /* new belongs after this old path if it has cost >= old's */
851 if (new_path->total_cost >= old_path->total_cost)
853 /* p1_prev advances */
858 * If we found an old path that dominates new_path, we can quit
859 * scanning the partial_pathlist; we will not add new_path, and we
860 * assume new_path cannot dominate any later path.
868 /* Accept the new path: insert it at proper place */
870 lappend_cell(parent_rel->partial_pathlist, insert_after, new_path);
872 parent_rel->partial_pathlist =
873 lcons(new_path, parent_rel->partial_pathlist);
877 /* Reject and recycle the new path */
883 * add_partial_path_precheck
884 * Check whether a proposed new partial path could possibly get accepted.
886 * Unlike add_path_precheck, we can ignore startup cost and parameterization,
887 * since they don't matter for partial paths (see add_partial_path). But
888 * we do want to make sure we don't add a partial path if there's already
889 * a complete path that dominates it, since in that case the proposed path
893 add_partial_path_precheck(RelOptInfo *parent_rel, Cost total_cost,
899 * Our goal here is twofold. First, we want to find out whether this path
900 * is clearly inferior to some existing partial path. If so, we want to
901 * reject it immediately. Second, we want to find out whether this path
902 * is clearly superior to some existing partial path -- at least, modulo
903 * final cost computations. If so, we definitely want to consider it.
905 * Unlike add_path(), we always compare pathkeys here. This is because we
906 * expect partial_pathlist to be very short, and getting a definitive
907 * answer at this stage avoids the need to call add_path_precheck.
909 foreach(p1, parent_rel->partial_pathlist)
911 Path *old_path = (Path *) lfirst(p1);
912 PathKeysComparison keyscmp;
914 keyscmp = compare_pathkeys(pathkeys, old_path->pathkeys);
915 if (keyscmp != PATHKEYS_DIFFERENT)
917 if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR &&
918 keyscmp != PATHKEYS_BETTER1)
920 if (old_path->total_cost > total_cost * STD_FUZZ_FACTOR &&
921 keyscmp != PATHKEYS_BETTER2)
927 * This path is neither clearly inferior to an existing partial path nor
928 * clearly good enough that it might replace one. Compare it to
929 * non-parallel plans. If it loses even before accounting for the cost of
930 * the Gather node, we should definitely reject it.
932 * Note that we pass the total_cost to add_path_precheck twice. This is
933 * because it's never advantageous to consider the startup cost of a
934 * partial path; the resulting plans, if run in parallel, will be run to
937 if (!add_path_precheck(parent_rel, total_cost, total_cost, pathkeys,
945 /*****************************************************************************
946 * PATH NODE CREATION ROUTINES
947 *****************************************************************************/
950 * create_seqscan_path
951 * Creates a path corresponding to a sequential scan, returning the
955 create_seqscan_path(PlannerInfo *root, RelOptInfo *rel,
956 Relids required_outer, int parallel_workers)
958 Path *pathnode = makeNode(Path);
960 pathnode->pathtype = T_SeqScan;
961 pathnode->parent = rel;
962 pathnode->pathtarget = rel->reltarget;
963 pathnode->param_info = get_baserel_parampathinfo(root, rel,
965 pathnode->parallel_aware = parallel_workers > 0 ? true : false;
966 pathnode->parallel_safe = rel->consider_parallel;
967 pathnode->parallel_workers = parallel_workers;
968 pathnode->pathkeys = NIL; /* seqscan has unordered result */
970 cost_seqscan(pathnode, root, rel, pathnode->param_info);
976 * create_samplescan_path
977 * Creates a path node for a sampled table scan.
980 create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
982 Path *pathnode = makeNode(Path);
984 pathnode->pathtype = T_SampleScan;
985 pathnode->parent = rel;
986 pathnode->pathtarget = rel->reltarget;
987 pathnode->param_info = get_baserel_parampathinfo(root, rel,
989 pathnode->parallel_aware = false;
990 pathnode->parallel_safe = rel->consider_parallel;
991 pathnode->parallel_workers = 0;
992 pathnode->pathkeys = NIL; /* samplescan has unordered result */
994 cost_samplescan(pathnode, root, rel, pathnode->param_info);
1001 * Creates a path node for an index scan.
1003 * 'index' is a usable index.
1004 * 'indexclauses' is a list of RestrictInfo nodes representing clauses
1005 * to be used as index qual conditions in the scan.
1006 * 'indexclausecols' is an integer list of index column numbers (zero based)
1007 * the indexclauses can be used with.
1008 * 'indexorderbys' is a list of bare expressions (no RestrictInfos)
1009 * to be used as index ordering operators in the scan.
1010 * 'indexorderbycols' is an integer list of index column numbers (zero based)
1011 * the ordering operators can be used with.
1012 * 'pathkeys' describes the ordering of the path.
1013 * 'indexscandir' is ForwardScanDirection or BackwardScanDirection
1014 * for an ordered index, or NoMovementScanDirection for
1015 * an unordered index.
1016 * 'indexonly' is true if an index-only scan is wanted.
1017 * 'required_outer' is the set of outer relids for a parameterized path.
1018 * 'loop_count' is the number of repetitions of the indexscan to factor into
1019 * estimates of caching behavior.
1020 * 'partial_path' is true if constructing a parallel index scan path.
1022 * Returns the new path node.
1025 create_index_path(PlannerInfo *root,
1026 IndexOptInfo *index,
1028 List *indexclausecols,
1029 List *indexorderbys,
1030 List *indexorderbycols,
1032 ScanDirection indexscandir,
1034 Relids required_outer,
1038 IndexPath *pathnode = makeNode(IndexPath);
1039 RelOptInfo *rel = index->rel;
1043 pathnode->path.pathtype = indexonly ? T_IndexOnlyScan : T_IndexScan;
1044 pathnode->path.parent = rel;
1045 pathnode->path.pathtarget = rel->reltarget;
1046 pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1048 pathnode->path.parallel_aware = false;
1049 pathnode->path.parallel_safe = rel->consider_parallel;
1050 pathnode->path.parallel_workers = 0;
1051 pathnode->path.pathkeys = pathkeys;
1053 /* Convert clauses to indexquals the executor can handle */
1054 expand_indexqual_conditions(index, indexclauses, indexclausecols,
1055 &indexquals, &indexqualcols);
1057 /* Fill in the pathnode */
1058 pathnode->indexinfo = index;
1059 pathnode->indexclauses = indexclauses;
1060 pathnode->indexquals = indexquals;
1061 pathnode->indexqualcols = indexqualcols;
1062 pathnode->indexorderbys = indexorderbys;
1063 pathnode->indexorderbycols = indexorderbycols;
1064 pathnode->indexscandir = indexscandir;
1066 cost_index(pathnode, root, loop_count, partial_path);
1072 * create_bitmap_heap_path
1073 * Creates a path node for a bitmap scan.
1075 * 'bitmapqual' is a tree of IndexPath, BitmapAndPath, and BitmapOrPath nodes.
1076 * 'required_outer' is the set of outer relids for a parameterized path.
1077 * 'loop_count' is the number of repetitions of the indexscan to factor into
1078 * estimates of caching behavior.
1080 * loop_count should match the value used when creating the component
1084 create_bitmap_heap_path(PlannerInfo *root,
1087 Relids required_outer,
1089 int parallel_degree)
1091 BitmapHeapPath *pathnode = makeNode(BitmapHeapPath);
1093 pathnode->path.pathtype = T_BitmapHeapScan;
1094 pathnode->path.parent = rel;
1095 pathnode->path.pathtarget = rel->reltarget;
1096 pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1098 pathnode->path.parallel_aware = parallel_degree > 0 ? true : false;
1099 pathnode->path.parallel_safe = rel->consider_parallel;
1100 pathnode->path.parallel_workers = parallel_degree;
1101 pathnode->path.pathkeys = NIL; /* always unordered */
1103 pathnode->bitmapqual = bitmapqual;
1105 cost_bitmap_heap_scan(&pathnode->path, root, rel,
1106 pathnode->path.param_info,
1107 bitmapqual, loop_count);
1113 * create_bitmap_and_path
1114 * Creates a path node representing a BitmapAnd.
1117 create_bitmap_and_path(PlannerInfo *root,
1121 BitmapAndPath *pathnode = makeNode(BitmapAndPath);
1123 pathnode->path.pathtype = T_BitmapAnd;
1124 pathnode->path.parent = rel;
1125 pathnode->path.pathtarget = rel->reltarget;
1126 pathnode->path.param_info = NULL; /* not used in bitmap trees */
1129 * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1130 * parallel-safe if and only if rel->consider_parallel is set. So, we can
1131 * set the flag for this path based only on the relation-level flag,
1132 * without actually iterating over the list of children.
1134 pathnode->path.parallel_aware = false;
1135 pathnode->path.parallel_safe = rel->consider_parallel;
1136 pathnode->path.parallel_workers = 0;
1138 pathnode->path.pathkeys = NIL; /* always unordered */
1140 pathnode->bitmapquals = bitmapquals;
1142 /* this sets bitmapselectivity as well as the regular cost fields: */
1143 cost_bitmap_and_node(pathnode, root);
1149 * create_bitmap_or_path
1150 * Creates a path node representing a BitmapOr.
1153 create_bitmap_or_path(PlannerInfo *root,
1157 BitmapOrPath *pathnode = makeNode(BitmapOrPath);
1159 pathnode->path.pathtype = T_BitmapOr;
1160 pathnode->path.parent = rel;
1161 pathnode->path.pathtarget = rel->reltarget;
1162 pathnode->path.param_info = NULL; /* not used in bitmap trees */
1165 * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1166 * parallel-safe if and only if rel->consider_parallel is set. So, we can
1167 * set the flag for this path based only on the relation-level flag,
1168 * without actually iterating over the list of children.
1170 pathnode->path.parallel_aware = false;
1171 pathnode->path.parallel_safe = rel->consider_parallel;
1172 pathnode->path.parallel_workers = 0;
1174 pathnode->path.pathkeys = NIL; /* always unordered */
1176 pathnode->bitmapquals = bitmapquals;
1178 /* this sets bitmapselectivity as well as the regular cost fields: */
1179 cost_bitmap_or_node(pathnode, root);
1185 * create_tidscan_path
1186 * Creates a path corresponding to a scan by TID, returning the pathnode.
1189 create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals,
1190 Relids required_outer)
1192 TidPath *pathnode = makeNode(TidPath);
1194 pathnode->path.pathtype = T_TidScan;
1195 pathnode->path.parent = rel;
1196 pathnode->path.pathtarget = rel->reltarget;
1197 pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1199 pathnode->path.parallel_aware = false;
1200 pathnode->path.parallel_safe = rel->consider_parallel;
1201 pathnode->path.parallel_workers = 0;
1202 pathnode->path.pathkeys = NIL; /* always unordered */
1204 pathnode->tidquals = tidquals;
1206 cost_tidscan(&pathnode->path, root, rel, tidquals,
1207 pathnode->path.param_info);
1213 * create_append_path
1214 * Creates a path corresponding to an Append plan, returning the
1217 * Note that we must handle subpaths = NIL, representing a dummy access path.
1220 create_append_path(PlannerInfo *root,
1222 List *subpaths, List *partial_subpaths,
1223 Relids required_outer,
1224 int parallel_workers, bool parallel_aware,
1225 List *partitioned_rels, double rows)
1227 AppendPath *pathnode = makeNode(AppendPath);
1230 Assert(!parallel_aware || parallel_workers > 0);
1232 pathnode->path.pathtype = T_Append;
1233 pathnode->path.parent = rel;
1234 pathnode->path.pathtarget = rel->reltarget;
1237 * When generating an Append path for a partitioned table, there may be
1238 * parameters that are useful so we can eliminate certain partitions
1239 * during execution. Here we'll go all the way and fully populate the
1240 * parameter info data as we do for normal base relations. However, we
1241 * need only bother doing this for RELOPT_BASEREL rels, as
1242 * RELOPT_OTHER_MEMBER_REL's Append paths are merged into the base rel's
1243 * Append subpaths. It would do no harm to do this, we just avoid it to
1244 * save wasting effort.
1246 if (partitioned_rels != NIL && root && rel->reloptkind == RELOPT_BASEREL)
1247 pathnode->path.param_info = get_baserel_parampathinfo(root,
1251 pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1254 pathnode->path.parallel_aware = parallel_aware;
1255 pathnode->path.parallel_safe = rel->consider_parallel;
1256 pathnode->path.parallel_workers = parallel_workers;
1257 pathnode->path.pathkeys = NIL; /* result is always considered unsorted */
1258 pathnode->partitioned_rels = list_copy(partitioned_rels);
1261 * For parallel append, non-partial paths are sorted by descending total
1262 * costs. That way, the total time to finish all non-partial paths is
1263 * minimized. Also, the partial paths are sorted by descending startup
1264 * costs. There may be some paths that require to do startup work by a
1265 * single worker. In such case, it's better for workers to choose the
1266 * expensive ones first, whereas the leader should choose the cheapest
1269 if (pathnode->path.parallel_aware)
1271 subpaths = list_qsort(subpaths, append_total_cost_compare);
1272 partial_subpaths = list_qsort(partial_subpaths,
1273 append_startup_cost_compare);
1275 pathnode->first_partial_path = list_length(subpaths);
1276 pathnode->subpaths = list_concat(subpaths, partial_subpaths);
1278 foreach(l, pathnode->subpaths)
1280 Path *subpath = (Path *) lfirst(l);
1282 pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1283 subpath->parallel_safe;
1285 /* All child paths must have same parameterization */
1286 Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1289 Assert(!parallel_aware || pathnode->path.parallel_safe);
1291 cost_append(pathnode);
1293 /* If the caller provided a row estimate, override the computed value. */
1295 pathnode->path.rows = rows;
1301 * append_total_cost_compare
1302 * qsort comparator for sorting append child paths by total_cost descending
1304 * For equal total costs, we fall back to comparing startup costs; if those
1305 * are equal too, break ties using bms_compare on the paths' relids.
1306 * (This is to avoid getting unpredictable results from qsort.)
1309 append_total_cost_compare(const void *a, const void *b)
1311 Path *path1 = (Path *) lfirst(*(ListCell **) a);
1312 Path *path2 = (Path *) lfirst(*(ListCell **) b);
1315 cmp = compare_path_costs(path1, path2, TOTAL_COST);
1318 return bms_compare(path1->parent->relids, path2->parent->relids);
1322 * append_startup_cost_compare
1323 * qsort comparator for sorting append child paths by startup_cost descending
1325 * For equal startup costs, we fall back to comparing total costs; if those
1326 * are equal too, break ties using bms_compare on the paths' relids.
1327 * (This is to avoid getting unpredictable results from qsort.)
1330 append_startup_cost_compare(const void *a, const void *b)
1332 Path *path1 = (Path *) lfirst(*(ListCell **) a);
1333 Path *path2 = (Path *) lfirst(*(ListCell **) b);
1336 cmp = compare_path_costs(path1, path2, STARTUP_COST);
1339 return bms_compare(path1->parent->relids, path2->parent->relids);
1343 * create_merge_append_path
1344 * Creates a path corresponding to a MergeAppend plan, returning the
1348 create_merge_append_path(PlannerInfo *root,
1352 Relids required_outer,
1353 List *partitioned_rels)
1355 MergeAppendPath *pathnode = makeNode(MergeAppendPath);
1356 Cost input_startup_cost;
1357 Cost input_total_cost;
1360 pathnode->path.pathtype = T_MergeAppend;
1361 pathnode->path.parent = rel;
1362 pathnode->path.pathtarget = rel->reltarget;
1363 pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1365 pathnode->path.parallel_aware = false;
1366 pathnode->path.parallel_safe = rel->consider_parallel;
1367 pathnode->path.parallel_workers = 0;
1368 pathnode->path.pathkeys = pathkeys;
1369 pathnode->partitioned_rels = list_copy(partitioned_rels);
1370 pathnode->subpaths = subpaths;
1373 * Apply query-wide LIMIT if known and path is for sole base relation.
1374 * (Handling this at this low level is a bit klugy.)
1376 if (bms_equal(rel->relids, root->all_baserels))
1377 pathnode->limit_tuples = root->limit_tuples;
1379 pathnode->limit_tuples = -1.0;
1382 * Add up the sizes and costs of the input paths.
1384 pathnode->path.rows = 0;
1385 input_startup_cost = 0;
1386 input_total_cost = 0;
1387 foreach(l, subpaths)
1389 Path *subpath = (Path *) lfirst(l);
1391 pathnode->path.rows += subpath->rows;
1392 pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1393 subpath->parallel_safe;
1395 if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1397 /* Subpath is adequately ordered, we won't need to sort it */
1398 input_startup_cost += subpath->startup_cost;
1399 input_total_cost += subpath->total_cost;
1403 /* We'll need to insert a Sort node, so include cost for that */
1404 Path sort_path; /* dummy for result of cost_sort */
1406 cost_sort(&sort_path,
1409 subpath->total_cost,
1410 subpath->parent->tuples,
1411 subpath->pathtarget->width,
1414 pathnode->limit_tuples);
1415 input_startup_cost += sort_path.startup_cost;
1416 input_total_cost += sort_path.total_cost;
1419 /* All child paths must have same parameterization */
1420 Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1423 /* Now we can compute total costs of the MergeAppend */
1424 cost_merge_append(&pathnode->path, root,
1425 pathkeys, list_length(subpaths),
1426 input_startup_cost, input_total_cost,
1427 pathnode->path.rows);
1433 * create_group_result_path
1434 * Creates a path representing a Result-and-nothing-else plan.
1436 * This is only used for degenerate grouping cases, in which we know we
1437 * need to produce one result row, possibly filtered by a HAVING qual.
1440 create_group_result_path(PlannerInfo *root, RelOptInfo *rel,
1441 PathTarget *target, List *havingqual)
1443 GroupResultPath *pathnode = makeNode(GroupResultPath);
1445 pathnode->path.pathtype = T_Result;
1446 pathnode->path.parent = rel;
1447 pathnode->path.pathtarget = target;
1448 pathnode->path.param_info = NULL; /* there are no other rels... */
1449 pathnode->path.parallel_aware = false;
1450 pathnode->path.parallel_safe = rel->consider_parallel;
1451 pathnode->path.parallel_workers = 0;
1452 pathnode->path.pathkeys = NIL;
1453 pathnode->quals = havingqual;
1456 * We can't quite use cost_resultscan() because the quals we want to
1457 * account for are not baserestrict quals of the rel. Might as well just
1460 pathnode->path.rows = 1;
1461 pathnode->path.startup_cost = target->cost.startup;
1462 pathnode->path.total_cost = target->cost.startup +
1463 cpu_tuple_cost + target->cost.per_tuple;
1466 * Add cost of qual, if any --- but we ignore its selectivity, since our
1467 * rowcount estimate should be 1 no matter what the qual is.
1473 cost_qual_eval(&qual_cost, havingqual, root);
1474 /* havingqual is evaluated once at startup */
1475 pathnode->path.startup_cost += qual_cost.startup + qual_cost.per_tuple;
1476 pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
1483 * create_material_path
1484 * Creates a path corresponding to a Material plan, returning the
1488 create_material_path(RelOptInfo *rel, Path *subpath)
1490 MaterialPath *pathnode = makeNode(MaterialPath);
1492 Assert(subpath->parent == rel);
1494 pathnode->path.pathtype = T_Material;
1495 pathnode->path.parent = rel;
1496 pathnode->path.pathtarget = rel->reltarget;
1497 pathnode->path.param_info = subpath->param_info;
1498 pathnode->path.parallel_aware = false;
1499 pathnode->path.parallel_safe = rel->consider_parallel &&
1500 subpath->parallel_safe;
1501 pathnode->path.parallel_workers = subpath->parallel_workers;
1502 pathnode->path.pathkeys = subpath->pathkeys;
1504 pathnode->subpath = subpath;
1506 cost_material(&pathnode->path,
1507 subpath->startup_cost,
1508 subpath->total_cost,
1510 subpath->pathtarget->width);
1516 * create_unique_path
1517 * Creates a path representing elimination of distinct rows from the
1518 * input data. Distinct-ness is defined according to the needs of the
1519 * semijoin represented by sjinfo. If it is not possible to identify
1520 * how to make the data unique, NULL is returned.
1522 * If used at all, this is likely to be called repeatedly on the same rel;
1523 * and the input subpath should always be the same (the cheapest_total path
1524 * for the rel). So we cache the result.
1527 create_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1528 SpecialJoinInfo *sjinfo)
1530 UniquePath *pathnode;
1531 Path sort_path; /* dummy for result of cost_sort */
1532 Path agg_path; /* dummy for result of cost_agg */
1533 MemoryContext oldcontext;
1536 /* Caller made a mistake if subpath isn't cheapest_total ... */
1537 Assert(subpath == rel->cheapest_total_path);
1538 Assert(subpath->parent == rel);
1539 /* ... or if SpecialJoinInfo is the wrong one */
1540 Assert(sjinfo->jointype == JOIN_SEMI);
1541 Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
1543 /* If result already cached, return it */
1544 if (rel->cheapest_unique_path)
1545 return (UniquePath *) rel->cheapest_unique_path;
1547 /* If it's not possible to unique-ify, return NULL */
1548 if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
1552 * When called during GEQO join planning, we are in a short-lived memory
1553 * context. We must make sure that the path and any subsidiary data
1554 * structures created for a baserel survive the GEQO cycle, else the
1555 * baserel is trashed for future GEQO cycles. On the other hand, when we
1556 * are creating those for a joinrel during GEQO, we don't want them to
1557 * clutter the main planning context. Upshot is that the best solution is
1558 * to explicitly allocate memory in the same context the given RelOptInfo
1561 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
1563 pathnode = makeNode(UniquePath);
1565 pathnode->path.pathtype = T_Unique;
1566 pathnode->path.parent = rel;
1567 pathnode->path.pathtarget = rel->reltarget;
1568 pathnode->path.param_info = subpath->param_info;
1569 pathnode->path.parallel_aware = false;
1570 pathnode->path.parallel_safe = rel->consider_parallel &&
1571 subpath->parallel_safe;
1572 pathnode->path.parallel_workers = subpath->parallel_workers;
1575 * Assume the output is unsorted, since we don't necessarily have pathkeys
1576 * to represent it. (This might get overridden below.)
1578 pathnode->path.pathkeys = NIL;
1580 pathnode->subpath = subpath;
1581 pathnode->in_operators = sjinfo->semi_operators;
1582 pathnode->uniq_exprs = sjinfo->semi_rhs_exprs;
1585 * If the input is a relation and it has a unique index that proves the
1586 * semi_rhs_exprs are unique, then we don't need to do anything. Note
1587 * that relation_has_unique_index_for automatically considers restriction
1588 * clauses for the rel, as well.
1590 if (rel->rtekind == RTE_RELATION && sjinfo->semi_can_btree &&
1591 relation_has_unique_index_for(root, rel, NIL,
1592 sjinfo->semi_rhs_exprs,
1593 sjinfo->semi_operators))
1595 pathnode->umethod = UNIQUE_PATH_NOOP;
1596 pathnode->path.rows = rel->rows;
1597 pathnode->path.startup_cost = subpath->startup_cost;
1598 pathnode->path.total_cost = subpath->total_cost;
1599 pathnode->path.pathkeys = subpath->pathkeys;
1601 rel->cheapest_unique_path = (Path *) pathnode;
1603 MemoryContextSwitchTo(oldcontext);
1609 * If the input is a subquery whose output must be unique already, then we
1610 * don't need to do anything. The test for uniqueness has to consider
1611 * exactly which columns we are extracting; for example "SELECT DISTINCT
1612 * x,y" doesn't guarantee that x alone is distinct. So we cannot check for
1613 * this optimization unless semi_rhs_exprs consists only of simple Vars
1614 * referencing subquery outputs. (Possibly we could do something with
1615 * expressions in the subquery outputs, too, but for now keep it simple.)
1617 if (rel->rtekind == RTE_SUBQUERY)
1619 RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1621 if (query_supports_distinctness(rte->subquery))
1623 List *sub_tlist_colnos;
1625 sub_tlist_colnos = translate_sub_tlist(sjinfo->semi_rhs_exprs,
1628 if (sub_tlist_colnos &&
1629 query_is_distinct_for(rte->subquery,
1631 sjinfo->semi_operators))
1633 pathnode->umethod = UNIQUE_PATH_NOOP;
1634 pathnode->path.rows = rel->rows;
1635 pathnode->path.startup_cost = subpath->startup_cost;
1636 pathnode->path.total_cost = subpath->total_cost;
1637 pathnode->path.pathkeys = subpath->pathkeys;
1639 rel->cheapest_unique_path = (Path *) pathnode;
1641 MemoryContextSwitchTo(oldcontext);
1648 /* Estimate number of output rows */
1649 pathnode->path.rows = estimate_num_groups(root,
1650 sjinfo->semi_rhs_exprs,
1653 numCols = list_length(sjinfo->semi_rhs_exprs);
1655 if (sjinfo->semi_can_btree)
1658 * Estimate cost for sort+unique implementation
1660 cost_sort(&sort_path, root, NIL,
1661 subpath->total_cost,
1663 subpath->pathtarget->width,
1669 * Charge one cpu_operator_cost per comparison per input tuple. We
1670 * assume all columns get compared at most of the tuples. (XXX
1671 * probably this is an overestimate.) This should agree with
1672 * create_upper_unique_path.
1674 sort_path.total_cost += cpu_operator_cost * rel->rows * numCols;
1677 if (sjinfo->semi_can_hash)
1680 * Estimate the overhead per hashtable entry at 64 bytes (same as in
1683 int hashentrysize = subpath->pathtarget->width + 64;
1685 if (hashentrysize * pathnode->path.rows > work_mem * 1024L)
1688 * We should not try to hash. Hack the SpecialJoinInfo to
1689 * remember this, in case we come through here again.
1691 sjinfo->semi_can_hash = false;
1694 cost_agg(&agg_path, root,
1696 numCols, pathnode->path.rows,
1698 subpath->startup_cost,
1699 subpath->total_cost,
1703 if (sjinfo->semi_can_btree && sjinfo->semi_can_hash)
1705 if (agg_path.total_cost < sort_path.total_cost)
1706 pathnode->umethod = UNIQUE_PATH_HASH;
1708 pathnode->umethod = UNIQUE_PATH_SORT;
1710 else if (sjinfo->semi_can_btree)
1711 pathnode->umethod = UNIQUE_PATH_SORT;
1712 else if (sjinfo->semi_can_hash)
1713 pathnode->umethod = UNIQUE_PATH_HASH;
1716 /* we can get here only if we abandoned hashing above */
1717 MemoryContextSwitchTo(oldcontext);
1721 if (pathnode->umethod == UNIQUE_PATH_HASH)
1723 pathnode->path.startup_cost = agg_path.startup_cost;
1724 pathnode->path.total_cost = agg_path.total_cost;
1728 pathnode->path.startup_cost = sort_path.startup_cost;
1729 pathnode->path.total_cost = sort_path.total_cost;
1732 rel->cheapest_unique_path = (Path *) pathnode;
1734 MemoryContextSwitchTo(oldcontext);
1740 * create_gather_merge_path
1742 * Creates a path corresponding to a gather merge scan, returning
1746 create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1747 PathTarget *target, List *pathkeys,
1748 Relids required_outer, double *rows)
1750 GatherMergePath *pathnode = makeNode(GatherMergePath);
1751 Cost input_startup_cost = 0;
1752 Cost input_total_cost = 0;
1754 Assert(subpath->parallel_safe);
1757 pathnode->path.pathtype = T_GatherMerge;
1758 pathnode->path.parent = rel;
1759 pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1761 pathnode->path.parallel_aware = false;
1763 pathnode->subpath = subpath;
1764 pathnode->num_workers = subpath->parallel_workers;
1765 pathnode->path.pathkeys = pathkeys;
1766 pathnode->path.pathtarget = target ? target : rel->reltarget;
1767 pathnode->path.rows += subpath->rows;
1769 if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1771 /* Subpath is adequately ordered, we won't need to sort it */
1772 input_startup_cost += subpath->startup_cost;
1773 input_total_cost += subpath->total_cost;
1777 /* We'll need to insert a Sort node, so include cost for that */
1778 Path sort_path; /* dummy for result of cost_sort */
1780 cost_sort(&sort_path,
1783 subpath->total_cost,
1785 subpath->pathtarget->width,
1789 input_startup_cost += sort_path.startup_cost;
1790 input_total_cost += sort_path.total_cost;
1793 cost_gather_merge(pathnode, root, rel, pathnode->path.param_info,
1794 input_startup_cost, input_total_cost, rows);
1800 * translate_sub_tlist - get subquery column numbers represented by tlist
1802 * The given targetlist usually contains only Vars referencing the given relid.
1803 * Extract their varattnos (ie, the column numbers of the subquery) and return
1804 * as an integer List.
1806 * If any of the tlist items is not a simple Var, we cannot determine whether
1807 * the subquery's uniqueness condition (if any) matches ours, so punt and
1811 translate_sub_tlist(List *tlist, int relid)
1818 Var *var = (Var *) lfirst(l);
1820 if (!var || !IsA(var, Var) ||
1821 var->varno != relid)
1822 return NIL; /* punt */
1824 result = lappend_int(result, var->varattno);
1830 * create_gather_path
1831 * Creates a path corresponding to a gather scan, returning the
1834 * 'rows' may optionally be set to override row estimates from other sources.
1837 create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1838 PathTarget *target, Relids required_outer, double *rows)
1840 GatherPath *pathnode = makeNode(GatherPath);
1842 Assert(subpath->parallel_safe);
1844 pathnode->path.pathtype = T_Gather;
1845 pathnode->path.parent = rel;
1846 pathnode->path.pathtarget = target;
1847 pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1849 pathnode->path.parallel_aware = false;
1850 pathnode->path.parallel_safe = false;
1851 pathnode->path.parallel_workers = 0;
1852 pathnode->path.pathkeys = NIL; /* Gather has unordered result */
1854 pathnode->subpath = subpath;
1855 pathnode->num_workers = subpath->parallel_workers;
1856 pathnode->single_copy = false;
1858 if (pathnode->num_workers == 0)
1860 pathnode->path.pathkeys = subpath->pathkeys;
1861 pathnode->num_workers = 1;
1862 pathnode->single_copy = true;
1865 cost_gather(pathnode, root, rel, pathnode->path.param_info, rows);
1871 * create_subqueryscan_path
1872 * Creates a path corresponding to a scan of a subquery,
1873 * returning the pathnode.
1876 create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1877 List *pathkeys, Relids required_outer)
1879 SubqueryScanPath *pathnode = makeNode(SubqueryScanPath);
1881 pathnode->path.pathtype = T_SubqueryScan;
1882 pathnode->path.parent = rel;
1883 pathnode->path.pathtarget = rel->reltarget;
1884 pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1886 pathnode->path.parallel_aware = false;
1887 pathnode->path.parallel_safe = rel->consider_parallel &&
1888 subpath->parallel_safe;
1889 pathnode->path.parallel_workers = subpath->parallel_workers;
1890 pathnode->path.pathkeys = pathkeys;
1891 pathnode->subpath = subpath;
1893 cost_subqueryscan(pathnode, root, rel, pathnode->path.param_info);
1899 * create_functionscan_path
1900 * Creates a path corresponding to a sequential scan of a function,
1901 * returning the pathnode.
1904 create_functionscan_path(PlannerInfo *root, RelOptInfo *rel,
1905 List *pathkeys, Relids required_outer)
1907 Path *pathnode = makeNode(Path);
1909 pathnode->pathtype = T_FunctionScan;
1910 pathnode->parent = rel;
1911 pathnode->pathtarget = rel->reltarget;
1912 pathnode->param_info = get_baserel_parampathinfo(root, rel,
1914 pathnode->parallel_aware = false;
1915 pathnode->parallel_safe = rel->consider_parallel;
1916 pathnode->parallel_workers = 0;
1917 pathnode->pathkeys = pathkeys;
1919 cost_functionscan(pathnode, root, rel, pathnode->param_info);
1925 * create_tablefuncscan_path
1926 * Creates a path corresponding to a sequential scan of a table function,
1927 * returning the pathnode.
1930 create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel,
1931 Relids required_outer)
1933 Path *pathnode = makeNode(Path);
1935 pathnode->pathtype = T_TableFuncScan;
1936 pathnode->parent = rel;
1937 pathnode->pathtarget = rel->reltarget;
1938 pathnode->param_info = get_baserel_parampathinfo(root, rel,
1940 pathnode->parallel_aware = false;
1941 pathnode->parallel_safe = rel->consider_parallel;
1942 pathnode->parallel_workers = 0;
1943 pathnode->pathkeys = NIL; /* result is always unordered */
1945 cost_tablefuncscan(pathnode, root, rel, pathnode->param_info);
1951 * create_valuesscan_path
1952 * Creates a path corresponding to a scan of a VALUES list,
1953 * returning the pathnode.
1956 create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel,
1957 Relids required_outer)
1959 Path *pathnode = makeNode(Path);
1961 pathnode->pathtype = T_ValuesScan;
1962 pathnode->parent = rel;
1963 pathnode->pathtarget = rel->reltarget;
1964 pathnode->param_info = get_baserel_parampathinfo(root, rel,
1966 pathnode->parallel_aware = false;
1967 pathnode->parallel_safe = rel->consider_parallel;
1968 pathnode->parallel_workers = 0;
1969 pathnode->pathkeys = NIL; /* result is always unordered */
1971 cost_valuesscan(pathnode, root, rel, pathnode->param_info);
1977 * create_ctescan_path
1978 * Creates a path corresponding to a scan of a non-self-reference CTE,
1979 * returning the pathnode.
1982 create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
1984 Path *pathnode = makeNode(Path);
1986 pathnode->pathtype = T_CteScan;
1987 pathnode->parent = rel;
1988 pathnode->pathtarget = rel->reltarget;
1989 pathnode->param_info = get_baserel_parampathinfo(root, rel,
1991 pathnode->parallel_aware = false;
1992 pathnode->parallel_safe = rel->consider_parallel;
1993 pathnode->parallel_workers = 0;
1994 pathnode->pathkeys = NIL; /* XXX for now, result is always unordered */
1996 cost_ctescan(pathnode, root, rel, pathnode->param_info);
2002 * create_namedtuplestorescan_path
2003 * Creates a path corresponding to a scan of a named tuplestore, returning
2007 create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel,
2008 Relids required_outer)
2010 Path *pathnode = makeNode(Path);
2012 pathnode->pathtype = T_NamedTuplestoreScan;
2013 pathnode->parent = rel;
2014 pathnode->pathtarget = rel->reltarget;
2015 pathnode->param_info = get_baserel_parampathinfo(root, rel,
2017 pathnode->parallel_aware = false;
2018 pathnode->parallel_safe = rel->consider_parallel;
2019 pathnode->parallel_workers = 0;
2020 pathnode->pathkeys = NIL; /* result is always unordered */
2022 cost_namedtuplestorescan(pathnode, root, rel, pathnode->param_info);
2028 * create_resultscan_path
2029 * Creates a path corresponding to a scan of an RTE_RESULT relation,
2030 * returning the pathnode.
2033 create_resultscan_path(PlannerInfo *root, RelOptInfo *rel,
2034 Relids required_outer)
2036 Path *pathnode = makeNode(Path);
2038 pathnode->pathtype = T_Result;
2039 pathnode->parent = rel;
2040 pathnode->pathtarget = rel->reltarget;
2041 pathnode->param_info = get_baserel_parampathinfo(root, rel,
2043 pathnode->parallel_aware = false;
2044 pathnode->parallel_safe = rel->consider_parallel;
2045 pathnode->parallel_workers = 0;
2046 pathnode->pathkeys = NIL; /* result is always unordered */
2048 cost_resultscan(pathnode, root, rel, pathnode->param_info);
2054 * create_worktablescan_path
2055 * Creates a path corresponding to a scan of a self-reference CTE,
2056 * returning the pathnode.
2059 create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel,
2060 Relids required_outer)
2062 Path *pathnode = makeNode(Path);
2064 pathnode->pathtype = T_WorkTableScan;
2065 pathnode->parent = rel;
2066 pathnode->pathtarget = rel->reltarget;
2067 pathnode->param_info = get_baserel_parampathinfo(root, rel,
2069 pathnode->parallel_aware = false;
2070 pathnode->parallel_safe = rel->consider_parallel;
2071 pathnode->parallel_workers = 0;
2072 pathnode->pathkeys = NIL; /* result is always unordered */
2074 /* Cost is the same as for a regular CTE scan */
2075 cost_ctescan(pathnode, root, rel, pathnode->param_info);
2081 * create_foreignscan_path
2082 * Creates a path corresponding to a scan of a foreign table, foreign join,
2083 * or foreign upper-relation processing, returning the pathnode.
2085 * This function is never called from core Postgres; rather, it's expected
2086 * to be called by the GetForeignPaths, GetForeignJoinPaths, or
2087 * GetForeignUpperPaths function of a foreign data wrapper. We make the FDW
2088 * supply all fields of the path, since we do not have any way to calculate
2089 * them in core. However, there is a usually-sane default for the pathtarget
2090 * (rel->reltarget), so we let a NULL for "target" select that.
2093 create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel,
2095 double rows, Cost startup_cost, Cost total_cost,
2097 Relids required_outer,
2098 Path *fdw_outerpath,
2101 ForeignPath *pathnode = makeNode(ForeignPath);
2103 pathnode->path.pathtype = T_ForeignScan;
2104 pathnode->path.parent = rel;
2105 pathnode->path.pathtarget = target ? target : rel->reltarget;
2106 pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
2108 pathnode->path.parallel_aware = false;
2109 pathnode->path.parallel_safe = rel->consider_parallel;
2110 pathnode->path.parallel_workers = 0;
2111 pathnode->path.rows = rows;
2112 pathnode->path.startup_cost = startup_cost;
2113 pathnode->path.total_cost = total_cost;
2114 pathnode->path.pathkeys = pathkeys;
2116 pathnode->fdw_outerpath = fdw_outerpath;
2117 pathnode->fdw_private = fdw_private;
2123 * calc_nestloop_required_outer
2124 * Compute the required_outer set for a nestloop join path
2126 * Note: result must not share storage with either input
2129 calc_nestloop_required_outer(Relids outerrelids,
2130 Relids outer_paramrels,
2132 Relids inner_paramrels)
2134 Relids required_outer;
2136 /* inner_path can require rels from outer path, but not vice versa */
2137 Assert(!bms_overlap(outer_paramrels, innerrelids));
2138 /* easy case if inner path is not parameterized */
2139 if (!inner_paramrels)
2140 return bms_copy(outer_paramrels);
2141 /* else, form the union ... */
2142 required_outer = bms_union(outer_paramrels, inner_paramrels);
2143 /* ... and remove any mention of now-satisfied outer rels */
2144 required_outer = bms_del_members(required_outer,
2146 /* maintain invariant that required_outer is exactly NULL if empty */
2147 if (bms_is_empty(required_outer))
2149 bms_free(required_outer);
2150 required_outer = NULL;
2152 return required_outer;
2156 * calc_non_nestloop_required_outer
2157 * Compute the required_outer set for a merge or hash join path
2159 * Note: result must not share storage with either input
2162 calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
2164 Relids outer_paramrels = PATH_REQ_OUTER(outer_path);
2165 Relids inner_paramrels = PATH_REQ_OUTER(inner_path);
2166 Relids required_outer;
2168 /* neither path can require rels from the other */
2169 Assert(!bms_overlap(outer_paramrels, inner_path->parent->relids));
2170 Assert(!bms_overlap(inner_paramrels, outer_path->parent->relids));
2171 /* form the union ... */
2172 required_outer = bms_union(outer_paramrels, inner_paramrels);
2173 /* we do not need an explicit test for empty; bms_union gets it right */
2174 return required_outer;
2178 * create_nestloop_path
2179 * Creates a pathnode corresponding to a nestloop join between two
2182 * 'joinrel' is the join relation.
2183 * 'jointype' is the type of join required
2184 * 'workspace' is the result from initial_cost_nestloop
2185 * 'extra' contains various information about the join
2186 * 'outer_path' is the outer path
2187 * 'inner_path' is the inner path
2188 * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2189 * 'pathkeys' are the path keys of the new join path
2190 * 'required_outer' is the set of required outer rels
2192 * Returns the resulting path node.
2195 create_nestloop_path(PlannerInfo *root,
2196 RelOptInfo *joinrel,
2198 JoinCostWorkspace *workspace,
2199 JoinPathExtraData *extra,
2202 List *restrict_clauses,
2204 Relids required_outer)
2206 NestPath *pathnode = makeNode(NestPath);
2207 Relids inner_req_outer = PATH_REQ_OUTER(inner_path);
2210 * If the inner path is parameterized by the outer, we must drop any
2211 * restrict_clauses that are due to be moved into the inner path. We have
2212 * to do this now, rather than postpone the work till createplan time,
2213 * because the restrict_clauses list can affect the size and cost
2214 * estimates for this path.
2216 if (bms_overlap(inner_req_outer, outer_path->parent->relids))
2218 Relids inner_and_outer = bms_union(inner_path->parent->relids,
2220 List *jclauses = NIL;
2223 foreach(lc, restrict_clauses)
2225 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2227 if (!join_clause_is_movable_into(rinfo,
2228 inner_path->parent->relids,
2230 jclauses = lappend(jclauses, rinfo);
2232 restrict_clauses = jclauses;
2235 pathnode->path.pathtype = T_NestLoop;
2236 pathnode->path.parent = joinrel;
2237 pathnode->path.pathtarget = joinrel->reltarget;
2238 pathnode->path.param_info =
2239 get_joinrel_parampathinfo(root,
2246 pathnode->path.parallel_aware = false;
2247 pathnode->path.parallel_safe = joinrel->consider_parallel &&
2248 outer_path->parallel_safe && inner_path->parallel_safe;
2249 /* This is a foolish way to estimate parallel_workers, but for now... */
2250 pathnode->path.parallel_workers = outer_path->parallel_workers;
2251 pathnode->path.pathkeys = pathkeys;
2252 pathnode->jointype = jointype;
2253 pathnode->inner_unique = extra->inner_unique;
2254 pathnode->outerjoinpath = outer_path;
2255 pathnode->innerjoinpath = inner_path;
2256 pathnode->joinrestrictinfo = restrict_clauses;
2258 final_cost_nestloop(root, pathnode, workspace, extra);
2264 * create_mergejoin_path
2265 * Creates a pathnode corresponding to a mergejoin join between
2268 * 'joinrel' is the join relation
2269 * 'jointype' is the type of join required
2270 * 'workspace' is the result from initial_cost_mergejoin
2271 * 'extra' contains various information about the join
2272 * 'outer_path' is the outer path
2273 * 'inner_path' is the inner path
2274 * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2275 * 'pathkeys' are the path keys of the new join path
2276 * 'required_outer' is the set of required outer rels
2277 * 'mergeclauses' are the RestrictInfo nodes to use as merge clauses
2278 * (this should be a subset of the restrict_clauses list)
2279 * 'outersortkeys' are the sort varkeys for the outer relation
2280 * 'innersortkeys' are the sort varkeys for the inner relation
2283 create_mergejoin_path(PlannerInfo *root,
2284 RelOptInfo *joinrel,
2286 JoinCostWorkspace *workspace,
2287 JoinPathExtraData *extra,
2290 List *restrict_clauses,
2292 Relids required_outer,
2294 List *outersortkeys,
2295 List *innersortkeys)
2297 MergePath *pathnode = makeNode(MergePath);
2299 pathnode->jpath.path.pathtype = T_MergeJoin;
2300 pathnode->jpath.path.parent = joinrel;
2301 pathnode->jpath.path.pathtarget = joinrel->reltarget;
2302 pathnode->jpath.path.param_info =
2303 get_joinrel_parampathinfo(root,
2310 pathnode->jpath.path.parallel_aware = false;
2311 pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2312 outer_path->parallel_safe && inner_path->parallel_safe;
2313 /* This is a foolish way to estimate parallel_workers, but for now... */
2314 pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2315 pathnode->jpath.path.pathkeys = pathkeys;
2316 pathnode->jpath.jointype = jointype;
2317 pathnode->jpath.inner_unique = extra->inner_unique;
2318 pathnode->jpath.outerjoinpath = outer_path;
2319 pathnode->jpath.innerjoinpath = inner_path;
2320 pathnode->jpath.joinrestrictinfo = restrict_clauses;
2321 pathnode->path_mergeclauses = mergeclauses;
2322 pathnode->outersortkeys = outersortkeys;
2323 pathnode->innersortkeys = innersortkeys;
2324 /* pathnode->skip_mark_restore will be set by final_cost_mergejoin */
2325 /* pathnode->materialize_inner will be set by final_cost_mergejoin */
2327 final_cost_mergejoin(root, pathnode, workspace, extra);
2333 * create_hashjoin_path
2334 * Creates a pathnode corresponding to a hash join between two relations.
2336 * 'joinrel' is the join relation
2337 * 'jointype' is the type of join required
2338 * 'workspace' is the result from initial_cost_hashjoin
2339 * 'extra' contains various information about the join
2340 * 'outer_path' is the cheapest outer path
2341 * 'inner_path' is the cheapest inner path
2342 * 'parallel_hash' to select Parallel Hash of inner path (shared hash table)
2343 * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2344 * 'required_outer' is the set of required outer rels
2345 * 'hashclauses' are the RestrictInfo nodes to use as hash clauses
2346 * (this should be a subset of the restrict_clauses list)
2349 create_hashjoin_path(PlannerInfo *root,
2350 RelOptInfo *joinrel,
2352 JoinCostWorkspace *workspace,
2353 JoinPathExtraData *extra,
2357 List *restrict_clauses,
2358 Relids required_outer,
2361 HashPath *pathnode = makeNode(HashPath);
2363 pathnode->jpath.path.pathtype = T_HashJoin;
2364 pathnode->jpath.path.parent = joinrel;
2365 pathnode->jpath.path.pathtarget = joinrel->reltarget;
2366 pathnode->jpath.path.param_info =
2367 get_joinrel_parampathinfo(root,
2374 pathnode->jpath.path.parallel_aware =
2375 joinrel->consider_parallel && parallel_hash;
2376 pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2377 outer_path->parallel_safe && inner_path->parallel_safe;
2378 /* This is a foolish way to estimate parallel_workers, but for now... */
2379 pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2382 * A hashjoin never has pathkeys, since its output ordering is
2383 * unpredictable due to possible batching. XXX If the inner relation is
2384 * small enough, we could instruct the executor that it must not batch,
2385 * and then we could assume that the output inherits the outer relation's
2386 * ordering, which might save a sort step. However there is considerable
2387 * downside if our estimate of the inner relation size is badly off. For
2388 * the moment we don't risk it. (Note also that if we wanted to take this
2389 * seriously, joinpath.c would have to consider many more paths for the
2390 * outer rel than it does now.)
2392 pathnode->jpath.path.pathkeys = NIL;
2393 pathnode->jpath.jointype = jointype;
2394 pathnode->jpath.inner_unique = extra->inner_unique;
2395 pathnode->jpath.outerjoinpath = outer_path;
2396 pathnode->jpath.innerjoinpath = inner_path;
2397 pathnode->jpath.joinrestrictinfo = restrict_clauses;
2398 pathnode->path_hashclauses = hashclauses;
2399 /* final_cost_hashjoin will fill in pathnode->num_batches */
2401 final_cost_hashjoin(root, pathnode, workspace, extra);
2407 * create_projection_path
2408 * Creates a pathnode that represents performing a projection.
2410 * 'rel' is the parent relation associated with the result
2411 * 'subpath' is the path representing the source of data
2412 * 'target' is the PathTarget to be computed
2415 create_projection_path(PlannerInfo *root,
2420 ProjectionPath *pathnode = makeNode(ProjectionPath);
2421 PathTarget *oldtarget = subpath->pathtarget;
2423 pathnode->path.pathtype = T_Result;
2424 pathnode->path.parent = rel;
2425 pathnode->path.pathtarget = target;
2426 /* For now, assume we are above any joins, so no parameterization */
2427 pathnode->path.param_info = NULL;
2428 pathnode->path.parallel_aware = false;
2429 pathnode->path.parallel_safe = rel->consider_parallel &&
2430 subpath->parallel_safe &&
2431 is_parallel_safe(root, (Node *) target->exprs);
2432 pathnode->path.parallel_workers = subpath->parallel_workers;
2433 /* Projection does not change the sort order */
2434 pathnode->path.pathkeys = subpath->pathkeys;
2436 pathnode->subpath = subpath;
2439 * We might not need a separate Result node. If the input plan node type
2440 * can project, we can just tell it to project something else. Or, if it
2441 * can't project but the desired target has the same expression list as
2442 * what the input will produce anyway, we can still give it the desired
2443 * tlist (possibly changing its ressortgroupref labels, but nothing else).
2444 * Note: in the latter case, create_projection_plan has to recheck our
2445 * conclusion; see comments therein.
2447 if (is_projection_capable_path(subpath) ||
2448 equal(oldtarget->exprs, target->exprs))
2450 /* No separate Result node needed */
2451 pathnode->dummypp = true;
2454 * Set cost of plan as subpath's cost, adjusted for tlist replacement.
2456 pathnode->path.rows = subpath->rows;
2457 pathnode->path.startup_cost = subpath->startup_cost +
2458 (target->cost.startup - oldtarget->cost.startup);
2459 pathnode->path.total_cost = subpath->total_cost +
2460 (target->cost.startup - oldtarget->cost.startup) +
2461 (target->cost.per_tuple - oldtarget->cost.per_tuple) * subpath->rows;
2465 /* We really do need the Result node */
2466 pathnode->dummypp = false;
2469 * The Result node's cost is cpu_tuple_cost per row, plus the cost of
2470 * evaluating the tlist. There is no qual to worry about.
2472 pathnode->path.rows = subpath->rows;
2473 pathnode->path.startup_cost = subpath->startup_cost +
2474 target->cost.startup;
2475 pathnode->path.total_cost = subpath->total_cost +
2476 target->cost.startup +
2477 (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows;
2484 * apply_projection_to_path
2485 * Add a projection step, or just apply the target directly to given path.
2487 * This has the same net effect as create_projection_path(), except that if
2488 * a separate Result plan node isn't needed, we just replace the given path's
2489 * pathtarget with the desired one. This must be used only when the caller
2490 * knows that the given path isn't referenced elsewhere and so can be modified
2493 * If the input path is a GatherPath or GatherMergePath, we try to push the
2494 * new target down to its input as well; this is a yet more invasive
2495 * modification of the input path, which create_projection_path() can't do.
2497 * Note that we mustn't change the source path's parent link; so when it is
2498 * add_path'd to "rel" things will be a bit inconsistent. So far that has
2499 * not caused any trouble.
2501 * 'rel' is the parent relation associated with the result
2502 * 'path' is the path representing the source of data
2503 * 'target' is the PathTarget to be computed
2506 apply_projection_to_path(PlannerInfo *root,
2514 * If given path can't project, we might need a Result node, so make a
2515 * separate ProjectionPath.
2517 if (!is_projection_capable_path(path))
2518 return (Path *) create_projection_path(root, rel, path, target);
2521 * We can just jam the desired tlist into the existing path, being sure to
2522 * update its cost estimates appropriately.
2524 oldcost = path->pathtarget->cost;
2525 path->pathtarget = target;
2527 path->startup_cost += target->cost.startup - oldcost.startup;
2528 path->total_cost += target->cost.startup - oldcost.startup +
2529 (target->cost.per_tuple - oldcost.per_tuple) * path->rows;
2532 * If the path happens to be a Gather or GatherMerge path, we'd like to
2533 * arrange for the subpath to return the required target list so that
2534 * workers can help project. But if there is something that is not
2535 * parallel-safe in the target expressions, then we can't.
2537 if ((IsA(path, GatherPath) ||IsA(path, GatherMergePath)) &&
2538 is_parallel_safe(root, (Node *) target->exprs))
2541 * We always use create_projection_path here, even if the subpath is
2542 * projection-capable, so as to avoid modifying the subpath in place.
2543 * It seems unlikely at present that there could be any other
2544 * references to the subpath, but better safe than sorry.
2546 * Note that we don't change the parallel path's cost estimates; it
2547 * might be appropriate to do so, to reflect the fact that the bulk of
2548 * the target evaluation will happen in workers.
2550 if (IsA(path, GatherPath))
2552 GatherPath *gpath = (GatherPath *) path;
2554 gpath->subpath = (Path *)
2555 create_projection_path(root,
2556 gpath->subpath->parent,
2562 GatherMergePath *gmpath = (GatherMergePath *) path;
2564 gmpath->subpath = (Path *)
2565 create_projection_path(root,
2566 gmpath->subpath->parent,
2571 else if (path->parallel_safe &&
2572 !is_parallel_safe(root, (Node *) target->exprs))
2575 * We're inserting a parallel-restricted target list into a path
2576 * currently marked parallel-safe, so we have to mark it as no longer
2579 path->parallel_safe = false;
2586 * create_set_projection_path
2587 * Creates a pathnode that represents performing a projection that
2588 * includes set-returning functions.
2590 * 'rel' is the parent relation associated with the result
2591 * 'subpath' is the path representing the source of data
2592 * 'target' is the PathTarget to be computed
2595 create_set_projection_path(PlannerInfo *root,
2600 ProjectSetPath *pathnode = makeNode(ProjectSetPath);
2604 pathnode->path.pathtype = T_ProjectSet;
2605 pathnode->path.parent = rel;
2606 pathnode->path.pathtarget = target;
2607 /* For now, assume we are above any joins, so no parameterization */
2608 pathnode->path.param_info = NULL;
2609 pathnode->path.parallel_aware = false;
2610 pathnode->path.parallel_safe = rel->consider_parallel &&
2611 subpath->parallel_safe &&
2612 is_parallel_safe(root, (Node *) target->exprs);
2613 pathnode->path.parallel_workers = subpath->parallel_workers;
2614 /* Projection does not change the sort order XXX? */
2615 pathnode->path.pathkeys = subpath->pathkeys;
2617 pathnode->subpath = subpath;
2620 * Estimate number of rows produced by SRFs for each row of input; if
2621 * there's more than one in this node, use the maximum.
2624 foreach(lc, target->exprs)
2626 Node *node = (Node *) lfirst(lc);
2629 itemrows = expression_returns_set_rows(node);
2630 if (tlist_rows < itemrows)
2631 tlist_rows = itemrows;
2635 * In addition to the cost of evaluating the tlist, charge cpu_tuple_cost
2636 * per input row, and half of cpu_tuple_cost for each added output row.
2637 * This is slightly bizarre maybe, but it's what 9.6 did; we may revisit
2638 * this estimate later.
2640 pathnode->path.rows = subpath->rows * tlist_rows;
2641 pathnode->path.startup_cost = subpath->startup_cost +
2642 target->cost.startup;
2643 pathnode->path.total_cost = subpath->total_cost +
2644 target->cost.startup +
2645 (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows +
2646 (pathnode->path.rows - subpath->rows) * cpu_tuple_cost / 2;
2653 * Creates a pathnode that represents performing an explicit sort.
2655 * 'rel' is the parent relation associated with the result
2656 * 'subpath' is the path representing the source of data
2657 * 'pathkeys' represents the desired sort order
2658 * 'limit_tuples' is the estimated bound on the number of output tuples,
2659 * or -1 if no LIMIT or couldn't estimate
2662 create_sort_path(PlannerInfo *root,
2666 double limit_tuples)
2668 SortPath *pathnode = makeNode(SortPath);
2670 pathnode->path.pathtype = T_Sort;
2671 pathnode->path.parent = rel;
2672 /* Sort doesn't project, so use source path's pathtarget */
2673 pathnode->path.pathtarget = subpath->pathtarget;
2674 /* For now, assume we are above any joins, so no parameterization */
2675 pathnode->path.param_info = NULL;
2676 pathnode->path.parallel_aware = false;
2677 pathnode->path.parallel_safe = rel->consider_parallel &&
2678 subpath->parallel_safe;
2679 pathnode->path.parallel_workers = subpath->parallel_workers;
2680 pathnode->path.pathkeys = pathkeys;
2682 pathnode->subpath = subpath;
2684 cost_sort(&pathnode->path, root, pathkeys,
2685 subpath->total_cost,
2687 subpath->pathtarget->width,
2688 0.0, /* XXX comparison_cost shouldn't be 0? */
2689 work_mem, limit_tuples);
2696 * Creates a pathnode that represents performing grouping of presorted input
2698 * 'rel' is the parent relation associated with the result
2699 * 'subpath' is the path representing the source of data
2700 * 'target' is the PathTarget to be computed
2701 * 'groupClause' is a list of SortGroupClause's representing the grouping
2702 * 'qual' is the HAVING quals if any
2703 * 'numGroups' is the estimated number of groups
2706 create_group_path(PlannerInfo *root,
2713 GroupPath *pathnode = makeNode(GroupPath);
2714 PathTarget *target = rel->reltarget;
2716 pathnode->path.pathtype = T_Group;
2717 pathnode->path.parent = rel;
2718 pathnode->path.pathtarget = target;
2719 /* For now, assume we are above any joins, so no parameterization */
2720 pathnode->path.param_info = NULL;
2721 pathnode->path.parallel_aware = false;
2722 pathnode->path.parallel_safe = rel->consider_parallel &&
2723 subpath->parallel_safe;
2724 pathnode->path.parallel_workers = subpath->parallel_workers;
2725 /* Group doesn't change sort ordering */
2726 pathnode->path.pathkeys = subpath->pathkeys;
2728 pathnode->subpath = subpath;
2730 pathnode->groupClause = groupClause;
2731 pathnode->qual = qual;
2733 cost_group(&pathnode->path, root,
2734 list_length(groupClause),
2737 subpath->startup_cost, subpath->total_cost,
2740 /* add tlist eval cost for each output row */
2741 pathnode->path.startup_cost += target->cost.startup;
2742 pathnode->path.total_cost += target->cost.startup +
2743 target->cost.per_tuple * pathnode->path.rows;
2749 * create_upper_unique_path
2750 * Creates a pathnode that represents performing an explicit Unique step
2751 * on presorted input.
2753 * This produces a Unique plan node, but the use-case is so different from
2754 * create_unique_path that it doesn't seem worth trying to merge the two.
2756 * 'rel' is the parent relation associated with the result
2757 * 'subpath' is the path representing the source of data
2758 * 'numCols' is the number of grouping columns
2759 * 'numGroups' is the estimated number of groups
2761 * The input path must be sorted on the grouping columns, plus possibly
2762 * additional columns; so the first numCols pathkeys are the grouping columns
2765 create_upper_unique_path(PlannerInfo *root,
2771 UpperUniquePath *pathnode = makeNode(UpperUniquePath);
2773 pathnode->path.pathtype = T_Unique;
2774 pathnode->path.parent = rel;
2775 /* Unique doesn't project, so use source path's pathtarget */
2776 pathnode->path.pathtarget = subpath->pathtarget;
2777 /* For now, assume we are above any joins, so no parameterization */
2778 pathnode->path.param_info = NULL;
2779 pathnode->path.parallel_aware = false;
2780 pathnode->path.parallel_safe = rel->consider_parallel &&
2781 subpath->parallel_safe;
2782 pathnode->path.parallel_workers = subpath->parallel_workers;
2783 /* Unique doesn't change the input ordering */
2784 pathnode->path.pathkeys = subpath->pathkeys;
2786 pathnode->subpath = subpath;
2787 pathnode->numkeys = numCols;
2790 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2791 * all columns get compared at most of the tuples. (XXX probably this is
2794 pathnode->path.startup_cost = subpath->startup_cost;
2795 pathnode->path.total_cost = subpath->total_cost +
2796 cpu_operator_cost * subpath->rows * numCols;
2797 pathnode->path.rows = numGroups;
2804 * Creates a pathnode that represents performing aggregation/grouping
2806 * 'rel' is the parent relation associated with the result
2807 * 'subpath' is the path representing the source of data
2808 * 'target' is the PathTarget to be computed
2809 * 'aggstrategy' is the Agg node's basic implementation strategy
2810 * 'aggsplit' is the Agg node's aggregate-splitting mode
2811 * 'groupClause' is a list of SortGroupClause's representing the grouping
2812 * 'qual' is the HAVING quals if any
2813 * 'aggcosts' contains cost info about the aggregate functions to be computed
2814 * 'numGroups' is the estimated number of groups (1 if not grouping)
2817 create_agg_path(PlannerInfo *root,
2821 AggStrategy aggstrategy,
2825 const AggClauseCosts *aggcosts,
2828 AggPath *pathnode = makeNode(AggPath);
2830 pathnode->path.pathtype = T_Agg;
2831 pathnode->path.parent = rel;
2832 pathnode->path.pathtarget = target;
2833 /* For now, assume we are above any joins, so no parameterization */
2834 pathnode->path.param_info = NULL;
2835 pathnode->path.parallel_aware = false;
2836 pathnode->path.parallel_safe = rel->consider_parallel &&
2837 subpath->parallel_safe;
2838 pathnode->path.parallel_workers = subpath->parallel_workers;
2839 if (aggstrategy == AGG_SORTED)
2840 pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */
2842 pathnode->path.pathkeys = NIL; /* output is unordered */
2843 pathnode->subpath = subpath;
2845 pathnode->aggstrategy = aggstrategy;
2846 pathnode->aggsplit = aggsplit;
2847 pathnode->numGroups = numGroups;
2848 pathnode->groupClause = groupClause;
2849 pathnode->qual = qual;
2851 cost_agg(&pathnode->path, root,
2852 aggstrategy, aggcosts,
2853 list_length(groupClause), numGroups,
2855 subpath->startup_cost, subpath->total_cost,
2858 /* add tlist eval cost for each output row */
2859 pathnode->path.startup_cost += target->cost.startup;
2860 pathnode->path.total_cost += target->cost.startup +
2861 target->cost.per_tuple * pathnode->path.rows;
2867 * create_groupingsets_path
2868 * Creates a pathnode that represents performing GROUPING SETS aggregation
2870 * GroupingSetsPath represents sorted grouping with one or more grouping sets.
2871 * The input path's result must be sorted to match the last entry in
2872 * rollup_groupclauses.
2874 * 'rel' is the parent relation associated with the result
2875 * 'subpath' is the path representing the source of data
2876 * 'target' is the PathTarget to be computed
2877 * 'having_qual' is the HAVING quals if any
2878 * 'rollups' is a list of RollupData nodes
2879 * 'agg_costs' contains cost info about the aggregate functions to be computed
2880 * 'numGroups' is the estimated total number of groups
2883 create_groupingsets_path(PlannerInfo *root,
2887 AggStrategy aggstrategy,
2889 const AggClauseCosts *agg_costs,
2892 GroupingSetsPath *pathnode = makeNode(GroupingSetsPath);
2893 PathTarget *target = rel->reltarget;
2895 bool is_first = true;
2896 bool is_first_sort = true;
2898 /* The topmost generated Plan node will be an Agg */
2899 pathnode->path.pathtype = T_Agg;
2900 pathnode->path.parent = rel;
2901 pathnode->path.pathtarget = target;
2902 pathnode->path.param_info = subpath->param_info;
2903 pathnode->path.parallel_aware = false;
2904 pathnode->path.parallel_safe = rel->consider_parallel &&
2905 subpath->parallel_safe;
2906 pathnode->path.parallel_workers = subpath->parallel_workers;
2907 pathnode->subpath = subpath;
2910 * Simplify callers by downgrading AGG_SORTED to AGG_PLAIN, and AGG_MIXED
2911 * to AGG_HASHED, here if possible.
2913 if (aggstrategy == AGG_SORTED &&
2914 list_length(rollups) == 1 &&
2915 ((RollupData *) linitial(rollups))->groupClause == NIL)
2916 aggstrategy = AGG_PLAIN;
2918 if (aggstrategy == AGG_MIXED &&
2919 list_length(rollups) == 1)
2920 aggstrategy = AGG_HASHED;
2923 * Output will be in sorted order by group_pathkeys if, and only if, there
2924 * is a single rollup operation on a non-empty list of grouping
2927 if (aggstrategy == AGG_SORTED && list_length(rollups) == 1)
2928 pathnode->path.pathkeys = root->group_pathkeys;
2930 pathnode->path.pathkeys = NIL;
2932 pathnode->aggstrategy = aggstrategy;
2933 pathnode->rollups = rollups;
2934 pathnode->qual = having_qual;
2936 Assert(rollups != NIL);
2937 Assert(aggstrategy != AGG_PLAIN || list_length(rollups) == 1);
2938 Assert(aggstrategy != AGG_MIXED || list_length(rollups) > 1);
2940 foreach(lc, rollups)
2942 RollupData *rollup = lfirst(lc);
2943 List *gsets = rollup->gsets;
2944 int numGroupCols = list_length(linitial(gsets));
2947 * In AGG_SORTED or AGG_PLAIN mode, the first rollup takes the
2948 * (already-sorted) input, and following ones do their own sort.
2950 * In AGG_HASHED mode, there is one rollup for each grouping set.
2952 * In AGG_MIXED mode, the first rollups are hashed, the first
2953 * non-hashed one takes the (already-sorted) input, and following ones
2954 * do their own sort.
2958 cost_agg(&pathnode->path, root,
2964 subpath->startup_cost,
2965 subpath->total_cost,
2968 if (!rollup->is_hashed)
2969 is_first_sort = false;
2973 Path sort_path; /* dummy for result of cost_sort */
2974 Path agg_path; /* dummy for result of cost_agg */
2976 if (rollup->is_hashed || is_first_sort)
2979 * Account for cost of aggregation, but don't charge input
2982 cost_agg(&agg_path, root,
2983 rollup->is_hashed ? AGG_HASHED : AGG_SORTED,
2990 if (!rollup->is_hashed)
2991 is_first_sort = false;
2995 /* Account for cost of sort, but don't charge input cost again */
2996 cost_sort(&sort_path, root, NIL,
2999 subpath->pathtarget->width,
3004 /* Account for cost of aggregation */
3006 cost_agg(&agg_path, root,
3012 sort_path.startup_cost,
3013 sort_path.total_cost,
3017 pathnode->path.total_cost += agg_path.total_cost;
3018 pathnode->path.rows += agg_path.rows;
3022 /* add tlist eval cost for each output row */
3023 pathnode->path.startup_cost += target->cost.startup;
3024 pathnode->path.total_cost += target->cost.startup +
3025 target->cost.per_tuple * pathnode->path.rows;
3031 * create_minmaxagg_path
3032 * Creates a pathnode that represents computation of MIN/MAX aggregates
3034 * 'rel' is the parent relation associated with the result
3035 * 'target' is the PathTarget to be computed
3036 * 'mmaggregates' is a list of MinMaxAggInfo structs
3037 * 'quals' is the HAVING quals if any
3040 create_minmaxagg_path(PlannerInfo *root,
3046 MinMaxAggPath *pathnode = makeNode(MinMaxAggPath);
3050 /* The topmost generated Plan node will be a Result */
3051 pathnode->path.pathtype = T_Result;
3052 pathnode->path.parent = rel;
3053 pathnode->path.pathtarget = target;
3054 /* For now, assume we are above any joins, so no parameterization */
3055 pathnode->path.param_info = NULL;
3056 pathnode->path.parallel_aware = false;
3057 /* A MinMaxAggPath implies use of subplans, so cannot be parallel-safe */
3058 pathnode->path.parallel_safe = false;
3059 pathnode->path.parallel_workers = 0;
3060 /* Result is one unordered row */
3061 pathnode->path.rows = 1;
3062 pathnode->path.pathkeys = NIL;
3064 pathnode->mmaggregates = mmaggregates;
3065 pathnode->quals = quals;
3067 /* Calculate cost of all the initplans ... */
3069 foreach(lc, mmaggregates)
3071 MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3073 initplan_cost += mminfo->pathcost;
3076 /* add tlist eval cost for each output row, plus cpu_tuple_cost */
3077 pathnode->path.startup_cost = initplan_cost + target->cost.startup;
3078 pathnode->path.total_cost = initplan_cost + target->cost.startup +
3079 target->cost.per_tuple + cpu_tuple_cost;
3082 * Add cost of qual, if any --- but we ignore its selectivity, since our
3083 * rowcount estimate should be 1 no matter what the qual is.
3089 cost_qual_eval(&qual_cost, quals, root);
3090 pathnode->path.startup_cost += qual_cost.startup;
3091 pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
3098 * create_windowagg_path
3099 * Creates a pathnode that represents computation of window functions
3101 * 'rel' is the parent relation associated with the result
3102 * 'subpath' is the path representing the source of data
3103 * 'target' is the PathTarget to be computed
3104 * 'windowFuncs' is a list of WindowFunc structs
3105 * 'winclause' is a WindowClause that is common to all the WindowFuncs
3107 * The input must be sorted according to the WindowClause's PARTITION keys
3108 * plus ORDER BY keys.
3111 create_windowagg_path(PlannerInfo *root,
3116 WindowClause *winclause)
3118 WindowAggPath *pathnode = makeNode(WindowAggPath);
3120 pathnode->path.pathtype = T_WindowAgg;
3121 pathnode->path.parent = rel;
3122 pathnode->path.pathtarget = target;
3123 /* For now, assume we are above any joins, so no parameterization */
3124 pathnode->path.param_info = NULL;
3125 pathnode->path.parallel_aware = false;
3126 pathnode->path.parallel_safe = rel->consider_parallel &&
3127 subpath->parallel_safe;
3128 pathnode->path.parallel_workers = subpath->parallel_workers;
3129 /* WindowAgg preserves the input sort order */
3130 pathnode->path.pathkeys = subpath->pathkeys;
3132 pathnode->subpath = subpath;
3133 pathnode->winclause = winclause;
3136 * For costing purposes, assume that there are no redundant partitioning
3137 * or ordering columns; it's not worth the trouble to deal with that
3138 * corner case here. So we just pass the unmodified list lengths to
3141 cost_windowagg(&pathnode->path, root,
3143 list_length(winclause->partitionClause),
3144 list_length(winclause->orderClause),
3145 subpath->startup_cost,
3146 subpath->total_cost,
3149 /* add tlist eval cost for each output row */
3150 pathnode->path.startup_cost += target->cost.startup;
3151 pathnode->path.total_cost += target->cost.startup +
3152 target->cost.per_tuple * pathnode->path.rows;
3159 * Creates a pathnode that represents computation of INTERSECT or EXCEPT
3161 * 'rel' is the parent relation associated with the result
3162 * 'subpath' is the path representing the source of data
3163 * 'cmd' is the specific semantics (INTERSECT or EXCEPT, with/without ALL)
3164 * 'strategy' is the implementation strategy (sorted or hashed)
3165 * 'distinctList' is a list of SortGroupClause's representing the grouping
3166 * 'flagColIdx' is the column number where the flag column will be, if any
3167 * 'firstFlag' is the flag value for the first input relation when hashing;
3168 * or -1 when sorting
3169 * 'numGroups' is the estimated number of distinct groups
3170 * 'outputRows' is the estimated number of output rows
3173 create_setop_path(PlannerInfo *root,
3177 SetOpStrategy strategy,
3179 AttrNumber flagColIdx,
3184 SetOpPath *pathnode = makeNode(SetOpPath);
3186 pathnode->path.pathtype = T_SetOp;
3187 pathnode->path.parent = rel;
3188 /* SetOp doesn't project, so use source path's pathtarget */
3189 pathnode->path.pathtarget = subpath->pathtarget;
3190 /* For now, assume we are above any joins, so no parameterization */
3191 pathnode->path.param_info = NULL;
3192 pathnode->path.parallel_aware = false;
3193 pathnode->path.parallel_safe = rel->consider_parallel &&
3194 subpath->parallel_safe;
3195 pathnode->path.parallel_workers = subpath->parallel_workers;
3196 /* SetOp preserves the input sort order if in sort mode */
3197 pathnode->path.pathkeys =
3198 (strategy == SETOP_SORTED) ? subpath->pathkeys : NIL;
3200 pathnode->subpath = subpath;
3201 pathnode->cmd = cmd;
3202 pathnode->strategy = strategy;
3203 pathnode->distinctList = distinctList;
3204 pathnode->flagColIdx = flagColIdx;
3205 pathnode->firstFlag = firstFlag;
3206 pathnode->numGroups = numGroups;
3209 * Charge one cpu_operator_cost per comparison per input tuple. We assume
3210 * all columns get compared at most of the tuples.
3212 pathnode->path.startup_cost = subpath->startup_cost;
3213 pathnode->path.total_cost = subpath->total_cost +
3214 cpu_operator_cost * subpath->rows * list_length(distinctList);
3215 pathnode->path.rows = outputRows;
3221 * create_recursiveunion_path
3222 * Creates a pathnode that represents a recursive UNION node
3224 * 'rel' is the parent relation associated with the result
3225 * 'leftpath' is the source of data for the non-recursive term
3226 * 'rightpath' is the source of data for the recursive term
3227 * 'target' is the PathTarget to be computed
3228 * 'distinctList' is a list of SortGroupClause's representing the grouping
3229 * 'wtParam' is the ID of Param representing work table
3230 * 'numGroups' is the estimated number of groups
3232 * For recursive UNION ALL, distinctList is empty and numGroups is zero
3234 RecursiveUnionPath *
3235 create_recursiveunion_path(PlannerInfo *root,
3244 RecursiveUnionPath *pathnode = makeNode(RecursiveUnionPath);
3246 pathnode->path.pathtype = T_RecursiveUnion;
3247 pathnode->path.parent = rel;
3248 pathnode->path.pathtarget = target;
3249 /* For now, assume we are above any joins, so no parameterization */
3250 pathnode->path.param_info = NULL;
3251 pathnode->path.parallel_aware = false;
3252 pathnode->path.parallel_safe = rel->consider_parallel &&
3253 leftpath->parallel_safe && rightpath->parallel_safe;
3254 /* Foolish, but we'll do it like joins for now: */
3255 pathnode->path.parallel_workers = leftpath->parallel_workers;
3256 /* RecursiveUnion result is always unsorted */
3257 pathnode->path.pathkeys = NIL;
3259 pathnode->leftpath = leftpath;
3260 pathnode->rightpath = rightpath;
3261 pathnode->distinctList = distinctList;
3262 pathnode->wtParam = wtParam;
3263 pathnode->numGroups = numGroups;
3265 cost_recursive_union(&pathnode->path, leftpath, rightpath);
3271 * create_lockrows_path
3272 * Creates a pathnode that represents acquiring row locks
3274 * 'rel' is the parent relation associated with the result
3275 * 'subpath' is the path representing the source of data
3276 * 'rowMarks' is a list of PlanRowMark's
3277 * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3280 create_lockrows_path(PlannerInfo *root, RelOptInfo *rel,
3281 Path *subpath, List *rowMarks, int epqParam)
3283 LockRowsPath *pathnode = makeNode(LockRowsPath);
3285 pathnode->path.pathtype = T_LockRows;
3286 pathnode->path.parent = rel;
3287 /* LockRows doesn't project, so use source path's pathtarget */
3288 pathnode->path.pathtarget = subpath->pathtarget;
3289 /* For now, assume we are above any joins, so no parameterization */
3290 pathnode->path.param_info = NULL;
3291 pathnode->path.parallel_aware = false;
3292 pathnode->path.parallel_safe = false;
3293 pathnode->path.parallel_workers = 0;
3294 pathnode->path.rows = subpath->rows;
3297 * The result cannot be assumed sorted, since locking might cause the sort
3298 * key columns to be replaced with new values.
3300 pathnode->path.pathkeys = NIL;
3302 pathnode->subpath = subpath;
3303 pathnode->rowMarks = rowMarks;
3304 pathnode->epqParam = epqParam;
3307 * We should charge something extra for the costs of row locking and
3308 * possible refetches, but it's hard to say how much. For now, use
3309 * cpu_tuple_cost per row.
3311 pathnode->path.startup_cost = subpath->startup_cost;
3312 pathnode->path.total_cost = subpath->total_cost +
3313 cpu_tuple_cost * subpath->rows;
3319 * create_modifytable_path
3320 * Creates a pathnode that represents performing INSERT/UPDATE/DELETE mods
3322 * 'rel' is the parent relation associated with the result
3323 * 'operation' is the operation type
3324 * 'canSetTag' is true if we set the command tag/es_processed
3325 * 'nominalRelation' is the parent RT index for use of EXPLAIN
3326 * 'rootRelation' is the partitioned table root RT index, or 0 if none
3327 * 'partColsUpdated' is true if any partitioning columns are being updated,
3328 * either from the target relation or a descendent partitioned table.
3329 * 'resultRelations' is an integer list of actual RT indexes of target rel(s)
3330 * 'subpaths' is a list of Path(s) producing source data (one per rel)
3331 * 'subroots' is a list of PlannerInfo structs (one per rel)
3332 * 'withCheckOptionLists' is a list of WCO lists (one per rel)
3333 * 'returningLists' is a list of RETURNING tlists (one per rel)
3334 * 'rowMarks' is a list of PlanRowMarks (non-locking only)
3335 * 'onconflict' is the ON CONFLICT clause, or NULL
3336 * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3339 create_modifytable_path(PlannerInfo *root, RelOptInfo *rel,
3340 CmdType operation, bool canSetTag,
3341 Index nominalRelation, Index rootRelation,
3342 bool partColsUpdated,
3343 List *resultRelations, List *subpaths,
3345 List *withCheckOptionLists, List *returningLists,
3346 List *rowMarks, OnConflictExpr *onconflict,
3349 ModifyTablePath *pathnode = makeNode(ModifyTablePath);
3353 Assert(list_length(resultRelations) == list_length(subpaths));
3354 Assert(list_length(resultRelations) == list_length(subroots));
3355 Assert(withCheckOptionLists == NIL ||
3356 list_length(resultRelations) == list_length(withCheckOptionLists));
3357 Assert(returningLists == NIL ||
3358 list_length(resultRelations) == list_length(returningLists));
3360 pathnode->path.pathtype = T_ModifyTable;
3361 pathnode->path.parent = rel;
3362 /* pathtarget is not interesting, just make it minimally valid */
3363 pathnode->path.pathtarget = rel->reltarget;
3364 /* For now, assume we are above any joins, so no parameterization */
3365 pathnode->path.param_info = NULL;
3366 pathnode->path.parallel_aware = false;
3367 pathnode->path.parallel_safe = false;
3368 pathnode->path.parallel_workers = 0;
3369 pathnode->path.pathkeys = NIL;
3372 * Compute cost & rowcount as sum of subpath costs & rowcounts.
3374 * Currently, we don't charge anything extra for the actual table
3375 * modification work, nor for the WITH CHECK OPTIONS or RETURNING
3376 * expressions if any. It would only be window dressing, since
3377 * ModifyTable is always a top-level node and there is no way for the
3378 * costs to change any higher-level planning choices. But we might want
3379 * to make it look better sometime.
3381 pathnode->path.startup_cost = 0;
3382 pathnode->path.total_cost = 0;
3383 pathnode->path.rows = 0;
3385 foreach(lc, subpaths)
3387 Path *subpath = (Path *) lfirst(lc);
3389 if (lc == list_head(subpaths)) /* first node? */
3390 pathnode->path.startup_cost = subpath->startup_cost;
3391 pathnode->path.total_cost += subpath->total_cost;
3392 pathnode->path.rows += subpath->rows;
3393 total_size += subpath->pathtarget->width * subpath->rows;
3397 * Set width to the average width of the subpath outputs. XXX this is
3398 * totally wrong: we should report zero if no RETURNING, else an average
3399 * of the RETURNING tlist widths. But it's what happened historically,
3400 * and improving it is a task for another day.
3402 if (pathnode->path.rows > 0)
3403 total_size /= pathnode->path.rows;
3404 pathnode->path.pathtarget->width = rint(total_size);
3406 pathnode->operation = operation;
3407 pathnode->canSetTag = canSetTag;
3408 pathnode->nominalRelation = nominalRelation;
3409 pathnode->rootRelation = rootRelation;
3410 pathnode->partColsUpdated = partColsUpdated;
3411 pathnode->resultRelations = resultRelations;
3412 pathnode->subpaths = subpaths;
3413 pathnode->subroots = subroots;
3414 pathnode->withCheckOptionLists = withCheckOptionLists;
3415 pathnode->returningLists = returningLists;
3416 pathnode->rowMarks = rowMarks;
3417 pathnode->onconflict = onconflict;
3418 pathnode->epqParam = epqParam;
3425 * Creates a pathnode that represents performing LIMIT/OFFSET
3427 * In addition to providing the actual OFFSET and LIMIT expressions,
3428 * the caller must provide estimates of their values for costing purposes.
3429 * The estimates are as computed by preprocess_limit(), ie, 0 represents
3430 * the clause not being present, and -1 means it's present but we could
3431 * not estimate its value.
3433 * 'rel' is the parent relation associated with the result
3434 * 'subpath' is the path representing the source of data
3435 * 'limitOffset' is the actual OFFSET expression, or NULL
3436 * 'limitCount' is the actual LIMIT expression, or NULL
3437 * 'offset_est' is the estimated value of the OFFSET expression
3438 * 'count_est' is the estimated value of the LIMIT expression
3441 create_limit_path(PlannerInfo *root, RelOptInfo *rel,
3443 Node *limitOffset, Node *limitCount,
3444 int64 offset_est, int64 count_est)
3446 LimitPath *pathnode = makeNode(LimitPath);
3448 pathnode->path.pathtype = T_Limit;
3449 pathnode->path.parent = rel;
3450 /* Limit doesn't project, so use source path's pathtarget */
3451 pathnode->path.pathtarget = subpath->pathtarget;
3452 /* For now, assume we are above any joins, so no parameterization */
3453 pathnode->path.param_info = NULL;
3454 pathnode->path.parallel_aware = false;
3455 pathnode->path.parallel_safe = rel->consider_parallel &&
3456 subpath->parallel_safe;
3457 pathnode->path.parallel_workers = subpath->parallel_workers;
3458 pathnode->path.rows = subpath->rows;
3459 pathnode->path.startup_cost = subpath->startup_cost;
3460 pathnode->path.total_cost = subpath->total_cost;
3461 pathnode->path.pathkeys = subpath->pathkeys;
3462 pathnode->subpath = subpath;
3463 pathnode->limitOffset = limitOffset;
3464 pathnode->limitCount = limitCount;
3467 * Adjust the output rows count and costs according to the offset/limit.
3468 * This is only a cosmetic issue if we are at top level, but if we are
3469 * building a subquery then it's important to report correct info to the
3472 * When the offset or count couldn't be estimated, use 10% of the
3473 * estimated number of rows emitted from the subpath.
3475 * XXX we don't bother to add eval costs of the offset/limit expressions
3476 * themselves to the path costs. In theory we should, but in most cases
3477 * those expressions are trivial and it's just not worth the trouble.
3479 if (offset_est != 0)
3484 offset_rows = (double) offset_est;
3486 offset_rows = clamp_row_est(subpath->rows * 0.10);
3487 if (offset_rows > pathnode->path.rows)
3488 offset_rows = pathnode->path.rows;
3489 if (subpath->rows > 0)
3490 pathnode->path.startup_cost +=
3491 (subpath->total_cost - subpath->startup_cost)
3492 * offset_rows / subpath->rows;
3493 pathnode->path.rows -= offset_rows;
3494 if (pathnode->path.rows < 1)
3495 pathnode->path.rows = 1;
3503 count_rows = (double) count_est;
3505 count_rows = clamp_row_est(subpath->rows * 0.10);
3506 if (count_rows > pathnode->path.rows)
3507 count_rows = pathnode->path.rows;
3508 if (subpath->rows > 0)
3509 pathnode->path.total_cost = pathnode->path.startup_cost +
3510 (subpath->total_cost - subpath->startup_cost)
3511 * count_rows / subpath->rows;
3512 pathnode->path.rows = count_rows;
3513 if (pathnode->path.rows < 1)
3514 pathnode->path.rows = 1;
3522 * reparameterize_path
3523 * Attempt to modify a Path to have greater parameterization
3525 * We use this to attempt to bring all child paths of an appendrel to the
3526 * same parameterization level, ensuring that they all enforce the same set
3527 * of join quals (and thus that that parameterization can be attributed to
3528 * an append path built from such paths). Currently, only a few path types
3529 * are supported here, though more could be added at need. We return NULL
3530 * if we can't reparameterize the given path.
3532 * Note: we intentionally do not pass created paths to add_path(); it would
3533 * possibly try to delete them on the grounds of being cost-inferior to the
3534 * paths they were made from, and we don't want that. Paths made here are
3535 * not necessarily of general-purpose usefulness, but they can be useful
3536 * as members of an append path.
3539 reparameterize_path(PlannerInfo *root, Path *path,
3540 Relids required_outer,
3543 RelOptInfo *rel = path->parent;
3545 /* Can only increase, not decrease, path's parameterization */
3546 if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
3548 switch (path->pathtype)
3551 return create_seqscan_path(root, rel, required_outer, 0);
3553 return (Path *) create_samplescan_path(root, rel, required_outer);
3555 case T_IndexOnlyScan:
3557 IndexPath *ipath = (IndexPath *) path;
3558 IndexPath *newpath = makeNode(IndexPath);
3561 * We can't use create_index_path directly, and would not want
3562 * to because it would re-compute the indexqual conditions
3563 * which is wasted effort. Instead we hack things a bit:
3564 * flat-copy the path node, revise its param_info, and redo
3565 * the cost estimate.
3567 memcpy(newpath, ipath, sizeof(IndexPath));
3568 newpath->path.param_info =
3569 get_baserel_parampathinfo(root, rel, required_outer);
3570 cost_index(newpath, root, loop_count, false);
3571 return (Path *) newpath;
3573 case T_BitmapHeapScan:
3575 BitmapHeapPath *bpath = (BitmapHeapPath *) path;
3577 return (Path *) create_bitmap_heap_path(root,
3583 case T_SubqueryScan:
3585 SubqueryScanPath *spath = (SubqueryScanPath *) path;
3587 return (Path *) create_subqueryscan_path(root,
3590 spath->path.pathkeys,
3594 /* Supported only for RTE_RESULT scan paths */
3595 if (IsA(path, Path))
3596 return create_resultscan_path(root, rel, required_outer);
3600 AppendPath *apath = (AppendPath *) path;
3601 List *childpaths = NIL;
3602 List *partialpaths = NIL;
3606 /* Reparameterize the children */
3608 foreach(lc, apath->subpaths)
3610 Path *spath = (Path *) lfirst(lc);
3612 spath = reparameterize_path(root, spath,
3617 /* We have to re-split the regular and partial paths */
3618 if (i < apath->first_partial_path)
3619 childpaths = lappend(childpaths, spath);
3621 partialpaths = lappend(partialpaths, spath);
3625 create_append_path(root, rel, childpaths, partialpaths,
3627 apath->path.parallel_workers,
3628 apath->path.parallel_aware,
3629 apath->partitioned_rels,
3639 * reparameterize_path_by_child
3640 * Given a path parameterized by the parent of the given child relation,
3641 * translate the path to be parameterized by the given child relation.
3643 * The function creates a new path of the same type as the given path, but
3644 * parameterized by the given child relation. Most fields from the original
3645 * path can simply be flat-copied, but any expressions must be adjusted to
3646 * refer to the correct varnos, and any paths must be recursively
3647 * reparameterized. Other fields that refer to specific relids also need
3650 * The cost, number of rows, width and parallel path properties depend upon
3651 * path->parent, which does not change during the translation. Hence those
3652 * members are copied as they are.
3654 * If the given path can not be reparameterized, the function returns NULL.
3657 reparameterize_path_by_child(PlannerInfo *root, Path *path,
3658 RelOptInfo *child_rel)
3661 #define FLAT_COPY_PATH(newnode, node, nodetype) \
3662 ( (newnode) = makeNode(nodetype), \
3663 memcpy((newnode), (node), sizeof(nodetype)) )
3665 #define ADJUST_CHILD_ATTRS(node) \
3667 (List *) adjust_appendrel_attrs_multilevel(root, (Node *) (node), \
3668 child_rel->relids, \
3669 child_rel->top_parent_relids))
3671 #define REPARAMETERIZE_CHILD_PATH(path) \
3673 (path) = reparameterize_path_by_child(root, (path), child_rel); \
3674 if ((path) == NULL) \
3678 #define REPARAMETERIZE_CHILD_PATH_LIST(pathlist) \
3680 if ((pathlist) != NIL) \
3682 (pathlist) = reparameterize_pathlist_by_child(root, (pathlist), \
3684 if ((pathlist) == NIL) \
3690 ParamPathInfo *new_ppi;
3691 ParamPathInfo *old_ppi;
3692 Relids required_outer;
3695 * If the path is not parameterized by parent of the given relation, it
3696 * doesn't need reparameterization.
3698 if (!path->param_info ||
3699 !bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
3702 /* Reparameterize a copy of given path. */
3703 switch (nodeTag(path))
3706 FLAT_COPY_PATH(new_path, path, Path);
3713 FLAT_COPY_PATH(ipath, path, IndexPath);
3714 ADJUST_CHILD_ATTRS(ipath->indexclauses);
3715 ADJUST_CHILD_ATTRS(ipath->indexquals);
3716 new_path = (Path *) ipath;
3720 case T_BitmapHeapPath:
3722 BitmapHeapPath *bhpath;
3724 FLAT_COPY_PATH(bhpath, path, BitmapHeapPath);
3725 REPARAMETERIZE_CHILD_PATH(bhpath->bitmapqual);
3726 new_path = (Path *) bhpath;
3730 case T_BitmapAndPath:
3732 BitmapAndPath *bapath;
3734 FLAT_COPY_PATH(bapath, path, BitmapAndPath);
3735 REPARAMETERIZE_CHILD_PATH_LIST(bapath->bitmapquals);
3736 new_path = (Path *) bapath;
3740 case T_BitmapOrPath:
3742 BitmapOrPath *bopath;
3744 FLAT_COPY_PATH(bopath, path, BitmapOrPath);
3745 REPARAMETERIZE_CHILD_PATH_LIST(bopath->bitmapquals);
3746 new_path = (Path *) bopath;
3754 FLAT_COPY_PATH(tpath, path, TidPath);
3755 ADJUST_CHILD_ATTRS(tpath->tidquals);
3756 new_path = (Path *) tpath;
3763 ReparameterizeForeignPathByChild_function rfpc_func;
3765 FLAT_COPY_PATH(fpath, path, ForeignPath);
3766 if (fpath->fdw_outerpath)
3767 REPARAMETERIZE_CHILD_PATH(fpath->fdw_outerpath);
3769 /* Hand over to FDW if needed. */
3771 path->parent->fdwroutine->ReparameterizeForeignPathByChild;
3773 fpath->fdw_private = rfpc_func(root, fpath->fdw_private,
3775 new_path = (Path *) fpath;
3783 FLAT_COPY_PATH(cpath, path, CustomPath);
3784 REPARAMETERIZE_CHILD_PATH_LIST(cpath->custom_paths);
3785 if (cpath->methods &&
3786 cpath->methods->ReparameterizeCustomPathByChild)
3787 cpath->custom_private =
3788 cpath->methods->ReparameterizeCustomPathByChild(root,
3789 cpath->custom_private,
3791 new_path = (Path *) cpath;
3799 FLAT_COPY_PATH(jpath, path, NestPath);
3801 REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
3802 REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
3803 ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
3804 new_path = (Path *) jpath;
3813 FLAT_COPY_PATH(mpath, path, MergePath);
3815 jpath = (JoinPath *) mpath;
3816 REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
3817 REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
3818 ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
3819 ADJUST_CHILD_ATTRS(mpath->path_mergeclauses);
3820 new_path = (Path *) mpath;
3829 FLAT_COPY_PATH(hpath, path, HashPath);
3831 jpath = (JoinPath *) hpath;
3832 REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
3833 REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
3834 ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
3835 ADJUST_CHILD_ATTRS(hpath->path_hashclauses);
3836 new_path = (Path *) hpath;
3844 FLAT_COPY_PATH(apath, path, AppendPath);
3845 REPARAMETERIZE_CHILD_PATH_LIST(apath->subpaths);
3846 new_path = (Path *) apath;
3850 case T_MergeAppendPath:
3852 MergeAppendPath *mapath;
3854 FLAT_COPY_PATH(mapath, path, MergeAppendPath);
3855 REPARAMETERIZE_CHILD_PATH_LIST(mapath->subpaths);
3856 new_path = (Path *) mapath;
3860 case T_MaterialPath:
3862 MaterialPath *mpath;
3864 FLAT_COPY_PATH(mpath, path, MaterialPath);
3865 REPARAMETERIZE_CHILD_PATH(mpath->subpath);
3866 new_path = (Path *) mpath;
3874 FLAT_COPY_PATH(upath, path, UniquePath);
3875 REPARAMETERIZE_CHILD_PATH(upath->subpath);
3876 ADJUST_CHILD_ATTRS(upath->uniq_exprs);
3877 new_path = (Path *) upath;
3885 FLAT_COPY_PATH(gpath, path, GatherPath);
3886 REPARAMETERIZE_CHILD_PATH(gpath->subpath);
3887 new_path = (Path *) gpath;
3891 case T_GatherMergePath:
3893 GatherMergePath *gmpath;
3895 FLAT_COPY_PATH(gmpath, path, GatherMergePath);
3896 REPARAMETERIZE_CHILD_PATH(gmpath->subpath);
3897 new_path = (Path *) gmpath;
3903 /* We don't know how to reparameterize this path. */
3908 * Adjust the parameterization information, which refers to the topmost
3909 * parent. The topmost parent can be multiple levels away from the given
3910 * child, hence use multi-level expression adjustment routines.
3912 old_ppi = new_path->param_info;
3914 adjust_child_relids_multilevel(root, old_ppi->ppi_req_outer,
3916 child_rel->top_parent_relids);
3918 /* If we already have a PPI for this parameterization, just return it */
3919 new_ppi = find_param_path_info(new_path->parent, required_outer);
3922 * If not, build a new one and link it to the list of PPIs. For the same
3923 * reason as explained in mark_dummy_rel(), allocate new PPI in the same
3924 * context the given RelOptInfo is in.
3926 if (new_ppi == NULL)
3928 MemoryContext oldcontext;
3929 RelOptInfo *rel = path->parent;
3931 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
3933 new_ppi = makeNode(ParamPathInfo);
3934 new_ppi->ppi_req_outer = bms_copy(required_outer);
3935 new_ppi->ppi_rows = old_ppi->ppi_rows;
3936 new_ppi->ppi_clauses = old_ppi->ppi_clauses;
3937 ADJUST_CHILD_ATTRS(new_ppi->ppi_clauses);
3938 rel->ppilist = lappend(rel->ppilist, new_ppi);
3940 MemoryContextSwitchTo(oldcontext);
3942 bms_free(required_outer);
3944 new_path->param_info = new_ppi;
3947 * Adjust the path target if the parent of the outer relation is
3948 * referenced in the targetlist. This can happen when only the parent of
3949 * outer relation is laterally referenced in this relation.
3951 if (bms_overlap(path->parent->lateral_relids,
3952 child_rel->top_parent_relids))
3954 new_path->pathtarget = copy_pathtarget(new_path->pathtarget);
3955 ADJUST_CHILD_ATTRS(new_path->pathtarget->exprs);
3962 * reparameterize_pathlist_by_child
3963 * Helper function to reparameterize a list of paths by given child rel.
3966 reparameterize_pathlist_by_child(PlannerInfo *root,
3968 RelOptInfo *child_rel)
3973 foreach(lc, pathlist)
3975 Path *path = reparameterize_path_by_child(root, lfirst(lc),
3984 result = lappend(result, path);