Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * pathnode.c
4 : * Routines to manipulate pathlists and create path nodes
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/optimizer/util/pathnode.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : #include "postgres.h"
16 :
17 : #include <math.h>
18 :
19 : #include "foreign/fdwapi.h"
20 : #include "miscadmin.h"
21 : #include "nodes/extensible.h"
22 : #include "optimizer/appendinfo.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 :
34 : typedef 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 */
40 : } PathCostComparison;
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 :
49 : static int append_total_cost_compare(const ListCell *a, const ListCell *b);
50 : static int append_startup_cost_compare(const ListCell *a, const ListCell *b);
51 : static List *reparameterize_pathlist_by_child(PlannerInfo *root,
52 : List *pathlist,
53 : RelOptInfo *child_rel);
54 : static bool pathlist_is_reparameterizable_by_child(List *pathlist,
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 : */
67 : int
68 1004116 : compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
69 : {
70 : /* Number of disabled nodes, if different, trumps all else. */
71 1004116 : if (unlikely(path1->disabled_nodes != path2->disabled_nodes))
72 : {
73 2712 : if (path1->disabled_nodes < path2->disabled_nodes)
74 2712 : return -1;
75 : else
76 0 : return +1;
77 : }
78 :
79 1001404 : if (criterion == STARTUP_COST)
80 : {
81 508274 : if (path1->startup_cost < path2->startup_cost)
82 302878 : return -1;
83 205396 : if (path1->startup_cost > path2->startup_cost)
84 101866 : return +1;
85 :
86 : /*
87 : * If paths have the same startup cost (not at all unlikely), order
88 : * them by total cost.
89 : */
90 103530 : if (path1->total_cost < path2->total_cost)
91 54768 : return -1;
92 48762 : if (path1->total_cost > path2->total_cost)
93 4526 : return +1;
94 : }
95 : else
96 : {
97 493130 : if (path1->total_cost < path2->total_cost)
98 465536 : return -1;
99 27594 : if (path1->total_cost > path2->total_cost)
100 3882 : return +1;
101 :
102 : /*
103 : * If paths have the same total cost, order them by startup cost.
104 : */
105 23712 : if (path1->startup_cost < path2->startup_cost)
106 2570 : return -1;
107 21142 : if (path1->startup_cost > path2->startup_cost)
108 8 : return +1;
109 : }
110 65370 : 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 : */
122 : int
123 6304 : compare_fractional_path_costs(Path *path1, Path *path2,
124 : double fraction)
125 : {
126 : Cost cost1,
127 : cost2;
128 :
129 : /* Number of disabled nodes, if different, trumps all else. */
130 6304 : if (unlikely(path1->disabled_nodes != path2->disabled_nodes))
131 : {
132 36 : if (path1->disabled_nodes < path2->disabled_nodes)
133 36 : return -1;
134 : else
135 0 : return +1;
136 : }
137 :
138 6268 : if (fraction <= 0.0 || fraction >= 1.0)
139 1942 : return compare_path_costs(path1, path2, TOTAL_COST);
140 4326 : cost1 = path1->startup_cost +
141 4326 : fraction * (path1->total_cost - path1->startup_cost);
142 4326 : cost2 = path2->startup_cost +
143 4326 : fraction * (path2->total_cost - path2->startup_cost);
144 4326 : if (cost1 < cost2)
145 3576 : return -1;
146 750 : if (cost1 > cost2)
147 750 : return +1;
148 0 : 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 : */
180 : static PathCostComparison
181 4157056 : compare_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 4157056 : if (unlikely(path1->disabled_nodes != path2->disabled_nodes))
188 : {
189 30794 : if (path1->disabled_nodes < path2->disabled_nodes)
190 16862 : return COSTS_BETTER1;
191 : else
192 13932 : 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 4126262 : if (path1->total_cost > path2->total_cost * fuzz_factor)
200 : {
201 : /* path1 fuzzily worse on total cost */
202 2163252 : if (CONSIDER_PATH_STARTUP_COST(path1) &&
203 137434 : path2->startup_cost > path1->startup_cost * fuzz_factor)
204 : {
205 : /* ... but path2 fuzzily worse on startup, so DIFFERENT */
206 92698 : return COSTS_DIFFERENT;
207 : }
208 : /* else path2 dominates */
209 2070554 : return COSTS_BETTER2;
210 : }
211 1963010 : if (path2->total_cost > path1->total_cost * fuzz_factor)
212 : {
213 : /* path2 fuzzily worse on total cost */
214 1017928 : if (CONSIDER_PATH_STARTUP_COST(path2) &&
215 61182 : path1->startup_cost > path2->startup_cost * fuzz_factor)
216 : {
217 : /* ... but path1 fuzzily worse on startup, so DIFFERENT */
218 40622 : return COSTS_DIFFERENT;
219 : }
220 : /* else path1 dominates */
221 977306 : return COSTS_BETTER1;
222 : }
223 : /* fuzzily the same on total cost ... */
224 945082 : if (path1->startup_cost > path2->startup_cost * fuzz_factor)
225 : {
226 : /* ... but path1 fuzzily worse on startup, so path2 wins */
227 369076 : return COSTS_BETTER2;
228 : }
229 576006 : if (path2->startup_cost > path1->startup_cost * fuzz_factor)
230 : {
231 : /* ... but path2 fuzzily worse on startup, so path1 wins */
232 62756 : return COSTS_BETTER1;
233 : }
234 : /* fuzzily the same on both costs */
235 513250 : 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 : */
267 : void
268 2016272 : set_cheapest(RelOptInfo *parent_rel)
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 2016272 : if (parent_rel->pathlist == NIL)
279 0 : elog(ERROR, "could not devise a query plan for the given query");
280 :
281 2016272 : cheapest_startup_path = cheapest_total_path = best_param_path = NULL;
282 2016272 : parameterized_paths = NIL;
283 :
284 4553558 : foreach(p, parent_rel->pathlist)
285 : {
286 2537286 : Path *path = (Path *) lfirst(p);
287 : int cmp;
288 :
289 2537286 : if (path->param_info)
290 : {
291 : /* Parameterized path, so add it to parameterized_paths */
292 131158 : 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 131158 : if (cheapest_total_path)
299 25686 : 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 105472 : if (best_param_path == NULL)
307 96780 : best_param_path = path;
308 : else
309 : {
310 8692 : switch (bms_subset_compare(PATH_REQ_OUTER(path),
311 8692 : PATH_REQ_OUTER(best_param_path)))
312 : {
313 60 : case BMS_EQUAL:
314 : /* keep the cheaper one */
315 60 : if (compare_path_costs(path, best_param_path,
316 : TOTAL_COST) < 0)
317 0 : best_param_path = path;
318 60 : break;
319 394 : case BMS_SUBSET1:
320 : /* new path is less-parameterized */
321 394 : best_param_path = path;
322 394 : break;
323 0 : case BMS_SUBSET2:
324 : /* old path is less-parameterized, keep it */
325 0 : break;
326 8238 : 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 8238 : break;
334 : }
335 : }
336 : }
337 : else
338 : {
339 : /* Unparameterized path, so consider it for cheapest slots */
340 2406128 : if (cheapest_total_path == NULL)
341 : {
342 2004646 : cheapest_startup_path = cheapest_total_path = path;
343 2004646 : 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 401482 : cmp = compare_path_costs(cheapest_startup_path, path, STARTUP_COST);
354 401482 : if (cmp > 0 ||
355 392 : (cmp == 0 &&
356 392 : compare_pathkeys(cheapest_startup_path->pathkeys,
357 : path->pathkeys) == PATHKEYS_BETTER2))
358 78554 : cheapest_startup_path = path;
359 :
360 401482 : cmp = compare_path_costs(cheapest_total_path, path, TOTAL_COST);
361 401482 : if (cmp > 0 ||
362 48 : (cmp == 0 &&
363 48 : compare_pathkeys(cheapest_total_path->pathkeys,
364 : path->pathkeys) == PATHKEYS_BETTER2))
365 0 : cheapest_total_path = path;
366 : }
367 : }
368 :
369 : /* Add cheapest unparameterized path, if any, to parameterized_paths */
370 2016272 : if (cheapest_total_path)
371 2004646 : 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 2016272 : if (cheapest_total_path == NULL)
378 11626 : cheapest_total_path = best_param_path;
379 : Assert(cheapest_total_path != NULL);
380 :
381 2016272 : parent_rel->cheapest_startup_path = cheapest_startup_path;
382 2016272 : parent_rel->cheapest_total_path = cheapest_total_path;
383 2016272 : parent_rel->cheapest_parameterized_paths = parameterized_paths;
384 2016272 : }
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 : */
458 : void
459 4208950 : add_path(RelOptInfo *parent_rel, Path *new_path)
460 : {
461 4208950 : bool accept_new = true; /* unless we find a superior old path */
462 4208950 : 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 : */
470 4208950 : CHECK_FOR_INTERRUPTS();
471 :
472 : /* Pretend parameterized paths have no pathkeys, per comment above */
473 4208950 : 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 6491670 : foreach(p1, parent_rel->pathlist)
481 : {
482 3828128 : Path *old_path = (Path *) lfirst(p1);
483 3828128 : 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 3828128 : costcmp = compare_path_costs_fuzzily(new_path, old_path,
492 : STD_FUZZ_FACTOR);
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 3828128 : if (costcmp != COSTS_DIFFERENT)
506 : {
507 : /* Similarly check to see if either dominates on pathkeys */
508 : List *old_path_pathkeys;
509 :
510 3694874 : old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
511 3694874 : keyscmp = compare_pathkeys(new_path_pathkeys,
512 : old_path_pathkeys);
513 3694874 : if (keyscmp != PATHKEYS_DIFFERENT)
514 : {
515 3516276 : switch (costcmp)
516 : {
517 360606 : case COSTS_EQUAL:
518 360606 : outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
519 360606 : PATH_REQ_OUTER(old_path));
520 360606 : if (keyscmp == PATHKEYS_BETTER1)
521 : {
522 7000 : if ((outercmp == BMS_EQUAL ||
523 7000 : outercmp == BMS_SUBSET1) &&
524 7000 : new_path->rows <= old_path->rows &&
525 6992 : new_path->parallel_safe >= old_path->parallel_safe)
526 6992 : remove_old = true; /* new dominates old */
527 : }
528 353606 : else if (keyscmp == PATHKEYS_BETTER2)
529 : {
530 18990 : if ((outercmp == BMS_EQUAL ||
531 18990 : outercmp == BMS_SUBSET2) &&
532 18990 : new_path->rows >= old_path->rows &&
533 18990 : new_path->parallel_safe <= old_path->parallel_safe)
534 18990 : accept_new = false; /* old dominates new */
535 : }
536 : else /* keyscmp == PATHKEYS_EQUAL */
537 : {
538 334616 : 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 329214 : if (new_path->parallel_safe >
556 329214 : old_path->parallel_safe)
557 42 : remove_old = true; /* new dominates old */
558 329172 : else if (new_path->parallel_safe <
559 329172 : old_path->parallel_safe)
560 54 : accept_new = false; /* old dominates new */
561 329118 : else if (new_path->rows < old_path->rows)
562 0 : remove_old = true; /* new dominates old */
563 329118 : else if (new_path->rows > old_path->rows)
564 190 : accept_new = false; /* old dominates new */
565 328928 : else if (compare_path_costs_fuzzily(new_path,
566 : old_path,
567 : 1.0000000001) == COSTS_BETTER1)
568 15876 : remove_old = true; /* new dominates old */
569 : else
570 313052 : accept_new = false; /* old equals or
571 : * dominates new */
572 : }
573 5402 : else if (outercmp == BMS_SUBSET1 &&
574 1224 : new_path->rows <= old_path->rows &&
575 1204 : new_path->parallel_safe >= old_path->parallel_safe)
576 1204 : remove_old = true; /* new dominates old */
577 4198 : else if (outercmp == BMS_SUBSET2 &&
578 3486 : new_path->rows >= old_path->rows &&
579 3452 : new_path->parallel_safe <= old_path->parallel_safe)
580 3452 : accept_new = false; /* old dominates new */
581 : /* else different parameterizations, keep both */
582 : }
583 360606 : break;
584 1015658 : case COSTS_BETTER1:
585 1015658 : if (keyscmp != PATHKEYS_BETTER2)
586 : {
587 706882 : outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
588 706882 : PATH_REQ_OUTER(old_path));
589 706882 : if ((outercmp == BMS_EQUAL ||
590 603778 : outercmp == BMS_SUBSET1) &&
591 603778 : new_path->rows <= old_path->rows &&
592 598892 : new_path->parallel_safe >= old_path->parallel_safe)
593 596354 : remove_old = true; /* new dominates old */
594 : }
595 1015658 : break;
596 2140012 : case COSTS_BETTER2:
597 2140012 : if (keyscmp != PATHKEYS_BETTER1)
598 : {
599 1361770 : outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
600 1361770 : PATH_REQ_OUTER(old_path));
601 1361770 : if ((outercmp == BMS_EQUAL ||
602 1278470 : outercmp == BMS_SUBSET2) &&
603 1278470 : new_path->rows >= old_path->rows &&
604 1211396 : new_path->parallel_safe <= old_path->parallel_safe)
605 1209670 : accept_new = false; /* old dominates new */
606 : }
607 2140012 : break;
608 0 : case COSTS_DIFFERENT:
609 :
610 : /*
611 : * can't get here, but keep this case to keep compiler
612 : * quiet
613 : */
614 0 : break;
615 : }
616 : }
617 : }
618 :
619 : /*
620 : * Remove current element from pathlist if dominated by new.
621 : */
622 3828128 : if (remove_old)
623 : {
624 620468 : 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 620468 : if (!IsA(old_path, IndexPath))
631 602624 : 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 3207660 : if (new_path->disabled_nodes > old_path->disabled_nodes ||
640 3193728 : (new_path->disabled_nodes == old_path->disabled_nodes &&
641 3192762 : new_path->total_cost >= old_path->total_cost))
642 2669322 : 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 3828128 : if (!accept_new)
651 1545408 : break;
652 : }
653 :
654 4208950 : if (accept_new)
655 : {
656 : /* Accept the new path: insert it at proper place in pathlist */
657 2663542 : parent_rel->pathlist =
658 2663542 : list_insert_nth(parent_rel->pathlist, insert_at, new_path);
659 : }
660 : else
661 : {
662 : /* Reject and recycle the new path */
663 1545408 : if (!IsA(new_path, IndexPath))
664 1451186 : pfree(new_path);
665 : }
666 4208950 : }
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 : */
685 : bool
686 4474306 : add_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 4474306 : new_path_pathkeys = required_outer ? NIL : pathkeys;
696 :
697 : /* Decide whether new path's startup cost is interesting */
698 4474306 : consider_startup = required_outer ? parent_rel->consider_param_startup : parent_rel->consider_startup;
699 :
700 5831402 : foreach(p1, parent_rel->pathlist)
701 : {
702 5537940 : 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 5537940 : if (unlikely(old_path->disabled_nodes != disabled_nodes))
712 : {
713 12918 : if (disabled_nodes < old_path->disabled_nodes)
714 318 : break;
715 : }
716 5525022 : else if (total_cost <= old_path->total_cost * STD_FUZZ_FACTOR)
717 1604180 : 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 3933442 : if (startup_cost > old_path->startup_cost * STD_FUZZ_FACTOR ||
729 1868656 : !consider_startup)
730 : {
731 : /* new path loses on cost, so check pathkeys... */
732 : List *old_path_pathkeys;
733 :
734 3830128 : old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
735 3830128 : keyscmp = compare_pathkeys(new_path_pathkeys,
736 : old_path_pathkeys);
737 3830128 : if (keyscmp == PATHKEYS_EQUAL ||
738 : keyscmp == PATHKEYS_BETTER2)
739 : {
740 : /* new path does not win on pathkeys... */
741 2637414 : if (bms_equal(required_outer, PATH_REQ_OUTER(old_path)))
742 : {
743 : /* Found an old path that dominates the new one */
744 2576346 : return false;
745 : }
746 : }
747 : }
748 : }
749 :
750 1897960 : 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 : */
792 : void
793 112314 : add_partial_path(RelOptInfo *parent_rel, Path *new_path)
794 : {
795 112314 : bool accept_new = true; /* unless we find a superior old path */
796 112314 : int insert_at = 0; /* where to insert new item */
797 : ListCell *p1;
798 :
799 : /* Check for query cancel. */
800 112314 : CHECK_FOR_INTERRUPTS();
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 151542 : foreach(p1, parent_rel->partial_pathlist)
813 : {
814 60170 : Path *old_path = (Path *) lfirst(p1);
815 60170 : bool remove_old = false; /* unless new proves superior */
816 : PathKeysComparison keyscmp;
817 :
818 : /* Compare pathkeys. */
819 60170 : keyscmp = compare_pathkeys(new_path->pathkeys, old_path->pathkeys);
820 :
821 : /* Unless pathkeys are incompatible, keep just one of the two paths. */
822 60170 : if (keyscmp != PATHKEYS_DIFFERENT)
823 : {
824 59960 : if (unlikely(new_path->disabled_nodes != old_path->disabled_nodes))
825 : {
826 1484 : if (new_path->disabled_nodes > old_path->disabled_nodes)
827 956 : accept_new = false;
828 : else
829 528 : remove_old = true;
830 : }
831 58476 : else if (new_path->total_cost > old_path->total_cost
832 58476 : * STD_FUZZ_FACTOR)
833 : {
834 : /* New path costs more; keep it only if pathkeys are better. */
835 20388 : if (keyscmp != PATHKEYS_BETTER1)
836 10856 : accept_new = false;
837 : }
838 38088 : else if (old_path->total_cost > new_path->total_cost
839 38088 : * STD_FUZZ_FACTOR)
840 : {
841 : /* Old path costs more; keep it only if pathkeys are better. */
842 28468 : if (keyscmp != PATHKEYS_BETTER2)
843 13002 : remove_old = true;
844 : }
845 9620 : else if (keyscmp == PATHKEYS_BETTER1)
846 : {
847 : /* Costs are about the same, new path has better pathkeys. */
848 0 : remove_old = true;
849 : }
850 9620 : else if (keyscmp == PATHKEYS_BETTER2)
851 : {
852 : /* Costs are about the same, old path has better pathkeys. */
853 2034 : accept_new = false;
854 : }
855 7586 : 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 490 : remove_old = true;
859 : }
860 : else
861 : {
862 : /*
863 : * Pathkeys are the same, and new path isn't materially
864 : * cheaper.
865 : */
866 7096 : accept_new = false;
867 : }
868 : }
869 :
870 : /*
871 : * Remove current element from partial_pathlist if dominated by new.
872 : */
873 60170 : if (remove_old)
874 : {
875 14020 : parent_rel->partial_pathlist =
876 14020 : foreach_delete_current(parent_rel->partial_pathlist, p1);
877 14020 : pfree(old_path);
878 : }
879 : else
880 : {
881 : /* new belongs after this old path if it has cost >= old's */
882 46150 : if (new_path->total_cost >= old_path->total_cost)
883 29512 : 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 60170 : if (!accept_new)
892 20942 : break;
893 : }
894 :
895 112314 : if (accept_new)
896 : {
897 : /* Accept the new path: insert it at proper place */
898 91372 : parent_rel->partial_pathlist =
899 91372 : list_insert_nth(parent_rel->partial_pathlist, insert_at, new_path);
900 : }
901 : else
902 : {
903 : /* Reject and recycle the new path */
904 20942 : pfree(new_path);
905 : }
906 112314 : }
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 : */
918 : bool
919 86684 : add_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 118024 : foreach(p1, parent_rel->partial_pathlist)
936 : {
937 96488 : Path *old_path = (Path *) lfirst(p1);
938 : PathKeysComparison keyscmp;
939 :
940 96488 : keyscmp = compare_pathkeys(pathkeys, old_path->pathkeys);
941 96488 : if (keyscmp != PATHKEYS_DIFFERENT)
942 : {
943 96296 : if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR &&
944 : keyscmp != PATHKEYS_BETTER1)
945 65148 : return false;
946 47178 : if (old_path->total_cost > total_cost * STD_FUZZ_FACTOR &&
947 : keyscmp != PATHKEYS_BETTER2)
948 16030 : 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 21536 : if (!add_path_precheck(parent_rel, disabled_nodes, total_cost, total_cost,
964 : pathkeys, NULL))
965 2332 : return false;
966 :
967 19204 : 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 : */
980 : Path *
981 415560 : create_seqscan_path(PlannerInfo *root, RelOptInfo *rel,
982 : Relids required_outer, int parallel_workers)
983 : {
984 415560 : Path *pathnode = makeNode(Path);
985 :
986 415560 : pathnode->pathtype = T_SeqScan;
987 415560 : pathnode->parent = rel;
988 415560 : pathnode->pathtarget = rel->reltarget;
989 415560 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
990 : required_outer);
991 415560 : pathnode->parallel_aware = (parallel_workers > 0);
992 415560 : pathnode->parallel_safe = rel->consider_parallel;
993 415560 : pathnode->parallel_workers = parallel_workers;
994 415560 : pathnode->pathkeys = NIL; /* seqscan has unordered result */
995 :
996 415560 : cost_seqscan(pathnode, root, rel, pathnode->param_info);
997 :
998 415560 : return pathnode;
999 : }
1000 :
1001 : /*
1002 : * create_samplescan_path
1003 : * Creates a path node for a sampled table scan.
1004 : */
1005 : Path *
1006 306 : create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
1007 : {
1008 306 : Path *pathnode = makeNode(Path);
1009 :
1010 306 : pathnode->pathtype = T_SampleScan;
1011 306 : pathnode->parent = rel;
1012 306 : pathnode->pathtarget = rel->reltarget;
1013 306 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1014 : required_outer);
1015 306 : pathnode->parallel_aware = false;
1016 306 : pathnode->parallel_safe = rel->consider_parallel;
1017 306 : pathnode->parallel_workers = 0;
1018 306 : pathnode->pathkeys = NIL; /* samplescan has unordered result */
1019 :
1020 306 : cost_samplescan(pathnode, root, rel, pathnode->param_info);
1021 :
1022 306 : 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 : */
1046 : IndexPath *
1047 756212 : create_index_path(PlannerInfo *root,
1048 : IndexOptInfo *index,
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 756212 : IndexPath *pathnode = makeNode(IndexPath);
1060 756212 : RelOptInfo *rel = index->rel;
1061 :
1062 756212 : pathnode->path.pathtype = indexonly ? T_IndexOnlyScan : T_IndexScan;
1063 756212 : pathnode->path.parent = rel;
1064 756212 : pathnode->path.pathtarget = rel->reltarget;
1065 756212 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1066 : required_outer);
1067 756212 : pathnode->path.parallel_aware = false;
1068 756212 : pathnode->path.parallel_safe = rel->consider_parallel;
1069 756212 : pathnode->path.parallel_workers = 0;
1070 756212 : pathnode->path.pathkeys = pathkeys;
1071 :
1072 756212 : pathnode->indexinfo = index;
1073 756212 : pathnode->indexclauses = indexclauses;
1074 756212 : pathnode->indexorderbys = indexorderbys;
1075 756212 : pathnode->indexorderbycols = indexorderbycols;
1076 756212 : pathnode->indexscandir = indexscandir;
1077 :
1078 756212 : cost_index(pathnode, root, loop_count, partial_path);
1079 :
1080 756212 : 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 : */
1095 : BitmapHeapPath *
1096 330940 : create_bitmap_heap_path(PlannerInfo *root,
1097 : RelOptInfo *rel,
1098 : Path *bitmapqual,
1099 : Relids required_outer,
1100 : double loop_count,
1101 : int parallel_degree)
1102 : {
1103 330940 : BitmapHeapPath *pathnode = makeNode(BitmapHeapPath);
1104 :
1105 330940 : pathnode->path.pathtype = T_BitmapHeapScan;
1106 330940 : pathnode->path.parent = rel;
1107 330940 : pathnode->path.pathtarget = rel->reltarget;
1108 330940 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1109 : required_outer);
1110 330940 : pathnode->path.parallel_aware = (parallel_degree > 0);
1111 330940 : pathnode->path.parallel_safe = rel->consider_parallel;
1112 330940 : pathnode->path.parallel_workers = parallel_degree;
1113 330940 : pathnode->path.pathkeys = NIL; /* always unordered */
1114 :
1115 330940 : pathnode->bitmapqual = bitmapqual;
1116 :
1117 330940 : cost_bitmap_heap_scan(&pathnode->path, root, rel,
1118 : pathnode->path.param_info,
1119 : bitmapqual, loop_count);
1120 :
1121 330940 : return pathnode;
1122 : }
1123 :
1124 : /*
1125 : * create_bitmap_and_path
1126 : * Creates a path node representing a BitmapAnd.
1127 : */
1128 : BitmapAndPath *
1129 49732 : create_bitmap_and_path(PlannerInfo *root,
1130 : RelOptInfo *rel,
1131 : List *bitmapquals)
1132 : {
1133 49732 : BitmapAndPath *pathnode = makeNode(BitmapAndPath);
1134 49732 : Relids required_outer = NULL;
1135 : ListCell *lc;
1136 :
1137 49732 : pathnode->path.pathtype = T_BitmapAnd;
1138 49732 : pathnode->path.parent = rel;
1139 49732 : 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 149196 : foreach(lc, bitmapquals)
1147 : {
1148 99464 : Path *bitmapqual = (Path *) lfirst(lc);
1149 :
1150 99464 : required_outer = bms_add_members(required_outer,
1151 99464 : PATH_REQ_OUTER(bitmapqual));
1152 : }
1153 49732 : 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 49732 : pathnode->path.parallel_aware = false;
1163 49732 : pathnode->path.parallel_safe = rel->consider_parallel;
1164 49732 : pathnode->path.parallel_workers = 0;
1165 :
1166 49732 : pathnode->path.pathkeys = NIL; /* always unordered */
1167 :
1168 49732 : pathnode->bitmapquals = bitmapquals;
1169 :
1170 : /* this sets bitmapselectivity as well as the regular cost fields: */
1171 49732 : cost_bitmap_and_node(pathnode, root);
1172 :
1173 49732 : return pathnode;
1174 : }
1175 :
1176 : /*
1177 : * create_bitmap_or_path
1178 : * Creates a path node representing a BitmapOr.
1179 : */
1180 : BitmapOrPath *
1181 1016 : create_bitmap_or_path(PlannerInfo *root,
1182 : RelOptInfo *rel,
1183 : List *bitmapquals)
1184 : {
1185 1016 : BitmapOrPath *pathnode = makeNode(BitmapOrPath);
1186 1016 : Relids required_outer = NULL;
1187 : ListCell *lc;
1188 :
1189 1016 : pathnode->path.pathtype = T_BitmapOr;
1190 1016 : pathnode->path.parent = rel;
1191 1016 : 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 2850 : foreach(lc, bitmapquals)
1199 : {
1200 1834 : Path *bitmapqual = (Path *) lfirst(lc);
1201 :
1202 1834 : required_outer = bms_add_members(required_outer,
1203 1834 : PATH_REQ_OUTER(bitmapqual));
1204 : }
1205 1016 : 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 1016 : pathnode->path.parallel_aware = false;
1215 1016 : pathnode->path.parallel_safe = rel->consider_parallel;
1216 1016 : pathnode->path.parallel_workers = 0;
1217 :
1218 1016 : pathnode->path.pathkeys = NIL; /* always unordered */
1219 :
1220 1016 : pathnode->bitmapquals = bitmapquals;
1221 :
1222 : /* this sets bitmapselectivity as well as the regular cost fields: */
1223 1016 : cost_bitmap_or_node(pathnode, root);
1224 :
1225 1016 : return pathnode;
1226 : }
1227 :
1228 : /*
1229 : * create_tidscan_path
1230 : * Creates a path corresponding to a scan by TID, returning the pathnode.
1231 : */
1232 : TidPath *
1233 860 : create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals,
1234 : Relids required_outer)
1235 : {
1236 860 : TidPath *pathnode = makeNode(TidPath);
1237 :
1238 860 : pathnode->path.pathtype = T_TidScan;
1239 860 : pathnode->path.parent = rel;
1240 860 : pathnode->path.pathtarget = rel->reltarget;
1241 860 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1242 : required_outer);
1243 860 : pathnode->path.parallel_aware = false;
1244 860 : pathnode->path.parallel_safe = rel->consider_parallel;
1245 860 : pathnode->path.parallel_workers = 0;
1246 860 : pathnode->path.pathkeys = NIL; /* always unordered */
1247 :
1248 860 : pathnode->tidquals = tidquals;
1249 :
1250 860 : cost_tidscan(&pathnode->path, root, rel, tidquals,
1251 : pathnode->path.param_info);
1252 :
1253 860 : 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 : */
1261 : TidRangePath *
1262 1940 : create_tidrangescan_path(PlannerInfo *root, RelOptInfo *rel,
1263 : List *tidrangequals, Relids required_outer)
1264 : {
1265 1940 : TidRangePath *pathnode = makeNode(TidRangePath);
1266 :
1267 1940 : pathnode->path.pathtype = T_TidRangeScan;
1268 1940 : pathnode->path.parent = rel;
1269 1940 : pathnode->path.pathtarget = rel->reltarget;
1270 1940 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1271 : required_outer);
1272 1940 : pathnode->path.parallel_aware = false;
1273 1940 : pathnode->path.parallel_safe = rel->consider_parallel;
1274 1940 : pathnode->path.parallel_workers = 0;
1275 1940 : pathnode->path.pathkeys = NIL; /* always unordered */
1276 :
1277 1940 : pathnode->tidrangequals = tidrangequals;
1278 :
1279 1940 : cost_tidrangescan(&pathnode->path, root, rel, tidrangequals,
1280 : pathnode->path.param_info);
1281 :
1282 1940 : 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 : */
1297 : AppendPath *
1298 76524 : create_append_path(PlannerInfo *root,
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 76524 : AppendPath *pathnode = makeNode(AppendPath);
1306 : ListCell *l;
1307 :
1308 : Assert(!parallel_aware || parallel_workers > 0);
1309 :
1310 76524 : pathnode->path.pathtype = T_Append;
1311 76524 : pathnode->path.parent = rel;
1312 76524 : 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 76524 : if (rel->reloptkind == RELOPT_BASEREL && root && subpaths != NIL)
1326 38150 : pathnode->path.param_info = get_baserel_parampathinfo(root,
1327 : rel,
1328 : required_outer);
1329 : else
1330 38374 : pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1331 : required_outer);
1332 :
1333 76524 : pathnode->path.parallel_aware = parallel_aware;
1334 76524 : pathnode->path.parallel_safe = rel->consider_parallel;
1335 76524 : pathnode->path.parallel_workers = parallel_workers;
1336 76524 : 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 76524 : 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 :
1356 25736 : list_sort(subpaths, append_total_cost_compare);
1357 25736 : list_sort(partial_subpaths, append_startup_cost_compare);
1358 : }
1359 76524 : pathnode->first_partial_path = list_length(subpaths);
1360 76524 : 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 76524 : if (root != NULL && bms_equal(rel->relids, root->all_query_rels))
1367 39250 : pathnode->limit_tuples = root->limit_tuples;
1368 : else
1369 37274 : pathnode->limit_tuples = -1.0;
1370 :
1371 250886 : foreach(l, pathnode->subpaths)
1372 : {
1373 174362 : Path *subpath = (Path *) lfirst(l);
1374 :
1375 309298 : pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1376 134936 : 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 76524 : if (list_length(pathnode->subpaths) == 1)
1395 : {
1396 22224 : Path *child = (Path *) linitial(pathnode->subpaths);
1397 :
1398 22224 : if (child->parallel_aware == parallel_aware)
1399 : {
1400 21786 : pathnode->path.rows = child->rows;
1401 21786 : pathnode->path.startup_cost = child->startup_cost;
1402 21786 : pathnode->path.total_cost = child->total_cost;
1403 : }
1404 : else
1405 438 : cost_append(pathnode, root);
1406 : /* Must do this last, else cost_append complains */
1407 22224 : pathnode->path.pathkeys = child->pathkeys;
1408 : }
1409 : else
1410 54300 : cost_append(pathnode, root);
1411 :
1412 : /* If the caller provided a row estimate, override the computed value. */
1413 76524 : if (rows >= 0)
1414 576 : pathnode->path.rows = rows;
1415 :
1416 76524 : 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 : */
1428 : static int
1429 4568 : append_total_cost_compare(const ListCell *a, const ListCell *b)
1430 : {
1431 4568 : Path *path1 = (Path *) lfirst(a);
1432 4568 : Path *path2 = (Path *) lfirst(b);
1433 : int cmp;
1434 :
1435 4568 : cmp = compare_path_costs(path1, path2, TOTAL_COST);
1436 4568 : if (cmp != 0)
1437 4292 : return -cmp;
1438 276 : 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 : */
1450 : static int
1451 34196 : append_startup_cost_compare(const ListCell *a, const ListCell *b)
1452 : {
1453 34196 : Path *path1 = (Path *) lfirst(a);
1454 34196 : Path *path2 = (Path *) lfirst(b);
1455 : int cmp;
1456 :
1457 34196 : cmp = compare_path_costs(path1, path2, STARTUP_COST);
1458 34196 : if (cmp != 0)
1459 13542 : return -cmp;
1460 20654 : 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 : */
1468 : MergeAppendPath *
1469 4358 : create_merge_append_path(PlannerInfo *root,
1470 : RelOptInfo *rel,
1471 : List *subpaths,
1472 : List *pathkeys,
1473 : Relids required_outer)
1474 : {
1475 4358 : MergeAppendPath *pathnode = makeNode(MergeAppendPath);
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 4358 : pathnode->path.pathtype = T_MergeAppend;
1488 4358 : pathnode->path.parent = rel;
1489 4358 : pathnode->path.pathtarget = rel->reltarget;
1490 4358 : pathnode->path.param_info = NULL;
1491 4358 : pathnode->path.parallel_aware = false;
1492 4358 : pathnode->path.parallel_safe = rel->consider_parallel;
1493 4358 : pathnode->path.parallel_workers = 0;
1494 4358 : pathnode->path.pathkeys = pathkeys;
1495 4358 : 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 4358 : if (bms_equal(rel->relids, root->all_query_rels))
1502 2202 : pathnode->limit_tuples = root->limit_tuples;
1503 : else
1504 2156 : pathnode->limit_tuples = -1.0;
1505 :
1506 : /*
1507 : * Add up the sizes and costs of the input paths.
1508 : */
1509 4358 : pathnode->path.rows = 0;
1510 4358 : input_disabled_nodes = 0;
1511 4358 : input_startup_cost = 0;
1512 4358 : input_total_cost = 0;
1513 16260 : foreach(l, subpaths)
1514 : {
1515 11902 : 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 */
1521 : Assert(bms_is_empty(PATH_REQ_OUTER(subpath)));
1522 :
1523 11902 : pathnode->path.rows += subpath->rows;
1524 21014 : pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1525 9112 : subpath->parallel_safe;
1526 :
1527 11902 : 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 346 : if (enable_incremental_sort && presorted_keys > 0)
1539 : {
1540 18 : 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 18 : subpath->pathtarget->width,
1549 : 0.0,
1550 : work_mem,
1551 : pathnode->limit_tuples);
1552 : }
1553 : else
1554 : {
1555 328 : cost_sort(&sort_path,
1556 : root,
1557 : pathkeys,
1558 : subpath->disabled_nodes,
1559 : subpath->total_cost,
1560 : subpath->rows,
1561 328 : subpath->pathtarget->width,
1562 : 0.0,
1563 : work_mem,
1564 : pathnode->limit_tuples);
1565 : }
1566 :
1567 346 : subpath = &sort_path;
1568 : }
1569 :
1570 11902 : input_disabled_nodes += subpath->disabled_nodes;
1571 11902 : input_startup_cost += subpath->startup_cost;
1572 11902 : 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 4358 : if (list_length(subpaths) == 1 &&
1582 110 : ((Path *) linitial(subpaths))->parallel_aware ==
1583 110 : pathnode->path.parallel_aware)
1584 : {
1585 110 : pathnode->path.disabled_nodes = input_disabled_nodes;
1586 110 : pathnode->path.startup_cost = input_startup_cost;
1587 110 : pathnode->path.total_cost = input_total_cost;
1588 : }
1589 : else
1590 4248 : 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 4358 : 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 : */
1606 : GroupResultPath *
1607 189718 : create_group_result_path(PlannerInfo *root, RelOptInfo *rel,
1608 : PathTarget *target, List *havingqual)
1609 : {
1610 189718 : GroupResultPath *pathnode = makeNode(GroupResultPath);
1611 :
1612 189718 : pathnode->path.pathtype = T_Result;
1613 189718 : pathnode->path.parent = rel;
1614 189718 : pathnode->path.pathtarget = target;
1615 189718 : pathnode->path.param_info = NULL; /* there are no other rels... */
1616 189718 : pathnode->path.parallel_aware = false;
1617 189718 : pathnode->path.parallel_safe = rel->consider_parallel;
1618 189718 : pathnode->path.parallel_workers = 0;
1619 189718 : pathnode->path.pathkeys = NIL;
1620 189718 : 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 189718 : pathnode->path.rows = 1;
1628 189718 : pathnode->path.startup_cost = target->cost.startup;
1629 189718 : pathnode->path.total_cost = target->cost.startup +
1630 189718 : 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 189718 : if (havingqual)
1637 : {
1638 : QualCost qual_cost;
1639 :
1640 616 : cost_qual_eval(&qual_cost, havingqual, root);
1641 : /* havingqual is evaluated once at startup */
1642 616 : pathnode->path.startup_cost += qual_cost.startup + qual_cost.per_tuple;
1643 616 : pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
1644 : }
1645 :
1646 189718 : return pathnode;
1647 : }
1648 :
1649 : /*
1650 : * create_material_path
1651 : * Creates a path corresponding to a Material plan, returning the
1652 : * pathnode.
1653 : */
1654 : MaterialPath *
1655 508166 : create_material_path(RelOptInfo *rel, Path *subpath)
1656 : {
1657 508166 : MaterialPath *pathnode = makeNode(MaterialPath);
1658 :
1659 : Assert(subpath->parent == rel);
1660 :
1661 508166 : pathnode->path.pathtype = T_Material;
1662 508166 : pathnode->path.parent = rel;
1663 508166 : pathnode->path.pathtarget = rel->reltarget;
1664 508166 : pathnode->path.param_info = subpath->param_info;
1665 508166 : pathnode->path.parallel_aware = false;
1666 961560 : pathnode->path.parallel_safe = rel->consider_parallel &&
1667 453394 : subpath->parallel_safe;
1668 508166 : pathnode->path.parallel_workers = subpath->parallel_workers;
1669 508166 : pathnode->path.pathkeys = subpath->pathkeys;
1670 :
1671 508166 : pathnode->subpath = subpath;
1672 :
1673 508166 : cost_material(&pathnode->path,
1674 : subpath->disabled_nodes,
1675 : subpath->startup_cost,
1676 : subpath->total_cost,
1677 : subpath->rows,
1678 508166 : subpath->pathtarget->width);
1679 :
1680 508166 : return pathnode;
1681 : }
1682 :
1683 : /*
1684 : * create_memoize_path
1685 : * Creates a path corresponding to a Memoize plan, returning the pathnode.
1686 : */
1687 : MemoizePath *
1688 292386 : create_memoize_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1689 : List *param_exprs, List *hash_operators,
1690 : bool singlerow, bool binary_mode, Cardinality est_calls)
1691 : {
1692 292386 : MemoizePath *pathnode = makeNode(MemoizePath);
1693 :
1694 : Assert(subpath->parent == rel);
1695 :
1696 292386 : pathnode->path.pathtype = T_Memoize;
1697 292386 : pathnode->path.parent = rel;
1698 292386 : pathnode->path.pathtarget = rel->reltarget;
1699 292386 : pathnode->path.param_info = subpath->param_info;
1700 292386 : pathnode->path.parallel_aware = false;
1701 570840 : pathnode->path.parallel_safe = rel->consider_parallel &&
1702 278454 : subpath->parallel_safe;
1703 292386 : pathnode->path.parallel_workers = subpath->parallel_workers;
1704 292386 : pathnode->path.pathkeys = subpath->pathkeys;
1705 :
1706 292386 : pathnode->subpath = subpath;
1707 292386 : pathnode->hash_operators = hash_operators;
1708 292386 : pathnode->param_exprs = param_exprs;
1709 292386 : pathnode->singlerow = singlerow;
1710 292386 : 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 292386 : pathnode->est_entries = 0;
1719 :
1720 292386 : pathnode->est_calls = clamp_row_est(est_calls);
1721 :
1722 : /* These will also be set later in cost_memoize_rescan() */
1723 292386 : pathnode->est_unique_keys = 0.0;
1724 292386 : pathnode->est_hit_ratio = 0.0;
1725 :
1726 : /* we should not generate this path type when enable_memoize=false */
1727 : Assert(enable_memoize);
1728 292386 : 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 292386 : pathnode->path.startup_cost = subpath->startup_cost + cpu_tuple_cost;
1735 292386 : pathnode->path.total_cost = subpath->total_cost + cpu_tuple_cost;
1736 292386 : pathnode->path.rows = subpath->rows;
1737 :
1738 292386 : 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 : */
1747 : GatherMergePath *
1748 14186 : create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1749 : PathTarget *target, List *pathkeys,
1750 : Relids required_outer, double *rows)
1751 : {
1752 14186 : GatherMergePath *pathnode = makeNode(GatherMergePath);
1753 14186 : int input_disabled_nodes = 0;
1754 14186 : Cost input_startup_cost = 0;
1755 14186 : 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 14186 : if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1768 0 : elog(ERROR, "gather merge input not sufficiently sorted");
1769 :
1770 14186 : pathnode->path.pathtype = T_GatherMerge;
1771 14186 : pathnode->path.parent = rel;
1772 14186 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1773 : required_outer);
1774 14186 : pathnode->path.parallel_aware = false;
1775 :
1776 14186 : pathnode->subpath = subpath;
1777 14186 : pathnode->num_workers = subpath->parallel_workers;
1778 14186 : pathnode->path.pathkeys = pathkeys;
1779 14186 : pathnode->path.pathtarget = target ? target : rel->reltarget;
1780 :
1781 14186 : input_disabled_nodes += subpath->disabled_nodes;
1782 14186 : input_startup_cost += subpath->startup_cost;
1783 14186 : input_total_cost += subpath->total_cost;
1784 :
1785 14186 : cost_gather_merge(pathnode, root, rel, pathnode->path.param_info,
1786 : input_disabled_nodes, input_startup_cost,
1787 : input_total_cost, rows);
1788 :
1789 14186 : 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 : */
1799 : GatherPath *
1800 22818 : create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1801 : PathTarget *target, Relids required_outer, double *rows)
1802 : {
1803 22818 : GatherPath *pathnode = makeNode(GatherPath);
1804 :
1805 : Assert(subpath->parallel_safe);
1806 :
1807 22818 : pathnode->path.pathtype = T_Gather;
1808 22818 : pathnode->path.parent = rel;
1809 22818 : pathnode->path.pathtarget = target;
1810 22818 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1811 : required_outer);
1812 22818 : pathnode->path.parallel_aware = false;
1813 22818 : pathnode->path.parallel_safe = false;
1814 22818 : pathnode->path.parallel_workers = 0;
1815 22818 : pathnode->path.pathkeys = NIL; /* Gather has unordered result */
1816 :
1817 22818 : pathnode->subpath = subpath;
1818 22818 : pathnode->num_workers = subpath->parallel_workers;
1819 22818 : pathnode->single_copy = false;
1820 :
1821 22818 : if (pathnode->num_workers == 0)
1822 : {
1823 0 : pathnode->path.pathkeys = subpath->pathkeys;
1824 0 : pathnode->num_workers = 1;
1825 0 : pathnode->single_copy = true;
1826 : }
1827 :
1828 22818 : cost_gather(pathnode, root, rel, pathnode->path.param_info, rows);
1829 :
1830 22818 : 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 : */
1843 : SubqueryScanPath *
1844 48390 : create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1845 : bool trivial_pathtarget,
1846 : List *pathkeys, Relids required_outer)
1847 : {
1848 48390 : SubqueryScanPath *pathnode = makeNode(SubqueryScanPath);
1849 :
1850 48390 : pathnode->path.pathtype = T_SubqueryScan;
1851 48390 : pathnode->path.parent = rel;
1852 48390 : pathnode->path.pathtarget = rel->reltarget;
1853 48390 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1854 : required_outer);
1855 48390 : pathnode->path.parallel_aware = false;
1856 81492 : pathnode->path.parallel_safe = rel->consider_parallel &&
1857 33102 : subpath->parallel_safe;
1858 48390 : pathnode->path.parallel_workers = subpath->parallel_workers;
1859 48390 : pathnode->path.pathkeys = pathkeys;
1860 48390 : pathnode->subpath = subpath;
1861 :
1862 48390 : cost_subqueryscan(pathnode, root, rel, pathnode->path.param_info,
1863 : trivial_pathtarget);
1864 :
1865 48390 : 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 : */
1873 : Path *
1874 50582 : create_functionscan_path(PlannerInfo *root, RelOptInfo *rel,
1875 : List *pathkeys, Relids required_outer)
1876 : {
1877 50582 : Path *pathnode = makeNode(Path);
1878 :
1879 50582 : pathnode->pathtype = T_FunctionScan;
1880 50582 : pathnode->parent = rel;
1881 50582 : pathnode->pathtarget = rel->reltarget;
1882 50582 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1883 : required_outer);
1884 50582 : pathnode->parallel_aware = false;
1885 50582 : pathnode->parallel_safe = rel->consider_parallel;
1886 50582 : pathnode->parallel_workers = 0;
1887 50582 : pathnode->pathkeys = pathkeys;
1888 :
1889 50582 : cost_functionscan(pathnode, root, rel, pathnode->param_info);
1890 :
1891 50582 : 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 : */
1899 : Path *
1900 626 : create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel,
1901 : Relids required_outer)
1902 : {
1903 626 : Path *pathnode = makeNode(Path);
1904 :
1905 626 : pathnode->pathtype = T_TableFuncScan;
1906 626 : pathnode->parent = rel;
1907 626 : pathnode->pathtarget = rel->reltarget;
1908 626 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1909 : required_outer);
1910 626 : pathnode->parallel_aware = false;
1911 626 : pathnode->parallel_safe = rel->consider_parallel;
1912 626 : pathnode->parallel_workers = 0;
1913 626 : pathnode->pathkeys = NIL; /* result is always unordered */
1914 :
1915 626 : cost_tablefuncscan(pathnode, root, rel, pathnode->param_info);
1916 :
1917 626 : 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 : */
1925 : Path *
1926 8218 : create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel,
1927 : Relids required_outer)
1928 : {
1929 8218 : Path *pathnode = makeNode(Path);
1930 :
1931 8218 : pathnode->pathtype = T_ValuesScan;
1932 8218 : pathnode->parent = rel;
1933 8218 : pathnode->pathtarget = rel->reltarget;
1934 8218 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1935 : required_outer);
1936 8218 : pathnode->parallel_aware = false;
1937 8218 : pathnode->parallel_safe = rel->consider_parallel;
1938 8218 : pathnode->parallel_workers = 0;
1939 8218 : pathnode->pathkeys = NIL; /* result is always unordered */
1940 :
1941 8218 : cost_valuesscan(pathnode, root, rel, pathnode->param_info);
1942 :
1943 8218 : 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 : */
1951 : Path *
1952 4232 : create_ctescan_path(PlannerInfo *root, RelOptInfo *rel,
1953 : List *pathkeys, Relids required_outer)
1954 : {
1955 4232 : Path *pathnode = makeNode(Path);
1956 :
1957 4232 : pathnode->pathtype = T_CteScan;
1958 4232 : pathnode->parent = rel;
1959 4232 : pathnode->pathtarget = rel->reltarget;
1960 4232 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1961 : required_outer);
1962 4232 : pathnode->parallel_aware = false;
1963 4232 : pathnode->parallel_safe = rel->consider_parallel;
1964 4232 : pathnode->parallel_workers = 0;
1965 4232 : pathnode->pathkeys = pathkeys;
1966 :
1967 4232 : cost_ctescan(pathnode, root, rel, pathnode->param_info);
1968 :
1969 4232 : 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 : */
1977 : Path *
1978 478 : create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel,
1979 : Relids required_outer)
1980 : {
1981 478 : Path *pathnode = makeNode(Path);
1982 :
1983 478 : pathnode->pathtype = T_NamedTuplestoreScan;
1984 478 : pathnode->parent = rel;
1985 478 : pathnode->pathtarget = rel->reltarget;
1986 478 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1987 : required_outer);
1988 478 : pathnode->parallel_aware = false;
1989 478 : pathnode->parallel_safe = rel->consider_parallel;
1990 478 : pathnode->parallel_workers = 0;
1991 478 : pathnode->pathkeys = NIL; /* result is always unordered */
1992 :
1993 478 : cost_namedtuplestorescan(pathnode, root, rel, pathnode->param_info);
1994 :
1995 478 : 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 : */
2003 : Path *
2004 4268 : create_resultscan_path(PlannerInfo *root, RelOptInfo *rel,
2005 : Relids required_outer)
2006 : {
2007 4268 : Path *pathnode = makeNode(Path);
2008 :
2009 4268 : pathnode->pathtype = T_Result;
2010 4268 : pathnode->parent = rel;
2011 4268 : pathnode->pathtarget = rel->reltarget;
2012 4268 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
2013 : required_outer);
2014 4268 : pathnode->parallel_aware = false;
2015 4268 : pathnode->parallel_safe = rel->consider_parallel;
2016 4268 : pathnode->parallel_workers = 0;
2017 4268 : pathnode->pathkeys = NIL; /* result is always unordered */
2018 :
2019 4268 : cost_resultscan(pathnode, root, rel, pathnode->param_info);
2020 :
2021 4268 : 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 : */
2029 : Path *
2030 926 : create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel,
2031 : Relids required_outer)
2032 : {
2033 926 : Path *pathnode = makeNode(Path);
2034 :
2035 926 : pathnode->pathtype = T_WorkTableScan;
2036 926 : pathnode->parent = rel;
2037 926 : pathnode->pathtarget = rel->reltarget;
2038 926 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
2039 : required_outer);
2040 926 : pathnode->parallel_aware = false;
2041 926 : pathnode->parallel_safe = rel->consider_parallel;
2042 926 : pathnode->parallel_workers = 0;
2043 926 : pathnode->pathkeys = NIL; /* result is always unordered */
2044 :
2045 : /* Cost is the same as for a regular CTE scan */
2046 926 : cost_ctescan(pathnode, root, rel, pathnode->param_info);
2047 :
2048 926 : 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 : */
2062 : ForeignPath *
2063 3664 : create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel,
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 3664 : ForeignPath *pathnode = makeNode(ForeignPath);
2074 :
2075 : /* Historically some FDWs were confused about when to use this */
2076 : Assert(IS_SIMPLE_REL(rel));
2077 :
2078 3664 : pathnode->path.pathtype = T_ForeignScan;
2079 3664 : pathnode->path.parent = rel;
2080 3664 : pathnode->path.pathtarget = target ? target : rel->reltarget;
2081 3664 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
2082 : required_outer);
2083 3664 : pathnode->path.parallel_aware = false;
2084 3664 : pathnode->path.parallel_safe = rel->consider_parallel;
2085 3664 : pathnode->path.parallel_workers = 0;
2086 3664 : pathnode->path.rows = rows;
2087 3664 : pathnode->path.disabled_nodes = disabled_nodes;
2088 3664 : pathnode->path.startup_cost = startup_cost;
2089 3664 : pathnode->path.total_cost = total_cost;
2090 3664 : pathnode->path.pathkeys = pathkeys;
2091 :
2092 3664 : pathnode->fdw_outerpath = fdw_outerpath;
2093 3664 : pathnode->fdw_restrictinfo = fdw_restrictinfo;
2094 3664 : pathnode->fdw_private = fdw_private;
2095 :
2096 3664 : 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 : */
2110 : ForeignPath *
2111 1200 : create_foreign_join_path(PlannerInfo *root, RelOptInfo *rel,
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 1200 : 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 1200 : if (!bms_is_empty(required_outer) || !bms_is_empty(rel->lateral_relids))
2131 0 : elog(ERROR, "parameterized foreign joins are not supported yet");
2132 :
2133 1200 : pathnode->path.pathtype = T_ForeignScan;
2134 1200 : pathnode->path.parent = rel;
2135 1200 : pathnode->path.pathtarget = target ? target : rel->reltarget;
2136 1200 : pathnode->path.param_info = NULL; /* XXX see above */
2137 1200 : pathnode->path.parallel_aware = false;
2138 1200 : pathnode->path.parallel_safe = rel->consider_parallel;
2139 1200 : pathnode->path.parallel_workers = 0;
2140 1200 : pathnode->path.rows = rows;
2141 1200 : pathnode->path.disabled_nodes = disabled_nodes;
2142 1200 : pathnode->path.startup_cost = startup_cost;
2143 1200 : pathnode->path.total_cost = total_cost;
2144 1200 : pathnode->path.pathkeys = pathkeys;
2145 :
2146 1200 : pathnode->fdw_outerpath = fdw_outerpath;
2147 1200 : pathnode->fdw_restrictinfo = fdw_restrictinfo;
2148 1200 : pathnode->fdw_private = fdw_private;
2149 :
2150 1200 : 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 : */
2164 : ForeignPath *
2165 586 : create_foreign_upper_path(PlannerInfo *root, RelOptInfo *rel,
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 586 : ForeignPath *pathnode = makeNode(ForeignPath);
2175 :
2176 : /*
2177 : * Upper relations should never have any lateral references, since joining
2178 : * is complete.
2179 : */
2180 : Assert(bms_is_empty(rel->lateral_relids));
2181 :
2182 586 : pathnode->path.pathtype = T_ForeignScan;
2183 586 : pathnode->path.parent = rel;
2184 586 : pathnode->path.pathtarget = target ? target : rel->reltarget;
2185 586 : pathnode->path.param_info = NULL;
2186 586 : pathnode->path.parallel_aware = false;
2187 586 : pathnode->path.parallel_safe = rel->consider_parallel;
2188 586 : pathnode->path.parallel_workers = 0;
2189 586 : pathnode->path.rows = rows;
2190 586 : pathnode->path.disabled_nodes = disabled_nodes;
2191 586 : pathnode->path.startup_cost = startup_cost;
2192 586 : pathnode->path.total_cost = total_cost;
2193 586 : pathnode->path.pathkeys = pathkeys;
2194 :
2195 586 : pathnode->fdw_outerpath = fdw_outerpath;
2196 586 : pathnode->fdw_restrictinfo = fdw_restrictinfo;
2197 586 : pathnode->fdw_private = fdw_private;
2198 :
2199 586 : 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 : */
2211 : Relids
2212 2945934 : calc_nestloop_required_outer(Relids outerrelids,
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 2945934 : if (!inner_paramrels)
2223 2000430 : return bms_copy(outer_paramrels);
2224 : /* else, form the union ... */
2225 945504 : required_outer = bms_union(outer_paramrels, inner_paramrels);
2226 : /* ... and remove any mention of now-satisfied outer rels */
2227 945504 : required_outer = bms_del_members(required_outer,
2228 : outerrelids);
2229 945504 : 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 : */
2238 : Relids
2239 1921618 : calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
2240 : {
2241 1921618 : Relids outer_paramrels = PATH_REQ_OUTER(outer_path);
2242 1921618 : 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 1921618 : if (inner_path->parent->top_parent_relids)
2255 40310 : innerrelids = inner_path->parent->top_parent_relids;
2256 : else
2257 1881308 : innerrelids = inner_path->parent->relids;
2258 :
2259 1921618 : if (outer_path->parent->top_parent_relids)
2260 40310 : outerrelids = outer_path->parent->top_parent_relids;
2261 : else
2262 1881308 : 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 1921618 : required_outer = bms_union(outer_paramrels, inner_paramrels);
2269 : /* we do not need an explicit test for empty; bms_union gets it right */
2270 1921618 : 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 : */
2290 : NestPath *
2291 1326716 : create_nestloop_path(PlannerInfo *root,
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 1326716 : NestPath *pathnode = makeNode(NestPath);
2303 1326716 : 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 1326716 : if (outer_path->parent->top_parent_relids)
2311 20722 : outerrelids = outer_path->parent->top_parent_relids;
2312 : else
2313 1305994 : 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 1326716 : if (bms_overlap(inner_req_outer, outerrelids))
2324 : {
2325 368970 : Bitmapset *enforced_serials = get_param_path_clause_serials(inner_path);
2326 368970 : List *jclauses = NIL;
2327 : ListCell *lc;
2328 :
2329 817600 : foreach(lc, restrict_clauses)
2330 : {
2331 448630 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2332 :
2333 448630 : if (!bms_is_member(rinfo->rinfo_serial, enforced_serials))
2334 57488 : jclauses = lappend(jclauses, rinfo);
2335 : }
2336 368970 : restrict_clauses = jclauses;
2337 : }
2338 :
2339 1326716 : pathnode->jpath.path.pathtype = T_NestLoop;
2340 1326716 : pathnode->jpath.path.parent = joinrel;
2341 1326716 : pathnode->jpath.path.pathtarget = joinrel->reltarget;
2342 1326716 : pathnode->jpath.path.param_info =
2343 1326716 : get_joinrel_parampathinfo(root,
2344 : joinrel,
2345 : outer_path,
2346 : inner_path,
2347 : extra->sjinfo,
2348 : required_outer,
2349 : &restrict_clauses);
2350 1326716 : pathnode->jpath.path.parallel_aware = false;
2351 3855482 : pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2352 1326716 : outer_path->parallel_safe && inner_path->parallel_safe;
2353 : /* This is a foolish way to estimate parallel_workers, but for now... */
2354 1326716 : pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2355 1326716 : pathnode->jpath.path.pathkeys = pathkeys;
2356 1326716 : pathnode->jpath.jointype = jointype;
2357 1326716 : pathnode->jpath.inner_unique = extra->inner_unique;
2358 1326716 : pathnode->jpath.outerjoinpath = outer_path;
2359 1326716 : pathnode->jpath.innerjoinpath = inner_path;
2360 1326716 : pathnode->jpath.joinrestrictinfo = restrict_clauses;
2361 :
2362 1326716 : final_cost_nestloop(root, pathnode, workspace, extra);
2363 :
2364 1326716 : 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 : */
2387 : MergePath *
2388 310184 : create_mergejoin_path(PlannerInfo *root,
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 310184 : MergePath *pathnode = makeNode(MergePath);
2404 :
2405 310184 : pathnode->jpath.path.pathtype = T_MergeJoin;
2406 310184 : pathnode->jpath.path.parent = joinrel;
2407 310184 : pathnode->jpath.path.pathtarget = joinrel->reltarget;
2408 310184 : pathnode->jpath.path.param_info =
2409 310184 : get_joinrel_parampathinfo(root,
2410 : joinrel,
2411 : outer_path,
2412 : inner_path,
2413 : extra->sjinfo,
2414 : required_outer,
2415 : &restrict_clauses);
2416 310184 : pathnode->jpath.path.parallel_aware = false;
2417 894782 : pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2418 310184 : outer_path->parallel_safe && inner_path->parallel_safe;
2419 : /* This is a foolish way to estimate parallel_workers, but for now... */
2420 310184 : pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2421 310184 : pathnode->jpath.path.pathkeys = pathkeys;
2422 310184 : pathnode->jpath.jointype = jointype;
2423 310184 : pathnode->jpath.inner_unique = extra->inner_unique;
2424 310184 : pathnode->jpath.outerjoinpath = outer_path;
2425 310184 : pathnode->jpath.innerjoinpath = inner_path;
2426 310184 : pathnode->jpath.joinrestrictinfo = restrict_clauses;
2427 310184 : pathnode->path_mergeclauses = mergeclauses;
2428 310184 : pathnode->outersortkeys = outersortkeys;
2429 310184 : pathnode->innersortkeys = innersortkeys;
2430 310184 : 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 310184 : final_cost_mergejoin(root, pathnode, workspace, extra);
2435 :
2436 310184 : 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 : */
2455 : HashPath *
2456 277090 : create_hashjoin_path(PlannerInfo *root,
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 277090 : HashPath *pathnode = makeNode(HashPath);
2469 :
2470 277090 : pathnode->jpath.path.pathtype = T_HashJoin;
2471 277090 : pathnode->jpath.path.parent = joinrel;
2472 277090 : pathnode->jpath.path.pathtarget = joinrel->reltarget;
2473 277090 : pathnode->jpath.path.param_info =
2474 277090 : get_joinrel_parampathinfo(root,
2475 : joinrel,
2476 : outer_path,
2477 : inner_path,
2478 : extra->sjinfo,
2479 : required_outer,
2480 : &restrict_clauses);
2481 277090 : pathnode->jpath.path.parallel_aware =
2482 277090 : joinrel->consider_parallel && parallel_hash;
2483 796102 : pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2484 277090 : outer_path->parallel_safe && inner_path->parallel_safe;
2485 : /* This is a foolish way to estimate parallel_workers, but for now... */
2486 277090 : 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 277090 : pathnode->jpath.path.pathkeys = NIL;
2500 277090 : pathnode->jpath.jointype = jointype;
2501 277090 : pathnode->jpath.inner_unique = extra->inner_unique;
2502 277090 : pathnode->jpath.outerjoinpath = outer_path;
2503 277090 : pathnode->jpath.innerjoinpath = inner_path;
2504 277090 : pathnode->jpath.joinrestrictinfo = restrict_clauses;
2505 277090 : pathnode->path_hashclauses = hashclauses;
2506 : /* final_cost_hashjoin will fill in pathnode->num_batches */
2507 :
2508 277090 : final_cost_hashjoin(root, pathnode, workspace, extra);
2509 :
2510 277090 : 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 : */
2521 : ProjectionPath *
2522 400440 : create_projection_path(PlannerInfo *root,
2523 : RelOptInfo *rel,
2524 : Path *subpath,
2525 : PathTarget *target)
2526 : {
2527 400440 : ProjectionPath *pathnode = makeNode(ProjectionPath);
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 : */
2537 400440 : if (IsA(subpath, ProjectionPath))
2538 : {
2539 12 : ProjectionPath *subpp = (ProjectionPath *) subpath;
2540 :
2541 : Assert(subpp->path.parent == rel);
2542 12 : subpath = subpp->subpath;
2543 : Assert(!IsA(subpath, ProjectionPath));
2544 : }
2545 :
2546 400440 : pathnode->path.pathtype = T_Result;
2547 400440 : pathnode->path.parent = rel;
2548 400440 : pathnode->path.pathtarget = target;
2549 400440 : pathnode->path.param_info = subpath->param_info;
2550 400440 : pathnode->path.parallel_aware = false;
2551 930932 : pathnode->path.parallel_safe = rel->consider_parallel &&
2552 522620 : subpath->parallel_safe &&
2553 122180 : is_parallel_safe(root, (Node *) target->exprs);
2554 400440 : pathnode->path.parallel_workers = subpath->parallel_workers;
2555 : /* Projection does not change the sort order */
2556 400440 : pathnode->path.pathkeys = subpath->pathkeys;
2557 :
2558 400440 : 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 400440 : oldtarget = subpath->pathtarget;
2570 416202 : if (is_projection_capable_path(subpath) ||
2571 15762 : equal(oldtarget->exprs, target->exprs))
2572 : {
2573 : /* No separate Result node needed */
2574 385936 : pathnode->dummypp = true;
2575 :
2576 : /*
2577 : * Set cost of plan as subpath's cost, adjusted for tlist replacement.
2578 : */
2579 385936 : pathnode->path.rows = subpath->rows;
2580 385936 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2581 385936 : pathnode->path.startup_cost = subpath->startup_cost +
2582 385936 : (target->cost.startup - oldtarget->cost.startup);
2583 385936 : pathnode->path.total_cost = subpath->total_cost +
2584 385936 : (target->cost.startup - oldtarget->cost.startup) +
2585 385936 : (target->cost.per_tuple - oldtarget->cost.per_tuple) * subpath->rows;
2586 : }
2587 : else
2588 : {
2589 : /* We really do need the Result node */
2590 14504 : 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 14504 : pathnode->path.rows = subpath->rows;
2597 14504 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2598 14504 : pathnode->path.startup_cost = subpath->startup_cost +
2599 14504 : target->cost.startup;
2600 14504 : pathnode->path.total_cost = subpath->total_cost +
2601 14504 : target->cost.startup +
2602 14504 : (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows;
2603 : }
2604 :
2605 400440 : 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 : */
2630 : Path *
2631 13574 : apply_projection_to_path(PlannerInfo *root,
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 13574 : if (!is_projection_capable_path(path))
2643 1470 : 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 12104 : oldcost = path->pathtarget->cost;
2650 12104 : path->pathtarget = target;
2651 :
2652 12104 : path->startup_cost += target->cost.startup - oldcost.startup;
2653 12104 : path->total_cost += target->cost.startup - oldcost.startup +
2654 12104 : (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 12128 : if ((IsA(path, GatherPath) || IsA(path, GatherMergePath)) &&
2663 24 : 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 24 : if (IsA(path, GatherPath))
2676 : {
2677 0 : GatherPath *gpath = (GatherPath *) path;
2678 :
2679 0 : gpath->subpath = (Path *)
2680 0 : create_projection_path(root,
2681 0 : gpath->subpath->parent,
2682 : gpath->subpath,
2683 : target);
2684 : }
2685 : else
2686 : {
2687 24 : GatherMergePath *gmpath = (GatherMergePath *) path;
2688 :
2689 24 : gmpath->subpath = (Path *)
2690 24 : create_projection_path(root,
2691 24 : gmpath->subpath->parent,
2692 : gmpath->subpath,
2693 : target);
2694 : }
2695 : }
2696 12080 : else if (path->parallel_safe &&
2697 4582 : !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 12 : path->parallel_safe = false;
2705 : }
2706 :
2707 12104 : 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 : */
2719 : ProjectSetPath *
2720 11760 : create_set_projection_path(PlannerInfo *root,
2721 : RelOptInfo *rel,
2722 : Path *subpath,
2723 : PathTarget *target)
2724 : {
2725 11760 : ProjectSetPath *pathnode = makeNode(ProjectSetPath);
2726 : double tlist_rows;
2727 : ListCell *lc;
2728 :
2729 11760 : pathnode->path.pathtype = T_ProjectSet;
2730 11760 : pathnode->path.parent = rel;
2731 11760 : pathnode->path.pathtarget = target;
2732 : /* For now, assume we are above any joins, so no parameterization */
2733 11760 : pathnode->path.param_info = NULL;
2734 11760 : pathnode->path.parallel_aware = false;
2735 27934 : pathnode->path.parallel_safe = rel->consider_parallel &&
2736 16138 : subpath->parallel_safe &&
2737 4378 : is_parallel_safe(root, (Node *) target->exprs);
2738 11760 : pathnode->path.parallel_workers = subpath->parallel_workers;
2739 : /* Projection does not change the sort order XXX? */
2740 11760 : pathnode->path.pathkeys = subpath->pathkeys;
2741 :
2742 11760 : 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 11760 : tlist_rows = 1;
2749 25498 : foreach(lc, target->exprs)
2750 : {
2751 13738 : Node *node = (Node *) lfirst(lc);
2752 : double itemrows;
2753 :
2754 13738 : itemrows = expression_returns_set_rows(root, node);
2755 13738 : if (tlist_rows < itemrows)
2756 11446 : 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 11760 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2766 11760 : pathnode->path.rows = subpath->rows * tlist_rows;
2767 11760 : pathnode->path.startup_cost = subpath->startup_cost +
2768 11760 : target->cost.startup;
2769 11760 : pathnode->path.total_cost = subpath->total_cost +
2770 11760 : target->cost.startup +
2771 11760 : (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows +
2772 11760 : (pathnode->path.rows - subpath->rows) * cpu_tuple_cost / 2;
2773 :
2774 11760 : 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 : */
2789 : IncrementalSortPath *
2790 9332 : create_incremental_sort_path(PlannerInfo *root,
2791 : RelOptInfo *rel,
2792 : Path *subpath,
2793 : List *pathkeys,
2794 : int presorted_keys,
2795 : double limit_tuples)
2796 : {
2797 9332 : IncrementalSortPath *sort = makeNode(IncrementalSortPath);
2798 9332 : SortPath *pathnode = &sort->spath;
2799 :
2800 9332 : pathnode->path.pathtype = T_IncrementalSort;
2801 9332 : pathnode->path.parent = rel;
2802 : /* Sort doesn't project, so use source path's pathtarget */
2803 9332 : pathnode->path.pathtarget = subpath->pathtarget;
2804 9332 : pathnode->path.param_info = subpath->param_info;
2805 9332 : pathnode->path.parallel_aware = false;
2806 13942 : pathnode->path.parallel_safe = rel->consider_parallel &&
2807 4610 : subpath->parallel_safe;
2808 9332 : pathnode->path.parallel_workers = subpath->parallel_workers;
2809 9332 : pathnode->path.pathkeys = pathkeys;
2810 :
2811 9332 : pathnode->subpath = subpath;
2812 :
2813 9332 : 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 9332 : subpath->pathtarget->width,
2820 : 0.0, /* XXX comparison_cost shouldn't be 0? */
2821 : work_mem, limit_tuples);
2822 :
2823 9332 : sort->nPresortedCols = presorted_keys;
2824 :
2825 9332 : 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 : */
2838 : SortPath *
2839 108570 : create_sort_path(PlannerInfo *root,
2840 : RelOptInfo *rel,
2841 : Path *subpath,
2842 : List *pathkeys,
2843 : double limit_tuples)
2844 : {
2845 108570 : SortPath *pathnode = makeNode(SortPath);
2846 :
2847 108570 : pathnode->path.pathtype = T_Sort;
2848 108570 : pathnode->path.parent = rel;
2849 : /* Sort doesn't project, so use source path's pathtarget */
2850 108570 : pathnode->path.pathtarget = subpath->pathtarget;
2851 108570 : pathnode->path.param_info = subpath->param_info;
2852 108570 : pathnode->path.parallel_aware = false;
2853 187742 : pathnode->path.parallel_safe = rel->consider_parallel &&
2854 79172 : subpath->parallel_safe;
2855 108570 : pathnode->path.parallel_workers = subpath->parallel_workers;
2856 108570 : pathnode->path.pathkeys = pathkeys;
2857 :
2858 108570 : pathnode->subpath = subpath;
2859 :
2860 108570 : cost_sort(&pathnode->path, root, pathkeys,
2861 : subpath->disabled_nodes,
2862 : subpath->total_cost,
2863 : subpath->rows,
2864 108570 : subpath->pathtarget->width,
2865 : 0.0, /* XXX comparison_cost shouldn't be 0? */
2866 : work_mem, limit_tuples);
2867 :
2868 108570 : 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 : */
2882 : GroupPath *
2883 1214 : create_group_path(PlannerInfo *root,
2884 : RelOptInfo *rel,
2885 : Path *subpath,
2886 : List *groupClause,
2887 : List *qual,
2888 : double numGroups)
2889 : {
2890 1214 : GroupPath *pathnode = makeNode(GroupPath);
2891 1214 : PathTarget *target = rel->reltarget;
2892 :
2893 1214 : pathnode->path.pathtype = T_Group;
2894 1214 : pathnode->path.parent = rel;
2895 1214 : pathnode->path.pathtarget = target;
2896 : /* For now, assume we are above any joins, so no parameterization */
2897 1214 : pathnode->path.param_info = NULL;
2898 1214 : pathnode->path.parallel_aware = false;
2899 1958 : pathnode->path.parallel_safe = rel->consider_parallel &&
2900 744 : subpath->parallel_safe;
2901 1214 : pathnode->path.parallel_workers = subpath->parallel_workers;
2902 : /* Group doesn't change sort ordering */
2903 1214 : pathnode->path.pathkeys = subpath->pathkeys;
2904 :
2905 1214 : pathnode->subpath = subpath;
2906 :
2907 1214 : pathnode->groupClause = groupClause;
2908 1214 : pathnode->qual = qual;
2909 :
2910 1214 : 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 1214 : pathnode->path.startup_cost += target->cost.startup;
2920 1214 : pathnode->path.total_cost += target->cost.startup +
2921 1214 : target->cost.per_tuple * pathnode->path.rows;
2922 :
2923 1214 : 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 : */
2939 : UniquePath *
2940 22808 : create_unique_path(PlannerInfo *root,
2941 : RelOptInfo *rel,
2942 : Path *subpath,
2943 : int numCols,
2944 : double numGroups)
2945 : {
2946 22808 : UniquePath *pathnode = makeNode(UniquePath);
2947 :
2948 22808 : pathnode->path.pathtype = T_Unique;
2949 22808 : pathnode->path.parent = rel;
2950 : /* Unique doesn't project, so use source path's pathtarget */
2951 22808 : pathnode->path.pathtarget = subpath->pathtarget;
2952 22808 : pathnode->path.param_info = subpath->param_info;
2953 22808 : pathnode->path.parallel_aware = false;
2954 41392 : pathnode->path.parallel_safe = rel->consider_parallel &&
2955 18584 : subpath->parallel_safe;
2956 22808 : pathnode->path.parallel_workers = subpath->parallel_workers;
2957 : /* Unique doesn't change the input ordering */
2958 22808 : pathnode->path.pathkeys = subpath->pathkeys;
2959 :
2960 22808 : pathnode->subpath = subpath;
2961 22808 : 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 22808 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2969 22808 : pathnode->path.startup_cost = subpath->startup_cost;
2970 22808 : pathnode->path.total_cost = subpath->total_cost +
2971 22808 : cpu_operator_cost * subpath->rows * numCols;
2972 22808 : pathnode->path.rows = numGroups;
2973 :
2974 22808 : 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 : */
2991 : AggPath *
2992 71198 : create_agg_path(PlannerInfo *root,
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 71198 : AggPath *pathnode = makeNode(AggPath);
3004 :
3005 71198 : pathnode->path.pathtype = T_Agg;
3006 71198 : pathnode->path.parent = rel;
3007 71198 : pathnode->path.pathtarget = target;
3008 71198 : pathnode->path.param_info = subpath->param_info;
3009 71198 : pathnode->path.parallel_aware = false;
3010 123170 : pathnode->path.parallel_safe = rel->consider_parallel &&
3011 51972 : subpath->parallel_safe;
3012 71198 : pathnode->path.parallel_workers = subpath->parallel_workers;
3013 :
3014 71198 : 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 7818 : if (list_length(subpath->pathkeys) > root->num_groupby_pathkeys)
3025 328 : pathnode->path.pathkeys = list_copy_head(subpath->pathkeys,
3026 : root->num_groupby_pathkeys);
3027 : else
3028 7490 : pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */
3029 : }
3030 : else
3031 63380 : pathnode->path.pathkeys = NIL; /* output is unordered */
3032 :
3033 71198 : pathnode->subpath = subpath;
3034 :
3035 71198 : pathnode->aggstrategy = aggstrategy;
3036 71198 : pathnode->aggsplit = aggsplit;
3037 71198 : pathnode->numGroups = numGroups;
3038 71198 : pathnode->transitionSpace = aggcosts ? aggcosts->transitionSpace : 0;
3039 71198 : pathnode->groupClause = groupClause;
3040 71198 : pathnode->qual = qual;
3041 :
3042 71198 : 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 71198 : subpath->rows, subpath->pathtarget->width);
3049 :
3050 : /* add tlist eval cost for each output row */
3051 71198 : pathnode->path.startup_cost += target->cost.startup;
3052 71198 : pathnode->path.total_cost += target->cost.startup +
3053 71198 : target->cost.per_tuple * pathnode->path.rows;
3054 :
3055 71198 : 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 : */
3073 : GroupingSetsPath *
3074 2128 : create_groupingsets_path(PlannerInfo *root,
3075 : RelOptInfo *rel,
3076 : Path *subpath,
3077 : List *having_qual,
3078 : AggStrategy aggstrategy,
3079 : List *rollups,
3080 : const AggClauseCosts *agg_costs)
3081 : {
3082 2128 : GroupingSetsPath *pathnode = makeNode(GroupingSetsPath);
3083 2128 : PathTarget *target = rel->reltarget;
3084 : ListCell *lc;
3085 2128 : bool is_first = true;
3086 2128 : bool is_first_sort = true;
3087 :
3088 : /* The topmost generated Plan node will be an Agg */
3089 2128 : pathnode->path.pathtype = T_Agg;
3090 2128 : pathnode->path.parent = rel;
3091 2128 : pathnode->path.pathtarget = target;
3092 2128 : pathnode->path.param_info = subpath->param_info;
3093 2128 : pathnode->path.parallel_aware = false;
3094 3118 : pathnode->path.parallel_safe = rel->consider_parallel &&
3095 990 : subpath->parallel_safe;
3096 2128 : pathnode->path.parallel_workers = subpath->parallel_workers;
3097 2128 : 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 3036 : if (aggstrategy == AGG_SORTED &&
3104 908 : list_length(rollups) == 1 &&
3105 458 : ((RollupData *) linitial(rollups))->groupClause == NIL)
3106 42 : aggstrategy = AGG_PLAIN;
3107 :
3108 3044 : if (aggstrategy == AGG_MIXED &&
3109 916 : list_length(rollups) == 1)
3110 0 : 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 2128 : if (aggstrategy == AGG_SORTED && list_length(rollups) == 1)
3118 416 : pathnode->path.pathkeys = root->group_pathkeys;
3119 : else
3120 1712 : pathnode->path.pathkeys = NIL;
3121 :
3122 2128 : pathnode->aggstrategy = aggstrategy;
3123 2128 : pathnode->rollups = rollups;
3124 2128 : pathnode->qual = having_qual;
3125 2128 : 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 7416 : foreach(lc, rollups)
3132 : {
3133 5288 : RollupData *rollup = lfirst(lc);
3134 5288 : List *gsets = rollup->gsets;
3135 5288 : 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 5288 : if (is_first)
3148 : {
3149 2128 : 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 2128 : subpath->pathtarget->width);
3160 2128 : is_first = false;
3161 2128 : if (!rollup->is_hashed)
3162 908 : 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 3160 : 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 2422 : cost_agg(&agg_path, root,
3176 2422 : 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 2422 : subpath->pathtarget->width);
3184 2422 : if (!rollup->is_hashed)
3185 916 : is_first_sort = false;
3186 : }
3187 : else
3188 : {
3189 : /* Account for cost of sort, but don't charge input cost again */
3190 738 : cost_sort(&sort_path, root, NIL, 0,
3191 : 0.0,
3192 : subpath->rows,
3193 738 : subpath->pathtarget->width,
3194 : 0.0,
3195 : work_mem,
3196 : -1.0);
3197 :
3198 : /* Account for cost of aggregation */
3199 :
3200 738 : 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 738 : subpath->pathtarget->width);
3211 : }
3212 :
3213 3160 : pathnode->path.disabled_nodes += agg_path.disabled_nodes;
3214 3160 : pathnode->path.total_cost += agg_path.total_cost;
3215 3160 : pathnode->path.rows += agg_path.rows;
3216 : }
3217 : }
3218 :
3219 : /* add tlist eval cost for each output row */
3220 2128 : pathnode->path.startup_cost += target->cost.startup;
3221 2128 : pathnode->path.total_cost += target->cost.startup +
3222 2128 : target->cost.per_tuple * pathnode->path.rows;
3223 :
3224 2128 : 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 : */
3236 : MinMaxAggPath *
3237 410 : create_minmaxagg_path(PlannerInfo *root,
3238 : RelOptInfo *rel,
3239 : PathTarget *target,
3240 : List *mmaggregates,
3241 : List *quals)
3242 : {
3243 410 : MinMaxAggPath *pathnode = makeNode(MinMaxAggPath);
3244 : Cost initplan_cost;
3245 410 : int initplan_disabled_nodes = 0;
3246 : ListCell *lc;
3247 :
3248 : /* The topmost generated Plan node will be a Result */
3249 410 : pathnode->path.pathtype = T_Result;
3250 410 : pathnode->path.parent = rel;
3251 410 : pathnode->path.pathtarget = target;
3252 : /* For now, assume we are above any joins, so no parameterization */
3253 410 : pathnode->path.param_info = NULL;
3254 410 : pathnode->path.parallel_aware = false;
3255 410 : pathnode->path.parallel_safe = true; /* might change below */
3256 410 : pathnode->path.parallel_workers = 0;
3257 : /* Result is one unordered row */
3258 410 : pathnode->path.rows = 1;
3259 410 : pathnode->path.pathkeys = NIL;
3260 :
3261 410 : pathnode->mmaggregates = mmaggregates;
3262 410 : pathnode->quals = quals;
3263 :
3264 : /* Calculate cost of all the initplans, and check parallel safety */
3265 410 : initplan_cost = 0;
3266 856 : foreach(lc, mmaggregates)
3267 : {
3268 446 : MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3269 :
3270 446 : initplan_disabled_nodes += mminfo->path->disabled_nodes;
3271 446 : initplan_cost += mminfo->pathcost;
3272 446 : if (!mminfo->path->parallel_safe)
3273 110 : pathnode->path.parallel_safe = false;
3274 : }
3275 :
3276 : /* add tlist eval cost for each output row, plus cpu_tuple_cost */
3277 410 : pathnode->path.disabled_nodes = initplan_disabled_nodes;
3278 410 : pathnode->path.startup_cost = initplan_cost + target->cost.startup;
3279 410 : pathnode->path.total_cost = initplan_cost + target->cost.startup +
3280 410 : 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 410 : if (quals)
3287 : {
3288 : QualCost qual_cost;
3289 :
3290 0 : cost_qual_eval(&qual_cost, quals, root);
3291 0 : pathnode->path.startup_cost += qual_cost.startup;
3292 0 : 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 410 : if (pathnode->path.parallel_safe)
3302 300 : pathnode->path.parallel_safe =
3303 600 : is_parallel_safe(root, (Node *) target->exprs) &&
3304 300 : is_parallel_safe(root, (Node *) quals);
3305 :
3306 410 : 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 : */
3327 : WindowAggPath *
3328 2754 : create_windowagg_path(PlannerInfo *root,
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 : {
3338 2754 : WindowAggPath *pathnode = makeNode(WindowAggPath);
3339 :
3340 : /* qual can only be set for the topwindow */
3341 : Assert(qual == NIL || topwindow);
3342 :
3343 2754 : pathnode->path.pathtype = T_WindowAgg;
3344 2754 : pathnode->path.parent = rel;
3345 2754 : pathnode->path.pathtarget = target;
3346 : /* For now, assume we are above any joins, so no parameterization */
3347 2754 : pathnode->path.param_info = NULL;
3348 2754 : pathnode->path.parallel_aware = false;
3349 2754 : pathnode->path.parallel_safe = rel->consider_parallel &&
3350 0 : subpath->parallel_safe;
3351 2754 : pathnode->path.parallel_workers = subpath->parallel_workers;
3352 : /* WindowAgg preserves the input sort order */
3353 2754 : pathnode->path.pathkeys = subpath->pathkeys;
3354 :
3355 2754 : pathnode->subpath = subpath;
3356 2754 : pathnode->winclause = winclause;
3357 2754 : pathnode->qual = qual;
3358 2754 : pathnode->runCondition = runCondition;
3359 2754 : 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 2754 : 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 2754 : pathnode->path.startup_cost += target->cost.startup;
3377 2754 : pathnode->path.total_cost += target->cost.startup +
3378 2754 : target->cost.per_tuple * pathnode->path.rows;
3379 :
3380 2754 : 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 : */
3400 : SetOpPath *
3401 1264 : create_setop_path(PlannerInfo *root,
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 1264 : SetOpPath *pathnode = makeNode(SetOpPath);
3412 :
3413 1264 : pathnode->path.pathtype = T_SetOp;
3414 1264 : pathnode->path.parent = rel;
3415 1264 : pathnode->path.pathtarget = rel->reltarget;
3416 : /* For now, assume we are above any joins, so no parameterization */
3417 1264 : pathnode->path.param_info = NULL;
3418 1264 : pathnode->path.parallel_aware = false;
3419 2528 : pathnode->path.parallel_safe = rel->consider_parallel &&
3420 1264 : leftpath->parallel_safe && rightpath->parallel_safe;
3421 1264 : pathnode->path.parallel_workers =
3422 1264 : leftpath->parallel_workers + rightpath->parallel_workers;
3423 : /* SetOp preserves the input sort order if in sort mode */
3424 1264 : pathnode->path.pathkeys =
3425 1264 : (strategy == SETOP_SORTED) ? leftpath->pathkeys : NIL;
3426 :
3427 1264 : pathnode->leftpath = leftpath;
3428 1264 : pathnode->rightpath = rightpath;
3429 1264 : pathnode->cmd = cmd;
3430 1264 : pathnode->strategy = strategy;
3431 1264 : pathnode->groupList = groupList;
3432 1264 : 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 1264 : pathnode->path.disabled_nodes =
3440 1264 : leftpath->disabled_nodes + rightpath->disabled_nodes;
3441 1264 : 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 662 : pathnode->path.startup_cost =
3449 662 : leftpath->startup_cost + rightpath->startup_cost;
3450 662 : pathnode->path.total_cost =
3451 1324 : leftpath->total_cost + rightpath->total_cost +
3452 662 : 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 662 : 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 602 : pathnode->path.startup_cost =
3471 1204 : leftpath->total_cost + rightpath->total_cost +
3472 602 : cpu_operator_cost * (leftpath->rows + rightpath->rows) * list_length(groupList);
3473 602 : 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 602 : 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 602 : if (!enable_hashagg)
3488 114 : 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 602 : hashentrysize = MAXALIGN(leftpath->pathtarget->width) +
3495 : MAXALIGN(SizeofMinimalTupleHeader);
3496 602 : if (hashentrysize * numGroups > get_hash_memory_limit())
3497 0 : pathnode->path.disabled_nodes++;
3498 : }
3499 1264 : pathnode->path.rows = outputRows;
3500 :
3501 1264 : 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 : */
3518 : RecursiveUnionPath *
3519 920 : create_recursiveunion_path(PlannerInfo *root,
3520 : RelOptInfo *rel,
3521 : Path *leftpath,
3522 : Path *rightpath,
3523 : PathTarget *target,
3524 : List *distinctList,
3525 : int wtParam,
3526 : double numGroups)
3527 : {
3528 920 : RecursiveUnionPath *pathnode = makeNode(RecursiveUnionPath);
3529 :
3530 920 : pathnode->path.pathtype = T_RecursiveUnion;
3531 920 : pathnode->path.parent = rel;
3532 920 : pathnode->path.pathtarget = target;
3533 : /* For now, assume we are above any joins, so no parameterization */
3534 920 : pathnode->path.param_info = NULL;
3535 920 : pathnode->path.parallel_aware = false;
3536 1840 : pathnode->path.parallel_safe = rel->consider_parallel &&
3537 920 : leftpath->parallel_safe && rightpath->parallel_safe;
3538 : /* Foolish, but we'll do it like joins for now: */
3539 920 : pathnode->path.parallel_workers = leftpath->parallel_workers;
3540 : /* RecursiveUnion result is always unsorted */
3541 920 : pathnode->path.pathkeys = NIL;
3542 :
3543 920 : pathnode->leftpath = leftpath;
3544 920 : pathnode->rightpath = rightpath;
3545 920 : pathnode->distinctList = distinctList;
3546 920 : pathnode->wtParam = wtParam;
3547 920 : pathnode->numGroups = numGroups;
3548 :
3549 920 : cost_recursive_union(&pathnode->path, leftpath, rightpath);
3550 :
3551 920 : 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 : */
3563 : LockRowsPath *
3564 8230 : create_lockrows_path(PlannerInfo *root, RelOptInfo *rel,
3565 : Path *subpath, List *rowMarks, int epqParam)
3566 : {
3567 8230 : LockRowsPath *pathnode = makeNode(LockRowsPath);
3568 :
3569 8230 : pathnode->path.pathtype = T_LockRows;
3570 8230 : pathnode->path.parent = rel;
3571 : /* LockRows doesn't project, so use source path's pathtarget */
3572 8230 : pathnode->path.pathtarget = subpath->pathtarget;
3573 : /* For now, assume we are above any joins, so no parameterization */
3574 8230 : pathnode->path.param_info = NULL;
3575 8230 : pathnode->path.parallel_aware = false;
3576 8230 : pathnode->path.parallel_safe = false;
3577 8230 : pathnode->path.parallel_workers = 0;
3578 8230 : 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 8230 : pathnode->path.pathkeys = NIL;
3585 :
3586 8230 : pathnode->subpath = subpath;
3587 8230 : pathnode->rowMarks = rowMarks;
3588 8230 : 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 8230 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
3596 8230 : pathnode->path.startup_cost = subpath->startup_cost;
3597 8230 : pathnode->path.total_cost = subpath->total_cost +
3598 8230 : cpu_tuple_cost * subpath->rows;
3599 :
3600 8230 : 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 : */
3627 : ModifyTablePath *
3628 86596 : create_modifytable_path(PlannerInfo *root, RelOptInfo *rel,
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 : {
3640 86596 : ModifyTablePath *pathnode = makeNode(ModifyTablePath);
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 86596 : pathnode->path.pathtype = T_ModifyTable;
3652 86596 : pathnode->path.parent = rel;
3653 : /* pathtarget is not interesting, just make it minimally valid */
3654 86596 : pathnode->path.pathtarget = rel->reltarget;
3655 : /* For now, assume we are above any joins, so no parameterization */
3656 86596 : pathnode->path.param_info = NULL;
3657 86596 : pathnode->path.parallel_aware = false;
3658 86596 : pathnode->path.parallel_safe = false;
3659 86596 : pathnode->path.parallel_workers = 0;
3660 86596 : 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 86596 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
3673 86596 : pathnode->path.startup_cost = subpath->startup_cost;
3674 86596 : pathnode->path.total_cost = subpath->total_cost;
3675 86596 : if (returningLists != NIL)
3676 : {
3677 2896 : 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 2896 : pathnode->path.pathtarget->width = subpath->pathtarget->width;
3686 : }
3687 : else
3688 : {
3689 83700 : pathnode->path.rows = 0;
3690 83700 : pathnode->path.pathtarget->width = 0;
3691 : }
3692 :
3693 86596 : pathnode->subpath = subpath;
3694 86596 : pathnode->operation = operation;
3695 86596 : pathnode->canSetTag = canSetTag;
3696 86596 : pathnode->nominalRelation = nominalRelation;
3697 86596 : pathnode->rootRelation = rootRelation;
3698 86596 : pathnode->partColsUpdated = partColsUpdated;
3699 86596 : pathnode->resultRelations = resultRelations;
3700 86596 : pathnode->updateColnosLists = updateColnosLists;
3701 86596 : pathnode->withCheckOptionLists = withCheckOptionLists;
3702 86596 : pathnode->returningLists = returningLists;
3703 86596 : pathnode->rowMarks = rowMarks;
3704 86596 : pathnode->onconflict = onconflict;
3705 86596 : pathnode->epqParam = epqParam;
3706 86596 : pathnode->mergeActionLists = mergeActionLists;
3707 86596 : pathnode->mergeJoinConditions = mergeJoinConditions;
3708 :
3709 86596 : 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 : */
3729 : LimitPath *
3730 6028 : create_limit_path(PlannerInfo *root, RelOptInfo *rel,
3731 : Path *subpath,
3732 : Node *limitOffset, Node *limitCount,
3733 : LimitOption limitOption,
3734 : int64 offset_est, int64 count_est)
3735 : {
3736 6028 : LimitPath *pathnode = makeNode(LimitPath);
3737 :
3738 6028 : pathnode->path.pathtype = T_Limit;
3739 6028 : pathnode->path.parent = rel;
3740 : /* Limit doesn't project, so use source path's pathtarget */
3741 6028 : pathnode->path.pathtarget = subpath->pathtarget;
3742 : /* For now, assume we are above any joins, so no parameterization */
3743 6028 : pathnode->path.param_info = NULL;
3744 6028 : pathnode->path.parallel_aware = false;
3745 8440 : pathnode->path.parallel_safe = rel->consider_parallel &&
3746 2412 : subpath->parallel_safe;
3747 6028 : pathnode->path.parallel_workers = subpath->parallel_workers;
3748 6028 : pathnode->path.rows = subpath->rows;
3749 6028 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
3750 6028 : pathnode->path.startup_cost = subpath->startup_cost;
3751 6028 : pathnode->path.total_cost = subpath->total_cost;
3752 6028 : pathnode->path.pathkeys = subpath->pathkeys;
3753 6028 : pathnode->subpath = subpath;
3754 6028 : pathnode->limitOffset = limitOffset;
3755 6028 : pathnode->limitCount = limitCount;
3756 6028 : pathnode->limitOption = limitOption;
3757 :
3758 : /*
3759 : * Adjust the output rows count and costs according to the offset/limit.
3760 : */
3761 6028 : adjust_limit_rows_costs(&pathnode->path.rows,
3762 : &pathnode->path.startup_cost,
3763 : &pathnode->path.total_cost,
3764 : offset_est, count_est);
3765 :
3766 6028 : 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 : */
3785 : void
3786 6212 : adjust_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 6212 : double input_rows = *rows;
3793 6212 : Cost input_startup_cost = *startup_cost;
3794 6212 : Cost input_total_cost = *total_cost;
3795 :
3796 6212 : if (offset_est != 0)
3797 : {
3798 : double offset_rows;
3799 :
3800 694 : if (offset_est > 0)
3801 670 : offset_rows = (double) offset_est;
3802 : else
3803 24 : offset_rows = clamp_row_est(input_rows * 0.10);
3804 694 : if (offset_rows > *rows)
3805 38 : offset_rows = *rows;
3806 694 : if (input_rows > 0)
3807 694 : *startup_cost +=
3808 694 : (input_total_cost - input_startup_cost)
3809 694 : * offset_rows / input_rows;
3810 694 : *rows -= offset_rows;
3811 694 : if (*rows < 1)
3812 46 : *rows = 1;
3813 : }
3814 :
3815 6212 : if (count_est != 0)
3816 : {
3817 : double count_rows;
3818 :
3819 6154 : if (count_est > 0)
3820 6148 : count_rows = (double) count_est;
3821 : else
3822 6 : count_rows = clamp_row_est(input_rows * 0.10);
3823 6154 : if (count_rows > *rows)
3824 248 : count_rows = *rows;
3825 6154 : if (input_rows > 0)
3826 6154 : *total_cost = *startup_cost +
3827 6154 : (input_total_cost - input_startup_cost)
3828 6154 : * count_rows / input_rows;
3829 6154 : *rows = count_rows;
3830 6154 : if (*rows < 1)
3831 0 : *rows = 1;
3832 : }
3833 6212 : }
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 : */
3853 : Path *
3854 356 : reparameterize_path(PlannerInfo *root, Path *path,
3855 : Relids required_outer,
3856 : double loop_count)
3857 : {
3858 356 : RelOptInfo *rel = path->parent;
3859 :
3860 : /* Can only increase, not decrease, path's parameterization */
3861 356 : if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
3862 0 : return NULL;
3863 356 : switch (path->pathtype)
3864 : {
3865 264 : case T_SeqScan:
3866 264 : return create_seqscan_path(root, rel, required_outer, 0);
3867 0 : case T_SampleScan:
3868 0 : return (Path *) create_samplescan_path(root, rel, required_outer);
3869 0 : case T_IndexScan:
3870 : case T_IndexOnlyScan:
3871 : {
3872 0 : IndexPath *ipath = (IndexPath *) path;
3873 0 : 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 0 : memcpy(newpath, ipath, sizeof(IndexPath));
3883 0 : newpath->path.param_info =
3884 0 : get_baserel_parampathinfo(root, rel, required_outer);
3885 0 : cost_index(newpath, root, loop_count, false);
3886 0 : return (Path *) newpath;
3887 : }
3888 0 : case T_BitmapHeapScan:
3889 : {
3890 0 : BitmapHeapPath *bpath = (BitmapHeapPath *) path;
3891 :
3892 0 : return (Path *) create_bitmap_heap_path(root,
3893 : rel,
3894 : bpath->bitmapqual,
3895 : required_outer,
3896 : loop_count, 0);
3897 : }
3898 0 : case T_SubqueryScan:
3899 : {
3900 0 : SubqueryScanPath *spath = (SubqueryScanPath *) path;
3901 0 : 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 0 : trivial_pathtarget =
3912 0 : (subpath->total_cost == spath->path.total_cost);
3913 :
3914 0 : return (Path *) create_subqueryscan_path(root,
3915 : rel,
3916 : subpath,
3917 : trivial_pathtarget,
3918 : spath->path.pathkeys,
3919 : required_outer);
3920 : }
3921 60 : case T_Result:
3922 : /* Supported only for RTE_RESULT scan paths */
3923 60 : if (IsA(path, Path))
3924 60 : return create_resultscan_path(root, rel, required_outer);
3925 0 : break;
3926 0 : case T_Append:
3927 : {
3928 0 : AppendPath *apath = (AppendPath *) path;
3929 0 : List *childpaths = NIL;
3930 0 : List *partialpaths = NIL;
3931 : int i;
3932 : ListCell *lc;
3933 :
3934 : /* Reparameterize the children */
3935 0 : i = 0;
3936 0 : foreach(lc, apath->subpaths)
3937 : {
3938 0 : Path *spath = (Path *) lfirst(lc);
3939 :
3940 0 : spath = reparameterize_path(root, spath,
3941 : required_outer,
3942 : loop_count);
3943 0 : if (spath == NULL)
3944 0 : return NULL;
3945 : /* We have to re-split the regular and partial paths */
3946 0 : if (i < apath->first_partial_path)
3947 0 : childpaths = lappend(childpaths, spath);
3948 : else
3949 0 : partialpaths = lappend(partialpaths, spath);
3950 0 : i++;
3951 : }
3952 0 : return (Path *)
3953 0 : create_append_path(root, rel, childpaths, partialpaths,
3954 : apath->path.pathkeys, required_outer,
3955 : apath->path.parallel_workers,
3956 0 : apath->path.parallel_aware,
3957 : -1);
3958 : }
3959 0 : case T_Material:
3960 : {
3961 0 : MaterialPath *mpath = (MaterialPath *) path;
3962 0 : Path *spath = mpath->subpath;
3963 :
3964 0 : spath = reparameterize_path(root, spath,
3965 : required_outer,
3966 : loop_count);
3967 0 : if (spath == NULL)
3968 0 : return NULL;
3969 0 : return (Path *) create_material_path(rel, spath);
3970 : }
3971 0 : case T_Memoize:
3972 : {
3973 0 : MemoizePath *mpath = (MemoizePath *) path;
3974 0 : Path *spath = mpath->subpath;
3975 :
3976 0 : spath = reparameterize_path(root, spath,
3977 : required_outer,
3978 : loop_count);
3979 0 : if (spath == NULL)
3980 0 : return NULL;
3981 0 : return (Path *) create_memoize_path(root, rel,
3982 : spath,
3983 : mpath->param_exprs,
3984 : mpath->hash_operators,
3985 0 : mpath->singlerow,
3986 0 : mpath->binary_mode,
3987 : mpath->est_calls);
3988 : }
3989 32 : default:
3990 32 : break;
3991 : }
3992 32 : 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 : */
4019 : Path *
4020 91942 : reparameterize_path_by_child(PlannerInfo *root, Path *path,
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) \
4035 : do { \
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) \
4042 : do { \
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 91942 : if (!path->param_info ||
4057 46056 : !bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
4058 90916 : 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 1026 : switch (nodeTag(path))
4073 : {
4074 228 : case T_Path:
4075 228 : new_path = path;
4076 228 : ADJUST_CHILD_ATTRS(new_path->parent->baserestrictinfo);
4077 228 : if (path->pathtype == T_SampleScan)
4078 : {
4079 48 : 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 48 : rte = planner_rt_fetch(scan_relid, root);
4085 : Assert(rte->rtekind == RTE_RELATION);
4086 : Assert(rte->tablesample != NULL);
4087 :
4088 48 : ADJUST_CHILD_ATTRS(rte->tablesample);
4089 : }
4090 228 : break;
4091 :
4092 528 : case T_IndexPath:
4093 : {
4094 528 : IndexPath *ipath = (IndexPath *) path;
4095 :
4096 528 : ADJUST_CHILD_ATTRS(ipath->indexinfo->indrestrictinfo);
4097 528 : ADJUST_CHILD_ATTRS(ipath->indexclauses);
4098 528 : new_path = (Path *) ipath;
4099 : }
4100 528 : break;
4101 :
4102 48 : case T_BitmapHeapPath:
4103 : {
4104 48 : BitmapHeapPath *bhpath = (BitmapHeapPath *) path;
4105 :
4106 48 : ADJUST_CHILD_ATTRS(bhpath->path.parent->baserestrictinfo);
4107 48 : REPARAMETERIZE_CHILD_PATH(bhpath->bitmapqual);
4108 48 : new_path = (Path *) bhpath;
4109 : }
4110 48 : break;
4111 :
4112 24 : case T_BitmapAndPath:
4113 : {
4114 24 : BitmapAndPath *bapath = (BitmapAndPath *) path;
4115 :
4116 24 : REPARAMETERIZE_CHILD_PATH_LIST(bapath->bitmapquals);
4117 24 : new_path = (Path *) bapath;
4118 : }
4119 24 : break;
4120 :
4121 24 : case T_BitmapOrPath:
4122 : {
4123 24 : BitmapOrPath *bopath = (BitmapOrPath *) path;
4124 :
4125 24 : REPARAMETERIZE_CHILD_PATH_LIST(bopath->bitmapquals);
4126 24 : new_path = (Path *) bopath;
4127 : }
4128 24 : break;
4129 :
4130 0 : case T_ForeignPath:
4131 : {
4132 0 : ForeignPath *fpath = (ForeignPath *) path;
4133 : ReparameterizeForeignPathByChild_function rfpc_func;
4134 :
4135 0 : ADJUST_CHILD_ATTRS(fpath->path.parent->baserestrictinfo);
4136 0 : if (fpath->fdw_outerpath)
4137 0 : REPARAMETERIZE_CHILD_PATH(fpath->fdw_outerpath);
4138 0 : if (fpath->fdw_restrictinfo)
4139 0 : ADJUST_CHILD_ATTRS(fpath->fdw_restrictinfo);
4140 :
4141 : /* Hand over to FDW if needed. */
4142 0 : rfpc_func =
4143 0 : path->parent->fdwroutine->ReparameterizeForeignPathByChild;
4144 0 : if (rfpc_func)
4145 0 : fpath->fdw_private = rfpc_func(root, fpath->fdw_private,
4146 : child_rel);
4147 0 : new_path = (Path *) fpath;
4148 : }
4149 0 : break;
4150 :
4151 0 : case T_CustomPath:
4152 : {
4153 0 : CustomPath *cpath = (CustomPath *) path;
4154 :
4155 0 : ADJUST_CHILD_ATTRS(cpath->path.parent->baserestrictinfo);
4156 0 : REPARAMETERIZE_CHILD_PATH_LIST(cpath->custom_paths);
4157 0 : if (cpath->custom_restrictinfo)
4158 0 : ADJUST_CHILD_ATTRS(cpath->custom_restrictinfo);
4159 0 : if (cpath->methods &&
4160 0 : cpath->methods->ReparameterizeCustomPathByChild)
4161 0 : cpath->custom_private =
4162 0 : cpath->methods->ReparameterizeCustomPathByChild(root,
4163 : cpath->custom_private,
4164 : child_rel);
4165 0 : new_path = (Path *) cpath;
4166 : }
4167 0 : break;
4168 :
4169 36 : case T_NestPath:
4170 : {
4171 36 : NestPath *npath = (NestPath *) path;
4172 36 : JoinPath *jpath = (JoinPath *) npath;
4173 :
4174 36 : REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4175 36 : REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4176 36 : ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4177 36 : new_path = (Path *) npath;
4178 : }
4179 36 : break;
4180 :
4181 0 : case T_MergePath:
4182 : {
4183 0 : MergePath *mpath = (MergePath *) path;
4184 0 : JoinPath *jpath = (JoinPath *) mpath;
4185 :
4186 0 : REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4187 0 : REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4188 0 : ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4189 0 : ADJUST_CHILD_ATTRS(mpath->path_mergeclauses);
4190 0 : new_path = (Path *) mpath;
4191 : }
4192 0 : break;
4193 :
4194 48 : case T_HashPath:
4195 : {
4196 48 : HashPath *hpath = (HashPath *) path;
4197 48 : JoinPath *jpath = (JoinPath *) hpath;
4198 :
4199 48 : REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4200 48 : REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4201 48 : ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4202 48 : ADJUST_CHILD_ATTRS(hpath->path_hashclauses);
4203 48 : new_path = (Path *) hpath;
4204 : }
4205 48 : break;
4206 :
4207 24 : case T_AppendPath:
4208 : {
4209 24 : AppendPath *apath = (AppendPath *) path;
4210 :
4211 24 : REPARAMETERIZE_CHILD_PATH_LIST(apath->subpaths);
4212 24 : new_path = (Path *) apath;
4213 : }
4214 24 : break;
4215 :
4216 0 : case T_MaterialPath:
4217 : {
4218 0 : MaterialPath *mpath = (MaterialPath *) path;
4219 :
4220 0 : REPARAMETERIZE_CHILD_PATH(mpath->subpath);
4221 0 : new_path = (Path *) mpath;
4222 : }
4223 0 : break;
4224 :
4225 66 : case T_MemoizePath:
4226 : {
4227 66 : MemoizePath *mpath = (MemoizePath *) path;
4228 :
4229 66 : REPARAMETERIZE_CHILD_PATH(mpath->subpath);
4230 66 : ADJUST_CHILD_ATTRS(mpath->param_exprs);
4231 66 : new_path = (Path *) mpath;
4232 : }
4233 66 : break;
4234 :
4235 0 : case T_GatherPath:
4236 : {
4237 0 : GatherPath *gpath = (GatherPath *) path;
4238 :
4239 0 : REPARAMETERIZE_CHILD_PATH(gpath->subpath);
4240 0 : new_path = (Path *) gpath;
4241 : }
4242 0 : break;
4243 :
4244 0 : default:
4245 : /* We don't know how to reparameterize this path. */
4246 0 : 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 1026 : old_ppi = new_path->param_info;
4255 : required_outer =
4256 1026 : adjust_child_relids_multilevel(root, old_ppi->ppi_req_outer,
4257 : child_rel,
4258 1026 : child_rel->top_parent);
4259 :
4260 : /* If we already have a PPI for this parameterization, just return it */
4261 1026 : 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 1026 : if (new_ppi == NULL)
4269 : {
4270 : MemoryContext oldcontext;
4271 864 : RelOptInfo *rel = path->parent;
4272 :
4273 864 : oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
4274 :
4275 864 : new_ppi = makeNode(ParamPathInfo);
4276 864 : new_ppi->ppi_req_outer = bms_copy(required_outer);
4277 864 : new_ppi->ppi_rows = old_ppi->ppi_rows;
4278 864 : new_ppi->ppi_clauses = old_ppi->ppi_clauses;
4279 864 : ADJUST_CHILD_ATTRS(new_ppi->ppi_clauses);
4280 864 : new_ppi->ppi_serials = bms_copy(old_ppi->ppi_serials);
4281 864 : rel->ppilist = lappend(rel->ppilist, new_ppi);
4282 :
4283 864 : MemoryContextSwitchTo(oldcontext);
4284 : }
4285 1026 : bms_free(required_outer);
4286 :
4287 1026 : 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 1026 : if (bms_overlap(path->parent->lateral_relids,
4295 1026 : child_rel->top_parent_relids))
4296 : {
4297 480 : new_path->pathtarget = copy_pathtarget(new_path->pathtarget);
4298 480 : ADJUST_CHILD_ATTRS(new_path->pathtarget->exprs);
4299 : }
4300 :
4301 1026 : 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 : */
4315 : bool
4316 37224 : path_is_reparameterizable_by_child(Path *path, RelOptInfo *child_rel)
4317 : {
4318 : #define REJECT_IF_PATH_NOT_REPARAMETERIZABLE(path) \
4319 : do { \
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) \
4325 : do { \
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 37224 : if (!path->param_info ||
4335 36816 : !bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
4336 984 : 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 36240 : switch (nodeTag(path))
4343 : {
4344 24312 : case T_Path:
4345 : case T_IndexPath:
4346 24312 : break;
4347 :
4348 48 : case T_BitmapHeapPath:
4349 : {
4350 48 : BitmapHeapPath *bhpath = (BitmapHeapPath *) path;
4351 :
4352 48 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(bhpath->bitmapqual);
4353 : }
4354 48 : break;
4355 :
4356 24 : case T_BitmapAndPath:
4357 : {
4358 24 : BitmapAndPath *bapath = (BitmapAndPath *) path;
4359 :
4360 24 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(bapath->bitmapquals);
4361 : }
4362 24 : break;
4363 :
4364 24 : case T_BitmapOrPath:
4365 : {
4366 24 : BitmapOrPath *bopath = (BitmapOrPath *) path;
4367 :
4368 24 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(bopath->bitmapquals);
4369 : }
4370 24 : break;
4371 :
4372 148 : case T_ForeignPath:
4373 : {
4374 148 : ForeignPath *fpath = (ForeignPath *) path;
4375 :
4376 148 : if (fpath->fdw_outerpath)
4377 0 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(fpath->fdw_outerpath);
4378 : }
4379 148 : break;
4380 :
4381 0 : case T_CustomPath:
4382 : {
4383 0 : CustomPath *cpath = (CustomPath *) path;
4384 :
4385 0 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(cpath->custom_paths);
4386 : }
4387 0 : break;
4388 :
4389 1248 : case T_NestPath:
4390 : case T_MergePath:
4391 : case T_HashPath:
4392 : {
4393 1248 : JoinPath *jpath = (JoinPath *) path;
4394 :
4395 1248 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(jpath->outerjoinpath);
4396 1248 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(jpath->innerjoinpath);
4397 : }
4398 1248 : break;
4399 :
4400 192 : case T_AppendPath:
4401 : {
4402 192 : AppendPath *apath = (AppendPath *) path;
4403 :
4404 192 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(apath->subpaths);
4405 : }
4406 192 : break;
4407 :
4408 0 : case T_MaterialPath:
4409 : {
4410 0 : MaterialPath *mpath = (MaterialPath *) path;
4411 :
4412 0 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(mpath->subpath);
4413 : }
4414 0 : break;
4415 :
4416 10244 : case T_MemoizePath:
4417 : {
4418 10244 : MemoizePath *mpath = (MemoizePath *) path;
4419 :
4420 10244 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(mpath->subpath);
4421 : }
4422 10244 : break;
4423 :
4424 0 : case T_GatherPath:
4425 : {
4426 0 : GatherPath *gpath = (GatherPath *) path;
4427 :
4428 0 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(gpath->subpath);
4429 : }
4430 0 : break;
4431 :
4432 0 : default:
4433 : /* We don't know how to reparameterize this path. */
4434 0 : return false;
4435 : }
4436 :
4437 36240 : 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 : */
4446 : static List *
4447 72 : reparameterize_pathlist_by_child(PlannerInfo *root,
4448 : List *pathlist,
4449 : RelOptInfo *child_rel)
4450 : {
4451 : ListCell *lc;
4452 72 : List *result = NIL;
4453 :
4454 216 : foreach(lc, pathlist)
4455 : {
4456 144 : Path *path = reparameterize_path_by_child(root, lfirst(lc),
4457 : child_rel);
4458 :
4459 144 : if (path == NULL)
4460 : {
4461 0 : list_free(result);
4462 0 : return NIL;
4463 : }
4464 :
4465 144 : result = lappend(result, path);
4466 : }
4467 :
4468 72 : 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 : */
4475 : static bool
4476 240 : pathlist_is_reparameterizable_by_child(List *pathlist, RelOptInfo *child_rel)
4477 : {
4478 : ListCell *lc;
4479 :
4480 720 : foreach(lc, pathlist)
4481 : {
4482 480 : Path *path = (Path *) lfirst(lc);
4483 :
4484 480 : if (!path_is_reparameterizable_by_child(path, child_rel))
4485 0 : return false;
4486 : }
4487 :
4488 240 : return true;
4489 : }
|