]> granicus.if.org Git - postgresql/blobdiff - src/backend/optimizer/plan/setrefs.c
Do parse analysis of an EXPLAIN's contained statement during the normal
[postgresql] / src / backend / optimizer / plan / setrefs.c
index bc8ce00d4e8ba68393b97d4b9dcbcd04de2118e7..aa4fd4e1ebe71b0eabf0eb826c50fe81119de8ea 100644 (file)
@@ -4,25 +4,27 @@
  *       Post-processing of a completed plan tree: fix references to subplan
  *       vars, compute regproc values for operators, etc
  *
- * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
  * IDENTIFICATION
- *       $PostgreSQL: pgsql/src/backend/optimizer/plan/setrefs.c,v 1.137 2007/10/11 18:05:27 tgl Exp $
+ *       $PostgreSQL: pgsql/src/backend/optimizer/plan/setrefs.c,v 1.157 2010/01/15 22:36:32 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
 #include "postgres.h"
 
+#include "access/transam.h"
 #include "catalog/pg_type.h"
 #include "nodes/makefuncs.h"
+#include "nodes/nodeFuncs.h"
 #include "optimizer/clauses.h"
 #include "optimizer/planmain.h"
 #include "optimizer/tlist.h"
-#include "parser/parse_expr.h"
 #include "parser/parsetree.h"
 #include "utils/lsyscache.h"
+#include "utils/syscache.h"
 
 
 typedef struct
@@ -36,7 +38,8 @@ typedef struct
 {
        List       *tlist;                      /* underlying target list */
        int                     num_vars;               /* number of plain Var tlist entries */
-       bool            has_non_vars;   /* are there non-plain-Var entries? */
+       bool            has_ph_vars;    /* are there PlaceHolderVar entries? */
+       bool            has_non_vars;   /* are there other entries? */
        /* array of num_vars entries: */
        tlist_vinfo vars[1];            /* VARIABLE LENGTH ARRAY */
 } indexed_tlist;                               /* VARIABLE LENGTH STRUCT */
@@ -63,16 +66,28 @@ typedef struct
        int                     rtoffset;
 } fix_upper_expr_context;
 
+/*
+ * Check if a Const node is a regclass value.  We accept plain OID too,
+ * since a regclass Const will get folded to that type if it's an argument
+ * to oideq or similar operators.  (This might result in some extraneous
+ * values in a plan's list of relation dependencies, but the worst result
+ * would be occasional useless replans.)
+ */
+#define ISREGCLASSCONST(con) \
+       (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
+        !(con)->constisnull)
+
 #define fix_scan_list(glob, lst, rtoffset) \
        ((List *) fix_scan_expr(glob, (Node *) (lst), rtoffset))
 
 static Plan *set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset);
 static Plan *set_subqueryscan_references(PlannerGlobal *glob,
-                                                                                SubqueryScan *plan,
-                                                                                int rtoffset);
+                                                       SubqueryScan *plan,
+                                                       int rtoffset);
 static bool trivial_subqueryscan(SubqueryScan *plan);
 static Node *fix_scan_expr(PlannerGlobal *glob, Node *node, int rtoffset);
 static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
+static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
 static void set_join_references(PlannerGlobal *glob, Join *join, int rtoffset);
 static void set_inner_join_references(PlannerGlobal *glob, Plan *inner_plan,
                                                  indexed_tlist *outer_itlist);
@@ -86,20 +101,26 @@ static Var *search_indexed_tlist_for_var(Var *var,
 static Var *search_indexed_tlist_for_non_var(Node *node,
                                                                 indexed_tlist *itlist,
                                                                 Index newvarno);
+static Var *search_indexed_tlist_for_sortgroupref(Node *node,
+                                                                         Index sortgroupref,
+                                                                         indexed_tlist *itlist,
+                                                                         Index newvarno);
 static List *fix_join_expr(PlannerGlobal *glob,
-                                                  List *clauses,
-                                                  indexed_tlist *outer_itlist,
-                                                  indexed_tlist *inner_itlist,
-                                                  Index acceptable_rel, int rtoffset);
+                         List *clauses,
+                         indexed_tlist *outer_itlist,
+                         indexed_tlist *inner_itlist,
+                         Index acceptable_rel, int rtoffset);
 static Node *fix_join_expr_mutator(Node *node,
-                                                                  fix_join_expr_context *context);
+                                         fix_join_expr_context *context);
 static Node *fix_upper_expr(PlannerGlobal *glob,
-                                                       Node *node,
-                                                       indexed_tlist *subplan_itlist,
-                                                       int rtoffset);
+                          Node *node,
+                          indexed_tlist *subplan_itlist,
+                          int rtoffset);
 static Node *fix_upper_expr_mutator(Node *node,
-                                                                       fix_upper_expr_context *context);
+                                          fix_upper_expr_context *context);
 static bool fix_opfuncids_walker(Node *node, void *context);
