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

Generated by: LCOV version 1.16