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

Generated by: LCOV version 1.13