LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - pathnode.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 90.7 % 1547 1403
Test Date: 2026-02-17 17:20:33 Functions: 100.0 % 63 63
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1