+static bool extract_query_dependencies_walker(Node *node,
+                                                                 PlannerGlobal *context);
 
 
 /*****************************************************************************
@@ -126,10 +147,12 @@ static bool fix_opfuncids_walker(Node *node, void *context);
  * 4. We compute regproc OIDs for operators (ie, we look up the function
  * that implements each op).
  *
- * 5. We create a list of OIDs of relations that the plan depends on.
+ * 5. We create lists of specific objects that the plan depends on.
  * This will be used by plancache.c to drive invalidation of cached plans.
- * (Someday we might want to generalize this to include other types of
- * objects, but for now tracking relations seems to solve most problems.)
+ * Relation dependencies are represented by OIDs, and everything else by
+ * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
+ * Currently, relations and user-defined functions are the only types of
+ * objects that are explicitly tracked this way.
  *
  * We also perform one final optimization step, which is to delete
  * SubqueryScan plan nodes that aren't doing anything useful (ie, have
@@ -147,34 +170,40 @@ static bool fix_opfuncids_walker(Node *node, void *context);
  *     glob: global data for planner run
  *     plan: the topmost node of the plan
  *     rtable: the rangetable for the current subquery
+ *     rowmarks: the PlanRowMark list for the current subquery
  *
  * The return value is normally the same Plan node passed in, but can be
  * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
  *
- * The flattened rangetable entries are appended to glob->finalrtable, and
- * the list of relation OIDs is appended to glob->relationOids.
+ * The flattened rangetable entries are appended to glob->finalrtable,
+ * and we also append rowmarks entries to glob->finalrowmarks.
+ * Plan dependencies are appended to glob->relationOids (for relations)
+ * and glob->invalItems (for everything else).
  *
  * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
- * to process targetlist and qual expressions.  We can assume that the Plan
+ * to process targetlist and qual expressions. We can assume that the Plan
  * nodes were just built by the planner and are not multiply referenced, but
  * it's not so safe to assume that for expression tree nodes.
  */
 Plan *
