Debian Codegraph @

src/backend/optimizer/util/pathnode.c

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