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