-set_plan_references(PlannerGlobal *glob, Plan *plan, List *rtable)
+set_plan_references(PlannerGlobal *glob, Plan *plan,
+                                       List *rtable, List *rowmarks)
 {
        int                     rtoffset = list_length(glob->finalrtable);
        ListCell   *lc;
 
        /*
-        * In the flat rangetable, we zero out substructure pointers that are
-        * not needed by the executor; this reduces the storage space and
-        * copying cost for cached plans.  We keep only the alias and eref
-        * Alias fields, which are needed by EXPLAIN.
+        * In the flat rangetable, we zero out substructure pointers that are not
+        * needed by the executor; this reduces the storage space and copying cost
+        * for cached plans.  We keep only the alias and eref Alias fields, which
+        * are needed by EXPLAIN, and the selectedCols and modifiedCols bitmaps,
+        * which are needed for executor-startup permissions checking and for
+        * trigger event checking.
         */
        foreach(lc, rtable)
        {
-               RangeTblEntry  *rte = (RangeTblEntry *) lfirst(lc);
-               RangeTblEntry  *newrte;
+               RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
+               RangeTblEntry *newrte;
 
                /* flat copy to duplicate all the scalar fields */
                newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
@@ -182,22 +211,24 @@ set_plan_references(PlannerGlobal *glob, Plan *plan, List *rtable)
 
                /* zap unneeded sub-structure */
                newrte->subquery = NULL;
+               newrte->joinaliasvars = NIL;
                newrte->funcexpr = NULL;
                newrte->funccoltypes = NIL;
                newrte->funccoltypmods = NIL;
                newrte->values_lists = NIL;
-               newrte->joinaliasvars = NIL;
+               newrte->ctecoltypes = NIL;
+               newrte->ctecoltypmods = NIL;
 
                glob->finalrtable = lappend(glob->finalrtable, newrte);
 
                /*
                 * If it's a plain relation RTE, add the table to relationOids.
                 *
-                * We do this even though the RTE might be unreferenced in the
-                * plan tree; this would correspond to cases such as views that
-                * were expanded, child tables that were eliminated by constraint
-                * exclusion, etc.  Schema invalidation on such a rel must still
-                * force rebuilding of the plan.
+                * We do this even though the RTE might be unreferenced in the plan
+                * tree; this would correspond to cases such as views that were
+                * expanded, child tables that were eliminated by constraint
+                * exclusion, etc.      Schema invalidation on such a rel must still force
+                * rebuilding of the plan.
                 *
                 * Note we don't bother to avoid duplicate list entries.  We could,
                 * but it would probably cost more cycles than it would save.
@@ -207,6 +238,27 @@ set_plan_references(PlannerGlobal *glob, Plan *plan, List *rtable)
                                                                                         newrte->relid);
        }
 
+       /*
+        * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
+        */
+       foreach(lc, rowmarks)
+       {
+               PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
+               PlanRowMark *newrc;
+
+               Assert(IsA(rc, PlanRowMark));
+
+               /* flat copy is enough since all fields are scalars */
+               newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
+               memcpy(newrc, rc, sizeof(PlanRowMark));
+
+               /* adjust indexes */
+               newrc->rti += rtoffset;
+               newrc->prti += rtoffset;
+
+               glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
+       }
+
        /* Now fix the Plan tree */
        return set_plan_refs(glob, plan, rtoffset);
 }
@@ -229,7 +281,7 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
        {
                case T_SeqScan:
                        {
-                               SeqScan *splan = (SeqScan *) plan;
+                               SeqScan    *splan = (SeqScan *) plan;
 
                                splan->scanrelid += rtoffset;
                                splan->plan.targetlist =
@@ -240,7 +292,7 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                        break;
                case T_IndexScan:
                        {
-                               IndexScan *splan = (IndexScan *) plan;
+                               IndexScan  *splan = (IndexScan *) plan;
 
                                splan->scan.scanrelid += rtoffset;
                                splan->scan.plan.targetlist =
@@ -282,7 +334,7 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                        break;
                case T_TidScan:
                        {
-                               TidScan *splan = (TidScan *) plan;
+                               TidScan    *splan = (TidScan *) plan;
 
                                splan->scan.scanrelid += rtoffset;
                                splan->scan.plan.targetlist =
@@ -324,7 +376,28 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                                        fix_scan_list(glob, splan->values_lists, rtoffset);
                        }
                        break;
+               case T_CteScan:
+                       {
+                               CteScan    *splan = (CteScan *) plan;
 
+                               splan->scan.scanrelid += rtoffset;
+                               splan->scan.plan.targetlist =
+                                       fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
+                               splan->scan.plan.qual =
+                                       fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
+                       }
+                       break;
+               case T_WorkTableScan:
+                       {
+                               WorkTableScan *splan = (WorkTableScan *) plan;
+
+                               splan->scan.scanrelid += rtoffset;
+                               splan->scan.plan.targetlist =
+                                       fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
+                               splan->scan.plan.qual =
+                                       fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
+                       }
+                       break;
                case T_NestLoop:
                case T_MergeJoin:
                case T_HashJoin:
@@ -340,26 +413,48 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                        /*
                         * These plan types don't actually bother to evaluate their
                         * targetlists, because they just return their unmodified input
-                        * tuples.  Even though the targetlist won't be used by the
+                        * tuples.      Even though the targetlist won't be used by the
                         * executor, we fix it up for possible use by EXPLAIN (not to
                         * mention ease of debugging --- wrong varnos are very confusing).
                         */
                        set_dummy_tlist_references(plan, rtoffset);
+
                        /*
                         * Since these plan types don't check quals either, we should not
                         * find any qual expression attached to them.
                         */
                        Assert(plan->qual == NIL);
                        break;
+               case T_LockRows:
+                       {
+                               LockRows   *splan = (LockRows *) plan;
+
+                               /*
+                                * Like the plan types above, LockRows doesn't evaluate its
+                                * tlist or quals.  But we have to fix up the RT indexes
+                                * in its rowmarks.
+                                */
+                               set_dummy_tlist_references(plan, rtoffset);
+                               Assert(splan->plan.qual == NIL);
+
+                               foreach(l, splan->rowMarks)
+                               {
+                                       PlanRowMark *rc = (PlanRowMark *) lfirst(l);
+
+                                       rc->rti += rtoffset;
+                                       rc->prti += rtoffset;
+                               }
+                       }
+                       break;
                case T_Limit:
                        {
-                               Limit *splan = (Limit *) plan;
+                               Limit      *splan = (Limit *) plan;
 
                                /*
                                 * Like the plan types above, Limit doesn't evaluate its tlist
                                 * or quals.  It does have live expressions for limit/offset,
-                                * however; and those cannot contain subplan variable refs,
-                                * so fix_scan_expr works for them.
+                                * however; and those cannot contain subplan variable refs, so
+                                * fix_scan_expr works for them.
                                 */
                                set_dummy_tlist_references(plan, rtoffset);
                                Assert(splan->plan.qual == NIL);
@@ -371,12 +466,13 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                        }
                        break;
                case T_Agg:
+               case T_WindowAgg:
                case T_Group:
                        set_upper_references(glob, plan, rtoffset);
                        break;
                case T_Result:
                        {
-                               Result *splan = (Result *) plan;
+                               Result     *splan = (Result *) plan;
 
                                /*
                                 * Result may or may not have a subplan; if not, it's more
@@ -396,9 +492,39 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                                        fix_scan_expr(glob, splan->resconstantqual, rtoffset);
                        }
                        break;
+               case T_ModifyTable:
+                       {
+                               ModifyTable *splan = (ModifyTable *) plan;
+
+                               /*
+                                * planner.c already called set_returning_clause_references,
+                                * so we should not process either the targetlist or the
+                                * returningLists.
+                                */
+                               Assert(splan->plan.qual == NIL);
+
+                               foreach(l, splan->resultRelations)
+                               {
+                                       lfirst_int(l) += rtoffset;
+                               }
+                               foreach(l, splan->rowMarks)
+                               {
+                                       PlanRowMark *rc = (PlanRowMark *) lfirst(l);
+
+                                       rc->rti += rtoffset;
+                                       rc->prti += rtoffset;
+                               }
+                               foreach(l, splan->plans)
+                               {
+                                       lfirst(l) = set_plan_refs(glob,
+                                                                                         (Plan *) lfirst(l),
+                                                                                         rtoffset);
+                               }
+                       }
+                       break;
                case T_Append:
                        {
-                               Append *splan = (Append *) plan;
+                               Append     *splan = (Append *) plan;
 
                                /*
                                 * Append, like Sort et al, doesn't actually evaluate its
@@ -414,9 +540,14 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                                }
                        }
                        break;
+               case T_RecursiveUnion:
+                       /* This doesn't evaluate targetlist or check quals either */
+                       set_dummy_tlist_references(plan, rtoffset);
+                       Assert(plan->qual == NIL);
+                       break;
                case T_BitmapAnd:
                        {
-                               BitmapAnd *splan = (BitmapAnd *) plan;
+                               BitmapAnd  *splan = (BitmapAnd *) plan;
 
                                /* BitmapAnd works like Append, but has no tlist */
                                Assert(splan->plan.targetlist == NIL);
@@ -431,7 +562,7 @@ set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
                        break;
                case T_BitmapOr:
                        {
-                               BitmapOr *splan = (BitmapOr *) plan;
+                               BitmapOr   *splan = (BitmapOr *) plan;
 
                                /* BitmapOr works like Append, but has no tlist */
                                Assert(splan->plan.targetlist == NIL);
@@ -479,10 +610,12 @@ set_subqueryscan_references(PlannerGlobal *glob,
        Plan       *result;
 
        /* First, recursively process the subplan */
-       plan->subplan = set_plan_references(glob, plan->subplan, plan->subrtable);
+       plan->subplan = set_plan_references(glob, plan->subplan,
+                                                                               plan->subrtable, plan->subrowmark);
 
-       /* subrtable is no longer needed in the plan tree */
+       /* subrtable/subrowmark are no longer needed in the plan tree */
        plan->subrtable = NIL;
+       plan->subrowmark = NIL;
 
        if (trivial_subqueryscan(plan))
        {
@@ -609,6 +742,79 @@ copyVar(Var *var)
        return newvar;
 }
 
+/*
+ * fix_expr_common
+ *             Do generic set_plan_references processing on an expression node
+ *
+ * This is code that is common to all variants of expression-fixing.
+ * We must look up operator opcode info for OpExpr and related nodes,
+ * add OIDs from regclass Const nodes into glob->relationOids,
+ * and add catalog TIDs for user-defined functions into glob->invalItems.
+ *
+ * We assume it's okay to update opcode info in-place.  So this could possibly
+ * scribble on the planner's input data structures, but it's OK.
+ */
+static void
+fix_expr_common(PlannerGlobal *glob, Node *node)
+{
+       /* We assume callers won't call us on a NULL pointer */
+       if (IsA(node, Aggref))
+       {
+               record_plan_function_dependency(glob,
+                                                                               ((Aggref *) node)->aggfnoid);
+       }
+       else if (IsA(node, WindowFunc))
+       {
+               record_plan_function_dependency(glob,
+                                                                               ((WindowFunc *) node)->winfnoid);
+       }
+       else if (IsA(node, FuncExpr))
+       {
+               record_plan_function_dependency(glob,
+                                                                               ((FuncExpr *) node)->funcid);
+       }
+       else if (IsA(node, OpExpr))
+       {
+               set_opfuncid((OpExpr *) node);
+               record_plan_function_dependency(glob,
+                                                                               ((OpExpr *) node)->opfuncid);
+       }
+       else if (IsA(node, DistinctExpr))
+       {
+               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
+               record_plan_function_dependency(glob,
+                                                                               ((DistinctExpr *) node)->opfuncid);
+       }
+       else if (IsA(node, NullIfExpr))
+       {
+               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
+               record_plan_function_dependency(glob,
+                                                                               ((NullIfExpr *) node)->opfuncid);
+       }
+       else if (IsA(node, ScalarArrayOpExpr))
+       {
+               set_sa_opfuncid((ScalarArrayOpExpr *) node);
+               record_plan_function_dependency(glob,
+                                                                        ((ScalarArrayOpExpr *) node)->opfuncid);
+       }
+       else if (IsA(node, ArrayCoerceExpr))
+       {
+               if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
+                       record_plan_function_dependency(glob,
+                                                                        ((ArrayCoerceExpr *) node)->elemfuncid);
+       }
+       else if (IsA(node, Const))
+       {
+               Const      *con = (Const *) node;
+
+               /* Check for regclass reference */
+               if (ISREGCLASSCONST(con))
+                       glob->relationOids =
+                               lappend_oid(glob->relationOids,
+                                                       DatumGetObjectId(con->constvalue));
+       }
+}
+
 /*
  * fix_scan_expr
  *             Do set_plan_references processing on a scan-level expression
@@ -624,7 +830,24 @@ fix_scan_expr(PlannerGlobal *glob, Node *node, int rtoffset)
 
        context.glob = glob;
        context.rtoffset = rtoffset;
-       return fix_scan_expr_mutator(node, &context);
+
+       if (rtoffset != 0 || glob->lastPHId != 0)
+       {
+               return fix_scan_expr_mutator(node, &context);
+       }
+       else
+       {
+               /*
+                * If rtoffset == 0, we don't need to change any Vars, and if there
+                * are no placeholders anywhere we won't need to remove them.  Then
+                * it's OK to just scribble on the input node tree instead of copying
+                * (since the only change, filling in any unset opfuncid fields, is
+                * harmless).  This saves just enough cycles to be noticeable on
+                * trivial queries.
+                */
+               (void) fix_scan_expr_walker(node, &context);
+               return node;
+       }
 }
 
 static Node *
@@ -637,9 +860,10 @@ fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
                Var                *var = copyVar((Var *) node);
 
                Assert(var->varlevelsup == 0);
+
                /*
                 * We should not see any Vars marked INNER, but in a nestloop inner
-                * scan there could be OUTER Vars.  Leave them alone.
+                * scan there could be OUTER Vars.      Leave them alone.
                 */
                Assert(var->varno != INNER);
                if (var->varno > 0 && var->varno != OUTER)
@@ -657,33 +881,29 @@ fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
                cexpr->cvarno += context->rtoffset;
                return (Node *) cexpr;
        }
-       /*
-        * Since we update opcode info in-place, this part could possibly
-        * scribble on the planner's input data structures, but it's OK.
-        */
-       if (IsA(node, OpExpr))
-               set_opfuncid((OpExpr *) node);
-       else if (IsA(node, DistinctExpr))
-               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
-       else if (IsA(node, NullIfExpr))
-               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
-       else if (IsA(node, ScalarArrayOpExpr))
-               set_sa_opfuncid((ScalarArrayOpExpr *) node);
-       else if (IsA(node, Const))
+       if (IsA(node, PlaceHolderVar))
        {
-               Const      *con = (Const *) node;
+               /* At scan level, we should always just evaluate the contained expr */
+               PlaceHolderVar *phv = (PlaceHolderVar *) node;
 
-               /* Check for regclass reference */
-               if (con->consttype == REGCLASSOID && !con->constisnull)
-                       context->glob->relationOids =
-                               lappend_oid(context->glob->relationOids,
-                                                       DatumGetObjectId(con->constvalue));
-               /* Fall through to let expression_tree_mutator copy it */
+               return fix_scan_expr_mutator((Node *) phv->phexpr, context);
        }
+       fix_expr_common(context->glob, node);
        return expression_tree_mutator(node, fix_scan_expr_mutator,
                                                                   (void *) context);
 }
 
+static bool
+fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
+{
+       if (node == NULL)
+               return false;
+       Assert(!IsA(node, PlaceHolderVar));
+       fix_expr_common(context->glob, node);
+       return expression_tree_walker(node, fix_scan_expr_walker,
+                                                                 (void *) context);
+}
+
 /*
  * set_join_references
  *       Modify the target list and quals of a join node to reference its
@@ -981,10 +1201,25 @@ set_upper_references(PlannerGlobal *glob, Plan *plan, int rtoffset)
                TargetEntry *tle = (TargetEntry *) lfirst(l);
                Node       *newexpr;
 
-               newexpr = fix_upper_expr(glob,
-                                                                (Node *) tle->expr,
-                                                                subplan_itlist,
-                                                                rtoffset);
+               /* If it's a non-Var sort/group item, first try to match by sortref */
+               if (tle->ressortgroupref != 0 && !IsA(tle->expr, Var))
+               {
+                       newexpr = (Node *)
+                               search_indexed_tlist_for_sortgroupref((Node *) tle->expr,
+                                                                                                         tle->ressortgroupref,
+                                                                                                         subplan_itlist,
+                                                                                                         OUTER);
+                       if (!newexpr)
+                               newexpr = fix_upper_expr(glob,
+                                                                                (Node *) tle->expr,
+                                                                                subplan_itlist,
+                                                                                rtoffset);
+               }
+               else
+                       newexpr = fix_upper_expr(glob,
+                                                                        (Node *) tle->expr,
+                                                                        subplan_itlist,
+                                                                        rtoffset);
                tle = flatCopyTargetEntry(tle);
                tle->expr = (Expr *) newexpr;
                output_targetlist = lappend(output_targetlist, tle);
@@ -1038,7 +1273,7 @@ set_dummy_tlist_references(Plan *plan, int rtoffset)
                }
                else
                {
-                       newvar->varnoold = 0;   /* wasn't ever a plain Var */
+                       newvar->varnoold = 0;           /* wasn't ever a plain Var */
                        newvar->varoattno = 0;
                }
 
@@ -1078,6 +1313,7 @@ build_tlist_index(List *tlist)
                           list_length(tlist) * sizeof(tlist_vinfo));
 
        itlist->tlist = tlist;
+       itlist->has_ph_vars = false;
        itlist->has_non_vars = false;
 
        /* Find the Vars and fill in the index array */
@@ -1095,6 +1331,8 @@ build_tlist_index(List *tlist)
                        vinfo->resno = tle->resno;
                        vinfo++;
                }
+               else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
+                       itlist->has_ph_vars = true;
                else
                        itlist->has_non_vars = true;
        }
