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