1 /*-------------------------------------------------------------------------
4 * Post-processing of a completed plan tree: fix references to subplan
5 * vars, compute regproc values for operators, etc
7 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * src/backend/optimizer/plan/setrefs.c
14 *-------------------------------------------------------------------------
18 #include "access/transam.h"
19 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/planmain.h"
24 #include "optimizer/planner.h"
25 #include "optimizer/tlist.h"
26 #include "tcop/utility.h"
27 #include "utils/lsyscache.h"
28 #include "utils/syscache.h"
33 Index varno; /* RT index of Var */
34 AttrNumber varattno; /* attr number of Var */
35 AttrNumber resno; /* TLE position of Var */
40 List *tlist; /* underlying target list */
41 int num_vars; /* number of plain Var tlist entries */
42 bool has_ph_vars; /* are there PlaceHolderVar entries? */
43 bool has_non_vars; /* are there other entries? */
44 /* array of num_vars entries: */
45 tlist_vinfo vars[1]; /* VARIABLE LENGTH ARRAY */
46 } indexed_tlist; /* VARIABLE LENGTH STRUCT */
52 } fix_scan_expr_context;
57 indexed_tlist *outer_itlist;
58 indexed_tlist *inner_itlist;
61 } fix_join_expr_context;
66 indexed_tlist *subplan_itlist;
69 } fix_upper_expr_context;
72 * Check if a Const node is a regclass value. We accept plain OID too,
73 * since a regclass Const will get folded to that type if it's an argument
74 * to oideq or similar operators. (This might result in some extraneous
75 * values in a plan's list of relation dependencies, but the worst result
76 * would be occasional useless replans.)
78 #define ISREGCLASSCONST(con) \
79 (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
82 #define fix_scan_list(root, lst, rtoffset) \
83 ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset))
85 static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing);
86 static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte);
87 static bool flatten_rtes_walker(Node *node, PlannerGlobal *glob);
88 static void add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte);
89 static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
90 static Plan *set_indexonlyscan_references(PlannerInfo *root,
93 static Plan *set_subqueryscan_references(PlannerInfo *root,
96 static bool trivial_subqueryscan(SubqueryScan *plan);
97 static Node *fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset);
98 static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
99 static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
100 static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
101 static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
102 static void set_dummy_tlist_references(Plan *plan, int rtoffset);
103 static indexed_tlist *build_tlist_index(List *tlist);
104 static Var *search_indexed_tlist_for_var(Var *var,
105 indexed_tlist *itlist,
108 static Var *search_indexed_tlist_for_non_var(Node *node,
109 indexed_tlist *itlist,
111 static Var *search_indexed_tlist_for_sortgroupref(Node *node,
113 indexed_tlist *itlist,
115 static List *fix_join_expr(PlannerInfo *root,
117 indexed_tlist *outer_itlist,
118 indexed_tlist *inner_itlist,
119 Index acceptable_rel, int rtoffset);
120 static Node *fix_join_expr_mutator(Node *node,
121 fix_join_expr_context *context);
122 static Node *fix_upper_expr(PlannerInfo *root,
124 indexed_tlist *subplan_itlist,
127 static Node *fix_upper_expr_mutator(Node *node,
128 fix_upper_expr_context *context);
129 static List *set_returning_clause_references(PlannerInfo *root,
132 Index resultRelation,
134 static bool fix_opfuncids_walker(Node *node, void *context);
135 static bool extract_query_dependencies_walker(Node *node,
136 PlannerInfo *context);
139 /*****************************************************************************
143 *****************************************************************************/
146 * set_plan_references
148 * This is the final processing pass of the planner/optimizer. The plan
149 * tree is complete; we just have to adjust some representational details
150 * for the convenience of the executor:
152 * 1. We flatten the various subquery rangetables into a single list, and
153 * zero out RangeTblEntry fields that are not useful to the executor.
155 * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
157 * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
160 * 4. We compute regproc OIDs for operators (ie, we look up the function
161 * that implements each op).
163 * 5. We create lists of specific objects that the plan depends on.
164 * This will be used by plancache.c to drive invalidation of cached plans.
165 * Relation dependencies are represented by OIDs, and everything else by
166 * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
167 * Currently, relations and user-defined functions are the only types of
168 * objects that are explicitly tracked this way.
170 * We also perform one final optimization step, which is to delete
171 * SubqueryScan plan nodes that aren't doing anything useful (ie, have
172 * no qual and a no-op targetlist). The reason for doing this last is that
173 * it can't readily be done before set_plan_references, because it would
174 * break set_upper_references: the Vars in the subquery's top tlist
175 * wouldn't match up with the Vars in the outer plan tree. The SubqueryScan
176 * serves a necessary function as a buffer between outer query and subquery
177 * variable numbering ... but after we've flattened the rangetable this is
178 * no longer a problem, since then there's only one rtindex namespace.
180 * set_plan_references recursively traverses the whole plan tree.
182 * The return value is normally the same Plan node passed in, but can be
183 * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
185 * The flattened rangetable entries are appended to root->glob->finalrtable.
186 * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
187 * RT indexes of ModifyTable result relations to root->glob->resultRelations.
188 * Plan dependencies are appended to root->glob->relationOids (for relations)
189 * and root->glob->invalItems (for everything else).
191 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
192 * to process targetlist and qual expressions. We can assume that the Plan
193 * nodes were just built by the planner and are not multiply referenced, but
194 * it's not so safe to assume that for expression tree nodes.
197 set_plan_references(PlannerInfo *root, Plan *plan)
199 PlannerGlobal *glob = root->glob;
200 int rtoffset = list_length(glob->finalrtable);
204 * Add all the query's RTEs to the flattened rangetable. The live ones
205 * will have their rangetable indexes increased by rtoffset. (Additional
206 * RTEs, not referenced by the Plan tree, might get added after those.)
208 add_rtes_to_flat_rtable(root, false);
211 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
213 foreach(lc, root->rowMarks)
215 PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
218 Assert(IsA(rc, PlanRowMark));
220 /* flat copy is enough since all fields are scalars */
221 newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
222 memcpy(newrc, rc, sizeof(PlanRowMark));
224 /* adjust indexes ... but *not* the rowmarkId */
225 newrc->rti += rtoffset;
226 newrc->prti += rtoffset;
228 glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
231 /* Now fix the Plan tree */
232 return set_plan_refs(root, plan, rtoffset);
236 * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
238 * This can recurse into subquery plans; "recursing" is true if so.
241 add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
243 PlannerGlobal *glob = root->glob;
248 * Add the query's own RTEs to the flattened rangetable.
250 * At top level, we must add all RTEs so that their indexes in the
251 * flattened rangetable match up with their original indexes. When
252 * recursing, we only care about extracting relation RTEs.
254 foreach(lc, root->parse->rtable)
256 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
258 if (!recursing || rte->rtekind == RTE_RELATION)
259 add_rte_to_flat_rtable(glob, rte);
263 * If there are any dead subqueries, they are not referenced in the Plan
264 * tree, so we must add RTEs contained in them to the flattened rtable
265 * separately. (If we failed to do this, the executor would not perform
266 * expected permission checks for tables mentioned in such subqueries.)
268 * Note: this pass over the rangetable can't be combined with the previous
269 * one, because that would mess up the numbering of the live RTEs in the
270 * flattened rangetable.
273 foreach(lc, root->parse->rtable)
275 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
278 * We should ignore inheritance-parent RTEs: their contents have been
279 * pulled up into our rangetable already. Also ignore any subquery
280 * RTEs without matching RelOptInfos, as they likewise have been
283 if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
285 RelOptInfo *rel = root->simple_rel_array[rti];
289 Assert(rel->relid == rti); /* sanity check on array */
292 * The subquery might never have been planned at all, if it
293 * was excluded on the basis of self-contradictory constraints
294 * in our query level. In this case apply
295 * flatten_unplanned_rtes.
297 * If it was planned but the plan is dummy, we assume that it
298 * has been omitted from our plan tree (see
299 * set_subquery_pathlist), and recurse to pull up its RTEs.
301 * Otherwise, it should be represented by a SubqueryScan node
302 * somewhere in our plan tree, and we'll pull up its RTEs when
303 * we process that plan node.
305 * However, if we're recursing, then we should pull up RTEs
306 * whether the subplan is dummy or not, because we've found
307 * that some upper query level is treating this one as dummy,
308 * and so we won't scan this level's plan tree at all.
310 if (rel->subplan == NULL)
311 flatten_unplanned_rtes(glob, rte);
312 else if (recursing || is_dummy_plan(rel->subplan))
314 Assert(rel->subroot != NULL);
315 add_rtes_to_flat_rtable(rel->subroot, true);
324 * Extract RangeTblEntries from a subquery that was never planned at all
327 flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
329 /* Use query_tree_walker to find all RTEs in the parse tree */
330 (void) query_tree_walker(rte->subquery,
337 flatten_rtes_walker(Node *node, PlannerGlobal *glob)
341 if (IsA(node, RangeTblEntry))
343 RangeTblEntry *rte = (RangeTblEntry *) node;
345 /* As above, we need only save relation RTEs */
346 if (rte->rtekind == RTE_RELATION)
347 add_rte_to_flat_rtable(glob, rte);
350 if (IsA(node, Query))
352 /* Recurse into subselects */
353 return query_tree_walker((Query *) node,
358 return expression_tree_walker(node, flatten_rtes_walker,
363 * Add (a copy of) the given RTE to the final rangetable
365 * In the flat rangetable, we zero out substructure pointers that are not
366 * needed by the executor; this reduces the storage space and copying cost
367 * for cached plans. We keep only the alias and eref Alias fields, which
368 * are needed by EXPLAIN, and the selectedCols and modifiedCols bitmaps,
369 * which are needed for executor-startup permissions checking and for
370 * trigger event checking.
373 add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte)
375 RangeTblEntry *newrte;
377 /* flat copy to duplicate all the scalar fields */
378 newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
379 memcpy(newrte, rte, sizeof(RangeTblEntry));
381 /* zap unneeded sub-structure */
382 newrte->subquery = NULL;
383 newrte->joinaliasvars = NIL;
384 newrte->functions = NIL;
385 newrte->values_lists = NIL;
386 newrte->values_collations = NIL;
387 newrte->ctecoltypes = NIL;
388 newrte->ctecoltypmods = NIL;
389 newrte->ctecolcollations = NIL;
391 glob->finalrtable = lappend(glob->finalrtable, newrte);
394 * Check for RT index overflow; it's very unlikely, but if it did happen,
395 * the executor would get confused by varnos that match the special varno
398 if (IS_SPECIAL_VARNO(list_length(glob->finalrtable)))
400 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
401 errmsg("too many range table entries")));
404 * If it's a plain relation RTE, add the table to relationOids.
406 * We do this even though the RTE might be unreferenced in the plan tree;
407 * this would correspond to cases such as views that were expanded, child
408 * tables that were eliminated by constraint exclusion, etc. Schema
409 * invalidation on such a rel must still force rebuilding of the plan.
411 * Note we don't bother to avoid making duplicate list entries. We could,
412 * but it would probably cost more cycles than it would save.
414 if (newrte->rtekind == RTE_RELATION)
415 glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
419 * set_plan_refs: recurse through the Plan nodes of a single subquery level
422 set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
430 * Plan-type-specific fixes
432 switch (nodeTag(plan))
436 SeqScan *splan = (SeqScan *) plan;
438 splan->scanrelid += rtoffset;
439 splan->plan.targetlist =
440 fix_scan_list(root, splan->plan.targetlist, rtoffset);
442 fix_scan_list(root, splan->plan.qual, rtoffset);
447 IndexScan *splan = (IndexScan *) plan;
449 splan->scan.scanrelid += rtoffset;
450 splan->scan.plan.targetlist =
451 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
452 splan->scan.plan.qual =
453 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
455 fix_scan_list(root, splan->indexqual, rtoffset);
456 splan->indexqualorig =
457 fix_scan_list(root, splan->indexqualorig, rtoffset);
458 splan->indexorderby =
459 fix_scan_list(root, splan->indexorderby, rtoffset);
460 splan->indexorderbyorig =
461 fix_scan_list(root, splan->indexorderbyorig, rtoffset);
464 case T_IndexOnlyScan:
466 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
468 return set_indexonlyscan_references(root, splan, rtoffset);
471 case T_BitmapIndexScan:
473 BitmapIndexScan *splan = (BitmapIndexScan *) plan;
475 splan->scan.scanrelid += rtoffset;
476 /* no need to fix targetlist and qual */
477 Assert(splan->scan.plan.targetlist == NIL);
478 Assert(splan->scan.plan.qual == NIL);
480 fix_scan_list(root, splan->indexqual, rtoffset);
481 splan->indexqualorig =
482 fix_scan_list(root, splan->indexqualorig, rtoffset);
485 case T_BitmapHeapScan:
487 BitmapHeapScan *splan = (BitmapHeapScan *) plan;
489 splan->scan.scanrelid += rtoffset;
490 splan->scan.plan.targetlist =
491 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
492 splan->scan.plan.qual =
493 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
494 splan->bitmapqualorig =
495 fix_scan_list(root, splan->bitmapqualorig, rtoffset);
500 TidScan *splan = (TidScan *) plan;
502 splan->scan.scanrelid += rtoffset;
503 splan->scan.plan.targetlist =
504 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
505 splan->scan.plan.qual =
506 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
508 fix_scan_list(root, splan->tidquals, rtoffset);
512 /* Needs special treatment, see comments below */
513 return set_subqueryscan_references(root,
514 (SubqueryScan *) plan,
518 FunctionScan *splan = (FunctionScan *) plan;
520 splan->scan.scanrelid += rtoffset;
521 splan->scan.plan.targetlist =
522 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
523 splan->scan.plan.qual =
524 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
526 fix_scan_list(root, splan->functions, rtoffset);
531 ValuesScan *splan = (ValuesScan *) plan;
533 splan->scan.scanrelid += rtoffset;
534 splan->scan.plan.targetlist =
535 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
536 splan->scan.plan.qual =
537 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
538 splan->values_lists =
539 fix_scan_list(root, splan->values_lists, rtoffset);
544 CteScan *splan = (CteScan *) plan;
546 splan->scan.scanrelid += rtoffset;
547 splan->scan.plan.targetlist =
548 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
549 splan->scan.plan.qual =
550 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
553 case T_WorkTableScan:
555 WorkTableScan *splan = (WorkTableScan *) plan;
557 splan->scan.scanrelid += rtoffset;
558 splan->scan.plan.targetlist =
559 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
560 splan->scan.plan.qual =
561 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
566 ForeignScan *splan = (ForeignScan *) plan;
568 splan->scan.scanrelid += rtoffset;
569 splan->scan.plan.targetlist =
570 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
571 splan->scan.plan.qual =
572 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
574 fix_scan_list(root, splan->fdw_exprs, rtoffset);
581 set_join_references(root, (Join *) plan, rtoffset);
591 * These plan types don't actually bother to evaluate their
592 * targetlists, because they just return their unmodified input
593 * tuples. Even though the targetlist won't be used by the
594 * executor, we fix it up for possible use by EXPLAIN (not to
595 * mention ease of debugging --- wrong varnos are very confusing).
597 set_dummy_tlist_references(plan, rtoffset);
600 * Since these plan types don't check quals either, we should not
601 * find any qual expression attached to them.
603 Assert(plan->qual == NIL);
607 LockRows *splan = (LockRows *) plan;
610 * Like the plan types above, LockRows doesn't evaluate its
611 * tlist or quals. But we have to fix up the RT indexes in
614 set_dummy_tlist_references(plan, rtoffset);
615 Assert(splan->plan.qual == NIL);
617 foreach(l, splan->rowMarks)
619 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
622 rc->prti += rtoffset;
628 Limit *splan = (Limit *) plan;
631 * Like the plan types above, Limit doesn't evaluate its tlist
632 * or quals. It does have live expressions for limit/offset,
633 * however; and those cannot contain subplan variable refs, so
634 * fix_scan_expr works for them.
636 set_dummy_tlist_references(plan, rtoffset);
637 Assert(splan->plan.qual == NIL);
640 fix_scan_expr(root, splan->limitOffset, rtoffset);
642 fix_scan_expr(root, splan->limitCount, rtoffset);
647 set_upper_references(root, plan, rtoffset);
651 WindowAgg *wplan = (WindowAgg *) plan;
653 set_upper_references(root, plan, rtoffset);
656 * Like Limit node limit/offset expressions, WindowAgg has
657 * frame offset expressions, which cannot contain subplan
658 * variable refs, so fix_scan_expr works for them.
661 fix_scan_expr(root, wplan->startOffset, rtoffset);
663 fix_scan_expr(root, wplan->endOffset, rtoffset);
668 Result *splan = (Result *) plan;
671 * Result may or may not have a subplan; if not, it's more
672 * like a scan node than an upper node.
674 if (splan->plan.lefttree != NULL)
675 set_upper_references(root, plan, rtoffset);
678 splan->plan.targetlist =
679 fix_scan_list(root, splan->plan.targetlist, rtoffset);
681 fix_scan_list(root, splan->plan.qual, rtoffset);
683 /* resconstantqual can't contain any subplan variable refs */
684 splan->resconstantqual =
685 fix_scan_expr(root, splan->resconstantqual, rtoffset);
690 ModifyTable *splan = (ModifyTable *) plan;
692 Assert(splan->plan.targetlist == NIL);
693 Assert(splan->plan.qual == NIL);
695 if (splan->returningLists)
703 * Pass each per-subplan returningList through
704 * set_returning_clause_references().
706 Assert(list_length(splan->returningLists) == list_length(splan->resultRelations));
707 Assert(list_length(splan->returningLists) == list_length(splan->plans));
708 forthree(lcrl, splan->returningLists,
709 lcrr, splan->resultRelations,
712 List *rlist = (List *) lfirst(lcrl);
713 Index resultrel = lfirst_int(lcrr);
714 Plan *subplan = (Plan *) lfirst(lcp);
716 rlist = set_returning_clause_references(root,
721 newRL = lappend(newRL, rlist);
723 splan->returningLists = newRL;
726 * Set up the visible plan targetlist as being the same as
727 * the first RETURNING list. This is for the use of
728 * EXPLAIN; the executor won't pay any attention to the
729 * targetlist. We postpone this step until here so that
730 * we don't have to do set_returning_clause_references()
731 * twice on identical targetlists.
733 splan->plan.targetlist = copyObject(linitial(newRL));
736 foreach(l, splan->resultRelations)
738 lfirst_int(l) += rtoffset;
740 foreach(l, splan->rowMarks)
742 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
745 rc->prti += rtoffset;
747 foreach(l, splan->plans)
749 lfirst(l) = set_plan_refs(root,
755 * Append this ModifyTable node's final result relation RT
756 * index(es) to the global list for the plan, and set its
757 * resultRelIndex to reflect their starting position in the
760 splan->resultRelIndex = list_length(root->glob->resultRelations);
761 root->glob->resultRelations =
762 list_concat(root->glob->resultRelations,
763 list_copy(splan->resultRelations));
768 Append *splan = (Append *) plan;
771 * Append, like Sort et al, doesn't actually evaluate its
772 * targetlist or check quals.
774 set_dummy_tlist_references(plan, rtoffset);
775 Assert(splan->plan.qual == NIL);
776 foreach(l, splan->appendplans)
778 lfirst(l) = set_plan_refs(root,
786 MergeAppend *splan = (MergeAppend *) plan;
789 * MergeAppend, like Sort et al, doesn't actually evaluate its
790 * targetlist or check quals.
792 set_dummy_tlist_references(plan, rtoffset);
793 Assert(splan->plan.qual == NIL);
794 foreach(l, splan->mergeplans)
796 lfirst(l) = set_plan_refs(root,
802 case T_RecursiveUnion:
803 /* This doesn't evaluate targetlist or check quals either */
804 set_dummy_tlist_references(plan, rtoffset);
805 Assert(plan->qual == NIL);
809 BitmapAnd *splan = (BitmapAnd *) plan;
811 /* BitmapAnd works like Append, but has no tlist */
812 Assert(splan->plan.targetlist == NIL);
813 Assert(splan->plan.qual == NIL);
814 foreach(l, splan->bitmapplans)
816 lfirst(l) = set_plan_refs(root,
824 BitmapOr *splan = (BitmapOr *) plan;
826 /* BitmapOr works like Append, but has no tlist */
827 Assert(splan->plan.targetlist == NIL);
828 Assert(splan->plan.qual == NIL);
829 foreach(l, splan->bitmapplans)
831 lfirst(l) = set_plan_refs(root,
838 elog(ERROR, "unrecognized node type: %d",
839 (int) nodeTag(plan));
844 * Now recurse into child plans, if any
846 * NOTE: it is essential that we recurse into child plans AFTER we set
847 * subplan references in this plan's tlist and quals. If we did the
848 * reference-adjustments bottom-up, then we would fail to match this
849 * plan's var nodes against the already-modified nodes of the children.
851 plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
852 plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
858 * set_indexonlyscan_references
859 * Do set_plan_references processing on an IndexOnlyScan
861 * This is unlike the handling of a plain IndexScan because we have to
862 * convert Vars referencing the heap into Vars referencing the index.
863 * We can use the fix_upper_expr machinery for that, by working from a
864 * targetlist describing the index columns.
867 set_indexonlyscan_references(PlannerInfo *root,
871 indexed_tlist *index_itlist;
873 index_itlist = build_tlist_index(plan->indextlist);
875 plan->scan.scanrelid += rtoffset;
876 plan->scan.plan.targetlist = (List *)
878 (Node *) plan->scan.plan.targetlist,
882 plan->scan.plan.qual = (List *)
884 (Node *) plan->scan.plan.qual,
888 /* indexqual is already transformed to reference index columns */
889 plan->indexqual = fix_scan_list(root, plan->indexqual, rtoffset);
890 /* indexorderby is already transformed to reference index columns */
891 plan->indexorderby = fix_scan_list(root, plan->indexorderby, rtoffset);
892 /* indextlist must NOT be transformed to reference index columns */
893 plan->indextlist = fix_scan_list(root, plan->indextlist, rtoffset);
897 return (Plan *) plan;
901 * set_subqueryscan_references
902 * Do set_plan_references processing on a SubqueryScan
904 * We try to strip out the SubqueryScan entirely; if we can't, we have
905 * to do the normal processing on it.
908 set_subqueryscan_references(PlannerInfo *root,
915 /* Need to look up the subquery's RelOptInfo, since we need its subroot */
916 rel = find_base_rel(root, plan->scan.scanrelid);
917 Assert(rel->subplan == plan->subplan);
919 /* Recursively process the subplan */
920 plan->subplan = set_plan_references(rel->subroot, plan->subplan);
922 if (trivial_subqueryscan(plan))
925 * We can omit the SubqueryScan node and just pull up the subplan.
930 result = plan->subplan;
932 /* We have to be sure we don't lose any initplans */
933 result->initPlan = list_concat(plan->scan.plan.initPlan,
937 * We also have to transfer the SubqueryScan's result-column names
938 * into the subplan, else columns sent to client will be improperly
939 * labeled if this is the topmost plan level. Copy the "source
940 * column" information too.
942 forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
944 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
945 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
947 ctle->resname = ptle->resname;
948 ctle->resorigtbl = ptle->resorigtbl;
949 ctle->resorigcol = ptle->resorigcol;
955 * Keep the SubqueryScan node. We have to do the processing that
956 * set_plan_references would otherwise have done on it. Notice we do
957 * not do set_upper_references() here, because a SubqueryScan will
958 * always have been created with correct references to its subplan's
959 * outputs to begin with.
961 plan->scan.scanrelid += rtoffset;
962 plan->scan.plan.targetlist =
963 fix_scan_list(root, plan->scan.plan.targetlist, rtoffset);
964 plan->scan.plan.qual =
965 fix_scan_list(root, plan->scan.plan.qual, rtoffset);
967 result = (Plan *) plan;
974 * trivial_subqueryscan
975 * Detect whether a SubqueryScan can be deleted from the plan tree.
977 * We can delete it if it has no qual to check and the targetlist just
978 * regurgitates the output of the child plan.
981 trivial_subqueryscan(SubqueryScan *plan)
987 if (plan->scan.plan.qual != NIL)
990 if (list_length(plan->scan.plan.targetlist) !=
991 list_length(plan->subplan->targetlist))
992 return false; /* tlists not same length */
995 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
997 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
998 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
1000 if (ptle->resjunk != ctle->resjunk)
1001 return false; /* tlist doesn't match junk status */
1004 * We accept either a Var referencing the corresponding element of the
1005 * subplan tlist, or a Const equaling the subplan element. See
1006 * generate_setop_tlist() for motivation.
1008 if (ptle->expr && IsA(ptle->expr, Var))
1010 Var *var = (Var *) ptle->expr;
1012 Assert(var->varno == plan->scan.scanrelid);
1013 Assert(var->varlevelsup == 0);
1014 if (var->varattno != attrno)
1015 return false; /* out of order */
1017 else if (ptle->expr && IsA(ptle->expr, Const))
1019 if (!equal(ptle->expr, ctle->expr))
1035 * fix_scan_expr and friends do this enough times that it's worth having
1036 * a bespoke routine instead of using the generic copyObject() function.
1041 Var *newvar = (Var *) palloc(sizeof(Var));
1049 * Do generic set_plan_references processing on an expression node
1051 * This is code that is common to all variants of expression-fixing.
1052 * We must look up operator opcode info for OpExpr and related nodes,
1053 * add OIDs from regclass Const nodes into root->glob->relationOids, and
1054 * add catalog TIDs for user-defined functions into root->glob->invalItems.
1056 * We assume it's okay to update opcode info in-place. So this could possibly
1057 * scribble on the planner's input data structures, but it's OK.
1060 fix_expr_common(PlannerInfo *root, Node *node)
1062 /* We assume callers won't call us on a NULL pointer */
1063 if (IsA(node, Aggref))
1065 record_plan_function_dependency(root,
1066 ((Aggref *) node)->aggfnoid);
1068 else if (IsA(node, WindowFunc))
1070 record_plan_function_dependency(root,
1071 ((WindowFunc *) node)->winfnoid);
1073 else if (IsA(node, FuncExpr))
1075 record_plan_function_dependency(root,
1076 ((FuncExpr *) node)->funcid);
1078 else if (IsA(node, OpExpr))
1080 set_opfuncid((OpExpr *) node);
1081 record_plan_function_dependency(root,
1082 ((OpExpr *) node)->opfuncid);
1084 else if (IsA(node, DistinctExpr))
1086 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1087 record_plan_function_dependency(root,
1088 ((DistinctExpr *) node)->opfuncid);
1090 else if (IsA(node, NullIfExpr))
1092 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1093 record_plan_function_dependency(root,
1094 ((NullIfExpr *) node)->opfuncid);
1096 else if (IsA(node, ScalarArrayOpExpr))
1098 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1099 record_plan_function_dependency(root,
1100 ((ScalarArrayOpExpr *) node)->opfuncid);
1102 else if (IsA(node, ArrayCoerceExpr))
1104 if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
1105 record_plan_function_dependency(root,
1106 ((ArrayCoerceExpr *) node)->elemfuncid);
1108 else if (IsA(node, Const))
1110 Const *con = (Const *) node;
1112 /* Check for regclass reference */
1113 if (ISREGCLASSCONST(con))
1114 root->glob->relationOids =
1115 lappend_oid(root->glob->relationOids,
1116 DatumGetObjectId(con->constvalue));
1122 * Do set_plan_references processing on a scan-level expression
1124 * This consists of incrementing all Vars' varnos by rtoffset,
1125 * looking up operator opcode info for OpExpr and related nodes,
1126 * and adding OIDs from regclass Const nodes into root->glob->relationOids.
1129 fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset)
1131 fix_scan_expr_context context;
1133 context.root = root;
1134 context.rtoffset = rtoffset;
1136 if (rtoffset != 0 || root->glob->lastPHId != 0)
1138 return fix_scan_expr_mutator(node, &context);
1143 * If rtoffset == 0, we don't need to change any Vars, and if there
1144 * are no placeholders anywhere we won't need to remove them. Then
1145 * it's OK to just scribble on the input node tree instead of copying
1146 * (since the only change, filling in any unset opfuncid fields, is
1147 * harmless). This saves just enough cycles to be noticeable on
1150 (void) fix_scan_expr_walker(node, &context);
1156 fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
1162 Var *var = copyVar((Var *) node);
1164 Assert(var->varlevelsup == 0);
1167 * We should not see any Vars marked INNER_VAR or OUTER_VAR. But an
1168 * indexqual expression could contain INDEX_VAR Vars.
1170 Assert(var->varno != INNER_VAR);
1171 Assert(var->varno != OUTER_VAR);
1172 if (!IS_SPECIAL_VARNO(var->varno))
1173 var->varno += context->rtoffset;
1174 if (var->varnoold > 0)
1175 var->varnoold += context->rtoffset;
1176 return (Node *) var;
1178 if (IsA(node, CurrentOfExpr))
1180 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
1182 Assert(cexpr->cvarno != INNER_VAR);
1183 Assert(cexpr->cvarno != OUTER_VAR);
1184 if (!IS_SPECIAL_VARNO(cexpr->cvarno))
1185 cexpr->cvarno += context->rtoffset;
1186 return (Node *) cexpr;
1188 if (IsA(node, PlaceHolderVar))
1190 /* At scan level, we should always just evaluate the contained expr */
1191 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1193 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
1195 fix_expr_common(context->root, node);
1196 return expression_tree_mutator(node, fix_scan_expr_mutator,
1201 fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
1205 Assert(!IsA(node, PlaceHolderVar));
1206 fix_expr_common(context->root, node);
1207 return expression_tree_walker(node, fix_scan_expr_walker,
1212 * set_join_references
1213 * Modify the target list and quals of a join node to reference its
1214 * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
1215 * attno values to the result domain number of either the corresponding
1216 * outer or inner join tuple item. Also perform opcode lookup for these
1217 * expressions. and add regclass OIDs to root->glob->relationOids.
1220 set_join_references(PlannerInfo *root, Join *join, int rtoffset)
1222 Plan *outer_plan = join->plan.lefttree;
1223 Plan *inner_plan = join->plan.righttree;
1224 indexed_tlist *outer_itlist;
1225 indexed_tlist *inner_itlist;
1227 outer_itlist = build_tlist_index(outer_plan->targetlist);
1228 inner_itlist = build_tlist_index(inner_plan->targetlist);
1230 /* All join plans have tlist, qual, and joinqual */
1231 join->plan.targetlist = fix_join_expr(root,
1232 join->plan.targetlist,
1237 join->plan.qual = fix_join_expr(root,
1243 join->joinqual = fix_join_expr(root,
1250 /* Now do join-type-specific stuff */
1251 if (IsA(join, NestLoop))
1253 NestLoop *nl = (NestLoop *) join;
1256 foreach(lc, nl->nestParams)
1258 NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
1260 nlp->paramval = (Var *) fix_upper_expr(root,
1261 (Node *) nlp->paramval,
1265 /* Check we replaced any PlaceHolderVar with simple Var */
1266 if (!(IsA(nlp->paramval, Var) &&
1267 nlp->paramval->varno == OUTER_VAR))
1268 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
1271 else if (IsA(join, MergeJoin))
1273 MergeJoin *mj = (MergeJoin *) join;
1275 mj->mergeclauses = fix_join_expr(root,
1282 else if (IsA(join, HashJoin))
1284 HashJoin *hj = (HashJoin *) join;
1286 hj->hashclauses = fix_join_expr(root,
1294 pfree(outer_itlist);
1295 pfree(inner_itlist);
1299 * set_upper_references
1300 * Update the targetlist and quals of an upper-level plan node
1301 * to refer to the tuples returned by its lefttree subplan.
1302 * Also perform opcode lookup for these expressions, and
1303 * add regclass OIDs to root->glob->relationOids.
1305 * This is used for single-input plan types like Agg, Group, Result.
1307 * In most cases, we have to match up individual Vars in the tlist and
1308 * qual expressions with elements of the subplan's tlist (which was
1309 * generated by flatten_tlist() from these selfsame expressions, so it
1310 * should have all the required variables). There is an important exception,
1311 * however: GROUP BY and ORDER BY expressions will have been pushed into the
1312 * subplan tlist unflattened. If these values are also needed in the output
1313 * then we want to reference the subplan tlist element rather than recomputing
1317 set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
1319 Plan *subplan = plan->lefttree;
1320 indexed_tlist *subplan_itlist;
1321 List *output_targetlist;
1324 subplan_itlist = build_tlist_index(subplan->targetlist);
1326 output_targetlist = NIL;
1327 foreach(l, plan->targetlist)
1329 TargetEntry *tle = (TargetEntry *) lfirst(l);
1332 /* If it's a non-Var sort/group item, first try to match by sortref */
1333 if (tle->ressortgroupref != 0 && !IsA(tle->expr, Var))
1336 search_indexed_tlist_for_sortgroupref((Node *) tle->expr,
1337 tle->ressortgroupref,
1341 newexpr = fix_upper_expr(root,
1348 newexpr = fix_upper_expr(root,
1353 tle = flatCopyTargetEntry(tle);
1354 tle->expr = (Expr *) newexpr;
1355 output_targetlist = lappend(output_targetlist, tle);
1357 plan->targetlist = output_targetlist;
1359 plan->qual = (List *)
1360 fix_upper_expr(root,
1361 (Node *) plan->qual,
1366 pfree(subplan_itlist);
1370 * set_dummy_tlist_references
1371 * Replace the targetlist of an upper-level plan node with a simple
1372 * list of OUTER_VAR references to its child.
1374 * This is used for plan types like Sort and Append that don't evaluate
1375 * their targetlists. Although the executor doesn't care at all what's in
1376 * the tlist, EXPLAIN needs it to be realistic.
1378 * Note: we could almost use set_upper_references() here, but it fails for
1379 * Append for lack of a lefttree subplan. Single-purpose code is faster
1383 set_dummy_tlist_references(Plan *plan, int rtoffset)
1385 List *output_targetlist;
1388 output_targetlist = NIL;
1389 foreach(l, plan->targetlist)
1391 TargetEntry *tle = (TargetEntry *) lfirst(l);
1392 Var *oldvar = (Var *) tle->expr;
1395 newvar = makeVar(OUTER_VAR,
1397 exprType((Node *) oldvar),
1398 exprTypmod((Node *) oldvar),
1399 exprCollation((Node *) oldvar),
1401 if (IsA(oldvar, Var))
1403 newvar->varnoold = oldvar->varno + rtoffset;
1404 newvar->varoattno = oldvar->varattno;
1408 newvar->varnoold = 0; /* wasn't ever a plain Var */
1409 newvar->varoattno = 0;
1412 tle = flatCopyTargetEntry(tle);
1413 tle->expr = (Expr *) newvar;
1414 output_targetlist = lappend(output_targetlist, tle);
1416 plan->targetlist = output_targetlist;
1418 /* We don't touch plan->qual here */
1423 * build_tlist_index --- build an index data structure for a child tlist
1425 * In most cases, subplan tlists will be "flat" tlists with only Vars,
1426 * so we try to optimize that case by extracting information about Vars
1427 * in advance. Matching a parent tlist to a child is still an O(N^2)
1428 * operation, but at least with a much smaller constant factor than plain
1429 * tlist_member() searches.
1431 * The result of this function is an indexed_tlist struct to pass to
1432 * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
1433 * When done, the indexed_tlist may be freed with a single pfree().
1435 static indexed_tlist *
1436 build_tlist_index(List *tlist)
1438 indexed_tlist *itlist;
1442 /* Create data structure with enough slots for all tlist entries */
1443 itlist = (indexed_tlist *)
1444 palloc(offsetof(indexed_tlist, vars) +
1445 list_length(tlist) * sizeof(tlist_vinfo));
1447 itlist->tlist = tlist;
1448 itlist->has_ph_vars = false;
1449 itlist->has_non_vars = false;
1451 /* Find the Vars and fill in the index array */
1452 vinfo = itlist->vars;
1455 TargetEntry *tle = (TargetEntry *) lfirst(l);
1457 if (tle->expr && IsA(tle->expr, Var))
1459 Var *var = (Var *) tle->expr;
1461 vinfo->varno = var->varno;
1462 vinfo->varattno = var->varattno;
1463 vinfo->resno = tle->resno;
1466 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1467 itlist->has_ph_vars = true;
1469 itlist->has_non_vars = true;
1472 itlist->num_vars = (vinfo - itlist->vars);
1478 * build_tlist_index_other_vars --- build a restricted tlist index
1480 * This is like build_tlist_index, but we only index tlist entries that
1481 * are Vars belonging to some rel other than the one specified. We will set
1482 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
1483 * (so nothing other than Vars and PlaceHolderVars can be matched).
1485 static indexed_tlist *
1486 build_tlist_index_other_vars(List *tlist, Index ignore_rel)
1488 indexed_tlist *itlist;
1492 /* Create data structure with enough slots for all tlist entries */
1493 itlist = (indexed_tlist *)
1494 palloc(offsetof(indexed_tlist, vars) +
1495 list_length(tlist) * sizeof(tlist_vinfo));
1497 itlist->tlist = tlist;
1498 itlist->has_ph_vars = false;
1499 itlist->has_non_vars = false;
1501 /* Find the desired Vars and fill in the index array */
1502 vinfo = itlist->vars;
1505 TargetEntry *tle = (TargetEntry *) lfirst(l);
1507 if (tle->expr && IsA(tle->expr, Var))
1509 Var *var = (Var *) tle->expr;
1511 if (var->varno != ignore_rel)
1513 vinfo->varno = var->varno;
1514 vinfo->varattno = var->varattno;
1515 vinfo->resno = tle->resno;
1519 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1520 itlist->has_ph_vars = true;
1523 itlist->num_vars = (vinfo - itlist->vars);
1529 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
1531 * If a match is found, return a copy of the given Var with suitably
1532 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
1533 * Also ensure that varnoold is incremented by rtoffset.
1534 * If no match, return NULL.
1537 search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
1538 Index newvarno, int rtoffset)
1540 Index varno = var->varno;
1541 AttrNumber varattno = var->varattno;
1545 vinfo = itlist->vars;
1546 i = itlist->num_vars;
1549 if (vinfo->varno == varno && vinfo->varattno == varattno)
1552 Var *newvar = copyVar(var);
1554 newvar->varno = newvarno;
1555 newvar->varattno = vinfo->resno;
1556 if (newvar->varnoold > 0)
1557 newvar->varnoold += rtoffset;
1562 return NULL; /* no match */
1566 * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
1568 * If a match is found, return a Var constructed to reference the tlist item.
1569 * If no match, return NULL.
1571 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
1572 * itlist->has_non_vars
1575 search_indexed_tlist_for_non_var(Node *node,
1576 indexed_tlist *itlist, Index newvarno)
1580 tle = tlist_member(node, itlist->tlist);
1583 /* Found a matching subplan output expression */
1586 newvar = makeVarFromTargetEntry(newvarno, tle);
1587 newvar->varnoold = 0; /* wasn't ever a plain Var */
1588 newvar->varoattno = 0;
1591 return NULL; /* no match */
1595 * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
1596 * (which is assumed not to be just a Var)
1598 * If a match is found, return a Var constructed to reference the tlist item.
1599 * If no match, return NULL.
1601 * This is needed to ensure that we select the right subplan TLE in cases
1602 * where there are multiple textually-equal()-but-volatile sort expressions.
1603 * And it's also faster than search_indexed_tlist_for_non_var.
1606 search_indexed_tlist_for_sortgroupref(Node *node,
1608 indexed_tlist *itlist,
1613 foreach(lc, itlist->tlist)
1615 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1617 /* The equal() check should be redundant, but let's be paranoid */
1618 if (tle->ressortgroupref == sortgroupref &&
1619 equal(node, tle->expr))
1621 /* Found a matching subplan output expression */
1624 newvar = makeVarFromTargetEntry(newvarno, tle);
1625 newvar->varnoold = 0; /* wasn't ever a plain Var */
1626 newvar->varoattno = 0;
1630 return NULL; /* no match */
1635 * Create a new set of targetlist entries or join qual clauses by
1636 * changing the varno/varattno values of variables in the clauses
1637 * to reference target list values from the outer and inner join
1638 * relation target lists. Also perform opcode lookup and add
1639 * regclass OIDs to root->glob->relationOids.
1641 * This is used in two different scenarios: a normal join clause, where all
1642 * the Vars in the clause *must* be replaced by OUTER_VAR or INNER_VAR
1643 * references; and a RETURNING clause, which may contain both Vars of the
1644 * target relation and Vars of other relations. In the latter case we want
1645 * to replace the other-relation Vars by OUTER_VAR references, while leaving
1646 * target Vars alone.
1648 * For a normal join, acceptable_rel should be zero so that any failure to
1649 * match a Var will be reported as an error. For the RETURNING case, pass
1650 * inner_itlist = NULL and acceptable_rel = the ID of the target relation.
1652 * 'clauses' is the targetlist or list of join clauses
1653 * 'outer_itlist' is the indexed target list of the outer join relation
1654 * 'inner_itlist' is the indexed target list of the inner join relation,
1656 * 'acceptable_rel' is either zero or the rangetable index of a relation
1657 * whose Vars may appear in the clause without provoking an error
1658 * 'rtoffset': how much to increment varnoold by
1660 * Returns the new expression tree. The original clause structure is
1664 fix_join_expr(PlannerInfo *root,
1666 indexed_tlist *outer_itlist,
1667 indexed_tlist *inner_itlist,
1668 Index acceptable_rel,
1671 fix_join_expr_context context;
1673 context.root = root;
1674 context.outer_itlist = outer_itlist;
1675 context.inner_itlist = inner_itlist;
1676 context.acceptable_rel = acceptable_rel;
1677 context.rtoffset = rtoffset;
1678 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1682 fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1690 Var *var = (Var *) node;
1692 /* First look for the var in the input tlists */
1693 newvar = search_indexed_tlist_for_var(var,
1694 context->outer_itlist,
1698 return (Node *) newvar;
1699 if (context->inner_itlist)
1701 newvar = search_indexed_tlist_for_var(var,
1702 context->inner_itlist,
1706 return (Node *) newvar;
1709 /* If it's for acceptable_rel, adjust and return it */
1710 if (var->varno == context->acceptable_rel)
1713 var->varno += context->rtoffset;
1714 if (var->varnoold > 0)
1715 var->varnoold += context->rtoffset;
1716 return (Node *) var;
1719 /* No referent found for Var */
1720 elog(ERROR, "variable not found in subplan target lists");
1722 if (IsA(node, PlaceHolderVar))
1724 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1726 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1727 if (context->outer_itlist->has_ph_vars)
1729 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1730 context->outer_itlist,
1733 return (Node *) newvar;
1735 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
1737 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1738 context->inner_itlist,
1741 return (Node *) newvar;
1744 /* If not supplied by input plans, evaluate the contained expr */
1745 return fix_join_expr_mutator((Node *) phv->phexpr, context);
1747 /* Try matching more complex expressions too, if tlists have any */
1748 if (context->outer_itlist->has_non_vars)
1750 newvar = search_indexed_tlist_for_non_var(node,
1751 context->outer_itlist,
1754 return (Node *) newvar;
1756 if (context->inner_itlist && context->inner_itlist->has_non_vars)
1758 newvar = search_indexed_tlist_for_non_var(node,
1759 context->inner_itlist,
1762 return (Node *) newvar;
1764 fix_expr_common(context->root, node);
1765 return expression_tree_mutator(node,
1766 fix_join_expr_mutator,
1772 * Modifies an expression tree so that all Var nodes reference outputs
1773 * of a subplan. Also performs opcode lookup, and adds regclass OIDs to
1774 * root->glob->relationOids.
1776 * This is used to fix up target and qual expressions of non-join upper-level
1777 * plan nodes, as well as index-only scan nodes.
1779 * An error is raised if no matching var can be found in the subplan tlist
1780 * --- so this routine should only be applied to nodes whose subplans'
1781 * targetlists were generated via flatten_tlist() or some such method.
1783 * If itlist->has_non_vars is true, then we try to match whole subexpressions
1784 * against elements of the subplan tlist, so that we can avoid recomputing
1785 * expressions that were already computed by the subplan. (This is relatively
1786 * expensive, so we don't want to try it in the common case where the
1787 * subplan tlist is just a flattened list of Vars.)
1789 * 'node': the tree to be fixed (a target item or qual)
1790 * 'subplan_itlist': indexed target list for subplan (or index)
1791 * 'newvarno': varno to use for Vars referencing tlist elements
1792 * 'rtoffset': how much to increment varnoold by
1794 * The resulting tree is a copy of the original in which all Var nodes have
1795 * varno = newvarno, varattno = resno of corresponding targetlist element.
1796 * The original tree is not modified.
1799 fix_upper_expr(PlannerInfo *root,
1801 indexed_tlist *subplan_itlist,
1805 fix_upper_expr_context context;
1807 context.root = root;
1808 context.subplan_itlist = subplan_itlist;
1809 context.newvarno = newvarno;
1810 context.rtoffset = rtoffset;
1811 return fix_upper_expr_mutator(node, &context);
1815 fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
1823 Var *var = (Var *) node;
1825 newvar = search_indexed_tlist_for_var(var,
1826 context->subplan_itlist,
1830 elog(ERROR, "variable not found in subplan target list");
1831 return (Node *) newvar;
1833 if (IsA(node, PlaceHolderVar))
1835 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1837 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1838 if (context->subplan_itlist->has_ph_vars)
1840 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1841 context->subplan_itlist,
1844 return (Node *) newvar;
1846 /* If not supplied by input plan, evaluate the contained expr */
1847 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
1849 /* Try matching more complex expressions too, if tlist has any */
1850 if (context->subplan_itlist->has_non_vars)
1852 newvar = search_indexed_tlist_for_non_var(node,
1853 context->subplan_itlist,
1856 return (Node *) newvar;
1858 fix_expr_common(context->root, node);
1859 return expression_tree_mutator(node,
1860 fix_upper_expr_mutator,
1865 * set_returning_clause_references
1866 * Perform setrefs.c's work on a RETURNING targetlist
1868 * If the query involves more than just the result table, we have to
1869 * adjust any Vars that refer to other tables to reference junk tlist
1870 * entries in the top subplan's targetlist. Vars referencing the result
1871 * table should be left alone, however (the executor will evaluate them
1872 * using the actual heap tuple, after firing triggers if any). In the
1873 * adjusted RETURNING list, result-table Vars will have their original
1874 * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
1876 * We also must perform opcode lookup and add regclass OIDs to
1877 * root->glob->relationOids.
1879 * 'rlist': the RETURNING targetlist to be fixed
1880 * 'topplan': the top subplan node that will be just below the ModifyTable
1881 * node (note it's not yet passed through set_plan_refs)
1882 * 'resultRelation': RT index of the associated result relation
1883 * 'rtoffset': how much to increment varnos by
1885 * Note: the given 'root' is for the parent query level, not the 'topplan'.
1886 * This does not matter currently since we only access the dependency-item
1887 * lists in root->glob, but it would need some hacking if we wanted a root
1888 * that actually matches the subplan.
1890 * Note: resultRelation is not yet adjusted by rtoffset.
1893 set_returning_clause_references(PlannerInfo *root,
1896 Index resultRelation,
1899 indexed_tlist *itlist;
1902 * We can perform the desired Var fixup by abusing the fix_join_expr
1903 * machinery that formerly handled inner indexscan fixup. We search the
1904 * top plan's targetlist for Vars of non-result relations, and use
1905 * fix_join_expr to convert RETURNING Vars into references to those tlist
1906 * entries, while leaving result-rel Vars as-is.
1908 * PlaceHolderVars will also be sought in the targetlist, but no
1909 * more-complex expressions will be. Note that it is not possible for a
1910 * PlaceHolderVar to refer to the result relation, since the result is
1911 * never below an outer join. If that case could happen, we'd have to be
1912 * prepared to pick apart the PlaceHolderVar and evaluate its contained
1913 * expression instead.
1915 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
1917 rlist = fix_join_expr(root,
1929 /*****************************************************************************
1930 * OPERATOR REGPROC LOOKUP
1931 *****************************************************************************/
1935 * Calculate opfuncid field from opno for each OpExpr node in given tree.
1936 * The given tree can be anything expression_tree_walker handles.
1938 * The argument is modified in-place. (This is OK since we'd want the
1939 * same change for any node, even if it gets visited more than once due to
1940 * shared structure.)
1943 fix_opfuncids(Node *node)
1945 /* This tree walk requires no special setup, so away we go... */
1946 fix_opfuncids_walker(node, NULL);
1950 fix_opfuncids_walker(Node *node, void *context)
1954 if (IsA(node, OpExpr))
1955 set_opfuncid((OpExpr *) node);
1956 else if (IsA(node, DistinctExpr))
1957 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1958 else if (IsA(node, NullIfExpr))
1959 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1960 else if (IsA(node, ScalarArrayOpExpr))
1961 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1962 return expression_tree_walker(node, fix_opfuncids_walker, context);
1967 * Set the opfuncid (procedure OID) in an OpExpr node,
1968 * if it hasn't been set already.
1970 * Because of struct equivalence, this can also be used for
1971 * DistinctExpr and NullIfExpr nodes.
1974 set_opfuncid(OpExpr *opexpr)
1976 if (opexpr->opfuncid == InvalidOid)
1977 opexpr->opfuncid = get_opcode(opexpr->opno);
1982 * As above, for ScalarArrayOpExpr nodes.
1985 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1987 if (opexpr->opfuncid == InvalidOid)
1988 opexpr->opfuncid = get_opcode(opexpr->opno);
1991 /*****************************************************************************
1992 * QUERY DEPENDENCY MANAGEMENT
1993 *****************************************************************************/
1996 * record_plan_function_dependency
1997 * Mark the current plan as depending on a particular function.
1999 * This is exported so that the function-inlining code can record a
2000 * dependency on a function that it's removed from the plan tree.
2003 record_plan_function_dependency(PlannerInfo *root, Oid funcid)
2006 * For performance reasons, we don't bother to track built-in functions;
2007 * we just assume they'll never change (or at least not in ways that'd
2008 * invalidate plans using them). For this purpose we can consider a
2009 * built-in function to be one with OID less than FirstBootstrapObjectId.
2010 * Note that the OID generator guarantees never to generate such an OID
2011 * after startup, even at OID wraparound.
2013 if (funcid >= (Oid) FirstBootstrapObjectId)
2015 PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2018 * It would work to use any syscache on pg_proc, but the easiest is
2019 * PROCOID since we already have the function's OID at hand. Note
2020 * that plancache.c knows we use PROCOID.
2022 inval_item->cacheId = PROCOID;
2023 inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
2024 ObjectIdGetDatum(funcid));
2026 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2031 * extract_query_dependencies
2032 * Given a not-yet-planned query or queries (i.e. a Query node or list
2033 * of Query nodes), extract dependencies just as set_plan_references
2036 * This is needed by plancache.c to handle invalidation of cached unplanned
2040 extract_query_dependencies(Node *query,
2041 List **relationOids,
2047 /* Make up dummy planner state so we can use this module's machinery */
2048 MemSet(&glob, 0, sizeof(glob));
2049 glob.type = T_PlannerGlobal;
2050 glob.relationOids = NIL;
2051 glob.invalItems = NIL;
2053 MemSet(&root, 0, sizeof(root));
2054 root.type = T_PlannerInfo;
2057 (void) extract_query_dependencies_walker(query, &root);
2059 *relationOids = glob.relationOids;
2060 *invalItems = glob.invalItems;
2064 extract_query_dependencies_walker(Node *node, PlannerInfo *context)
2068 Assert(!IsA(node, PlaceHolderVar));
2069 /* Extract function dependencies and check for regclass Consts */
2070 fix_expr_common(context, node);
2071 if (IsA(node, Query))
2073 Query *query = (Query *) node;
2076 if (query->commandType == CMD_UTILITY)
2079 * Ignore utility statements, except those (such as EXPLAIN) that
2080 * contain a parsed-but-not-planned query.
2082 query = UtilityContainsQuery(query->utilityStmt);
2087 /* Collect relation OIDs in this Query's rtable */
2088 foreach(lc, query->rtable)
2090 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2092 if (rte->rtekind == RTE_RELATION)
2093 context->glob->relationOids =
2094 lappend_oid(context->glob->relationOids, rte->relid);
2097 /* And recurse into the query's subexpressions */
2098 return query_tree_walker(query, extract_query_dependencies_walker,
2099 (void *) context, 0);
2101 return expression_tree_walker(node, extract_query_dependencies_walker,