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