LCOV - code coverage report
Current view: top level - src/backend/optimizer/prep - prepjointree.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 851 960 88.6 %
Date: 2019-09-19 02:07:14 Functions: 38 40 95.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * prepjointree.c
       4             :  *    Planner preprocessing for subqueries and join tree manipulation.
       5             :  *
       6             :  * NOTE: the intended sequence for invoking these operations is
       7             :  *      replace_empty_jointree
       8             :  *      pull_up_sublinks
       9             :  *      preprocess_function_rtes
      10             :  *      pull_up_subqueries
      11             :  *      flatten_simple_union_all
      12             :  *      do expression preprocessing (including flattening JOIN alias vars)
      13             :  *      reduce_outer_joins
      14             :  *      remove_useless_result_rtes
      15             :  *
      16             :  *
      17             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
      18             :  * Portions Copyright (c) 1994, Regents of the University of California
      19             :  *
      20             :  *
      21             :  * IDENTIFICATION
      22             :  *    src/backend/optimizer/prep/prepjointree.c
      23             :  *
      24             :  *-------------------------------------------------------------------------
      25             :  */
      26             : #include "postgres.h"
      27             : 
      28             : #include "catalog/pg_type.h"
      29             : #include "nodes/makefuncs.h"
      30             : #include "nodes/nodeFuncs.h"
      31             : #include "optimizer/clauses.h"
      32             : #include "optimizer/optimizer.h"
      33             : #include "optimizer/placeholder.h"
      34             : #include "optimizer/prep.h"
      35             : #include "optimizer/subselect.h"
      36             : #include "optimizer/tlist.h"
      37             : #include "parser/parse_relation.h"
      38             : #include "parser/parsetree.h"
      39             : #include "rewrite/rewriteManip.h"
      40             : 
      41             : 
      42             : typedef struct pullup_replace_vars_context
      43             : {
      44             :     PlannerInfo *root;
      45             :     List       *targetlist;     /* tlist of subquery being pulled up */
      46             :     RangeTblEntry *target_rte;  /* RTE of subquery */
      47             :     Relids      relids;         /* relids within subquery, as numbered after
      48             :                                  * pullup (set only if target_rte->lateral) */
      49             :     bool       *outer_hasSubLinks;  /* -> outer query's hasSubLinks */
      50             :     int         varno;          /* varno of subquery */
      51             :     bool        need_phvs;      /* do we need PlaceHolderVars? */
      52             :     bool        wrap_non_vars;  /* do we need 'em on *all* non-Vars? */
      53             :     Node      **rv_cache;       /* cache for results with PHVs */
      54             : } pullup_replace_vars_context;
      55             : 
      56             : typedef struct reduce_outer_joins_state
      57             : {
      58             :     Relids      relids;         /* base relids within this subtree */
      59             :     bool        contains_outer; /* does subtree contain outer join(s)? */
      60             :     List       *sub_states;     /* List of states for subtree components */
      61             : } reduce_outer_joins_state;
      62             : 
      63             : static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
      64             :                                                Relids *relids);
      65             : static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
      66             :                                            Node **jtlink1, Relids available_rels1,
      67             :                                            Node **jtlink2, Relids available_rels2);
      68             : static Node *pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
      69             :                                         JoinExpr *lowest_outer_join,
      70             :                                         JoinExpr *lowest_nulling_outer_join,
      71             :                                         AppendRelInfo *containing_appendrel);
      72             : static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
      73             :                                      RangeTblEntry *rte,
      74             :                                      JoinExpr *lowest_outer_join,
      75             :                                      JoinExpr *lowest_nulling_outer_join,
      76             :                                      AppendRelInfo *containing_appendrel);
      77             : static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode,
      78             :                                       RangeTblEntry *rte);
      79             : static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root,
      80             :                                        int parentRTindex, Query *setOpQuery,
      81             :                                        int childRToffset);
      82             : static void make_setop_translation_list(Query *query, Index newvarno,
      83             :                                         List **translated_vars);
      84             : static bool is_simple_subquery(Query *subquery, RangeTblEntry *rte,
      85             :                                JoinExpr *lowest_outer_join);
      86             : static Node *pull_up_simple_values(PlannerInfo *root, Node *jtnode,
      87             :                                    RangeTblEntry *rte);
      88             : static bool is_simple_values(PlannerInfo *root, RangeTblEntry *rte);
      89             : static Node *pull_up_constant_function(PlannerInfo *root, Node *jtnode,
      90             :                                        RangeTblEntry *rte,
      91             :                                        JoinExpr *lowest_nulling_outer_join,
      92             :                                        AppendRelInfo *containing_appendrel);
      93             : static bool is_simple_union_all(Query *subquery);
      94             : static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery,
      95             :                                         List *colTypes);
      96             : static bool is_safe_append_member(Query *subquery);
      97             : static bool jointree_contains_lateral_outer_refs(Node *jtnode, bool restricted,
      98             :                                                  Relids safe_upper_varnos);
      99             : static void perform_pullup_replace_vars(PlannerInfo *root,
     100             :                                         pullup_replace_vars_context *rvcontext,
     101             :                                         JoinExpr *lowest_nulling_outer_join,
     102             :                                         AppendRelInfo *containing_appendrel);
     103             : static void replace_vars_in_jointree(Node *jtnode,
     104             :                                      pullup_replace_vars_context *context,
     105             :                                      JoinExpr *lowest_nulling_outer_join);
     106             : static Node *pullup_replace_vars(Node *expr,
     107             :                                  pullup_replace_vars_context *context);
     108             : static Node *pullup_replace_vars_callback(Var *var,
     109             :                                           replace_rte_variables_context *context);
     110             : static Query *pullup_replace_vars_subquery(Query *query,
     111             :                                            pullup_replace_vars_context *context);
     112             : static reduce_outer_joins_state *reduce_outer_joins_pass1(Node *jtnode);
     113             : static void reduce_outer_joins_pass2(Node *jtnode,
     114             :                                      reduce_outer_joins_state *state,
     115             :                                      PlannerInfo *root,
     116             :                                      Relids nonnullable_rels,
     117             :                                      List *nonnullable_vars,
     118             :                                      List *forced_null_vars);
     119             : static Node *remove_useless_results_recurse(PlannerInfo *root, Node *jtnode);
     120             : static int  get_result_relid(PlannerInfo *root, Node *jtnode);
     121             : static void remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc);
     122             : static bool find_dependent_phvs(Node *node, int varno);
     123             : static void substitute_phv_relids(Node *node,
     124             :                                   int varno, Relids subrelids);
     125             : static void fix_append_rel_relids(List *append_rel_list, int varno,
     126             :                                   Relids subrelids);
     127             : static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
     128             : 
     129             : 
     130             : /*
     131             :  * replace_empty_jointree
     132             :  *      If the Query's jointree is empty, replace it with a dummy RTE_RESULT
     133             :  *      relation.
     134             :  *
     135             :  * By doing this, we can avoid a bunch of corner cases that formerly existed
     136             :  * for SELECTs with omitted FROM clauses.  An example is that a subquery
     137             :  * with empty jointree previously could not be pulled up, because that would
     138             :  * have resulted in an empty relid set, making the subquery not uniquely
     139             :  * identifiable for join or PlaceHolderVar processing.
     140             :  *
     141             :  * Unlike most other functions in this file, this function doesn't recurse;
     142             :  * we rely on other processing to invoke it on sub-queries at suitable times.
     143             :  */
     144             : void
     145      342796 : replace_empty_jointree(Query *parse)
     146             : {
     147             :     RangeTblEntry *rte;
     148             :     Index       rti;
     149             :     RangeTblRef *rtr;
     150             : 
     151             :     /* Nothing to do if jointree is already nonempty */
     152      342796 :     if (parse->jointree->fromlist != NIL)
     153      228212 :         return;
     154             : 
     155             :     /* We mustn't change it in the top level of a setop tree, either */
     156      114584 :     if (parse->setOperations)
     157        2452 :         return;
     158             : 
     159             :     /* Create suitable RTE */
     160      112132 :     rte = makeNode(RangeTblEntry);
     161      112132 :     rte->rtekind = RTE_RESULT;
     162      112132 :     rte->eref = makeAlias("*RESULT*", NIL);
     163             : 
     164             :     /* Add it to rangetable */
     165      112132 :     parse->rtable = lappend(parse->rtable, rte);
     166      112132 :     rti = list_length(parse->rtable);
     167             : 
     168             :     /* And jam a reference into the jointree */
     169      112132 :     rtr = makeNode(RangeTblRef);
     170      112132 :     rtr->rtindex = rti;
     171      112132 :     parse->jointree->fromlist = list_make1(rtr);
     172             : }
     173             : 
     174             : /*
     175             :  * pull_up_sublinks
     176             :  *      Attempt to pull up ANY and EXISTS SubLinks to be treated as
     177             :  *      semijoins or anti-semijoins.
     178             :  *
     179             :  * A clause "foo op ANY (sub-SELECT)" can be processed by pulling the
     180             :  * sub-SELECT up to become a rangetable entry and treating the implied
     181             :  * comparisons as quals of a semijoin.  However, this optimization *only*
     182             :  * works at the top level of WHERE or a JOIN/ON clause, because we cannot
     183             :  * distinguish whether the ANY ought to return FALSE or NULL in cases
     184             :  * involving NULL inputs.  Also, in an outer join's ON clause we can only
     185             :  * do this if the sublink is degenerate (ie, references only the nullable
     186             :  * side of the join).  In that case it is legal to push the semijoin
     187             :  * down into the nullable side of the join.  If the sublink references any
     188             :  * nonnullable-side variables then it would have to be evaluated as part
     189             :  * of the outer join, which makes things way too complicated.
     190             :  *
     191             :  * Under similar conditions, EXISTS and NOT EXISTS clauses can be handled
     192             :  * by pulling up the sub-SELECT and creating a semijoin or anti-semijoin.
     193             :  *
     194             :  * This routine searches for such clauses and does the necessary parsetree
     195             :  * transformations if any are found.
     196             :  *
     197             :  * This routine has to run before preprocess_expression(), so the quals
     198             :  * clauses are not yet reduced to implicit-AND format, and are not guaranteed
     199             :  * to be AND/OR-flat either.  That means we need to recursively search through
     200             :  * explicit AND clauses.  We stop as soon as we hit a non-AND item.
     201             :  */
     202             : void
     203       39202 : pull_up_sublinks(PlannerInfo *root)
     204             : {
     205             :     Node       *jtnode;
     206             :     Relids      relids;
     207             : 
     208             :     /* Begin recursion through the jointree */
     209       39202 :     jtnode = pull_up_sublinks_jointree_recurse(root,
     210       39202 :                                                (Node *) root->parse->jointree,
     211             :                                                &relids);
     212             : 
     213             :     /*
     214             :      * root->parse->jointree must always be a FromExpr, so insert a dummy one
     215             :      * if we got a bare RangeTblRef or JoinExpr out of the recursion.
     216             :      */
     217       39202 :     if (IsA(jtnode, FromExpr))
     218       31354 :         root->parse->jointree = (FromExpr *) jtnode;
     219             :     else
     220        7848 :         root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
     221       39202 : }
     222             : 
     223             : /*
     224             :  * Recurse through jointree nodes for pull_up_sublinks()
     225             :  *
     226             :  * In addition to returning the possibly-modified jointree node, we return
     227             :  * a relids set of the contained rels into *relids.
     228             :  */
     229             : static Node *
     230      120282 : pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
     231             :                                   Relids *relids)
     232             : {
     233      120282 :     if (jtnode == NULL)
     234             :     {
     235           0 :         *relids = NULL;
     236             :     }
     237      120282 :     else if (IsA(jtnode, RangeTblRef))
     238             :     {
     239       64928 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
     240             : 
     241       64928 :         *relids = bms_make_singleton(varno);
     242             :         /* jtnode is returned unmodified */
     243             :     }
     244       55354 :     else if (IsA(jtnode, FromExpr))
     245             :     {
     246       39206 :         FromExpr   *f = (FromExpr *) jtnode;
     247       39206 :         List       *newfromlist = NIL;
     248       39206 :         Relids      frelids = NULL;
     249             :         FromExpr   *newf;
     250             :         Node       *jtlink;
     251             :         ListCell   *l;
     252             : 
     253             :         /* First, recurse to process children and collect their relids */
     254       79794 :         foreach(l, f->fromlist)
     255             :         {
     256             :             Node       *newchild;
     257             :             Relids      childrelids;
     258             : 
     259       40588 :             newchild = pull_up_sublinks_jointree_recurse(root,
     260       40588 :                                                          lfirst(l),
     261             :                                                          &childrelids);
     262       40588 :             newfromlist = lappend(newfromlist, newchild);
     263       40588 :             frelids = bms_join(frelids, childrelids);
     264             :         }
     265             :         /* Build the replacement FromExpr; no quals yet */
     266       39206 :         newf = makeFromExpr(newfromlist, NULL);
     267             :         /* Set up a link representing the rebuilt jointree */
     268       39206 :         jtlink = (Node *) newf;
     269             :         /* Now process qual --- all children are available for use */
     270       39206 :         newf->quals = pull_up_sublinks_qual_recurse(root, f->quals,
     271             :                                                     &jtlink, frelids,
     272             :                                                     NULL, NULL);
     273             : 
     274             :         /*
     275             :          * Note that the result will be either newf, or a stack of JoinExprs
     276             :          * with newf at the base.  We rely on subsequent optimization steps to
     277             :          * flatten this and rearrange the joins as needed.
     278             :          *
     279             :          * Although we could include the pulled-up subqueries in the returned
     280             :          * relids, there's no need since upper quals couldn't refer to their
     281             :          * outputs anyway.
     282             :          */
     283       39206 :         *relids = frelids;
     284       39206 :         jtnode = jtlink;
     285             :     }
     286       16148 :     else if (IsA(jtnode, JoinExpr))
     287             :     {
     288             :         JoinExpr   *j;
     289             :         Relids      leftrelids;
     290             :         Relids      rightrelids;
     291             :         Node       *jtlink;
     292             : 
     293             :         /*
     294             :          * Make a modifiable copy of join node, but don't bother copying its
     295             :          * subnodes (yet).
     296             :          */
     297       16148 :         j = (JoinExpr *) palloc(sizeof(JoinExpr));
     298       16148 :         memcpy(j, jtnode, sizeof(JoinExpr));
     299       16148 :         jtlink = (Node *) j;
     300             : 
     301             :         /* Recurse to process children and collect their relids */
     302       16148 :         j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
     303             :                                                     &leftrelids);
     304       16148 :         j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
     305             :                                                     &rightrelids);
     306             : 
     307             :         /*
     308             :          * Now process qual, showing appropriate child relids as available,
     309             :          * and attach any pulled-up jointree items at the right place. In the
     310             :          * inner-join case we put new JoinExprs above the existing one (much
     311             :          * as for a FromExpr-style join).  In outer-join cases the new
     312             :          * JoinExprs must go into the nullable side of the outer join. The
     313             :          * point of the available_rels machinations is to ensure that we only
     314             :          * pull up quals for which that's okay.
     315             :          *
     316             :          * We don't expect to see any pre-existing JOIN_SEMI or JOIN_ANTI
     317             :          * nodes here.
     318             :          */
     319       16148 :         switch (j->jointype)
     320             :         {
     321             :             case JOIN_INNER:
     322        3932 :                 j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
     323             :                                                          &jtlink,
     324             :                                                          bms_union(leftrelids,
     325             :                                                                    rightrelids),
     326             :                                                          NULL, NULL);
     327        3932 :                 break;
     328             :             case JOIN_LEFT:
     329       12216 :                 j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
     330             :                                                          &j->rarg,
     331             :                                                          rightrelids,
     332             :                                                          NULL, NULL);
     333       12216 :                 break;
     334             :             case JOIN_FULL:
     335             :                 /* can't do anything with full-join quals */
     336           0 :                 break;
     337             :             case JOIN_RIGHT:
     338           0 :                 j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
     339             :                                                          &j->larg,
     340             :                                                          leftrelids,
     341             :                                                          NULL, NULL);
     342           0 :                 break;
     343             :             default:
     344           0 :                 elog(ERROR, "unrecognized join type: %d",
     345             :                      (int) j->jointype);
     346             :                 break;
     347             :         }
     348             : 
     349             :         /*
     350             :          * Although we could include the pulled-up subqueries in the returned
     351             :          * relids, there's no need since upper quals couldn't refer to their
     352             :          * outputs anyway.  But we *do* need to include the join's own rtindex
     353             :          * because we haven't yet collapsed join alias variables, so upper
     354             :          * levels would mistakenly think they couldn't use references to this
     355             :          * join.
     356             :          */
     357       16148 :         *relids = bms_join(leftrelids, rightrelids);
     358       16148 :         if (j->rtindex)
     359       16148 :             *relids = bms_add_member(*relids, j->rtindex);
     360       16148 :         jtnode = jtlink;
     361             :     }
     362             :     else
     363           0 :         elog(ERROR, "unrecognized node type: %d",
     364             :              (int) nodeTag(jtnode));
     365      120282 :     return jtnode;
     366             : }
     367             : 
     368             : /*
     369             :  * Recurse through top-level qual nodes for pull_up_sublinks()
     370             :  *
     371             :  * jtlink1 points to the link in the jointree where any new JoinExprs should
     372             :  * be inserted if they reference available_rels1 (i.e., available_rels1
     373             :  * denotes the relations present underneath jtlink1).  Optionally, jtlink2 can
     374             :  * point to a second link where new JoinExprs should be inserted if they
     375             :  * reference available_rels2 (pass NULL for both those arguments if not used).
     376             :  * Note that SubLinks referencing both sets of variables cannot be optimized.
     377             :  * If we find multiple pull-up-able SubLinks, they'll get stacked onto jtlink1
     378             :  * and/or jtlink2 in the order we encounter them.  We rely on subsequent
     379             :  * optimization to rearrange the stack if appropriate.
     380             :  *
     381             :  * Returns the replacement qual node, or NULL if the qual should be removed.
     382             :  */
     383             : static Node *
     384      108950 : pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
     385             :                               Node **jtlink1, Relids available_rels1,
     386             :                               Node **jtlink2, Relids available_rels2)
     387             : {
     388      108950 :     if (node == NULL)
     389        6288 :         return NULL;
     390      102662 :     if (IsA(node, SubLink))
     391             :     {
     392         784 :         SubLink    *sublink = (SubLink *) node;
     393             :         JoinExpr   *j;
     394             :         Relids      child_rels;
     395             : 
     396             :         /* Is it a convertible ANY or EXISTS clause? */
     397         784 :         if (sublink->subLinkType == ANY_SUBLINK)
     398             :         {
     399         592 :             if ((j = convert_ANY_sublink_to_join(root, sublink,
     400             :                                                  available_rels1)) != NULL)
     401             :             {
     402             :                 /* Yes; insert the new join node into the join tree */
     403         544 :                 j->larg = *jtlink1;
     404         544 :                 *jtlink1 = (Node *) j;
     405             :                 /* Recursively process pulled-up jointree nodes */
     406         544 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
     407             :                                                             j->rarg,
     408             :                                                             &child_rels);
     409             : 
     410             :                 /*
     411             :                  * Now recursively process the pulled-up quals.  Any inserted
     412             :                  * joins can get stacked onto either j->larg or j->rarg,
     413             :                  * depending on which rels they reference.
     414             :                  */
     415         544 :                 j->quals = pull_up_sublinks_qual_recurse(root,
     416             :                                                          j->quals,
     417             :                                                          &j->larg,
     418             :                                                          available_rels1,
     419             :                                                          &j->rarg,
     420             :                                                          child_rels);
     421             :                 /* Return NULL representing constant TRUE */
     422         544 :                 return NULL;
     423             :             }
     424          48 :             if (available_rels2 != NULL &&
     425             :                 (j = convert_ANY_sublink_to_join(root, sublink,
     426             :                                                  available_rels2)) != NULL)
     427             :             {
     428             :                 /* Yes; insert the new join node into the join tree */
     429           0 :                 j->larg = *jtlink2;
     430           0 :                 *jtlink2 = (Node *) j;
     431             :                 /* Recursively process pulled-up jointree nodes */
     432           0 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
     433             :                                                             j->rarg,
     434             :                                                             &child_rels);
     435             : 
     436             :                 /*
     437             :                  * Now recursively process the pulled-up quals.  Any inserted
     438             :                  * joins can get stacked onto either j->larg or j->rarg,
     439             :                  * depending on which rels they reference.
     440             :                  */
     441           0 :                 j->quals = pull_up_sublinks_qual_recurse(root,
     442             :                                                          j->quals,
     443             :                                                          &j->larg,
     444             :                                                          available_rels2,
     445             :                                                          &j->rarg,
     446             :                                                          child_rels);
     447             :                 /* Return NULL representing constant TRUE */
     448           0 :                 return NULL;
     449             :             }
     450             :         }
     451         192 :         else if (sublink->subLinkType == EXISTS_SUBLINK)
     452             :         {
     453         164 :             if ((j = convert_EXISTS_sublink_to_join(root, sublink, false,
     454             :                                                     available_rels1)) != NULL)
     455             :             {
     456             :                 /* Yes; insert the new join node into the join tree */
     457         118 :                 j->larg = *jtlink1;
     458         118 :                 *jtlink1 = (Node *) j;
     459             :                 /* Recursively process pulled-up jointree nodes */
     460         118 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
     461             :                                                             j->rarg,
     462             :                                                             &child_rels);
     463             : 
     464             :                 /*
     465             :                  * Now recursively process the pulled-up quals.  Any inserted
     466             :                  * joins can get stacked onto either j->larg or j->rarg,
     467             :                  * depending on which rels they reference.
     468             :                  */
     469         118 :                 j->quals = pull_up_sublinks_qual_recurse(root,
     470             :                                                          j->quals,
     471             :                                                          &j->larg,
     472             :                                                          available_rels1,
     473             :                                                          &j->rarg,
     474             :                                                          child_rels);
     475             :                 /* Return NULL representing constant TRUE */
     476         118 :                 return NULL;
     477             :             }
     478          46 :             if (available_rels2 != NULL &&
     479             :                 (j = convert_EXISTS_sublink_to_join(root, sublink, false,
     480             :                                                     available_rels2)) != NULL)
     481             :             {
     482             :                 /* Yes; insert the new join node into the join tree */
     483           0 :                 j->larg = *jtlink2;
     484           0 :                 *jtlink2 = (Node *) j;
     485             :                 /* Recursively process pulled-up jointree nodes */
     486           0 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
     487             :                                                             j->rarg,
     488             :                                                             &child_rels);
     489             : 
     490             :                 /*
     491             :                  * Now recursively process the pulled-up quals.  Any inserted
     492             :                  * joins can get stacked onto either j->larg or j->rarg,
     493             :                  * depending on which rels they reference.
     494             :                  */
     495           0 :                 j->quals = pull_up_sublinks_qual_recurse(root,
     496             :                                                          j->quals,
     497             :                                                          &j->larg,
     498             :                                                          available_rels2,
     499             :                                                          &j->rarg,
     500             :                                                          child_rels);
     501             :                 /* Return NULL representing constant TRUE */
     502           0 :                 return NULL;
     503             :             }
     504             :         }
     505             :         /* Else return it unmodified */
     506         122 :         return node;
     507             :     }
     508      101878 :     if (is_notclause(node))
     509             :     {
     510             :         /* If the immediate argument of NOT is EXISTS, try to convert */
     511        9678 :         SubLink    *sublink = (SubLink *) get_notclausearg((Expr *) node);
     512             :         JoinExpr   *j;
     513             :         Relids      child_rels;
     514             : 
     515        9678 :         if (sublink && IsA(sublink, SubLink))
     516             :         {
     517        7594 :             if (sublink->subLinkType == EXISTS_SUBLINK)
     518             :             {
     519        7546 :                 if ((j = convert_EXISTS_sublink_to_join(root, sublink, true,
     520             :                                                         available_rels1)) != NULL)
     521             :                 {
     522             :                     /* Yes; insert the new join node into the join tree */
     523        7534 :                     j->larg = *jtlink1;
     524        7534 :                     *jtlink1 = (Node *) j;
     525             :                     /* Recursively process pulled-up jointree nodes */
     526        7534 :                     j->rarg = pull_up_sublinks_jointree_recurse(root,
     527             :                                                                 j->rarg,
     528             :                                                                 &child_rels);
     529             : 
     530             :                     /*
     531             :                      * Now recursively process the pulled-up quals.  Because
     532             :                      * we are underneath a NOT, we can't pull up sublinks that
     533             :                      * reference the left-hand stuff, but it's still okay to
     534             :                      * pull up sublinks referencing j->rarg.
     535             :                      */
     536        7534 :                     j->quals = pull_up_sublinks_qual_recurse(root,
     537             :                                                              j->quals,
     538             :                                                              &j->rarg,
     539             :                                                              child_rels,
     540             :                                                              NULL, NULL);
     541             :                     /* Return NULL representing constant TRUE */
     542        7534 :                     return NULL;
     543             :                 }
     544          12 :                 if (available_rels2 != NULL &&
     545             :                     (j = convert_EXISTS_sublink_to_join(root, sublink, true,
     546             :                                                         available_rels2)) != NULL)
     547             :                 {
     548             :                     /* Yes; insert the new join node into the join tree */
     549           0 :                     j->larg = *jtlink2;
     550           0 :                     *jtlink2 = (Node *) j;
     551             :                     /* Recursively process pulled-up jointree nodes */
     552           0 :                     j->rarg = pull_up_sublinks_jointree_recurse(root,
     553             :                                                                 j->rarg,
     554             :                                                                 &child_rels);
     555             : 
     556             :                     /*
     557             :                      * Now recursively process the pulled-up quals.  Because
     558             :                      * we are underneath a NOT, we can't pull up sublinks that
     559             :                      * reference the left-hand stuff, but it's still okay to
     560             :                      * pull up sublinks referencing j->rarg.
     561             :                      */
     562           0 :                     j->quals = pull_up_sublinks_qual_recurse(root,
     563             :                                                              j->quals,
     564             :                                                              &j->rarg,
     565             :                                                              child_rels,
     566             :                                                              NULL, NULL);
     567             :                     /* Return NULL representing constant TRUE */
     568           0 :                     return NULL;
     569             :                 }
     570             :             }
     571             :         }
     572             :         /* Else return it unmodified */
     573        2144 :         return node;
     574             :     }
     575       92200 :     if (is_andclause(node))
     576             :     {
     577             :         /* Recurse into AND clause */
     578       17662 :         List       *newclauses = NIL;
     579             :         ListCell   *l;
     580             : 
     581       63062 :         foreach(l, ((BoolExpr *) node)->args)
     582             :         {
     583       45400 :             Node       *oldclause = (Node *) lfirst(l);
     584             :             Node       *newclause;
     585             : 
     586       45400 :             newclause = pull_up_sublinks_qual_recurse(root,
     587             :                                                       oldclause,
     588             :                                                       jtlink1,
     589             :                                                       available_rels1,
     590             :                                                       jtlink2,
     591             :                                                       available_rels2);
     592       45400 :             if (newclause)
     593       43420 :                 newclauses = lappend(newclauses, newclause);
     594             :         }
     595             :         /* We might have got back fewer clauses than we started with */
     596       17662 :         if (newclauses == NIL)
     597         320 :             return NULL;
     598       17342 :         else if (list_length(newclauses) == 1)
     599         862 :             return (Node *) linitial(newclauses);
     600             :         else
     601       16480 :             return (Node *) make_andclause(newclauses);
     602             :     }
     603             :     /* Stop if not an AND */
     604       74538 :     return node;
     605             : }
     606             : 
     607             : /*
     608             :  * preprocess_function_rtes
     609             :  *      Constant-simplify any FUNCTION RTEs in the FROM clause, and then
     610             :  *      attempt to "inline" any that are set-returning functions.
     611             :  *
     612             :  * If an RTE_FUNCTION rtable entry invokes a set-returning function that
     613             :  * contains just a simple SELECT, we can convert the rtable entry to an
     614             :  * RTE_SUBQUERY entry exposing the SELECT directly.  This is especially
     615             :  * useful if the subquery can then be "pulled up" for further optimization,
     616             :  * but we do it even if not, to reduce executor overhead.
     617             :  *
     618             :  * This has to be done before we have started to do any optimization of
     619             :  * subqueries, else any such steps wouldn't get applied to subqueries
     620             :  * obtained via inlining.  However, we do it after pull_up_sublinks
     621             :  * so that we can inline any functions used in SubLink subselects.
     622             :  *
     623             :  * The reason for applying const-simplification at this stage is that
     624             :  * (a) we'd need to do it anyway to inline a SRF, and (b) by doing it now,
     625             :  * we can be sure that pull_up_constant_function() will see constants
     626             :  * if there are constants to be seen.  This approach also guarantees
     627             :  * that every FUNCTION RTE has been const-simplified, allowing planner.c's
     628             :  * preprocess_expression() to skip doing it again.
     629             :  *
     630             :  * Like most of the planner, this feels free to scribble on its input data
     631             :  * structure.
     632             :  */
     633             : void
     634      335144 : preprocess_function_rtes(PlannerInfo *root)
     635             : {
     636             :     ListCell   *rt;
     637             : 
     638      885204 :     foreach(rt, root->parse->rtable)
     639             :     {
     640      550060 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
     641             : 
     642      550060 :         if (rte->rtekind == RTE_FUNCTION)
     643             :         {
     644             :             Query      *funcquery;
     645             : 
     646             :             /* Apply const-simplification */
     647       28626 :             rte->functions = (List *)
     648       28626 :                 eval_const_expressions(root, (Node *) rte->functions);
     649             : 
     650             :             /* Check safety of expansion, and expand if possible */
     651       28626 :             funcquery = inline_set_returning_function(root, rte);
     652       28626 :             if (funcquery)
     653             :             {
     654             :                 /* Successful expansion, convert the RTE to a subquery */
     655          32 :                 rte->rtekind = RTE_SUBQUERY;
     656          32 :                 rte->subquery = funcquery;
     657          32 :                 rte->security_barrier = false;
     658             :                 /* Clear fields that should not be set in a subquery RTE */
     659          32 :                 rte->functions = NIL;
     660          32 :                 rte->funcordinality = false;
     661             :             }
     662             :         }
     663             :     }
     664      335144 : }
     665             : 
     666             : /*
     667             :  * pull_up_subqueries
     668             :  *      Look for subqueries in the rangetable that can be pulled up into
     669             :  *      the parent query.  If the subquery has no special features like
     670             :  *      grouping/aggregation then we can merge it into the parent's jointree.
     671             :  *      Also, subqueries that are simple UNION ALL structures can be
     672             :  *      converted into "append relations".
     673             :  */
     674             : void
     675      335144 : pull_up_subqueries(PlannerInfo *root)
     676             : {
     677             :     /* Top level of jointree must always be a FromExpr */
     678             :     Assert(IsA(root->parse->jointree, FromExpr));
     679             :     /* Recursion starts with no containing join nor appendrel */
     680      670284 :     root->parse->jointree = (FromExpr *)
     681      335144 :         pull_up_subqueries_recurse(root, (Node *) root->parse->jointree,
     682             :                                    NULL, NULL, NULL);
     683             :     /* We should still have a FromExpr */
     684             :     Assert(IsA(root->parse->jointree, FromExpr));
     685      335140 : }
     686             : 
     687             : /*
     688             :  * pull_up_subqueries_recurse
     689             :  *      Recursive guts of pull_up_subqueries.
     690             :  *
     691             :  * This recursively processes the jointree and returns a modified jointree.
     692             :  *
     693             :  * If this jointree node is within either side of an outer join, then
     694             :  * lowest_outer_join references the lowest such JoinExpr node; otherwise
     695             :  * it is NULL.  We use this to constrain the effects of LATERAL subqueries.
     696             :  *
     697             :  * If this jointree node is within the nullable side of an outer join, then
     698             :  * lowest_nulling_outer_join references the lowest such JoinExpr node;
     699             :  * otherwise it is NULL.  This forces use of the PlaceHolderVar mechanism for
     700             :  * references to non-nullable targetlist items, but only for references above
     701             :  * that join.
     702             :  *
     703             :  * If we are looking at a member subquery of an append relation,
     704             :  * containing_appendrel describes that relation; else it is NULL.
     705             :  * This forces use of the PlaceHolderVar mechanism for all non-Var targetlist
     706             :  * items, and puts some additional restrictions on what can be pulled up.
     707             :  *
     708             :  * A tricky aspect of this code is that if we pull up a subquery we have
     709             :  * to replace Vars that reference the subquery's outputs throughout the
     710             :  * parent query, including quals attached to jointree nodes above the one
     711             :  * we are currently processing!  We handle this by being careful to maintain
     712             :  * validity of the jointree structure while recursing, in the following sense:
     713             :  * whenever we recurse, all qual expressions in the tree must be reachable
     714             :  * from the top level, in case the recursive call needs to modify them.
     715             :  *
     716             :  * Notice also that we can't turn pullup_replace_vars loose on the whole
     717             :  * jointree, because it'd return a mutated copy of the tree; we have to
     718             :  * invoke it just on the quals, instead.  This behavior is what makes it
     719             :  * reasonable to pass lowest_outer_join and lowest_nulling_outer_join as
     720             :  * pointers rather than some more-indirect way of identifying the lowest
     721             :  * OJs.  Likewise, we don't replace append_rel_list members but only their
     722             :  * substructure, so the containing_appendrel reference is safe to use.
     723             :  */
     724             : static Node *
     725      806584 : pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
     726             :                            JoinExpr *lowest_outer_join,
     727             :                            JoinExpr *lowest_nulling_outer_join,
     728             :                            AppendRelInfo *containing_appendrel)
     729             : {
     730             :     Assert(jtnode != NULL);
     731      806584 :     if (IsA(jtnode, RangeTblRef))
     732             :     {
     733      407774 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
     734      407774 :         RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
     735             : 
     736             :         /*
     737             :          * Is this a subquery RTE, and if so, is the subquery simple enough to
     738             :          * pull up?
     739             :          *
     740             :          * If we are looking at an append-relation member, we can't pull it up
     741             :          * unless is_safe_append_member says so.
     742             :          */
     743      451666 :         if (rte->rtekind == RTE_SUBQUERY &&
     744       83928 :             is_simple_subquery(rte->subquery, rte, lowest_outer_join) &&
     745        3692 :             (containing_appendrel == NULL ||
     746        3692 :              is_safe_append_member(rte->subquery)))
     747       37750 :             return pull_up_simple_subquery(root, jtnode, rte,
     748             :                                            lowest_outer_join,
     749             :                                            lowest_nulling_outer_join,
     750             :                                            containing_appendrel);
     751             : 
     752             :         /*
     753             :          * Alternatively, is it a simple UNION ALL subquery?  If so, flatten
     754             :          * into an "append relation".
     755             :          *
     756             :          * It's safe to do this regardless of whether this query is itself an
     757             :          * appendrel member.  (If you're thinking we should try to flatten the
     758             :          * two levels of appendrel together, you're right; but we handle that
     759             :          * in set_append_rel_pathlist, not here.)
     760             :          */
     761      376166 :         if (rte->rtekind == RTE_SUBQUERY &&
     762        6142 :             is_simple_union_all(rte->subquery))
     763         674 :             return pull_up_simple_union_all(root, jtnode, rte);
     764             : 
     765             :         /*
     766             :          * Or perhaps it's a simple VALUES RTE?
     767             :          *
     768             :          * We don't allow VALUES pullup below an outer join nor into an
     769             :          * appendrel (such cases are impossible anyway at the moment).
     770             :          */
     771      369350 :         if (rte->rtekind == RTE_VALUES &&
     772        4302 :             lowest_outer_join == NULL &&
     773        4302 :             containing_appendrel == NULL &&
     774        4302 :             is_simple_values(root, rte))
     775         526 :             return pull_up_simple_values(root, jtnode, rte);
     776             : 
     777             :         /*
     778             :          * Or perhaps it's a FUNCTION RTE that we could inline?
     779             :          */
     780      368824 :         if (rte->rtekind == RTE_FUNCTION)
     781       28594 :             return pull_up_constant_function(root, jtnode, rte,
     782             :                                              lowest_nulling_outer_join,
     783             :                                              containing_appendrel);
     784             : 
     785             :         /* Otherwise, do nothing at this node. */
     786             :     }
     787      398810 :     else if (IsA(jtnode, FromExpr))
     788             :     {
     789      342996 :         FromExpr   *f = (FromExpr *) jtnode;
     790             :         ListCell   *l;
     791             : 
     792             :         Assert(containing_appendrel == NULL);
     793             :         /* Recursively transform all the child nodes */
     794      698836 :         foreach(l, f->fromlist)
     795             :         {
     796      355844 :             lfirst(l) = pull_up_subqueries_recurse(root, lfirst(l),
     797             :                                                    lowest_outer_join,
     798             :                                                    lowest_nulling_outer_join,
     799             :                                                    NULL);
     800             :         }
     801             :     }
     802       55814 :     else if (IsA(jtnode, JoinExpr))
     803             :     {
     804       55814 :         JoinExpr   *j = (JoinExpr *) jtnode;
     805             : 
     806             :         Assert(containing_appendrel == NULL);
     807             :         /* Recurse, being careful to tell myself when inside outer join */
     808       55814 :         switch (j->jointype)
     809             :         {
     810             :             case JOIN_INNER:
     811       12500 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
     812             :                                                      lowest_outer_join,
     813             :                                                      lowest_nulling_outer_join,
     814             :                                                      NULL);
     815       12500 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
     816             :                                                      lowest_outer_join,
     817             :                                                      lowest_nulling_outer_join,
     818             :                                                      NULL);
     819       12500 :                 break;
     820             :             case JOIN_LEFT:
     821             :             case JOIN_SEMI:
     822             :             case JOIN_ANTI:
     823       42660 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
     824             :                                                      j,
     825             :                                                      lowest_nulling_outer_join,
     826             :                                                      NULL);
     827       42660 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
     828             :                                                      j,
     829             :                                                      j,
     830             :                                                      NULL);
     831       42660 :                 break;
     832             :             case JOIN_FULL:
     833         482 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
     834             :                                                      j,
     835             :                                                      j,
     836             :                                                      NULL);
     837         482 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
     838             :                                                      j,
     839             :                                                      j,
     840             :                                                      NULL);
     841         482 :                 break;
     842             :             case JOIN_RIGHT:
     843         172 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
     844             :                                                      j,
     845             :                                                      j,
     846             :                                                      NULL);
     847         172 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
     848             :                                                      j,
     849             :                                                      lowest_nulling_outer_join,
     850             :                                                      NULL);
     851         172 :                 break;
     852             :             default:
     853           0 :                 elog(ERROR, "unrecognized join type: %d",
     854             :                      (int) j->jointype);
     855             :                 break;
     856             :         }
     857             :     }
     858             :     else
     859           0 :         elog(ERROR, "unrecognized node type: %d",
     860             :              (int) nodeTag(jtnode));
     861      739036 :     return jtnode;
     862             : }
     863             : 
     864             : /*
     865             :  * pull_up_simple_subquery
     866             :  *      Attempt to pull up a single simple subquery.
     867             :  *
     868             :  * jtnode is a RangeTblRef that has been tentatively identified as a simple
     869             :  * subquery by pull_up_subqueries.  We return the replacement jointree node,
     870             :  * or jtnode itself if we determine that the subquery can't be pulled up
     871             :  * after all.
     872             :  *
     873             :  * rte is the RangeTblEntry referenced by jtnode.  Remaining parameters are
     874             :  * as for pull_up_subqueries_recurse.
     875             :  */
     876             : static Node *
     877       37750 : pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
     878             :                         JoinExpr *lowest_outer_join,
     879             :                         JoinExpr *lowest_nulling_outer_join,
     880             :                         AppendRelInfo *containing_appendrel)
     881             : {
     882       37750 :     Query      *parse = root->parse;
     883       37750 :     int         varno = ((RangeTblRef *) jtnode)->rtindex;
     884             :     Query      *subquery;
     885             :     PlannerInfo *subroot;
     886             :     int         rtoffset;
     887             :     pullup_replace_vars_context rvcontext;
     888             :     ListCell   *lc;
     889             : 
     890             :     /*
     891             :      * Need a modifiable copy of the subquery to hack on.  Even if we didn't
     892             :      * sometimes choose not to pull up below, we must do this to avoid
     893             :      * problems if the same subquery is referenced from multiple jointree
     894             :      * items (which can't happen normally, but might after rule rewriting).
     895             :      */
     896       37750 :     subquery = copyObject(rte->subquery);
     897             : 
     898             :     /*
     899             :      * Create a PlannerInfo data structure for this subquery.
     900             :      *
     901             :      * NOTE: the next few steps should match the first processing in
     902             :      * subquery_planner().  Can we refactor to avoid code duplication, or
     903             :      * would that just make things uglier?
     904             :      */
     905       37750 :     subroot = makeNode(PlannerInfo);
     906       37750 :     subroot->parse = subquery;
     907       37750 :     subroot->glob = root->glob;
     908       37750 :     subroot->query_level = root->query_level;
     909       37750 :     subroot->parent_root = root->parent_root;
     910       37750 :     subroot->plan_params = NIL;
     911       37750 :     subroot->outer_params = NULL;
     912       37750 :     subroot->planner_cxt = CurrentMemoryContext;
     913       37750 :     subroot->init_plans = NIL;
     914       37750 :     subroot->cte_plan_ids = NIL;
     915       37750 :     subroot->multiexpr_params = NIL;
     916       37750 :     subroot->eq_classes = NIL;
     917       37750 :     subroot->ec_merging_done = false;
     918       37750 :     subroot->append_rel_list = NIL;
     919       37750 :     subroot->rowMarks = NIL;
     920       37750 :     memset(subroot->upper_rels, 0, sizeof(subroot->upper_rels));
     921       37750 :     memset(subroot->upper_targets, 0, sizeof(subroot->upper_targets));
     922       37750 :     subroot->processed_tlist = NIL;
     923       37750 :     subroot->grouping_map = NULL;
     924       37750 :     subroot->minmax_aggs = NIL;
     925       37750 :     subroot->qual_security_level = 0;
     926       37750 :     subroot->inhTargetKind = INHKIND_NONE;
     927       37750 :     subroot->hasRecursion = false;
     928       37750 :     subroot->wt_param_id = -1;
     929       37750 :     subroot->non_recursive_path = NULL;
     930             : 
     931             :     /* No CTEs to worry about */
     932             :     Assert(subquery->cteList == NIL);
     933             : 
     934             :     /*
     935             :      * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
     936             :      * that we don't need so many special cases to deal with that situation.
     937             :      */
     938       37750 :     replace_empty_jointree(subquery);
     939             : 
     940             :     /*
     941             :      * Pull up any SubLinks within the subquery's quals, so that we don't
     942             :      * leave unoptimized SubLinks behind.
     943             :      */
     944       37750 :     if (subquery->hasSubLinks)
     945        9566 :         pull_up_sublinks(subroot);
     946             : 
     947             :     /*
     948             :      * Similarly, preprocess its function RTEs to inline any set-returning
     949             :      * functions in its rangetable.
     950             :      */
     951       37750 :     preprocess_function_rtes(subroot);
     952             : 
     953             :     /*
     954             :      * Recursively pull up the subquery's subqueries, so that
     955             :      * pull_up_subqueries' processing is complete for its jointree and
     956             :      * rangetable.
     957             :      *
     958             :      * Note: it's okay that the subquery's recursion starts with NULL for
     959             :      * containing-join info, even if we are within an outer join in the upper
     960             :      * query; the lower query starts with a clean slate for outer-join
     961             :      * semantics.  Likewise, we needn't pass down appendrel state.
     962             :      */
     963       37750 :     pull_up_subqueries(subroot);
     964             : 
     965             :     /*
     966             :      * Now we must recheck whether the subquery is still simple enough to pull
     967             :      * up.  If not, abandon processing it.
     968             :      *
     969             :      * We don't really need to recheck all the conditions involved, but it's
     970             :      * easier just to keep this "if" looking the same as the one in
     971             :      * pull_up_subqueries_recurse.
     972             :      */
     973       75464 :     if (is_simple_subquery(subquery, rte, lowest_outer_join) &&
     974        1406 :         (containing_appendrel == NULL || is_safe_append_member(subquery)))
     975             :     {
     976             :         /* good to go */
     977             :     }
     978             :     else
     979             :     {
     980             :         /*
     981             :          * Give up, return unmodified RangeTblRef.
     982             :          *
     983             :          * Note: The work we just did will be redone when the subquery gets
     984             :          * planned on its own.  Perhaps we could avoid that by storing the
     985             :          * modified subquery back into the rangetable, but I'm not gonna risk
     986             :          * it now.
     987             :          */
     988          36 :         return jtnode;
     989             :     }
     990             : 
     991             :     /*
     992             :      * We must flatten any join alias Vars in the subquery's targetlist,
     993             :      * because pulling up the subquery's subqueries might have changed their
     994             :      * expansions into arbitrary expressions, which could affect
     995             :      * pullup_replace_vars' decisions about whether PlaceHolderVar wrappers
     996             :      * are needed for tlist entries.  (Likely it'd be better to do
     997             :      * flatten_join_alias_vars on the whole query tree at some earlier stage,
     998             :      * maybe even in the rewriter; but for now let's just fix this case here.)
     999             :      */
    1000       37714 :     subquery->targetList = (List *)
    1001       37714 :         flatten_join_alias_vars(subroot->parse, (Node *) subquery->targetList);
    1002             : 
    1003             :     /*
    1004             :      * Adjust level-0 varnos in subquery so that we can append its rangetable
    1005             :      * to upper query's.  We have to fix the subquery's append_rel_list as
    1006             :      * well.
    1007             :      */
    1008       37714 :     rtoffset = list_length(parse->rtable);
    1009       37714 :     OffsetVarNodes((Node *) subquery, rtoffset, 0);
    1010       37714 :     OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);
    1011             : 
    1012             :     /*
    1013             :      * Upper-level vars in subquery are now one level closer to their parent
    1014             :      * than before.
    1015             :      */
    1016       37714 :     IncrementVarSublevelsUp((Node *) subquery, -1, 1);
    1017       37714 :     IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);
    1018             : 
    1019             :     /*
    1020             :      * The subquery's targetlist items are now in the appropriate form to
    1021             :      * insert into the top query, except that we may need to wrap them in
    1022             :      * PlaceHolderVars.  Set up required context data for pullup_replace_vars.
    1023             :      */
    1024       37714 :     rvcontext.root = root;
    1025       37714 :     rvcontext.targetlist = subquery->targetList;
    1026       37714 :     rvcontext.target_rte = rte;
    1027       37714 :     if (rte->lateral)
    1028         280 :         rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree,
    1029             :                                                   true);
    1030             :     else                        /* won't need relids */
    1031       37434 :         rvcontext.relids = NULL;
    1032       37714 :     rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
    1033       37714 :     rvcontext.varno = varno;
    1034             :     /* these flags will be set below, if needed */
    1035       37714 :     rvcontext.need_phvs = false;
    1036       37714 :     rvcontext.wrap_non_vars = false;
    1037             :     /* initialize cache array with indexes 0 .. length(tlist) */
    1038       37714 :     rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) *
    1039             :                                  sizeof(Node *));
    1040             : 
    1041             :     /*
    1042             :      * If we are under an outer join then non-nullable items and lateral
    1043             :      * references may have to be turned into PlaceHolderVars.
    1044             :      */
    1045       37714 :     if (lowest_nulling_outer_join != NULL)
    1046        1138 :         rvcontext.need_phvs = true;
    1047             : 
    1048             :     /*
    1049             :      * If we are dealing with an appendrel member then anything that's not a
    1050             :      * simple Var has to be turned into a PlaceHolderVar.  We force this to
    1051             :      * ensure that what we pull up doesn't get merged into a surrounding
    1052             :      * expression during later processing and then fail to match the
    1053             :      * expression actually available from the appendrel.
    1054             :      */
    1055       37714 :     if (containing_appendrel != NULL)
    1056             :     {
    1057        1370 :         rvcontext.need_phvs = true;
    1058        1370 :         rvcontext.wrap_non_vars = true;
    1059             :     }
    1060             : 
    1061             :     /*
    1062             :      * If the parent query uses grouping sets, we need a PlaceHolderVar for
    1063             :      * anything that's not a simple Var.  Again, this ensures that expressions
    1064             :      * retain their separate identity so that they will match grouping set
    1065             :      * columns when appropriate.  (It'd be sufficient to wrap values used in
    1066             :      * grouping set columns, and do so only in non-aggregated portions of the
    1067             :      * tlist and havingQual, but that would require a lot of infrastructure
    1068             :      * that pullup_replace_vars hasn't currently got.)
    1069             :      */
    1070       37714 :     if (parse->groupingSets)
    1071             :     {
    1072         136 :         rvcontext.need_phvs = true;
    1073         136 :         rvcontext.wrap_non_vars = true;
    1074             :     }
    1075             : 
    1076             :     /*
    1077             :      * Replace all of the top query's references to the subquery's outputs
    1078             :      * with copies of the adjusted subtlist items, being careful not to
    1079             :      * replace any of the jointree structure.
    1080             :      */
    1081       37714 :     perform_pullup_replace_vars(root, &rvcontext,
    1082             :                                 lowest_nulling_outer_join,
    1083             :                                 containing_appendrel);
    1084             : 
    1085             :     /*
    1086             :      * If the subquery had a LATERAL marker, propagate that to any of its
    1087             :      * child RTEs that could possibly now contain lateral cross-references.
    1088             :      * The children might or might not contain any actual lateral
    1089             :      * cross-references, but we have to mark the pulled-up child RTEs so that
    1090             :      * later planner stages will check for such.
    1091             :      */
    1092       37710 :     if (rte->lateral)
    1093             :     {
    1094         732 :         foreach(lc, subquery->rtable)
    1095             :         {
    1096         452 :             RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(lc);
    1097             : 
    1098         452 :             switch (child_rte->rtekind)
    1099             :             {
    1100             :                 case RTE_RELATION:
    1101         216 :                     if (child_rte->tablesample)
    1102          12 :                         child_rte->lateral = true;
    1103         216 :                     break;
    1104             :                 case RTE_SUBQUERY:
    1105             :                 case RTE_FUNCTION:
    1106             :                 case RTE_VALUES:
    1107             :                 case RTE_TABLEFUNC:
    1108          92 :                     child_rte->lateral = true;
    1109          92 :                     break;
    1110             :                 case RTE_JOIN:
    1111             :                 case RTE_CTE:
    1112             :                 case RTE_NAMEDTUPLESTORE:
    1113             :                 case RTE_RESULT:
    1114             :                     /* these can't contain any lateral references */
    1115         144 :                     break;
    1116             :             }
    1117             :         }
    1118             :     }
    1119             : 
    1120             :     /*
    1121             :      * Now append the adjusted rtable entries to upper query. (We hold off
    1122             :      * until after fixing the upper rtable entries; no point in running that
    1123             :      * code on the subquery ones too.)
    1124             :      */
    1125       37710 :     parse->rtable = list_concat(parse->rtable, subquery->rtable);
    1126             : 
    1127             :     /*
    1128             :      * Pull up any FOR UPDATE/SHARE markers, too.  (OffsetVarNodes already
    1129             :      * adjusted the marker rtindexes, so just concat the lists.)
    1130             :      */
    1131       37710 :     parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
    1132             : 
    1133             :     /*
    1134             :      * We also have to fix the relid sets of any PlaceHolderVar nodes in the
    1135             :      * parent query.  (This could perhaps be done by pullup_replace_vars(),
    1136             :      * but it seems cleaner to use two passes.)  Note in particular that any
    1137             :      * PlaceHolderVar nodes just created by pullup_replace_vars() will be
    1138             :      * adjusted, so having created them with the subquery's varno is correct.
    1139             :      *
    1140             :      * Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We
    1141             :      * already checked that this won't require introducing multiple subrelids
    1142             :      * into the single-slot AppendRelInfo structs.
    1143             :      */
    1144       70586 :     if (parse->hasSubLinks || root->glob->lastPHId != 0 ||
    1145       32876 :         root->append_rel_list)
    1146             :     {
    1147             :         Relids      subrelids;
    1148             : 
    1149        5808 :         subrelids = get_relids_in_jointree((Node *) subquery->jointree, false);
    1150        5808 :         substitute_phv_relids((Node *) parse, varno, subrelids);
    1151        5808 :         fix_append_rel_relids(root->append_rel_list, varno, subrelids);
    1152             :     }
    1153             : 
    1154             :     /*
    1155             :      * And now add subquery's AppendRelInfos to our list.
    1156             :      */
    1157       37710 :     root->append_rel_list = list_concat(root->append_rel_list,
    1158       37710 :                                         subroot->append_rel_list);
    1159             : 
    1160             :     /*
    1161             :      * We don't have to do the equivalent bookkeeping for outer-join info,
    1162             :      * because that hasn't been set up yet.  placeholder_list likewise.
    1163             :      */
    1164             :     Assert(root->join_info_list == NIL);
    1165             :     Assert(subroot->join_info_list == NIL);
    1166             :     Assert(root->placeholder_list == NIL);
    1167             :     Assert(subroot->placeholder_list == NIL);
    1168             : 
    1169             :     /*
    1170             :      * Miscellaneous housekeeping.
    1171             :      *
    1172             :      * Although replace_rte_variables() faithfully updated parse->hasSubLinks
    1173             :      * if it copied any SubLinks out of the subquery's targetlist, we still
    1174             :      * could have SubLinks added to the query in the expressions of FUNCTION
    1175             :      * and VALUES RTEs copied up from the subquery.  So it's necessary to copy
    1176             :      * subquery->hasSubLinks anyway.  Perhaps this can be improved someday.
    1177             :      */
    1178       37710 :     parse->hasSubLinks |= subquery->hasSubLinks;
    1179             : 
    1180             :     /* If subquery had any RLS conditions, now main query does too */
    1181       37710 :     parse->hasRowSecurity |= subquery->hasRowSecurity;
    1182             : 
    1183             :     /*
    1184             :      * subquery won't be pulled up if it hasAggs, hasWindowFuncs, or
    1185             :      * hasTargetSRFs, so no work needed on those flags
    1186             :      */
    1187             : 
    1188             :     /*
    1189             :      * Return the adjusted subquery jointree to replace the RangeTblRef entry
    1190             :      * in parent's jointree; or, if the FromExpr is degenerate, just return
    1191             :      * its single member.
    1192             :      */
    1193             :     Assert(IsA(subquery->jointree, FromExpr));
    1194             :     Assert(subquery->jointree->fromlist != NIL);
    1195       69782 :     if (subquery->jointree->quals == NULL &&
    1196       32072 :         list_length(subquery->jointree->fromlist) == 1)
    1197       31952 :         return (Node *) linitial(subquery->jointree->fromlist);
    1198             : 
    1199        5758 :     return (Node *) subquery->jointree;
    1200             : }
    1201             : 
    1202             : /*
    1203             :  * pull_up_simple_union_all
    1204             :  *      Pull up a single simple UNION ALL subquery.
    1205             :  *
    1206             :  * jtnode is a RangeTblRef that has been identified as a simple UNION ALL
    1207             :  * subquery by pull_up_subqueries.  We pull up the leaf subqueries and
    1208             :  * build an "append relation" for the union set.  The result value is just
    1209             :  * jtnode, since we don't actually need to change the query jointree.
    1210             :  */
    1211             : static Node *
    1212         674 : pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
    1213             : {
    1214         674 :     int         varno = ((RangeTblRef *) jtnode)->rtindex;
    1215         674 :     Query      *subquery = rte->subquery;
    1216         674 :     int         rtoffset = list_length(root->parse->rtable);
    1217             :     List       *rtable;
    1218             : 
    1219             :     /*
    1220             :      * Make a modifiable copy of the subquery's rtable, so we can adjust
    1221             :      * upper-level Vars in it.  There are no such Vars in the setOperations
    1222             :      * tree proper, so fixing the rtable should be sufficient.
    1223             :      */
    1224         674 :     rtable = copyObject(subquery->rtable);
    1225             : 
    1226             :     /*
    1227             :      * Upper-level vars in subquery are now one level closer to their parent
    1228             :      * than before.  We don't have to worry about offsetting varnos, though,
    1229             :      * because the UNION leaf queries can't cross-reference each other.
    1230             :      */
    1231         674 :     IncrementVarSublevelsUp_rtable(rtable, -1, 1);
    1232             : 
    1233             :     /*
    1234             :      * If the UNION ALL subquery had a LATERAL marker, propagate that to all
    1235             :      * its children.  The individual children might or might not contain any
    1236             :      * actual lateral cross-references, but we have to mark the pulled-up
    1237             :      * child RTEs so that later planner stages will check for such.
    1238             :      */
    1239         674 :     if (rte->lateral)
    1240             :     {
    1241             :         ListCell   *rt;
    1242             : 
    1243          72 :         foreach(rt, rtable)
    1244             :         {
    1245          48 :             RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(rt);
    1246             : 
    1247             :             Assert(child_rte->rtekind == RTE_SUBQUERY);
    1248          48 :             child_rte->lateral = true;
    1249             :         }
    1250             :     }
    1251             : 
    1252             :     /*
    1253             :      * Append child RTEs to parent rtable.
    1254             :      */
    1255         674 :     root->parse->rtable = list_concat(root->parse->rtable, rtable);
    1256             : 
    1257             :     /*
    1258             :      * Recursively scan the subquery's setOperations tree and add
    1259             :      * AppendRelInfo nodes for leaf subqueries to the parent's
    1260             :      * append_rel_list.  Also apply pull_up_subqueries to the leaf subqueries.
    1261             :      */
    1262             :     Assert(subquery->setOperations);
    1263         674 :     pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
    1264             :                                rtoffset);
    1265             : 
    1266             :     /*
    1267             :      * Mark the parent as an append relation.
    1268             :      */
    1269         674 :     rte->inh = true;
    1270             : 
    1271         674 :     return jtnode;
    1272             : }
    1273             : 
    1274             : /*
    1275             :  * pull_up_union_leaf_queries -- recursive guts of pull_up_simple_union_all
    1276             :  *
    1277             :  * Build an AppendRelInfo for each leaf query in the setop tree, and then
    1278             :  * apply pull_up_subqueries to the leaf query.
    1279             :  *
    1280             :  * Note that setOpQuery is the Query containing the setOp node, whose tlist
    1281             :  * contains references to all the setop output columns.  When called from
    1282             :  * pull_up_simple_union_all, this is *not* the same as root->parse, which is
    1283             :  * the parent Query we are pulling up into.
    1284             :  *
    1285             :  * parentRTindex is the appendrel parent's index in root->parse->rtable.
    1286             :  *
    1287             :  * The child RTEs have already been copied to the parent.  childRToffset
    1288             :  * tells us where in the parent's range table they were copied.  When called
    1289             :  * from flatten_simple_union_all, childRToffset is 0 since the child RTEs
    1290             :  * were already in root->parse->rtable and no RT index adjustment is needed.
    1291             :  */
    1292             : static void
    1293        6056 : pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex,
    1294             :                            Query *setOpQuery, int childRToffset)
    1295             : {
    1296        6056 :     if (IsA(setOp, RangeTblRef))
    1297             :     {
    1298        3968 :         RangeTblRef *rtr = (RangeTblRef *) setOp;
    1299             :         int         childRTindex;
    1300             :         AppendRelInfo *appinfo;
    1301             : 
    1302             :         /*
    1303             :          * Calculate the index in the parent's range table
    1304             :          */
    1305        3968 :         childRTindex = childRToffset + rtr->rtindex;
    1306             : 
    1307             :         /*
    1308             :          * Build a suitable AppendRelInfo, and attach to parent's list.
    1309             :          */
    1310        3968 :         appinfo = makeNode(AppendRelInfo);
    1311        3968 :         appinfo->parent_relid = parentRTindex;
    1312        3968 :         appinfo->child_relid = childRTindex;
    1313        3968 :         appinfo->parent_reltype = InvalidOid;
    1314        3968 :         appinfo->child_reltype = InvalidOid;
    1315        3968 :         make_setop_translation_list(setOpQuery, childRTindex,
    1316             :                                     &appinfo->translated_vars);
    1317        3968 :         appinfo->parent_reloid = InvalidOid;
    1318        3968 :         root->append_rel_list = lappend(root->append_rel_list, appinfo);
    1319             : 
    1320             :         /*
    1321             :          * Recursively apply pull_up_subqueries to the new child RTE.  (We
    1322             :          * must build the AppendRelInfo first, because this will modify it.)
    1323             :          * Note that we can pass NULL for containing-join info even if we're
    1324             :          * actually under an outer join, because the child's expressions
    1325             :          * aren't going to propagate up to the join.  Also, we ignore the
    1326             :          * possibility that pull_up_subqueries_recurse() returns a different
    1327             :          * jointree node than what we pass it; if it does, the important thing
    1328             :          * is that it replaced the child relid in the AppendRelInfo node.
    1329             :          */
    1330        3968 :         rtr = makeNode(RangeTblRef);
    1331        3968 :         rtr->rtindex = childRTindex;
    1332        3968 :         (void) pull_up_subqueries_recurse(root, (Node *) rtr,
    1333             :                                           NULL, NULL, appinfo);
    1334             :     }
    1335        2088 :     else if (IsA(setOp, SetOperationStmt))
    1336             :     {
    1337        2088 :         SetOperationStmt *op = (SetOperationStmt *) setOp;
    1338             : 
    1339             :         /* Recurse to reach leaf queries */
    1340        2088 :         pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
    1341             :                                    childRToffset);
    1342        2088 :         pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery,
    1343             :                                    childRToffset);
    1344             :     }
    1345             :     else
    1346             :     {
    1347           0 :         elog(ERROR, "unrecognized node type: %d",
    1348             :              (int) nodeTag(setOp));
    1349             :     }
    1350        6056 : }
    1351             : 
    1352             : /*
    1353             :  * make_setop_translation_list
    1354             :  *    Build the list of translations from parent Vars to child Vars for
    1355             :  *    a UNION ALL member.  (At this point it's just a simple list of
    1356             :  *    referencing Vars, but if we succeed in pulling up the member
    1357             :  *    subquery, the Vars will get replaced by pulled-up expressions.)
    1358             :  */
    1359             : static void
    1360        3968 : make_setop_translation_list(Query *query, Index newvarno,
    1361             :                             List **translated_vars)
    1362             : {
    1363        3968 :     List       *vars = NIL;
    1364             :     ListCell   *l;
    1365             : 
    1366        9790 :     foreach(l, query->targetList)
    1367             :     {
    1368        5822 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
    1369             : 
    1370        5822 :         if (tle->resjunk)
    1371           0 :             continue;
    1372             : 
    1373        5822 :         vars = lappend(vars, makeVarFromTargetEntry(newvarno, tle));
    1374             :     }
    1375             : 
    1376        3968 :     *translated_vars = vars;
    1377        3968 : }
    1378             : 
    1379             : /*
    1380             :  * is_simple_subquery
    1381             :  *    Check a subquery in the range table to see if it's simple enough
    1382             :  *    to pull up into the parent query.
    1383             :  *
    1384             :  * rte is the RTE_SUBQUERY RangeTblEntry that contained the subquery.
    1385             :  * (Note subquery is not necessarily equal to rte->subquery; it could be a
    1386             :  * processed copy of that.)
    1387             :  * lowest_outer_join is the lowest outer join above the subquery, or NULL.
    1388             :  */
    1389             : static bool
    1390       81642 : is_simple_subquery(Query *subquery, RangeTblEntry *rte,
    1391             :                    JoinExpr *lowest_outer_join)
    1392             : {
    1393             :     /*
    1394             :      * Let's just make sure it's a valid subselect ...
    1395             :      */
    1396      163284 :     if (!IsA(subquery, Query) ||
    1397       81642 :         subquery->commandType != CMD_SELECT)
    1398           0 :         elog(ERROR, "subquery is bogus");
    1399             : 
    1400             :     /*
    1401             :      * Can't currently pull up a query with setops (unless it's simple UNION
    1402             :      * ALL, which is handled by a different code path). Maybe after querytree
    1403             :      * redesign...
    1404             :      */
    1405       81642 :     if (subquery->setOperations)
    1406        1082 :         return false;
    1407             : 
    1408             :     /*
    1409             :      * Can't pull up a subquery involving grouping, aggregation, SRFs,
    1410             :      * sorting, limiting, or WITH.  (XXX WITH could possibly be allowed later)
    1411             :      *
    1412             :      * We also don't pull up a subquery that has explicit FOR UPDATE/SHARE
    1413             :      * clauses, because pullup would cause the locking to occur semantically
    1414             :      * higher than it should.  Implicit FOR UPDATE/SHARE is okay because in
    1415             :      * that case the locking was originally declared in the upper query
    1416             :      * anyway.
    1417             :      */
    1418      160654 :     if (subquery->hasAggs ||
    1419      160108 :         subquery->hasWindowFuncs ||
    1420      159068 :         subquery->hasTargetSRFs ||
    1421      158072 :         subquery->groupClause ||
    1422      158036 :         subquery->groupingSets ||
    1423      158036 :         subquery->havingQual ||
    1424      157562 :         subquery->sortClause ||
    1425      156984 :         subquery->distinctClause ||
    1426      156696 :         subquery->limitOffset ||
    1427      156360 :         subquery->limitCount ||
    1428      156196 :         subquery->hasForUpdate ||
    1429       78092 :         subquery->cteList)
    1430        2504 :         return false;
    1431             : 
    1432             :     /*
    1433             :      * Don't pull up if the RTE represents a security-barrier view; we
    1434             :      * couldn't prevent information leakage once the RTE's Vars are scattered
    1435             :      * about in the upper query.
    1436             :      */
    1437       78056 :     if (rte->security_barrier)
    1438         180 :         return false;
    1439             : 
    1440             :     /*
    1441             :      * If the subquery is LATERAL, check for pullup restrictions from that.
    1442             :      */
    1443       77876 :     if (rte->lateral)
    1444             :     {
    1445             :         bool        restricted;
    1446             :         Relids      safe_upper_varnos;
    1447             : 
    1448             :         /*
    1449             :          * The subquery's WHERE and JOIN/ON quals mustn't contain any lateral
    1450             :          * references to rels outside a higher outer join (including the case
    1451             :          * where the outer join is within the subquery itself).  In such a
    1452             :          * case, pulling up would result in a situation where we need to
    1453             :          * postpone quals from below an outer join to above it, which is
    1454             :          * probably completely wrong and in any case is a complication that
    1455             :          * doesn't seem worth addressing at the moment.
    1456             :          */
    1457         596 :         if (lowest_outer_join != NULL)
    1458             :         {
    1459         224 :             restricted = true;
    1460         224 :             safe_upper_varnos = get_relids_in_jointree((Node *) lowest_outer_join,
    1461             :                                                        true);
    1462             :         }
    1463             :         else
    1464             :         {
    1465         372 :             restricted = false;
    1466         372 :             safe_upper_varnos = NULL;   /* doesn't matter */
    1467             :         }
    1468             : 
    1469         596 :         if (jointree_contains_lateral_outer_refs((Node *) subquery->jointree,
    1470             :                                                  restricted, safe_upper_varnos))
    1471           8 :             return false;
    1472             : 
    1473             :         /*
    1474             :          * If there's an outer join above the LATERAL subquery, also disallow
    1475             :          * pullup if the subquery's targetlist has any references to rels
    1476             :          * outside the outer join, since these might get pulled into quals
    1477             :          * above the subquery (but in or below the outer join) and then lead
    1478             :          * to qual-postponement issues similar to the case checked for above.
    1479             :          * (We wouldn't need to prevent pullup if no such references appear in
    1480             :          * outer-query quals, but we don't have enough info here to check
    1481             :          * that.  Also, maybe this restriction could be removed if we forced
    1482             :          * such refs to be wrapped in PlaceHolderVars, even when they're below
    1483             :          * the nearest outer join?  But it's a pretty hokey usage, so not
    1484             :          * clear this is worth sweating over.)
    1485             :          */
    1486         588 :         if (lowest_outer_join != NULL)
    1487             :         {
    1488         224 :             Relids      lvarnos = pull_varnos_of_level((Node *) subquery->targetList, 1);
    1489             : 
    1490         224 :             if (!bms_is_subset(lvarnos, safe_upper_varnos))
    1491           8 :                 return false;
    1492             :         }
    1493             :     }
    1494             : 
    1495             :     /*
    1496             :      * Don't pull up a subquery that has any volatile functions in its
    1497             :      * targetlist.  Otherwise we might introduce multiple evaluations of these
    1498             :      * functions, if they get copied to multiple places in the upper query,
    1499             :      * leading to surprising results.  (Note: the PlaceHolderVar mechanism
    1500             :      * doesn't quite guarantee single evaluation; else we could pull up anyway
    1501             :      * and just wrap such items in PlaceHolderVars ...)
    1502             :      */
    1503       77860 :     if (contain_volatile_functions((Node *) subquery->targetList))
    1504          74 :         return false;
    1505             : 
    1506       77786 :     return true;
    1507             : }
    1508             : 
    1509             : /*
    1510             :  * pull_up_simple_values
    1511             :  *      Pull up a single simple VALUES RTE.
    1512             :  *
    1513             :  * jtnode is a RangeTblRef that has been identified as a simple VALUES RTE
    1514             :  * by pull_up_subqueries.  We always return a RangeTblRef representing a
    1515             :  * RESULT RTE to replace it (all failure cases should have been detected by
    1516             :  * is_simple_values()).  Actually, what we return is just jtnode, because
    1517             :  * we replace the VALUES RTE in the rangetable with the RESULT RTE.
    1518             :  *
    1519             :  * rte is the RangeTblEntry referenced by jtnode.  Because of the limited
    1520             :  * possible usage of VALUES RTEs, we do not need the remaining parameters
    1521             :  * of pull_up_subqueries_recurse.
    1522             :  */
    1523             : static Node *
    1524         526 : pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
    1525             : {
    1526         526 :     Query      *parse = root->parse;
    1527         526 :     int         varno = ((RangeTblRef *) jtnode)->rtindex;
    1528             :     List       *values_list;
    1529             :     List       *tlist;
    1530             :     AttrNumber  attrno;
    1531             :     pullup_replace_vars_context rvcontext;
    1532             :     ListCell   *lc;
    1533             : 
    1534             :     Assert(rte->rtekind == RTE_VALUES);
    1535             :     Assert(list_length(rte->values_lists) == 1);
    1536             : 
    1537             :     /*
    1538             :      * Need a modifiable copy of the VALUES list to hack on, just in case it's
    1539             :      * multiply referenced.
    1540             :      */
    1541         526 :     values_list = copyObject(linitial(rte->values_lists));
    1542             : 
    1543             :     /*
    1544             :      * The VALUES RTE can't contain any Vars of level zero, let alone any that
    1545             :      * are join aliases, so no need to flatten join alias Vars.
    1546             :      */
    1547             :     Assert(!contain_vars_of_level((Node *) values_list, 0));
    1548             : 
    1549             :     /*
    1550             :      * Set up required context data for pullup_replace_vars.  In particular,
    1551             :      * we have to make the VALUES list look like a subquery targetlist.
    1552             :      */
    1553         526 :     tlist = NIL;
    1554         526 :     attrno = 1;
    1555        1200 :     foreach(lc, values_list)
    1556             :     {
    1557         674 :         tlist = lappend(tlist,
    1558         674 :                         makeTargetEntry((Expr *) lfirst(lc),
    1559             :                                         attrno,
    1560             :                                         NULL,
    1561             :                                         false));
    1562         674 :         attrno++;
    1563             :     }
    1564         526 :     rvcontext.root = root;
    1565         526 :     rvcontext.targetlist = tlist;
    1566         526 :     rvcontext.target_rte = rte;
    1567         526 :     rvcontext.relids = NULL;
    1568         526 :     rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
    1569         526 :     rvcontext.varno = varno;
    1570         526 :     rvcontext.need_phvs = false;
    1571         526 :     rvcontext.wrap_non_vars = false;
    1572             :     /* initialize cache array with indexes 0 .. length(tlist) */
    1573         526 :     rvcontext.rv_cache = palloc0((list_length(tlist) + 1) *
    1574             :                                  sizeof(Node *));
    1575             : 
    1576             :     /*
    1577             :      * Replace all of the top query's references to the RTE's outputs with
    1578             :      * copies of the adjusted VALUES expressions, being careful not to replace
    1579             :      * any of the jointree structure.  We can assume there's no outer joins or
    1580             :      * appendrels in the dummy Query that surrounds a VALUES RTE.
    1581             :      */
    1582         526 :     perform_pullup_replace_vars(root, &rvcontext, NULL, NULL);
    1583             : 
    1584             :     /*
    1585             :      * There should be no appendrels to fix, nor any outer joins and hence no
    1586             :      * PlaceHolderVars.
    1587             :      */
    1588             :     Assert(root->append_rel_list == NIL);
    1589             :     Assert(root->join_info_list == NIL);
    1590             :     Assert(root->placeholder_list == NIL);
    1591             : 
    1592             :     /*
    1593             :      * Replace the VALUES RTE with a RESULT RTE.  The VALUES RTE is the only
    1594             :      * rtable entry in the current query level, so this is easy.
    1595             :      */
    1596             :     Assert(list_length(parse->rtable) == 1);
    1597             : 
    1598             :     /* Create suitable RTE */
    1599         526 :     rte = makeNode(RangeTblEntry);
    1600         526 :     rte->rtekind = RTE_RESULT;
    1601         526 :     rte->eref = makeAlias("*RESULT*", NIL);
    1602             : 
    1603             :     /* Replace rangetable */
    1604         526 :     parse->rtable = list_make1(rte);
    1605             : 
    1606             :     /* We could manufacture a new RangeTblRef, but the one we have is fine */
    1607             :     Assert(varno == 1);
    1608             : 
    1609         526 :     return jtnode;
    1610             : }
    1611             : 
    1612             : /*
    1613             :  * is_simple_values
    1614             :  *    Check a VALUES RTE in the range table to see if it's simple enough
    1615             :  *    to pull up into the parent query.
    1616             :  *
    1617             :  * rte is the RTE_VALUES RangeTblEntry to check.
    1618             :  */
    1619             : static bool
    1620        4302 : is_simple_values(PlannerInfo *root, RangeTblEntry *rte)
    1621             : {
    1622             :     Assert(rte->rtekind == RTE_VALUES);
    1623             : 
    1624             :     /*
    1625             :      * There must be exactly one VALUES list, else it's not semantically
    1626             :      * correct to replace the VALUES RTE with a RESULT RTE, nor would we have
    1627             :      * a unique set of expressions to substitute into the parent query.
    1628             :      */
    1629        4302 :     if (list_length(rte->values_lists) != 1)
    1630        3776 :         return false;
    1631             : 
    1632             :     /*
    1633             :      * Because VALUES can't appear under an outer join (or at least, we won't
    1634             :      * try to pull it up if it does), we need not worry about LATERAL, nor
    1635             :      * about validity of PHVs for the VALUES' outputs.
    1636             :      */
    1637             : 
    1638             :     /*
    1639             :      * Don't pull up a VALUES that contains any set-returning or volatile
    1640             :      * functions.  The considerations here are basically identical to the
    1641             :      * restrictions on a pull-able subquery's targetlist.
    1642             :      */
    1643        1052 :     if (expression_returns_set((Node *) rte->values_lists) ||
    1644         526 :         contain_volatile_functions((Node *) rte->values_lists))
    1645           0 :         return false;
    1646             : 
    1647             :     /*
    1648             :      * Do not pull up a VALUES that's not the only RTE in its parent query.
    1649             :      * This is actually the only case that the parser will generate at the
    1650             :      * moment, and assuming this is true greatly simplifies
    1651             :      * pull_up_simple_values().
    1652             :      */
    1653        1052 :     if (list_length(root->parse->rtable) != 1 ||
    1654         526 :         rte != (RangeTblEntry *) linitial(root->parse->rtable))
    1655           0 :         return false;
    1656             : 
    1657         526 :     return true;
    1658             : }
    1659             : 
    1660             : /*
    1661             :  * pull_up_constant_function
    1662             :  *      Pull up an RTE_FUNCTION expression that was simplified to a constant.
    1663             :  *
    1664             :  * jtnode is a RangeTblRef that has been identified as a FUNCTION RTE by
    1665             :  * pull_up_subqueries.  If its expression is just a Const, hoist that value
    1666             :  * up into the parent query, and replace the RTE_FUNCTION with RTE_RESULT.
    1667             :  *
    1668             :  * In principle we could pull up any immutable expression, but we don't.
    1669             :  * That might result in multiple evaluations of the expression, which could
    1670             :  * be costly if it's not just a Const.  Also, the main value of this is
    1671             :  * to let the constant participate in further const-folding, and of course
    1672             :  * that won't happen for a non-Const.
    1673             :  *
    1674             :  * The pulled-up value might need to be wrapped in a PlaceHolderVar if the
    1675             :  * RTE is below an outer join or is part of an appendrel; the extra
    1676             :  * parameters show whether that's needed.
    1677             :  */
    1678             : static Node *
    1679       28594 : pull_up_constant_function(PlannerInfo *root, Node *jtnode,
    1680             :                           RangeTblEntry *rte,
    1681             :                           JoinExpr *lowest_nulling_outer_join,
    1682             :                           AppendRelInfo *containing_appendrel)
    1683             : {
    1684       28594 :     Query      *parse = root->parse;
    1685             :     RangeTblFunction *rtf;
    1686             :     pullup_replace_vars_context rvcontext;
    1687             : 
    1688             :     /* Fail if the RTE has ORDINALITY - we don't implement that here. */
    1689       28594 :     if (rte->funcordinality)
    1690        6178 :         return jtnode;
    1691             : 
    1692             :     /* Fail if RTE isn't a single, simple Const expr */
    1693       22416 :     if (list_length(rte->functions) != 1)
    1694          40 :         return jtnode;
    1695       22376 :     rtf = linitial_node(RangeTblFunction, rte->functions);
    1696       22376 :     if (!IsA(rtf->funcexpr, Const))
    1697       22264 :         return jtnode;
    1698             : 
    1699             :     /* Create context for applying pullup_replace_vars */
    1700         112 :     rvcontext.root = root;
    1701         112 :     rvcontext.targetlist = list_make1(makeTargetEntry((Expr *) rtf->funcexpr,
    1702             :                                                       1,    /* resno */
    1703             :                                                       NULL, /* resname */
    1704             :                                                       false));  /* resjunk */
    1705         112 :     rvcontext.target_rte = rte;
    1706             : 
    1707             :     /*
    1708             :      * Since this function was reduced to a Const, it doesn't contain any
    1709             :      * lateral references, even if it's marked as LATERAL.  This means we
    1710             :      * don't need to fill relids.
    1711             :      */
    1712         112 :     rvcontext.relids = NULL;
    1713             : 
    1714         112 :     rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
    1715         112 :     rvcontext.varno = ((RangeTblRef *) jtnode)->rtindex;
    1716             :     /* these flags will be set below, if needed */
    1717         112 :     rvcontext.need_phvs = false;
    1718         112 :     rvcontext.wrap_non_vars = false;
    1719             :     /* initialize cache array with indexes 0 .. length(tlist) */
    1720         112 :     rvcontext.rv_cache = palloc0((list_length(rvcontext.targetlist) + 1) *
    1721             :                                  sizeof(Node *));
    1722             : 
    1723             :     /*
    1724             :      * If we are under an outer join then non-nullable items and lateral
    1725             :      * references may have to be turned into PlaceHolderVars.
    1726             :      */
    1727         112 :     if (lowest_nulling_outer_join != NULL)
    1728          12 :         rvcontext.need_phvs = true;
    1729             : 
    1730             :     /*
    1731             :      * If we are dealing with an appendrel member then anything that's not a
    1732             :      * simple Var has to be turned into a PlaceHolderVar.  (See comments in
    1733             :      * pull_up_simple_subquery().)
    1734             :      */
    1735         112 :     if (containing_appendrel != NULL)
    1736             :     {
    1737           0 :         rvcontext.need_phvs = true;
    1738           0 :         rvcontext.wrap_non_vars = true;
    1739             :     }
    1740             : 
    1741             :     /*
    1742             :      * If the parent query uses grouping sets, we need a PlaceHolderVar for
    1743             :      * anything that's not a simple Var.
    1744             :      */
    1745         112 :     if (parse->groupingSets)
    1746             :     {
    1747           0 :         rvcontext.need_phvs = true;
    1748           0 :         rvcontext.wrap_non_vars = true;
    1749             :     }
    1750             : 
    1751             :     /*
    1752             :      * Replace all of the top query's references to the RTE's output with
    1753             :      * copies of the funcexpr, being careful not to replace any of the
    1754             :      * jointree structure.
    1755             :      */
    1756         112 :     perform_pullup_replace_vars(root, &rvcontext,
    1757             :                                 lowest_nulling_outer_join,
    1758             :                                 containing_appendrel);
    1759             : 
    1760             :     /*
    1761             :      * We don't need to bother with changing PlaceHolderVars in the parent
    1762             :      * query.  Their references to the RT index are still good for now, and
    1763             :      * will get removed later if we're able to drop the RTE_RESULT.
    1764             :      */
    1765             : 
    1766             :     /*
    1767             :      * Convert the RTE to be RTE_RESULT type, signifying that we don't need to
    1768             :      * scan it anymore, and zero out RTE_FUNCTION-specific fields.
    1769             :      */
    1770         112 :     rte->rtekind = RTE_RESULT;
    1771         112 :     rte->functions = NIL;
    1772             : 
    1773             :     /*
    1774             :      * We can reuse the RangeTblRef node.
    1775             :      */
    1776         112 :     return jtnode;
    1777             : }
    1778             : 
    1779             : /*
    1780             :  * is_simple_union_all
    1781             :  *    Check a subquery to see if it's a simple UNION ALL.
    1782             :  *
    1783             :  * We require all the setops to be UNION ALL (no mixing) and there can't be
    1784             :  * any datatype coercions involved, ie, all the leaf queries must emit the
    1785             :  * same datatypes.
    1786             :  */
    1787             : static bool
    1788        6142 : is_simple_union_all(Query *subquery)
    1789             : {
    1790             :     SetOperationStmt *topop;
    1791             : 
    1792             :     /* Let's just make sure it's a valid subselect ... */
    1793       12284 :     if (!IsA(subquery, Query) ||
    1794        6142 :         subquery->commandType != CMD_SELECT)
    1795           0 :         elog(ERROR, "subquery is bogus");
    1796             : 
    1797             :     /* Is it a set-operation query at all? */
    1798        6142 :     topop = castNode(SetOperationStmt, subquery->setOperations);
    1799        6142 :     if (!topop)
    1800        5060 :         return false;
    1801             : 
    1802             :     /* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
    1803        2148 :     if (subquery->sortClause ||
    1804        2132 :         subquery->limitOffset ||
    1805        2132 :         subquery->limitCount ||
    1806        2132 :         subquery->rowMarks ||
    1807        1066 :         subquery->cteList)
    1808          20 :         return false;
    1809             : 
    1810             :     /* Recursively check the tree of set operations */
    1811        1062 :     return is_simple_union_all_recurse((Node *) topop, subquery,
    1812             :                                        topop->colTypes);
    1813             : }
    1814             : 
    1815             : static bool
    1816        7898 : is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
    1817             : {
    1818        7898 :     if (IsA(setOp, RangeTblRef))
    1819             :     {
    1820        4324 :         RangeTblRef *rtr = (RangeTblRef *) setOp;
    1821        4324 :         RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
    1822        4324 :         Query      *subquery = rte->subquery;
    1823             : 
    1824             :         Assert(subquery != NULL);
    1825             : 
    1826             :         /* Leaf nodes are OK if they match the toplevel column types */
    1827             :         /* We don't have to compare typmods or collations here */
    1828        4324 :         return tlist_same_datatypes(subquery->targetList, colTypes, true);
    1829             :     }
    1830        3574 :     else if (IsA(setOp, SetOperationStmt))
    1831             :     {
    1832        3574 :         SetOperationStmt *op = (SetOperationStmt *) setOp;
    1833             : 
    1834             :         /* Must be UNION ALL */
    1835        3574 :         if (op->op != SETOP_UNION || !op->all)
    1836        1130 :             return false;
    1837             : 
    1838             :         /* Recurse to check inputs */
    1839        4704 :         return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
    1840        2260 :             is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
    1841             :     }
    1842             :     else
    1843             :     {
    1844           0 :         elog(ERROR, "unrecognized node type: %d",
    1845             :              (int) nodeTag(setOp));
    1846             :         return false;           /* keep compiler quiet */
    1847             :     }
    1848             : }
    1849             : 
    1850             : /*
    1851             :  * is_safe_append_member
    1852             :  *    Check a subquery that is a leaf of a UNION ALL appendrel to see if it's
    1853             :  *    safe to pull up.
    1854             :  */
    1855             : static bool
    1856        5098 : is_safe_append_member(Query *subquery)
    1857             : {
    1858             :     FromExpr   *jtnode;
    1859             : 
    1860             :     /*
    1861             :      * It's only safe to pull up the child if its jointree contains exactly
    1862             :      * one RTE, else the AppendRelInfo data structure breaks. The one base RTE
    1863             :      * could be buried in several levels of FromExpr, however.  Also, if the
    1864             :      * child's jointree is completely empty, we can pull up because
    1865             :      * pull_up_simple_subquery will insert a single RTE_RESULT RTE instead.
    1866             :      *
    1867             :      * Also, the child can't have any WHERE quals because there's no place to
    1868             :      * put them in an appendrel.  (This is a bit annoying...) If we didn't
    1869             :      * need to check this, we'd just test whether get_relids_in_jointree()
    1870             :      * yields a singleton set, to be more consistent with the coding of
    1871             :      * fix_append_rel_relids().
    1872             :      */
    1873        5098 :     jtnode = subquery->jointree;
    1874             :     Assert(IsA(jtnode, FromExpr));
    1875             :     /* Check the completely-empty case */
    1876        5098 :     if (jtnode->fromlist == NIL && jtnode->quals == NULL)
    1877         300 :         return true;
    1878             :     /* Check the more general case */
    1879       12116 :     while (IsA(jtnode, FromExpr))
    1880             :     {
    1881        4806 :         if (jtnode->quals != NULL)
    1882        2286 :             return false;
    1883        2520 :         if (list_length(jtnode->fromlist) != 1)
    1884           0 :             return false;
    1885        2520 :         jtnode = linitial(jtnode->fromlist);
    1886             :     }
    1887        2512 :     if (!IsA(jtnode, RangeTblRef))
    1888          36 :         return false;
    1889             : 
    1890        2476 :     return true;
    1891             : }
    1892             : 
    1893             : /*
    1894             :  * jointree_contains_lateral_outer_refs
    1895             :  *      Check for disallowed lateral references in a jointree's quals
    1896             :  *
    1897             :  * If restricted is false, all level-1 Vars are allowed (but we still must
    1898             :  * search the jointree, since it might contain outer joins below which there
    1899             :  * will be restrictions).  If restricted is true, return true when any qual
    1900             :  * in the jointree contains level-1 Vars coming from outside the rels listed
    1901             :  * in safe_upper_varnos.
    1902             :  */
    1903             : static bool
    1904        1436 : jointree_contains_lateral_outer_refs(Node *jtnode, bool restricted,
    1905             :                                      Relids safe_upper_varnos)
    1906             : {
    1907        1436 :     if (jtnode == NULL)
    1908           0 :         return false;
    1909        1436 :     if (IsA(jtnode, RangeTblRef))
    1910         700 :         return false;
    1911         736 :     else if (IsA(jtnode, FromExpr))
    1912             :     {
    1913         604 :         FromExpr   *f = (FromExpr *) jtnode;
    1914             :         ListCell   *l;
    1915             : 
    1916             :         /* First, recurse to check child joins */
    1917        1172 :         foreach(l, f->fromlist)
    1918             :         {
    1919         576 :             if (jointree_contains_lateral_outer_refs(lfirst(l),
    1920             :                                                      restricted,
    1921             :                                                      safe_upper_varnos))
    1922           8 :                 return true;
    1923             :         }
    1924             : 
    1925             :         /* Then check the top-level quals */
    1926         828 :         if (restricted &&
    1927         232 :             !bms_is_subset(pull_varnos_of_level(f->quals, 1),
    1928             :                            safe_upper_varnos))
    1929           0 :             return true;
    1930             :     }
    1931         132 :     else if (IsA(jtnode, JoinExpr))
    1932             :     {
    1933         132 :         JoinExpr   *j = (JoinExpr *) jtnode;
    1934             : 
    1935             :         /*
    1936             :          * If this is an outer join, we mustn't allow any upper lateral
    1937             :          * references in or below it.
    1938             :          */
    1939         132 :         if (j->jointype != JOIN_INNER)
    1940             :         {
    1941          52 :             restricted = true;
    1942          52 :             safe_upper_varnos = NULL;
    1943             :         }
    1944             : 
    1945             :         /* Check the child joins */
    1946         132 :         if (jointree_contains_lateral_outer_refs(j->larg,
    1947             :                                                  restricted,
    1948             :                                                  safe_upper_varnos))
    1949           0 :             return true;
    1950         132 :         if (jointree_contains_lateral_outer_refs(j->rarg,
    1951             :                                                  restricted,
    1952             :                                                  safe_upper_varnos))
    1953           0 :             return true;
    1954             : 
    1955             :         /* Check the JOIN's qual clauses */
    1956         264 :         if (restricted &&
    1957         132 :             !bms_is_subset(pull_varnos_of_level(j->quals, 1),
    1958             :                            safe_upper_varnos))
    1959           8 :             return true;
    1960             :     }
    1961             :     else
    1962           0 :         elog(ERROR, "unrecognized node type: %d",
    1963             :              (int) nodeTag(jtnode));
    1964         720 :     return false;
    1965             : }
    1966             : 
    1967             : /*
    1968             :  * Perform pullup_replace_vars everyplace it's needed in the query tree.
    1969             :  *
    1970             :  * Caller has already filled *rvcontext with data describing what to
    1971             :  * substitute for Vars referencing the target subquery.  In addition
    1972             :  * we need the identity of the lowest outer join that can null the
    1973             :  * target subquery, and its containing appendrel if any.
    1974             :  */
    1975             : static void
    1976       38352 : perform_pullup_replace_vars(PlannerInfo *root,
    1977             :                             pullup_replace_vars_context *rvcontext,
    1978             :                             JoinExpr *lowest_nulling_outer_join,
    1979             :                             AppendRelInfo *containing_appendrel)
    1980             : {
    1981       38352 :     Query      *parse = root->parse;
    1982             :     ListCell   *lc;
    1983             : 
    1984             :     /*
    1985             :      * Replace all of the top query's references to the subquery's outputs
    1986             :      * with copies of the adjusted subtlist items, being careful not to
    1987             :      * replace any of the jointree structure.  (This'd be a lot cleaner if we
    1988             :      * could use query_tree_mutator.)  We have to use PHVs in the targetList,
    1989             :      * returningList, and havingQual, since those are certainly above any
    1990             :      * outer join.  replace_vars_in_jointree tracks its location in the
    1991             :      * jointree and uses PHVs or not appropriately.
    1992             :      */
    1993       38352 :     parse->targetList = (List *)
    1994       38352 :         pullup_replace_vars((Node *) parse->targetList, rvcontext);
    1995       38352 :     parse->returningList = (List *)
    1996       38352 :         pullup_replace_vars((Node *) parse->returningList, rvcontext);
    1997       38352 :     if (parse->onConflict)
    1998             :     {
    1999          32 :         parse->onConflict->onConflictSet = (List *)
    2000          16 :             pullup_replace_vars((Node *) parse->onConflict->onConflictSet,
    2001             :                                 rvcontext);
    2002          32 :         parse->onConflict->onConflictWhere =
    2003          16 :             pullup_replace_vars(parse->onConflict->onConflictWhere,
    2004             :                                 rvcontext);
    2005             : 
    2006             :         /*
    2007             :          * We assume ON CONFLICT's arbiterElems, arbiterWhere, exclRelTlist
    2008             :          * can't contain any references to a subquery.
    2009             :          */
    2010             :     }
    2011       38352 :     replace_vars_in_jointree((Node *) parse->jointree, rvcontext,
    2012             :                              lowest_nulling_outer_join);
    2013             :     Assert(parse->setOperations == NULL);
    2014       38348 :     parse->havingQual = pullup_replace_vars(parse->havingQual, rvcontext);
    2015             : 
    2016             :     /*
    2017             :      * Replace references in the translated_vars lists of appendrels.  When
    2018             :      * pulling up an appendrel member, we do not need PHVs in the list of the
    2019             :      * parent appendrel --- there isn't any outer join between.  Elsewhere,
    2020             :      * use PHVs for safety.  (This analysis could be made tighter but it seems
    2021             :      * unlikely to be worth much trouble.)
    2022             :      */
    2023       40822 :     foreach(lc, root->append_rel_list)
    2024             :     {
    2025        2474 :         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
    2026        2474 :         bool        save_need_phvs = rvcontext->need_phvs;
    2027             : 
    2028        2474 :         if (appinfo == containing_appendrel)
    2029        1370 :             rvcontext->need_phvs = false;
    2030        2474 :         appinfo->translated_vars = (List *)
    2031        2474 :             pullup_replace_vars((Node *) appinfo->translated_vars, rvcontext);
    2032        2474 :         rvcontext->need_phvs = save_need_phvs;
    2033             :     }
    2034             : 
    2035             :     /*
    2036             :      * Replace references in the joinaliasvars lists of join RTEs.
    2037             :      *
    2038             :      * You might think that we could avoid using PHVs for alias vars of joins
    2039             :      * below lowest_nulling_outer_join, but that doesn't work because the
    2040             :      * alias vars could be referenced above that join; we need the PHVs to be
    2041             :      * present in such references after the alias vars get flattened.  (It
    2042             :      * might be worth trying to be smarter here, someday.)
    2043             :      */
    2044      104736 :     foreach(lc, parse->rtable)
    2045             :     {
    2046       66388 :         RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
    2047             : 
    2048       66388 :         if (otherrte->rtekind == RTE_JOIN)
    2049        2292 :             otherrte->joinaliasvars = (List *)
    2050        2292 :                 pullup_replace_vars((Node *) otherrte->joinaliasvars,
    2051             :                                     rvcontext);
    2052             :     }
    2053       38348 : }
    2054             : 
    2055             : /*
    2056             :  * Helper routine for perform_pullup_replace_vars: do pullup_replace_vars on
    2057             :  * every expression in the jointree, without changing the jointree structure
    2058             :  * itself.  Ugly, but there's no other way...
    2059             :  *
    2060             :  * If we are at or below lowest_nulling_outer_join, we can suppress use of
    2061             :  * PlaceHolderVars wrapped around the replacement expressions.
    2062             :  */
    2063             : static void
    2064       86638 : replace_vars_in_jointree(Node *jtnode,
    2065             :                          pullup_replace_vars_context *context,
    2066             :                          JoinExpr *lowest_nulling_outer_join)
    2067             : {
    2068       86638 :     if (jtnode == NULL)
    2069           0 :         return;
    2070       86638 :     if (IsA(jtnode, RangeTblRef))
    2071             :     {
    2072             :         /*
    2073             :          * If the RangeTblRef refers to a LATERAL subquery (that isn't the
    2074             :          * same subquery we're pulling up), it might contain references to the
    2075             :          * target subquery, which we must replace.  We drive this from the
    2076             :          * jointree scan, rather than a scan of the rtable, for a couple of
    2077             :          * reasons: we can avoid processing no-longer-referenced RTEs, and we
    2078             :          * can use the appropriate setting of need_phvs depending on whether
    2079             :          * the RTE is above possibly-nulling outer joins or not.
    2080             :          */
    2081       43562 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
    2082             : 
    2083       43562 :         if (varno != context->varno) /* ignore target subquery itself */
    2084             :         {
    2085        6580 :             RangeTblEntry *rte = rt_fetch(varno, context->root->parse->rtable);
    2086             : 
    2087             :             Assert(rte != context->target_rte);
    2088        6580 :             if (rte->lateral)
    2089             :             {
    2090         412 :                 switch (rte->rtekind)
    2091             :                 {
    2092             :                     case RTE_RELATION:
    2093             :                         /* shouldn't be marked LATERAL unless tablesample */
    2094             :                         Assert(rte->tablesample);
    2095           0 :                         rte->tablesample = (TableSampleClause *)
    2096           0 :                             pullup_replace_vars((Node *) rte->tablesample,
    2097             :                                                 context);
    2098           0 :                         break;
    2099             :                     case RTE_SUBQUERY:
    2100         208 :                         rte->subquery =
    2101         208 :                             pullup_replace_vars_subquery(rte->subquery,
    2102             :                                                          context);
    2103         208 :                         break;
    2104             :                     case RTE_FUNCTION:
    2105         160 :                         rte->functions = (List *)
    2106         160 :                             pullup_replace_vars((Node *) rte->functions,
    2107             :                                                 context);
    2108         160 :                         break;
    2109             :                     case RTE_TABLEFUNC:
    2110          44 :                         rte->tablefunc = (TableFunc *)
    2111          44 :                             pullup_replace_vars((Node *) rte->tablefunc,
    2112             :                                                 context);
    2113          44 :                         break;
    2114             :                     case RTE_VALUES:
    2115           0 :                         rte->values_lists = (List *)
    2116           0 :                             pullup_replace_vars((Node *) rte->values_lists,
    2117             :                                                 context);
    2118           0 :                         break;
    2119             :                     case RTE_JOIN:
    2120             :                     case RTE_CTE:
    2121             :                     case RTE_NAMEDTUPLESTORE:
    2122             :                     case RTE_RESULT:
    2123             :                         /* these shouldn't be marked LATERAL */
    2124             :                         Assert(false);
    2125           0 :                         break;
    2126             :                 }
    2127             :             }
    2128             :         }
    2129             :     }
    2130       43076 :     else if (IsA(jtnode, FromExpr))
    2131             :     {
    2132       39516 :         FromExpr   *f = (FromExpr *) jtnode;
    2133             :         ListCell   *l;
    2134             : 
    2135       80682 :         foreach(l, f->fromlist)
    2136       41166 :             replace_vars_in_jointree(lfirst(l), context,
    2137             :                                      lowest_nulling_outer_join);
    2138       39516 :         f->quals = pullup_replace_vars(f->quals, context);
    2139             :     }
    2140        3560 :     else if (IsA(jtnode, JoinExpr))
    2141             :     {
    2142        3560 :         JoinExpr   *j = (JoinExpr *) jtnode;
    2143        3560 :         bool        save_need_phvs = context->need_phvs;
    2144             : 
    2145        3560 :         if (j == lowest_nulling_outer_join)
    2146             :         {
    2147             :             /* no more PHVs in or below this join */
    2148        1150 :             context->need_phvs = false;
    2149        1150 :             lowest_nulling_outer_join = NULL;
    2150             :         }
    2151        3560 :         replace_vars_in_jointree(j->larg, context, lowest_nulling_outer_join);
    2152        3560 :         replace_vars_in_jointree(j->rarg, context, lowest_nulling_outer_join);
    2153             : 
    2154             :         /*
    2155             :          * Use PHVs within the join quals of a full join, even when it's the
    2156             :          * lowest nulling outer join.  Otherwise, we cannot identify which
    2157             :          * side of the join a pulled-up var-free expression came from, which
    2158             :          * can lead to failure to make a plan at all because none of the quals
    2159             :          * appear to be mergeable or hashable conditions.  For this purpose we
    2160             :          * don't care about the state of wrap_non_vars, so leave it alone.
    2161             :          */
    2162        3560 :         if (j->jointype == JOIN_FULL)
    2163         352 :             context->need_phvs = true;
    2164             : 
    2165        3560 :         j->quals = pullup_replace_vars(j->quals, context);
    2166             : 
    2167             :         /*
    2168             :          * We don't bother to update the colvars list, since it won't be used
    2169             :          * again ...
    2170             :          */
    2171        3560 :         context->need_phvs = save_need_phvs;
    2172             :     }
    2173             :     else
    2174           0 :         elog(ERROR, "unrecognized node type: %d",
    2175             :              (int) nodeTag(jtnode));
    2176             : }
    2177             : 
    2178             : /*
    2179             :  * Apply pullup variable replacement throughout an expression tree
    2180             :  *
    2181             :  * Returns a modified copy of the tree, so this can't be used where we
    2182             :  * need to do in-place replacement.
    2183             :  */
    2184             : static Node *
    2185      163130 : pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
    2186             : {
    2187      163130 :     return replace_rte_variables(expr,
    2188             :                                  context->varno, 0,
    2189             :                                  pullup_replace_vars_callback,
    2190             :                                  (void *) context,
    2191             :                                  context->outer_hasSubLinks);
    2192             : }
    2193             : 
    2194             : static Node *
    2195      124036 : pullup_replace_vars_callback(Var *var,
    2196             :                              replace_rte_variables_context *context)
    2197             : {
    2198      124036 :     pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
    2199      124036 :     int         varattno = var->varattno;
    2200             :     Node       *newnode;
    2201             : 
    2202             :     /*
    2203             :      * If PlaceHolderVars are needed, we cache the modified expressions in
    2204             :      * rcon->rv_cache[].  This is not in hopes of any material speed gain
    2205             :      * within this function, but to avoid generating identical PHVs with
    2206             :      * different IDs.  That would result in duplicate evaluations at runtime,
    2207             :      * and possibly prevent optimizations that rely on recognizing different
    2208             :      * references to the same subquery output as being equal().  So it's worth
    2209             :      * a bit of extra effort to avoid it.
    2210             :      */
    2211      124036 :     if (rcon->need_phvs &&
    2212        4618 :         varattno >= InvalidAttrNumber &&
    2213        9236 :         varattno <= list_length(rcon->targetlist) &&
    2214        4618 :         rcon->rv_cache[varattno] != NULL)
    2215             :     {
    2216             :         /* Just copy the entry and fall through to adjust its varlevelsup */
    2217        1718 :         newnode = copyObject(rcon->rv_cache[varattno]);
    2218             :     }
    2219      122318 :     else if (varattno == InvalidAttrNumber)
    2220             :     {
    2221             :         /* Must expand whole-tuple reference into RowExpr */
    2222             :         RowExpr    *rowexpr;
    2223             :         List       *colnames;
    2224             :         List       *fields;
    2225         264 :         bool        save_need_phvs = rcon->need_phvs;
    2226         264 :         int         save_sublevelsup = context->sublevels_up;
    2227             : 
    2228             :         /*
    2229             :          * If generating an expansion for a var of a named rowtype (ie, this
    2230             :          * is a plain relation RTE), then we must include dummy items for
    2231             :          * dropped columns.  If the var is RECORD (ie, this is a JOIN), then
    2232             :          * omit dropped columns. Either way, attach column names to the
    2233             :          * RowExpr for use of ruleutils.c.
    2234             :          *
    2235             :          * In order to be able to cache the results, we always generate the
    2236             :          * expansion with varlevelsup = 0, and then adjust if needed.
    2237             :          */
    2238         528 :         expandRTE(rcon->target_rte,
    2239         264 :                   var->varno, 0 /* not varlevelsup */ , var->location,
    2240         264 :                   (var->vartype != RECORDOID),
    2241             :                   &colnames, &fields);
    2242             :         /* Adjust the generated per-field Vars, but don't insert PHVs */
    2243         264 :         rcon->need_phvs = false;
    2244         264 :         context->sublevels_up = 0;   /* to match the expandRTE output */
    2245         264 :         fields = (List *) replace_rte_variables_mutator((Node *) fields,
    2246             :                                                         context);
    2247         264 :         rcon->need_phvs = save_need_phvs;
    2248         264 :         context->sublevels_up = save_sublevelsup;
    2249             : 
    2250         264 :         rowexpr = makeNode(RowExpr);
    2251         264 :         rowexpr->args = fields;
    2252         264 :         rowexpr->row_typeid = var->vartype;
    2253         264 :         rowexpr->row_format = COERCE_IMPLICIT_CAST;
    2254         264 :         rowexpr->colnames = colnames;
    2255         264 :         rowexpr->location = var->location;
    2256         264 :         newnode = (Node *) rowexpr;
    2257             : 
    2258             :         /*
    2259             :          * Insert PlaceHolderVar if needed.  Notice that we are wrapping one
    2260             :          * PlaceHolderVar around the whole RowExpr, rather than putting one
    2261             :          * around each element of the row.  This is because we need the
    2262             :          * expression to yield NULL, not ROW(NULL,NULL,...) when it is forced
    2263             :          * to null by an outer join.
    2264             :          */
    2265         264 :         if (rcon->need_phvs)
    2266             :         {
    2267             :             /* RowExpr is certainly not strict, so always need PHV */
    2268           8 :             newnode = (Node *)
    2269           8 :                 make_placeholder_expr(rcon->root,
    2270             :                                       (Expr *) newnode,
    2271             :                                       bms_make_singleton(rcon->varno));
    2272             :             /* cache it with the PHV, and with varlevelsup still zero */
    2273           8 :             rcon->rv_cache[InvalidAttrNumber] = copyObject(newnode);
    2274             :         }
    2275             :     }
    2276             :     else
    2277             :     {
    2278             :         /* Normal case referencing one targetlist element */
    2279      122054 :         TargetEntry *tle = get_tle_by_resno(rcon->targetlist, varattno);
    2280             : 
    2281      122054 :         if (tle == NULL)        /* shouldn't happen */
    2282           0 :             elog(ERROR, "could not find attribute %d in subquery targetlist",
    2283             :                  varattno);
    2284             : 
    2285             :         /* Make a copy of the tlist item to return */
    2286      122054 :         newnode = (Node *) copyObject(tle->expr);
    2287             : 
    2288             :         /* Insert PlaceHolderVar if needed */
    2289      122054 :         if (rcon->need_phvs)
    2290             :         {
    2291             :             bool        wrap;
    2292             : 
    2293        5144 :             if (newnode && IsA(newnode, Var) &&
    2294        2252 :                 ((Var *) newnode)->varlevelsup == 0)
    2295             :             {
    2296             :                 /*
    2297             :                  * Simple Vars always escape being wrapped, unless they are
    2298             :                  * lateral references to something outside the subquery being
    2299             :                  * pulled up.  (Even then, we could omit the PlaceHolderVar if
    2300             :                  * the referenced rel is under the same lowest outer join, but
    2301             :                  * it doesn't seem worth the trouble to check that.)
    2302             :                  */
    2303        4728 :                 if (rcon->target_rte->lateral &&
    2304         232 :                     !bms_is_member(((Var *) newnode)->varno, rcon->relids))
    2305          16 :                     wrap = true;
    2306             :                 else
    2307        2232 :                     wrap = false;
    2308             :             }
    2309         672 :             else if (newnode && IsA(newnode, PlaceHolderVar) &&
    2310          28 :                      ((PlaceHolderVar *) newnode)->phlevelsup == 0)
    2311             :             {
    2312             :                 /* No need to wrap a PlaceHolderVar with another one, either */
    2313          28 :                 wrap = false;
    2314             :             }
    2315         616 :             else if (rcon->wrap_non_vars)
    2316             :             {
    2317             :                 /* Wrap all non-Vars in a PlaceHolderVar */
    2318          64 :                 wrap = true;
    2319             :             }
    2320             :             else
    2321             :             {
    2322             :                 /*
    2323             :                  * If it contains a Var of the subquery being pulled up, and
    2324             :                  * does not contain any non-strict constructs, then it's
    2325             :                  * certainly nullable so we don't need to insert a
    2326             :                  * PlaceHolderVar.
    2327             :                  *
    2328             :                  * This analysis could be tighter: in particular, a non-strict
    2329             :                  * construct hidden within a lower-level PlaceHolderVar is not
    2330             :                  * reason to add another PHV.  But for now it doesn't seem
    2331             :                  * worth the code to be more exact.
    2332             :                  *
    2333             :                  * Note: in future maybe we should insert a PlaceHolderVar
    2334             :                  * anyway, if the tlist item is expensive to evaluate?
    2335             :                  *
    2336             :                  * For a LATERAL subquery, we have to check the actual var
    2337             :                  * membership of the node, but if it's non-lateral then any
    2338             :                  * level-zero var must belong to the subquery.
    2339             :                  */
    2340         616 :                 if ((rcon->target_rte->lateral ?
    2341          64 :                      bms_overlap(pull_varnos((Node *) newnode), rcon->relids) :
    2342         664 :                      contain_vars_of_level((Node *) newnode, 0)) &&
    2343         176 :                     !contain_nonstrict_functions((Node *) newnode))
    2344             :                 {
    2345             :                     /* No wrap needed */
    2346           0 :                     wrap = false;
    2347             :                 }
    2348             :                 else
    2349             :                 {
    2350             :                     /* Else wrap it in a PlaceHolderVar */
    2351         552 :                     wrap = true;
    2352             :                 }
    2353             :             }
    2354             : 
    2355        2892 :             if (wrap)
    2356         632 :                 newnode = (Node *)
    2357         632 :                     make_placeholder_expr(rcon->root,
    2358             :                                           (Expr *) newnode,
    2359             :                                           bms_make_singleton(rcon->varno));
    2360             : 
    2361             :             /*
    2362             :              * Cache it if possible (ie, if the attno is in range, which it
    2363             :              * probably always should be).  We can cache the value even if we
    2364             :              * decided we didn't need a PHV, since this result will be
    2365             :              * suitable for any request that has need_phvs.
    2366             :              */
    2367        5784 :             if (varattno > InvalidAttrNumber &&
    2368        2892 :                 varattno <= list_length(rcon->targetlist))
    2369        2892 :                 rcon->rv_cache[varattno] = copyObject(newnode);
    2370             :         }
    2371             :     }
    2372             : 
    2373             :     /* Must adjust varlevelsup if tlist item is from higher query */
    2374      124036 :     if (var->varlevelsup > 0)
    2375         384 :         IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
    2376             : 
    2377      124036 :     return newnode;
    2378             : }
    2379             : 
    2380             : /*
    2381             :  * Apply pullup variable replacement to a subquery
    2382             :  *
    2383             :  * This needs to be different from pullup_replace_vars() because
    2384             :  * replace_rte_variables will think that it shouldn't increment sublevels_up
    2385             :  * before entering the Query; so we need to call it with sublevels_up == 1.
    2386             :  */
    2387             : static Query *
    2388         208 : pullup_replace_vars_subquery(Query *query,
    2389             :                              pullup_replace_vars_context *context)
    2390             : {
    2391             :     Assert(IsA(query, Query));
    2392         208 :     return (Query *) replace_rte_variables((Node *) query,
    2393             :                                            context->varno, 1,
    2394             :                                            pullup_replace_vars_callback,
    2395             :                                            (void *) context,
    2396             :                                            NULL);
    2397             : }
    2398             : 
    2399             : 
    2400             : /*
    2401             :  * flatten_simple_union_all
    2402             :  *      Try to optimize top-level UNION ALL structure into an appendrel
    2403             :  *
    2404             :  * If a query's setOperations tree consists entirely of simple UNION ALL
    2405             :  * operations, flatten it into an append relation, which we can process more
    2406             :  * intelligently than the general setops case.  Otherwise, do nothing.
    2407             :  *
    2408             :  * In most cases, this can succeed only for a top-level query, because for a
    2409             :  * subquery in FROM, the parent query's invocation of pull_up_subqueries would
    2410             :  * already have flattened the UNION via pull_up_simple_union_all.  But there
    2411             :  * are a few cases we can support here but not in that code path, for example
    2412             :  * when the subquery also contains ORDER BY.
    2413             :  */
    2414             : void
    2415        2452 : flatten_simple_union_all(PlannerInfo *root)
    2416             : {
    2417        2452 :     Query      *parse = root->parse;
    2418             :     SetOperationStmt *topop;
    2419             :     Node       *leftmostjtnode;
    2420             :     int         leftmostRTI;
    2421             :     RangeTblEntry *leftmostRTE;
    2422             :     int         childRTI;
    2423             :     RangeTblEntry *childRTE;
    2424             :     RangeTblRef *rtr;
    2425             : 
    2426             :     /* Shouldn't be called unless query has setops */
    2427        2452 :     topop = castNode(SetOperationStmt, parse->setOperations);
    2428             :     Assert(topop);
    2429             : 
    2430             :     /* Can't optimize away a recursive UNION */
    2431        2452 :     if (root->hasRecursion)
    2432         320 :         return;
    2433             : 
    2434             :     /*
    2435             :      * Recursively check the tree of set operations.  If not all UNION ALL
    2436             :      * with identical column types, punt.
    2437             :      */
    2438        2132 :     if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
    2439         926 :         return;
    2440             : 
    2441             :     /*
    2442             :      * Locate the leftmost leaf query in the setops tree.  The upper query's
    2443             :      * Vars all refer to this RTE (see transformSetOperationStmt).
    2444             :      */
    2445        1206 :     leftmostjtnode = topop->larg;
    2446        2462 :     while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
    2447          50 :         leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
    2448             :     Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
    2449        1206 :     leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
    2450        1206 :     leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
    2451             :     Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
    2452             : 
    2453             :     /*
    2454             :      * Make a copy of the leftmost RTE and add it to the rtable.  This copy
    2455             :      * will represent the leftmost leaf query in its capacity as a member of
    2456             :      * the appendrel.  The original will represent the appendrel as a whole.
    2457             :      * (We must do things this way because the upper query's Vars have to be
    2458             :      * seen as referring to the whole appendrel.)
    2459             :      */
    2460        1206 :     childRTE = copyObject(leftmostRTE);
    2461        1206 :     parse->rtable = lappend(parse->rtable, childRTE);
    2462        1206 :     childRTI = list_length(parse->rtable);
    2463             : 
    2464             :     /* Modify the setops tree to reference the child copy */
    2465        1206 :     ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
    2466             : 
    2467             :     /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
    2468        1206 :     leftmostRTE->inh = true;
    2469             : 
    2470             :     /*
    2471             :      * Form a RangeTblRef for the appendrel, and insert it into FROM.  The top
    2472             :      * Query of a setops tree should have had an empty FromClause initially.
    2473             :      */
    2474        1206 :     rtr = makeNode(RangeTblRef);
    2475        1206 :     rtr->rtindex = leftmostRTI;
    2476             :     Assert(parse->jointree->fromlist == NIL);
    2477        1206 :     parse->jointree->fromlist = list_make1(rtr);
    2478             : 
    2479             :     /*
    2480             :      * Now pretend the query has no setops.  We must do this before trying to
    2481             :      * do subquery pullup, because of Assert in pull_up_simple_subquery.
    2482             :      */
    2483        1206 :     parse->setOperations = NULL;
    2484             : 
    2485             :     /*
    2486             :      * Build AppendRelInfo information, and apply pull_up_subqueries to the
    2487             :      * leaf queries of the UNION ALL.  (We must do that now because they
    2488             :      * weren't previously referenced by the jointree, and so were missed by
    2489             :      * the main invocation of pull_up_subqueries.)
    2490             :      */
    2491        1206 :     pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
    2492             : }
    2493             : 
    2494             : 
    2495             : /*
    2496             :  * reduce_outer_joins
    2497             :  *      Attempt to reduce outer joins to plain inner joins.
    2498             :  *
    2499             :  * The idea here is that given a query like
    2500             :  *      SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42;
    2501             :  * we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE
    2502             :  * is strict.  The strict operator will always return NULL, causing the outer
    2503             :  * WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's
    2504             :  * columns.  Therefore, there's no need for the join to produce null-extended
    2505             :  * rows in the first place --- which makes it a plain join not an outer join.
    2506             :  * (This scenario may not be very likely in a query written out by hand, but
    2507             :  * it's reasonably likely when pushing quals down into complex views.)
    2508             :  *
    2509             :  * More generally, an outer join can be reduced in strength if there is a
    2510             :  * strict qual above it in the qual tree that constrains a Var from the
    2511             :  * nullable side of the join to be non-null.  (For FULL joins this applies
    2512             :  * to each side separately.)
    2513             :  *
    2514             :  * Another transformation we apply here is to recognize cases like
    2515             :  *      SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.y IS NULL;
    2516             :  * If the join clause is strict for b.y, then only null-extended rows could
    2517             :  * pass the upper WHERE, and we can conclude that what the query is really
    2518             :  * specifying is an anti-semijoin.  We change the join type from JOIN_LEFT
    2519             :  * to JOIN_ANTI.  The IS NULL clause then becomes redundant, and must be
    2520             :  * removed to prevent bogus selectivity calculations, but we leave it to
    2521             :  * distribute_qual_to_rels to get rid of such clauses.
    2522             :  *
    2523             :  * Also, we get rid of JOIN_RIGHT cases by flipping them around to become
    2524             :  * JOIN_LEFT.  This saves some code here and in some later planner routines,
    2525             :  * but the main reason to do it is to not need to invent a JOIN_REVERSE_ANTI
    2526             :  * join type.
    2527             :  *
    2528             :  * To ease recognition of strict qual clauses, we require this routine to be
    2529             :  * run after expression preprocessing (i.e., qual canonicalization and JOIN
    2530             :  * alias-var expansion).
    2531             :  */
    2532             : void
    2533       29984 : reduce_outer_joins(PlannerInfo *root)
    2534             : {
    2535             :     reduce_outer_joins_state *state;
    2536             : 
    2537             :     /*
    2538             :      * To avoid doing strictness checks on more quals than necessary, we want
    2539             :      * to stop descending the jointree as soon as there are no outer joins
    2540             :      * below our current point.  This consideration forces a two-pass process.
    2541             :      * The first pass gathers information about which base rels appear below
    2542             :      * each side of each join clause, and about whether there are outer
    2543             :      * join(s) below each side of each join clause. The second pass examines
    2544             :      * qual clauses and changes join types as it descends the tree.
    2545             :      */
    2546       29984 :     state = reduce_outer_joins_pass1((Node *) root->parse->jointree);
    2547             : 
    2548             :     /* planner.c shouldn't have called me if no outer joins */
    2549       29984 :     if (state == NULL || !state->contains_outer)
    2550           0 :         elog(ERROR, "so where are the outer joins?");
    2551             : 
    2552       29984 :     reduce_outer_joins_pass2((Node *) root->parse->jointree,
    2553             :                              state, root, NULL, NIL, NIL);
    2554       29984 : }
    2555             : 
    2556             : /*
    2557             :  * reduce_outer_joins_pass1 - phase 1 data collection
    2558             :  *
    2559             :  * Returns a state node describing the given jointree node.
    2560             :  */
    2561             : static reduce_outer_joins_state *
    2562      144312 : reduce_outer_joins_pass1(Node *jtnode)
    2563             : {
    2564             :     reduce_outer_joins_state *result;
    2565             : 
    2566      144312 :     result = (reduce_outer_joins_state *)
    2567             :         palloc(sizeof(reduce_outer_joins_state));
    2568      144312 :     result->relids = NULL;
    2569      144312 :     result->contains_outer = false;
    2570      144312 :     result->sub_states = NIL;
    2571             : 
    2572      144312 :     if (jtnode == NULL)
    2573           0 :         return result;
    2574      144312 :     if (IsA(jtnode, RangeTblRef))
    2575             :     {
    2576       72134 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
    2577             : 
    2578       72134 :         result->relids = bms_make_singleton(varno);
    2579             :     }
    2580       72178 :     else if (IsA(jtnode, FromExpr))
    2581             :     {
    2582       31004 :         FromExpr   *f = (FromExpr *) jtnode;
    2583             :         ListCell   *l;
    2584             : 
    2585       62984 :         foreach(l, f->fromlist)
    2586             :         {
    2587             :             reduce_outer_joins_state *sub_state;
    2588             : 
    2589       31980 :             sub_state = reduce_outer_joins_pass1(lfirst(l));
    2590       31980 :             result->relids = bms_add_members(result->relids,
    2591       31980 :                                              sub_state->relids);
    2592       31980 :             result->contains_outer |= sub_state->contains_outer;
    2593       31980 :             result->sub_states = lappend(result->sub_states, sub_state);
    2594             :         }
    2595             :     }
    2596       41174 :     else if (IsA(jtnode, JoinExpr))
    2597             :     {
    2598       41174 :         JoinExpr   *j = (JoinExpr *) jtnode;
    2599             :         reduce_outer_joins_state *sub_state;
    2600             : 
    2601             :         /* join's own RT index is not wanted in result->relids */
    2602       41174 :         if (IS_OUTER_JOIN(j->jointype))
    2603       35296 :             result->contains_outer = true;
    2604             : 
    2605       41174 :         sub_state = reduce_outer_joins_pass1(j->larg);
    2606       41174 :         result->relids = bms_add_members(result->relids,
    2607       41174 :                                          sub_state->relids);
    2608       41174 :         result->contains_outer |= sub_state->contains_outer;
    2609       41174 :         result->sub_states = lappend(result->sub_states, sub_state);
    2610             : 
    2611       41174 :         sub_state = reduce_outer_joins_pass1(j->rarg);
    2612       41174 :         result->relids = bms_add_members(result->relids,
    2613       41174 :                                          sub_state->relids);
    2614       41174 :         result->contains_outer |= sub_state->contains_outer;
    2615       41174 :         result->sub_states = lappend(result->sub_states, sub_state);
    2616             :     }
    2617             :     else
    2618           0 :         elog(ERROR, "unrecognized node type: %d",
    2619             :              (int) nodeTag(jtnode));
    2620      144312 :     return result;
    2621             : }
    2622             : 
    2623             : /*
    2624             :  * reduce_outer_joins_pass2 - phase 2 processing
    2625             :  *
    2626             :  *  jtnode: current jointree node
    2627             :  *  state: state data collected by phase 1 for this node
    2628             :  *  root: toplevel planner state
    2629             :  *  nonnullable_rels: set of base relids forced non-null by upper quals
    2630             :  *  nonnullable_vars: list of Vars forced non-null by upper quals
    2631             :  *  forced_null_vars: list of Vars forced null by upper quals
    2632             :  */
    2633             : static void
    2634       66202 : reduce_outer_joins_pass2(Node *jtnode,
    2635             :                          reduce_outer_joins_state *state,
    2636             :                          PlannerInfo *root,
    2637             :                          Relids nonnullable_rels,
    2638             :                          List *nonnullable_vars,
    2639             :                          List *forced_null_vars)
    2640             : {
    2641             :     /*
    2642             :      * pass 2 should never descend as far as an empty subnode or base rel,
    2643             :      * because it's only called on subtrees marked as contains_outer.
    2644             :      */
    2645       66202 :     if (jtnode == NULL)
    2646           0 :         elog(ERROR, "reached empty jointree");
    2647       66202 :     if (IsA(jtnode, RangeTblRef))
    2648           0 :         elog(ERROR, "reached base rel");
    2649       66202 :     else if (IsA(jtnode, FromExpr))
    2650             :     {
    2651       30592 :         FromExpr   *f = (FromExpr *) jtnode;
    2652             :         ListCell   *l;
    2653             :         ListCell   *s;
    2654             :         Relids      pass_nonnullable_rels;
    2655             :         List       *pass_nonnullable_vars;
    2656             :         List       *pass_forced_null_vars;
    2657             : 
    2658             :         /* Scan quals to see if we can add any constraints */
    2659       30592 :         pass_nonnullable_rels = find_nonnullable_rels(f->quals);
    2660       30592 :         pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
    2661             :                                                 nonnullable_rels);
    2662       30592 :         pass_nonnullable_vars = find_nonnullable_vars(f->quals);
    2663       30592 :         pass_nonnullable_vars = list_concat(pass_nonnullable_vars,
    2664             :                                             nonnullable_vars);
    2665       30592 :         pass_forced_null_vars = find_forced_null_vars(f->quals);
    2666       30592 :         pass_forced_null_vars = list_concat(pass_forced_null_vars,
    2667             :                                             forced_null_vars);
    2668             :         /* And recurse --- but only into interesting subtrees */
    2669             :         Assert(list_length(f->fromlist) == list_length(state->sub_states));
    2670       62084 :         forboth(l, f->fromlist, s, state->sub_states)
    2671             :         {
    2672       31492 :             reduce_outer_joins_state *sub_state = lfirst(s);
    2673             : 
    2674       31492 :             if (sub_state->contains_outer)
    2675       30612 :                 reduce_outer_joins_pass2(lfirst(l), sub_state, root,
    2676             :                                          pass_nonnullable_rels,
    2677             :                                          pass_nonnullable_vars,
    2678             :                                          pass_forced_null_vars);
    2679             :         }
    2680       30592 :         bms_free(pass_nonnullable_rels);
    2681             :         /* can't so easily clean up var lists, unfortunately */
    2682             :     }
    2683       35610 :     else if (IsA(jtnode, JoinExpr))
    2684             :     {
    2685       35610 :         JoinExpr   *j = (JoinExpr *) jtnode;
    2686       35610 :         int         rtindex = j->rtindex;
    2687       35610 :         JoinType    jointype = j->jointype;
    2688       35610 :         reduce_outer_joins_state *left_state = linitial(state->sub_states);
    2689       35610 :         reduce_outer_joins_state *right_state = lsecond(state->sub_states);
    2690       35610 :         List       *local_nonnullable_vars = NIL;
    2691       35610 :         bool        computed_local_nonnullable_vars = false;
    2692             : 
    2693             :         /* Can we simplify this join? */
    2694       35610 :         switch (jointype)
    2695             :         {
    2696             :             case JOIN_INNER:
    2697         310 :                 break;
    2698             :             case JOIN_LEFT:
    2699       34464 :                 if (bms_overlap(nonnullable_rels, right_state->relids))
    2700         632 :                     jointype = JOIN_INNER;
    2701       34464 :                 break;
    2702             :             case JOIN_RIGHT:
    2703         172 :                 if (bms_overlap(nonnullable_rels, left_state->relids))
    2704          12 :                     jointype = JOIN_INNER;
    2705         172 :                 break;
    2706             :             case JOIN_FULL:
    2707         482 :                 if (bms_overlap(nonnullable_rels, left_state->relids))
    2708             :                 {
    2709           0 :                     if (bms_overlap(nonnullable_rels, right_state->relids))
    2710           0 :                         jointype = JOIN_INNER;
    2711             :                     else
    2712           0 :                         jointype = JOIN_LEFT;
    2713             :                 }
    2714             :                 else
    2715             :                 {
    2716         482 :                     if (bms_overlap(nonnullable_rels, right_state->relids))
    2717          12 :                         jointype = JOIN_RIGHT;
    2718             :                 }
    2719         482 :                 break;
    2720             :             case JOIN_SEMI:
    2721             :             case JOIN_ANTI:
    2722             : 
    2723             :                 /*
    2724             :                  * These could only have been introduced by pull_up_sublinks,
    2725             :                  * so there's no way that upper quals could refer to their
    2726             :                  * righthand sides, and no point in checking.
    2727             :                  */
    2728         182 :                 break;
    2729             :             default:
    2730           0 :                 elog(ERROR, "unrecognized join type: %d",
    2731             :                      (int) jointype);
    2732             :                 break;
    2733             :         }
    2734             : 
    2735             :         /*
    2736             :          * Convert JOIN_RIGHT to JOIN_LEFT.  Note that in the case where we
    2737             :          * reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no
    2738             :          * longer matches the internal ordering of any CoalesceExpr's built to
    2739             :          * represent merged join variables.  We don't care about that at
    2740             :          * present, but be wary of it ...
    2741             :          */
    2742       35610 :         if (jointype == JOIN_RIGHT)
    2743             :         {
    2744             :             Node       *tmparg;
    2745             : 
    2746         172 :             tmparg = j->larg;
    2747         172 :             j->larg = j->rarg;
    2748         172 :             j->rarg = tmparg;
    2749         172 :             jointype = JOIN_LEFT;
    2750         172 :             right_state = linitial(state->sub_states);
    2751         172 :             left_state = lsecond(state->sub_states);
    2752             :         }
    2753             : 
    2754             :         /*
    2755             :          * See if we can reduce JOIN_LEFT to JOIN_ANTI.  This is the case if
    2756             :          * the join's own quals are strict for any var that was forced null by
    2757             :          * higher qual levels.  NOTE: there are other ways that we could
    2758             :          * detect an anti-join, in particular if we were to check whether Vars
    2759             :          * coming from the RHS must be non-null because of table constraints.
    2760             :          * That seems complicated and expensive though (in particular, one
    2761             :          * would have to be wary of lower outer joins). For the moment this
    2762             :          * seems sufficient.
    2763             :          */
    2764       35610 :         if (jointype == JOIN_LEFT)
    2765             :         {
    2766             :             List       *overlap;
    2767             : 
    2768       34004 :             local_nonnullable_vars = find_nonnullable_vars(j->quals);
    2769       34004 :             computed_local_nonnullable_vars = true;
    2770             : 
    2771             :             /*
    2772             :              * It's not sufficient to check whether local_nonnullable_vars and
    2773             :              * forced_null_vars overlap: we need to know if the overlap
    2774             :              * includes any RHS variables.
    2775             :              */
    2776       34004 :             overlap = list_intersection(local_nonnullable_vars,
    2777             :                                         forced_null_vars);
    2778       34660 :             if (overlap != NIL &&
    2779         656 :                 bms_overlap(pull_varnos((Node *) overlap),
    2780         656 :                             right_state->relids))
    2781         656 :                 jointype = JOIN_ANTI;
    2782             :         }
    2783             : 
    2784             :         /* Apply the jointype change, if any, to both jointree node and RTE */
    2785       35610 :         if (rtindex && jointype != j->jointype)
    2786             :         {
    2787        1472 :             RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
    2788             : 
    2789             :             Assert(rte->rtekind == RTE_JOIN);
    2790             :             Assert(rte->jointype == j->jointype);
    2791        1472 :             rte->jointype = jointype;
    2792             :         }
    2793       35610 :         j->jointype = jointype;
    2794             : 
    2795             :         /* Only recurse if there's more to do below here */
    2796       35610 :         if (left_state->contains_outer || right_state->contains_outer)
    2797             :         {
    2798             :             Relids      local_nonnullable_rels;
    2799             :             List       *local_forced_null_vars;
    2800             :             Relids      pass_nonnullable_rels;
    2801             :             List       *pass_nonnullable_vars;
    2802             :             List       *pass_forced_null_vars;
    2803             : 
    2804             :             /*
    2805             :              * If this join is (now) inner, we can add any constraints its
    2806             :              * quals provide to those we got from above.  But if it is outer,
    2807             :              * we can pass down the local constraints only into the nullable
    2808             :              * side, because an outer join never eliminates any rows from its
    2809             :              * non-nullable side.  Also, there is no point in passing upper
    2810             :              * constraints into the nullable side, since if there were any
    2811             :              * we'd have been able to reduce the join.  (In the case of upper
    2812             :              * forced-null constraints, we *must not* pass them into the
    2813             :              * nullable side --- they either applied here, or not.) The upshot
    2814             :              * is that we pass either the local or the upper constraints,
    2815             :              * never both, to the children of an outer join.
    2816             :              *
    2817             :              * Note that a SEMI join works like an inner join here: it's okay
    2818             :              * to pass down both local and upper constraints.  (There can't be
    2819             :              * any upper constraints affecting its inner side, but it's not
    2820             :              * worth having a separate code path to avoid passing them.)
    2821             :              *
    2822             :              * At a FULL join we just punt and pass nothing down --- is it
    2823             :              * possible to be smarter?
    2824             :              */
    2825        5596 :             if (jointype != JOIN_FULL)
    2826             :             {
    2827        5522 :                 local_nonnullable_rels = find_nonnullable_rels(j->quals);
    2828        5522 :                 if (!computed_local_nonnullable_vars)
    2829         606 :                     local_nonnullable_vars = find_nonnullable_vars(j->quals);
    2830        5522 :                 local_forced_null_vars = find_forced_null_vars(j->quals);
    2831        5522 :                 if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
    2832             :                 {
    2833             :                     /* OK to merge upper and local constraints */
    2834         428 :                     local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
    2835             :                                                              nonnullable_rels);
    2836         428 :                     local_nonnullable_vars = list_concat(local_nonnullable_vars,
    2837             :                                                          nonnullable_vars);
    2838         428 :                     local_forced_null_vars = list_concat(local_forced_null_vars,
    2839             :                                                          forced_null_vars);
    2840             :                 }
    2841             :             }
    2842             :             else
    2843             :             {
    2844             :                 /* no use in calculating these */
    2845          74 :                 local_nonnullable_rels = NULL;
    2846          74 :                 local_forced_null_vars = NIL;
    2847             :             }
    2848             : 
    2849        5596 :             if (left_state->contains_outer)
    2850             :             {
    2851        5292 :                 if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
    2852             :                 {
    2853             :                     /* pass union of local and upper constraints */
    2854         336 :                     pass_nonnullable_rels = local_nonnullable_rels;
    2855         336 :                     pass_nonnullable_vars = local_nonnullable_vars;
    2856         336 :                     pass_forced_null_vars = local_forced_null_vars;
    2857             :                 }
    2858        4956 :                 else if (jointype != JOIN_FULL) /* ie, LEFT or ANTI */
    2859             :                 {
    2860             :                     /* can't pass local constraints to non-nullable side */
    2861        4906 :                     pass_nonnullable_rels = nonnullable_rels;
    2862        4906 :                     pass_nonnullable_vars = nonnullable_vars;
    2863        4906 :                     pass_forced_null_vars = forced_null_vars;
    2864             :                 }
    2865             :                 else
    2866             :                 {
    2867             :                     /* no constraints pass through JOIN_FULL */
    2868          50 :                     pass_nonnullable_rels = NULL;
    2869          50 :                     pass_nonnullable_vars = NIL;
    2870          50 :                     pass_forced_null_vars = NIL;
    2871             :                 }
    2872        5292 :                 reduce_outer_joins_pass2(j->larg, left_state, root,
    2873             :                                          pass_nonnullable_rels,
    2874             :                                          pass_nonnullable_vars,
    2875             :                                          pass_forced_null_vars);
    2876             :             }
    2877             : 
    2878        5596 :             if (right_state->contains_outer)
    2879             :             {
    2880         314 :                 if (jointype != JOIN_FULL)  /* ie, INNER/LEFT/SEMI/ANTI */
    2881             :                 {
    2882             :                     /* pass appropriate constraints, per comment above */
    2883         290 :                     pass_nonnullable_rels = local_nonnullable_rels;
    2884         290 :                     pass_nonnullable_vars = local_nonnullable_vars;
    2885         290 :                     pass_forced_null_vars = local_forced_null_vars;
    2886             :                 }
    2887             :                 else
    2888             :                 {
    2889             :                     /* no constraints pass through JOIN_FULL */
    2890          24 :                     pass_nonnullable_rels = NULL;
    2891          24 :                     pass_nonnullable_vars = NIL;
    2892          24 :                     pass_forced_null_vars = NIL;
    2893             :                 }
    2894         314 :                 reduce_outer_joins_pass2(j->rarg, right_state, root,
    2895             :                                          pass_nonnullable_rels,
    2896             :                                          pass_nonnullable_vars,
    2897             :                                          pass_forced_null_vars);
    2898             :             }
    2899        5596 :             bms_free(local_nonnullable_rels);
    2900             :         }
    2901             :     }
    2902             :     else
    2903           0 :         elog(ERROR, "unrecognized node type: %d",
    2904             :              (int) nodeTag(jtnode));
    2905       66202 : }
    2906             : 
    2907             : 
    2908             : /*
    2909             :  * remove_useless_result_rtes
    2910             :  *      Attempt to remove RTE_RESULT RTEs from the join tree.
    2911             :  *
    2912             :  * We can remove RTE_RESULT entries from the join tree using the knowledge
    2913             :  * that RTE_RESULT returns exactly one row and has no output columns.  Hence,
    2914             :  * if one is inner-joined to anything else, we can delete it.  Optimizations
    2915             :  * are also possible for some outer-join cases, as detailed below.
    2916             :  *
    2917             :  * Some of these optimizations depend on recognizing empty (constant-true)
    2918             :  * quals for FromExprs and JoinExprs.  That makes it useful to apply this
    2919             :  * optimization pass after expression preprocessing, since that will have
    2920             :  * eliminated constant-true quals, allowing more cases to be recognized as
    2921             :  * optimizable.  What's more, the usual reason for an RTE_RESULT to be present
    2922             :  * is that we pulled up a subquery or VALUES clause, thus very possibly
    2923             :  * replacing Vars with constants, making it more likely that a qual can be
    2924             :  * reduced to constant true.  Also, because some optimizations depend on
    2925             :  * the outer-join type, it's best to have done reduce_outer_joins() first.
    2926             :  *
    2927             :  * A PlaceHolderVar referencing an RTE_RESULT RTE poses an obstacle to this
    2928             :  * process: we must remove the RTE_RESULT's relid from the PHV's phrels, but
    2929             :  * we must not reduce the phrels set to empty.  If that would happen, and
    2930             :  * the RTE_RESULT is an immediate child of an outer join, we have to give up
    2931             :  * and not remove the RTE_RESULT: there is noplace else to evaluate the
    2932             :  * PlaceHolderVar.  (That is, in such cases the RTE_RESULT *does* have output
    2933             :  * columns.)  But if the RTE_RESULT is an immediate child of an inner join,
    2934             :  * we can change the PlaceHolderVar's phrels so as to evaluate it at the
    2935             :  * inner join instead.  This is OK because we really only care that PHVs are
    2936             :  * evaluated above or below the correct outer joins.
    2937             :  *
    2938             :  * We used to try to do this work as part of pull_up_subqueries() where the
    2939             :  * potentially-optimizable cases get introduced; but it's way simpler, and
    2940             :  * more effective, to do it separately.
    2941             :  */
    2942             : void
    2943      111198 : remove_useless_result_rtes(PlannerInfo *root)
    2944             : {
    2945             :     ListCell   *cell;
    2946             : 
    2947             :     /* Top level of jointree must always be a FromExpr */
    2948             :     Assert(IsA(root->parse->jointree, FromExpr));
    2949             :     /* Recurse ... */
    2950      222396 :     root->parse->jointree = (FromExpr *)
    2951      111198 :         remove_useless_results_recurse(root, (Node *) root->parse->jointree);
    2952             :     /* We should still have a FromExpr */
    2953             :     Assert(IsA(root->parse->jointree, FromExpr));
    2954             : 
    2955             :     /*
    2956             :      * Remove any PlanRowMark referencing an RTE_RESULT RTE.  We obviously
    2957             :      * must do that for any RTE_RESULT that we just removed.  But one for a
    2958             :      * RTE that we did not remove can be dropped anyway: since the RTE has
    2959             :      * only one possible output row, there is no need for EPQ to mark and
    2960             :      * restore that row.
    2961             :      *
    2962             :      * It's necessary, not optional, to remove the PlanRowMark for a surviving
    2963             :      * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
    2964             :      * RTE_RESULT, which the executor has no support for.
    2965             :      */
    2966      111222 :     foreach(cell, root->rowMarks)
    2967             :     {
    2968          24 :         PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
    2969             : 
    2970          24 :         if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
    2971          16 :             root->rowMarks = foreach_delete_current(root->rowMarks, cell);
    2972             :     }
    2973      111198 : }
    2974             : 
    2975             : /*
    2976             :  * remove_useless_results_recurse
    2977             :  *      Recursive guts of remove_useless_result_rtes.
    2978             :  *
    2979             :  * This recursively processes the jointree and returns a modified jointree.
    2980             :  */
    2981             : static Node *
    2982      223826 : remove_useless_results_recurse(PlannerInfo *root, Node *jtnode)
    2983             : {
    2984             :     Assert(jtnode != NULL);
    2985      223826 :     if (IsA(jtnode, RangeTblRef))
    2986             :     {
    2987             :         /* Can't immediately do anything with a RangeTblRef */
    2988             :     }
    2989      111876 :     else if (IsA(jtnode, FromExpr))
    2990             :     {
    2991      111418 :         FromExpr   *f = (FromExpr *) jtnode;
    2992      111418 :         Relids      result_relids = NULL;
    2993             :         ListCell   *cell;
    2994             : 
    2995             :         /*
    2996             :          * We can drop RTE_RESULT rels from the fromlist so long as at least
    2997             :          * one child remains, since joining to a one-row table changes
    2998             :          * nothing.  The easiest way to mechanize this rule is to modify the
    2999             :          * list in-place.
    3000             :          */
    3001      223130 :         foreach(cell, f->fromlist)
    3002             :         {
    3003      111712 :             Node       *child = (Node *) lfirst(cell);
    3004             :             int         varno;
    3005             : 
    3006             :             /* Recursively transform child ... */
    3007      111712 :             child = remove_useless_results_recurse(root, child);
    3008             :             /* ... and stick it back into the tree */
    3009      111712 :             lfirst(cell) = child;
    3010             : 
    3011             :             /*
    3012             :              * If it's an RTE_RESULT with at least one sibling, we can drop
    3013             :              * it.  We don't yet know what the inner join's final relid set
    3014             :              * will be, so postpone cleanup of PHVs etc till after this loop.
    3015             :              */
    3016      111712 :             if (list_length(f->fromlist) > 1 &&
    3017             :                 (varno = get_result_relid(root, child)) != 0)
    3018             :             {
    3019         104 :                 f->fromlist = foreach_delete_current(f->fromlist, cell);
    3020         104 :                 result_relids = bms_add_member(result_relids, varno);
    3021             :             }
    3022             :         }
    3023             : 
    3024             :         /*
    3025             :          * Clean up if we dropped any RTE_RESULT RTEs.  This is a bit
    3026             :          * inefficient if there's more than one, but it seems better to
    3027             :          * optimize the support code for the single-relid case.
    3028             :          */
    3029      111418 :         if (result_relids)
    3030             :         {
    3031         104 :             int         varno = -1;
    3032             : 
    3033         312 :             while ((varno = bms_next_member(result_relids, varno)) >= 0)
    3034         104 :                 remove_result_refs(root, varno, (Node *) f);
    3035             :         }
    3036             : 
    3037             :         /*
    3038             :          * If we're not at the top of the jointree, it's valid to simplify a
    3039             :          * degenerate FromExpr into its single child.  (At the top, we must
    3040             :          * keep the FromExpr since Query.jointree is required to point to a
    3041             :          * FromExpr.)
    3042             :          */
    3043      111638 :         if (f != root->parse->jointree &&
    3044         228 :             f->quals == NULL &&
    3045           8 :             list_length(f->fromlist) == 1)
    3046           8 :             return (Node *) linitial(f->fromlist);
    3047             :     }
    3048         458 :     else if (IsA(jtnode, JoinExpr))
    3049             :     {
    3050         458 :         JoinExpr   *j = (JoinExpr *) jtnode;
    3051             :         int         varno;
    3052             : 
    3053             :         /* First, recurse */
    3054         458 :         j->larg = remove_useless_results_recurse(root, j->larg);
    3055         458 :         j->rarg = remove_useless_results_recurse(root, j->rarg);
    3056             : 
    3057             :         /* Apply join-type-specific optimization rules */
    3058         458 :         switch (j->jointype)
    3059             :         {
    3060             :             case JOIN_INNER:
    3061             : 
    3062             :                 /*
    3063             :                  * An inner join is equivalent to a FromExpr, so if either
    3064             :                  * side was simplified to an RTE_RESULT rel, we can replace
    3065             :                  * the join with a FromExpr with just the other side; and if
    3066             :                  * the qual is empty (JOIN ON TRUE) then we can omit the
    3067             :                  * FromExpr as well.
    3068             :                  */
    3069         122 :                 if ((varno = get_result_relid(root, j->larg)) != 0)
    3070             :                 {
    3071          22 :                     remove_result_refs(root, varno, j->rarg);
    3072          22 :                     if (j->quals)
    3073           8 :                         jtnode = (Node *)
    3074           8 :                             makeFromExpr(list_make1(j->rarg), j->quals);
    3075             :                     else
    3076          14 :                         jtnode = j->rarg;
    3077             :                 }
    3078         100 :                 else if ((varno = get_result_relid(root, j->rarg)) != 0)
    3079             :                 {
    3080          46 :                     remove_result_refs(root, varno, j->larg);
    3081          46 :                     if (j->quals)
    3082          46 :                         jtnode = (Node *)
    3083          46 :                             makeFromExpr(list_make1(j->larg), j->quals);
    3084             :                     else
    3085           0 :                         jtnode = j->larg;
    3086             :                 }
    3087         122 :                 break;
    3088             :             case JOIN_LEFT:
    3089             : 
    3090             :                 /*
    3091             :                  * We can simplify this case if the RHS is an RTE_RESULT, with
    3092             :                  * two different possibilities:
    3093             :                  *
    3094             :                  * If the qual is empty (JOIN ON TRUE), then the join can be
    3095             :                  * strength-reduced to a plain inner join, since each LHS row
    3096             :                  * necessarily has exactly one join partner.  So we can always
    3097             :                  * discard the RHS, much as in the JOIN_INNER case above.
    3098             :                  *
    3099             :                  * Otherwise, it's still true that each LHS row should be
    3100             :                  * returned exactly once, and since the RHS returns no columns
    3101             :                  * (unless there are PHVs that have to be evaluated there), we
    3102             :                  * don't much care if it's null-extended or not.  So in this
    3103             :                  * case also, we can just ignore the qual and discard the left
    3104             :                  * join.
    3105             :                  */
    3106         136 :                 if ((varno = get_result_relid(root, j->rarg)) != 0 &&
    3107          32 :                     (j->quals == NULL ||
    3108          16 :                      !find_dependent_phvs((Node *) root->parse, varno)))
    3109             :                 {
    3110           0 :                     remove_result_refs(root, varno, j->larg);
    3111           0 :                     jtnode = j->larg;
    3112             :                 }
    3113         120 :                 break;
    3114             :             case JOIN_RIGHT:
    3115             :                 /* Mirror-image of the JOIN_LEFT case */
    3116           0 :                 if ((varno = get_result_relid(root, j->larg)) != 0 &&
    3117           0 :                     (j->quals == NULL ||
    3118           0 :                      !find_dependent_phvs((Node *) root->parse, varno)))
    3119             :                 {
    3120           0 :                     remove_result_refs(root, varno, j->rarg);
    3121           0 :                     jtnode = j->rarg;
    3122             :                 }
    3123           0 :                 break;
    3124             :             case JOIN_SEMI:
    3125             : 
    3126             :                 /*
    3127             :                  * We may simplify this case if the RHS is an RTE_RESULT; the
    3128             :                  * join qual becomes effectively just a filter qual for the
    3129             :                  * LHS, since we should either return the LHS row or not.  For
    3130             :                  * simplicity we inject the filter qual into a new FromExpr.
    3131             :                  *
    3132             :                  * Unlike the LEFT/RIGHT cases, we just Assert that there are
    3133             :                  * no PHVs that need to be evaluated at the semijoin's RHS,
    3134             :                  * since the rest of the query couldn't reference any outputs
    3135             :                  * of the semijoin's RHS.
    3136             :                  */
    3137         204 :                 if ((varno = get_result_relid(root, j->rarg)) != 0)
    3138             :                 {
    3139             :                     Assert(!find_dependent_phvs((Node *) root->parse, varno));
    3140           4 :                     remove_result_refs(root, varno, j->larg);
    3141           4 :                     if (j->quals)
    3142           4 :                         jtnode = (Node *)
    3143           4 :                             makeFromExpr(list_make1(j->larg), j->quals);
    3144             :                     else
    3145           0 :                         jtnode = j->larg;
    3146             :                 }
    3147         204 :                 break;
    3148             :             case JOIN_FULL:
    3149             :             case JOIN_ANTI:
    3150             :                 /* We have no special smarts for these cases */
    3151          12 :                 break;
    3152             :             default:
    3153           0 :                 elog(ERROR, "unrecognized join type: %d",
    3154             :                      (int) j->jointype);
    3155             :                 break;
    3156             :         }
    3157             :     }
    3158             :     else
    3159           0 :         elog(ERROR, "unrecognized node type: %d",
    3160             :              (int) nodeTag(jtnode));
    3161      223818 :     return jtnode;
    3162             : }
    3163             : 
    3164             : /*
    3165             :  * get_result_relid
    3166             :  *      If jtnode is a RangeTblRef for an RTE_RESULT RTE, return its relid;
    3167             :  *      otherwise return 0.
    3168             :  */
    3169             : static int
    3170        1006 : get_result_relid(PlannerInfo *root, Node *jtnode)
    3171             : {
    3172             :     int         varno;
    3173             : 
    3174        1006 :     if (!IsA(jtnode, RangeTblRef))
    3175         120 :         return 0;
    3176         886 :     varno = ((RangeTblRef *) jtnode)->rtindex;
    3177         886 :     if (rt_fetch(varno, root->parse->rtable)->rtekind != RTE_RESULT)
    3178         694 :         return 0;
    3179         192 :     return varno;
    3180             : }
    3181             : 
    3182             : /*
    3183             :  * remove_result_refs
    3184             :  *      Helper routine for dropping an unneeded RTE_RESULT RTE.
    3185             :  *
    3186             :  * This doesn't physically remove the RTE from the jointree, because that's
    3187             :  * more easily handled in remove_useless_results_recurse.  What it does do
    3188             :  * is the necessary cleanup in the rest of the tree: we must adjust any PHVs
    3189             :  * that may reference the RTE.  Be sure to call this at a point where the
    3190             :  * jointree is valid (no disconnected nodes).
    3191             :  *
    3192             :  * Note that we don't need to process the append_rel_list, since RTEs
    3193             :  * referenced directly in the jointree won't be appendrel members.
    3194             :  *
    3195             :  * varno is the RTE_RESULT's relid.
    3196             :  * newjtloc is the jointree location at which any PHVs referencing the
    3197             :  * RTE_RESULT should be evaluated instead.
    3198             :  */
    3199             : static void
    3200         176 : remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc)
    3201             : {
    3202             :     /* Fix up PlaceHolderVars as needed */
    3203             :     /* If there are no PHVs anywhere, we can skip this bit */
    3204         176 :     if (root->glob->lastPHId != 0)
    3205             :     {
    3206             :         Relids      subrelids;
    3207             : 
    3208          36 :         subrelids = get_relids_in_jointree(newjtloc, false);
    3209             :         Assert(!bms_is_empty(subrelids));
    3210          36 :         substitute_phv_relids((Node *) root->parse, varno, subrelids);
    3211             :     }
    3212             : 
    3213             :     /*
    3214             :      * We also need to remove any PlanRowMark referencing the RTE, but we
    3215             :      * postpone that work until we return to remove_useless_result_rtes.
    3216             :      */
    3217         176 : }
    3218             : 
    3219             : 
    3220             : /*
    3221             :  * find_dependent_phvs - are there any PlaceHolderVars whose relids are
    3222             :  * exactly the given varno?
    3223             :  */
    3224             : 
    3225             : typedef struct
    3226             : {
    3227             :     Relids      relids;
    3228             :     int         sublevels_up;
    3229             : } find_dependent_phvs_context;
    3230             : 
    3231             : static bool
    3232         228 : find_dependent_phvs_walker(Node *node,
    3233             :                            find_dependent_phvs_context *context)
    3234             : {
    3235         228 :     if (node == NULL)
    3236          12 :         return false;
    3237         216 :     if (IsA(node, PlaceHolderVar))
    3238             :     {
    3239          36 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
    3240             : 
    3241          72 :         if (phv->phlevelsup == context->sublevels_up &&
    3242          36 :             bms_equal(context->relids, phv->phrels))
    3243          16 :             return true;
    3244             :         /* fall through to examine children */
    3245             :     }
    3246         200 :     if (IsA(node, Query))
    3247             :     {
    3248             :         /* Recurse into subselects */
    3249             :         bool        result;
    3250             : 
    3251           0 :         context->sublevels_up++;
    3252           0 :         result = query_tree_walker((Query *) node,
    3253             :                                    find_dependent_phvs_walker,
    3254             :                                    (void *) context, 0);
    3255           0 :         context->sublevels_up--;
    3256           0 :         return result;
    3257             :     }
    3258             :     /* Shouldn't need to handle planner auxiliary nodes here */
    3259             :     Assert(!IsA(node, SpecialJoinInfo));
    3260             :     Assert(!IsA(node, AppendRelInfo));
    3261             :     Assert(!IsA(node, PlaceHolderInfo));
    3262             :     Assert(!IsA(node, MinMaxAggInfo));
    3263             : 
    3264         200 :     return expression_tree_walker(node, find_dependent_phvs_walker,
    3265             :                                   (void *) context);
    3266             : }
    3267             : 
    3268             : static bool
    3269          16 : find_dependent_phvs(Node *node, int varno)
    3270             : {
    3271             :     find_dependent_phvs_context context;
    3272             : 
    3273          16 :     context.relids = bms_make_singleton(varno);
    3274          16 :     context.sublevels_up = 0;
    3275             : 
    3276             :     /*
    3277             :      * Must be prepared to start with a Query or a bare expression tree.
    3278             :      */
    3279          16 :     return query_or_expression_tree_walker(node,
    3280             :                                            find_dependent_phvs_walker,
    3281             :                                            (void *) &context,
    3282             :                                            0);
    3283             : }
    3284             : 
    3285             : /*
    3286             :  * substitute_phv_relids - adjust PlaceHolderVar relid sets after pulling up
    3287             :  * a subquery or removing an RTE_RESULT jointree item
    3288             :  *
    3289             :  * Find any PlaceHolderVar nodes in the given tree that reference the
    3290             :  * pulled-up relid, and change them to reference the replacement relid(s).
    3291             :  *
    3292             :  * NOTE: although this has the form of a walker, we cheat and modify the
    3293             :  * nodes in-place.  This should be OK since the tree was copied by
    3294             :  * pullup_replace_vars earlier.  Avoid scribbling on the original values of
    3295             :  * the bitmapsets, though, because expression_tree_mutator doesn't copy those.
    3296             :  */
    3297             : 
    3298             : typedef struct
    3299             : {
    3300             :     int         varno;
    3301             :     int         sublevels_up;
    3302             :     Relids      subrelids;
    3303             : } substitute_phv_relids_context;
    3304             : 
    3305             : static bool
    3306      849914 : substitute_phv_relids_walker(Node *node,
    3307             :                              substitute_phv_relids_context *context)
    3308             : {
    3309      849914 :     if (node == NULL)
    3310      339782 :         return false;
    3311      510132 :     if (IsA(node, PlaceHolderVar))
    3312             :     {
    3313        1642 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
    3314             : 
    3315        3268 :         if (phv->phlevelsup == context->sublevels_up &&
    3316        1626 :             bms_is_member(context->varno, phv->phrels))
    3317             :         {
    3318        1020 :             phv->phrels = bms_union(phv->phrels,
    3319        1020 :                                     context->subrelids);
    3320        1020 :             phv->phrels = bms_del_member(phv->phrels,
    3321             :                                          context->varno);
    3322             :             /* Assert we haven't broken the PHV */
    3323             :             Assert(!bms_is_empty(phv->phrels));
    3324             :         }
    3325             :         /* fall through to examine children */
    3326             :     }
    3327      510132 :     if (IsA(node, Query))
    3328             :     {
    3329             :         /* Recurse into subselects */
    3330             :         bool        result;
    3331             : 
    3332       22420 :         context->sublevels_up++;
    3333       22420 :         result = query_tree_walker((Query *) node,
    3334             :                                    substitute_phv_relids_walker,
    3335             :                                    (void *) context, 0);
    3336       22420 :         context->sublevels_up--;
    3337       22420 :         return result;
    3338             :     }
    3339             :     /* Shouldn't need to handle planner auxiliary nodes here */
    3340             :     Assert(!IsA(node, SpecialJoinInfo));
    3341             :     Assert(!IsA(node, AppendRelInfo));
    3342             :     Assert(!IsA(node, PlaceHolderInfo));
    3343             :     Assert(!IsA(node, MinMaxAggInfo));
    3344             : 
    3345      487712 :     return expression_tree_walker(node, substitute_phv_relids_walker,
    3346             :                                   (void *) context);
    3347             : }
    3348             : 
    3349             : static void
    3350        8318 : substitute_phv_relids(Node *node, int varno, Relids subrelids)
    3351             : {
    3352             :     substitute_phv_relids_context context;
    3353             : 
    3354        8318 :     context.varno = varno;
    3355        8318 :     context.sublevels_up = 0;
    3356        8318 :     context.subrelids = subrelids;
    3357             : 
    3358             :     /*
    3359             :      * Must be prepared to start with a Query or a bare expression tree.
    3360             :      */
    3361        8318 :     query_or_expression_tree_walker(node,
    3362             :                                     substitute_phv_relids_walker,
    3363             :                                     (void *) &context,
    3364             :                                     0);
    3365        8318 : }
    3366             : 
    3367             : /*
    3368             :  * fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
    3369             :  *
    3370             :  * When we pull up a subquery, any AppendRelInfo references to the subquery's
    3371             :  * RT index have to be replaced by the substituted relid (and there had better
    3372             :  * be only one).  We also need to apply substitute_phv_relids to their
    3373             :  * translated_vars lists, since those might contain PlaceHolderVars.
    3374             :  *
    3375             :  * We assume we may modify the AppendRelInfo nodes in-place.
    3376             :  */
    3377             : static void
    3378        5808 : fix_append_rel_relids(List *append_rel_list, int varno, Relids subrelids)
    3379             : {
    3380             :     ListCell   *l;
    3381        5808 :     int         subvarno = -1;
    3382             : 
    3383             :     /*
    3384             :      * We only want to extract the member relid once, but we mustn't fail
    3385             :      * immediately if there are multiple members; it could be that none of the
    3386             :      * AppendRelInfo nodes refer to it.  So compute it on first use. Note that
    3387             :      * bms_singleton_member will complain if set is not singleton.
    3388             :      */
    3389        8282 :     foreach(l, append_rel_list)
    3390             :     {
    3391        2474 :         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
    3392             : 
    3393             :         /* The parent_relid shouldn't ever be a pullup target */
    3394             :         Assert(appinfo->parent_relid != varno);
    3395             : 
    3396        2474 :         if (appinfo->child_relid == varno)
    3397             :         {
    3398        1370 :             if (subvarno < 0)
    3399        1370 :                 subvarno = bms_singleton_member(subrelids);
    3400        1370 :             appinfo->child_relid = subvarno;
    3401             :         }
    3402             : 
    3403             :         /* Also fix up any PHVs in its translated vars */
    3404        2474 :         substitute_phv_relids((Node *) appinfo->translated_vars,
    3405             :                               varno, subrelids);
    3406             :     }
    3407        5808 : }
    3408             : 
    3409             : /*
    3410             :  * get_relids_in_jointree: get set of RT indexes present in a jointree
    3411             :  *
    3412             :  * If include_joins is true, join RT indexes are included; if false,
    3413             :  * only base rels are included.
    3414             :  */
    3415             : Relids
    3416       56930 : get_relids_in_jointree(Node *jtnode, bool include_joins)
    3417             : {
    3418       56930 :     Relids      result = NULL;
    3419             : 
    3420       56930 :     if (jtnode == NULL)
    3421           0 :         return result;
    3422       56930 :     if (IsA(jtnode, RangeTblRef))
    3423             :     {
    3424       28890 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
    3425             : 
    3426       28890 :         result = bms_make_singleton(varno);
    3427             :     }
    3428       28040 :     else if (IsA(jtnode, FromExpr))
    3429             :     {
    3430       26112 :         FromExpr   *f = (FromExpr *) jtnode;
    3431             :         ListCell   *l;
    3432             : 
    3433       53150 :         foreach(l, f->fromlist)
    3434             :         {
    3435       54076 :             result = bms_join(result,
    3436       27038 :                               get_relids_in_jointree(lfirst(l),
    3437             :                                                      include_joins));
    3438             :         }
    3439             :     }
    3440        1928 :     else if (IsA(jtnode, JoinExpr))
    3441             :     {
    3442        1928 :         JoinExpr   *j = (JoinExpr *) jtnode;
    3443             : 
    3444        1928 :         result = get_relids_in_jointree(j->larg, include_joins);
    3445        1928 :         result = bms_join(result,
    3446             :                           get_relids_in_jointree(j->rarg, include_joins));
    3447        1928 :         if (include_joins && j->rtindex)
    3448         324 :             result = bms_add_member(result, j->rtindex);
    3449             :     }
    3450             :     else
    3451           0 :         elog(ERROR, "unrecognized node type: %d",
    3452             :              (int) nodeTag(jtnode));
    3453       56930 :     return result;
    3454             : }
    3455             : 
    3456             : /*
    3457             :  * get_relids_for_join: get set of base RT indexes making up a join
    3458             :  */
    3459             : Relids
    3460           0 : get_relids_for_join(Query *query, int joinrelid)
    3461             : {
    3462             :     Node       *jtnode;
    3463             : 
    3464           0 :     jtnode = find_jointree_node_for_rel((Node *) query->jointree,
    3465             :                                         joinrelid);
    3466           0 :     if (!jtnode)
    3467           0 :         elog(ERROR, "could not find join node %d", joinrelid);
    3468           0 :     return get_relids_in_jointree(jtnode, false);
    3469             : }
    3470             : 
    3471             : /*
    3472             :  * find_jointree_node_for_rel: locate jointree node for a base or join RT index
    3473             :  *
    3474             :  * Returns NULL if not found
    3475             :  */
    3476             : static Node *
    3477           0 : find_jointree_node_for_rel(Node *jtnode, int relid)
    3478             : {
    3479           0 :     if (jtnode == NULL)
    3480           0 :         return NULL;
    3481           0 :     if (IsA(jtnode, RangeTblRef))
    3482             :     {
    3483           0 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
    3484             : 
    3485           0 :         if (relid == varno)
    3486           0 :             return jtnode;
    3487             :     }
    3488           0 :     else if (IsA(jtnode, FromExpr))
    3489             :     {
    3490           0 :         FromExpr   *f = (FromExpr *) jtnode;
    3491             :         ListCell   *l;
    3492             : 
    3493           0 :         foreach(l, f->fromlist)
    3494             :         {
    3495           0 :             jtnode = find_jointree_node_for_rel(lfirst(l), relid);
    3496           0 :             if (jtnode)
    3497           0 :                 return jtnode;
    3498             :         }
    3499             :     }
    3500           0 :     else if (IsA(jtnode, JoinExpr))
    3501             :     {
    3502           0 :         JoinExpr   *j = (JoinExpr *) jtnode;
    3503             : 
    3504           0 :         if (relid == j->rtindex)
    3505           0 :             return jtnode;
    3506           0 :         jtnode = find_jointree_node_for_rel(j->larg, relid);
    3507           0 :         if (jtnode)
    3508           0 :             return jtnode;
    3509           0 :         jtnode = find_jointree_node_for_rel(j->rarg, relid);
    3510           0 :         if (jtnode)
    3511           0 :             return jtnode;
    3512             :     }
    3513             :     else
    3514           0 :         elog(ERROR, "unrecognized node type: %d",
    3515             :              (int) nodeTag(jtnode));
    3516           0 :     return NULL;
    3517             : }

Generated by: LCOV version 1.13