@@ -1108,7 +1346,9 @@ build_tlist_index(List *tlist)
  * build_tlist_index_other_vars --- build a restricted tlist index
  *
  * This is like build_tlist_index, but we only index tlist entries that
- * are Vars and belong to some rel other than the one specified.
+ * are Vars belonging to some rel other than the one specified.  We will set
+ * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
+ * (so nothing other than Vars and PlaceHolderVars can be matched).
  */
 static indexed_tlist *
 build_tlist_index_other_vars(List *tlist, Index ignore_rel)
@@ -1123,6 +1363,7 @@ build_tlist_index_other_vars(List *tlist, Index ignore_rel)
                           list_length(tlist) * sizeof(tlist_vinfo));
 
        itlist->tlist = tlist;
+       itlist->has_ph_vars = false;
        itlist->has_non_vars = false;
 
        /* Find the desired Vars and fill in the index array */
@@ -1143,6 +1384,8 @@ build_tlist_index_other_vars(List *tlist, Index ignore_rel)
                                vinfo++;
                        }
                }
+               else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
+                       itlist->has_ph_vars = true;
        }
 
        itlist->num_vars = (vinfo - itlist->vars);
@@ -1193,7 +1436,8 @@ search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
  * If a match is found, return a Var constructed to reference the tlist item.
  * If no match, return NULL.
  *
