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

Generated by: LCOV version 1.14