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