Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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