- * NOTE: it is a waste of time to call this if !itlist->has_non_vars
+ * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
+ * itlist->has_non_vars
  */
 static Var *
 search_indexed_tlist_for_non_var(Node *node,
@@ -1219,6 +1463,49 @@ search_indexed_tlist_for_non_var(Node *node,
        return NULL;                            /* no match */
 }
 
+/*
+ * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
+ *             (which is assumed not to be just a Var)
+ *
+ * If a match is found, return a Var constructed to reference the tlist item.
+ * If no match, return NULL.
+ *
+ * This is needed to ensure that we select the right subplan TLE in cases
+ * where there are multiple textually-equal()-but-volatile sort expressions.
+ * And it's also faster than search_indexed_tlist_for_non_var.
+ */
+static Var *
+search_indexed_tlist_for_sortgroupref(Node *node,
+                                                                         Index sortgroupref,
+                                                                         indexed_tlist *itlist,
+                                                                         Index newvarno)
+{
+       ListCell   *lc;
+
+       foreach(lc, itlist->tlist)
+       {
+               TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+               /* The equal() check should be redundant, but let's be paranoid */
+               if (tle->ressortgroupref == sortgroupref &&
+                       equal(node, tle->expr))
+               {
+                       /* Found a matching subplan output expression */
+                       Var                *newvar;
+
+                       newvar = makeVar(newvarno,
+                                                        tle->resno,
+                                                        exprType((Node *) tle->expr),
+                                                        exprTypmod((Node *) tle->expr),
+                                                        0);
+                       newvar->varnoold = 0;   /* wasn't ever a plain Var */
+                       newvar->varoattno = 0;
+                       return newvar;
+               }
+       }
+       return NULL;                            /* no match */
+}
+
 /*
  * fix_join_expr
  *        Create a new set of targetlist entries or join qual clauses by
@@ -1308,6 +1595,31 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
                /* No referent found for Var */
                elog(ERROR, "variable not found in subplan target lists");
        }
