Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * pathnode.c
4 : * Routines to manipulate pathlists and create path nodes
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/optimizer/util/pathnode.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : #include "postgres.h"
16 :
17 : #include <math.h>
18 :
19 : #include "access/htup_details.h"
20 : #include "executor/nodeSetOp.h"
21 : #include "foreign/fdwapi.h"
22 : #include "miscadmin.h"
23 : #include "nodes/extensible.h"
24 : #include "optimizer/appendinfo.h"
25 : #include "optimizer/clauses.h"
26 : #include "optimizer/cost.h"
27 : #include "optimizer/optimizer.h"
28 : #include "optimizer/pathnode.h"
29 : #include "optimizer/paths.h"
30 : #include "optimizer/planmain.h"
31 : #include "optimizer/tlist.h"
32 : #include "parser/parsetree.h"
33 : #include "utils/memutils.h"
34 : #include "utils/selfuncs.h"
35 :
36 : typedef enum
37 : {
38 : COSTS_EQUAL, /* path costs are fuzzily equal */
39 : COSTS_BETTER1, /* first path is cheaper than second */
40 : COSTS_BETTER2, /* second path is cheaper than first */
41 : COSTS_DIFFERENT, /* neither path dominates the other on cost */
42 : } PathCostComparison;
43 :
44 : /*
45 : * STD_FUZZ_FACTOR is the normal fuzz factor for compare_path_costs_fuzzily.
46 : * XXX is it worth making this user-controllable? It provides a tradeoff
47 : * between planner runtime and the accuracy of path cost comparisons.
48 : */
49 : #define STD_FUZZ_FACTOR 1.01
50 :
51 : static int append_total_cost_compare(const ListCell *a, const ListCell *b);
52 : static int append_startup_cost_compare(const ListCell *a, const ListCell *b);
53 : static List *reparameterize_pathlist_by_child(PlannerInfo *root,
54 : List *pathlist,
55 : RelOptInfo *child_rel);
56 : static bool pathlist_is_reparameterizable_by_child(List *pathlist,
57 : RelOptInfo *child_rel);
58 :
59 :
60 : /*****************************************************************************
61 : * MISC. PATH UTILITIES
62 : *****************************************************************************/
63 :
64 : /*
65 : * compare_path_costs
66 : * Return -1, 0, or +1 according as path1 is cheaper, the same cost,
67 : * or more expensive than path2 for the specified criterion.
68 : */
69 : int
70 1120536 : compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
71 : {
72 : /* Number of disabled nodes, if different, trumps all else. */
73 1120536 : if (unlikely(path1->disabled_nodes != path2->disabled_nodes))
74 : {
75 2712 : if (path1->disabled_nodes < path2->disabled_nodes)
76 2712 : return -1;
77 : else
78 0 : return +1;
79 : }
80 :
81 1117824 : if (criterion == STARTUP_COST)
82 : {
83 562854 : if (path1->startup_cost < path2->startup_cost)
84 343288 : return -1;
85 219566 : if (path1->startup_cost > path2->startup_cost)
86 112884 : return +1;
87 :
88 : /*
89 : * If paths have the same startup cost (not at all unlikely), order
90 : * them by total cost.
91 : */
92 106682 : if (path1->total_cost < path2->total_cost)
93 55008 : return -1;
94 51674 : if (path1->total_cost > path2->total_cost)
95 5114 : return +1;
96 : }
97 : else
98 : {
99 554970 : if (path1->total_cost < path2->total_cost)
100 518204 : return -1;
101 36766 : if (path1->total_cost > path2->total_cost)
102 10708 : return +1;
103 :
104 : /*
105 : * If paths have the same total cost, order them by startup cost.
106 : */
107 26058 : if (path1->startup_cost < path2->startup_cost)
108 2594 : return -1;
109 23464 : if (path1->startup_cost > path2->startup_cost)
110 30 : return +1;
111 : }
112 69994 : return 0;
113 : }
114 :
115 : /*
116 : * compare_fractional_path_costs
117 : * Return -1, 0, or +1 according as path1 is cheaper, the same cost,
118 : * or more expensive than path2 for fetching the specified fraction
119 : * of the total tuples.
120 : *
121 : * If fraction is <= 0 or > 1, we interpret it as 1, ie, we select the
122 : * path with the cheaper total_cost.
123 : */
124 : int
125 6334 : compare_fractional_path_costs(Path *path1, Path *path2,
126 : double fraction)
127 : {
128 : Cost cost1,
129 : cost2;
130 :
131 : /* Number of disabled nodes, if different, trumps all else. */
132 6334 : if (unlikely(path1->disabled_nodes != path2->disabled_nodes))
133 : {
134 36 : if (path1->disabled_nodes < path2->disabled_nodes)
135 36 : return -1;
136 : else
137 0 : return +1;
138 : }
139 :
140 6298 : if (fraction <= 0.0 || fraction >= 1.0)
141 1962 : return compare_path_costs(path1, path2, TOTAL_COST);
142 4336 : cost1 = path1->startup_cost +
143 4336 : fraction * (path1->total_cost - path1->startup_cost);
144 4336 : cost2 = path2->startup_cost +
145 4336 : fraction * (path2->total_cost - path2->startup_cost);
146 4336 : if (cost1 < cost2)
147 3586 : return -1;
148 750 : if (cost1 > cost2)
149 750 : return +1;
150 0 : return 0;
151 : }
152 :
153 : /*
154 : * compare_path_costs_fuzzily
155 : * Compare the costs of two paths to see if either can be said to
156 : * dominate the other.
157 : *
158 : * We use fuzzy comparisons so that add_path() can avoid keeping both of
159 : * a pair of paths that really have insignificantly different cost.
160 : *
161 : * The fuzz_factor argument must be 1.0 plus delta, where delta is the
162 : * fraction of the smaller cost that is considered to be a significant
163 : * difference. For example, fuzz_factor = 1.01 makes the fuzziness limit
164 : * be 1% of the smaller cost.
165 : *
166 : * The two paths are said to have "equal" costs if both startup and total
167 : * costs are fuzzily the same. Path1 is said to be better than path2 if
168 : * it has fuzzily better startup cost and fuzzily no worse total cost,
169 : * or if it has fuzzily better total cost and fuzzily no worse startup cost.
170 : * Path2 is better than path1 if the reverse holds. Finally, if one path
171 : * is fuzzily better than the other on startup cost and fuzzily worse on
172 : * total cost, we just say that their costs are "different", since neither
173 : * dominates the other across the whole performance spectrum.
174 : *
175 : * This function also enforces a policy rule that paths for which the relevant
176 : * one of parent->consider_startup and parent->consider_param_startup is false
177 : * cannot survive comparisons solely on the grounds of good startup cost, so
178 : * we never return COSTS_DIFFERENT when that is true for the total-cost loser.
179 : * (But if total costs are fuzzily equal, we compare startup costs anyway,
180 : * in hopes of eliminating one path or the other.)
181 : */
182 : static PathCostComparison
183 4609090 : compare_path_costs_fuzzily(Path *path1, Path *path2, double fuzz_factor)
184 : {
185 : #define CONSIDER_PATH_STARTUP_COST(p) \
186 : ((p)->param_info == NULL ? (p)->parent->consider_startup : (p)->parent->consider_param_startup)
187 :
188 : /* Number of disabled nodes, if different, trumps all else. */
189 4609090 : if (unlikely(path1->disabled_nodes != path2->disabled_nodes))
190 : {
191 31104 : if (path1->disabled_nodes < path2->disabled_nodes)
192 16900 : return COSTS_BETTER1;
193 : else
194 14204 : return COSTS_BETTER2;
195 : }
196 :
197 : /*
198 : * Check total cost first since it's more likely to be different; many
199 : * paths have zero startup cost.
200 : */
201 4577986 : if (path1->total_cost > path2->total_cost * fuzz_factor)
202 : {
203 : /* path1 fuzzily worse on total cost */
204 2399304 : if (CONSIDER_PATH_STARTUP_COST(path1) &&
205 137478 : path2->startup_cost > path1->startup_cost * fuzz_factor)
206 : {
207 : /* ... but path2 fuzzily worse on startup, so DIFFERENT */
208 92784 : return COSTS_DIFFERENT;
209 : }
210 : /* else path2 dominates */
211 2306520 : return COSTS_BETTER2;
212 : }
213 2178682 : if (path2->total_cost > path1->total_cost * fuzz_factor)
214 : {
215 : /* path2 fuzzily worse on total cost */
216 1142848 : if (CONSIDER_PATH_STARTUP_COST(path2) &&
217 61352 : path1->startup_cost > path2->startup_cost * fuzz_factor)
218 : {
219 : /* ... but path1 fuzzily worse on startup, so DIFFERENT */
220 40712 : return COSTS_DIFFERENT;
221 : }
222 : /* else path1 dominates */
223 1102136 : return COSTS_BETTER1;
224 : }
225 : /* fuzzily the same on total cost ... */
226 1035834 : if (path1->startup_cost > path2->startup_cost * fuzz_factor)
227 : {
228 : /* ... but path1 fuzzily worse on startup, so path2 wins */
229 376852 : return COSTS_BETTER2;
230 : }
231 658982 : if (path2->startup_cost > path1->startup_cost * fuzz_factor)
232 : {
233 : /* ... but path2 fuzzily worse on startup, so path1 wins */
234 65720 : return COSTS_BETTER1;
235 : }
236 : /* fuzzily the same on both costs */
237 593262 : return COSTS_EQUAL;
238 :
239 : #undef CONSIDER_PATH_STARTUP_COST
240 : }
241 :
242 : /*
243 : * set_cheapest
244 : * Find the minimum-cost paths from among a relation's paths,
245 : * and save them in the rel's cheapest-path fields.
246 : *
247 : * cheapest_total_path is normally the cheapest-total-cost unparameterized
248 : * path; but if there are no unparameterized paths, we assign it to be the
249 : * best (cheapest least-parameterized) parameterized path. However, only
250 : * unparameterized paths are considered candidates for cheapest_startup_path,
251 : * so that will be NULL if there are no unparameterized paths.
252 : *
253 : * The cheapest_parameterized_paths list collects all parameterized paths
254 : * that have survived the add_path() tournament for this relation. (Since
255 : * add_path ignores pathkeys for a parameterized path, these will be paths
256 : * that have best cost or best row count for their parameterization. We
257 : * may also have both a parallel-safe and a non-parallel-safe path in some
258 : * cases for the same parameterization in some cases, but this should be
259 : * relatively rare since, most typically, all paths for the same relation
260 : * will be parallel-safe or none of them will.)
261 : *
262 : * cheapest_parameterized_paths always includes the cheapest-total
263 : * unparameterized path, too, if there is one; the users of that list find
264 : * it more convenient if that's included.
265 : *
266 : * This is normally called only after we've finished constructing the path
267 : * list for the rel node.
268 : */
269 : void
270 2093516 : set_cheapest(RelOptInfo *parent_rel)
271 : {
272 : Path *cheapest_startup_path;
273 : Path *cheapest_total_path;
274 : Path *best_param_path;
275 : List *parameterized_paths;
276 : ListCell *p;
277 :
278 : Assert(IsA(parent_rel, RelOptInfo));
279 :
280 2093516 : if (parent_rel->pathlist == NIL)
281 0 : elog(ERROR, "could not devise a query plan for the given query");
282 :
283 2093516 : cheapest_startup_path = cheapest_total_path = best_param_path = NULL;
284 2093516 : parameterized_paths = NIL;
285 :
286 4761214 : foreach(p, parent_rel->pathlist)
287 : {
288 2667698 : Path *path = (Path *) lfirst(p);
289 : int cmp;
290 :
291 2667698 : if (path->param_info)
292 : {
293 : /* Parameterized path, so add it to parameterized_paths */
294 142420 : parameterized_paths = lappend(parameterized_paths, path);
295 :
296 : /*
297 : * If we have an unparameterized cheapest-total, we no longer care
298 : * about finding the best parameterized path, so move on.
299 : */
300 142420 : if (cheapest_total_path)
301 29918 : continue;
302 :
303 : /*
304 : * Otherwise, track the best parameterized path, which is the one
305 : * with least total cost among those of the minimum
306 : * parameterization.
307 : */
308 112502 : if (best_param_path == NULL)
309 102616 : best_param_path = path;
310 : else
311 : {
312 9886 : switch (bms_subset_compare(PATH_REQ_OUTER(path),
313 9886 : PATH_REQ_OUTER(best_param_path)))
314 : {
315 60 : case BMS_EQUAL:
316 : /* keep the cheaper one */
317 60 : if (compare_path_costs(path, best_param_path,
318 : TOTAL_COST) < 0)
319 0 : best_param_path = path;
320 60 : break;
321 768 : case BMS_SUBSET1:
322 : /* new path is less-parameterized */
323 768 : best_param_path = path;
324 768 : break;
325 6 : case BMS_SUBSET2:
326 : /* old path is less-parameterized, keep it */
327 6 : break;
328 9052 : case BMS_DIFFERENT:
329 :
330 : /*
331 : * This means that neither path has the least possible
332 : * parameterization for the rel. We'll sit on the old
333 : * path until something better comes along.
334 : */
335 9052 : break;
336 : }
337 : }
338 : }
339 : else
340 : {
341 : /* Unparameterized path, so consider it for cheapest slots */
342 2525278 : if (cheapest_total_path == NULL)
343 : {
344 2080798 : cheapest_startup_path = cheapest_total_path = path;
345 2080798 : continue;
346 : }
347 :
348 : /*
349 : * If we find two paths of identical costs, try to keep the
350 : * better-sorted one. The paths might have unrelated sort
351 : * orderings, in which case we can only guess which might be
352 : * better to keep, but if one is superior then we definitely
353 : * should keep that one.
354 : */
355 444480 : cmp = compare_path_costs(cheapest_startup_path, path, STARTUP_COST);
356 444480 : if (cmp > 0 ||
357 384 : (cmp == 0 &&
358 384 : compare_pathkeys(cheapest_startup_path->pathkeys,
359 : path->pathkeys) == PATHKEYS_BETTER2))
360 83058 : cheapest_startup_path = path;
361 :
362 444480 : cmp = compare_path_costs(cheapest_total_path, path, TOTAL_COST);
363 444480 : if (cmp > 0 ||
364 48 : (cmp == 0 &&
365 48 : compare_pathkeys(cheapest_total_path->pathkeys,
366 : path->pathkeys) == PATHKEYS_BETTER2))
367 0 : cheapest_total_path = path;
368 : }
369 : }
370 :
371 : /* Add cheapest unparameterized path, if any, to parameterized_paths */
372 2093516 : if (cheapest_total_path)
373 2080798 : parameterized_paths = lcons(cheapest_total_path, parameterized_paths);
374 :
375 : /*
376 : * If there is no unparameterized path, use the best parameterized path as
377 : * cheapest_total_path (but not as cheapest_startup_path).
378 : */
379 2093516 : if (cheapest_total_path == NULL)
380 12718 : cheapest_total_path = best_param_path;
381 : Assert(cheapest_total_path != NULL);
382 :
383 2093516 : parent_rel->cheapest_startup_path = cheapest_startup_path;
384 2093516 : parent_rel->cheapest_total_path = cheapest_total_path;
385 2093516 : parent_rel->cheapest_parameterized_paths = parameterized_paths;
386 2093516 : }
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 4593618 : add_path(RelOptInfo *parent_rel, Path *new_path)
462 : {
463 4593618 : bool accept_new = true; /* unless we find a superior old path */
464 4593618 : 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 4593618 : CHECK_FOR_INTERRUPTS();
473 :
474 : /* Pretend parameterized paths have no pathkeys, per comment above */
475 4593618 : 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 7114032 : foreach(p1, parent_rel->pathlist)
483 : {
484 4240842 : Path *old_path = (Path *) lfirst(p1);
485 4240842 : 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 4240842 : 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 4240842 : if (costcmp != COSTS_DIFFERENT)
508 : {
509 : /* Similarly check to see if either dominates on pathkeys */
510 : List *old_path_pathkeys;
511 :
512 4107412 : old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
513 4107412 : keyscmp = compare_pathkeys(new_path_pathkeys,
514 : old_path_pathkeys);
515 4107412 : if (keyscmp != PATHKEYS_DIFFERENT)
516 : {
517 3920374 : switch (costcmp)
518 : {
519 400932 : case COSTS_EQUAL:
520 400932 : outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
521 400932 : PATH_REQ_OUTER(old_path));
522 400932 : if (keyscmp == PATHKEYS_BETTER1)
523 : {
524 6988 : if ((outercmp == BMS_EQUAL ||
525 6988 : outercmp == BMS_SUBSET1) &&
526 6988 : new_path->rows <= old_path->rows &&
527 6980 : new_path->parallel_safe >= old_path->parallel_safe)
528 6980 : remove_old = true; /* new dominates old */
529 : }
530 393944 : else if (keyscmp == PATHKEYS_BETTER2)
531 : {
532 19992 : if ((outercmp == BMS_EQUAL ||
533 19992 : outercmp == BMS_SUBSET2) &&
534 19992 : new_path->rows >= old_path->rows &&
535 19988 : new_path->parallel_safe <= old_path->parallel_safe)
536 19988 : accept_new = false; /* old dominates new */
537 : }
538 : else /* keyscmp == PATHKEYS_EQUAL */
539 : {
540 373952 : 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 368534 : if (new_path->parallel_safe >
558 368534 : old_path->parallel_safe)
559 42 : remove_old = true; /* new dominates old */
560 368492 : else if (new_path->parallel_safe <
561 368492 : old_path->parallel_safe)
562 54 : accept_new = false; /* old dominates new */
563 368438 : else if (new_path->rows < old_path->rows)
564 0 : remove_old = true; /* new dominates old */
565 368438 : else if (new_path->rows > old_path->rows)
566 190 : accept_new = false; /* old dominates new */
567 368248 : else if (compare_path_costs_fuzzily(new_path,
568 : old_path,
569 : 1.0000000001) == COSTS_BETTER1)
570 16338 : remove_old = true; /* new dominates old */
571 : else
572 351910 : accept_new = false; /* old equals or
573 : * dominates new */
574 : }
575 5418 : else if (outercmp == BMS_SUBSET1 &&
576 1194 : new_path->rows <= old_path->rows &&
577 1174 : new_path->parallel_safe >= old_path->parallel_safe)
578 1174 : remove_old = true; /* new dominates old */
579 4244 : else if (outercmp == BMS_SUBSET2 &&
580 3522 : new_path->rows >= old_path->rows &&
581 3486 : new_path->parallel_safe <= old_path->parallel_safe)
582 3486 : accept_new = false; /* old dominates new */
583 : /* else different parameterizations, keep both */
584 : }
585 400932 : break;
586 1141198 : case COSTS_BETTER1:
587 1141198 : if (keyscmp != PATHKEYS_BETTER2)
588 : {
589 774006 : outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
590 774006 : PATH_REQ_OUTER(old_path));
591 774006 : if ((outercmp == BMS_EQUAL ||
592 661914 : outercmp == BMS_SUBSET1) &&
593 661914 : new_path->rows <= old_path->rows &&
594 656298 : new_path->parallel_safe >= old_path->parallel_safe)
595 653712 : remove_old = true; /* new dominates old */
596 : }
597 1141198 : break;
598 2378244 : case COSTS_BETTER2:
599 2378244 : if (keyscmp != PATHKEYS_BETTER1)
600 : {
601 1512064 : outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
602 1512064 : PATH_REQ_OUTER(old_path));
603 1512064 : if ((outercmp == BMS_EQUAL ||
604 1424190 : outercmp == BMS_SUBSET2) &&
605 1424190 : new_path->rows >= old_path->rows &&
606 1346526 : new_path->parallel_safe <= old_path->parallel_safe)
607 1344800 : accept_new = false; /* old dominates new */
608 : }
609 2378244 : 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 4240842 : if (remove_old)
625 : {
626 678246 : 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 678246 : if (!IsA(old_path, IndexPath))
633 658594 : 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 3562596 : if (new_path->disabled_nodes > old_path->disabled_nodes ||
642 3548392 : (new_path->disabled_nodes == old_path->disabled_nodes &&
643 3547426 : new_path->total_cost >= old_path->total_cost))
644 2953438 : 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 4240842 : if (!accept_new)
653 1720428 : break;
654 : }
655 :
656 4593618 : if (accept_new)
657 : {
658 : /* Accept the new path: insert it at proper place in pathlist */
659 2873190 : parent_rel->pathlist =
660 2873190 : list_insert_nth(parent_rel->pathlist, insert_at, new_path);
661 : }
662 : else
663 : {
664 : /* Reject and recycle the new path */
665 1720428 : if (!IsA(new_path, IndexPath))
666 1618222 : pfree(new_path);
667 : }
668 4593618 : }
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 5260226 : 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 5260226 : new_path_pathkeys = required_outer ? NIL : pathkeys;
698 :
699 : /* Decide whether new path's startup cost is interesting */
700 5260226 : consider_startup = required_outer ? parent_rel->consider_param_startup : parent_rel->consider_startup;
701 :
702 6733608 : foreach(p1, parent_rel->pathlist)
703 : {
704 6388956 : 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 6388956 : if (unlikely(old_path->disabled_nodes != disabled_nodes))
714 : {
715 12966 : if (disabled_nodes < old_path->disabled_nodes)
716 318 : break;
717 : }
718 6375990 : else if (total_cost <= old_path->total_cost * STD_FUZZ_FACTOR)
719 1908670 : 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 4479968 : if (startup_cost > old_path->startup_cost * STD_FUZZ_FACTOR ||
731 2108632 : !consider_startup)
732 : {
733 : /* new path loses on cost, so check pathkeys... */
734 : List *old_path_pathkeys;
735 :
736 4376566 : old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
737 4376566 : keyscmp = compare_pathkeys(new_path_pathkeys,
738 : old_path_pathkeys);
739 4376566 : if (keyscmp == PATHKEYS_EQUAL ||
740 : keyscmp == PATHKEYS_BETTER2)
741 : {
742 : /* new path does not win on pathkeys... */
743 3072880 : if (bms_equal(required_outer, PATH_REQ_OUTER(old_path)))
744 : {
745 : /* Found an old path that dominates the new one */
746 3006586 : return false;
747 : }
748 : }
749 : }
750 : }
751 :
752 2253640 : 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 307306 : add_partial_path(RelOptInfo *parent_rel, Path *new_path)
796 : {
797 307306 : bool accept_new = true; /* unless we find a superior old path */
798 307306 : int insert_at = 0; /* where to insert new item */
799 : ListCell *p1;
800 :
801 : /* Check for query cancel. */
802 307306 : 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 428252 : foreach(p1, parent_rel->partial_pathlist)
815 : {
816 252186 : Path *old_path = (Path *) lfirst(p1);
817 252186 : bool remove_old = false; /* unless new proves superior */
818 : PathKeysComparison keyscmp;
819 :
820 : /* Compare pathkeys. */
821 252186 : keyscmp = compare_pathkeys(new_path->pathkeys, old_path->pathkeys);
822 :
823 : /* Unless pathkeys are incompatible, keep just one of the two paths. */
824 252186 : if (keyscmp != PATHKEYS_DIFFERENT)
825 : {
826 251976 : 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 250492 : else if (new_path->total_cost > old_path->total_cost
834 250492 : * STD_FUZZ_FACTOR)
835 : {
836 : /* New path costs more; keep it only if pathkeys are better. */
837 123394 : if (keyscmp != PATHKEYS_BETTER1)
838 89314 : accept_new = false;
839 : }
840 127098 : else if (old_path->total_cost > new_path->total_cost
841 127098 : * STD_FUZZ_FACTOR)
842 : {
843 : /* Old path costs more; keep it only if pathkeys are better. */
844 85490 : if (keyscmp != PATHKEYS_BETTER2)
845 30120 : remove_old = true;
846 : }
847 41608 : else if (keyscmp == PATHKEYS_BETTER1)
848 : {
849 : /* Costs are about the same, new path has better pathkeys. */
850 24 : remove_old = true;
851 : }
852 41584 : else if (keyscmp == PATHKEYS_BETTER2)
853 : {
854 : /* Costs are about the same, old path has better pathkeys. */
855 2034 : accept_new = false;
856 : }
857 39550 : 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 614 : remove_old = true;
861 : }
862 : else
863 : {
864 : /*
865 : * Pathkeys are the same, and new path isn't materially
866 : * cheaper.
867 : */
868 38936 : accept_new = false;
869 : }
870 : }
871 :
872 : /*
873 : * Remove current element from partial_pathlist if dominated by new.
874 : */
875 252186 : if (remove_old)
876 : {
877 31286 : parent_rel->partial_pathlist =
878 31286 : foreach_delete_current(parent_rel->partial_pathlist, p1);
879 31286 : pfree(old_path);
880 : }
881 : else
882 : {
883 : /* new belongs after this old path if it has cost >= old's */
884 220900 : if (new_path->total_cost >= old_path->total_cost)
885 164358 : 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 252186 : if (!accept_new)
894 131240 : break;
895 : }
896 :
897 307306 : if (accept_new)
898 : {
899 : /* Accept the new path: insert it at proper place */
900 176066 : parent_rel->partial_pathlist =
901 176066 : list_insert_nth(parent_rel->partial_pathlist, insert_at, new_path);
902 : }
903 : else
904 : {
905 : /* Reject and recycle the new path */
906 131240 : pfree(new_path);
907 : }
908 307306 : }
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 449104 : 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 573278 : foreach(p1, parent_rel->partial_pathlist)
938 : {
939 466844 : Path *old_path = (Path *) lfirst(p1);
940 : PathKeysComparison keyscmp;
941 :
942 466844 : keyscmp = compare_pathkeys(pathkeys, old_path->pathkeys);
943 466844 : if (keyscmp != PATHKEYS_DIFFERENT)
944 : {
945 466652 : if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR &&
946 : keyscmp != PATHKEYS_BETTER1)
947 342670 : return false;
948 237234 : if (old_path->total_cost > total_cost * STD_FUZZ_FACTOR &&
949 : keyscmp != PATHKEYS_BETTER2)
950 113252 : 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 106434 : if (!add_path_precheck(parent_rel, disabled_nodes, total_cost, total_cost,
966 : pathkeys, NULL))
967 2734 : return false;
968 :
969 103700 : 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 432608 : create_seqscan_path(PlannerInfo *root, RelOptInfo *rel,
984 : Relids required_outer, int parallel_workers)
985 : {
986 432608 : Path *pathnode = makeNode(Path);
987 :
988 432608 : pathnode->pathtype = T_SeqScan;
989 432608 : pathnode->parent = rel;
990 432608 : pathnode->pathtarget = rel->reltarget;
991 432608 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
992 : required_outer);
993 432608 : pathnode->parallel_aware = (parallel_workers > 0);
994 432608 : pathnode->parallel_safe = rel->consider_parallel;
995 432608 : pathnode->parallel_workers = parallel_workers;
996 432608 : pathnode->pathkeys = NIL; /* seqscan has unordered result */
997 :
998 432608 : cost_seqscan(pathnode, root, rel, pathnode->param_info);
999 :
1000 432608 : 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 801052 : 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 801052 : IndexPath *pathnode = makeNode(IndexPath);
1062 801052 : RelOptInfo *rel = index->rel;
1063 :
1064 801052 : pathnode->path.pathtype = indexonly ? T_IndexOnlyScan : T_IndexScan;
1065 801052 : pathnode->path.parent = rel;
1066 801052 : pathnode->path.pathtarget = rel->reltarget;
1067 801052 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1068 : required_outer);
1069 801052 : pathnode->path.parallel_aware = false;
1070 801052 : pathnode->path.parallel_safe = rel->consider_parallel;
1071 801052 : pathnode->path.parallel_workers = 0;
1072 801052 : pathnode->path.pathkeys = pathkeys;
1073 :
1074 801052 : pathnode->indexinfo = index;
1075 801052 : pathnode->indexclauses = indexclauses;
1076 801052 : pathnode->indexorderbys = indexorderbys;
1077 801052 : pathnode->indexorderbycols = indexorderbycols;
1078 801052 : pathnode->indexscandir = indexscandir;
1079 :
1080 801052 : cost_index(pathnode, root, loop_count, partial_path);
1081 :
1082 801052 : 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 350356 : 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 350356 : BitmapHeapPath *pathnode = makeNode(BitmapHeapPath);
1106 :
1107 350356 : pathnode->path.pathtype = T_BitmapHeapScan;
1108 350356 : pathnode->path.parent = rel;
1109 350356 : pathnode->path.pathtarget = rel->reltarget;
1110 350356 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1111 : required_outer);
1112 350356 : pathnode->path.parallel_aware = (parallel_degree > 0);
1113 350356 : pathnode->path.parallel_safe = rel->consider_parallel;
1114 350356 : pathnode->path.parallel_workers = parallel_degree;
1115 350356 : pathnode->path.pathkeys = NIL; /* always unordered */
1116 :
1117 350356 : pathnode->bitmapqual = bitmapqual;
1118 :
1119 350356 : cost_bitmap_heap_scan(&pathnode->path, root, rel,
1120 : pathnode->path.param_info,
1121 : bitmapqual, loop_count);
1122 :
1123 350356 : return pathnode;
1124 : }
1125 :
1126 : /*
1127 : * create_bitmap_and_path
1128 : * Creates a path node representing a BitmapAnd.
1129 : */
1130 : BitmapAndPath *
1131 49644 : create_bitmap_and_path(PlannerInfo *root,
1132 : RelOptInfo *rel,
1133 : List *bitmapquals)
1134 : {
1135 49644 : BitmapAndPath *pathnode = makeNode(BitmapAndPath);
1136 49644 : Relids required_outer = NULL;
1137 : ListCell *lc;
1138 :
1139 49644 : pathnode->path.pathtype = T_BitmapAnd;
1140 49644 : pathnode->path.parent = rel;
1141 49644 : 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 148932 : foreach(lc, bitmapquals)
1149 : {
1150 99288 : Path *bitmapqual = (Path *) lfirst(lc);
1151 :
1152 99288 : required_outer = bms_add_members(required_outer,
1153 99288 : PATH_REQ_OUTER(bitmapqual));
1154 : }
1155 49644 : 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 49644 : pathnode->path.parallel_aware = false;
1165 49644 : pathnode->path.parallel_safe = rel->consider_parallel;
1166 49644 : pathnode->path.parallel_workers = 0;
1167 :
1168 49644 : pathnode->path.pathkeys = NIL; /* always unordered */
1169 :
1170 49644 : pathnode->bitmapquals = bitmapquals;
1171 :
1172 : /* this sets bitmapselectivity as well as the regular cost fields: */
1173 49644 : cost_bitmap_and_node(pathnode, root);
1174 :
1175 49644 : return pathnode;
1176 : }
1177 :
1178 : /*
1179 : * create_bitmap_or_path
1180 : * Creates a path node representing a BitmapOr.
1181 : */
1182 : BitmapOrPath *
1183 1016 : create_bitmap_or_path(PlannerInfo *root,
1184 : RelOptInfo *rel,
1185 : List *bitmapquals)
1186 : {
1187 1016 : BitmapOrPath *pathnode = makeNode(BitmapOrPath);
1188 1016 : Relids required_outer = NULL;
1189 : ListCell *lc;
1190 :
1191 1016 : pathnode->path.pathtype = T_BitmapOr;
1192 1016 : pathnode->path.parent = rel;
1193 1016 : 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 2850 : foreach(lc, bitmapquals)
1201 : {
1202 1834 : Path *bitmapqual = (Path *) lfirst(lc);
1203 :
1204 1834 : required_outer = bms_add_members(required_outer,
1205 1834 : PATH_REQ_OUTER(bitmapqual));
1206 : }
1207 1016 : 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 1016 : pathnode->path.parallel_aware = false;
1217 1016 : pathnode->path.parallel_safe = rel->consider_parallel;
1218 1016 : pathnode->path.parallel_workers = 0;
1219 :
1220 1016 : pathnode->path.pathkeys = NIL; /* always unordered */
1221 :
1222 1016 : pathnode->bitmapquals = bitmapquals;
1223 :
1224 : /* this sets bitmapselectivity as well as the regular cost fields: */
1225 1016 : cost_bitmap_or_node(pathnode, root);
1226 :
1227 1016 : 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 872 : create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals,
1236 : Relids required_outer)
1237 : {
1238 872 : TidPath *pathnode = makeNode(TidPath);
1239 :
1240 872 : pathnode->path.pathtype = T_TidScan;
1241 872 : pathnode->path.parent = rel;
1242 872 : pathnode->path.pathtarget = rel->reltarget;
1243 872 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1244 : required_outer);
1245 872 : pathnode->path.parallel_aware = false;
1246 872 : pathnode->path.parallel_safe = rel->consider_parallel;
1247 872 : pathnode->path.parallel_workers = 0;
1248 872 : pathnode->path.pathkeys = NIL; /* always unordered */
1249 :
1250 872 : pathnode->tidquals = tidquals;
1251 :
1252 872 : cost_tidscan(&pathnode->path, root, rel, tidquals,
1253 : pathnode->path.param_info);
1254 :
1255 872 : 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 1944 : create_tidrangescan_path(PlannerInfo *root, RelOptInfo *rel,
1265 : List *tidrangequals, Relids required_outer)
1266 : {
1267 1944 : TidRangePath *pathnode = makeNode(TidRangePath);
1268 :
1269 1944 : pathnode->path.pathtype = T_TidRangeScan;
1270 1944 : pathnode->path.parent = rel;
1271 1944 : pathnode->path.pathtarget = rel->reltarget;
1272 1944 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1273 : required_outer);
1274 1944 : pathnode->path.parallel_aware = false;
1275 1944 : pathnode->path.parallel_safe = rel->consider_parallel;
1276 1944 : pathnode->path.parallel_workers = 0;
1277 1944 : pathnode->path.pathkeys = NIL; /* always unordered */
1278 :
1279 1944 : pathnode->tidrangequals = tidrangequals;
1280 :
1281 1944 : cost_tidrangescan(&pathnode->path, root, rel, tidrangequals,
1282 : pathnode->path.param_info);
1283 :
1284 1944 : 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 91696 : 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 91696 : AppendPath *pathnode = makeNode(AppendPath);
1308 : ListCell *l;
1309 :
1310 : Assert(!parallel_aware || parallel_workers > 0);
1311 :
1312 91696 : pathnode->path.pathtype = T_Append;
1313 91696 : pathnode->path.parent = rel;
1314 91696 : 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 91696 : if (rel->reloptkind == RELOPT_BASEREL && root && subpaths != NIL)
1328 40006 : pathnode->path.param_info = get_baserel_parampathinfo(root,
1329 : rel,
1330 : required_outer);
1331 : else
1332 51690 : pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1333 : required_outer);
1334 :
1335 91696 : pathnode->path.parallel_aware = parallel_aware;
1336 91696 : pathnode->path.parallel_safe = rel->consider_parallel;
1337 91696 : pathnode->path.parallel_workers = parallel_workers;
1338 91696 : 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 91696 : 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 33018 : list_sort(subpaths, append_total_cost_compare);
1359 33018 : list_sort(partial_subpaths, append_startup_cost_compare);
1360 : }
1361 91696 : pathnode->first_partial_path = list_length(subpaths);
1362 91696 : 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 91696 : if (root != NULL && bms_equal(rel->relids, root->all_query_rels))
1369 46278 : pathnode->limit_tuples = root->limit_tuples;
1370 : else
1371 45418 : pathnode->limit_tuples = -1.0;
1372 :
1373 311462 : foreach(l, pathnode->subpaths)
1374 : {
1375 219766 : Path *subpath = (Path *) lfirst(l);
1376 :
1377 399486 : pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1378 179720 : 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 91696 : if (list_length(pathnode->subpaths) == 1)
1397 : {
1398 22492 : Path *child = (Path *) linitial(pathnode->subpaths);
1399 :
1400 22492 : if (child->parallel_aware == parallel_aware)
1401 : {
1402 22054 : pathnode->path.rows = child->rows;
1403 22054 : pathnode->path.startup_cost = child->startup_cost;
1404 22054 : 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 22492 : pathnode->path.pathkeys = child->pathkeys;
1410 : }
1411 : else
1412 69204 : cost_append(pathnode, root);
1413 :
1414 : /* If the caller provided a row estimate, override the computed value. */
1415 91696 : if (rows >= 0)
1416 576 : pathnode->path.rows = rows;
1417 :
1418 91696 : 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 21796 : append_total_cost_compare(const ListCell *a, const ListCell *b)
1432 : {
1433 21796 : Path *path1 = (Path *) lfirst(a);
1434 21796 : Path *path2 = (Path *) lfirst(b);
1435 : int cmp;
1436 :
1437 21796 : cmp = compare_path_costs(path1, path2, TOTAL_COST);
1438 21796 : if (cmp != 0)
1439 19428 : return -cmp;
1440 2368 : 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 44184 : append_startup_cost_compare(const ListCell *a, const ListCell *b)
1454 : {
1455 44184 : Path *path1 = (Path *) lfirst(a);
1456 44184 : Path *path2 = (Path *) lfirst(b);
1457 : int cmp;
1458 :
1459 44184 : cmp = compare_path_costs(path1, path2, STARTUP_COST);
1460 44184 : if (cmp != 0)
1461 21462 : return -cmp;
1462 22722 : 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 10036 : create_merge_append_path(PlannerInfo *root,
1472 : RelOptInfo *rel,
1473 : List *subpaths,
1474 : List *pathkeys,
1475 : Relids required_outer)
1476 : {
1477 10036 : 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 10036 : pathnode->path.pathtype = T_MergeAppend;
1490 10036 : pathnode->path.parent = rel;
1491 10036 : pathnode->path.pathtarget = rel->reltarget;
1492 10036 : pathnode->path.param_info = NULL;
1493 10036 : pathnode->path.parallel_aware = false;
1494 10036 : pathnode->path.parallel_safe = rel->consider_parallel;
1495 10036 : pathnode->path.parallel_workers = 0;
1496 10036 : pathnode->path.pathkeys = pathkeys;
1497 10036 : 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 10036 : if (bms_equal(rel->relids, root->all_query_rels))
1504 4638 : pathnode->limit_tuples = root->limit_tuples;
1505 : else
1506 5398 : pathnode->limit_tuples = -1.0;
1507 :
1508 : /*
1509 : * Add up the sizes and costs of the input paths.
1510 : */
1511 10036 : pathnode->path.rows = 0;
1512 10036 : input_disabled_nodes = 0;
1513 10036 : input_startup_cost = 0;
1514 10036 : input_total_cost = 0;
1515 36252 : foreach(l, subpaths)
1516 : {
1517 26216 : 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 26216 : pathnode->path.rows += subpath->rows;
1526 49728 : pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1527 23512 : subpath->parallel_safe;
1528 :
1529 26216 : 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 314 : 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 296 : cost_sort(&sort_path,
1558 : root,
1559 : pathkeys,
1560 : subpath->disabled_nodes,
1561 : subpath->total_cost,
1562 : subpath->rows,
1563 296 : subpath->pathtarget->width,
1564 : 0.0,
1565 : work_mem,
1566 : pathnode->limit_tuples);
1567 : }
1568 :
1569 314 : subpath = &sort_path;
1570 : }
1571 :
1572 26216 : input_disabled_nodes += subpath->disabled_nodes;
1573 26216 : input_startup_cost += subpath->startup_cost;
1574 26216 : 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 10036 : if (list_length(subpaths) == 1 &&
1584 128 : ((Path *) linitial(subpaths))->parallel_aware ==
1585 128 : pathnode->path.parallel_aware)
1586 : {
1587 128 : pathnode->path.disabled_nodes = input_disabled_nodes;
1588 128 : pathnode->path.startup_cost = input_startup_cost;
1589 128 : pathnode->path.total_cost = input_total_cost;
1590 : }
1591 : else
1592 9908 : 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 10036 : 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 190976 : create_group_result_path(PlannerInfo *root, RelOptInfo *rel,
1610 : PathTarget *target, List *havingqual)
1611 : {
1612 190976 : GroupResultPath *pathnode = makeNode(GroupResultPath);
1613 :
1614 190976 : pathnode->path.pathtype = T_Result;
1615 190976 : pathnode->path.parent = rel;
1616 190976 : pathnode->path.pathtarget = target;
1617 190976 : pathnode->path.param_info = NULL; /* there are no other rels... */
1618 190976 : pathnode->path.parallel_aware = false;
1619 190976 : pathnode->path.parallel_safe = rel->consider_parallel;
1620 190976 : pathnode->path.parallel_workers = 0;
1621 190976 : pathnode->path.pathkeys = NIL;
1622 190976 : 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 190976 : pathnode->path.rows = 1;
1630 190976 : pathnode->path.startup_cost = target->cost.startup;
1631 190976 : pathnode->path.total_cost = target->cost.startup +
1632 190976 : 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 190976 : if (havingqual)
1639 : {
1640 : QualCost qual_cost;
1641 :
1642 628 : cost_qual_eval(&qual_cost, havingqual, root);
1643 : /* havingqual is evaluated once at startup */
1644 628 : pathnode->path.startup_cost += qual_cost.startup + qual_cost.per_tuple;
1645 628 : pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
1646 : }
1647 :
1648 190976 : 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 672702 : create_material_path(RelOptInfo *rel, Path *subpath)
1658 : {
1659 672702 : MaterialPath *pathnode = makeNode(MaterialPath);
1660 :
1661 : Assert(subpath->parent == rel);
1662 :
1663 672702 : pathnode->path.pathtype = T_Material;
1664 672702 : pathnode->path.parent = rel;
1665 672702 : pathnode->path.pathtarget = rel->reltarget;
1666 672702 : pathnode->path.param_info = subpath->param_info;
1667 672702 : pathnode->path.parallel_aware = false;
1668 1288928 : pathnode->path.parallel_safe = rel->consider_parallel &&
1669 616226 : subpath->parallel_safe;
1670 672702 : pathnode->path.parallel_workers = subpath->parallel_workers;
1671 672702 : pathnode->path.pathkeys = subpath->pathkeys;
1672 :
1673 672702 : pathnode->subpath = subpath;
1674 :
1675 672702 : cost_material(&pathnode->path,
1676 : subpath->disabled_nodes,
1677 : subpath->startup_cost,
1678 : subpath->total_cost,
1679 : subpath->rows,
1680 672702 : subpath->pathtarget->width);
1681 :
1682 672702 : 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 315470 : create_memoize_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1691 : List *param_exprs, List *hash_operators,
1692 : bool singlerow, bool binary_mode, Cardinality est_calls)
1693 : {
1694 315470 : MemoizePath *pathnode = makeNode(MemoizePath);
1695 :
1696 : Assert(subpath->parent == rel);
1697 :
1698 315470 : pathnode->path.pathtype = T_Memoize;
1699 315470 : pathnode->path.parent = rel;
1700 315470 : pathnode->path.pathtarget = rel->reltarget;
1701 315470 : pathnode->path.param_info = subpath->param_info;
1702 315470 : pathnode->path.parallel_aware = false;
1703 616796 : pathnode->path.parallel_safe = rel->consider_parallel &&
1704 301326 : subpath->parallel_safe;
1705 315470 : pathnode->path.parallel_workers = subpath->parallel_workers;
1706 315470 : pathnode->path.pathkeys = subpath->pathkeys;
1707 :
1708 315470 : pathnode->subpath = subpath;
1709 315470 : pathnode->hash_operators = hash_operators;
1710 315470 : pathnode->param_exprs = param_exprs;
1711 315470 : pathnode->singlerow = singlerow;
1712 315470 : pathnode->binary_mode = binary_mode;
1713 :
1714 : /*
1715 : * For now we set est_entries to 0. cost_memoize_rescan() does all the
1716 : * hard work to determine how many cache entries there are likely to be,
1717 : * so it seems best to leave it up to that function to fill this field in.
1718 : * If left at 0, the executor will make a guess at a good value.
1719 : */
1720 315470 : pathnode->est_entries = 0;
1721 :
1722 315470 : pathnode->est_calls = clamp_row_est(est_calls);
1723 :
1724 : /* These will also be set later in cost_memoize_rescan() */
1725 315470 : pathnode->est_unique_keys = 0.0;
1726 315470 : pathnode->est_hit_ratio = 0.0;
1727 :
1728 : /* we should not generate this path type when enable_memoize=false */
1729 : Assert(enable_memoize);
1730 315470 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
1731 :
1732 : /*
1733 : * Add a small additional charge for caching the first entry. All the
1734 : * harder calculations for rescans are performed in cost_memoize_rescan().
1735 : */
1736 315470 : pathnode->path.startup_cost = subpath->startup_cost + cpu_tuple_cost;
1737 315470 : pathnode->path.total_cost = subpath->total_cost + cpu_tuple_cost;
1738 315470 : pathnode->path.rows = subpath->rows;
1739 :
1740 315470 : return pathnode;
1741 : }
1742 :
1743 : /*
1744 : * create_gather_merge_path
1745 : *
1746 : * Creates a path corresponding to a gather merge scan, returning
1747 : * the pathnode.
1748 : */
1749 : GatherMergePath *
1750 17524 : create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1751 : PathTarget *target, List *pathkeys,
1752 : Relids required_outer, double *rows)
1753 : {
1754 17524 : GatherMergePath *pathnode = makeNode(GatherMergePath);
1755 17524 : int input_disabled_nodes = 0;
1756 17524 : Cost input_startup_cost = 0;
1757 17524 : Cost input_total_cost = 0;
1758 :
1759 : Assert(subpath->parallel_safe);
1760 : Assert(pathkeys);
1761 :
1762 : /*
1763 : * The subpath should guarantee that it is adequately ordered either by
1764 : * adding an explicit sort node or by using presorted input. We cannot
1765 : * add an explicit Sort node for the subpath in createplan.c on additional
1766 : * pathkeys, because we can't guarantee the sort would be safe. For
1767 : * example, expressions may be volatile or otherwise parallel unsafe.
1768 : */
1769 17524 : if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1770 0 : elog(ERROR, "gather merge input not sufficiently sorted");
1771 :
1772 17524 : pathnode->path.pathtype = T_GatherMerge;
1773 17524 : pathnode->path.parent = rel;
1774 17524 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1775 : required_outer);
1776 17524 : pathnode->path.parallel_aware = false;
1777 :
1778 17524 : pathnode->subpath = subpath;
1779 17524 : pathnode->num_workers = subpath->parallel_workers;
1780 17524 : pathnode->path.pathkeys = pathkeys;
1781 17524 : pathnode->path.pathtarget = target ? target : rel->reltarget;
1782 :
1783 17524 : input_disabled_nodes += subpath->disabled_nodes;
1784 17524 : input_startup_cost += subpath->startup_cost;
1785 17524 : input_total_cost += subpath->total_cost;
1786 :
1787 17524 : cost_gather_merge(pathnode, root, rel, pathnode->path.param_info,
1788 : input_disabled_nodes, input_startup_cost,
1789 : input_total_cost, rows);
1790 :
1791 17524 : return pathnode;
1792 : }
1793 :
1794 : /*
1795 : * create_gather_path
1796 : * Creates a path corresponding to a gather scan, returning the
1797 : * pathnode.
1798 : *
1799 : * 'rows' may optionally be set to override row estimates from other sources.
1800 : */
1801 : GatherPath *
1802 24820 : create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1803 : PathTarget *target, Relids required_outer, double *rows)
1804 : {
1805 24820 : GatherPath *pathnode = makeNode(GatherPath);
1806 :
1807 : Assert(subpath->parallel_safe);
1808 :
1809 24820 : pathnode->path.pathtype = T_Gather;
1810 24820 : pathnode->path.parent = rel;
1811 24820 : pathnode->path.pathtarget = target;
1812 24820 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1813 : required_outer);
1814 24820 : pathnode->path.parallel_aware = false;
1815 24820 : pathnode->path.parallel_safe = false;
1816 24820 : pathnode->path.parallel_workers = 0;
1817 24820 : pathnode->path.pathkeys = NIL; /* Gather has unordered result */
1818 :
1819 24820 : pathnode->subpath = subpath;
1820 24820 : pathnode->num_workers = subpath->parallel_workers;
1821 24820 : pathnode->single_copy = false;
1822 :
1823 24820 : if (pathnode->num_workers == 0)
1824 : {
1825 0 : pathnode->path.pathkeys = subpath->pathkeys;
1826 0 : pathnode->num_workers = 1;
1827 0 : pathnode->single_copy = true;
1828 : }
1829 :
1830 24820 : cost_gather(pathnode, root, rel, pathnode->path.param_info, rows);
1831 :
1832 24820 : return pathnode;
1833 : }
1834 :
1835 : /*
1836 : * create_subqueryscan_path
1837 : * Creates a path corresponding to a scan of a subquery,
1838 : * returning the pathnode.
1839 : *
1840 : * Caller must pass trivial_pathtarget = true if it believes rel->reltarget to
1841 : * be trivial, ie just a fetch of all the subquery output columns in order.
1842 : * While we could determine that here, the caller can usually do it more
1843 : * efficiently (or at least amortize it over multiple calls).
1844 : */
1845 : SubqueryScanPath *
1846 55688 : create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1847 : bool trivial_pathtarget,
1848 : List *pathkeys, Relids required_outer)
1849 : {
1850 55688 : SubqueryScanPath *pathnode = makeNode(SubqueryScanPath);
1851 :
1852 55688 : pathnode->path.pathtype = T_SubqueryScan;
1853 55688 : pathnode->path.parent = rel;
1854 55688 : pathnode->path.pathtarget = rel->reltarget;
1855 55688 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1856 : required_outer);
1857 55688 : pathnode->path.parallel_aware = false;
1858 96024 : pathnode->path.parallel_safe = rel->consider_parallel &&
1859 40336 : subpath->parallel_safe;
1860 55688 : pathnode->path.parallel_workers = subpath->parallel_workers;
1861 55688 : pathnode->path.pathkeys = pathkeys;
1862 55688 : pathnode->subpath = subpath;
1863 :
1864 55688 : cost_subqueryscan(pathnode, root, rel, pathnode->path.param_info,
1865 : trivial_pathtarget);
1866 :
1867 55688 : return pathnode;
1868 : }
1869 :
1870 : /*
1871 : * create_functionscan_path
1872 : * Creates a path corresponding to a sequential scan of a function,
1873 : * returning the pathnode.
1874 : */
1875 : Path *
1876 51322 : create_functionscan_path(PlannerInfo *root, RelOptInfo *rel,
1877 : List *pathkeys, Relids required_outer)
1878 : {
1879 51322 : Path *pathnode = makeNode(Path);
1880 :
1881 51322 : pathnode->pathtype = T_FunctionScan;
1882 51322 : pathnode->parent = rel;
1883 51322 : pathnode->pathtarget = rel->reltarget;
1884 51322 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1885 : required_outer);
1886 51322 : pathnode->parallel_aware = false;
1887 51322 : pathnode->parallel_safe = rel->consider_parallel;
1888 51322 : pathnode->parallel_workers = 0;
1889 51322 : pathnode->pathkeys = pathkeys;
1890 :
1891 51322 : cost_functionscan(pathnode, root, rel, pathnode->param_info);
1892 :
1893 51322 : return pathnode;
1894 : }
1895 :
1896 : /*
1897 : * create_tablefuncscan_path
1898 : * Creates a path corresponding to a sequential scan of a table function,
1899 : * returning the pathnode.
1900 : */
1901 : Path *
1902 626 : create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel,
1903 : Relids required_outer)
1904 : {
1905 626 : Path *pathnode = makeNode(Path);
1906 :
1907 626 : pathnode->pathtype = T_TableFuncScan;
1908 626 : pathnode->parent = rel;
1909 626 : pathnode->pathtarget = rel->reltarget;
1910 626 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1911 : required_outer);
1912 626 : pathnode->parallel_aware = false;
1913 626 : pathnode->parallel_safe = rel->consider_parallel;
1914 626 : pathnode->parallel_workers = 0;
1915 626 : pathnode->pathkeys = NIL; /* result is always unordered */
1916 :
1917 626 : cost_tablefuncscan(pathnode, root, rel, pathnode->param_info);
1918 :
1919 626 : return pathnode;
1920 : }
1921 :
1922 : /*
1923 : * create_valuesscan_path
1924 : * Creates a path corresponding to a scan of a VALUES list,
1925 : * returning the pathnode.
1926 : */
1927 : Path *
1928 8268 : create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel,
1929 : Relids required_outer)
1930 : {
1931 8268 : Path *pathnode = makeNode(Path);
1932 :
1933 8268 : pathnode->pathtype = T_ValuesScan;
1934 8268 : pathnode->parent = rel;
1935 8268 : pathnode->pathtarget = rel->reltarget;
1936 8268 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1937 : required_outer);
1938 8268 : pathnode->parallel_aware = false;
1939 8268 : pathnode->parallel_safe = rel->consider_parallel;
1940 8268 : pathnode->parallel_workers = 0;
1941 8268 : pathnode->pathkeys = NIL; /* result is always unordered */
1942 :
1943 8268 : cost_valuesscan(pathnode, root, rel, pathnode->param_info);
1944 :
1945 8268 : return pathnode;
1946 : }
1947 :
1948 : /*
1949 : * create_ctescan_path
1950 : * Creates a path corresponding to a scan of a non-self-reference CTE,
1951 : * returning the pathnode.
1952 : */
1953 : Path *
1954 4242 : create_ctescan_path(PlannerInfo *root, RelOptInfo *rel,
1955 : List *pathkeys, Relids required_outer)
1956 : {
1957 4242 : Path *pathnode = makeNode(Path);
1958 :
1959 4242 : pathnode->pathtype = T_CteScan;
1960 4242 : pathnode->parent = rel;
1961 4242 : pathnode->pathtarget = rel->reltarget;
1962 4242 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1963 : required_outer);
1964 4242 : pathnode->parallel_aware = false;
1965 4242 : pathnode->parallel_safe = rel->consider_parallel;
1966 4242 : pathnode->parallel_workers = 0;
1967 4242 : pathnode->pathkeys = pathkeys;
1968 :
1969 4242 : cost_ctescan(pathnode, root, rel, pathnode->param_info);
1970 :
1971 4242 : return pathnode;
1972 : }
1973 :
1974 : /*
1975 : * create_namedtuplestorescan_path
1976 : * Creates a path corresponding to a scan of a named tuplestore, returning
1977 : * the pathnode.
1978 : */
1979 : Path *
1980 474 : create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel,
1981 : Relids required_outer)
1982 : {
1983 474 : Path *pathnode = makeNode(Path);
1984 :
1985 474 : pathnode->pathtype = T_NamedTuplestoreScan;
1986 474 : pathnode->parent = rel;
1987 474 : pathnode->pathtarget = rel->reltarget;
1988 474 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
1989 : required_outer);
1990 474 : pathnode->parallel_aware = false;
1991 474 : pathnode->parallel_safe = rel->consider_parallel;
1992 474 : pathnode->parallel_workers = 0;
1993 474 : pathnode->pathkeys = NIL; /* result is always unordered */
1994 :
1995 474 : cost_namedtuplestorescan(pathnode, root, rel, pathnode->param_info);
1996 :
1997 474 : return pathnode;
1998 : }
1999 :
2000 : /*
2001 : * create_resultscan_path
2002 : * Creates a path corresponding to a scan of an RTE_RESULT relation,
2003 : * returning the pathnode.
2004 : */
2005 : Path *
2006 4256 : create_resultscan_path(PlannerInfo *root, RelOptInfo *rel,
2007 : Relids required_outer)
2008 : {
2009 4256 : Path *pathnode = makeNode(Path);
2010 :
2011 4256 : pathnode->pathtype = T_Result;
2012 4256 : pathnode->parent = rel;
2013 4256 : pathnode->pathtarget = rel->reltarget;
2014 4256 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
2015 : required_outer);
2016 4256 : pathnode->parallel_aware = false;
2017 4256 : pathnode->parallel_safe = rel->consider_parallel;
2018 4256 : pathnode->parallel_workers = 0;
2019 4256 : pathnode->pathkeys = NIL; /* result is always unordered */
2020 :
2021 4256 : cost_resultscan(pathnode, root, rel, pathnode->param_info);
2022 :
2023 4256 : return pathnode;
2024 : }
2025 :
2026 : /*
2027 : * create_worktablescan_path
2028 : * Creates a path corresponding to a scan of a self-reference CTE,
2029 : * returning the pathnode.
2030 : */
2031 : Path *
2032 934 : create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel,
2033 : Relids required_outer)
2034 : {
2035 934 : Path *pathnode = makeNode(Path);
2036 :
2037 934 : pathnode->pathtype = T_WorkTableScan;
2038 934 : pathnode->parent = rel;
2039 934 : pathnode->pathtarget = rel->reltarget;
2040 934 : pathnode->param_info = get_baserel_parampathinfo(root, rel,
2041 : required_outer);
2042 934 : pathnode->parallel_aware = false;
2043 934 : pathnode->parallel_safe = rel->consider_parallel;
2044 934 : pathnode->parallel_workers = 0;
2045 934 : pathnode->pathkeys = NIL; /* result is always unordered */
2046 :
2047 : /* Cost is the same as for a regular CTE scan */
2048 934 : cost_ctescan(pathnode, root, rel, pathnode->param_info);
2049 :
2050 934 : return pathnode;
2051 : }
2052 :
2053 : /*
2054 : * create_foreignscan_path
2055 : * Creates a path corresponding to a scan of a foreign base table,
2056 : * returning the pathnode.
2057 : *
2058 : * This function is never called from core Postgres; rather, it's expected
2059 : * to be called by the GetForeignPaths function of a foreign data wrapper.
2060 : * We make the FDW supply all fields of the path, since we do not have any way
2061 : * to calculate them in core. However, there is a usually-sane default for
2062 : * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2063 : */
2064 : ForeignPath *
2065 3722 : create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel,
2066 : PathTarget *target,
2067 : double rows, int disabled_nodes,
2068 : Cost startup_cost, Cost total_cost,
2069 : List *pathkeys,
2070 : Relids required_outer,
2071 : Path *fdw_outerpath,
2072 : List *fdw_restrictinfo,
2073 : List *fdw_private)
2074 : {
2075 3722 : ForeignPath *pathnode = makeNode(ForeignPath);
2076 :
2077 : /* Historically some FDWs were confused about when to use this */
2078 : Assert(IS_SIMPLE_REL(rel));
2079 :
2080 3722 : pathnode->path.pathtype = T_ForeignScan;
2081 3722 : pathnode->path.parent = rel;
2082 3722 : pathnode->path.pathtarget = target ? target : rel->reltarget;
2083 3722 : pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
2084 : required_outer);
2085 3722 : pathnode->path.parallel_aware = false;
2086 3722 : pathnode->path.parallel_safe = rel->consider_parallel;
2087 3722 : pathnode->path.parallel_workers = 0;
2088 3722 : pathnode->path.rows = rows;
2089 3722 : pathnode->path.disabled_nodes = disabled_nodes;
2090 3722 : pathnode->path.startup_cost = startup_cost;
2091 3722 : pathnode->path.total_cost = total_cost;
2092 3722 : pathnode->path.pathkeys = pathkeys;
2093 :
2094 3722 : pathnode->fdw_outerpath = fdw_outerpath;
2095 3722 : pathnode->fdw_restrictinfo = fdw_restrictinfo;
2096 3722 : pathnode->fdw_private = fdw_private;
2097 :
2098 3722 : return pathnode;
2099 : }
2100 :
2101 : /*
2102 : * create_foreign_join_path
2103 : * Creates a path corresponding to a scan of a foreign join,
2104 : * returning the pathnode.
2105 : *
2106 : * This function is never called from core Postgres; rather, it's expected
2107 : * to be called by the GetForeignJoinPaths function of a foreign data wrapper.
2108 : * We make the FDW supply all fields of the path, since we do not have any way
2109 : * to calculate them in core. However, there is a usually-sane default for
2110 : * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2111 : */
2112 : ForeignPath *
2113 1212 : create_foreign_join_path(PlannerInfo *root, RelOptInfo *rel,
2114 : PathTarget *target,
2115 : double rows, int disabled_nodes,
2116 : Cost startup_cost, Cost total_cost,
2117 : List *pathkeys,
2118 : Relids required_outer,
2119 : Path *fdw_outerpath,
2120 : List *fdw_restrictinfo,
2121 : List *fdw_private)
2122 : {
2123 1212 : ForeignPath *pathnode = makeNode(ForeignPath);
2124 :
2125 : /*
2126 : * We should use get_joinrel_parampathinfo to handle parameterized paths,
2127 : * but the API of this function doesn't support it, and existing
2128 : * extensions aren't yet trying to build such paths anyway. For the
2129 : * moment just throw an error if someone tries it; eventually we should
2130 : * revisit this.
2131 : */
2132 1212 : if (!bms_is_empty(required_outer) || !bms_is_empty(rel->lateral_relids))
2133 0 : elog(ERROR, "parameterized foreign joins are not supported yet");
2134 :
2135 1212 : pathnode->path.pathtype = T_ForeignScan;
2136 1212 : pathnode->path.parent = rel;
2137 1212 : pathnode->path.pathtarget = target ? target : rel->reltarget;
2138 1212 : pathnode->path.param_info = NULL; /* XXX see above */
2139 1212 : pathnode->path.parallel_aware = false;
2140 1212 : pathnode->path.parallel_safe = rel->consider_parallel;
2141 1212 : pathnode->path.parallel_workers = 0;
2142 1212 : pathnode->path.rows = rows;
2143 1212 : pathnode->path.disabled_nodes = disabled_nodes;
2144 1212 : pathnode->path.startup_cost = startup_cost;
2145 1212 : pathnode->path.total_cost = total_cost;
2146 1212 : pathnode->path.pathkeys = pathkeys;
2147 :
2148 1212 : pathnode->fdw_outerpath = fdw_outerpath;
2149 1212 : pathnode->fdw_restrictinfo = fdw_restrictinfo;
2150 1212 : pathnode->fdw_private = fdw_private;
2151 :
2152 1212 : return pathnode;
2153 : }
2154 :
2155 : /*
2156 : * create_foreign_upper_path
2157 : * Creates a path corresponding to an upper relation that's computed
2158 : * directly by an FDW, returning the pathnode.
2159 : *
2160 : * This function is never called from core Postgres; rather, it's expected to
2161 : * be called by the GetForeignUpperPaths function of a foreign data wrapper.
2162 : * We make the FDW supply all fields of the path, since we do not have any way
2163 : * to calculate them in core. However, there is a usually-sane default for
2164 : * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2165 : */
2166 : ForeignPath *
2167 588 : create_foreign_upper_path(PlannerInfo *root, RelOptInfo *rel,
2168 : PathTarget *target,
2169 : double rows, int disabled_nodes,
2170 : Cost startup_cost, Cost total_cost,
2171 : List *pathkeys,
2172 : Path *fdw_outerpath,
2173 : List *fdw_restrictinfo,
2174 : List *fdw_private)
2175 : {
2176 588 : ForeignPath *pathnode = makeNode(ForeignPath);
2177 :
2178 : /*
2179 : * Upper relations should never have any lateral references, since joining
2180 : * is complete.
2181 : */
2182 : Assert(bms_is_empty(rel->lateral_relids));
2183 :
2184 588 : pathnode->path.pathtype = T_ForeignScan;
2185 588 : pathnode->path.parent = rel;
2186 588 : pathnode->path.pathtarget = target ? target : rel->reltarget;
2187 588 : pathnode->path.param_info = NULL;
2188 588 : pathnode->path.parallel_aware = false;
2189 588 : pathnode->path.parallel_safe = rel->consider_parallel;
2190 588 : pathnode->path.parallel_workers = 0;
2191 588 : pathnode->path.rows = rows;
2192 588 : pathnode->path.disabled_nodes = disabled_nodes;
2193 588 : pathnode->path.startup_cost = startup_cost;
2194 588 : pathnode->path.total_cost = total_cost;
2195 588 : pathnode->path.pathkeys = pathkeys;
2196 :
2197 588 : pathnode->fdw_outerpath = fdw_outerpath;
2198 588 : pathnode->fdw_restrictinfo = fdw_restrictinfo;
2199 588 : pathnode->fdw_private = fdw_private;
2200 :
2201 588 : return pathnode;
2202 : }
2203 :
2204 : /*
2205 : * calc_nestloop_required_outer
2206 : * Compute the required_outer set for a nestloop join path
2207 : *
2208 : * Note: when considering a child join, the inputs nonetheless use top-level
2209 : * parent relids
2210 : *
2211 : * Note: result must not share storage with either input
2212 : */
2213 : Relids
2214 3365942 : calc_nestloop_required_outer(Relids outerrelids,
2215 : Relids outer_paramrels,
2216 : Relids innerrelids,
2217 : Relids inner_paramrels)
2218 : {
2219 : Relids required_outer;
2220 :
2221 : /* inner_path can require rels from outer path, but not vice versa */
2222 : Assert(!bms_overlap(outer_paramrels, innerrelids));
2223 : /* easy case if inner path is not parameterized */
2224 3365942 : if (!inner_paramrels)
2225 2333932 : return bms_copy(outer_paramrels);
2226 : /* else, form the union ... */
2227 1032010 : required_outer = bms_union(outer_paramrels, inner_paramrels);
2228 : /* ... and remove any mention of now-satisfied outer rels */
2229 1032010 : required_outer = bms_del_members(required_outer,
2230 : outerrelids);
2231 1032010 : return required_outer;
2232 : }
2233 :
2234 : /*
2235 : * calc_non_nestloop_required_outer
2236 : * Compute the required_outer set for a merge or hash join path
2237 : *
2238 : * Note: result must not share storage with either input
2239 : */
2240 : Relids
2241 2264142 : calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
2242 : {
2243 2264142 : Relids outer_paramrels = PATH_REQ_OUTER(outer_path);
2244 2264142 : Relids inner_paramrels = PATH_REQ_OUTER(inner_path);
2245 : Relids innerrelids PG_USED_FOR_ASSERTS_ONLY;
2246 : Relids outerrelids PG_USED_FOR_ASSERTS_ONLY;
2247 : Relids required_outer;
2248 :
2249 : /*
2250 : * Any parameterization of the input paths refers to topmost parents of
2251 : * the relevant relations, because reparameterize_path_by_child() hasn't
2252 : * been called yet. So we must consider topmost parents of the relations
2253 : * being joined, too, while checking for disallowed parameterization
2254 : * cases.
2255 : */
2256 2264142 : if (inner_path->parent->top_parent_relids)
2257 159758 : innerrelids = inner_path->parent->top_parent_relids;
2258 : else
2259 2104384 : innerrelids = inner_path->parent->relids;
2260 :
2261 2264142 : if (outer_path->parent->top_parent_relids)
2262 159758 : outerrelids = outer_path->parent->top_parent_relids;
2263 : else
2264 2104384 : outerrelids = outer_path->parent->relids;
2265 :
2266 : /* neither path can require rels from the other */
2267 : Assert(!bms_overlap(outer_paramrels, innerrelids));
2268 : Assert(!bms_overlap(inner_paramrels, outerrelids));
2269 : /* form the union ... */
2270 2264142 : required_outer = bms_union(outer_paramrels, inner_paramrels);
2271 : /* we do not need an explicit test for empty; bms_union gets it right */
2272 2264142 : return required_outer;
2273 : }
2274 :
2275 : /*
2276 : * create_nestloop_path
2277 : * Creates a pathnode corresponding to a nestloop join between two
2278 : * relations.
2279 : *
2280 : * 'joinrel' is the join relation.
2281 : * 'jointype' is the type of join required
2282 : * 'workspace' is the result from initial_cost_nestloop
2283 : * 'extra' contains various information about the join
2284 : * 'outer_path' is the outer path
2285 : * 'inner_path' is the inner path
2286 : * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2287 : * 'pathkeys' are the path keys of the new join path
2288 : * 'required_outer' is the set of required outer rels
2289 : *
2290 : * Returns the resulting path node.
2291 : */
2292 : NestPath *
2293 1456540 : create_nestloop_path(PlannerInfo *root,
2294 : RelOptInfo *joinrel,
2295 : JoinType jointype,
2296 : JoinCostWorkspace *workspace,
2297 : JoinPathExtraData *extra,
2298 : Path *outer_path,
2299 : Path *inner_path,
2300 : List *restrict_clauses,
2301 : List *pathkeys,
2302 : Relids required_outer)
2303 : {
2304 1456540 : NestPath *pathnode = makeNode(NestPath);
2305 1456540 : Relids inner_req_outer = PATH_REQ_OUTER(inner_path);
2306 : Relids outerrelids;
2307 :
2308 : /*
2309 : * Paths are parameterized by top-level parents, so run parameterization
2310 : * tests on the parent relids.
2311 : */
2312 1456540 : if (outer_path->parent->top_parent_relids)
2313 76102 : outerrelids = outer_path->parent->top_parent_relids;
2314 : else
2315 1380438 : outerrelids = outer_path->parent->relids;
2316 :
2317 : /*
2318 : * If the inner path is parameterized by the outer, we must drop any
2319 : * restrict_clauses that are due to be moved into the inner path. We have
2320 : * to do this now, rather than postpone the work till createplan time,
2321 : * because the restrict_clauses list can affect the size and cost
2322 : * estimates for this path. We detect such clauses by checking for serial
2323 : * number match to clauses already enforced in the inner path.
2324 : */
2325 1456540 : if (bms_overlap(inner_req_outer, outerrelids))
2326 : {
2327 394636 : Bitmapset *enforced_serials = get_param_path_clause_serials(inner_path);
2328 394636 : List *jclauses = NIL;
2329 : ListCell *lc;
2330 :
2331 875938 : foreach(lc, restrict_clauses)
2332 : {
2333 481302 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2334 :
2335 481302 : if (!bms_is_member(rinfo->rinfo_serial, enforced_serials))
2336 60252 : jclauses = lappend(jclauses, rinfo);
2337 : }
2338 394636 : restrict_clauses = jclauses;
2339 : }
2340 :
2341 1456540 : pathnode->jpath.path.pathtype = T_NestLoop;
2342 1456540 : pathnode->jpath.path.parent = joinrel;
2343 1456540 : pathnode->jpath.path.pathtarget = joinrel->reltarget;
2344 1456540 : pathnode->jpath.path.param_info =
2345 1456540 : get_joinrel_parampathinfo(root,
2346 : joinrel,
2347 : outer_path,
2348 : inner_path,
2349 : extra->sjinfo,
2350 : required_outer,
2351 : &restrict_clauses);
2352 1456540 : pathnode->jpath.path.parallel_aware = false;
2353 4242218 : pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2354 1456540 : outer_path->parallel_safe && inner_path->parallel_safe;
2355 : /* This is a foolish way to estimate parallel_workers, but for now... */
2356 1456540 : pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2357 1456540 : pathnode->jpath.path.pathkeys = pathkeys;
2358 1456540 : pathnode->jpath.jointype = jointype;
2359 1456540 : pathnode->jpath.inner_unique = extra->inner_unique;
2360 1456540 : pathnode->jpath.outerjoinpath = outer_path;
2361 1456540 : pathnode->jpath.innerjoinpath = inner_path;
2362 1456540 : pathnode->jpath.joinrestrictinfo = restrict_clauses;
2363 :
2364 1456540 : final_cost_nestloop(root, pathnode, workspace, extra);
2365 :
2366 1456540 : return pathnode;
2367 : }
2368 :
2369 : /*
2370 : * create_mergejoin_path
2371 : * Creates a pathnode corresponding to a mergejoin join between
2372 : * two relations
2373 : *
2374 : * 'joinrel' is the join relation
2375 : * 'jointype' is the type of join required
2376 : * 'workspace' is the result from initial_cost_mergejoin
2377 : * 'extra' contains various information about the join
2378 : * 'outer_path' is the outer path
2379 : * 'inner_path' is the inner path
2380 : * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2381 : * 'pathkeys' are the path keys of the new join path
2382 : * 'required_outer' is the set of required outer rels
2383 : * 'mergeclauses' are the RestrictInfo nodes to use as merge clauses
2384 : * (this should be a subset of the restrict_clauses list)
2385 : * 'outersortkeys' are the sort varkeys for the outer relation
2386 : * 'innersortkeys' are the sort varkeys for the inner relation
2387 : * 'outer_presorted_keys' is the number of presorted keys of the outer path
2388 : */
2389 : MergePath *
2390 457384 : create_mergejoin_path(PlannerInfo *root,
2391 : RelOptInfo *joinrel,
2392 : JoinType jointype,
2393 : JoinCostWorkspace *workspace,
2394 : JoinPathExtraData *extra,
2395 : Path *outer_path,
2396 : Path *inner_path,
2397 : List *restrict_clauses,
2398 : List *pathkeys,
2399 : Relids required_outer,
2400 : List *mergeclauses,
2401 : List *outersortkeys,
2402 : List *innersortkeys,
2403 : int outer_presorted_keys)
2404 : {
2405 457384 : MergePath *pathnode = makeNode(MergePath);
2406 :
2407 457384 : pathnode->jpath.path.pathtype = T_MergeJoin;
2408 457384 : pathnode->jpath.path.parent = joinrel;
2409 457384 : pathnode->jpath.path.pathtarget = joinrel->reltarget;
2410 457384 : pathnode->jpath.path.param_info =
2411 457384 : get_joinrel_parampathinfo(root,
2412 : joinrel,
2413 : outer_path,
2414 : inner_path,
2415 : extra->sjinfo,
2416 : required_outer,
2417 : &restrict_clauses);
2418 457384 : pathnode->jpath.path.parallel_aware = false;
2419 1334858 : pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2420 457384 : outer_path->parallel_safe && inner_path->parallel_safe;
2421 : /* This is a foolish way to estimate parallel_workers, but for now... */
2422 457384 : pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2423 457384 : pathnode->jpath.path.pathkeys = pathkeys;
2424 457384 : pathnode->jpath.jointype = jointype;
2425 457384 : pathnode->jpath.inner_unique = extra->inner_unique;
2426 457384 : pathnode->jpath.outerjoinpath = outer_path;
2427 457384 : pathnode->jpath.innerjoinpath = inner_path;
2428 457384 : pathnode->jpath.joinrestrictinfo = restrict_clauses;
2429 457384 : pathnode->path_mergeclauses = mergeclauses;
2430 457384 : pathnode->outersortkeys = outersortkeys;
2431 457384 : pathnode->innersortkeys = innersortkeys;
2432 457384 : pathnode->outer_presorted_keys = outer_presorted_keys;
2433 : /* pathnode->skip_mark_restore will be set by final_cost_mergejoin */
2434 : /* pathnode->materialize_inner will be set by final_cost_mergejoin */
2435 :
2436 457384 : final_cost_mergejoin(root, pathnode, workspace, extra);
2437 :
2438 457384 : return pathnode;
2439 : }
2440 :
2441 : /*
2442 : * create_hashjoin_path
2443 : * Creates a pathnode corresponding to a hash join between two relations.
2444 : *
2445 : * 'joinrel' is the join relation
2446 : * 'jointype' is the type of join required
2447 : * 'workspace' is the result from initial_cost_hashjoin
2448 : * 'extra' contains various information about the join
2449 : * 'outer_path' is the cheapest outer path
2450 : * 'inner_path' is the cheapest inner path
2451 : * 'parallel_hash' to select Parallel Hash of inner path (shared hash table)
2452 : * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2453 : * 'required_outer' is the set of required outer rels
2454 : * 'hashclauses' are the RestrictInfo nodes to use as hash clauses
2455 : * (this should be a subset of the restrict_clauses list)
2456 : */
2457 : HashPath *
2458 452968 : create_hashjoin_path(PlannerInfo *root,
2459 : RelOptInfo *joinrel,
2460 : JoinType jointype,
2461 : JoinCostWorkspace *workspace,
2462 : JoinPathExtraData *extra,
2463 : Path *outer_path,
2464 : Path *inner_path,
2465 : bool parallel_hash,
2466 : List *restrict_clauses,
2467 : Relids required_outer,
2468 : List *hashclauses)
2469 : {
2470 452968 : HashPath *pathnode = makeNode(HashPath);
2471 :
2472 452968 : pathnode->jpath.path.pathtype = T_HashJoin;
2473 452968 : pathnode->jpath.path.parent = joinrel;
2474 452968 : pathnode->jpath.path.pathtarget = joinrel->reltarget;
2475 452968 : pathnode->jpath.path.param_info =
2476 452968 : get_joinrel_parampathinfo(root,
2477 : joinrel,
2478 : outer_path,
2479 : inner_path,
2480 : extra->sjinfo,
2481 : required_outer,
2482 : &restrict_clauses);
2483 452968 : pathnode->jpath.path.parallel_aware =
2484 452968 : joinrel->consider_parallel && parallel_hash;
2485 1322358 : pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2486 452968 : outer_path->parallel_safe && inner_path->parallel_safe;
2487 : /* This is a foolish way to estimate parallel_workers, but for now... */
2488 452968 : pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2489 :
2490 : /*
2491 : * A hashjoin never has pathkeys, since its output ordering is
2492 : * unpredictable due to possible batching. XXX If the inner relation is
2493 : * small enough, we could instruct the executor that it must not batch,
2494 : * and then we could assume that the output inherits the outer relation's
2495 : * ordering, which might save a sort step. However there is considerable
2496 : * downside if our estimate of the inner relation size is badly off. For
2497 : * the moment we don't risk it. (Note also that if we wanted to take this
2498 : * seriously, joinpath.c would have to consider many more paths for the
2499 : * outer rel than it does now.)
2500 : */
2501 452968 : pathnode->jpath.path.pathkeys = NIL;
2502 452968 : pathnode->jpath.jointype = jointype;
2503 452968 : pathnode->jpath.inner_unique = extra->inner_unique;
2504 452968 : pathnode->jpath.outerjoinpath = outer_path;
2505 452968 : pathnode->jpath.innerjoinpath = inner_path;
2506 452968 : pathnode->jpath.joinrestrictinfo = restrict_clauses;
2507 452968 : pathnode->path_hashclauses = hashclauses;
2508 : /* final_cost_hashjoin will fill in pathnode->num_batches */
2509 :
2510 452968 : final_cost_hashjoin(root, pathnode, workspace, extra);
2511 :
2512 452968 : return pathnode;
2513 : }
2514 :
2515 : /*
2516 : * create_projection_path
2517 : * Creates a pathnode that represents performing a projection.
2518 : *
2519 : * 'rel' is the parent relation associated with the result
2520 : * 'subpath' is the path representing the source of data
2521 : * 'target' is the PathTarget to be computed
2522 : */
2523 : ProjectionPath *
2524 412080 : create_projection_path(PlannerInfo *root,
2525 : RelOptInfo *rel,
2526 : Path *subpath,
2527 : PathTarget *target)
2528 : {
2529 412080 : ProjectionPath *pathnode = makeNode(ProjectionPath);
2530 : PathTarget *oldtarget;
2531 :
2532 : /*
2533 : * We mustn't put a ProjectionPath directly above another; it's useless
2534 : * and will confuse create_projection_plan. Rather than making sure all
2535 : * callers handle that, let's implement it here, by stripping off any
2536 : * ProjectionPath in what we're given. Given this rule, there won't be
2537 : * more than one.
2538 : */
2539 412080 : if (IsA(subpath, ProjectionPath))
2540 : {
2541 12 : ProjectionPath *subpp = (ProjectionPath *) subpath;
2542 :
2543 : Assert(subpp->path.parent == rel);
2544 12 : subpath = subpp->subpath;
2545 : Assert(!IsA(subpath, ProjectionPath));
2546 : }
2547 :
2548 412080 : pathnode->path.pathtype = T_Result;
2549 412080 : pathnode->path.parent = rel;
2550 412080 : pathnode->path.pathtarget = target;
2551 412080 : pathnode->path.param_info = subpath->param_info;
2552 412080 : pathnode->path.parallel_aware = false;
2553 963754 : pathnode->path.parallel_safe = rel->consider_parallel &&
2554 543676 : subpath->parallel_safe &&
2555 131596 : is_parallel_safe(root, (Node *) target->exprs);
2556 412080 : pathnode->path.parallel_workers = subpath->parallel_workers;
2557 : /* Projection does not change the sort order */
2558 412080 : pathnode->path.pathkeys = subpath->pathkeys;
2559 :
2560 412080 : pathnode->subpath = subpath;
2561 :
2562 : /*
2563 : * We might not need a separate Result node. If the input plan node type
2564 : * can project, we can just tell it to project something else. Or, if it
2565 : * can't project but the desired target has the same expression list as
2566 : * what the input will produce anyway, we can still give it the desired
2567 : * tlist (possibly changing its ressortgroupref labels, but nothing else).
2568 : * Note: in the latter case, create_projection_plan has to recheck our
2569 : * conclusion; see comments therein.
2570 : */
2571 412080 : oldtarget = subpath->pathtarget;
2572 428430 : if (is_projection_capable_path(subpath) ||
2573 16350 : equal(oldtarget->exprs, target->exprs))
2574 : {
2575 : /* No separate Result node needed */
2576 397612 : pathnode->dummypp = true;
2577 :
2578 : /*
2579 : * Set cost of plan as subpath's cost, adjusted for tlist replacement.
2580 : */
2581 397612 : pathnode->path.rows = subpath->rows;
2582 397612 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2583 397612 : pathnode->path.startup_cost = subpath->startup_cost +
2584 397612 : (target->cost.startup - oldtarget->cost.startup);
2585 397612 : pathnode->path.total_cost = subpath->total_cost +
2586 397612 : (target->cost.startup - oldtarget->cost.startup) +
2587 397612 : (target->cost.per_tuple - oldtarget->cost.per_tuple) * subpath->rows;
2588 : }
2589 : else
2590 : {
2591 : /* We really do need the Result node */
2592 14468 : pathnode->dummypp = false;
2593 :
2594 : /*
2595 : * The Result node's cost is cpu_tuple_cost per row, plus the cost of
2596 : * evaluating the tlist. There is no qual to worry about.
2597 : */
2598 14468 : pathnode->path.rows = subpath->rows;
2599 14468 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2600 14468 : pathnode->path.startup_cost = subpath->startup_cost +
2601 14468 : target->cost.startup;
2602 14468 : pathnode->path.total_cost = subpath->total_cost +
2603 14468 : target->cost.startup +
2604 14468 : (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows;
2605 : }
2606 :
2607 412080 : return pathnode;
2608 : }
2609 :
2610 : /*
2611 : * apply_projection_to_path
2612 : * Add a projection step, or just apply the target directly to given path.
2613 : *
2614 : * This has the same net effect as create_projection_path(), except that if
2615 : * a separate Result plan node isn't needed, we just replace the given path's
2616 : * pathtarget with the desired one. This must be used only when the caller
2617 : * knows that the given path isn't referenced elsewhere and so can be modified
2618 : * in-place.
2619 : *
2620 : * If the input path is a GatherPath or GatherMergePath, we try to push the
2621 : * new target down to its input as well; this is a yet more invasive
2622 : * modification of the input path, which create_projection_path() can't do.
2623 : *
2624 : * Note that we mustn't change the source path's parent link; so when it is
2625 : * add_path'd to "rel" things will be a bit inconsistent. So far that has
2626 : * not caused any trouble.
2627 : *
2628 : * 'rel' is the parent relation associated with the result
2629 : * 'path' is the path representing the source of data
2630 : * 'target' is the PathTarget to be computed
2631 : */
2632 : Path *
2633 13636 : apply_projection_to_path(PlannerInfo *root,
2634 : RelOptInfo *rel,
2635 : Path *path,
2636 : PathTarget *target)
2637 : {
2638 : QualCost oldcost;
2639 :
2640 : /*
2641 : * If given path can't project, we might need a Result node, so make a
2642 : * separate ProjectionPath.
2643 : */
2644 13636 : if (!is_projection_capable_path(path))
2645 1482 : return (Path *) create_projection_path(root, rel, path, target);
2646 :
2647 : /*
2648 : * We can just jam the desired tlist into the existing path, being sure to
2649 : * update its cost estimates appropriately.
2650 : */
2651 12154 : oldcost = path->pathtarget->cost;
2652 12154 : path->pathtarget = target;
2653 :
2654 12154 : path->startup_cost += target->cost.startup - oldcost.startup;
2655 12154 : path->total_cost += target->cost.startup - oldcost.startup +
2656 12154 : (target->cost.per_tuple - oldcost.per_tuple) * path->rows;
2657 :
2658 : /*
2659 : * If the path happens to be a Gather or GatherMerge path, we'd like to
2660 : * arrange for the subpath to return the required target list so that
2661 : * workers can help project. But if there is something that is not
2662 : * parallel-safe in the target expressions, then we can't.
2663 : */
2664 12178 : if ((IsA(path, GatherPath) || IsA(path, GatherMergePath)) &&
2665 24 : is_parallel_safe(root, (Node *) target->exprs))
2666 : {
2667 : /*
2668 : * We always use create_projection_path here, even if the subpath is
2669 : * projection-capable, so as to avoid modifying the subpath in place.
2670 : * It seems unlikely at present that there could be any other
2671 : * references to the subpath, but better safe than sorry.
2672 : *
2673 : * Note that we don't change the parallel path's cost estimates; it
2674 : * might be appropriate to do so, to reflect the fact that the bulk of
2675 : * the target evaluation will happen in workers.
2676 : */
2677 24 : if (IsA(path, GatherPath))
2678 : {
2679 0 : GatherPath *gpath = (GatherPath *) path;
2680 :
2681 0 : gpath->subpath = (Path *)
2682 0 : create_projection_path(root,
2683 0 : gpath->subpath->parent,
2684 : gpath->subpath,
2685 : target);
2686 : }
2687 : else
2688 : {
2689 24 : GatherMergePath *gmpath = (GatherMergePath *) path;
2690 :
2691 24 : gmpath->subpath = (Path *)
2692 24 : create_projection_path(root,
2693 24 : gmpath->subpath->parent,
2694 : gmpath->subpath,
2695 : target);
2696 : }
2697 : }
2698 12130 : else if (path->parallel_safe &&
2699 4614 : !is_parallel_safe(root, (Node *) target->exprs))
2700 : {
2701 : /*
2702 : * We're inserting a parallel-restricted target list into a path
2703 : * currently marked parallel-safe, so we have to mark it as no longer
2704 : * safe.
2705 : */
2706 12 : path->parallel_safe = false;
2707 : }
2708 :
2709 12154 : return path;
2710 : }
2711 :
2712 : /*
2713 : * create_set_projection_path
2714 : * Creates a pathnode that represents performing a projection that
2715 : * includes set-returning functions.
2716 : *
2717 : * 'rel' is the parent relation associated with the result
2718 : * 'subpath' is the path representing the source of data
2719 : * 'target' is the PathTarget to be computed
2720 : */
2721 : ProjectSetPath *
2722 11810 : create_set_projection_path(PlannerInfo *root,
2723 : RelOptInfo *rel,
2724 : Path *subpath,
2725 : PathTarget *target)
2726 : {
2727 11810 : ProjectSetPath *pathnode = makeNode(ProjectSetPath);
2728 : double tlist_rows;
2729 : ListCell *lc;
2730 :
2731 11810 : pathnode->path.pathtype = T_ProjectSet;
2732 11810 : pathnode->path.parent = rel;
2733 11810 : pathnode->path.pathtarget = target;
2734 : /* For now, assume we are above any joins, so no parameterization */
2735 11810 : pathnode->path.param_info = NULL;
2736 11810 : pathnode->path.parallel_aware = false;
2737 28066 : pathnode->path.parallel_safe = rel->consider_parallel &&
2738 16220 : subpath->parallel_safe &&
2739 4410 : is_parallel_safe(root, (Node *) target->exprs);
2740 11810 : pathnode->path.parallel_workers = subpath->parallel_workers;
2741 : /* Projection does not change the sort order XXX? */
2742 11810 : pathnode->path.pathkeys = subpath->pathkeys;
2743 :
2744 11810 : pathnode->subpath = subpath;
2745 :
2746 : /*
2747 : * Estimate number of rows produced by SRFs for each row of input; if
2748 : * there's more than one in this node, use the maximum.
2749 : */
2750 11810 : tlist_rows = 1;
2751 25616 : foreach(lc, target->exprs)
2752 : {
2753 13806 : Node *node = (Node *) lfirst(lc);
2754 : double itemrows;
2755 :
2756 13806 : itemrows = expression_returns_set_rows(root, node);
2757 13806 : if (tlist_rows < itemrows)
2758 11496 : tlist_rows = itemrows;
2759 : }
2760 :
2761 : /*
2762 : * In addition to the cost of evaluating the tlist, charge cpu_tuple_cost
2763 : * per input row, and half of cpu_tuple_cost for each added output row.
2764 : * This is slightly bizarre maybe, but it's what 9.6 did; we may revisit
2765 : * this estimate later.
2766 : */
2767 11810 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2768 11810 : pathnode->path.rows = subpath->rows * tlist_rows;
2769 11810 : pathnode->path.startup_cost = subpath->startup_cost +
2770 11810 : target->cost.startup;
2771 11810 : pathnode->path.total_cost = subpath->total_cost +
2772 11810 : target->cost.startup +
2773 11810 : (cpu_tuple_cost + target->cost.per_tuple) * subpath->rows +
2774 11810 : (pathnode->path.rows - subpath->rows) * cpu_tuple_cost / 2;
2775 :
2776 11810 : return pathnode;
2777 : }
2778 :
2779 : /*
2780 : * create_incremental_sort_path
2781 : * Creates a pathnode that represents performing an incremental sort.
2782 : *
2783 : * 'rel' is the parent relation associated with the result
2784 : * 'subpath' is the path representing the source of data
2785 : * 'pathkeys' represents the desired sort order
2786 : * 'presorted_keys' is the number of keys by which the input path is
2787 : * already sorted
2788 : * 'limit_tuples' is the estimated bound on the number of output tuples,
2789 : * or -1 if no LIMIT or couldn't estimate
2790 : */
2791 : IncrementalSortPath *
2792 10256 : create_incremental_sort_path(PlannerInfo *root,
2793 : RelOptInfo *rel,
2794 : Path *subpath,
2795 : List *pathkeys,
2796 : int presorted_keys,
2797 : double limit_tuples)
2798 : {
2799 10256 : IncrementalSortPath *sort = makeNode(IncrementalSortPath);
2800 10256 : SortPath *pathnode = &sort->spath;
2801 :
2802 10256 : pathnode->path.pathtype = T_IncrementalSort;
2803 10256 : pathnode->path.parent = rel;
2804 : /* Sort doesn't project, so use source path's pathtarget */
2805 10256 : pathnode->path.pathtarget = subpath->pathtarget;
2806 10256 : pathnode->path.param_info = subpath->param_info;
2807 10256 : pathnode->path.parallel_aware = false;
2808 15726 : pathnode->path.parallel_safe = rel->consider_parallel &&
2809 5470 : subpath->parallel_safe;
2810 10256 : pathnode->path.parallel_workers = subpath->parallel_workers;
2811 10256 : pathnode->path.pathkeys = pathkeys;
2812 :
2813 10256 : pathnode->subpath = subpath;
2814 :
2815 10256 : cost_incremental_sort(&pathnode->path,
2816 : root, pathkeys, presorted_keys,
2817 : subpath->disabled_nodes,
2818 : subpath->startup_cost,
2819 : subpath->total_cost,
2820 : subpath->rows,
2821 10256 : subpath->pathtarget->width,
2822 : 0.0, /* XXX comparison_cost shouldn't be 0? */
2823 : work_mem, limit_tuples);
2824 :
2825 10256 : sort->nPresortedCols = presorted_keys;
2826 :
2827 10256 : return sort;
2828 : }
2829 :
2830 : /*
2831 : * create_sort_path
2832 : * Creates a pathnode that represents performing an explicit sort.
2833 : *
2834 : * 'rel' is the parent relation associated with the result
2835 : * 'subpath' is the path representing the source of data
2836 : * 'pathkeys' represents the desired sort order
2837 : * 'limit_tuples' is the estimated bound on the number of output tuples,
2838 : * or -1 if no LIMIT or couldn't estimate
2839 : */
2840 : SortPath *
2841 116190 : create_sort_path(PlannerInfo *root,
2842 : RelOptInfo *rel,
2843 : Path *subpath,
2844 : List *pathkeys,
2845 : double limit_tuples)
2846 : {
2847 116190 : SortPath *pathnode = makeNode(SortPath);
2848 :
2849 116190 : pathnode->path.pathtype = T_Sort;
2850 116190 : pathnode->path.parent = rel;
2851 : /* Sort doesn't project, so use source path's pathtarget */
2852 116190 : pathnode->path.pathtarget = subpath->pathtarget;
2853 116190 : pathnode->path.param_info = subpath->param_info;
2854 116190 : pathnode->path.parallel_aware = false;
2855 202690 : pathnode->path.parallel_safe = rel->consider_parallel &&
2856 86500 : subpath->parallel_safe;
2857 116190 : pathnode->path.parallel_workers = subpath->parallel_workers;
2858 116190 : pathnode->path.pathkeys = pathkeys;
2859 :
2860 116190 : pathnode->subpath = subpath;
2861 :
2862 116190 : cost_sort(&pathnode->path, root, pathkeys,
2863 : subpath->disabled_nodes,
2864 : subpath->total_cost,
2865 : subpath->rows,
2866 116190 : subpath->pathtarget->width,
2867 : 0.0, /* XXX comparison_cost shouldn't be 0? */
2868 : work_mem, limit_tuples);
2869 :
2870 116190 : return pathnode;
2871 : }
2872 :
2873 : /*
2874 : * create_group_path
2875 : * Creates a pathnode that represents performing grouping of presorted input
2876 : *
2877 : * 'rel' is the parent relation associated with the result
2878 : * 'subpath' is the path representing the source of data
2879 : * 'target' is the PathTarget to be computed
2880 : * 'groupClause' is a list of SortGroupClause's representing the grouping
2881 : * 'qual' is the HAVING quals if any
2882 : * 'numGroups' is the estimated number of groups
2883 : */
2884 : GroupPath *
2885 1226 : create_group_path(PlannerInfo *root,
2886 : RelOptInfo *rel,
2887 : Path *subpath,
2888 : List *groupClause,
2889 : List *qual,
2890 : double numGroups)
2891 : {
2892 1226 : GroupPath *pathnode = makeNode(GroupPath);
2893 1226 : PathTarget *target = rel->reltarget;
2894 :
2895 1226 : pathnode->path.pathtype = T_Group;
2896 1226 : pathnode->path.parent = rel;
2897 1226 : pathnode->path.pathtarget = target;
2898 : /* For now, assume we are above any joins, so no parameterization */
2899 1226 : pathnode->path.param_info = NULL;
2900 1226 : pathnode->path.parallel_aware = false;
2901 1970 : pathnode->path.parallel_safe = rel->consider_parallel &&
2902 744 : subpath->parallel_safe;
2903 1226 : pathnode->path.parallel_workers = subpath->parallel_workers;
2904 : /* Group doesn't change sort ordering */
2905 1226 : pathnode->path.pathkeys = subpath->pathkeys;
2906 :
2907 1226 : pathnode->subpath = subpath;
2908 :
2909 1226 : pathnode->groupClause = groupClause;
2910 1226 : pathnode->qual = qual;
2911 :
2912 1226 : cost_group(&pathnode->path, root,
2913 : list_length(groupClause),
2914 : numGroups,
2915 : qual,
2916 : subpath->disabled_nodes,
2917 : subpath->startup_cost, subpath->total_cost,
2918 : subpath->rows);
2919 :
2920 : /* add tlist eval cost for each output row */
2921 1226 : pathnode->path.startup_cost += target->cost.startup;
2922 1226 : pathnode->path.total_cost += target->cost.startup +
2923 1226 : target->cost.per_tuple * pathnode->path.rows;
2924 :
2925 1226 : return pathnode;
2926 : }
2927 :
2928 : /*
2929 : * create_unique_path
2930 : * Creates a pathnode that represents performing an explicit Unique step
2931 : * on presorted input.
2932 : *
2933 : * 'rel' is the parent relation associated with the result
2934 : * 'subpath' is the path representing the source of data
2935 : * 'numCols' is the number of grouping columns
2936 : * 'numGroups' is the estimated number of groups
2937 : *
2938 : * The input path must be sorted on the grouping columns, plus possibly
2939 : * additional columns; so the first numCols pathkeys are the grouping columns
2940 : */
2941 : UniquePath *
2942 22386 : create_unique_path(PlannerInfo *root,
2943 : RelOptInfo *rel,
2944 : Path *subpath,
2945 : int numCols,
2946 : double numGroups)
2947 : {
2948 22386 : UniquePath *pathnode = makeNode(UniquePath);
2949 :
2950 22386 : pathnode->path.pathtype = T_Unique;
2951 22386 : pathnode->path.parent = rel;
2952 : /* Unique doesn't project, so use source path's pathtarget */
2953 22386 : pathnode->path.pathtarget = subpath->pathtarget;
2954 22386 : pathnode->path.param_info = subpath->param_info;
2955 22386 : pathnode->path.parallel_aware = false;
2956 40522 : pathnode->path.parallel_safe = rel->consider_parallel &&
2957 18136 : subpath->parallel_safe;
2958 22386 : pathnode->path.parallel_workers = subpath->parallel_workers;
2959 : /* Unique doesn't change the input ordering */
2960 22386 : pathnode->path.pathkeys = subpath->pathkeys;
2961 :
2962 22386 : pathnode->subpath = subpath;
2963 22386 : pathnode->numkeys = numCols;
2964 :
2965 : /*
2966 : * Charge one cpu_operator_cost per comparison per input tuple. We assume
2967 : * all columns get compared at most of the tuples. (XXX probably this is
2968 : * an overestimate.)
2969 : */
2970 22386 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
2971 22386 : pathnode->path.startup_cost = subpath->startup_cost;
2972 22386 : pathnode->path.total_cost = subpath->total_cost +
2973 22386 : cpu_operator_cost * subpath->rows * numCols;
2974 22386 : pathnode->path.rows = numGroups;
2975 :
2976 22386 : return pathnode;
2977 : }
2978 :
2979 : /*
2980 : * create_agg_path
2981 : * Creates a pathnode that represents performing aggregation/grouping
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 : * 'aggstrategy' is the Agg node's basic implementation strategy
2987 : * 'aggsplit' is the Agg node's aggregate-splitting mode
2988 : * 'groupClause' is a list of SortGroupClause's representing the grouping
2989 : * 'qual' is the HAVING quals if any
2990 : * 'aggcosts' contains cost info about the aggregate functions to be computed
2991 : * 'numGroups' is the estimated number of groups (1 if not grouping)
2992 : */
2993 : AggPath *
2994 80410 : create_agg_path(PlannerInfo *root,
2995 : RelOptInfo *rel,
2996 : Path *subpath,
2997 : PathTarget *target,
2998 : AggStrategy aggstrategy,
2999 : AggSplit aggsplit,
3000 : List *groupClause,
3001 : List *qual,
3002 : const AggClauseCosts *aggcosts,
3003 : double numGroups)
3004 : {
3005 80410 : AggPath *pathnode = makeNode(AggPath);
3006 :
3007 80410 : pathnode->path.pathtype = T_Agg;
3008 80410 : pathnode->path.parent = rel;
3009 80410 : pathnode->path.pathtarget = target;
3010 80410 : pathnode->path.param_info = subpath->param_info;
3011 80410 : pathnode->path.parallel_aware = false;
3012 140828 : pathnode->path.parallel_safe = rel->consider_parallel &&
3013 60418 : subpath->parallel_safe;
3014 80410 : pathnode->path.parallel_workers = subpath->parallel_workers;
3015 :
3016 80410 : if (aggstrategy == AGG_SORTED)
3017 : {
3018 : /*
3019 : * Attempt to preserve the order of the subpath. Additional pathkeys
3020 : * may have been added in adjust_group_pathkeys_for_groupagg() to
3021 : * support ORDER BY / DISTINCT aggregates. Pathkeys added there
3022 : * belong to columns within the aggregate function, so we must strip
3023 : * these additional pathkeys off as those columns are unavailable
3024 : * above the aggregate node.
3025 : */
3026 14020 : if (list_length(subpath->pathkeys) > root->num_groupby_pathkeys)
3027 808 : pathnode->path.pathkeys = list_copy_head(subpath->pathkeys,
3028 : root->num_groupby_pathkeys);
3029 : else
3030 13212 : pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */
3031 : }
3032 : else
3033 66390 : pathnode->path.pathkeys = NIL; /* output is unordered */
3034 :
3035 80410 : pathnode->subpath = subpath;
3036 :
3037 80410 : pathnode->aggstrategy = aggstrategy;
3038 80410 : pathnode->aggsplit = aggsplit;
3039 80410 : pathnode->numGroups = numGroups;
3040 80410 : pathnode->transitionSpace = aggcosts ? aggcosts->transitionSpace : 0;
3041 80410 : pathnode->groupClause = groupClause;
3042 80410 : pathnode->qual = qual;
3043 :
3044 80410 : cost_agg(&pathnode->path, root,
3045 : aggstrategy, aggcosts,
3046 : list_length(groupClause), numGroups,
3047 : qual,
3048 : subpath->disabled_nodes,
3049 : subpath->startup_cost, subpath->total_cost,
3050 80410 : subpath->rows, subpath->pathtarget->width);
3051 :
3052 : /* add tlist eval cost for each output row */
3053 80410 : pathnode->path.startup_cost += target->cost.startup;
3054 80410 : pathnode->path.total_cost += target->cost.startup +
3055 80410 : target->cost.per_tuple * pathnode->path.rows;
3056 :
3057 80410 : return pathnode;
3058 : }
3059 :
3060 : /*
3061 : * create_groupingsets_path
3062 : * Creates a pathnode that represents performing GROUPING SETS aggregation
3063 : *
3064 : * GroupingSetsPath represents sorted grouping with one or more grouping sets.
3065 : * The input path's result must be sorted to match the last entry in
3066 : * rollup_groupclauses.
3067 : *
3068 : * 'rel' is the parent relation associated with the result
3069 : * 'subpath' is the path representing the source of data
3070 : * 'target' is the PathTarget to be computed
3071 : * 'having_qual' is the HAVING quals if any
3072 : * 'rollups' is a list of RollupData nodes
3073 : * 'agg_costs' contains cost info about the aggregate functions to be computed
3074 : */
3075 : GroupingSetsPath *
3076 2230 : create_groupingsets_path(PlannerInfo *root,
3077 : RelOptInfo *rel,
3078 : Path *subpath,
3079 : List *having_qual,
3080 : AggStrategy aggstrategy,
3081 : List *rollups,
3082 : const AggClauseCosts *agg_costs)
3083 : {
3084 2230 : GroupingSetsPath *pathnode = makeNode(GroupingSetsPath);
3085 2230 : PathTarget *target = rel->reltarget;
3086 : ListCell *lc;
3087 2230 : bool is_first = true;
3088 2230 : bool is_first_sort = true;
3089 :
3090 : /* The topmost generated Plan node will be an Agg */
3091 2230 : pathnode->path.pathtype = T_Agg;
3092 2230 : pathnode->path.parent = rel;
3093 2230 : pathnode->path.pathtarget = target;
3094 2230 : pathnode->path.param_info = subpath->param_info;
3095 2230 : pathnode->path.parallel_aware = false;
3096 3220 : pathnode->path.parallel_safe = rel->consider_parallel &&
3097 990 : subpath->parallel_safe;
3098 2230 : pathnode->path.parallel_workers = subpath->parallel_workers;
3099 2230 : pathnode->subpath = subpath;
3100 :
3101 : /*
3102 : * Simplify callers by downgrading AGG_SORTED to AGG_PLAIN, and AGG_MIXED
3103 : * to AGG_HASHED, here if possible.
3104 : */
3105 3192 : if (aggstrategy == AGG_SORTED &&
3106 962 : list_length(rollups) == 1 &&
3107 500 : ((RollupData *) linitial(rollups))->groupClause == NIL)
3108 60 : aggstrategy = AGG_PLAIN;
3109 :
3110 3170 : if (aggstrategy == AGG_MIXED &&
3111 940 : list_length(rollups) == 1)
3112 0 : aggstrategy = AGG_HASHED;
3113 :
3114 : /*
3115 : * Output will be in sorted order by group_pathkeys if, and only if, there
3116 : * is a single rollup operation on a non-empty list of grouping
3117 : * expressions.
3118 : */
3119 2230 : if (aggstrategy == AGG_SORTED && list_length(rollups) == 1)
3120 440 : pathnode->path.pathkeys = root->group_pathkeys;
3121 : else
3122 1790 : pathnode->path.pathkeys = NIL;
3123 :
3124 2230 : pathnode->aggstrategy = aggstrategy;
3125 2230 : pathnode->rollups = rollups;
3126 2230 : pathnode->qual = having_qual;
3127 2230 : pathnode->transitionSpace = agg_costs ? agg_costs->transitionSpace : 0;
3128 :
3129 : Assert(rollups != NIL);
3130 : Assert(aggstrategy != AGG_PLAIN || list_length(rollups) == 1);
3131 : Assert(aggstrategy != AGG_MIXED || list_length(rollups) > 1);
3132 :
3133 7680 : foreach(lc, rollups)
3134 : {
3135 5450 : RollupData *rollup = lfirst(lc);
3136 5450 : List *gsets = rollup->gsets;
3137 5450 : int numGroupCols = list_length(linitial(gsets));
3138 :
3139 : /*
3140 : * In AGG_SORTED or AGG_PLAIN mode, the first rollup takes the
3141 : * (already-sorted) input, and following ones do their own sort.
3142 : *
3143 : * In AGG_HASHED mode, there is one rollup for each grouping set.
3144 : *
3145 : * In AGG_MIXED mode, the first rollups are hashed, the first
3146 : * non-hashed one takes the (already-sorted) input, and following ones
3147 : * do their own sort.
3148 : */
3149 5450 : if (is_first)
3150 : {
3151 2230 : cost_agg(&pathnode->path, root,
3152 : aggstrategy,
3153 : agg_costs,
3154 : numGroupCols,
3155 : rollup->numGroups,
3156 : having_qual,
3157 : subpath->disabled_nodes,
3158 : subpath->startup_cost,
3159 : subpath->total_cost,
3160 : subpath->rows,
3161 2230 : subpath->pathtarget->width);
3162 2230 : is_first = false;
3163 2230 : if (!rollup->is_hashed)
3164 962 : is_first_sort = false;
3165 : }
3166 : else
3167 : {
3168 : Path sort_path; /* dummy for result of cost_sort */
3169 : Path agg_path; /* dummy for result of cost_agg */
3170 :
3171 3220 : if (rollup->is_hashed || is_first_sort)
3172 : {
3173 : /*
3174 : * Account for cost of aggregation, but don't charge input
3175 : * cost again
3176 : */
3177 2470 : cost_agg(&agg_path, root,
3178 2470 : rollup->is_hashed ? AGG_HASHED : AGG_SORTED,
3179 : agg_costs,
3180 : numGroupCols,
3181 : rollup->numGroups,
3182 : having_qual,
3183 : 0, 0.0, 0.0,
3184 : subpath->rows,
3185 2470 : subpath->pathtarget->width);
3186 2470 : if (!rollup->is_hashed)
3187 940 : is_first_sort = false;
3188 : }
3189 : else
3190 : {
3191 : /* Account for cost of sort, but don't charge input cost again */
3192 750 : cost_sort(&sort_path, root, NIL, 0,
3193 : 0.0,
3194 : subpath->rows,
3195 750 : subpath->pathtarget->width,
3196 : 0.0,
3197 : work_mem,
3198 : -1.0);
3199 :
3200 : /* Account for cost of aggregation */
3201 :
3202 750 : cost_agg(&agg_path, root,
3203 : AGG_SORTED,
3204 : agg_costs,
3205 : numGroupCols,
3206 : rollup->numGroups,
3207 : having_qual,
3208 : sort_path.disabled_nodes,
3209 : sort_path.startup_cost,
3210 : sort_path.total_cost,
3211 : sort_path.rows,
3212 750 : subpath->pathtarget->width);
3213 : }
3214 :
3215 3220 : pathnode->path.disabled_nodes += agg_path.disabled_nodes;
3216 3220 : pathnode->path.total_cost += agg_path.total_cost;
3217 3220 : pathnode->path.rows += agg_path.rows;
3218 : }
3219 : }
3220 :
3221 : /* add tlist eval cost for each output row */
3222 2230 : pathnode->path.startup_cost += target->cost.startup;
3223 2230 : pathnode->path.total_cost += target->cost.startup +
3224 2230 : target->cost.per_tuple * pathnode->path.rows;
3225 :
3226 2230 : return pathnode;
3227 : }
3228 :
3229 : /*
3230 : * create_minmaxagg_path
3231 : * Creates a pathnode that represents computation of MIN/MAX aggregates
3232 : *
3233 : * 'rel' is the parent relation associated with the result
3234 : * 'target' is the PathTarget to be computed
3235 : * 'mmaggregates' is a list of MinMaxAggInfo structs
3236 : * 'quals' is the HAVING quals if any
3237 : */
3238 : MinMaxAggPath *
3239 410 : create_minmaxagg_path(PlannerInfo *root,
3240 : RelOptInfo *rel,
3241 : PathTarget *target,
3242 : List *mmaggregates,
3243 : List *quals)
3244 : {
3245 410 : MinMaxAggPath *pathnode = makeNode(MinMaxAggPath);
3246 : Cost initplan_cost;
3247 410 : int initplan_disabled_nodes = 0;
3248 : ListCell *lc;
3249 :
3250 : /* The topmost generated Plan node will be a Result */
3251 410 : pathnode->path.pathtype = T_Result;
3252 410 : pathnode->path.parent = rel;
3253 410 : pathnode->path.pathtarget = target;
3254 : /* For now, assume we are above any joins, so no parameterization */
3255 410 : pathnode->path.param_info = NULL;
3256 410 : pathnode->path.parallel_aware = false;
3257 410 : pathnode->path.parallel_safe = true; /* might change below */
3258 410 : pathnode->path.parallel_workers = 0;
3259 : /* Result is one unordered row */
3260 410 : pathnode->path.rows = 1;
3261 410 : pathnode->path.pathkeys = NIL;
3262 :
3263 410 : pathnode->mmaggregates = mmaggregates;
3264 410 : pathnode->quals = quals;
3265 :
3266 : /* Calculate cost of all the initplans, and check parallel safety */
3267 410 : initplan_cost = 0;
3268 856 : foreach(lc, mmaggregates)
3269 : {
3270 446 : MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3271 :
3272 446 : initplan_disabled_nodes += mminfo->path->disabled_nodes;
3273 446 : initplan_cost += mminfo->pathcost;
3274 446 : if (!mminfo->path->parallel_safe)
3275 110 : pathnode->path.parallel_safe = false;
3276 : }
3277 :
3278 : /* add tlist eval cost for each output row, plus cpu_tuple_cost */
3279 410 : pathnode->path.disabled_nodes = initplan_disabled_nodes;
3280 410 : pathnode->path.startup_cost = initplan_cost + target->cost.startup;
3281 410 : pathnode->path.total_cost = initplan_cost + target->cost.startup +
3282 410 : target->cost.per_tuple + cpu_tuple_cost;
3283 :
3284 : /*
3285 : * Add cost of qual, if any --- but we ignore its selectivity, since our
3286 : * rowcount estimate should be 1 no matter what the qual is.
3287 : */
3288 410 : if (quals)
3289 : {
3290 : QualCost qual_cost;
3291 :
3292 0 : cost_qual_eval(&qual_cost, quals, root);
3293 0 : pathnode->path.startup_cost += qual_cost.startup;
3294 0 : pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
3295 : }
3296 :
3297 : /*
3298 : * If the initplans were all parallel-safe, also check safety of the
3299 : * target and quals. (The Result node itself isn't parallelizable, but if
3300 : * we are in a subquery then it can be useful for the outer query to know
3301 : * that this one is parallel-safe.)
3302 : */
3303 410 : if (pathnode->path.parallel_safe)
3304 300 : pathnode->path.parallel_safe =
3305 600 : is_parallel_safe(root, (Node *) target->exprs) &&
3306 300 : is_parallel_safe(root, (Node *) quals);
3307 :
3308 410 : return pathnode;
3309 : }
3310 :
3311 : /*
3312 : * create_windowagg_path
3313 : * Creates a pathnode that represents computation of window functions
3314 : *
3315 : * 'rel' is the parent relation associated with the result
3316 : * 'subpath' is the path representing the source of data
3317 : * 'target' is the PathTarget to be computed
3318 : * 'windowFuncs' is a list of WindowFunc structs
3319 : * 'runCondition' is a list of OpExprs to short-circuit WindowAgg execution
3320 : * 'winclause' is a WindowClause that is common to all the WindowFuncs
3321 : * 'qual' WindowClause.runconditions from lower-level WindowAggPaths.
3322 : * Must always be NIL when topwindow == false
3323 : * 'topwindow' pass as true only for the top-level WindowAgg. False for all
3324 : * intermediate WindowAggs.
3325 : *
3326 : * The input must be sorted according to the WindowClause's PARTITION keys
3327 : * plus ORDER BY keys.
3328 : */
3329 : WindowAggPath *
3330 2964 : create_windowagg_path(PlannerInfo *root,
3331 : RelOptInfo *rel,
3332 : Path *subpath,
3333 : PathTarget *target,
3334 : List *windowFuncs,
3335 : List *runCondition,
3336 : WindowClause *winclause,
3337 : List *qual,
3338 : bool topwindow)
3339 : {
3340 2964 : WindowAggPath *pathnode = makeNode(WindowAggPath);
3341 :
3342 : /* qual can only be set for the topwindow */
3343 : Assert(qual == NIL || topwindow);
3344 :
3345 2964 : pathnode->path.pathtype = T_WindowAgg;
3346 2964 : pathnode->path.parent = rel;
3347 2964 : pathnode->path.pathtarget = target;
3348 : /* For now, assume we are above any joins, so no parameterization */
3349 2964 : pathnode->path.param_info = NULL;
3350 2964 : pathnode->path.parallel_aware = false;
3351 2964 : pathnode->path.parallel_safe = rel->consider_parallel &&
3352 0 : subpath->parallel_safe;
3353 2964 : pathnode->path.parallel_workers = subpath->parallel_workers;
3354 : /* WindowAgg preserves the input sort order */
3355 2964 : pathnode->path.pathkeys = subpath->pathkeys;
3356 :
3357 2964 : pathnode->subpath = subpath;
3358 2964 : pathnode->winclause = winclause;
3359 2964 : pathnode->qual = qual;
3360 2964 : pathnode->runCondition = runCondition;
3361 2964 : pathnode->topwindow = topwindow;
3362 :
3363 : /*
3364 : * For costing purposes, assume that there are no redundant partitioning
3365 : * or ordering columns; it's not worth the trouble to deal with that
3366 : * corner case here. So we just pass the unmodified list lengths to
3367 : * cost_windowagg.
3368 : */
3369 2964 : cost_windowagg(&pathnode->path, root,
3370 : windowFuncs,
3371 : winclause,
3372 : subpath->disabled_nodes,
3373 : subpath->startup_cost,
3374 : subpath->total_cost,
3375 : subpath->rows);
3376 :
3377 : /* add tlist eval cost for each output row */
3378 2964 : pathnode->path.startup_cost += target->cost.startup;
3379 2964 : pathnode->path.total_cost += target->cost.startup +
3380 2964 : target->cost.per_tuple * pathnode->path.rows;
3381 :
3382 2964 : return pathnode;
3383 : }
3384 :
3385 : /*
3386 : * create_setop_path
3387 : * Creates a pathnode that represents computation of INTERSECT or EXCEPT
3388 : *
3389 : * 'rel' is the parent relation associated with the result
3390 : * 'leftpath' is the path representing the left-hand source of data
3391 : * 'rightpath' is the path representing the right-hand source of data
3392 : * 'cmd' is the specific semantics (INTERSECT or EXCEPT, with/without ALL)
3393 : * 'strategy' is the implementation strategy (sorted or hashed)
3394 : * 'groupList' is a list of SortGroupClause's representing the grouping
3395 : * 'numGroups' is the estimated number of distinct groups in left-hand input
3396 : * 'outputRows' is the estimated number of output rows
3397 : *
3398 : * leftpath and rightpath must produce the same columns. Moreover, if
3399 : * strategy is SETOP_SORTED, leftpath and rightpath must both be sorted
3400 : * by all the grouping columns.
3401 : */
3402 : SetOpPath *
3403 1276 : create_setop_path(PlannerInfo *root,
3404 : RelOptInfo *rel,
3405 : Path *leftpath,
3406 : Path *rightpath,
3407 : SetOpCmd cmd,
3408 : SetOpStrategy strategy,
3409 : List *groupList,
3410 : double numGroups,
3411 : double outputRows)
3412 : {
3413 1276 : SetOpPath *pathnode = makeNode(SetOpPath);
3414 :
3415 1276 : pathnode->path.pathtype = T_SetOp;
3416 1276 : pathnode->path.parent = rel;
3417 1276 : pathnode->path.pathtarget = rel->reltarget;
3418 : /* For now, assume we are above any joins, so no parameterization */
3419 1276 : pathnode->path.param_info = NULL;
3420 1276 : pathnode->path.parallel_aware = false;
3421 2552 : pathnode->path.parallel_safe = rel->consider_parallel &&
3422 1276 : leftpath->parallel_safe && rightpath->parallel_safe;
3423 1276 : pathnode->path.parallel_workers =
3424 1276 : leftpath->parallel_workers + rightpath->parallel_workers;
3425 : /* SetOp preserves the input sort order if in sort mode */
3426 1276 : pathnode->path.pathkeys =
3427 1276 : (strategy == SETOP_SORTED) ? leftpath->pathkeys : NIL;
3428 :
3429 1276 : pathnode->leftpath = leftpath;
3430 1276 : pathnode->rightpath = rightpath;
3431 1276 : pathnode->cmd = cmd;
3432 1276 : pathnode->strategy = strategy;
3433 1276 : pathnode->groupList = groupList;
3434 1276 : pathnode->numGroups = numGroups;
3435 :
3436 : /*
3437 : * Compute cost estimates. As things stand, we end up with the same total
3438 : * cost in this node for sort and hash methods, but different startup
3439 : * costs. This could be refined perhaps, but it'll do for now.
3440 : */
3441 1276 : pathnode->path.disabled_nodes =
3442 1276 : leftpath->disabled_nodes + rightpath->disabled_nodes;
3443 1276 : if (strategy == SETOP_SORTED)
3444 : {
3445 : /*
3446 : * In sorted mode, we can emit output incrementally. Charge one
3447 : * cpu_operator_cost per comparison per input tuple. Like cost_group,
3448 : * we assume all columns get compared at most of the tuples.
3449 : */
3450 668 : pathnode->path.startup_cost =
3451 668 : leftpath->startup_cost + rightpath->startup_cost;
3452 668 : pathnode->path.total_cost =
3453 1336 : leftpath->total_cost + rightpath->total_cost +
3454 668 : cpu_operator_cost * (leftpath->rows + rightpath->rows) * list_length(groupList);
3455 :
3456 : /*
3457 : * Also charge a small amount per extracted tuple. Like cost_sort,
3458 : * charge only operator cost not cpu_tuple_cost, since SetOp does no
3459 : * qual-checking or projection.
3460 : */
3461 668 : pathnode->path.total_cost += cpu_operator_cost * outputRows;
3462 : }
3463 : else
3464 : {
3465 : Size hashtablesize;
3466 :
3467 : /*
3468 : * In hashed mode, we must read all the input before we can emit
3469 : * anything. Also charge comparison costs to represent the cost of
3470 : * hash table lookups.
3471 : */
3472 608 : pathnode->path.startup_cost =
3473 1216 : leftpath->total_cost + rightpath->total_cost +
3474 608 : cpu_operator_cost * (leftpath->rows + rightpath->rows) * list_length(groupList);
3475 608 : pathnode->path.total_cost = pathnode->path.startup_cost;
3476 :
3477 : /*
3478 : * Also charge a small amount per extracted tuple. Like cost_sort,
3479 : * charge only operator cost not cpu_tuple_cost, since SetOp does no
3480 : * qual-checking or projection.
3481 : */
3482 608 : pathnode->path.total_cost += cpu_operator_cost * outputRows;
3483 :
3484 : /*
3485 : * Mark the path as disabled if enable_hashagg is off. While this
3486 : * isn't exactly a HashAgg node, it seems close enough to justify
3487 : * letting that switch control it.
3488 : */
3489 608 : if (!enable_hashagg)
3490 114 : pathnode->path.disabled_nodes++;
3491 :
3492 : /*
3493 : * Also disable if it doesn't look like the hashtable will fit into
3494 : * hash_mem. (Note: reject on equality, to ensure that an estimate of
3495 : * SIZE_MAX disables hashing regardless of the hash_mem limit.)
3496 : */
3497 608 : hashtablesize = EstimateSetOpHashTableSpace(numGroups,
3498 608 : leftpath->pathtarget->width);
3499 608 : if (hashtablesize >= get_hash_memory_limit())
3500 0 : pathnode->path.disabled_nodes++;
3501 : }
3502 1276 : pathnode->path.rows = outputRows;
3503 :
3504 1276 : return pathnode;
3505 : }
3506 :
3507 : /*
3508 : * create_recursiveunion_path
3509 : * Creates a pathnode that represents a recursive UNION node
3510 : *
3511 : * 'rel' is the parent relation associated with the result
3512 : * 'leftpath' is the source of data for the non-recursive term
3513 : * 'rightpath' is the source of data for the recursive term
3514 : * 'target' is the PathTarget to be computed
3515 : * 'distinctList' is a list of SortGroupClause's representing the grouping
3516 : * 'wtParam' is the ID of Param representing work table
3517 : * 'numGroups' is the estimated number of groups
3518 : *
3519 : * For recursive UNION ALL, distinctList is empty and numGroups is zero
3520 : */
3521 : RecursiveUnionPath *
3522 928 : create_recursiveunion_path(PlannerInfo *root,
3523 : RelOptInfo *rel,
3524 : Path *leftpath,
3525 : Path *rightpath,
3526 : PathTarget *target,
3527 : List *distinctList,
3528 : int wtParam,
3529 : double numGroups)
3530 : {
3531 928 : RecursiveUnionPath *pathnode = makeNode(RecursiveUnionPath);
3532 :
3533 928 : pathnode->path.pathtype = T_RecursiveUnion;
3534 928 : pathnode->path.parent = rel;
3535 928 : pathnode->path.pathtarget = target;
3536 : /* For now, assume we are above any joins, so no parameterization */
3537 928 : pathnode->path.param_info = NULL;
3538 928 : pathnode->path.parallel_aware = false;
3539 1856 : pathnode->path.parallel_safe = rel->consider_parallel &&
3540 928 : leftpath->parallel_safe && rightpath->parallel_safe;
3541 : /* Foolish, but we'll do it like joins for now: */
3542 928 : pathnode->path.parallel_workers = leftpath->parallel_workers;
3543 : /* RecursiveUnion result is always unsorted */
3544 928 : pathnode->path.pathkeys = NIL;
3545 :
3546 928 : pathnode->leftpath = leftpath;
3547 928 : pathnode->rightpath = rightpath;
3548 928 : pathnode->distinctList = distinctList;
3549 928 : pathnode->wtParam = wtParam;
3550 928 : pathnode->numGroups = numGroups;
3551 :
3552 928 : cost_recursive_union(&pathnode->path, leftpath, rightpath);
3553 :
3554 928 : return pathnode;
3555 : }
3556 :
3557 : /*
3558 : * create_lockrows_path
3559 : * Creates a pathnode that represents acquiring row locks
3560 : *
3561 : * 'rel' is the parent relation associated with the result
3562 : * 'subpath' is the path representing the source of data
3563 : * 'rowMarks' is a list of PlanRowMark's
3564 : * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3565 : */
3566 : LockRowsPath *
3567 8380 : create_lockrows_path(PlannerInfo *root, RelOptInfo *rel,
3568 : Path *subpath, List *rowMarks, int epqParam)
3569 : {
3570 8380 : LockRowsPath *pathnode = makeNode(LockRowsPath);
3571 :
3572 8380 : pathnode->path.pathtype = T_LockRows;
3573 8380 : pathnode->path.parent = rel;
3574 : /* LockRows doesn't project, so use source path's pathtarget */
3575 8380 : pathnode->path.pathtarget = subpath->pathtarget;
3576 : /* For now, assume we are above any joins, so no parameterization */
3577 8380 : pathnode->path.param_info = NULL;
3578 8380 : pathnode->path.parallel_aware = false;
3579 8380 : pathnode->path.parallel_safe = false;
3580 8380 : pathnode->path.parallel_workers = 0;
3581 8380 : pathnode->path.rows = subpath->rows;
3582 :
3583 : /*
3584 : * The result cannot be assumed sorted, since locking might cause the sort
3585 : * key columns to be replaced with new values.
3586 : */
3587 8380 : pathnode->path.pathkeys = NIL;
3588 :
3589 8380 : pathnode->subpath = subpath;
3590 8380 : pathnode->rowMarks = rowMarks;
3591 8380 : pathnode->epqParam = epqParam;
3592 :
3593 : /*
3594 : * We should charge something extra for the costs of row locking and
3595 : * possible refetches, but it's hard to say how much. For now, use
3596 : * cpu_tuple_cost per row.
3597 : */
3598 8380 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
3599 8380 : pathnode->path.startup_cost = subpath->startup_cost;
3600 8380 : pathnode->path.total_cost = subpath->total_cost +
3601 8380 : cpu_tuple_cost * subpath->rows;
3602 :
3603 8380 : return pathnode;
3604 : }
3605 :
3606 : /*
3607 : * create_modifytable_path
3608 : * Creates a pathnode that represents performing INSERT/UPDATE/DELETE/MERGE
3609 : * mods
3610 : *
3611 : * 'rel' is the parent relation associated with the result
3612 : * 'subpath' is a Path producing source data
3613 : * 'operation' is the operation type
3614 : * 'canSetTag' is true if we set the command tag/es_processed
3615 : * 'nominalRelation' is the parent RT index for use of EXPLAIN
3616 : * 'rootRelation' is the partitioned/inherited table root RTI, or 0 if none
3617 : * 'resultRelations' is an integer list of actual RT indexes of target rel(s)
3618 : * 'updateColnosLists' is a list of UPDATE target column number lists
3619 : * (one sublist per rel); or NIL if not an UPDATE
3620 : * 'withCheckOptionLists' is a list of WCO lists (one per rel)
3621 : * 'returningLists' is a list of RETURNING tlists (one per rel)
3622 : * 'rowMarks' is a list of PlanRowMarks (non-locking only)
3623 : * 'onconflict' is the ON CONFLICT clause, or NULL
3624 : * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3625 : * 'mergeActionLists' is a list of lists of MERGE actions (one per rel)
3626 : * 'mergeJoinConditions' is a list of join conditions for MERGE (one per rel)
3627 : */
3628 : ModifyTablePath *
3629 87510 : create_modifytable_path(PlannerInfo *root, RelOptInfo *rel,
3630 : Path *subpath,
3631 : CmdType operation, bool canSetTag,
3632 : Index nominalRelation, Index rootRelation,
3633 : List *resultRelations,
3634 : List *updateColnosLists,
3635 : List *withCheckOptionLists, List *returningLists,
3636 : List *rowMarks, OnConflictExpr *onconflict,
3637 : List *mergeActionLists, List *mergeJoinConditions,
3638 : int epqParam)
3639 : {
3640 87510 : ModifyTablePath *pathnode = makeNode(ModifyTablePath);
3641 :
3642 : Assert(operation == CMD_MERGE ||
3643 : (operation == CMD_UPDATE ?
3644 : list_length(resultRelations) == list_length(updateColnosLists) :
3645 : updateColnosLists == NIL));
3646 : Assert(withCheckOptionLists == NIL ||
3647 : list_length(resultRelations) == list_length(withCheckOptionLists));
3648 : Assert(returningLists == NIL ||
3649 : list_length(resultRelations) == list_length(returningLists));
3650 :
3651 87510 : pathnode->path.pathtype = T_ModifyTable;
3652 87510 : pathnode->path.parent = rel;
3653 : /* pathtarget is not interesting, just make it minimally valid */
3654 87510 : pathnode->path.pathtarget = rel->reltarget;
3655 : /* For now, assume we are above any joins, so no parameterization */
3656 87510 : pathnode->path.param_info = NULL;
3657 87510 : pathnode->path.parallel_aware = false;
3658 87510 : pathnode->path.parallel_safe = false;
3659 87510 : pathnode->path.parallel_workers = 0;
3660 87510 : pathnode->path.pathkeys = NIL;
3661 :
3662 : /*
3663 : * Compute cost & rowcount as subpath cost & rowcount (if RETURNING)
3664 : *
3665 : * Currently, we don't charge anything extra for the actual table
3666 : * modification work, nor for the WITH CHECK OPTIONS or RETURNING
3667 : * expressions if any. It would only be window dressing, since
3668 : * ModifyTable is always a top-level node and there is no way for the
3669 : * costs to change any higher-level planning choices. But we might want
3670 : * to make it look better sometime.
3671 : */
3672 87510 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
3673 87510 : pathnode->path.startup_cost = subpath->startup_cost;
3674 87510 : pathnode->path.total_cost = subpath->total_cost;
3675 87510 : if (returningLists != NIL)
3676 : {
3677 2964 : pathnode->path.rows = subpath->rows;
3678 :
3679 : /*
3680 : * Set width to match the subpath output. XXX this is totally wrong:
3681 : * we should return an average of the RETURNING tlist widths. But
3682 : * it's what happened historically, and improving it is a task for
3683 : * another day. (Again, it's mostly window dressing.)
3684 : */
3685 2964 : pathnode->path.pathtarget->width = subpath->pathtarget->width;
3686 : }
3687 : else
3688 : {
3689 84546 : pathnode->path.rows = 0;
3690 84546 : pathnode->path.pathtarget->width = 0;
3691 : }
3692 :
3693 87510 : pathnode->subpath = subpath;
3694 87510 : pathnode->operation = operation;
3695 87510 : pathnode->canSetTag = canSetTag;
3696 87510 : pathnode->nominalRelation = nominalRelation;
3697 87510 : pathnode->rootRelation = rootRelation;
3698 87510 : pathnode->resultRelations = resultRelations;
3699 87510 : pathnode->updateColnosLists = updateColnosLists;
3700 87510 : pathnode->withCheckOptionLists = withCheckOptionLists;
3701 87510 : pathnode->returningLists = returningLists;
3702 87510 : pathnode->rowMarks = rowMarks;
3703 87510 : pathnode->onconflict = onconflict;
3704 87510 : pathnode->epqParam = epqParam;
3705 87510 : pathnode->mergeActionLists = mergeActionLists;
3706 87510 : pathnode->mergeJoinConditions = mergeJoinConditions;
3707 :
3708 87510 : return pathnode;
3709 : }
3710 :
3711 : /*
3712 : * create_limit_path
3713 : * Creates a pathnode that represents performing LIMIT/OFFSET
3714 : *
3715 : * In addition to providing the actual OFFSET and LIMIT expressions,
3716 : * the caller must provide estimates of their values for costing purposes.
3717 : * The estimates are as computed by preprocess_limit(), ie, 0 represents
3718 : * the clause not being present, and -1 means it's present but we could
3719 : * not estimate its value.
3720 : *
3721 : * 'rel' is the parent relation associated with the result
3722 : * 'subpath' is the path representing the source of data
3723 : * 'limitOffset' is the actual OFFSET expression, or NULL
3724 : * 'limitCount' is the actual LIMIT expression, or NULL
3725 : * 'offset_est' is the estimated value of the OFFSET expression
3726 : * 'count_est' is the estimated value of the LIMIT expression
3727 : */
3728 : LimitPath *
3729 6080 : create_limit_path(PlannerInfo *root, RelOptInfo *rel,
3730 : Path *subpath,
3731 : Node *limitOffset, Node *limitCount,
3732 : LimitOption limitOption,
3733 : int64 offset_est, int64 count_est)
3734 : {
3735 6080 : LimitPath *pathnode = makeNode(LimitPath);
3736 :
3737 6080 : pathnode->path.pathtype = T_Limit;
3738 6080 : pathnode->path.parent = rel;
3739 : /* Limit doesn't project, so use source path's pathtarget */
3740 6080 : pathnode->path.pathtarget = subpath->pathtarget;
3741 : /* For now, assume we are above any joins, so no parameterization */
3742 6080 : pathnode->path.param_info = NULL;
3743 6080 : pathnode->path.parallel_aware = false;
3744 8526 : pathnode->path.parallel_safe = rel->consider_parallel &&
3745 2446 : subpath->parallel_safe;
3746 6080 : pathnode->path.parallel_workers = subpath->parallel_workers;
3747 6080 : pathnode->path.rows = subpath->rows;
3748 6080 : pathnode->path.disabled_nodes = subpath->disabled_nodes;
3749 6080 : pathnode->path.startup_cost = subpath->startup_cost;
3750 6080 : pathnode->path.total_cost = subpath->total_cost;
3751 6080 : pathnode->path.pathkeys = subpath->pathkeys;
3752 6080 : pathnode->subpath = subpath;
3753 6080 : pathnode->limitOffset = limitOffset;
3754 6080 : pathnode->limitCount = limitCount;
3755 6080 : pathnode->limitOption = limitOption;
3756 :
3757 : /*
3758 : * Adjust the output rows count and costs according to the offset/limit.
3759 : */
3760 6080 : adjust_limit_rows_costs(&pathnode->path.rows,
3761 : &pathnode->path.startup_cost,
3762 : &pathnode->path.total_cost,
3763 : offset_est, count_est);
3764 :
3765 6080 : return pathnode;
3766 : }
3767 :
3768 : /*
3769 : * adjust_limit_rows_costs
3770 : * Adjust the size and cost estimates for a LimitPath node according to the
3771 : * offset/limit.
3772 : *
3773 : * This is only a cosmetic issue if we are at top level, but if we are
3774 : * building a subquery then it's important to report correct info to the outer
3775 : * planner.
3776 : *
3777 : * When the offset or count couldn't be estimated, use 10% of the estimated
3778 : * number of rows emitted from the subpath.
3779 : *
3780 : * XXX we don't bother to add eval costs of the offset/limit expressions
3781 : * themselves to the path costs. In theory we should, but in most cases those
3782 : * expressions are trivial and it's just not worth the trouble.
3783 : */
3784 : void
3785 6264 : adjust_limit_rows_costs(double *rows, /* in/out parameter */
3786 : Cost *startup_cost, /* in/out parameter */
3787 : Cost *total_cost, /* in/out parameter */
3788 : int64 offset_est,
3789 : int64 count_est)
3790 : {
3791 6264 : double input_rows = *rows;
3792 6264 : Cost input_startup_cost = *startup_cost;
3793 6264 : Cost input_total_cost = *total_cost;
3794 :
3795 6264 : if (offset_est != 0)
3796 : {
3797 : double offset_rows;
3798 :
3799 710 : if (offset_est > 0)
3800 686 : offset_rows = (double) offset_est;
3801 : else
3802 24 : offset_rows = clamp_row_est(input_rows * 0.10);
3803 710 : if (offset_rows > *rows)
3804 38 : offset_rows = *rows;
3805 710 : if (input_rows > 0)
3806 710 : *startup_cost +=
3807 710 : (input_total_cost - input_startup_cost)
3808 710 : * offset_rows / input_rows;
3809 710 : *rows -= offset_rows;
3810 710 : if (*rows < 1)
3811 46 : *rows = 1;
3812 : }
3813 :
3814 6264 : if (count_est != 0)
3815 : {
3816 : double count_rows;
3817 :
3818 6190 : if (count_est > 0)
3819 6184 : count_rows = (double) count_est;
3820 : else
3821 6 : count_rows = clamp_row_est(input_rows * 0.10);
3822 6190 : if (count_rows > *rows)
3823 248 : count_rows = *rows;
3824 6190 : if (input_rows > 0)
3825 6190 : *total_cost = *startup_cost +
3826 6190 : (input_total_cost - input_startup_cost)
3827 6190 : * count_rows / input_rows;
3828 6190 : *rows = count_rows;
3829 6190 : if (*rows < 1)
3830 0 : *rows = 1;
3831 : }
3832 6264 : }
3833 :
3834 :
3835 : /*
3836 : * reparameterize_path
3837 : * Attempt to modify a Path to have greater parameterization
3838 : *
3839 : * We use this to attempt to bring all child paths of an appendrel to the
3840 : * same parameterization level, ensuring that they all enforce the same set
3841 : * of join quals (and thus that that parameterization can be attributed to
3842 : * an append path built from such paths). Currently, only a few path types
3843 : * are supported here, though more could be added at need. We return NULL
3844 : * if we can't reparameterize the given path.
3845 : *
3846 : * Note: we intentionally do not pass created paths to add_path(); it would
3847 : * possibly try to delete them on the grounds of being cost-inferior to the
3848 : * paths they were made from, and we don't want that. Paths made here are
3849 : * not necessarily of general-purpose usefulness, but they can be useful
3850 : * as members of an append path.
3851 : */
3852 : Path *
3853 356 : reparameterize_path(PlannerInfo *root, Path *path,
3854 : Relids required_outer,
3855 : double loop_count)
3856 : {
3857 356 : RelOptInfo *rel = path->parent;
3858 :
3859 : /* Can only increase, not decrease, path's parameterization */
3860 356 : if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
3861 0 : return NULL;
3862 356 : switch (path->pathtype)
3863 : {
3864 264 : case T_SeqScan:
3865 264 : return create_seqscan_path(root, rel, required_outer, 0);
3866 0 : case T_SampleScan:
3867 0 : return (Path *) create_samplescan_path(root, rel, required_outer);
3868 0 : case T_IndexScan:
3869 : case T_IndexOnlyScan:
3870 : {
3871 0 : IndexPath *ipath = (IndexPath *) path;
3872 0 : IndexPath *newpath = makeNode(IndexPath);
3873 :
3874 : /*
3875 : * We can't use create_index_path directly, and would not want
3876 : * to because it would re-compute the indexqual conditions
3877 : * which is wasted effort. Instead we hack things a bit:
3878 : * flat-copy the path node, revise its param_info, and redo
3879 : * the cost estimate.
3880 : */
3881 0 : memcpy(newpath, ipath, sizeof(IndexPath));
3882 0 : newpath->path.param_info =
3883 0 : get_baserel_parampathinfo(root, rel, required_outer);
3884 0 : cost_index(newpath, root, loop_count, false);
3885 0 : return (Path *) newpath;
3886 : }
3887 0 : case T_BitmapHeapScan:
3888 : {
3889 0 : BitmapHeapPath *bpath = (BitmapHeapPath *) path;
3890 :
3891 0 : return (Path *) create_bitmap_heap_path(root,
3892 : rel,
3893 : bpath->bitmapqual,
3894 : required_outer,
3895 : loop_count, 0);
3896 : }
3897 0 : case T_SubqueryScan:
3898 : {
3899 0 : SubqueryScanPath *spath = (SubqueryScanPath *) path;
3900 0 : Path *subpath = spath->subpath;
3901 : bool trivial_pathtarget;
3902 :
3903 : /*
3904 : * If existing node has zero extra cost, we must have decided
3905 : * its target is trivial. (The converse is not true, because
3906 : * it might have a trivial target but quals to enforce; but in
3907 : * that case the new node will too, so it doesn't matter
3908 : * whether we get the right answer here.)
3909 : */
3910 0 : trivial_pathtarget =
3911 0 : (subpath->total_cost == spath->path.total_cost);
3912 :
3913 0 : return (Path *) create_subqueryscan_path(root,
3914 : rel,
3915 : subpath,
3916 : trivial_pathtarget,
3917 : spath->path.pathkeys,
3918 : required_outer);
3919 : }
3920 60 : case T_Result:
3921 : /* Supported only for RTE_RESULT scan paths */
3922 60 : if (IsA(path, Path))
3923 60 : return create_resultscan_path(root, rel, required_outer);
3924 0 : break;
3925 0 : case T_Append:
3926 : {
3927 0 : AppendPath *apath = (AppendPath *) path;
3928 0 : List *childpaths = NIL;
3929 0 : List *partialpaths = NIL;
3930 : int i;
3931 : ListCell *lc;
3932 :
3933 : /* Reparameterize the children */
3934 0 : i = 0;
3935 0 : foreach(lc, apath->subpaths)
3936 : {
3937 0 : Path *spath = (Path *) lfirst(lc);
3938 :
3939 0 : spath = reparameterize_path(root, spath,
3940 : required_outer,
3941 : loop_count);
3942 0 : if (spath == NULL)
3943 0 : return NULL;
3944 : /* We have to re-split the regular and partial paths */
3945 0 : if (i < apath->first_partial_path)
3946 0 : childpaths = lappend(childpaths, spath);
3947 : else
3948 0 : partialpaths = lappend(partialpaths, spath);
3949 0 : i++;
3950 : }
3951 0 : return (Path *)
3952 0 : create_append_path(root, rel, childpaths, partialpaths,
3953 : apath->path.pathkeys, required_outer,
3954 : apath->path.parallel_workers,
3955 0 : apath->path.parallel_aware,
3956 : -1);
3957 : }
3958 0 : case T_Material:
3959 : {
3960 0 : MaterialPath *mpath = (MaterialPath *) path;
3961 0 : Path *spath = mpath->subpath;
3962 :
3963 0 : spath = reparameterize_path(root, spath,
3964 : required_outer,
3965 : loop_count);
3966 0 : if (spath == NULL)
3967 0 : return NULL;
3968 0 : return (Path *) create_material_path(rel, spath);
3969 : }
3970 0 : case T_Memoize:
3971 : {
3972 0 : MemoizePath *mpath = (MemoizePath *) path;
3973 0 : Path *spath = mpath->subpath;
3974 :
3975 0 : spath = reparameterize_path(root, spath,
3976 : required_outer,
3977 : loop_count);
3978 0 : if (spath == NULL)
3979 0 : return NULL;
3980 0 : return (Path *) create_memoize_path(root, rel,
3981 : spath,
3982 : mpath->param_exprs,
3983 : mpath->hash_operators,
3984 0 : mpath->singlerow,
3985 0 : mpath->binary_mode,
3986 : mpath->est_calls);
3987 : }
3988 32 : default:
3989 32 : break;
3990 : }
3991 32 : return NULL;
3992 : }
3993 :
3994 : /*
3995 : * reparameterize_path_by_child
3996 : * Given a path parameterized by the parent of the given child relation,
3997 : * translate the path to be parameterized by the given child relation.
3998 : *
3999 : * Most fields in the path are not changed, but any expressions must be
4000 : * adjusted to refer to the correct varnos, and any subpaths must be
4001 : * recursively reparameterized. Other fields that refer to specific relids
4002 : * also need adjustment.
4003 : *
4004 : * The cost, number of rows, width and parallel path properties depend upon
4005 : * path->parent, which does not change during the translation. So we need
4006 : * not change those.
4007 : *
4008 : * Currently, only a few path types are supported here, though more could be
4009 : * added at need. We return NULL if we can't reparameterize the given path.
4010 : *
4011 : * Note that this function can change referenced RangeTblEntries, RelOptInfos
4012 : * and IndexOptInfos as well as the Path structures. Therefore, it's only safe
4013 : * to call during create_plan(), when we have made a final choice of which Path
4014 : * to use for each RangeTblEntry/RelOptInfo/IndexOptInfo.
4015 : *
4016 : * Keep this code in sync with path_is_reparameterizable_by_child()!
4017 : */
4018 : Path *
4019 98272 : reparameterize_path_by_child(PlannerInfo *root, Path *path,
4020 : RelOptInfo *child_rel)
4021 : {
4022 : Path *new_path;
4023 : ParamPathInfo *new_ppi;
4024 : ParamPathInfo *old_ppi;
4025 : Relids required_outer;
4026 :
4027 : #define ADJUST_CHILD_ATTRS(node) \
4028 : ((node) = (void *) adjust_appendrel_attrs_multilevel(root, \
4029 : (Node *) (node), \
4030 : child_rel, \
4031 : child_rel->top_parent))
4032 :
4033 : #define REPARAMETERIZE_CHILD_PATH(path) \
4034 : do { \
4035 : (path) = reparameterize_path_by_child(root, (path), child_rel); \
4036 : if ((path) == NULL) \
4037 : return NULL; \
4038 : } while(0)
4039 :
4040 : #define REPARAMETERIZE_CHILD_PATH_LIST(pathlist) \
4041 : do { \
4042 : if ((pathlist) != NIL) \
4043 : { \
4044 : (pathlist) = reparameterize_pathlist_by_child(root, (pathlist), \
4045 : child_rel); \
4046 : if ((pathlist) == NIL) \
4047 : return NULL; \
4048 : } \
4049 : } while(0)
4050 :
4051 : /*
4052 : * If the path is not parameterized by the parent of the given relation,
4053 : * it doesn't need reparameterization.
4054 : */
4055 98272 : if (!path->param_info ||
4056 50008 : !bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
4057 97246 : return path;
4058 :
4059 : /*
4060 : * If possible, reparameterize the given path.
4061 : *
4062 : * This function is currently only applied to the inner side of a nestloop
4063 : * join that is being partitioned by the partitionwise-join code. Hence,
4064 : * we need only support path types that plausibly arise in that context.
4065 : * (In particular, supporting sorted path types would be a waste of code
4066 : * and cycles: even if we translated them here, they'd just lose in
4067 : * subsequent cost comparisons.) If we do see an unsupported path type,
4068 : * that just means we won't be able to generate a partitionwise-join plan
4069 : * using that path type.
4070 : */
4071 1026 : switch (nodeTag(path))
4072 : {
4073 228 : case T_Path:
4074 228 : new_path = path;
4075 228 : ADJUST_CHILD_ATTRS(new_path->parent->baserestrictinfo);
4076 228 : if (path->pathtype == T_SampleScan)
4077 : {
4078 48 : Index scan_relid = path->parent->relid;
4079 : RangeTblEntry *rte;
4080 :
4081 : /* it should be a base rel with a tablesample clause... */
4082 : Assert(scan_relid > 0);
4083 48 : rte = planner_rt_fetch(scan_relid, root);
4084 : Assert(rte->rtekind == RTE_RELATION);
4085 : Assert(rte->tablesample != NULL);
4086 :
4087 48 : ADJUST_CHILD_ATTRS(rte->tablesample);
4088 : }
4089 228 : break;
4090 :
4091 528 : case T_IndexPath:
4092 : {
4093 528 : IndexPath *ipath = (IndexPath *) path;
4094 :
4095 528 : ADJUST_CHILD_ATTRS(ipath->indexinfo->indrestrictinfo);
4096 528 : ADJUST_CHILD_ATTRS(ipath->indexclauses);
4097 528 : new_path = (Path *) ipath;
4098 : }
4099 528 : break;
4100 :
4101 48 : case T_BitmapHeapPath:
4102 : {
4103 48 : BitmapHeapPath *bhpath = (BitmapHeapPath *) path;
4104 :
4105 48 : ADJUST_CHILD_ATTRS(bhpath->path.parent->baserestrictinfo);
4106 48 : REPARAMETERIZE_CHILD_PATH(bhpath->bitmapqual);
4107 48 : new_path = (Path *) bhpath;
4108 : }
4109 48 : break;
4110 :
4111 24 : case T_BitmapAndPath:
4112 : {
4113 24 : BitmapAndPath *bapath = (BitmapAndPath *) path;
4114 :
4115 24 : REPARAMETERIZE_CHILD_PATH_LIST(bapath->bitmapquals);
4116 24 : new_path = (Path *) bapath;
4117 : }
4118 24 : break;
4119 :
4120 24 : case T_BitmapOrPath:
4121 : {
4122 24 : BitmapOrPath *bopath = (BitmapOrPath *) path;
4123 :
4124 24 : REPARAMETERIZE_CHILD_PATH_LIST(bopath->bitmapquals);
4125 24 : new_path = (Path *) bopath;
4126 : }
4127 24 : break;
4128 :
4129 0 : case T_ForeignPath:
4130 : {
4131 0 : ForeignPath *fpath = (ForeignPath *) path;
4132 : ReparameterizeForeignPathByChild_function rfpc_func;
4133 :
4134 0 : ADJUST_CHILD_ATTRS(fpath->path.parent->baserestrictinfo);
4135 0 : if (fpath->fdw_outerpath)
4136 0 : REPARAMETERIZE_CHILD_PATH(fpath->fdw_outerpath);
4137 0 : if (fpath->fdw_restrictinfo)
4138 0 : ADJUST_CHILD_ATTRS(fpath->fdw_restrictinfo);
4139 :
4140 : /* Hand over to FDW if needed. */
4141 0 : rfpc_func =
4142 0 : path->parent->fdwroutine->ReparameterizeForeignPathByChild;
4143 0 : if (rfpc_func)
4144 0 : fpath->fdw_private = rfpc_func(root, fpath->fdw_private,
4145 : child_rel);
4146 0 : new_path = (Path *) fpath;
4147 : }
4148 0 : break;
4149 :
4150 0 : case T_CustomPath:
4151 : {
4152 0 : CustomPath *cpath = (CustomPath *) path;
4153 :
4154 0 : ADJUST_CHILD_ATTRS(cpath->path.parent->baserestrictinfo);
4155 0 : REPARAMETERIZE_CHILD_PATH_LIST(cpath->custom_paths);
4156 0 : if (cpath->custom_restrictinfo)
4157 0 : ADJUST_CHILD_ATTRS(cpath->custom_restrictinfo);
4158 0 : if (cpath->methods &&
4159 0 : cpath->methods->ReparameterizeCustomPathByChild)
4160 0 : cpath->custom_private =
4161 0 : cpath->methods->ReparameterizeCustomPathByChild(root,
4162 : cpath->custom_private,
4163 : child_rel);
4164 0 : new_path = (Path *) cpath;
4165 : }
4166 0 : break;
4167 :
4168 36 : case T_NestPath:
4169 : {
4170 36 : NestPath *npath = (NestPath *) path;
4171 36 : JoinPath *jpath = (JoinPath *) npath;
4172 :
4173 36 : REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4174 36 : REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4175 36 : ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4176 36 : new_path = (Path *) npath;
4177 : }
4178 36 : break;
4179 :
4180 0 : case T_MergePath:
4181 : {
4182 0 : MergePath *mpath = (MergePath *) path;
4183 0 : JoinPath *jpath = (JoinPath *) mpath;
4184 :
4185 0 : REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4186 0 : REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4187 0 : ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4188 0 : ADJUST_CHILD_ATTRS(mpath->path_mergeclauses);
4189 0 : new_path = (Path *) mpath;
4190 : }
4191 0 : break;
4192 :
4193 48 : case T_HashPath:
4194 : {
4195 48 : HashPath *hpath = (HashPath *) path;
4196 48 : JoinPath *jpath = (JoinPath *) hpath;
4197 :
4198 48 : REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4199 48 : REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4200 48 : ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4201 48 : ADJUST_CHILD_ATTRS(hpath->path_hashclauses);
4202 48 : new_path = (Path *) hpath;
4203 : }
4204 48 : break;
4205 :
4206 24 : case T_AppendPath:
4207 : {
4208 24 : AppendPath *apath = (AppendPath *) path;
4209 :
4210 24 : REPARAMETERIZE_CHILD_PATH_LIST(apath->subpaths);
4211 24 : new_path = (Path *) apath;
4212 : }
4213 24 : break;
4214 :
4215 0 : case T_MaterialPath:
4216 : {
4217 0 : MaterialPath *mpath = (MaterialPath *) path;
4218 :
4219 0 : REPARAMETERIZE_CHILD_PATH(mpath->subpath);
4220 0 : new_path = (Path *) mpath;
4221 : }
4222 0 : break;
4223 :
4224 66 : case T_MemoizePath:
4225 : {
4226 66 : MemoizePath *mpath = (MemoizePath *) path;
4227 :
4228 66 : REPARAMETERIZE_CHILD_PATH(mpath->subpath);
4229 66 : ADJUST_CHILD_ATTRS(mpath->param_exprs);
4230 66 : new_path = (Path *) mpath;
4231 : }
4232 66 : break;
4233 :
4234 0 : case T_GatherPath:
4235 : {
4236 0 : GatherPath *gpath = (GatherPath *) path;
4237 :
4238 0 : REPARAMETERIZE_CHILD_PATH(gpath->subpath);
4239 0 : new_path = (Path *) gpath;
4240 : }
4241 0 : break;
4242 :
4243 0 : default:
4244 : /* We don't know how to reparameterize this path. */
4245 0 : return NULL;
4246 : }
4247 :
4248 : /*
4249 : * Adjust the parameterization information, which refers to the topmost
4250 : * parent. The topmost parent can be multiple levels away from the given
4251 : * child, hence use multi-level expression adjustment routines.
4252 : */
4253 1026 : old_ppi = new_path->param_info;
4254 : required_outer =
4255 1026 : adjust_child_relids_multilevel(root, old_ppi->ppi_req_outer,
4256 : child_rel,
4257 1026 : child_rel->top_parent);
4258 :
4259 : /* If we already have a PPI for this parameterization, just return it */
4260 1026 : new_ppi = find_param_path_info(new_path->parent, required_outer);
4261 :
4262 : /*
4263 : * If not, build a new one and link it to the list of PPIs. For the same
4264 : * reason as explained in mark_dummy_rel(), allocate new PPI in the same
4265 : * context the given RelOptInfo is in.
4266 : */
4267 1026 : if (new_ppi == NULL)
4268 : {
4269 : MemoryContext oldcontext;
4270 864 : RelOptInfo *rel = path->parent;
4271 :
4272 864 : oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
4273 :
4274 864 : new_ppi = makeNode(ParamPathInfo);
4275 864 : new_ppi->ppi_req_outer = bms_copy(required_outer);
4276 864 : new_ppi->ppi_rows = old_ppi->ppi_rows;
4277 864 : new_ppi->ppi_clauses = old_ppi->ppi_clauses;
4278 864 : ADJUST_CHILD_ATTRS(new_ppi->ppi_clauses);
4279 864 : new_ppi->ppi_serials = bms_copy(old_ppi->ppi_serials);
4280 864 : rel->ppilist = lappend(rel->ppilist, new_ppi);
4281 :
4282 864 : MemoryContextSwitchTo(oldcontext);
4283 : }
4284 1026 : bms_free(required_outer);
4285 :
4286 1026 : new_path->param_info = new_ppi;
4287 :
4288 : /*
4289 : * Adjust the path target if the parent of the outer relation is
4290 : * referenced in the targetlist. This can happen when only the parent of
4291 : * outer relation is laterally referenced in this relation.
4292 : */
4293 1026 : if (bms_overlap(path->parent->lateral_relids,
4294 1026 : child_rel->top_parent_relids))
4295 : {
4296 480 : new_path->pathtarget = copy_pathtarget(new_path->pathtarget);
4297 480 : ADJUST_CHILD_ATTRS(new_path->pathtarget->exprs);
4298 : }
4299 :
4300 1026 : return new_path;
4301 : }
4302 :
4303 : /*
4304 : * path_is_reparameterizable_by_child
4305 : * Given a path parameterized by the parent of the given child relation,
4306 : * see if it can be translated to be parameterized by the child relation.
4307 : *
4308 : * This must return true if and only if reparameterize_path_by_child()
4309 : * would succeed on this path. Currently it's sufficient to verify that
4310 : * the path and all of its subpaths (if any) are of the types handled by
4311 : * that function. However, subpaths that are not parameterized can be
4312 : * disregarded since they won't require translation.
4313 : */
4314 : bool
4315 37224 : path_is_reparameterizable_by_child(Path *path, RelOptInfo *child_rel)
4316 : {
4317 : #define REJECT_IF_PATH_NOT_REPARAMETERIZABLE(path) \
4318 : do { \
4319 : if (!path_is_reparameterizable_by_child(path, child_rel)) \
4320 : return false; \
4321 : } while(0)
4322 :
4323 : #define REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(pathlist) \
4324 : do { \
4325 : if (!pathlist_is_reparameterizable_by_child(pathlist, child_rel)) \
4326 : return false; \
4327 : } while(0)
4328 :
4329 : /*
4330 : * If the path is not parameterized by the parent of the given relation,
4331 : * it doesn't need reparameterization.
4332 : */
4333 37224 : if (!path->param_info ||
4334 36816 : !bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
4335 984 : return true;
4336 :
4337 : /*
4338 : * Check that the path type is one that reparameterize_path_by_child() can
4339 : * handle, and recursively check subpaths.
4340 : */
4341 36240 : switch (nodeTag(path))
4342 : {
4343 24312 : case T_Path:
4344 : case T_IndexPath:
4345 24312 : break;
4346 :
4347 48 : case T_BitmapHeapPath:
4348 : {
4349 48 : BitmapHeapPath *bhpath = (BitmapHeapPath *) path;
4350 :
4351 48 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(bhpath->bitmapqual);
4352 : }
4353 48 : break;
4354 :
4355 24 : case T_BitmapAndPath:
4356 : {
4357 24 : BitmapAndPath *bapath = (BitmapAndPath *) path;
4358 :
4359 24 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(bapath->bitmapquals);
4360 : }
4361 24 : break;
4362 :
4363 24 : case T_BitmapOrPath:
4364 : {
4365 24 : BitmapOrPath *bopath = (BitmapOrPath *) path;
4366 :
4367 24 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(bopath->bitmapquals);
4368 : }
4369 24 : break;
4370 :
4371 148 : case T_ForeignPath:
4372 : {
4373 148 : ForeignPath *fpath = (ForeignPath *) path;
4374 :
4375 148 : if (fpath->fdw_outerpath)
4376 0 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(fpath->fdw_outerpath);
4377 : }
4378 148 : break;
4379 :
4380 0 : case T_CustomPath:
4381 : {
4382 0 : CustomPath *cpath = (CustomPath *) path;
4383 :
4384 0 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(cpath->custom_paths);
4385 : }
4386 0 : break;
4387 :
4388 1248 : case T_NestPath:
4389 : case T_MergePath:
4390 : case T_HashPath:
4391 : {
4392 1248 : JoinPath *jpath = (JoinPath *) path;
4393 :
4394 1248 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(jpath->outerjoinpath);
4395 1248 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(jpath->innerjoinpath);
4396 : }
4397 1248 : break;
4398 :
4399 192 : case T_AppendPath:
4400 : {
4401 192 : AppendPath *apath = (AppendPath *) path;
4402 :
4403 192 : REJECT_IF_PATH_LIST_NOT_REPARAMETERIZABLE(apath->subpaths);
4404 : }
4405 192 : break;
4406 :
4407 0 : case T_MaterialPath:
4408 : {
4409 0 : MaterialPath *mpath = (MaterialPath *) path;
4410 :
4411 0 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(mpath->subpath);
4412 : }
4413 0 : break;
4414 :
4415 10244 : case T_MemoizePath:
4416 : {
4417 10244 : MemoizePath *mpath = (MemoizePath *) path;
4418 :
4419 10244 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(mpath->subpath);
4420 : }
4421 10244 : break;
4422 :
4423 0 : case T_GatherPath:
4424 : {
4425 0 : GatherPath *gpath = (GatherPath *) path;
4426 :
4427 0 : REJECT_IF_PATH_NOT_REPARAMETERIZABLE(gpath->subpath);
4428 : }
4429 0 : break;
4430 :
4431 0 : default:
4432 : /* We don't know how to reparameterize this path. */
4433 0 : return false;
4434 : }
4435 :
4436 36240 : return true;
4437 : }
4438 :
4439 : /*
4440 : * reparameterize_pathlist_by_child
4441 : * Helper function to reparameterize a list of paths by given child rel.
4442 : *
4443 : * Returns NIL to indicate failure, so pathlist had better not be NIL.
4444 : */
4445 : static List *
4446 72 : reparameterize_pathlist_by_child(PlannerInfo *root,
4447 : List *pathlist,
4448 : RelOptInfo *child_rel)
4449 : {
4450 : ListCell *lc;
4451 72 : List *result = NIL;
4452 :
4453 216 : foreach(lc, pathlist)
4454 : {
4455 144 : Path *path = reparameterize_path_by_child(root, lfirst(lc),
4456 : child_rel);
4457 :
4458 144 : if (path == NULL)
4459 : {
4460 0 : list_free(result);
4461 0 : return NIL;
4462 : }
4463 :
4464 144 : result = lappend(result, path);
4465 : }
4466 :
4467 72 : return result;
4468 : }
4469 :
4470 : /*
4471 : * pathlist_is_reparameterizable_by_child
4472 : * Helper function to check if a list of paths can be reparameterized.
4473 : */
4474 : static bool
4475 240 : pathlist_is_reparameterizable_by_child(List *pathlist, RelOptInfo *child_rel)
4476 : {
4477 : ListCell *lc;
4478 :
4479 720 : foreach(lc, pathlist)
4480 : {
4481 480 : Path *path = (Path *) lfirst(lc);
4482 :
4483 480 : if (!path_is_reparameterizable_by_child(path, child_rel))
4484 0 : return false;
4485 : }
4486 :
4487 240 : return true;
4488 : }
|