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-2015, 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 tlist_vinfo vars[FLEXIBLE_ARRAY_MEMBER]; /* has num_vars entries */
51 } fix_scan_expr_context;
56 indexed_tlist *outer_itlist;
57 indexed_tlist *inner_itlist;
60 } fix_join_expr_context;
65 indexed_tlist *subplan_itlist;
68 } fix_upper_expr_context;
71 * Check if a Const node is a regclass value. We accept plain OID too,
72 * since a regclass Const will get folded to that type if it's an argument
73 * to oideq or similar operators. (This might result in some extraneous
74 * values in a plan's list of relation dependencies, but the worst result
75 * would be occasional useless replans.)
77 #define ISREGCLASSCONST(con) \
78 (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
81 #define fix_scan_list(root, lst, rtoffset) \
82 ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset))
84 static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing);
85 static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte);
86 static bool flatten_rtes_walker(Node *node, PlannerGlobal *glob);
87 static void add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte);
88 static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
89 static Plan *set_indexonlyscan_references(PlannerInfo *root,
92 static Plan *set_subqueryscan_references(PlannerInfo *root,
95 static bool trivial_subqueryscan(SubqueryScan *plan);
96 static void set_foreignscan_references(PlannerInfo *root,
99 static void set_customscan_references(PlannerInfo *root,
102 static Node *fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset);
103 static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
104 static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
105 static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
106 static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
107 static void set_dummy_tlist_references(Plan *plan, int rtoffset);
108 static indexed_tlist *build_tlist_index(List *tlist);
109 static Var *search_indexed_tlist_for_var(Var *var,
110 indexed_tlist *itlist,
113 static Var *search_indexed_tlist_for_non_var(Node *node,
114 indexed_tlist *itlist,
116 static Var *search_indexed_tlist_for_sortgroupref(Node *node,
118 indexed_tlist *itlist,
120 static List *fix_join_expr(PlannerInfo *root,
122 indexed_tlist *outer_itlist,
123 indexed_tlist *inner_itlist,
124 Index acceptable_rel, int rtoffset);
125 static Node *fix_join_expr_mutator(Node *node,
126 fix_join_expr_context *context);
127 static Node *fix_upper_expr(PlannerInfo *root,
129 indexed_tlist *subplan_itlist,
132 static Node *fix_upper_expr_mutator(Node *node,
133 fix_upper_expr_context *context);
134 static List *set_returning_clause_references(PlannerInfo *root,
137 Index resultRelation,
139 static bool fix_opfuncids_walker(Node *node, void *context);
140 static bool extract_query_dependencies_walker(Node *node,
141 PlannerInfo *context);
144 /*****************************************************************************
148 *****************************************************************************/
151 * set_plan_references
153 * This is the final processing pass of the planner/optimizer. The plan
154 * tree is complete; we just have to adjust some representational details
155 * for the convenience of the executor:
157 * 1. We flatten the various subquery rangetables into a single list, and
158 * zero out RangeTblEntry fields that are not useful to the executor.
160 * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
162 * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
165 * 4. PARAM_MULTIEXPR Params are replaced by regular PARAM_EXEC Params,
166 * now that we have finished planning all MULTIEXPR subplans.
168 * 5. We compute regproc OIDs for operators (ie, we look up the function
169 * that implements each op).
171 * 6. We create lists of specific objects that the plan depends on.
172 * This will be used by plancache.c to drive invalidation of cached plans.
173 * Relation dependencies are represented by OIDs, and everything else by
174 * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
175 * Currently, relations and user-defined functions are the only types of
176 * objects that are explicitly tracked this way.
178 * We also perform one final optimization step, which is to delete
179 * SubqueryScan plan nodes that aren't doing anything useful (ie, have
180 * no qual and a no-op targetlist). The reason for doing this last is that
181 * it can't readily be done before set_plan_references, because it would
182 * break set_upper_references: the Vars in the subquery's top tlist
183 * wouldn't match up with the Vars in the outer plan tree. The SubqueryScan
184 * serves a necessary function as a buffer between outer query and subquery
185 * variable numbering ... but after we've flattened the rangetable this is
186 * no longer a problem, since then there's only one rtindex namespace.
188 * set_plan_references recursively traverses the whole plan tree.
190 * The return value is normally the same Plan node passed in, but can be
191 * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
193 * The flattened rangetable entries are appended to root->glob->finalrtable.
194 * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
195 * RT indexes of ModifyTable result relations to root->glob->resultRelations.
196 * Plan dependencies are appended to root->glob->relationOids (for relations)
197 * and root->glob->invalItems (for everything else).
199 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
200 * to process targetlist and qual expressions. We can assume that the Plan
201 * nodes were just built by the planner and are not multiply referenced, but
202 * it's not so safe to assume that for expression tree nodes.
205 set_plan_references(PlannerInfo *root, Plan *plan)
207 PlannerGlobal *glob = root->glob;
208 int rtoffset = list_length(glob->finalrtable);
212 * Add all the query's RTEs to the flattened rangetable. The live ones
213 * will have their rangetable indexes increased by rtoffset. (Additional
214 * RTEs, not referenced by the Plan tree, might get added after those.)
216 add_rtes_to_flat_rtable(root, false);
219 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
221 foreach(lc, root->rowMarks)
223 PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
226 Assert(IsA(rc, PlanRowMark));
228 /* flat copy is enough since all fields are scalars */
229 newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
230 memcpy(newrc, rc, sizeof(PlanRowMark));
232 /* adjust indexes ... but *not* the rowmarkId */
233 newrc->rti += rtoffset;
234 newrc->prti += rtoffset;
236 glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
239 /* Now fix the Plan tree */
240 return set_plan_refs(root, plan, rtoffset);
244 * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
246 * This can recurse into subquery plans; "recursing" is true if so.
249 add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
251 PlannerGlobal *glob = root->glob;
256 * Add the query's own RTEs to the flattened rangetable.
258 * At top level, we must add all RTEs so that their indexes in the
259 * flattened rangetable match up with their original indexes. When
260 * recursing, we only care about extracting relation RTEs.
262 foreach(lc, root->parse->rtable)
264 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
266 if (!recursing || rte->rtekind == RTE_RELATION)
267 add_rte_to_flat_rtable(glob, rte);
271 * If there are any dead subqueries, they are not referenced in the Plan
272 * tree, so we must add RTEs contained in them to the flattened rtable
273 * separately. (If we failed to do this, the executor would not perform
274 * expected permission checks for tables mentioned in such subqueries.)
276 * Note: this pass over the rangetable can't be combined with the previous
277 * one, because that would mess up the numbering of the live RTEs in the
278 * flattened rangetable.
281 foreach(lc, root->parse->rtable)
283 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
286 * We should ignore inheritance-parent RTEs: their contents have been
287 * pulled up into our rangetable already. Also ignore any subquery
288 * RTEs without matching RelOptInfos, as they likewise have been
291 if (rte->rtekind == RTE_SUBQUERY && !rte->inh &&
292 rti < root->simple_rel_array_size)
294 RelOptInfo *rel = root->simple_rel_array[rti];
298 Assert(rel->relid == rti); /* sanity check on array */
301 * The subquery might never have been planned at all, if it
302 * was excluded on the basis of self-contradictory constraints
303 * in our query level. In this case apply
304 * flatten_unplanned_rtes.
306 * If it was planned but the plan is dummy, we assume that it
307 * has been omitted from our plan tree (see
308 * set_subquery_pathlist), and recurse to pull up its RTEs.
310 * Otherwise, it should be represented by a SubqueryScan node
311 * somewhere in our plan tree, and we'll pull up its RTEs when
312 * we process that plan node.
314 * However, if we're recursing, then we should pull up RTEs
315 * whether the subplan is dummy or not, because we've found
316 * that some upper query level is treating this one as dummy,
317 * and so we won't scan this level's plan tree at all.
319 if (rel->subplan == NULL)
320 flatten_unplanned_rtes(glob, rte);
321 else if (recursing || is_dummy_plan(rel->subplan))
323 Assert(rel->subroot != NULL);
324 add_rtes_to_flat_rtable(rel->subroot, true);
333 * Extract RangeTblEntries from a subquery that was never planned at all
336 flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
338 /* Use query_tree_walker to find all RTEs in the parse tree */
339 (void) query_tree_walker(rte->subquery,
346 flatten_rtes_walker(Node *node, PlannerGlobal *glob)
350 if (IsA(node, RangeTblEntry))
352 RangeTblEntry *rte = (RangeTblEntry *) node;
354 /* As above, we need only save relation RTEs */
355 if (rte->rtekind == RTE_RELATION)
356 add_rte_to_flat_rtable(glob, rte);
359 if (IsA(node, Query))
361 /* Recurse into subselects */
362 return query_tree_walker((Query *) node,
367 return expression_tree_walker(node, flatten_rtes_walker,
372 * Add (a copy of) the given RTE to the final rangetable
374 * In the flat rangetable, we zero out substructure pointers that are not
375 * needed by the executor; this reduces the storage space and copying cost
376 * for cached plans. We keep only the alias and eref Alias fields, which are
377 * needed by EXPLAIN, and the selectedCols, insertedCols and updatedCols
378 * bitmaps, which are needed for executor-startup permissions checking and for
379 * trigger event checking.
382 add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte)
384 RangeTblEntry *newrte;
386 /* flat copy to duplicate all the scalar fields */
387 newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
388 memcpy(newrte, rte, sizeof(RangeTblEntry));
390 /* zap unneeded sub-structure */
391 newrte->subquery = NULL;
392 newrte->joinaliasvars = NIL;
393 newrte->functions = NIL;
394 newrte->values_lists = NIL;
395 newrte->values_collations = NIL;
396 newrte->ctecoltypes = NIL;
397 newrte->ctecoltypmods = NIL;
398 newrte->ctecolcollations = NIL;
400 glob->finalrtable = lappend(glob->finalrtable, newrte);
403 * Check for RT index overflow; it's very unlikely, but if it did happen,
404 * the executor would get confused by varnos that match the special varno
407 if (IS_SPECIAL_VARNO(list_length(glob->finalrtable)))
409 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
410 errmsg("too many range table entries")));
413 * If it's a plain relation RTE, add the table to relationOids.
415 * We do this even though the RTE might be unreferenced in the plan tree;
416 * this would correspond to cases such as views that were expanded, child
417 * tables that were eliminated by constraint exclusion, etc. Schema
418 * invalidation on such a rel must still force rebuilding of the plan.
420 * Note we don't bother to avoid making duplicate list entries. We could,
421 * but it would probably cost more cycles than it would save.
423 if (newrte->rtekind == RTE_RELATION)
424 glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
428 * set_plan_refs: recurse through the Plan nodes of a single subquery level
431 set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
439 * Plan-type-specific fixes
441 switch (nodeTag(plan))
445 SeqScan *splan = (SeqScan *) plan;
447 splan->scanrelid += rtoffset;
448 splan->plan.targetlist =
449 fix_scan_list(root, splan->plan.targetlist, rtoffset);
451 fix_scan_list(root, splan->plan.qual, rtoffset);
456 SampleScan *splan = (SampleScan *) plan;
458 splan->scanrelid += rtoffset;
459 splan->plan.targetlist =
460 fix_scan_list(root, splan->plan.targetlist, rtoffset);
462 fix_scan_list(root, splan->plan.qual, rtoffset);
467 IndexScan *splan = (IndexScan *) plan;
469 splan->scan.scanrelid += rtoffset;
470 splan->scan.plan.targetlist =
471 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
472 splan->scan.plan.qual =
473 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
475 fix_scan_list(root, splan->indexqual, rtoffset);
476 splan->indexqualorig =
477 fix_scan_list(root, splan->indexqualorig, rtoffset);
478 splan->indexorderby =
479 fix_scan_list(root, splan->indexorderby, rtoffset);
480 splan->indexorderbyorig =
481 fix_scan_list(root, splan->indexorderbyorig, rtoffset);
484 case T_IndexOnlyScan:
486 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
488 return set_indexonlyscan_references(root, splan, rtoffset);
491 case T_BitmapIndexScan:
493 BitmapIndexScan *splan = (BitmapIndexScan *) plan;
495 splan->scan.scanrelid += rtoffset;
496 /* no need to fix targetlist and qual */
497 Assert(splan->scan.plan.targetlist == NIL);
498 Assert(splan->scan.plan.qual == NIL);
500 fix_scan_list(root, splan->indexqual, rtoffset);
501 splan->indexqualorig =
502 fix_scan_list(root, splan->indexqualorig, rtoffset);
505 case T_BitmapHeapScan:
507 BitmapHeapScan *splan = (BitmapHeapScan *) plan;
509 splan->scan.scanrelid += rtoffset;
510 splan->scan.plan.targetlist =
511 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
512 splan->scan.plan.qual =
513 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
514 splan->bitmapqualorig =
515 fix_scan_list(root, splan->bitmapqualorig, rtoffset);
520 TidScan *splan = (TidScan *) plan;
522 splan->scan.scanrelid += rtoffset;
523 splan->scan.plan.targetlist =
524 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
525 splan->scan.plan.qual =
526 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
528 fix_scan_list(root, splan->tidquals, rtoffset);
532 /* Needs special treatment, see comments below */
533 return set_subqueryscan_references(root,
534 (SubqueryScan *) plan,
538 FunctionScan *splan = (FunctionScan *) plan;
540 splan->scan.scanrelid += rtoffset;
541 splan->scan.plan.targetlist =
542 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
543 splan->scan.plan.qual =
544 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
546 fix_scan_list(root, splan->functions, rtoffset);
551 ValuesScan *splan = (ValuesScan *) plan;
553 splan->scan.scanrelid += rtoffset;
554 splan->scan.plan.targetlist =
555 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
556 splan->scan.plan.qual =
557 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
558 splan->values_lists =
559 fix_scan_list(root, splan->values_lists, rtoffset);
564 CteScan *splan = (CteScan *) plan;
566 splan->scan.scanrelid += rtoffset;
567 splan->scan.plan.targetlist =
568 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
569 splan->scan.plan.qual =
570 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
573 case T_WorkTableScan:
575 WorkTableScan *splan = (WorkTableScan *) plan;
577 splan->scan.scanrelid += rtoffset;
578 splan->scan.plan.targetlist =
579 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
580 splan->scan.plan.qual =
581 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
585 set_foreignscan_references(root, (ForeignScan *) plan, rtoffset);
588 set_customscan_references(root, (CustomScan *) plan, rtoffset);
594 set_join_references(root, (Join *) plan, rtoffset);
604 * These plan types don't actually bother to evaluate their
605 * targetlists, because they just return their unmodified input
606 * tuples. Even though the targetlist won't be used by the
607 * executor, we fix it up for possible use by EXPLAIN (not to
608 * mention ease of debugging --- wrong varnos are very confusing).
610 set_dummy_tlist_references(plan, rtoffset);
613 * Since these plan types don't check quals either, we should not
614 * find any qual expression attached to them.
616 Assert(plan->qual == NIL);
620 LockRows *splan = (LockRows *) plan;
623 * Like the plan types above, LockRows doesn't evaluate its
624 * tlist or quals. But we have to fix up the RT indexes in
627 set_dummy_tlist_references(plan, rtoffset);
628 Assert(splan->plan.qual == NIL);
630 foreach(l, splan->rowMarks)
632 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
635 rc->prti += rtoffset;
641 Limit *splan = (Limit *) plan;
644 * Like the plan types above, Limit doesn't evaluate its tlist
645 * or quals. It does have live expressions for limit/offset,
646 * however; and those cannot contain subplan variable refs, so
647 * fix_scan_expr works for them.
649 set_dummy_tlist_references(plan, rtoffset);
650 Assert(splan->plan.qual == NIL);
653 fix_scan_expr(root, splan->limitOffset, rtoffset);
655 fix_scan_expr(root, splan->limitCount, rtoffset);
660 set_upper_references(root, plan, rtoffset);
664 WindowAgg *wplan = (WindowAgg *) plan;
666 set_upper_references(root, plan, rtoffset);
669 * Like Limit node limit/offset expressions, WindowAgg has
670 * frame offset expressions, which cannot contain subplan
671 * variable refs, so fix_scan_expr works for them.
674 fix_scan_expr(root, wplan->startOffset, rtoffset);
676 fix_scan_expr(root, wplan->endOffset, rtoffset);
681 Result *splan = (Result *) plan;
684 * Result may or may not have a subplan; if not, it's more
685 * like a scan node than an upper node.
687 if (splan->plan.lefttree != NULL)
688 set_upper_references(root, plan, rtoffset);
691 splan->plan.targetlist =
692 fix_scan_list(root, splan->plan.targetlist, rtoffset);
694 fix_scan_list(root, splan->plan.qual, rtoffset);
696 /* resconstantqual can't contain any subplan variable refs */
697 splan->resconstantqual =
698 fix_scan_expr(root, splan->resconstantqual, rtoffset);
703 ModifyTable *splan = (ModifyTable *) plan;
705 Assert(splan->plan.targetlist == NIL);
706 Assert(splan->plan.qual == NIL);
708 splan->withCheckOptionLists =
709 fix_scan_list(root, splan->withCheckOptionLists, rtoffset);
711 if (splan->returningLists)
719 * Pass each per-subplan returningList through
720 * set_returning_clause_references().
722 Assert(list_length(splan->returningLists) == list_length(splan->resultRelations));
723 Assert(list_length(splan->returningLists) == list_length(splan->plans));
724 forthree(lcrl, splan->returningLists,
725 lcrr, splan->resultRelations,
728 List *rlist = (List *) lfirst(lcrl);
729 Index resultrel = lfirst_int(lcrr);
730 Plan *subplan = (Plan *) lfirst(lcp);
732 rlist = set_returning_clause_references(root,
737 newRL = lappend(newRL, rlist);
739 splan->returningLists = newRL;
742 * Set up the visible plan targetlist as being the same as
743 * the first RETURNING list. This is for the use of
744 * EXPLAIN; the executor won't pay any attention to the
745 * targetlist. We postpone this step until here so that
746 * we don't have to do set_returning_clause_references()
747 * twice on identical targetlists.
749 splan->plan.targetlist = copyObject(linitial(newRL));
753 * We treat ModifyTable with ON CONFLICT as a form of 'pseudo
754 * join', where the inner side is the EXCLUDED tuple.
755 * Therefore use fix_join_expr to setup the relevant variables
756 * to INNER_VAR. We explicitly don't create any OUTER_VARs as
757 * those are already used by RETURNING and it seems better to
758 * be non-conflicting.
760 if (splan->onConflictSet)
762 indexed_tlist *itlist;
764 itlist = build_tlist_index(splan->exclRelTlist);
766 splan->onConflictSet =
767 fix_join_expr(root, splan->onConflictSet,
769 linitial_int(splan->resultRelations),
772 splan->onConflictWhere = (Node *)
773 fix_join_expr(root, (List *) splan->onConflictWhere,
775 linitial_int(splan->resultRelations),
778 splan->exclRelTlist =
779 fix_scan_list(root, splan->exclRelTlist, rtoffset);
782 splan->nominalRelation += rtoffset;
783 splan->exclRelRTI += rtoffset;
785 foreach(l, splan->resultRelations)
787 lfirst_int(l) += rtoffset;
789 foreach(l, splan->rowMarks)
791 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
794 rc->prti += rtoffset;
796 foreach(l, splan->plans)
798 lfirst(l) = set_plan_refs(root,
804 * Append this ModifyTable node's final result relation RT
805 * index(es) to the global list for the plan, and set its
806 * resultRelIndex to reflect their starting position in the
809 splan->resultRelIndex = list_length(root->glob->resultRelations);
810 root->glob->resultRelations =
811 list_concat(root->glob->resultRelations,
812 list_copy(splan->resultRelations));
817 Append *splan = (Append *) plan;
820 * Append, like Sort et al, doesn't actually evaluate its
821 * targetlist or check quals.
823 set_dummy_tlist_references(plan, rtoffset);
824 Assert(splan->plan.qual == NIL);
825 foreach(l, splan->appendplans)
827 lfirst(l) = set_plan_refs(root,
835 MergeAppend *splan = (MergeAppend *) plan;
838 * MergeAppend, like Sort et al, doesn't actually evaluate its
839 * targetlist or check quals.
841 set_dummy_tlist_references(plan, rtoffset);
842 Assert(splan->plan.qual == NIL);
843 foreach(l, splan->mergeplans)
845 lfirst(l) = set_plan_refs(root,
851 case T_RecursiveUnion:
852 /* This doesn't evaluate targetlist or check quals either */
853 set_dummy_tlist_references(plan, rtoffset);
854 Assert(plan->qual == NIL);
858 BitmapAnd *splan = (BitmapAnd *) plan;
860 /* BitmapAnd works like Append, but has no tlist */
861 Assert(splan->plan.targetlist == NIL);
862 Assert(splan->plan.qual == NIL);
863 foreach(l, splan->bitmapplans)
865 lfirst(l) = set_plan_refs(root,
873 BitmapOr *splan = (BitmapOr *) plan;
875 /* BitmapOr works like Append, but has no tlist */
876 Assert(splan->plan.targetlist == NIL);
877 Assert(splan->plan.qual == NIL);
878 foreach(l, splan->bitmapplans)
880 lfirst(l) = set_plan_refs(root,
887 elog(ERROR, "unrecognized node type: %d",
888 (int) nodeTag(plan));
893 * Now recurse into child plans, if any
895 * NOTE: it is essential that we recurse into child plans AFTER we set
896 * subplan references in this plan's tlist and quals. If we did the
897 * reference-adjustments bottom-up, then we would fail to match this
898 * plan's var nodes against the already-modified nodes of the children.
900 plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
901 plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
907 * set_indexonlyscan_references
908 * Do set_plan_references processing on an IndexOnlyScan
910 * This is unlike the handling of a plain IndexScan because we have to
911 * convert Vars referencing the heap into Vars referencing the index.
912 * We can use the fix_upper_expr machinery for that, by working from a
913 * targetlist describing the index columns.
916 set_indexonlyscan_references(PlannerInfo *root,
920 indexed_tlist *index_itlist;
922 index_itlist = build_tlist_index(plan->indextlist);
924 plan->scan.scanrelid += rtoffset;
925 plan->scan.plan.targetlist = (List *)
927 (Node *) plan->scan.plan.targetlist,
931 plan->scan.plan.qual = (List *)
933 (Node *) plan->scan.plan.qual,
937 /* indexqual is already transformed to reference index columns */
938 plan->indexqual = fix_scan_list(root, plan->indexqual, rtoffset);
939 /* indexorderby is already transformed to reference index columns */
940 plan->indexorderby = fix_scan_list(root, plan->indexorderby, rtoffset);
941 /* indextlist must NOT be transformed to reference index columns */
942 plan->indextlist = fix_scan_list(root, plan->indextlist, rtoffset);
946 return (Plan *) plan;
950 * set_subqueryscan_references
951 * Do set_plan_references processing on a SubqueryScan
953 * We try to strip out the SubqueryScan entirely; if we can't, we have
954 * to do the normal processing on it.
957 set_subqueryscan_references(PlannerInfo *root,
964 /* Need to look up the subquery's RelOptInfo, since we need its subroot */
965 rel = find_base_rel(root, plan->scan.scanrelid);
966 Assert(rel->subplan == plan->subplan);
968 /* Recursively process the subplan */
969 plan->subplan = set_plan_references(rel->subroot, plan->subplan);
971 if (trivial_subqueryscan(plan))
974 * We can omit the SubqueryScan node and just pull up the subplan.
979 result = plan->subplan;
981 /* We have to be sure we don't lose any initplans */
982 result->initPlan = list_concat(plan->scan.plan.initPlan,
986 * We also have to transfer the SubqueryScan's result-column names
987 * into the subplan, else columns sent to client will be improperly
988 * labeled if this is the topmost plan level. Copy the "source
989 * column" information too.
991 forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
993 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
994 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
996 ctle->resname = ptle->resname;
997 ctle->resorigtbl = ptle->resorigtbl;
998 ctle->resorigcol = ptle->resorigcol;
1004 * Keep the SubqueryScan node. We have to do the processing that
1005 * set_plan_references would otherwise have done on it. Notice we do
1006 * not do set_upper_references() here, because a SubqueryScan will
1007 * always have been created with correct references to its subplan's
1008 * outputs to begin with.
1010 plan->scan.scanrelid += rtoffset;
1011 plan->scan.plan.targetlist =
1012 fix_scan_list(root, plan->scan.plan.targetlist, rtoffset);
1013 plan->scan.plan.qual =
1014 fix_scan_list(root, plan->scan.plan.qual, rtoffset);
1016 result = (Plan *) plan;
1023 * trivial_subqueryscan
1024 * Detect whether a SubqueryScan can be deleted from the plan tree.
1026 * We can delete it if it has no qual to check and the targetlist just
1027 * regurgitates the output of the child plan.
1030 trivial_subqueryscan(SubqueryScan *plan)
1036 if (plan->scan.plan.qual != NIL)
1039 if (list_length(plan->scan.plan.targetlist) !=
1040 list_length(plan->subplan->targetlist))
1041 return false; /* tlists not same length */
1044 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
1046 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
1047 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
1049 if (ptle->resjunk != ctle->resjunk)
1050 return false; /* tlist doesn't match junk status */
1053 * We accept either a Var referencing the corresponding element of the
1054 * subplan tlist, or a Const equaling the subplan element. See
1055 * generate_setop_tlist() for motivation.
1057 if (ptle->expr && IsA(ptle->expr, Var))
1059 Var *var = (Var *) ptle->expr;
1061 Assert(var->varno == plan->scan.scanrelid);
1062 Assert(var->varlevelsup == 0);
1063 if (var->varattno != attrno)
1064 return false; /* out of order */
1066 else if (ptle->expr && IsA(ptle->expr, Const))
1068 if (!equal(ptle->expr, ctle->expr))
1081 * set_foreignscan_references
1082 * Do set_plan_references processing on a ForeignScan
1085 set_foreignscan_references(PlannerInfo *root,
1089 /* Adjust scanrelid if it's valid */
1090 if (fscan->scan.scanrelid > 0)
1091 fscan->scan.scanrelid += rtoffset;
1093 if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1095 /* Adjust tlist, qual, fdw_exprs to reference custom scan tuple */
1096 indexed_tlist *itlist = build_tlist_index(fscan->fdw_scan_tlist);
1098 fscan->scan.plan.targetlist = (List *)
1099 fix_upper_expr(root,
1100 (Node *) fscan->scan.plan.targetlist,
1104 fscan->scan.plan.qual = (List *)
1105 fix_upper_expr(root,
1106 (Node *) fscan->scan.plan.qual,
1110 fscan->fdw_exprs = (List *)
1111 fix_upper_expr(root,
1112 (Node *) fscan->fdw_exprs,
1117 /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1118 fscan->fdw_scan_tlist =
1119 fix_scan_list(root, fscan->fdw_scan_tlist, rtoffset);
1123 /* Adjust tlist, qual, fdw_exprs in the standard way */
1124 fscan->scan.plan.targetlist =
1125 fix_scan_list(root, fscan->scan.plan.targetlist, rtoffset);
1126 fscan->scan.plan.qual =
1127 fix_scan_list(root, fscan->scan.plan.qual, rtoffset);
1129 fix_scan_list(root, fscan->fdw_exprs, rtoffset);
1132 /* Adjust fs_relids if needed */
1135 Bitmapset *tempset = NULL;
1138 while ((x = bms_next_member(fscan->fs_relids, x)) >= 0)
1139 tempset = bms_add_member(tempset, x + rtoffset);
1140 fscan->fs_relids = tempset;
1145 * set_customscan_references
1146 * Do set_plan_references processing on a CustomScan
1149 set_customscan_references(PlannerInfo *root,
1153 /* Adjust scanrelid if it's valid */
1154 if (cscan->scan.scanrelid > 0)
1155 cscan->scan.scanrelid += rtoffset;
1157 if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1159 /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1160 indexed_tlist *itlist = build_tlist_index(cscan->custom_scan_tlist);
1162 cscan->scan.plan.targetlist = (List *)
1163 fix_upper_expr(root,
1164 (Node *) cscan->scan.plan.targetlist,
1168 cscan->scan.plan.qual = (List *)
1169 fix_upper_expr(root,
1170 (Node *) cscan->scan.plan.qual,
1174 cscan->custom_exprs = (List *)
1175 fix_upper_expr(root,
1176 (Node *) cscan->custom_exprs,
1181 /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1182 cscan->custom_scan_tlist =
1183 fix_scan_list(root, cscan->custom_scan_tlist, rtoffset);
1187 /* Adjust tlist, qual, custom_exprs in the standard way */
1188 cscan->scan.plan.targetlist =
1189 fix_scan_list(root, cscan->scan.plan.targetlist, rtoffset);
1190 cscan->scan.plan.qual =
1191 fix_scan_list(root, cscan->scan.plan.qual, rtoffset);
1192 cscan->custom_exprs =
1193 fix_scan_list(root, cscan->custom_exprs, rtoffset);
1196 /* Adjust custom_relids if needed */
1199 Bitmapset *tempset = NULL;
1202 while ((x = bms_next_member(cscan->custom_relids, x)) >= 0)
1203 tempset = bms_add_member(tempset, x + rtoffset);
1204 cscan->custom_relids = tempset;
1212 * fix_scan_expr and friends do this enough times that it's worth having
1213 * a bespoke routine instead of using the generic copyObject() function.
1218 Var *newvar = (Var *) palloc(sizeof(Var));
1226 * Do generic set_plan_references processing on an expression node
1228 * This is code that is common to all variants of expression-fixing.
1229 * We must look up operator opcode info for OpExpr and related nodes,
1230 * add OIDs from regclass Const nodes into root->glob->relationOids, and
1231 * add catalog TIDs for user-defined functions into root->glob->invalItems.
1233 * We assume it's okay to update opcode info in-place. So this could possibly
1234 * scribble on the planner's input data structures, but it's OK.
1237 fix_expr_common(PlannerInfo *root, Node *node)
1239 /* We assume callers won't call us on a NULL pointer */
1240 if (IsA(node, Aggref))
1242 record_plan_function_dependency(root,
1243 ((Aggref *) node)->aggfnoid);
1245 else if (IsA(node, WindowFunc))
1247 record_plan_function_dependency(root,
1248 ((WindowFunc *) node)->winfnoid);
1250 else if (IsA(node, FuncExpr))
1252 record_plan_function_dependency(root,
1253 ((FuncExpr *) node)->funcid);
1255 else if (IsA(node, OpExpr))
1257 set_opfuncid((OpExpr *) node);
1258 record_plan_function_dependency(root,
1259 ((OpExpr *) node)->opfuncid);
1261 else if (IsA(node, DistinctExpr))
1263 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1264 record_plan_function_dependency(root,
1265 ((DistinctExpr *) node)->opfuncid);
1267 else if (IsA(node, NullIfExpr))
1269 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1270 record_plan_function_dependency(root,
1271 ((NullIfExpr *) node)->opfuncid);
1273 else if (IsA(node, ScalarArrayOpExpr))
1275 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1276 record_plan_function_dependency(root,
1277 ((ScalarArrayOpExpr *) node)->opfuncid);
1279 else if (IsA(node, ArrayCoerceExpr))
1281 if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
1282 record_plan_function_dependency(root,
1283 ((ArrayCoerceExpr *) node)->elemfuncid);
1285 else if (IsA(node, Const))
1287 Const *con = (Const *) node;
1289 /* Check for regclass reference */
1290 if (ISREGCLASSCONST(con))
1291 root->glob->relationOids =
1292 lappend_oid(root->glob->relationOids,
1293 DatumGetObjectId(con->constvalue));
1299 * Do set_plan_references processing on a Param
1301 * If it's a PARAM_MULTIEXPR, replace it with the appropriate Param from
1302 * root->multiexpr_params; otherwise no change is needed.
1303 * Just for paranoia's sake, we make a copy of the node in either case.
1306 fix_param_node(PlannerInfo *root, Param *p)
1308 if (p->paramkind == PARAM_MULTIEXPR)
1310 int subqueryid = p->paramid >> 16;
1311 int colno = p->paramid & 0xFFFF;
1314 if (subqueryid <= 0 ||
1315 subqueryid > list_length(root->multiexpr_params))
1316 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
1317 params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
1318 if (colno <= 0 || colno > list_length(params))
1319 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
1320 return copyObject(list_nth(params, colno - 1));
1322 return copyObject(p);
1327 * Do set_plan_references processing on a scan-level expression
1329 * This consists of incrementing all Vars' varnos by rtoffset,
1330 * replacing PARAM_MULTIEXPR Params, expanding PlaceHolderVars,
1331 * looking up operator opcode info for OpExpr and related nodes,
1332 * and adding OIDs from regclass Const nodes into root->glob->relationOids.
1335 fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset)
1337 fix_scan_expr_context context;
1339 context.root = root;
1340 context.rtoffset = rtoffset;
1342 if (rtoffset != 0 ||
1343 root->multiexpr_params != NIL ||
1344 root->glob->lastPHId != 0)
1346 return fix_scan_expr_mutator(node, &context);
1351 * If rtoffset == 0, we don't need to change any Vars, and if there
1352 * are no MULTIEXPR subqueries then we don't need to replace
1353 * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
1354 * we won't need to remove them. Then it's OK to just scribble on the
1355 * input node tree instead of copying (since the only change, filling
1356 * in any unset opfuncid fields, is harmless). This saves just enough
1357 * cycles to be noticeable on trivial queries.
1359 (void) fix_scan_expr_walker(node, &context);
1365 fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
1371 Var *var = copyVar((Var *) node);
1373 Assert(var->varlevelsup == 0);
1376 * We should not see any Vars marked INNER_VAR or OUTER_VAR. But an
1377 * indexqual expression could contain INDEX_VAR Vars.
1379 Assert(var->varno != INNER_VAR);
1380 Assert(var->varno != OUTER_VAR);
1381 if (!IS_SPECIAL_VARNO(var->varno))
1382 var->varno += context->rtoffset;
1383 if (var->varnoold > 0)
1384 var->varnoold += context->rtoffset;
1385 return (Node *) var;
1387 if (IsA(node, Param))
1388 return fix_param_node(context->root, (Param *) node);
1389 if (IsA(node, CurrentOfExpr))
1391 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
1393 Assert(cexpr->cvarno != INNER_VAR);
1394 Assert(cexpr->cvarno != OUTER_VAR);
1395 if (!IS_SPECIAL_VARNO(cexpr->cvarno))
1396 cexpr->cvarno += context->rtoffset;
1397 return (Node *) cexpr;
1399 if (IsA(node, PlaceHolderVar))
1401 /* At scan level, we should always just evaluate the contained expr */
1402 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1404 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
1406 fix_expr_common(context->root, node);
1407 return expression_tree_mutator(node, fix_scan_expr_mutator,
1412 fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
1416 Assert(!IsA(node, PlaceHolderVar));
1417 fix_expr_common(context->root, node);
1418 return expression_tree_walker(node, fix_scan_expr_walker,
1423 * set_join_references
1424 * Modify the target list and quals of a join node to reference its
1425 * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
1426 * attno values to the result domain number of either the corresponding
1427 * outer or inner join tuple item. Also perform opcode lookup for these
1428 * expressions. and add regclass OIDs to root->glob->relationOids.
1431 set_join_references(PlannerInfo *root, Join *join, int rtoffset)
1433 Plan *outer_plan = join->plan.lefttree;
1434 Plan *inner_plan = join->plan.righttree;
1435 indexed_tlist *outer_itlist;
1436 indexed_tlist *inner_itlist;
1438 outer_itlist = build_tlist_index(outer_plan->targetlist);
1439 inner_itlist = build_tlist_index(inner_plan->targetlist);
1442 * First process the joinquals (including merge or hash clauses). These
1443 * are logically below the join so they can always use all values
1444 * available from the input tlists. It's okay to also handle
1445 * NestLoopParams now, because those couldn't refer to nullable
1448 join->joinqual = fix_join_expr(root,
1455 /* Now do join-type-specific stuff */
1456 if (IsA(join, NestLoop))
1458 NestLoop *nl = (NestLoop *) join;
1461 foreach(lc, nl->nestParams)
1463 NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
1465 nlp->paramval = (Var *) fix_upper_expr(root,
1466 (Node *) nlp->paramval,
1470 /* Check we replaced any PlaceHolderVar with simple Var */
1471 if (!(IsA(nlp->paramval, Var) &&
1472 nlp->paramval->varno == OUTER_VAR))
1473 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
1476 else if (IsA(join, MergeJoin))
1478 MergeJoin *mj = (MergeJoin *) join;
1480 mj->mergeclauses = fix_join_expr(root,
1487 else if (IsA(join, HashJoin))
1489 HashJoin *hj = (HashJoin *) join;
1491 hj->hashclauses = fix_join_expr(root,
1500 * Now we need to fix up the targetlist and qpqual, which are logically
1501 * above the join. This means they should not re-use any input expression
1502 * that was computed in the nullable side of an outer join. Vars and
1503 * PlaceHolderVars are fine, so we can implement this restriction just by
1504 * clearing has_non_vars in the indexed_tlist structs.
1506 * XXX This is a grotty workaround for the fact that we don't clearly
1507 * distinguish between a Var appearing below an outer join and the "same"
1508 * Var appearing above it. If we did, we'd not need to hack the matching
1511 switch (join->jointype)
1516 inner_itlist->has_non_vars = false;
1519 outer_itlist->has_non_vars = false;
1522 outer_itlist->has_non_vars = false;
1523 inner_itlist->has_non_vars = false;
1529 join->plan.targetlist = fix_join_expr(root,
1530 join->plan.targetlist,
1535 join->plan.qual = fix_join_expr(root,
1542 pfree(outer_itlist);
1543 pfree(inner_itlist);
1547 * set_upper_references
1548 * Update the targetlist and quals of an upper-level plan node
1549 * to refer to the tuples returned by its lefttree subplan.
1550 * Also perform opcode lookup for these expressions, and
1551 * add regclass OIDs to root->glob->relationOids.
1553 * This is used for single-input plan types like Agg, Group, Result.
1555 * In most cases, we have to match up individual Vars in the tlist and
1556 * qual expressions with elements of the subplan's tlist (which was
1557 * generated by flatten_tlist() from these selfsame expressions, so it
1558 * should have all the required variables). There is an important exception,
1559 * however: GROUP BY and ORDER BY expressions will have been pushed into the
1560 * subplan tlist unflattened. If these values are also needed in the output
1561 * then we want to reference the subplan tlist element rather than recomputing
1565 set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
1567 Plan *subplan = plan->lefttree;
1568 indexed_tlist *subplan_itlist;
1569 List *output_targetlist;
1572 subplan_itlist = build_tlist_index(subplan->targetlist);
1574 output_targetlist = NIL;
1575 foreach(l, plan->targetlist)
1577 TargetEntry *tle = (TargetEntry *) lfirst(l);
1580 /* If it's a non-Var sort/group item, first try to match by sortref */
1581 if (tle->ressortgroupref != 0 && !IsA(tle->expr, Var))
1584 search_indexed_tlist_for_sortgroupref((Node *) tle->expr,
1585 tle->ressortgroupref,
1589 newexpr = fix_upper_expr(root,
1596 newexpr = fix_upper_expr(root,
1601 tle = flatCopyTargetEntry(tle);
1602 tle->expr = (Expr *) newexpr;
1603 output_targetlist = lappend(output_targetlist, tle);
1605 plan->targetlist = output_targetlist;
1607 plan->qual = (List *)
1608 fix_upper_expr(root,
1609 (Node *) plan->qual,
1614 pfree(subplan_itlist);
1618 * set_dummy_tlist_references
1619 * Replace the targetlist of an upper-level plan node with a simple
1620 * list of OUTER_VAR references to its child.
1622 * This is used for plan types like Sort and Append that don't evaluate
1623 * their targetlists. Although the executor doesn't care at all what's in
1624 * the tlist, EXPLAIN needs it to be realistic.
1626 * Note: we could almost use set_upper_references() here, but it fails for
1627 * Append for lack of a lefttree subplan. Single-purpose code is faster
1631 set_dummy_tlist_references(Plan *plan, int rtoffset)
1633 List *output_targetlist;
1636 output_targetlist = NIL;
1637 foreach(l, plan->targetlist)
1639 TargetEntry *tle = (TargetEntry *) lfirst(l);
1640 Var *oldvar = (Var *) tle->expr;
1643 newvar = makeVar(OUTER_VAR,
1645 exprType((Node *) oldvar),
1646 exprTypmod((Node *) oldvar),
1647 exprCollation((Node *) oldvar),
1649 if (IsA(oldvar, Var))
1651 newvar->varnoold = oldvar->varno + rtoffset;
1652 newvar->varoattno = oldvar->varattno;
1656 newvar->varnoold = 0; /* wasn't ever a plain Var */
1657 newvar->varoattno = 0;
1660 tle = flatCopyTargetEntry(tle);
1661 tle->expr = (Expr *) newvar;
1662 output_targetlist = lappend(output_targetlist, tle);
1664 plan->targetlist = output_targetlist;
1666 /* We don't touch plan->qual here */
1671 * build_tlist_index --- build an index data structure for a child tlist
1673 * In most cases, subplan tlists will be "flat" tlists with only Vars,
1674 * so we try to optimize that case by extracting information about Vars
1675 * in advance. Matching a parent tlist to a child is still an O(N^2)
1676 * operation, but at least with a much smaller constant factor than plain
1677 * tlist_member() searches.
1679 * The result of this function is an indexed_tlist struct to pass to
1680 * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
1681 * When done, the indexed_tlist may be freed with a single pfree().
1683 static indexed_tlist *
1684 build_tlist_index(List *tlist)
1686 indexed_tlist *itlist;
1690 /* Create data structure with enough slots for all tlist entries */
1691 itlist = (indexed_tlist *)
1692 palloc(offsetof(indexed_tlist, vars) +
1693 list_length(tlist) * sizeof(tlist_vinfo));
1695 itlist->tlist = tlist;
1696 itlist->has_ph_vars = false;
1697 itlist->has_non_vars = false;
1699 /* Find the Vars and fill in the index array */
1700 vinfo = itlist->vars;
1703 TargetEntry *tle = (TargetEntry *) lfirst(l);
1705 if (tle->expr && IsA(tle->expr, Var))
1707 Var *var = (Var *) tle->expr;
1709 vinfo->varno = var->varno;
1710 vinfo->varattno = var->varattno;
1711 vinfo->resno = tle->resno;
1714 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1715 itlist->has_ph_vars = true;
1717 itlist->has_non_vars = true;
1720 itlist->num_vars = (vinfo - itlist->vars);
1726 * build_tlist_index_other_vars --- build a restricted tlist index
1728 * This is like build_tlist_index, but we only index tlist entries that
1729 * are Vars belonging to some rel other than the one specified. We will set
1730 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
1731 * (so nothing other than Vars and PlaceHolderVars can be matched).
1733 static indexed_tlist *
1734 build_tlist_index_other_vars(List *tlist, Index ignore_rel)
1736 indexed_tlist *itlist;
1740 /* Create data structure with enough slots for all tlist entries */
1741 itlist = (indexed_tlist *)
1742 palloc(offsetof(indexed_tlist, vars) +
1743 list_length(tlist) * sizeof(tlist_vinfo));
1745 itlist->tlist = tlist;
1746 itlist->has_ph_vars = false;
1747 itlist->has_non_vars = false;
1749 /* Find the desired Vars and fill in the index array */
1750 vinfo = itlist->vars;
1753 TargetEntry *tle = (TargetEntry *) lfirst(l);
1755 if (tle->expr && IsA(tle->expr, Var))
1757 Var *var = (Var *) tle->expr;
1759 if (var->varno != ignore_rel)
1761 vinfo->varno = var->varno;
1762 vinfo->varattno = var->varattno;
1763 vinfo->resno = tle->resno;
1767 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1768 itlist->has_ph_vars = true;
1771 itlist->num_vars = (vinfo - itlist->vars);
1777 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
1779 * If a match is found, return a copy of the given Var with suitably
1780 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
1781 * Also ensure that varnoold is incremented by rtoffset.
1782 * If no match, return NULL.
1785 search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
1786 Index newvarno, int rtoffset)
1788 Index varno = var->varno;
1789 AttrNumber varattno = var->varattno;
1793 vinfo = itlist->vars;
1794 i = itlist->num_vars;
1797 if (vinfo->varno == varno && vinfo->varattno == varattno)
1800 Var *newvar = copyVar(var);
1802 newvar->varno = newvarno;
1803 newvar->varattno = vinfo->resno;
1804 if (newvar->varnoold > 0)
1805 newvar->varnoold += rtoffset;
1810 return NULL; /* no match */
1814 * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
1816 * If a match is found, return a Var constructed to reference the tlist item.
1817 * If no match, return NULL.
1819 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
1820 * itlist->has_non_vars. Furthermore, set_join_references() relies on being
1821 * able to prevent matching of non-Vars by clearing itlist->has_non_vars,
1822 * so there's a correctness reason not to call it unless that's set.
1825 search_indexed_tlist_for_non_var(Node *node,
1826 indexed_tlist *itlist, Index newvarno)
1830 tle = tlist_member(node, itlist->tlist);
1833 /* Found a matching subplan output expression */
1836 newvar = makeVarFromTargetEntry(newvarno, tle);
1837 newvar->varnoold = 0; /* wasn't ever a plain Var */
1838 newvar->varoattno = 0;
1841 return NULL; /* no match */
1845 * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
1846 * (which is assumed not to be just a Var)
1848 * If a match is found, return a Var constructed to reference the tlist item.
1849 * If no match, return NULL.
1851 * This is needed to ensure that we select the right subplan TLE in cases
1852 * where there are multiple textually-equal()-but-volatile sort expressions.
1853 * And it's also faster than search_indexed_tlist_for_non_var.
1856 search_indexed_tlist_for_sortgroupref(Node *node,
1858 indexed_tlist *itlist,
1863 foreach(lc, itlist->tlist)
1865 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1867 /* The equal() check should be redundant, but let's be paranoid */
1868 if (tle->ressortgroupref == sortgroupref &&
1869 equal(node, tle->expr))
1871 /* Found a matching subplan output expression */
1874 newvar = makeVarFromTargetEntry(newvarno, tle);
1875 newvar->varnoold = 0; /* wasn't ever a plain Var */
1876 newvar->varoattno = 0;
1880 return NULL; /* no match */
1885 * Create a new set of targetlist entries or join qual clauses by
1886 * changing the varno/varattno values of variables in the clauses
1887 * to reference target list values from the outer and inner join
1888 * relation target lists. Also perform opcode lookup and add
1889 * regclass OIDs to root->glob->relationOids.
1891 * This is used in two different scenarios: a normal join clause, where all
1892 * the Vars in the clause *must* be replaced by OUTER_VAR or INNER_VAR
1893 * references; and a RETURNING clause, which may contain both Vars of the
1894 * target relation and Vars of other relations. In the latter case we want
1895 * to replace the other-relation Vars by OUTER_VAR references, while leaving
1896 * target Vars alone.
1898 * For a normal join, acceptable_rel should be zero so that any failure to
1899 * match a Var will be reported as an error. For the RETURNING case, pass
1900 * inner_itlist = NULL and acceptable_rel = the ID of the target relation.
1902 * 'clauses' is the targetlist or list of join clauses
1903 * 'outer_itlist' is the indexed target list of the outer join relation,
1905 * 'inner_itlist' is the indexed target list of the inner join relation,
1907 * 'acceptable_rel' is either zero or the rangetable index of a relation
1908 * whose Vars may appear in the clause without provoking an error
1909 * 'rtoffset': how much to increment varnoold by
1911 * Returns the new expression tree. The original clause structure is
1915 fix_join_expr(PlannerInfo *root,
1917 indexed_tlist *outer_itlist,
1918 indexed_tlist *inner_itlist,
1919 Index acceptable_rel,
1922 fix_join_expr_context context;
1924 context.root = root;
1925 context.outer_itlist = outer_itlist;
1926 context.inner_itlist = inner_itlist;
1927 context.acceptable_rel = acceptable_rel;
1928 context.rtoffset = rtoffset;
1929 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1933 fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1941 Var *var = (Var *) node;
1943 /* First look for the var in the input tlists */
1944 if (context->outer_itlist)
1946 newvar = search_indexed_tlist_for_var(var,
1947 context->outer_itlist,
1951 return (Node *) newvar;
1954 /* Then in the outer */
1955 if (context->inner_itlist)
1957 newvar = search_indexed_tlist_for_var(var,
1958 context->inner_itlist,
1962 return (Node *) newvar;
1965 /* If it's for acceptable_rel, adjust and return it */
1966 if (var->varno == context->acceptable_rel)
1969 var->varno += context->rtoffset;
1970 if (var->varnoold > 0)
1971 var->varnoold += context->rtoffset;
1972 return (Node *) var;
1975 /* No referent found for Var */
1976 elog(ERROR, "variable not found in subplan target lists");
1978 if (IsA(node, PlaceHolderVar))
1980 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1982 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1983 if (context->outer_itlist && context->outer_itlist->has_ph_vars)
1985 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1986 context->outer_itlist,
1989 return (Node *) newvar;
1991 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
1993 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1994 context->inner_itlist,
1997 return (Node *) newvar;
2000 /* If not supplied by input plans, evaluate the contained expr */
2001 return fix_join_expr_mutator((Node *) phv->phexpr, context);
2003 if (IsA(node, Param))
2004 return fix_param_node(context->root, (Param *) node);
2005 /* Try matching more complex expressions too, if tlists have any */
2006 if (context->outer_itlist && context->outer_itlist->has_non_vars)
2008 newvar = search_indexed_tlist_for_non_var(node,
2009 context->outer_itlist,
2012 return (Node *) newvar;
2014 if (context->inner_itlist && context->inner_itlist->has_non_vars)
2016 newvar = search_indexed_tlist_for_non_var(node,
2017 context->inner_itlist,
2020 return (Node *) newvar;
2022 fix_expr_common(context->root, node);
2023 return expression_tree_mutator(node,
2024 fix_join_expr_mutator,
2030 * Modifies an expression tree so that all Var nodes reference outputs
2031 * of a subplan. Also performs opcode lookup, and adds regclass OIDs to
2032 * root->glob->relationOids.
2034 * This is used to fix up target and qual expressions of non-join upper-level
2035 * plan nodes, as well as index-only scan nodes.
2037 * An error is raised if no matching var can be found in the subplan tlist
2038 * --- so this routine should only be applied to nodes whose subplans'
2039 * targetlists were generated via flatten_tlist() or some such method.
2041 * If itlist->has_non_vars is true, then we try to match whole subexpressions
2042 * against elements of the subplan tlist, so that we can avoid recomputing
2043 * expressions that were already computed by the subplan. (This is relatively
2044 * expensive, so we don't want to try it in the common case where the
2045 * subplan tlist is just a flattened list of Vars.)
2047 * 'node': the tree to be fixed (a target item or qual)
2048 * 'subplan_itlist': indexed target list for subplan (or index)
2049 * 'newvarno': varno to use for Vars referencing tlist elements
2050 * 'rtoffset': how much to increment varnoold by
2052 * The resulting tree is a copy of the original in which all Var nodes have
2053 * varno = newvarno, varattno = resno of corresponding targetlist element.
2054 * The original tree is not modified.
2057 fix_upper_expr(PlannerInfo *root,
2059 indexed_tlist *subplan_itlist,
2063 fix_upper_expr_context context;
2065 context.root = root;
2066 context.subplan_itlist = subplan_itlist;
2067 context.newvarno = newvarno;
2068 context.rtoffset = rtoffset;
2069 return fix_upper_expr_mutator(node, &context);
2073 fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
2081 Var *var = (Var *) node;
2083 newvar = search_indexed_tlist_for_var(var,
2084 context->subplan_itlist,
2088 elog(ERROR, "variable not found in subplan target list");
2089 return (Node *) newvar;
2091 if (IsA(node, PlaceHolderVar))
2093 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2095 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
2096 if (context->subplan_itlist->has_ph_vars)
2098 newvar = search_indexed_tlist_for_non_var((Node *) phv,
2099 context->subplan_itlist,
2102 return (Node *) newvar;
2104 /* If not supplied by input plan, evaluate the contained expr */
2105 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
2107 if (IsA(node, Param))
2108 return fix_param_node(context->root, (Param *) node);
2109 /* Try matching more complex expressions too, if tlist has any */
2110 if (context->subplan_itlist->has_non_vars)
2112 newvar = search_indexed_tlist_for_non_var(node,
2113 context->subplan_itlist,
2116 return (Node *) newvar;
2118 fix_expr_common(context->root, node);
2119 return expression_tree_mutator(node,
2120 fix_upper_expr_mutator,
2125 * set_returning_clause_references
2126 * Perform setrefs.c's work on a RETURNING targetlist
2128 * If the query involves more than just the result table, we have to
2129 * adjust any Vars that refer to other tables to reference junk tlist
2130 * entries in the top subplan's targetlist. Vars referencing the result
2131 * table should be left alone, however (the executor will evaluate them
2132 * using the actual heap tuple, after firing triggers if any). In the
2133 * adjusted RETURNING list, result-table Vars will have their original
2134 * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
2136 * We also must perform opcode lookup and add regclass OIDs to
2137 * root->glob->relationOids.
2139 * 'rlist': the RETURNING targetlist to be fixed
2140 * 'topplan': the top subplan node that will be just below the ModifyTable
2141 * node (note it's not yet passed through set_plan_refs)
2142 * 'resultRelation': RT index of the associated result relation
2143 * 'rtoffset': how much to increment varnos by
2145 * Note: the given 'root' is for the parent query level, not the 'topplan'.
2146 * This does not matter currently since we only access the dependency-item
2147 * lists in root->glob, but it would need some hacking if we wanted a root
2148 * that actually matches the subplan.
2150 * Note: resultRelation is not yet adjusted by rtoffset.
2153 set_returning_clause_references(PlannerInfo *root,
2156 Index resultRelation,
2159 indexed_tlist *itlist;
2162 * We can perform the desired Var fixup by abusing the fix_join_expr
2163 * machinery that formerly handled inner indexscan fixup. We search the
2164 * top plan's targetlist for Vars of non-result relations, and use
2165 * fix_join_expr to convert RETURNING Vars into references to those tlist
2166 * entries, while leaving result-rel Vars as-is.
2168 * PlaceHolderVars will also be sought in the targetlist, but no
2169 * more-complex expressions will be. Note that it is not possible for a
2170 * PlaceHolderVar to refer to the result relation, since the result is
2171 * never below an outer join. If that case could happen, we'd have to be
2172 * prepared to pick apart the PlaceHolderVar and evaluate its contained
2173 * expression instead.
2175 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
2177 rlist = fix_join_expr(root,
2189 /*****************************************************************************
2190 * OPERATOR REGPROC LOOKUP
2191 *****************************************************************************/
2195 * Calculate opfuncid field from opno for each OpExpr node in given tree.
2196 * The given tree can be anything expression_tree_walker handles.
2198 * The argument is modified in-place. (This is OK since we'd want the
2199 * same change for any node, even if it gets visited more than once due to
2200 * shared structure.)
2203 fix_opfuncids(Node *node)
2205 /* This tree walk requires no special setup, so away we go... */
2206 fix_opfuncids_walker(node, NULL);
2210 fix_opfuncids_walker(Node *node, void *context)
2214 if (IsA(node, OpExpr))
2215 set_opfuncid((OpExpr *) node);
2216 else if (IsA(node, DistinctExpr))
2217 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2218 else if (IsA(node, NullIfExpr))
2219 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2220 else if (IsA(node, ScalarArrayOpExpr))
2221 set_sa_opfuncid((ScalarArrayOpExpr *) node);
2222 return expression_tree_walker(node, fix_opfuncids_walker, context);
2227 * Set the opfuncid (procedure OID) in an OpExpr node,
2228 * if it hasn't been set already.
2230 * Because of struct equivalence, this can also be used for
2231 * DistinctExpr and NullIfExpr nodes.
2234 set_opfuncid(OpExpr *opexpr)
2236 if (opexpr->opfuncid == InvalidOid)
2237 opexpr->opfuncid = get_opcode(opexpr->opno);
2242 * As above, for ScalarArrayOpExpr nodes.
2245 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
2247 if (opexpr->opfuncid == InvalidOid)
2248 opexpr->opfuncid = get_opcode(opexpr->opno);
2251 /*****************************************************************************
2252 * QUERY DEPENDENCY MANAGEMENT
2253 *****************************************************************************/
2256 * record_plan_function_dependency
2257 * Mark the current plan as depending on a particular function.
2259 * This is exported so that the function-inlining code can record a
2260 * dependency on a function that it's removed from the plan tree.
2263 record_plan_function_dependency(PlannerInfo *root, Oid funcid)
2266 * For performance reasons, we don't bother to track built-in functions;
2267 * we just assume they'll never change (or at least not in ways that'd
2268 * invalidate plans using them). For this purpose we can consider a
2269 * built-in function to be one with OID less than FirstBootstrapObjectId.
2270 * Note that the OID generator guarantees never to generate such an OID
2271 * after startup, even at OID wraparound.
2273 if (funcid >= (Oid) FirstBootstrapObjectId)
2275 PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2278 * It would work to use any syscache on pg_proc, but the easiest is
2279 * PROCOID since we already have the function's OID at hand. Note
2280 * that plancache.c knows we use PROCOID.
2282 inval_item->cacheId = PROCOID;
2283 inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
2284 ObjectIdGetDatum(funcid));
2286 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2291 * extract_query_dependencies
2292 * Given a not-yet-planned query or queries (i.e. a Query node or list
2293 * of Query nodes), extract dependencies just as set_plan_references
2296 * This is needed by plancache.c to handle invalidation of cached unplanned
2300 extract_query_dependencies(Node *query,
2301 List **relationOids,
2303 bool *hasRowSecurity)
2308 /* Make up dummy planner state so we can use this module's machinery */
2309 MemSet(&glob, 0, sizeof(glob));
2310 glob.type = T_PlannerGlobal;
2311 glob.relationOids = NIL;
2312 glob.invalItems = NIL;
2313 glob.hasRowSecurity = false;
2315 MemSet(&root, 0, sizeof(root));
2316 root.type = T_PlannerInfo;
2319 (void) extract_query_dependencies_walker(query, &root);
2321 *relationOids = glob.relationOids;
2322 *invalItems = glob.invalItems;
2323 *hasRowSecurity = glob.hasRowSecurity;
2327 extract_query_dependencies_walker(Node *node, PlannerInfo *context)
2331 Assert(!IsA(node, PlaceHolderVar));
2332 /* Extract function dependencies and check for regclass Consts */
2333 fix_expr_common(context, node);
2334 if (IsA(node, Query))
2336 Query *query = (Query *) node;
2339 /* Collect row security information */
2340 context->glob->hasRowSecurity = query->hasRowSecurity;
2342 if (query->commandType == CMD_UTILITY)
2345 * Ignore utility statements, except those (such as EXPLAIN) that
2346 * contain a parsed-but-not-planned query.
2348 query = UtilityContainsQuery(query->utilityStmt);
2353 /* Collect relation OIDs in this Query's rtable */
2354 foreach(lc, query->rtable)
2356 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2358 if (rte->rtekind == RTE_RELATION)
2359 context->glob->relationOids =
2360 lappend_oid(context->glob->relationOids, rte->relid);
2363 /* And recurse into the query's subexpressions */
2364 return query_tree_walker(query, extract_query_dependencies_walker,
2365 (void *) context, 0);
2367 return expression_tree_walker(node, extract_query_dependencies_walker,