+       if (IsA(node, PlaceHolderVar))
+       {
+               PlaceHolderVar *phv = (PlaceHolderVar *) node;
+
+               /* See if the PlaceHolderVar has bubbled up from a lower plan node */
+               if (context->outer_itlist->has_ph_vars)
+               {
+                       newvar = search_indexed_tlist_for_non_var((Node *) phv,
+                                                                                                         context->outer_itlist,
+                                                                                                         OUTER);
+                       if (newvar)
+                               return (Node *) newvar;
+               }
+               if (context->inner_itlist && context->inner_itlist->has_ph_vars)
+               {
+                       newvar = search_indexed_tlist_for_non_var((Node *) phv,
+                                                                                                         context->inner_itlist,
+                                                                                                         INNER);
+                       if (newvar)
+                               return (Node *) newvar;
+               }
+
+               /* If not supplied by input plans, evaluate the contained expr */
+               return fix_join_expr_mutator((Node *) phv->phexpr, context);
+       }
        /* Try matching more complex expressions too, if tlists have any */
        if (context->outer_itlist->has_non_vars)
        {
@@ -1325,29 +1637,7 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
                if (newvar)
                        return (Node *) newvar;
        }
-       /*
-        * Since we update opcode info in-place, this part could possibly
-        * scribble on the planner's input data structures, but it's OK.
-        */
-       if (IsA(node, OpExpr))
-               set_opfuncid((OpExpr *) node);
-       else if (IsA(node, DistinctExpr))
-               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
-       else if (IsA(node, NullIfExpr))
-               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
-       else if (IsA(node, ScalarArrayOpExpr))
-               set_sa_opfuncid((ScalarArrayOpExpr *) node);
-       else if (IsA(node, Const))
-       {
-               Const      *con = (Const *) node;
-
-               /* Check for regclass reference */
-               if (con->consttype == REGCLASSOID && !con->constisnull)
-                       context->glob->relationOids =
-                               lappend_oid(context->glob->relationOids,
-                                                       DatumGetObjectId(con->constvalue));
-               /* Fall through to let expression_tree_mutator copy it */
-       }
+       fix_expr_common(context->glob, node);
        return expression_tree_mutator(node,
                                                                   fix_join_expr_mutator,
                                                                   (void *) context);
@@ -1413,6 +1703,22 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
                        elog(ERROR, "variable not found in subplan target list");
                return (Node *) newvar;
        }
+       if (IsA(node, PlaceHolderVar))
+       {
+               PlaceHolderVar *phv = (PlaceHolderVar *) node;
+
+               /* See if the PlaceHolderVar has bubbled up from a lower plan node */
+               if (context->subplan_itlist->has_ph_vars)
+               {
+                       newvar = search_indexed_tlist_for_non_var((Node *) phv,
+                                                                                                         context->subplan_itlist,
+                                                                                                         OUTER);
+                       if (newvar)
+                               return (Node *) newvar;
+               }
+               /* If not supplied by input plan, evaluate the contained expr */
+               return fix_upper_expr_mutator((Node *) phv->phexpr, context);
+       }
        /* Try matching more complex expressions too, if tlist has any */
        if (context->subplan_itlist->has_non_vars)
        {
@@ -1422,29 +1728,7 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
                if (newvar)
                        return (Node *) newvar;
        }
-       /*
-        * Since we update opcode info in-place, this part could possibly
-        * scribble on the planner's input data structures, but it's OK.
-        */
-       if (IsA(node, OpExpr))
-               set_opfuncid((OpExpr *) node);
-       else if (IsA(node, DistinctExpr))
-               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
-       else if (IsA(node, NullIfExpr))
-               set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
-       else if (IsA(node, ScalarArrayOpExpr))
-               set_sa_opfuncid((ScalarArrayOpExpr *) node);
-       else if (IsA(node, Const))
-       {
-               Const      *con = (Const *) node;
-
-               /* Check for regclass reference */
-               if (con->consttype == REGCLASSOID && !con->constisnull)
-                       context->glob->relationOids =
-                               lappend_oid(context->glob->relationOids,
-                                                       DatumGetObjectId(con->constvalue));
-               /* Fall through to let expression_tree_mutator copy it */
-       }
+       fix_expr_common(context->glob, node);
        return expression_tree_mutator(node,
                                                                   fix_upper_expr_mutator,
                                                                   (void *) context);
@@ -1456,7 +1740,7 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
  *
  * If the query involves more than just the result table, we have to
  * adjust any Vars that refer to other tables to reference junk tlist
- * entries in the top plan's targetlist.  Vars referencing the result
+ * entries in the top subplan's targetlist.  Vars referencing the result
  * table should be left alone, however (the executor will evaluate them
  * using the actual heap tuple, after firing triggers if any). In the
  * adjusted RETURNING list, result-table Vars will still have their
@@ -1466,8 +1750,8 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
  * glob->relationOids.
  *
  * 'rlist': the RETURNING targetlist to be fixed
- * 'topplan': the top Plan node for the query (not yet passed through
- *             set_plan_references)
+ * 'topplan': the top subplan node that will be just below the ModifyTable
+ *             node (note it's not yet passed through set_plan_references)
  * 'resultRelation': RT index of the associated result relation
  *
  * Note: we assume that result relations will have rtoffset zero, that is,
@@ -1485,8 +1769,15 @@ set_returning_clause_references(PlannerGlobal *glob,
         * We can perform the desired Var fixup by abusing the fix_join_expr
         * machinery that normally handles inner indexscan fixup.  We search the
         * top plan's targetlist for Vars of non-result relations, and use
-        * fix_join_expr to convert RETURNING Vars into references to those
-        * tlist entries, while leaving result-rel Vars as-is.
+        * fix_join_expr to convert RETURNING Vars into references to those tlist
+        * entries, while leaving result-rel Vars as-is.
+        *
+        * PlaceHolderVars will also be sought in the targetlist, but no
+        * more-complex expressions will be.  Note that it is not possible for a
+        * PlaceHolderVar to refer to the result relation, since the result is
+        * never below an outer join.  If that case could happen, we'd have to be
+        * prepared to pick apart the PlaceHolderVar and evaluate its contained
+        * expression instead.
         */
        itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
 
@@ -1563,3 +1854,123 @@ set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
        if (opexpr->opfuncid == InvalidOid)
                opexpr->opfuncid = get_opcode(opexpr->opno);
 }
+
+/*****************************************************************************
+ *                                     QUERY DEPENDENCY MANAGEMENT
+ *****************************************************************************/
+
+/*
+ * record_plan_function_dependency
+ *             Mark the current plan as depending on a particular function.
+ *
+ * This is exported so that the function-inlining code can record a
+ * dependency on a function that it's removed from the plan tree.
+ */
+void
+record_plan_function_dependency(PlannerGlobal *glob, Oid funcid)
+{
+       /*
+        * For performance reasons, we don't bother to track built-in functions;
+        * we just assume they'll never change (or at least not in ways that'd
+        * invalidate plans using them).  For this purpose we can consider a
+        * built-in function to be one with OID less than FirstBootstrapObjectId.
+        * Note that the OID generator guarantees never to generate such an OID
+        * after startup, even at OID wraparound.
+        */
+       if (funcid >= (Oid) FirstBootstrapObjectId)
+       {
+               HeapTuple       func_tuple;
+               PlanInvalItem *inval_item;
+
+               func_tuple = SearchSysCache(PROCOID,
+                                                                       ObjectIdGetDatum(funcid),
+                                                                       0, 0, 0);
+               if (!HeapTupleIsValid(func_tuple))
+                       elog(ERROR, "cache lookup failed for function %u", funcid);
+
+               inval_item = makeNode(PlanInvalItem);
+
+               /*
+                * It would work to use any syscache on pg_proc, but plancache.c
+                * expects us to use PROCOID.
+                */
+               inval_item->cacheId = PROCOID;
+               inval_item->tupleId = func_tuple->t_self;
+
+               glob->invalItems = lappend(glob->invalItems, inval_item);
+
+               ReleaseSysCache(func_tuple);
+       }
+}
+
+/*
+ * extract_query_dependencies
+ *             Given a not-yet-planned query or queries (i.e. a Query node or list
+ *             of Query nodes), extract dependencies just as set_plan_references
+ *             would do.
+ *
+ * This is needed by plancache.c to handle invalidation of cached unplanned
+ * queries.
+ */
+void
+extract_query_dependencies(Node *query,
+                                                  List **relationOids,
+                                                  List **invalItems)
+{
+       PlannerGlobal glob;
+
+       /* Make up a dummy PlannerGlobal so we can use this module's machinery */
+       MemSet(&glob, 0, sizeof(glob));
+       glob.type = T_PlannerGlobal;
+       glob.relationOids = NIL;
+       glob.invalItems = NIL;
+
+       (void) extract_query_dependencies_walker(query, &glob);
+
+       *relationOids = glob.relationOids;
+       *invalItems = glob.invalItems;
+}
+
+static bool
+extract_query_dependencies_walker(Node *node, PlannerGlobal *context)
+{
+       if (node == NULL)
+               return false;
+       Assert(!IsA(node, PlaceHolderVar));
+       /* Extract function dependencies and check for regclass Consts */
+       fix_expr_common(context, node);
+       if (IsA(node, Query))
+       {
+               Query      *query = (Query *) node;
+               ListCell   *lc;
+
+               if (query->commandType == CMD_UTILITY)
+               {
+                       /* Ignore utility statements, except EXPLAIN */
+                       if (IsA(query->utilityStmt, ExplainStmt))
+                       {
+                               query = (Query *) ((ExplainStmt *) query->utilityStmt)->query;
+                               Assert(IsA(query, Query));
+                               Assert(query->commandType != CMD_UTILITY);
+                       }
+                       else
+                               return false;
+               }
+
+               /* Collect relation OIDs in this Query's rtable */
+               foreach(lc, query->rtable)
+               {
+                       RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
+
+                       if (rte->rtekind == RTE_RELATION)
+                               context->relationOids = lappend_oid(context->relationOids,
+                                                                                                       rte->relid);
+               }
+
+               /* And recurse into the query's subexpressions */
+               return query_tree_walker(query, extract_query_dependencies_walker,
+                                                                (void *) context, 0);
+       }
+       return expression_tree_walker(node, extract_query_dependencies_walker,
+                                                                 (void *) context);
+}